Metasploit Weekly Wrap-Up 10/18/2024

Post Syndicated from Spencer McIntyre original https://blog.rapid7.com/2024/10/18/metasploit-weekly-wrap-up-10-18-2024/

ESC15: EKUwu

Metasploit Weekly Wrap-Up 10/18/2024

AD CS continues to be a popular target for penetration testers and security practitioners. The latest escalation technique (hence the the ESC in ESC15) was discovered by Justin Bollinger with details being released just last week. This latest configuration flaw has common issuance requirements to other ESC flaws such as requiring no authorized signatures or manager approval. Additionally, templates must be schema version 1 which enables an attacker to craft a signing request with a custom set of EKU OIDs which will be present in the issued certificate. By overriding the OIDs, the template can be used in a few ways with the most useful being as a certificate enrollment agent. With a valid enrollment agent certificate, a user can issue certificates for other users which, when combined with the builtin “User” certificate, can enable Kerberos authentication to a wide variety of services.

This week’s release of Metasploit has added support to our existing AD CS related modules for identifying and exploiting ESC15.

The auxiliary/admin/ldap/ad_cs_cert_template module can be used along with the new esc15_template to create a vulnerable certificate or (by leveraging ESC4) update an existing certificate to be vulnerable to ESC15.
The auxiliary/gather/ldap_esc_vulnerable_cert_finder module has been updated to identify vulnerable certificate templates.
The auxiliary/admin/dcerpc/icpr_cer module has been updated with the new ADD_CERT_APP_POLICY option to enable users to add EKUs by OID, thus enabling exploitation of ESC15.

For exploitation steps, see the ESC15 section of our AD CS documentation.

New module content (2)

WordPress WP Fastest Cache Unauthenticated SQLi (CVE-2023-6063)

Authors: Alex Sanford, Julien Voisin, and Valentin Lobstein
Type: Auxiliary
Pull request: #19473 contributed by Chocapikk
Path: scanner/http/wp_fastest_cache_sqli
AttackerKB reference: CVE-2023-6063

Description: This adds an auxiliary module to dump user credentials through a Time-based SQL injection present in WP Fastest Cache Plugin <= 1.2.2.

BYOB Unauthenticated RCE via Arbitrary File Write and Command Injection (CVE-2024-45256, CVE-2024-45257)

Authors: Valentin Lobstein and chebuya
Type: Exploit
Pull request: #19485 contributed by Chocapikk
Path: unix/webapp/byob_unauth_rce
AttackerKB reference: CVE-2024-45257

Description: This adds an exploit module for BYOB unauthenticated RCE (CVE-2024-45256, CVE-2024-45257).

Enhanced Modules (2)

Modules which have either been enhanced, or renamed:

  • #19482 from Chocapikk – The module allows users to select between the two vulnerabilities (c_only_fields for CVE-2024-8522 and c_fields for CVE-2024-8529) and includes options such as specifying the number of rows to retrieve (COUNT).
  • #19538 from zeroSteiner – This adds support for ESC15 to various AD CS related modules.

Enhancements and features (6)

  • #19108 from smashery – Adds a new API, create_process, which supports creating processes against an open session from an array of args, rather than from a commandline string that needs to go through a subshell. This pull request also fixes multiple module compatibility issues across different session types, i.e. targeting Meterpreter/PowerShell/Cmd/Unix sessions should now behave consistently when running post exploitation and local privilege escalation modules that execute processes.
  • #19497 from Chocapikk – This adds an helper library for the development of WordPress SQLi modules.
  • #19539 from smashery – This adds functionality to keep the new LDAP sessions alive beyond a server’s idle timeout.
  • #19540 from smashery – Update Metasploit’s HTTP request User Agent strings for October 2024.
  • #19549 from zeroSteiner – This pull request includes multiple fixes and improvements to the Meterpreter payloads. zeroSteiner fixed a stdapi_fs_ls: Operation failed: 1 error when running the ls command with the Java Meterpreter. cdelafuente-r7 has updated the Java Meterpreter payload to now run on newer OpenJDK versions on Alpine Linux hosts. wolfcod has made improvements for running the C Meterpreter on Windows XP machines when creating remote threads, as well as fixing a memory leak in the sysinfo command.
  • #19561 from cdelafuente-r7 – Updates the gather/ldap_esc_vulnerable_cert_finder module to now register the detected vulnerabilities into the Metasploit database if it is currently active.

Bugs fixed (2)

  • #19495 from cdelafuente-r7 – Fixes an edgecase crash in the admin/kerberos/get_ticket module when the supplied cert_file contained a subjectAltName extension with an unexpected value present.
  • #19563 from adfoster-r7 – Updates exploits/linux/http/metabase_setup_token_rce to support older versions.

Documentation

You can find the latest Metasploit documentation on our docsite at docs.metasploit.com.

Get it

As always, you can update to the latest Metasploit Framework with msfupdate
and you can get more details on the changes since the last blog post from
GitHub:

If you are a git user, you can clone the Metasploit Framework repo (master branch) for the latest.
To install fresh without using git, you can use the open-source-only Nightly Installers or the
commercial edition Metasploit Pro

A customer’s journey with Amazon OpenSearch Ingestion pipelines

Post Syndicated from Navnit Shukla original https://aws.amazon.com/blogs/big-data/a-customers-journey-with-amazon-opensearch-ingestion-pipelines/

This is a guest post co-written with Mike Mosher, Sr. Principal Cloud Platform Network Architect at a multi-national financial credit reporting company.

I work for a multi-national financial credit reporting company that offers credit risk, fraud, targeted marketing, and automated decisioning solutions. We are an AWS early adopter and have embraced the cloud to drive digital transformation efforts. Our Cloud Center of Excellence (CCoE) team operates a global AWS Landing Zone, which includes a centralized AWS network infrastructure. We are also an AWS PrivateLink Ready Partner and offer our E-Connect solution to allow our B2B customers to connect to a range of products through private, secure, and performant connectivity.

Our E-Connect solution is a platform comprised of multiple AWS services like Application Load Balancer (ALB), Network Load Balancer (NLB), Gateway Load Balancer (GWLB), AWS Transit Gateway, AWS PrivateLink, AWS WAF, and third-party security appliances. All of these services and resources, as well as the large amount of network traffic across the platform, create a large number of logs, and we needed a solution to aggregate and organize these logs for quick analysis by our operations teams when troubleshooting the platform.

Our original design consisted of Amazon OpenSearch Service, selected for its ability to return specific log entries from extensive datasets in seconds. We also complemented this with Logstash, allowing us to use multiple filters to enrich and augment the data before sending to the OpenSearch cluster, facilitating a more comprehensive and insightful monitoring experience.

In this post, we share our journey, including the hurdles we faced, the solutions we thought about, and why we went with Amazon OpenSearch Ingestion pipelines to make our log management smoother.

Overview of the initial solution

We originally wanted to store and analyze the logs in an OpenSearch cluster, and decided to use the AWS-managed service for OpenSearch called Amazon OpenSearch Service. We also wanted to enrich these logs with Logstash, but there was no AWS-managed service for this, so we needed to deploy the application on an Amazon Elastic Compute Cloud (Amazon EC2) server. This setup meant that we had to implement a lot of maintenance of the server, including using AWS CodePipeline and AWS CodeDeploy to push new Logstash configurations to the server and restart the service. We also needed to perform server maintenance tasks such as patching and updating the operating system (OS) and the Logstash application, and monitor server resources such as Java heap, CPU, memory, and storage.

The complexity extended to validating the network path from the Logstash server to the OpenSearch cluster, incorporating checks on Access Control Lists (ACLs) and security groups, as well as routes in the VPC subnets. Scaling beyond a single EC2 server introduced considerations for managing an auto scaling group, Amazon Simple Queue Service (Amazon SQS) queues, and more. Maintaining the continuous functionality of our solution became a significant effort, diverting focus from the core tasks of operating and monitoring the platform.

The following diagram illustrates our initial architecture.

Possible solutions for us:

Our team looked at multiple options to manage the logs from this platform. We possess a Splunk solution for storing and analyzing logs, and we did assess it as a potential competitor to OpenSearch Service. However, we opted against it for several reasons:

  • Our team is more familiar with OpenSearch Service and Logstash than Splunk.
  • Amazon OpenSearch Service, being a managed service in AWS, facilitates a smoother log transfer process compared to our on-premises Splunk solution. Also, transporting logs to the on-premises Splunk cluster would incur high costs, consume bandwidth on our AWS Direct Connect connections, and introduce unnecessary complexity.
  • Splunk’s pricing structure, based on storage in GBs, proved cost-prohibitive for the volume of logs we intended to store and analyze.

Initial designs for an OpenSearch Ingestion pipeline solution

The Amazon team approached me about a new feature they were launching: Amazon OpenSearch Ingestion. This feature offered a great solution to the problems we were facing with managing EC2 instances for Logstash. First, the new feature removed all the heavy lifting from our team of managing multiple EC2 instances, scaling the servers up and down based on traffic, and monitoring the ingestion of logs and the resources of the underlying servers. Second, Amazon OpenSearch Ingestion pipelines supported most if not all of the Logstash filters we were using in our current solution, which allowed us to use the same functionality of our current solution for enriching the logs.

We were thrilled to be accepted into the AWS beta program, emerging as one of its earliest and largest adopters. Our journey began with ingesting VPC flow logs for our internet ingress platform, alongside Transit Gateway flow logs connecting all VPCs in the AWS Region. Handling such a substantial volume of logs proved to be a significant task, with Transit Gateway flow logs alone reaching upwards of 14 TB per day. As we expanded our scope to include other logs like ALB and NLB access logs and AWS WAF logs, the scale of the solution translated to higher costs.

However, our enthusiasm was somewhat dampened by the challenges we faced initially. Despite our best efforts, we encountered performance issues with the domain. Through collaborative efforts with the AWS team, we uncovered misconfigurations within our setup. We had been using instances that were inadequately sized for the volume of data we were handling. Consequently, these instances were constantly operating at maximum CPU capacity, resulting in a backlog of incoming logs. This bottleneck cascaded into our OpenSearch Ingestion pipelines, forcing them to scale up unnecessarily, even as the OpenSearch cluster struggled to keep pace.

These challenges led to a suboptimal performance from our cluster. We found ourselves unable to analyze flow logs or access logs promptly, sometimes waiting days after their creation. Additionally, the costs associated with these inefficiencies far exceeded our initial expectations.

However, with the assistance of the AWS team, we successfully addressed these issues, optimizing our setup for improved performance and cost-efficiency. This experience underscored the importance of proper configuration and collaboration in maximizing the potential of AWS services, ultimately leading to a more positive outcome for our data ingestion processes.

Optimized design for our OpenSearch Ingestion pipelines solution

We collaborated with AWS to enhance our overall solution, building a solution that is both high performing, cost-effective, and aligned with our monitoring requirements. The solution involves selectively ingesting specific log fields into the OpenSearch Service domain using an Amazon S3 Select pipeline in the pipeline source; alternative selective ingestion can also be done by filtering within pipelines. You can use include_keys and exclude_keys in your sink to filter data that’s routed to destination. We also used the built-in Index State Management feature to remove logs older than a predefined period to reduce the overall cost of the cluster.

The ingested logs in OpenSearch Service empower us to derive aggregate data, providing insights into trends and issues across the entire platform. For additional detailed analysis of these logs including all original log fields, we use Amazon Athena tables with partitioning to quickly and cost-effectively query Amazon Simple Storage Service (Amazon S3) for logs stored in Parquet format.

This comprehensive solution significantly enhances our platform visibility, reduces overall monitoring costs for handling a large log volume, and expedites our time to identify root causes when troubleshooting platform incidents.

The following diagram illustrates our optimized architecture.

Performance comparison

The following table compares the performance of the initial design with Logstash on Amazon EC2, the original OpenSearch Ingestion pipeline solution, and the optimized OpenSearch Ingestion pipeline solution.

  Initial Design with Logstash on Amazon EC2 Original Ingestion Pipeline Solution Optimized Ingestion Pipeline Solution
Maintenance Effort High: Solution required the team to manage multiple services and instances, taking effort away from managing and monitoring our platform. Low: OpenSearch Ingestion managed most of the undifferentiated heavy lifting, leaving the team to only maintain the ingestion pipeline configuration file. Low: OpenSearch Ingestion managed most of the undifferentiated heavy lifting, leaving the team to only maintain the ingestion pipeline configuration file.
Performance High: EC2 instances with Logstash could scale up and down as needed in the auto scaling group. Low: Due to insufficient resources on the OpenSearch cluster, the ingestion pipelines were constantly at max OpenSearch Compute Units (OCUs), causing log delivery to be delayed by multiple days. High: Ingestion pipelines can scale up and down in OCUs as needed.
Real-time Log Availability Medium: In order to pull, process, and deliver the large number of logs in Amazon S3, we needed a large number of EC2 instances. To save on cost, we ran fewer instances, which led to slower log delivery to OpenSearch. Low: Due to insufficient resources on the OpenSearch cluster, the ingestion pipelines were constantly at max OCUs, causing log delivery to be delayed by multiple days. High: The optimized solution was able to deliver a large number of logs to OpenSearch to be analyzed in near real time.
Cost Saving Medium: Running multiple services and instances to send logs to OpenSearch increased the cost of the overall solution. Low: Due to insufficient resources on the OpenSearch cluster, the ingestion pipelines were constantly at max OCUs, increasing the cost of the service. High: The optimized solution was able to scale the ingestion pipeline OCUs up and down as needed, which kept the overall cost low.
Overall Benefit Medium Low High

Conclusion

In this post, we highlighted my journey to build a solution using OpenSearch Service and OpenSearch Ingestion pipelines. This solution allows us to focus on analyzing logs and supporting our platform, without needing to support the infrastructure to deliver logs to OpenSearch. We also highlighted the need to optimize the service in order to increase performance and reduce cost.

As our next steps, we aim to explore the recently announced Amazon OpenSearch Service zero-ETL integration with Amazon S3 (in preview) feature within OpenSearch Service. This step is intended to further reduce the solution’s costs and provide flexibility in the timing and number of logs that are ingested.


About the Authors

Navnit Shukla serves as an AWS Specialist Solutions Architect with a focus on analytics. He possesses a strong enthusiasm for assisting clients in discovering valuable insights from their data. Through his expertise, he constructs innovative solutions that empower businesses to arrive at informed, data-driven choices. Notably, Navnit Shukla is the accomplished author of the book titled “Data Wrangling on AWS.” He can be reached via LinkedIn.

Mike Mosher is s Senior Principal Cloud Platform Network Architect at a multi-national financial credit reporting company. He has more than 16 years of experience in on-premises and cloud networking and is passionate about building new architectures on the cloud that serve customers and solve problems. Outside of work, he enjoys time with his family and traveling back home to the mountains of Colorado.

Single sign-on SSO for Amazon OpenSearch Service using SAML and Keycloak

Post Syndicated from Sajeev Attiyil Bhaskaran original https://aws.amazon.com/blogs/big-data/single-sign-on-sso-for-amazon-opensearch-service-using-saml-and-keycloak/

A standard use case for customers is to integrate existing identity providers (IdPs) with Amazon OpenSearch Service. OpenSearch Service offers built-in support for single sign-on (SSO) authentication for OpenSearch Dashboards, and uses SAML protocol. The SAML authentication for OpenSearch Service lets you integrate your existing third-party IdPs, such as Okta, Ping Identity, OneLogin, Auth0, ADFS, Azure Active Directory, and Keycloak, with OpenSearch Service dashboards.

In this post, we walk you through how to configure service provider-initiated authentication for OpenSearch Dashboards by using OpenSearch Service and Keycloak. We also discuss how to set up users, groups, and roles in Keycloak and configure their access to OpenSearch Dashboards.

Solution overview

The following diagram illustrates the SAML authentication flow for this solution.

image1

The sign-in flow consists of the following steps.

  1. The user opens a browser to navigate to the OpenSearch Dashboards endpoint of OpenSearch Service in a virtual private cloud (VPC), for example https://vpc-abc123.us-east-1.es.amazonaws.com/_dashboards.
  2. The service provider (OpenSearch Service) uses the information about the IdP (Keycloak) to generate a SAML authentication request. The service provider redirects SAML authentication requests back to the browser.
  3. The browser relays the SAML authentication request to Keycloak. Keycloak parses the SAML authentication request and asks for the user to insert their login and password to authenticate.
  4. After a successful authentication, Keycloak generates a SAML authentication response that includes authenticated user details from Keycloak and sends the encoded SAML response to the browser.
  5. The browser relays the SAML response to OpenSearch Service Assertion Consumer Service (ACS) URL.
  6. OpenSearch Service validates the SAML response. If the validation checks are passed, the user is redirected to the front page of OpenSearch Dashboards. The authorization is performed according to the roles mapped to the user.

Prerequisites

To complete this walkthrough, you should have the following set up:

  • An OpenSearch Service domain running OpenSearch or Elasticsearch version 6.7 or later with fine-grained access control enabled within a VPC.
  • Keycloak installed and configured. In this post, we created the IdP in the same VPC of the OpenSearch domain. There is no need for a direct connection between the IdP and the service provider, so you can have the IdP in a different network as well.
  • A properly configured security group for OpenSearch Service and Keycloak IdP server to receive inbound traffic from users.
  • A browser with network connectivity to both Keycloak and OpenSearch Dashboards.

Enable SAML authentication for OpenSearch Service

The first step is to enable SAML authentication for OpenSearch Service. Complete the following steps:

  1. On the OpenSearch Service console, open the details page for your OpenSearch Service domain.
  2. On the Security configuration tab, choose Edit.
  3. Select Enable SAML authentication.

image2

Enabling this option automatically populates different IdP URLs, which is required to configure SAML support in the Keycloak IdP. Note down the values under Service provider entity ID and SP-initiated SSO URL. The OpenSearch Dashboards login flow can be configured either as service provider-initiated or IdP-initiated. The service provider-initiated login flow is initiated by OpenSearch Service, and the IdP-initiated login flow is initiated by the IdP (for example, Keycloak). In this post, we use a service provider-initiated login flow.

image3

Configure Keycloak as IdP

During the SAML authentication process, when the user is authenticated, the browser receives a SAML assertion token from Keycloak and forwards it to OpenSearch Service. The OpenSearch Service domain authorizes the user with backend roles according to the attributes presented in the token.

To configure Keycloak as IdP, complete the following steps:

  1. Log in to the Keycloak IdP admin console with admin user privileges (for example, https://<Keycloak server>:8081/admin/).
  2. Choose Create Realm.
  3. For Realm name, enter a name (for example, Amazon_OpenSearch) and choose Create.

For managing OpenSearch Service specific roles, users, and groups, you first create a separate client realm that provides a logical space to manage objects.

  1. In the navigation pane, choose your realm, then choose Clients.
  2. Choose Create client.
  3. In the General Settings window, for Client type, choose SAML
  4. For Client ID, use the service provider entity ID you copied earlier, then choose Next
    image6
  5. Under Login settings, enter the service provider-initiated SSO URL copied from earlier (for example, https://vpc-abc123.us-east-1.es.amazonaws.com/_dashboards/_opendistro/_security/saml/acs) and choose Save.image7
  6. On the client settings tab, under Signature and Encryption, turn on Sign Assertions and keep all other options as default, then choose Save.
    image8
  7. On the Keys tab, under Signing keys config, turn Client signature required off.

image9

Configure Keycloak users, roles, and groups

After you have configured the Keycloak IdP client for OpenSearch Service, you can create roles, groups, and users on the IdP side. For this post, we create two roles, two groups, and two users, as listed in the following table.

Users Groups Roles
super_user_1 super_user_group super_user_role
readonly_user_1 readonly_user_group readonly_user_role

Complete the following steps:

  1. In the navigation pane for your realm, choose Realm roles.
  2. Choose Create role.image10
  3. For Role name, enter a name (for this post, super_user_role) and choose Save.image11
  4. Repeat these steps to create a second role, readonly_user_role.

Now let’s create groups, assign the roles to the groups, and map the users to the groups.

  1. Under your realm, choose Groups in the navigation pane.
  2. Choose Create group.
  3. For Name, enter a group name (for example, super_user_group) and choose Save.image12
  4. Repeat these steps to create a second group, readonly_user_group.

When the new groups are created, they will be listed on the Groups page.

image13

  1. On the details page for each group, on the Role mapping tab, choose Assign role.image14
  2. For the group super_user_group, select the role super_user_role and choose Assign.

image15

  1. Repeat these steps to assign the role readonly_user_role to the group readonly_user_group.

The last step is to create users and assign them to groups so they automatically inherit group privileges. For this post, we create two users, super_user_1 and readonly_user_1, with dashboard admin and dashboard read-only privileges, respectively.

  1. Under your realm, choose Users in the navigation pane.
  2. Choose Create new user.
  3. Under General, configure the user details, including user name, first name, last name, and email, then choose Create.

  1. Set a temporary password on the Credentials tab after you create the user.
  2. Choose Add user and repeat these steps to add your second user, readonly_user_1.
  3. To join a user to a specific group, choose Join Group on the Groups tab of the respective user.

image17

  1. Select the group the user is joining and choose Join. For example, the user super_user_1 is joining the group super_user_group.

  1. Repeat these steps for the user readonly_user_1 to join the group readonly_user_group.

Next, you can remove the default role mapping for the users because you already assigned the roles to their respective groups.

  1. On the Role Mapping tab, select the default role.
  2. Unassign the default role for the user by choosing Unassign and then Remove.
  3. Repeat these steps for the other user.

image19

  1. Choose Client scopes in the navigation pane.
  2. In the Name column, choose role_list.

image20

  1. On the Mappers tab, choose role list.

image21

  1. Turn on Single Role Attribute and choose Save.

Download SAML metadata from Keycloak

The configuration of Keycloak is now complete, so you can download the SAML metadata file from Keycloak. The SAML metadata is in XML format and is needed to configure SAML in the OpenSearch Service domain.

  1. Under your realm, choose Realm settings in the navigation pane.
  2. On the General tab, choose SAML 2.0 Identify Provider Metadata under Endpoints.image23

This will generate an IdP metadata file in another window. This XML file contains information on the provider, such as a TLS certificate, SSO endpoints, and the IdP entity ID.

  1. Download this XML file locally so you can upload this file on the OpenSearch Service console in later steps.

Integrate OpenSearch Service SAML with Keycloak

To integrate OpenSearch Service with the Keycloak IDP, you need to upload the IdP metadata XML file on the OpenSearch Service console.

  1. On the OpenSearch Service console, navigate to your domain.
  2. Choose Security configuration, then choose Edit.
  3. Under Metadata from IdP, choose Import from XML file to import the file and auto-populate the IdP entity ID.

Alternatively, you can copy and paste the contents of the entity ID property from the metadata file.

image24

  1. For SAML master backend role, enter super_user_role.

This means that a user with this role is provided manager user privileges to the cluster, but can only use permissions within OpenSearch Dashboards.

image25

  1. Expand the Additional settings section
  2. For Roles key, enter an attribute from the assertion (in our case, Role) and choose Save Changes.image26

Test the OpenSearch Dashboards SAML authentication with Keycloak

You’re now ready to test the SAML integration with Keycloak as an IdP.

  1. Choose the OpenSearch Dashboards URL provided on OpenSearch Service console.

It will automatically redirect you to the Keycloak sign-in page for authentication.

  1. Enter the admin user name (super_user_1) and password and choose Sign In.

Upon successful authentication, it will redirect you to the home page of OpenSearch Dashboards. If you encounter issues at this step, refer to SAML troubleshooting for common issues.

Internally, the security plugin maps the backend role super_user_role to the reserved security roles all_access and security_manager. Therefore, Keycloak users with the backend role super_user_role are authorized with the privileges of the manager user in the domain. To grant read-only dashboard access to user readonly_user_1, log in to OpenSearch Dashboards as the user super_user_1. Then map the role readonly_user_role as a backend role for the reserved security role opensearch_dashboards_read_only.

When establishing access control for the cluster, it’s crucial to carefully manage the permissions granted to users, adhering to the principle of least privilege. By having both super_user_role with administrative capabilities and read-only readonly_user_role, you can strike a balance. This approach allows a small number of trusted users to have full administrative access within OpenSearch Dashboards, while also enabling read-only access for other stakeholders who require visibility but don’t need more access.

At the time of writing, if you specify the <SingleLogoutService /> details in the Keycloak metadata XML, when you sign out from OpenSearch Dashboards, it will call Keycloak directly and try to sign the user out. This doesn’t work currently with some of the versions of OpenSearch Service, because Keycloak expects the sign-out request to be signed with a certificate that OpenSearch Service doesn’t currently support. If you remove <SingleLogoutService /> from the metadata XML file, OpenSearch Service will use its own internal sign-out mechanism and sign the user out on the OpenSearch Service side. No calls will be made to Keycloak for signing out.

Clean up

If you don’t want to continue using the solution, delete the resources you created:

  • OpenSearch Service domain
  • VPN and Keycloak instance

Conclusion

In this post, you learned how to configure Keycloak as an IdP to access OpenSearch Dashboards using SAML. To learn more about OpenSearch Service and SAML integration, refer to SAML authentication for OpenSearch Dashboards. Stay tuned for a series of posts focusing on SAML integrations with OpenSearch Service and Amazon OpenSearch Serverless.


About the Author

image27Sajeev is a Senior Cloud Engineer (Big Data & Analytics) and a Subject Matter Expert for Amazon OpenSearch Service. He works closely with AWS customers to provide them architectural and engineering assistance and guidance. He dives deep into big data technologies and streaming solutions and leads onsite and online sessions for customers to design the best solutions for their use cases.

Закон за управление на информационните и комуникационните технологии в обществения сектор

Post Syndicated from Bozho original https://blog.bozho.net/blog/4412

Ключова реформа, без която няма да имаме устойчива дигитализация в обществения сектор, е приемането на изцяло нов закон за управление на информационните и комуникационните технологии в обществения сектор, за да може всички дигитални инициативи да бъдат успешни и държавата да може да си управлява информационните технологии адекватно, вкл. по отношение на киберсигурността и ограничаването на чуждестранни цифрови влияния.

Подготвили сме този закон, с който да се поправят множество системни проблеми, които сме идентифицирали в последните години. В предстоящата дълга публикация ще опиша основните направления, в т.ч.:

  • Преструктуриране на административните структури
  • Споделени ИТ услуги
  • Споделени ресурси на електронното управление
  • Рамкови споразумения и системна интеграция
  • Въвеждане на нови ръководни длъжности за дигитална трансформация
  • Централен орган за покупки
  • Стандартизация на експлоатацията
  • Предварително обсъждане на технически спецификации
  • Механизми за установяване и покриване на нуждите

Преструктуриране на административните структури

В момента структурата на Министерството на електронното управление включва една инфраструктурна агенция, която се занимава с мрежи и облак и самото министерство, което се занимава с политики. Темата „киберсигурност“ е разделена между двете, а има и Информационно обслужване, чийто принципал е министърът, което се занимава с т.нар. „системна интеграция“. Със закона целта е да се стигне до следната структура: министерство, агенция за киберсигурност, агенция за споделени услуги и ресурси и системен интегратор (Информационно обслужване).

Агенцията за споделени услуги и ресурси ще се занимава, както и досега, с поддръжката и развитието на държавния облак, на единната електронна съобщенителна мрежа, както и на хоризонталните системи на електорнното управление. Двете агенции ще работят по специален класификатор на длъжностите и ще имат облекчена структура спрямо другите административни стурктури, защото иначе би се получило излишно раздуване на щат. По отноешние на т.нар. обща администрация, ще използват тази на министерството като споделена (напр. по отношение на управление на човешки ресурси).

Агенцията за киберсигурност, освен с настоящите задължения на МЕУ и изпълнителната агенция по линия на киберсигурността, и бъдещите задължения по втората директива за мрежова и информационна сигурност, ще трябва да извършва дейности по противодействие на чуждестранна намеса в информационното пространство. Дефиницията и функциите на агенцията в това отношение са заимствени от френската агенция VIGINUM, като дефиницията е: координирана информационна намеса, която отговаря на всяко от следните условия: а) насочена е срещу основен интерес на страната; б) използва информация, която е едновременно невярна и опасна; в) използва неавтентични методи за разпространение на информацията; г) произтича с висока степен на вероятност от трета страна;“.

Споделени ИКТ услуги

В администрацията има множество дейности, които могат да бъдат изнесени от администрациите и споделяни (от т.нар. центрове за споделени услуги – практика, използвана в бизнеса отдавна). Със закона се дефинира кръгът на тези услуги (напр. поддръжка на мрежи, на периферни устройства, специализирани одити, управление на проекти и много други). Съз законопроекта се въвежда класификатор на услугите, както и детайлизиране на видовете услуги.

Началото на такава реформа дадохме през 2022 г., като събрахме информация от всички администрации за дейности по поддръжка, като целта беше да преназначим всички в изпълнителната агенция към министерството, което позволява по-добро управление на човешките ресурси, по-адекватно заплащане, стандартизиране и централизиране на процеси, изпозлване на единни информационни системи и др.

Отделно от това, в секторите „Образование“ и „Здравеопазване“ следва да бъдат създадени териториални центрове за споделени услуги, които да обслужваат лечебни и здравни заведения и училища и детски градини. Общините ще могат да се групират, за да ползват такива споделени услуги.

Споделени ресурси на електронното управление

Споделените ресурси на електронното управление са централизираните системи, които могат (и трябва) да се ползват от всички администрации. Това в момента включва: държавния облак, единната електронна съобщителна мрежа, защитения интернет възел (internet exchange), както и хоризонталните системи на електронното управление: системата за междурегистров обмен (RegiX), системата за електронна автентикация, системата за сигурно електронно връчване, портала за електронно управление egov.bg, системата за електронни плащания pay.egov.bg.

Към тези системи в законопроекта се добавят няколко други, които са от изключителна важност за киберсигурността и проследимостта на действията и трябва да бъдат въведени максимално бързо: централизиран; регистър за проследимост на събитията и централизирана система за оторизиране и проследяване на администраторските достъпи.

Създава се и правна рамка за устойчивото развитие на тези системи, както и задължение за тяхното използване – вместо всяка администрация сама да си купува хардуер, всички да са длъжни да използват държавния облак, който пък от своя страна следа да бъде развит до качествена „инфраструктура като услуга“, а не както е в момента – ръчно-крачен режим за заявяване на виртуални машини.

Предвижда се и фонд за развитие на софтуера с отворен код, по примера на Германия и други държави, които финансират разработването на ключови за държавната администрация компоненти с отворен код.

Рамкови споразумения и системна интеграция

Основен дефицит на управлението на информационните технологии е липсата на предвидимост и на гъвкавост. Изграждането на нови системи отнема години (а понякога – десетилетие), дори дребни нови функционалности са много отвъд сроковете. Идентифицираните нужди преминават през бавен процес и докато се стигне до това, те да бъдат обезпечени, изискванията са се променили.

В други европейски държави се използват два подхода, понякога в комбинация – рамкови споразумения и национален системен интегратор. В подготвения законопроект има и двата.

Рамковите споразумения по образец, одобрен от МЕУ, следа да покриват основни ИТ услуги, от които има нужда администрацията. Те следва да бъдат сключвани от министерства и да могат да се използват в цялата структура на министерството (т.е. и от всички агенции към него). По този начин ще се постигне бързина и икономии от мащаба. Най-често тези рамкови споразумения биха били с консорциуми, защото спектърът от услуги е доста широк и няма много компании, които да предлагат целия набор на достатъчно добро ниво. Това ще намали разходите, тъй като ще се заплаща на малки части, при реална нужда, а не както в момента – на големи парчета, при които възможността за оценка на разходите е трудна.

Този ред ще е приложим за повечето институции. За няколко специфични институции ще се прилага същият подход, но с точно определен интегратор – по всяка вероятност Информационно обслужване. Точният кръг на администрациите, които със закон ще бъдат определени да използват услугите на системния интегратор, ще може да се обновява веднъж годишно през Закона за бюджета, а не както в момента – понякога на всеки 2 седмици с решение на Министерския съвет.

Този подход се използва в доста европейски държави, като системният интегратор (държавна собственост) се явява лице, осъществяващо публични функции и гарантира устойчивост на ключови регистри и системи в държавата. Развил съм тази концепция още през 2021 г., като смятам, че електронното управление вече е основна функция на държавата и тя не може да бъде аутсорсната по отношение на някои критични дейности. Например ако Търговският регистър спре, държавата се срива. Ако данните от имотния регистър се загубят, имаме сериозен проблем (макар нотариалните актове да са при собствениците). Ако частно лице има достъп до цялата здравна информация на всички пациенти, се създава сериозен риск. Още повече, че в някои случаи има квази-монополиация от една фирма, поради т.нар. vendor lock-in. За да се избегнат тези рискове, е нужен вътрешен за държавата капацитет за основни ИТ услуги.

В същото време, такава концентрация на ключови системи в системния интегратор крие рискове. За ограничаване на тези рискове, в законопроекта се въвеждат редица контролни механизми, в т.ч.: одит от Сметната палата на цялостната дейност, забрана за участие в открити процедури (което би било проблем за конкуренцията, защото интеграторът може да субсидира участието в открити процедури със „сигурните пари“, които получава като лице, осъществяващо публична функция с изкючителни права), въвеждане на двустепенна форма на управление, изслушване на изпълнителния директор в ресорната парламентарна комисия преди назначаване (което задължително е с конкурс), ограничения за превъзлагане, годишни отчети за дейността и най-вече – пълна прозрачност на дейността и на финансирането от държавата.

Тук обикновено има реакция „как така държавата ще прави тези неща сама, това е комунизъм“. Но както писах по-горе, това е основна функция на държавата в 21-ви век. Както държавата не си аутсорства армията и полицията, така според мен не може да си аутсорства дългсорочното познание за ключови регистри. Може някои дейности да бъдат възлагани на външни изпълнители, но основното познание за тези ключови системи трябва да остане вътре в държавата, за да се избегнат зависимости. Едно е да наемеш фирма да ти построи и поддържа път, друго е никой в държавта да не знае как работи системата за обществени поръчки, напр.

Другият аргумент е, че за да аутсорснеш нещо (което ще бъдат мнозинството от дейностите в ИКТ), трявва да имаш вътрешен капацитет да управляваш аутсорсинга. Напр. чрез (споделен) project management office, чрез професионално консултиране на подготовката на технически спецификации, чрез експертно участие в приемането на резултата – особено при приемането в момента има сериозни дефицити, защото по спецификация се поръчва Мерцедес (образно казано), а накрая се получава Москвич с ламарини на Мерцедес, обаче никой в приемателната комисия не разбира, не може да отвори капака и подписва.

Комбинацията от рамкови споразумения, системна интеграция, споделени услуги и ресурси, и развиване на вътрешния капацитет за управление на ИКТ в администрациите (описан в следващата точка), ще даде възможност държавата най-накрая да влезе в релси с информационните технологии.

Въвеждане на нови ръководни длъжности за дигитална трансформация

В администрацията в момента няма определена длъжност с лидерска роля в информационните технологии. Обикновено ИТ директорът (с малки изключения), не участва в стратегическото развитие на администрацията, на нейните услуги и вътрешни процеси. ИТ директорът организира наличието на интернет, компютри и принтери, да се купят лицензи за софтуера за информационна сигурност, и участва в писането на технически спецификации за обществени поръчки. Нужно е да има Chief Information Officer, който да се занимава не просто с технологичната част, а с промяната на вътрешните процеси и да докладва директно на министъра, а не да е „в трета глуха“ на административната йерархия, някъде като началник на отдел в общтата администрация. Затова предлагаме създаването на „Секретар по информационни технологии“, с ясно определени правомощия в Закона за администрацията.

Паралелно с това предлагаме и регламентиране на законово ниво на т.нар. Chief information security officer, или в случая – секретар по информационна сигурност. В момента такива трябва да има по силата на подзаконовата уредба към Закона за киберсигурност, но много често тази длъжност или е незаета, или се съвместява от някой друг, или се аутсорства, или се дава на човек, който е сравнително ниско в йерархията. Затова въвеждането на законово ниво, с ясни функции, трябва да подобри това, като в същото време, в комбинация с повишеното заплащане за ИТ длъжности, да привлече компетентни експерти.

Третата роля е секретар по управление на риска – chief risk officer. Рискът е нещо трудно да осмисляне в администрацията, която работи по строги процеси, но по много причини е важно да има човек с екип, който да управлява рисковете. Всяка административна структура има различни рискове, които в момента не се управляват, а ИТ рисковете са само част от тях.

В законопроекта се предвижда и отделен раздел на класификатора по Закона за държавния служител, предвиден само за ИТ длъжности.

Централен орган за покупки

В администрацията постоянно се купуват стандартни неща – лаптопи, принтери, лицензи за често-срещан софтуер. В много държави това е организирано през т.нар. „централен орган за покупки“, където има сключени рамкови споразумения с максимални отстъпки (поради големия обем), и след това купуването става (образно казано) с едно натискане на мишката, вместо едногодишни процедури по ЗОП или по-кратки, под праговете, които в следващите години „избухват“ като цена. В някои случаи към тези покупки има нужда и от услуги по внедряване, които също ще бъдат предоставяни през системата, от оторизираните партньори на съответния доставчик, на предварително определени цени.

По този начин ще бъдат спестени средства (заради по-големите отстъпки) и време (заради по-бързия процес) по закупуване и внедряване в експлоатация. Централният орган за покупки ще е задължителен за централната администрация, но ще може да се използва и от местната и от съдебната власт, по тяхна преценка.

Със закона се предвижда централният орган за покупки за ИКТ да бъде към Министерството на електронното управление. Такъв беше заложен и в програмата на предишното редовно правителство, но уреждането му на законово ниво повишава шанса да бъде изпълнен по правилния начин.

Стандартизация на експлоатацията

В момента внедряването в експлоатация на системи е на етап „дивия запад“. Кое как се внедрява, как се правят промени в продукционна среда, какво се мониторира и как се реагира, какво се одитира – всичко е ad-hoc, и често не се случва. Системи падат, защото никой не ги мониторира, в продукционна среда се внедряват неща, които не са тесвани; системите в продукционна среда се различават от това, което е предадено на възложителя.

Затова със законопроекта се въвежда стандартизиран ред за внедряване в експлоатация, задължения за мониторинг, както и за оперативна устойчивост – предвижда се разпоредбите на DORA (регламент за финансовия сектор) да се прилагат и за системи със стратегическо значение. Въвежда се и задължение за регулярни специализирани одити на стратегически системи.

Със законопроекта се въвежда т.нар. total cost of ownership (обща цена за притежаване на активите). Към момента такива изчисления не се правят при избор на дадена технология, продукт или подход (build vs buy). И често държавата харчи пари за изцяло нова разработка на нещо, което съществува на по-ниска цена или обратното – плаща прескъпи лицензи за продукти, чиято функционалност използва на 5% и може да разработи сравнително лесно. Сходен проблем има и при закупуването на лицензи, особено при все по-популярния subscription модел. Затова се въвежда задължение за изчисляване на TCO.

Предварително обсъждане на технически спецификации

Един от проблемите, който се забелязва във всички сектори, но и в конкретно в ИТ, е че техническата спецификация се появява на бял свят с обявяването на обществената поръчка. Това води до следния проблем: ако в нея има проблеми, недообмислени апсекти, заключващи критерии за конкретен доставчик, единственият начин тя да се промени, е да се прекрати процедурата, което пък води до допълнително забавяне.

Затова със законопроекта се въвежда предварителна стъпка на обществено обсъждане на техническите спецификации, за да може всички участници да преценят има ли дискриминационни критерии или изисквания, чието изпълнение би създало рискове за целия проект.

Механизми за установяване и покриване на нуждите

Информационните технологии са изключително динамични, нови решения на стари проблеми се появяват непрекъснато, а съществуващите решения търпят съществени промени, вкл. концептуални. Законът за обществените поръчки дава формалната част на възлагането, но не дава структуриран процес на предшестващите стъпки. Със законопроекта се въвежда конкретика в процесите по установяване на нуждите на организациите и начините за тяхното покриване.

Понякога решението е „build vs buy“ (да изградиш нова система или да си купиш лиценз за съществуваща, която да „настроиш“ спрямо твоите нужди), понякога има решения, за които администрацията дори не подозира, че могат да решат техни дългогодишни проблеми в дадена сфера, понякога, за да стигнеш до работеща концепция, е нужно да получиш обратна връзка от бизнес какви са възможните подходи.

Ако някоя администрация подходи по-креативно към тези проблеми, това оставя съмнения за злоупотреби: напр. защо питаш фирмите да ти кажат как да подходиш към проблема? Защо приемаш фирма Х, която да ти предложи иновативно решение? Защо внедряваш пилотно продукт, който не си избрал по реда на ЗОП, и след това не получава ли той примущество? Затова със законпроекта се въвждат няколко такива механизма, по които процесите да бъдат ясни и да се ограничи риска от злоупотреби: пазарно проучване (да не се бърка с пазарна консултация, което е съществуващ ред в ЗОП), заявка за предложения (request for offer), пилотно внедряване (с гаранции, че това няма да даде преимущество при последваща процедура по ЗОП), диалог за иновации (при който съвместно се идентифицират проблеми и потенциални решения). Всяка една стъпка от тези процеси се документира и публикува, така че да има пълна проследимост и прозрачност.

Заключение

Законопроектът е с много широк обхват и прави съществена реформа във всички структури на държавата. Смятам, че такъв е крайно необходим, за да може държавата да изпълнява основните си функции в 21-ви век, да намали разходите за ИКТ, да повиши качеството на предоставяните услуги и да гарантира устойчивост на информационните си ресурси.

Материалът Закон за управление на информационните и комуникационните технологии в обществения сектор е публикуван за пръв път на БЛОГодаря.

[$] The long road to lazy preemption

Post Syndicated from corbet original https://lwn.net/Articles/994322/

The kernel’s CPU scheduler currently offers several preemption modes that
implement a range of tradeoffs between system throughput and response time.
Back in September 2023, a discussion
on scheduling
led to the concept of “lazy preemption”, which could
simplify scheduling in the kernel while providing better results. Things
went quiet for a while, but lazy preemption has returned in the form of this patch series
from Peter Zijlstra. While the concept appears to work well, there is
still a fair amount of work to be done.

Justice Department Indicts Tech CEO for Falsifying Security Certifications

Post Syndicated from Bruce Schneier original https://www.schneier.com/blog/archives/2024/10/justice-department-indicts-tech-ceo-for-falsifying-security-certifications.html

The Wall Street Journal is reporting that the CEO of a still unnamed company has been indicted for creating a fake auditing company to falsify security certifications in order to win government business.

Security updates for Friday

Post Syndicated from daroc original https://lwn.net/Articles/994703/

Security updates have been issued by AlmaLinux (java-1.8.0-openjdk, java-11-openjdk, java-17-openjdk, java-21-openjdk, and webkit2gtk3), Debian (apache2), Red Hat (expat), SUSE (cups-filters, jetty-minimal, OpenIPMI, and python-starlette), and Ubuntu (linux-azure, linux-azure, linux-azure-5.15, linux-azure, linux-azure-5.4, and oath-toolkit).

7 Rapid Questions on our Belfast Placement Programme: Orla Magee and Paddy McDermott

Post Syndicated from Rapid7 original https://blog.rapid7.com/2024/10/18/7-rapid-questions-on-our-belfast-placement-programme-orla-magee-and-paddy-mcdermott/

7 Rapid Questions on our Belfast Placement Programme: Orla Magee and Paddy McDermott

Ever wonder what it’s like to be an intern at Rapid7 in Belfast?

Software Engineers Orla Magee and Paddy McDermott share what the interview process looked like for them, along with impactful projects and advice for others exploring Rapid7’s Placement Programme.

What was the interview process like for the Placement Programme?

Paddy: The interview process for Rapid7’s Placement Programme was well structured and welcoming. It consisted of two parts, a one-on-one chat focusing on cultural alignment, and a technical interview with programming questions and a puzzle to solve. The interviewers were approachable, which helped me feel at ease. I felt as though they struck a good balance, assessing my skills without overwhelming me with information and questions. It felt like a genuine attempt to get to know me as a person and assess my skills, rather than just ticking boxes.

Orla: From the start, the talent acquisition team was friendly and communicative, keeping me well-informed about each stage. The interviewers seemed genuinely interested in getting to know me as a person, highlighting that being yourself is crucial in this process. Overall, the interview experience reflected positively on Rapid7’s commitment to finding well-rounded individuals who can contribute both technically and culturally to their team, which made me feel at ease and excited for an opportunity to work at Rapid7.

What initially stood out to you about Rapid7?

Paddy: What stood out to me about Rapid7 was the genuine connection I felt with the people I met during the interview process. The interviewers were engaging and approachable, which gave me a strong sense of the company’s collaborative culture. Another thing that caught my attention was Rapid7’s commitment to growing new talent. This became clear when I attended an event specifically for intern applicants, where I got to experience the company’s welcoming atmosphere firsthand. A mix of friendly people, a learning-focused environment and the opportunity for significant professional growth really made Rapid7 stand out as an ideal place to begin my career.

What was the learning curve like coming into Rapid7 as a student, and what resources or tools did you have to navigate that?

Orla: Transitioning from university to working at Rapid7 as a student came with a significant learning curve. In university, I was used to working independently on projects. At Rapid7, I had to adapt to collaborating as part of a team. This shift required developing my communication skills and learning to work effectively with others. Additionally, the codebase was much bigger and more complex than the smaller-scale projects I had worked on in university. To help navigate these challenges, I was paired with a mentor at the start of my internship, who was instrumental in developing my technical abilities and helping me adjust to working in a professional environment. Alongside my mentor, my team members were always willing to offer assistance and guidance, creating a supportive atmosphere that facilitated my learning and growth. This combination of mentorship and team support was crucial in helping me overcome the learning curve and successfully adapt to a new work environment.

Can you share a memorable project or experience?

Paddy: One of my most memorable achievements during my placement was developing a full-stack status page. This project was particularly significant as it served a real, practical purpose within the company. The status page I created was designed to alert on outages and display the health of various components of our team’s pipeline. This tool was used beyond our team, and was shared internally across different parts of the company. This project allowed me to greatly expand my full-stack development skills in a meaningful way. It was rewarding to see something I built from the ground up being actively used to improve monitoring and communication about our pipeline’s status.

What advice would you give someone looking to land a Placement with Rapid7?

Orla: Take advantage of intern nights, held at the office, as these events offer a unique glimpse into Rapid7’s culture and team dynamics. These events are great opportunities to network and build connections with current staff members, potentially giving you an insider’s perspective on the company.

Paddy: My main advice would be to be yourself throughout the whole process as this will really   help you connect with the interviewers and showcase your true potential. Also, make sure to demonstrate a strong willingness to learn, as Rapid7 values candidates who are eager to grow and take on new challenges.

What were some of your biggest fears coming in, And how did that compare to reality?

Orla: When I started my internship at Rapid7, my main concern was that my technical skills might not measure up to those of my peers. I worried about potentially struggling to contribute meaningfully to the team, but my real experience showed that these worries were unnecessary. From day one, I was met with a welcoming and supportive environment. My colleagues were not only understanding of my position as an intern but were also genuinely enthusiastic about helping me develop my skills. They took the time to walk me through their current projects, providing valuable context and insights that helped me quickly get up to speed. My initial uncertainty was replaced with excitement for the opportunity to learn and contribute, and the reality of the internship far exceeded my expectations.

How has your placement experience prepared you for a successful career?

Paddy: Overall, the placement has given me a mix of technical growth, hands-on experience and professional development creating a strong foundation for my future in tech. I’ve learned many new programming languages with guidance from experienced colleagues. Working in a live production environment has equipped me with real-world skills and experiences. Presenting demos has boosted my confidence in public speaking and taught me how to communicate technical concepts effectively. I’ve built connections and friendships with coworkers which has made the work environment enjoyable and allowed me to start to form a professional network that will be valuable in my career.

Interested in learning more about the Placement Programme, or additional emerging talent programmes at Rapid7? Click here to explore our offerings and view open jobs.

Options for AWS customers who use Entrust-issued certificates

Post Syndicated from Zach Miller original https://aws.amazon.com/blogs/security/options-for-aws-customers-who-use-entrust-issued-certificates/

Multiple popular browsers have announced that they will no longer trust public certificates issued by Entrust later this year. Certificates that are issued by Entrust on dates up to and including October 31, 2024 will continue to be trusted until they expire, according to current information from browser makers. Certificates issued by Entrust after that date will not be trusted.

If you’ve imported Entrust certificates into AWS Certificate Manager (ACM) for use with integrated services such as Amazon CloudFront or Elastic Load Balancing, consider reissuing these certificates through Entrust before October 31, 2024, and re-importing them. This will provide you with a longer timeline to evaluate your alternatives. In this blog post, we discuss how you can determine whether certificates you imported to ACM will be affected, and suggest potential alternatives, including public certificates issued by Amazon Trust Services.

How to tell if you’ve imported Entrust certificates to ACM

If you’re unsure whether you’ve imported certificates to ACM, there are a few different ways to verify. You can use the ACM console to view your certificates for that AWS account. Certificates that are imported to ACM have the type Imported, as shown in Figure 1.

Figure 1: Viewing certificates in AWS Certificate Manager

Figure 1: Viewing certificates in AWS Certificate Manager

You can also list the certificates in your AWS account by using the AWS CLI or APIs. You can use the list-certificates command with the AWS CLI:

aws acm list-certificates

You can then filter the response to only show the certificate ARN of certificates that are imported into ACM by using the following command:

aws acm list-certificates --query 'CertificateSummaryList[?Type==`IMPORTED`].CertificateArn'

After you’ve identified the ARNs of imported certificates, you can use the describe-certificate CLI command to get more information about each of the imported certificates. One of the returned fields is Issuer—this field indicates who originally issued the certificate in question. See the following example command and output, where in this case the issuer is Amazon:

aws acm describe-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012

{
"Certificate": {
"CertificateArn": "arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012",
"CreatedAt": 1446835267.0,
"DomainName": "www.example.com",
"DomainValidationOptions": [
{
"DomainName": "www.example.com",
"ValidationDomain": "www.example.com",
"ValidationEmails": [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
},
{
"DomainName": "www.example.net",
"ValidationDomain": "www.example.net",
"ValidationEmails": [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
}
],
"InUseBy": [],
"IssuedAt": 1446835815.0,
"Issuer": "Amazon",
"KeyAlgorithm": "RSA-2048",
"NotAfter": 1478433600.0,
"NotBefore": 1446768000.0,
"Serial": "0f:ac:b0:a3:8d:ea:65:52:2d:7d:01:3a:39:36:db:d6",
"SignatureAlgorithm": "SHA256WITHRSA",
"Status": "ISSUED",
"Subject": "CN=www.example.com",
"SubjectAlternativeNames": [
"www.example.com",
"www.example.net"
]
}
}

You can use one of these methods to determine whether you’ve imported certificates to ACM, and use the Issuer field of the DescribeCertificate response to check whether any of your imported certificates were issued by Entrust and will be affected by the coming changes in popular browsers.

Lastly, you can also use this sample code from our GitHub repository to discover imported certificates that were issued by a certain CA or issuer. The project evaluates the ACM certificates for a given AWS account, flagging certificates with an Issuer value that matches against a specific, customizable list of CAs. This can be run as a Python script, an AWS Config query, or a custom rule in AWS Config.

Consider replacing Entrust certificates with public certificates issued through ACM

If you’re using Extended Validation (EV) or Organization Validation (OV) certificates, we recommend that you use Domain Validated (DV) certificates from ACM instead. Popular browsers do not differentiate between EV/OV and DV certificates when indicating whether a site is trusted. Additionally, EV/OV certificate issuance and renewals cannot be automated and require manual effort, unlike DV certificates.

You can use ACM to get DV certificates at no additional cost for use with Amazon CloudFront, Elastic Load Balancing, or Amazon API Gateway. Our public certificates are issued by Amazon Trust Services and are trusted by popular browsers and operating systems. When you issue certificates through ACM, you get the benefit of fully managed certificate renewal, where ACM automatically renews and redeploys the certificate when it is 60 days from expiration.

Evaluate use of private certificates for internal-facing use cases

We also recommend that you re-evaluate your use of certificates to reconsider whether you need private or public certificates for your use cases. For internal-facing workloads, you should consider using private certificates. This will allow you to control the certificate parameters, such as the certificate type or the validity period, to align with your specific TLS requirements. For example, ACM issued public certificates are valid for 395 days, but you might have use cases in which certificates with a longer validity period make more sense, and in such cases you can issue private certificates from AWS Private Certificate Authority (AWS Private CA).

Conclusion

In summary, if you are importing Entrust-issued certificates to ACM, evaluate whether you need public or private certificates, especially for internal-facing workloads—for which private certificates are typically better suited. For public certificates, take this opportunity to re-evaluate your usage of EV and OV certificates, and whether they could be replaced with DV certificates. If you want to use public certificates with services such as Amazon CloudFront, Elastic Load Balancing, or Amazon API Gateway, issue the certificates directly from ACM. Lastly, if you need more time to evaluate your options before making a decision, consider re-issuing and re-importing your certificates from Entrust before October 31, 2024. Popular browsers stated their intention to trust certificates issued by Entrust prior to October 31, 2024 until these certificates expire, giving you until the next certificate renewal to make an informed decision. You can learn more about ACM by reviewing the AWS documentation, and get started issuing certificates from ACM in the AWS Management Console.

 
If you have feedback about this post, submit comments in the Comments section below. If you have questions about this post, contact AWS Support.
 

Zach Miller
Zach Miller

Zach is a Principal Security Specialist Solutions Architect at AWS. His background is in data protection and security architecture, focused on a variety of security domains, including applied cryptography and secrets management. Today, he focuses on helping enterprise AWS customers adopt and operationalize AWS security services to increase security effectiveness and reduce risk.
Chandan Kundapur
Chandan Kundapur

Chandan is a Principal Technical Product Manager on the AWS Certificate Manager (ACM) team. With close to 20 years of cybersecurity experience, he has a passion for driving the ACM team’s product strategy to help AWS customers identify and secure their resources and endpoints with public and private certificates.
Ian Olson
Ian Olson

Ian is a Senior Security Specialist Solutions Architect at Amazon Web Services. He helps customers automate security services to safeguard against threats like DDoS attacks and web exploitations. Through intelligent automation, he delivers security solutions tailored to organizations of any scale. When he’s not working, Ian enjoys spending quality time with his two young children.

Научни новини: Кой взе Нобеловите награди за медицина, физика и химия и защо

Post Syndicated from Михаил Ангелов original https://www.toest.bg/nauchni-novini-koy-vze-nobelovitie-naghradi-za-mieditsina-fizika-i-khimiia-i-zashto/

Медицина/физиология

Научни новини: Кой взе Нобеловите награди за медицина, физика и химия и защо
Виктор Амброс и Гари Ръвкън. Илюстрация: Niklas Elmehed © Nobel Prize Outreach

Научни новини: Кой взе Нобеловите награди за медицина, физика и химия и защо

По традиция първата обявена награда е в категорията медицина/физиология. Тази година лауреатите са Виктор Амброс и Гари Ръвкън за откриването на микро-РНК и участието ѝ в регулацията на гените след транскрипцията. Този вид РНК е непозната за науката до 1993 г. и с времето се оказва, че е един от ключовите компоненти за нормалното функциониране на процесите в сложните организми.

Централната догма в биологията най-общо указва потока на информация в живите организми като ДНК -> РНК -> протеини. От ДНК в процеса на транскрипция се образува информационна РНК (иРНК). Тя от своя страна е основа за транслацията, при която от множество аминокиселини се образуват протеини – основен градивен елемент на тъканите, както и главните отговорници за протичането на биохимичните процеси в организма ни. 

Но както знаем, всяка клетка носи пълния набор от генетична информация, която е нужна за изграждането на тялото ни, без значение къде се намира. Това означава, че за оформянето на специфични тъкани и органи е нужно да бъдат активирани само част от тези гени – регулация на генната активност. Процесът е изключително сложен и динамичен, като по време на съществуването на една клетка са активни различни гени в различна степен. Поддържането на този фин баланс е ключов за нормалното протичане на живота на клетките.

Малко след средата на миналия век стават известни няколко механизма за това. Един от тях се базира на т.нар. транскрипционни фактори – протеини, които имат способността да се свързват с ДНК, като или помагат в процеса на транскрипция, или пречат, регулирайки количеството РНК и съответно количеството протеин, което се произвежда от клетките. 

Друг механизъм се основава на промени в начина, по който се съхраняват около 2 метра ДНК в ядрото на всяка клека. За да може да се побере, тя се навива подобно на телефонен кабел. Някои читатели знаят добре колко досадно е да се разплете такъв кабел, когато се пренавие и стане на топка. Поради изключително важната функция на ДНК, ако това се случи в клетките, решението ще бъде по-сложно от досадно разплитане. Ето защо е необходим елегантен подход – нишката се навива около своеобразни „макари“, наречени хистони. Но освен че изпълняват структурна роля, те имат значение и за регулацията на гените. Ако ДНК се навие много плътно около тях, то ензимите, които я разчитат, за да произведат РНК, не могат да изпълняват функцията си и така гените на практика се „изключват“. Това е един от механизмите, на които се базира епигенетиката. Тя обяснява как в организмите може да настъпят промени, които се наследяват, без реално да има промяна в генетичната информация.

Но както често се оказва в биологията, за да се случи дадено нещо, има и още един начин. Откриването му е следствие от работата на Амброс и Ръвкън в лабораторията на Робърт Хорвиц, който по-късно, през 2002 г., получава една трета от Нобеловата награда за медицина за откритията си при програмираната клетъчна смърт (апоптоза). При този процес клетките активират в себе си механизми, водещи до тяхното загиване. Това помага при оформянето на някои органи – например отпадането на ципата между пръстите, или има защитна функция, предпазвайки тялото от образуване на тумори.

Организмът, който изследват учените, е микроскопичен кръгъл червей – нематодата C. elegans. Той често е обект на изследвания, защото е лесен за отглеждане, има сравнително малък и добре проучен геном и дава възможност за прехвърляне на установеното при него към по-висши организми. Двамата учени разглеждат мутанти с променена функция на два специфични гена. Мутациите в гена lin-4, с който работи Амброс, водят до липса на различни специализирани клетки и зависещите от тях тъкани в червеите. Обектът на Ръвкън – lin-14, обикновено е активен в началните стадии на развитие на организма, но при мутации в него C. elegans продължава да образува ембрионални клетки по-дълго от нормалното.

Пъзелът започва да се сглобява, след като Амброс установява, че lin-4 блокира действието на lin-14, а Ръвкън прави интересното откритие, че това се случва след – а не както се очаква – преди да се образува иРНК. Още по-интригуващо е, че някои от мутациите, които променят функцията на lin-14, се намират в част на РНК, която не кодира протеин (т.нар. UTR – нетранслиран регион). Следващият пробив идва от лабораторията на Амброс. Ученият успява да установи местоположението на lin-4 в генома в участък, който не съдържа гени, кодиращи протеин. Вместо това от гена се получават две много къси РНК молекули.

Сравнявайки секвенциите на двете РНК молекули – късата, кодирана от lin-4, и иРНК от lin-14, – учените установяват, че те са комплементарни една с друга (последователностите им се припокриват). Значението на това става ясно веднага – открит е нов механизъм за генно регулиране, и то след като вече е образувана иРНК, още повече не от протеин, а от непознат до момента вид РНК.

За съжаление, двете публикации не предизвикват очаквания фурор и този тип генна регулация се приема за механизъм, специфичен за нематодата, съответно без особено значение за човека и други по-висши организми. Промяната идва няколко години по-късно, когато групата на Ръвкън открива друга микро-РНК, кодирана от гена let-7. Негови близки разновидности се срещат в цялото животинско царство – от водните гъби до човека, и са пример за много добре запазена секвенция, каквато се наблюдава в гени с изключително важно значение.

След откриването на let-7 са идентифицирани над хиляда различни микро-РНК при човека и е установено, че те са универсален механизъм за генна регулация при всички многоклетъчни организми и най-вероятно са еволюирали преди милиони години в общия предшественик на всички организми, населяващи планетата. 

Вече се знае повече и за механизма им на действие. След като от ДНК се получи дългата форма на микро-РНК, тя се завива като фуркет за коса в U-форма благодарение на сходни секвенции в двата си края. След това ензим, наречен Dicer, я срязва, давайки късата активна форма на микро-РНК. Тя е свободна да се свърже с целевата си иРНК, като или предизвиква нейното разрушаване, или пречи на ензимите, които я „превеждат“ в протеин. Процесът е изключително сложен и съществуват мрежи на регулация, в които един ген може да бъде модулиран от много микро-РНК или една микро-РНК може да влияе върху множество гени.

Значението на този механизъм е голямо – потвърждава се от присъствието му във всички сложни организми, както и от това, че при нарушаване на нормалната му функция се отключват множество нежелани процеси. При човека са познати редица генетични заболявания, причинени от мутации в гените, отговорни за синтеза на микро-РНК. Знаейки за тези негативни ефекти, учените вече работят по различни терапии, които могат да възстановят нормалното функциониране на генната регулация или да променят нежеланата дейност на определени гени.

Това не е първата Нобелова награда, свързана с малки РНК молекули. През 2006 г. високото отличие е присъдено на Андрю Файър и Крег Мело за откритието на РНК интерференцията отново в нематодата C. elegans. Процесът е много сходен с този при микро-РНК, но за разлика от тях, small interfering RNA (siRNA) са строго специфични за конкретна целева РНК. Благодарение на това те се използват успешно и като терапия срещу различни вирусни заболявания, а също и като инструмент в молекулярната биология.

Въпреки невероятната скорост, с която напредва познанието ни за фундаменталните процеси, протичащи в живите организми, тези награди показват колко сложна е регулацията им и колко изненади могат все още да крият. Понякога любопитството и работата с организми, които изглеждат не особено важни, разкриват цяло ново поле в медицината и генетиката.

Физика

Научни новини: Кой взе Нобеловите награди за медицина, физика и химия и защо
Джон Хопфилд и Джефри Хинтън. Илюстрация: Niklas Elmehed © Nobel Prize Outreach

Тази година наградата за физика е присъдена на Джон Хопфилд и Джефри Хинтън за тяхната основополагаща работа в полето на машинното обучение с изкуствени невронни мрежи. Наградата предизвика значителен интерес, тъй като изглежда малко необичайно отличието за физика да се даде за разработка в полето на информационните технологии – каквато са невронните мрежи, – и това дори доведе до негативни коментари в социалните мрежи. Също така Хинтън попадна в редица новини миналата година, когато прекрати десетгодишното си участие в подразделението на Google за изкуствен интелект – Google Brain, изразявайки силна тревога от развитието на изкуствения интелект и заплахата му за човечеството.

Според Нобеловия комитет наградата е оправдана, тъй като двамата учени са използвали фундаментални похвати от физиката като статистически модели и с разработките си са помогнали за напредъка на изследванията в много полета, като физика на елементарните частици, астрофизика, материалознание и др.

Кариерата на Хопфилд е дълга и интересна. След като защитава докторат по физика през 1958 г., проявява интерес в развиващото се поле на молекулярната биология, където предлага концепцията за „кинетична корекция“, която дава потенциално обяснение за високата точност при биохимични процеси, като репликацията на ДНК. В статия, публикувана през 1982 г., ученият описва мрежа, в която връзките между отделните звена може да се разглеждат като физични сили. Тази структура, известна като мрежа на Хопфилд, е много сходна с асоциативната памет при хората.

Използвайки познанията си за магнитните материали, в които всеки атом влияе на околните, създавайки зони с еднакво поле, той описва мрежа, в която „невроните“ могат да съдържат 0 или 1 и са свързани помежду си с различни по сила нишки. Така едно изображение може да бъде разделено на отделни пиксели и в зависимост от това дали са черни, или бели, да им се даде стойност – съответно 0 или 1.

При обучението на мрежата силата на връзките между отделните неврони се променя, докато не се постигне възможно най-ниска енергия – оптимална стойност. Когато мрежата се използва, специален алгоритъм преминава през новото изображение и проверява дали промяната в цвета на всеки пиксел ще доведе до стойност, най-близка до оптималната. Така малко по малко е възможно да се пресъздаде оригиналното изображение. Особено полезно в случая е, че в модела може да се запазят няколко изображения, които невронната мрежа да различи. Наред с това моделът може да работи и с частично липсващи данни или с известно количество шум.

Вдъхновен от тази идея, Хинтън решава да опита да я разшири, заемайки идеи от статистическата механика. При нея се разглеждат системи, състоящи се от множество сходни елементи, например молекулите в даден обем газ. Въпреки че самите молекули не могат да бъдат проследени, състоянието им може да се установи приблизително чрез наблюдение на параметрите на цялата система и чрез използване на статистическо моделиране, за да се определи кое е най-вероятно, с помощта на уравнението на Болцман, формулирано от австрийския физик през XIX в.

Усъвършенстваният вид невронни мрежи – „машини на Болцман“ – е публикуван от Хинтън само три години след тези на Хопфилд. Те имат два вида неврони – видими, които получават входната информация, и скрити, които са отделени в друг слой. Между всички неврони отново има връзки с различна тежест, които се оптимизират по време на обучение, така че вероятността да се получи резултат, сходен с началните данни, да е най-висока. Така новите невронни мрежи вече могат да разпознават информация, която не са виждали, но е близка до някоя от познатите им.

След поставянето на това начало е изминат дълъг път и са въведени най-различни иновации. Един пример е откритието, че ако връзките са само между някои неврони, мрежите са по-ефективни. Така от първоначалната невронна мрежа на Хинтън, която се състои от 30 неврона, в момента имаме големи езикови модели с над един трилион. Скромно начало на революция, която тепърва набира скорост.

Най-вероятно повечето от нас вече са използвали новите технологии, приели общото наименование изкуствен интелект. Не само за по-добър машинен превод или препоръки за музика и сериали, а и за разговори с различни чат програми, за генериране на изображения и текст, за решаване на сложни задачи. Полза има и за самите физици, които може да са обидени от наградата тази година, но те често използват подобни алгоритми за обобщаване на големи обеми данни, премахване на шум или при търсенето на екзопланети. В крайна сметка едва ли има поле на съвременната наука, което не е почерпило ползи от технологията, създадена от Хопфилд и Хинтън.

Но бързият напредък крие и своите рискове. Генерирането на фалшиви изображения, неразличими от истинска фотография, вече е факт. Създаването на видео вече достига ниво, при което зрителите лесно може да се заблудят, ако не внимават. Клонирането на гласове е реалност. OpenAI опитаха да наподобят Скарлет Йохансон при озвучаването на гласовия асистент на ChatGPT, а популярният създател на съдържание за Raspberry Pi Джеф Гийрлинг сподели, че китайска компания е използвала гласа му, за да озвучи свои рекламни видеа. Всичко това се случва на фона на сравнително ниска медийна култура, разсеяна и поляризирана публика и целенасочени дезинформационни кампании от актьори, подкрепяни от държавите. 

Двамата лауреати независимо един от друг изказват своите тревоги за скоростта и липсата на контрол при създаването на нови модели и инструменти и апелират за по-силни регулации и проучвания, преди моделите да станат общодостъпни. Хинтън е особено притеснен за развитието на т.нар. изкуствен интелект с общо предназначение (силен ИИ), който ще има способности, неразличими от тези на хората, а с развитието си – дори и по-големи. Към момента ние сме най-интелигентните създания в нашия свят и няма еднозначен отговор на въпроса какво ще стане, когато това се промени.

Химия

Научни новини: Кой взе Нобеловите награди за медицина, физика и химия и защо
Дейвид Бейкър, Демис Хасабис и Джон Джъмпър. Илюстрация: Niklas Elmehed © Nobel Prize Outreach

Наградата за химия затвърждава приноса и популярността на изкуствения интелект. Тази година половината е присъдена на Дейвид Бейкър за приноса му в изчислителната химия, а другата половина е разделена между Демис Хасабис и Джон Джъмпър за разработката на софтуер, който може да предсказва структурата на протеините. За разлика от наградата за физика, където връзката може да се определи като сравнително слаба, тук приносът за (био)химията е пряк и определено може да се определи като революционен.

Ако ДНК са инструкциите как може да се построи един жив организъм, то протеините са тухлите, строителната техника, работниците… на практика всичко необходимо за строежа. Учудващото е, че тази критична роля се крепи на едва двайсетина основни елемента, от които са изградени самите те. По шаблона на иРНК в процеса на транслация аминокиселините се подреждат в нишка една след друга – това е тяхната първична структура. В зависимост от последователността, в която са подредени, нишката се нагъва в няколко характерни форми – най-често срещаните са алфа-спирала и бета-лист. Чрез взаимодействия между тези структури протеинът се „нагъва“ триизмерно (възможно е далечни части от веригата да се окажат една до друга), оформяйки своята третична структура, в която може да има активни центрове, участъци за свързване с молекули и други функционални модули.

В началото на 60-те години на миналия век Кристиан Анфинсен открива, че образуването на третичната структура е обратим процес – протеините могат да се „разгъват“, но след това успешно връщат функционалната си форма. Това откритие подсказва на учените, че най-вероятно третичната структура зависи от първичната, и за него Анфинсен е награден с „Нобел“ за химия през 1972 г.

По това време вече е била известна структурата на някои протеини благодарение на приложението на една технология от началото на миналия век – рентгеновата кристалография. При нея кристал от изучаваното вещество се облъчва с рентгенови лъчи и се наблюдава как се променя дифракцията им в зависимост от атомите и химичните връзки между тях в кристала. Това е основа за предходна Нобелова награда за химия – на Джон Кендрю и Макс Перуц през 1962 г. С напредването на технологиите към набора с инструменти се добавят ЯМР спектроскопия и криогенна електронна микроскопия.

Тъй като триизмерната структура на протеините е ключова за тяхната функция, откриването ѝ е много важно, но и изключително трудно дори и с новите технологии. Представете си какво въображение (и познания) трябва да имате, за да познаете спиралната структура на ДНК от популярната Снимка 51 на Розалинд Франклин! Няколко десетилетия по-късно на помощ идва компютър с абстрактно мислене.

Демис Хасабис е един от основателите на DeepMind – компания, поставила си за цел да обучава изкуствен интелект, като му дава да играе стари видеоигри, но с уловката, че не му обясняват правилата. Скоро след придобиването на компанията от Google е създаден AlphaGo Zero – програмата, победила шампион по играта го, което е считано за много високо постижение. След тази победа екипът насочва вниманието си към проблема с разпознаването на триизмерните структури на протеините. В този проект се включва и Джон Джъмпър.

С един от първите си опити софтуерът на учените, наречен AlphaFold, успява да подобри разпознаването на третичните структури от 40% при наличните алгоритми до 60% – впечатляващ успех. За втората версия на програмата екипът подава на изкуствения интелект всички известни към момента структури и техните секвенции. Това допълнително разширява нейните способности, давайки резултат с качество, близко до рентгеновата кристалография. С тази разлика, че експерименти, които са отнемали години, вече се провеждат за минути. Почти като на игра.

Общо с игрите има и другият лауреат – Дейвид Бейкър. Заинтригуван от процеса на оформяне на третичната структура на протеините, Бейкър заедно с екипа си създава софтуер за тяхното предсказване много преди AlphaFold. Любопитното е, че софтуерът Rosetta@home работи дистрибутирано – всеки може да инсталира малко приложение на компютъра си, което в свободното време, когато процесорът не е зает с важни неща, да обработва известно количество входни данни. След като направи изчисленията, то връща резултата до централен сървър, който обобщава данните. Този софтуер беше използван и за разработката на ваксина против SARS-CoV-2 с наночастици, която все още не е достъпна, но клиничните изследвания са изключително обещаващи.

Въпреки успеха на Rosetta@home учените стигат до интересно откритие – геймърите са по-добри в намирането на закономерности и създаване на триизмерни структури. Това води до създаването на играта Foldit, за която е публикувана статия в журнала Nature. Играта постига успехи, но както при шаха и го, в крайна сметка AlphaFold надвива човешките играчи.

На Бейкър обаче му хрумва и друга идея – да обърне работата на програмата и вместо да ѝ даде секвенция, чиято структура да бъде определена, да ѝ посочи желаната триизмерна форма и да получи нужната последователност от аминокиселини. Създаването на протеини de novo е от голям интерес за учените, но до този момент е много сложно и в повечето случаи се правят промени във вече съществуващи структури, за да им се придадат малко по-различни свойства.

Така двама учени от групата на Бейкър създават нов за природата протеин – Top7 – с дотогава нечуваната за de novo синтезиран протеин дължина от 93 аминокиселини. Секвенцията му е „преведена“ в ДНК и вмъкната в бактерия, която произвежда новия протеин, а кристалографски анализ показва, че структурата му е почти неразличима от предсказаната. Това е огромен напредък, който веднага дава отзвук в биохимичните среди. Възможността за създаване на протеини с нови функции, които не са производни на еволюцията и природните процеси, има потенциала да доведе до драстични промени в най-различни аспекти на живота ни – медицина, химичен синтез, хранителна химия, нови материали. Някои може да се използват за създаване на бактерии, които се хранят с пластмаса или с петролни остатъци, други – като своеобразни ваксини, които обвиват вирусните частици и не им позволяват да се намножават. Един от протеините, разработени от групата на Бейкър, действа по сходен начин, свързвайки се с молекулата на фентанила – един от много опасните съвременни опиоиди, което позволява създаването на бързи тестове за веществото.

Ако се върнем към това, че на практика целият живот на планетата е изграден и движен от протеини, става ясно какви промени могат да предизвикат откритията на тези трима учени и екипите им. Въпреки че в повечето медии наградите бяха поставени донякъде под сянката на изкуствения интелект, може да се приеме, че годината е особено силна за биохимията и молекулярната биология. Разработките в двете полета освен фундаментално значение имат и голям приложен потенциал, което прави преценката на Нобеловия комитет напълно валидна.

Докога с титаните Борисов и Пеевски?

Post Syndicated from Емилия Милчева original https://www.toest.bg/dokoga-s-titanite-borisov-i-peevski/

Докога с титаните Борисов и Пеевски?

Толкова нови играчи напъплиха българската политика в последните години, но никой не успя да измести нейните двама титани – Бойко Борисов и Делян Пеевски. Въпреки опитите за реформи старата политическа култура и лобистките мрежи, които те управляват, не само показаха устойчивост на новите влияния, но и оказаха (и оказват) съпротива. Така политическият ландшафт не се промени особено – новото поколение лидери преживя неуспехи, подсилени от саботажите на старото. Тези процеси поставят под съмнение капацитета на демокрациите да обновяват своите елити не само поради незрялост, но и поради закърняване на вътрешнопартийната демокрация и заради омерзението на гражданите от политическото безсилие.

Докато олигархът Пеевски беше в сянка, доминацията на лидера на ГЕРБ Борисов беше безспорна. Негови бяха микрофоните, първите новини в емисиите, първите страници на вестниците, изобщо публичното говорене, издържано в аз-форма. Но управлението, известно като сглобка, извади през лятото на 2023 г. Пеевски под светлините на прожекторите независимо от санкциите му за корупция от САЩ и Великобритания. От ПП–ДБ ги забравиха за деветте месеца, през които лидерите на ГЕРБ–СДС, ПП–ДБ и ДПС се събираха, сговаряха и сглобяваха за едно или друго.

Възходът на Пеевски отслаби доминиращата роля на Борисов, а разцепването на ДПС отслабва Пеевски. Но все така продължава зависимостта на българската политическа система от фигури, които остават на власт твърде дълго. 

Една друга фигура – на президента Румен Радев, черпи сили от тяхното отслабване. Недостатъчни, за да наложи президентска форма на управление, но ще стигнат, за да избута една нова партия на сцената сред отломките на БСП и ДПС. А това би означавало още един титан, който ще се бори да съсредоточи в ръцете си повече контрол и по-голяма власт от тази, с която се е сдобил като президент. Макар като такъв да разполага с квоти за назначения в Конституционния съд, Съвета за електронни медии, Българската народна банка, а също и с издаването на указите за назначения на посланици, висши военни, тримата големи в съдебната власт…

Време е този период от политическата история на България да приключи в полза на реалния парламентаризъм.

Битката на силоваците

Борисов беше неоспоримият силовак на българската политическа сцена, който доминираше над всички останали повече от десетилетие с комбинацията си от харизма, популизъм и твърд контрол върху структурите на ГЕРБ. Той успешно балансираше между различни лобита, понякога разграничавайки се от доскорошни съюзници, за да запази контрол над политическия процес.

През 2023 г. символът на задкулисието се превърна в българското политическо динамо. След санкциите по „Магнитски“ изглеждаше, че Пеевски е отслабен, но вместо това се върна по-силен, като ключов играч, включително в преговори по различни теми между ПП–ДБ и ГЕРБ, а влиянието му в прокуратурата, службите и МВР остана непокътнато. Като че ли се налагаше нов политически ред, в който на Борисов бе отредена второстепенна роля.

Но ето че сглобката се разпадна. При повторното завъртане на рулетката с мандатите Борисов и ГЕРБ успешно избегнаха опцията да управляват с ДПС на Пеевски – не без помощта на ДПС на Доган. И на възхода на Пеевски беше сложен край. Или по-скоро началото на края. 

Мястото на ДПС – Ново начало и на олигарха в един бъдещ парламент и управление ще определи и неговата тежест и дали ще бъде ограничено влиянието му в съдебната система и в други контролирани от модела „Пеевски“ институции. Дали Бойко Борисов няма да се възползва от тази слабост, за да укрепи своите позиции? Зависи от броя на депутатските мандати, които ще получи, и от търсенето на съуправленци на тази база. Но отслабването на единия ключов играч не прелива мощ на другия. Средата е променена, балансът – все по-труден, тъй като мнозинствата, необходими да крепят едно управление, се увеличават. Следователно ресурсите за разпределение се смаляват. 

Без конкуренция няма демокрация

Дълготрайното господстващо положение на определени фигури обаче уврежда сериозно демокрацията и политическата култура в България. Затормозяването и възпирането с всички средства на конкуренцията не работи както за свободния пазар, така и в политиката. Резултатът е уродливостта на една контролирана демокрация, така често срещана в посткомунистическия свят. 

Какво прави формалната конкуренция? Същото, което прави „Лукойл“ на пазара на горива на едро. Въпреки наличието на многопартийна система важните решения и насоки се определят от доминиращи партии или от лидери, които контролират политическия процес. Контролираните демокрации също така ограничават действията на неправителствените организации и медиите, които не се подчиняват на статуквото. Така гражданското участие бива игнорирано или омаловажено, както и контролът над властта. 

Признак за контролирана демокрация е и незачитането на човешките права и свободи. България има своята срамна история – опитите за асимилация на българските мюсюлмани чрез насилствена смяна на имената и забрана на културните им и религиозни практики. В по-ново време това е продължаващата гетовизация на ромите. 

Фактът, че 50-тият парламент позволи одобрението на безсмислена, мракобесна поправка в закона, забраняваща пропаганда на „нетрадиционна сексуална ориентация“ в училищата, е доказателство за липсата на здрави съпротивителни сили срещу хомофобията и дискриминацията, досущ като в Русия. Освен че подкопават основите на демокрацията, промените в Закона за предучилищното и училищното образование са сигнал, че различията се осъждат, вместо да се приемат и уважават. 

Изборите на 27 октомври са първите в най-новата история на България, на които партията, произвела Пеевски, ще се яви разцепена. Това означава, че ДПС ще бъде значително затруднено да прокарва влиянието си. Затруднена ще е и тази част от Движението, която Пеевски държи (освен ако не бъде отворена машината за компромати). С отслабването на партията, свързвана с политически клиентелизъм и използване на етническо разделение, се отваря опция за обновление, което да намали зависимостта на политическата система от олигархични кръгове и задкулисни договорки.

Но без установяване на здравословен парламентаризъм българската политика ще продължи да произвежда „титани“, чиято единствена цел е да я монополизират за употреба от „обръчите“ и за лична изгода.

Automate AWS End User Messaging US toll-free Number Registrations

Post Syndicated from Bruno Giorgini original https://aws.amazon.com/blogs/messaging-and-targeting/automate-us-tfn-registrations/

Introduction:

AWS End User Messaging enables customers to send SMS messages to recipients located across the globe.
If you are planning on rolling out SMS across multiple countries, we recommend reviewing this blog. When you send SMS or MMS messages using AWS End User Messaging SMS, you must use a specific origination identity that supports the sending of SMS. In the US the originators that are supported are Toll-Free(TFN), 10DLC, and short codes and each of these has its own registration process.

This blog discusses the process of programmatically registering Toll-Free numbers (TFNs), which can be used exclusively within the United States. TFNs have a max throughput of 3 Messages Per Second(MPS) and are typically used for low-volume/throughput use cases. You can learn more about TFNs here.

TFNs have a relatively simple registration process, however, for Independent Software Vendors (ISVs), SaaS providers, or large organizations with many teams or use cases, completing dozens, or hundreds of TFN registrations manually can be time-consuming, tedious, and error-prone. AWS End User Messaging APIs can be used to streamline the TFN registration process by enabling AWS customers to programmatically register TFNs in the USA. You can learn more about the TFN registration requirements and process here.

In this post, we will discuss the AWS End User Messaging APIs required for programmatically registering TFNs. We’ll explore a simple Bash script you can use to automate the registration of a single TFN, as well as a Python script that you can use to bulk register multiple TFNs. Both of these scripts help simplify the TFN registration process and can save both time and effort for businesses looking to leverage AWS End User Messaging for their communication needs.

Outline of the APIs used in the scripts:

There are seven actions that need to be taken in order for a TFN registration to be created and submitted. The two scripts in this post automate these actions:

  1. create-registration
    • Creates a new registration
    • The “RegistrationType” field controls whether this is a registration for a Toll-Free, or 10DLC or a SenderID.
  2. describe-registration-field-definitions
    • Retrieves the specified RegistrationType field definitions.
    • You can use DescribeRegistrationFieldDefinitions to view the requirements for creating, filling out, and submitting each registration type. In this post we have chosen Toll-Free and provided the values.
  3. create-registration-attachment
    • The carriers require you to provide a mockup that closely resemble the opt-in experience that your customers will complete to ensure end-users have consented to receiving SMS messages from this toll-free number. This should be a screenshot of your website or mobile application’s opt-in workflow.
    • The maximum file size is 500kb, and valid file extensions are PDF, JPEG, or PNG.
    • You need to wait until the attachment is uploaded before moving to step 4.
  4. put-registration-field-value
    • This action needs to be repeated for all required fields (retrieved in step 2)
  5. request-phone-number
    • Request an origination phone number for use in your account (needed for step 6)
  6. create-registration-association
    • This associates the registration with the origination identity (phone number) you requested in step 5.
    • You will need the PhoneNumberId for the origination identity.
  7. submit-registration-version
    1. This will submit the specified registration for review and approval
    2. IMPORTANT:
      • Make sure that all of your data is correct, especially before attempting to submit multiple registrations using the second script option below.
      • Once your script has submitted the registration, it’s initial status will be “CREATED” and should change to “REVIEWING” within 24 hours.
      • Once submitted, you will be unable to edit or delete this registration until it is approved or rejected by the third-party registrar that controls the registration process for the type of registration you are submitting (in this blog we’re registering TFNs).
      • You begin incurring costs for the TFNs as soon as you successfully submit the registration.

No matter which script you decide to use, it’s important to keep a these things in mind:

  1. The registration information you provide will be reviewed by a third-party company. This is standard, no matter which provider you use for SMS
  2. While AWS submits the registration on your behalf, we do not participate in the actual review process, nor can we influence the third-party.
  3. The review process for TFNs can take up to 15 business days and if the information provided in the registration process is incomplete, inaccurate, or the use case falls into a forbidden category (Guidelines for using toll-free numbers) , the application can be rejected.
  4. If your toll-free number registration is rejected, the status of your registration will change to “Requires Updates“. We recommend monitoring your registration status frequently to ensure that you do not miss an update and extend the time it takes to complete.

Prerequisites for either approach:

Before running either script, you’ll need:

  1. An AWS account with permission to use/provision the AWS End User Messaging service (link) in the target region.

The following information for each TFN you wish to register/request (you can retrieve this list with describe-registration-field-definitions API):

Company Info
  • Company Name
  • Website
  • Address 1
  • Address 2 (optional)
  • City
  • State / Province
  • Zip Code / Postal Code
  • Country Code
Contact Info
  • First Name
  • Last Name
  • Support Email
  • Support Phone Number
Messaging Use Case
  • Monthly Message Volume (you must use one of the options below)
    • “10”
    • “100”
    • “1,000”
    • “10,000”
    • “100,000”
    • “250,000”
    • “500,000”
    • “750,000”
    • “1,000,000”
    • “5,000,000”
    • “10,000,000+”
  • Use Case Category (you must use one of the options below)
    • “Two-factor authentication”
    • “One-time passcodes”
    • “Notifications”
    • “Polling and surveys”
    • “Info on demand”
    • “Promotions & marketing”
    • “Other”
  • Use Case Details
  • Opt-In Description – The primary purpose of the Opt-in Description is to demonstrate that the end user explicitly consents to receive text messages and understands the nature of the program. Your application is being reviewed by a 3rd party reviewer, so make sure to provide clear and thorough information about how your end-users opt-in to your SMS service and any associated fees or charges. If the reviewer cannot determine how your opt-in process works then your application will be denied and returned. If your Opt-in process requires a log-in, is not yet published publicly, is a verbal opt-in, or if it occurs on printed sources such as fliers and paper forms then make sure to thoroughly document how this process is completed by the end-user receiving messages. Provide a screenshot and host the screenshot on a publicly accessible website (like OneDrive or Google Drive) and provide the URL in the text as well as in the Opt-In Image below.
  • Opt-In Image – This is optional, but highly recommended, even if you provide a description above:
    • If your experience is not publicly available, the carriers will require you to provide one to ensure end-users have consented to receiving SMS messages from this toll-free number.
    • You are encouraged to provide a screenshot (PDF, JPEG, or PNG) of your website or mobile application’s opt-in workflow. This could also be a screenshot of a paper form, a verbal opt-in script, or an as yet published website experience in development.
    • The maximum file size is 500Kb.
Message Samples
  • Message Sample 1
  • Message Sample 2 (optional)
  • Message Sample 3 (optional)

Option 1 – Execute a script to register a single TFN

The script requires the additional prerequisites (if you use AWS CloudShell to run the script, the AWS CLI and jq are already installed).

  • AWS CLI installed and configured with appropriate AWS account credentials and region (link)
  • jq (a lightweight and flexible command-line JSON processor) installed (link)
  1. Set environment variables for each of the required fields.

Before running the registration script, you must first set the necessary variables, replacing the placeholder values with your company actual data (these values are listed as a prerequisite above). Ensure that the opt-in screenshot image file optInImage.png is in the same directory as the script, or provide the correct path to the image file in the attachment_body variable. Note – the allowed file types for the opt-in screenshot are PNG, JPG, and PDF with a max file size of 500 kb.

Run the environment variable exports:

export AWS_REGION="us-west-2"
export COMPANY_NAME="Your Company Name"
export COMPANY_WEBSITE="www.yourcompany.com"
export COMPANY_ADDRESS1="123 Main Street"
export COMPANY_ADDRESS2="Suite 200"
export COMPANY_CITY="Your City"
export COMPANY_STATE="Your State"
export COMPANY_ZIPCODE="12345"
export COMPANY_COUNTRY_CODE="US"
export CONTACT_FIRSTNAME="John"
export CONTACT_LASTNAME="Doe"
export CONTACT_EMAIL="[email protected]"
export CONTACT_PHONE="+1234567890"
export USECASE_DETAILS="Details about your use case"
export OPTIN_DESCRIPTION="Description of opt-in process"
export MONTHLY_MESSAGE_VOLUME="10"
export USECASE_CATEGORY="Other"
export MESSAGE_SAMPLE1="Sample message"
export ATTACHMENT_BODY="fileb://optInImage.png"
  1. Copy and save the below script as register_us_toll_free_number.sh into your current directory. Adjust the region variable in the script to the one you’re using to register the US TFN.
#!/bin/bash
set -euo pipefail

# Check dependencies
command -v aws >/dev/null 2>&1 || { echo "AWS CLI is required but it's not installed. Aborting."; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq is required but it's not installed. Aborting."; exit 1; }

# Initialize variables from environment or use default values
region="${AWS_REGION:-'us-west-2'}"
companyInfo_companyName="${COMPANY_NAME:-"Default Company Name"}"
companyInfo_website="${COMPANY_WEBSITE:-"https://defaultcompany.com"}"
companyInfo_address1="${COMPANY_ADDRESS1:-"123 Default St."}"
companyInfo_address2="${COMPANY_ADDRESS2:-""}"  # Optional
companyInfo_city="${COMPANY_CITY:-"Default City"}"
companyInfo_state="${COMPANY_STATE:-"Default State"}"
companyInfo_zipCode="${COMPANY_ZIPCODE:-"00000"}"
companyInfo_isoCountryCode="${COMPANY_COUNTRY_CODE:-"US"}"
contactInfo_firstName="${CONTACT_FIRSTNAME:-"John"}"
contactInfo_lastName="${CONTACT_LASTNAME:-"Doe"}"
contactInfo_supportEmail="${CONTACT_EMAIL:-"[email protected]"}"
contactInfo_supportPhoneNumber="${CONTACT_PHONE:-"+10000000000"}"
messagingUseCase_useCaseDetails="${USECASE_DETAILS:-"Default use case details"}"
messagingUseCase_optInDescription="${OPTIN_DESCRIPTION:-"Default opt-in process description"}"
messagingUseCase_monthlyMessageVolume="${MONTHLY_MESSAGE_VOLUME:-"10"}"
messagingUseCase_useCaseCategory="${USECASE_CATEGORY:-"Other"}"
messageSamples_messageSample1="${MESSAGE_SAMPLE1:-"This is a sample message."}"
attachment_body="${ATTACHMENT_BODY:-"fileb://optInImage.png"}"  # Path to the image, can be overridden

# Log to file
log_file="registration.log"
echo "Logging to $log_file"
exec > >(tee -a "$log_file") 2>&1

# Retry configuration
max_retries=10
retry_interval=2
retry_count=0
upload_complete=false

# Helper function to put registration field values
put_registration_field_value() {
    local field_path="$1"
    local value="$2"
    aws pinpoint-sms-voice-v2 --region "$region" put-registration-field-value \
         --registration-id "$registration_id" \
         --field-path "$field_path" \
         --text-value "$value" || { echo "Failed to update $field_path"; exit 1; }
}

# Helper function to validate registration field values
validate_input() {
    local required_vars=(
        "AWS_REGION"
        "COMPANY_NAME"
        "COMPANY_WEBSITE"
        "COMPANY_ADDRESS1"
        "COMPANY_CITY"
        "COMPANY_STATE"
        "COMPANY_ZIPCODE"
        "COMPANY_COUNTRY_CODE"
        "CONTACT_FIRSTNAME"
        "CONTACT_LASTNAME"
        "CONTACT_EMAIL"
        "CONTACT_PHONE"
        "USECASE_DETAILS"
        "OPTIN_DESCRIPTION"
        "MONTHLY_MESSAGE_VOLUME"
        "USECASE_CATEGORY"
        "MESSAGE_SAMPLE1"
        "ATTACHMENT_BODY"
    )

    for var in "${required_vars[@]}"; do
        if [ -z "${!var}" ]; then
            echo "Error: $var is missing or empty" >&2
            return 1
        fi
    done

    # Validate zip code
    if [[ ! "$COMPANY_ZIPCODE" =~ ^[0-9]+$ ]]; then
        echo "Error: Invalid or missing zip code" >&2
        return 1
    fi

    # Validate monthly message volume
    local valid_volumes=("10" "100" "1,000" "10,000" "100,000" "250,000" "500,000" "750,000" "1,000,000" "5,000,000" "10,000,000+")
    local volume_valid=false
    for volume in "${valid_volumes[@]}"; do
        if [ "$MONTHLY_MESSAGE_VOLUME" = "$volume" ]; then
            volume_valid=true
            break
        fi
    done
    if [ "$volume_valid" = false ]; then
        echo "Error: Invalid or missing monthly_message_volume" >&2
        return 1
    fi

    # Validate use case category
    local valid_categories=("Two-factor authentication" "One-time passcodes" "Notifications" "Polling and surveys" "Info on demand" "Promotions & marketing" "Other")
    local category_valid=false
    for category in "${valid_categories[@]}"; do
        if [ "$USECASE_CATEGORY" = "$category" ]; then
            category_valid=true
            break
        fi
    done
    if [ "$category_valid" = false ]; then
        echo "Error: Invalid or missing use_case_category" >&2
        return 1
    fi

    # Additional validations (you can add more as needed)
    if [[ ! "$COMPANY_WEBSITE" =~ ^https?:// ]]; then
        echo "Error: COMPANY_WEBSITE must start with http:// or https://" >&2
        return 1
    fi
    
    if [[ ! "$CONTACT_EMAIL" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
        echo "Error: CONTACT_EMAIL is not a valid email address" >&2
        return 1
    fi
    
    if [[ ! "$CONTACT_PHONE" =~ ^\+[1-9][0-9]{10,14}$ ]]; then
        echo "Error: CONTACT_PHONE must be in E.164 format (e.g., +10000000000)" >&2
        return 1
    fi
    
    echo "All required variables are set and valid"
    return 0
}


# Step 1: Create registration
echo "Creating registration..."
create_registration_output=$(aws pinpoint-sms-voice-v2 --region "$region" create-registration \
      --registration-type 'US_TOLL_FREE_REGISTRATION' \
      --tags Key=Name,Value='Registration friendly name') || { echo "Failed to create registration"; exit 1; }

# Extract RegistrationId
registration_id=$(echo "$create_registration_output" | jq -r '.RegistrationId')
if [ -z "$registration_id" ]; then
    echo "Error: Registration ID not found!"
    exit 1
fi
echo "Registration ID: $registration_id"

# Step 2: Create registration attachment
echo "Creating registration attachment..."
create_attachment_output=$(aws pinpoint-sms-voice-v2 --region "$region" create-registration-attachment \
      --attachment-body "$attachment_body") || { echo "Failed to create registration attachment"; exit 1; }

# Extract RegistrationAttachmentId
attachment_id=$(echo "$create_attachment_output" | jq -r '.RegistrationAttachmentId')
if [ -z "$attachment_id" ]; then
    echo "Error: Attachment ID not found!"
    exit 1
fi
echo "Attachment ID: $attachment_id"

# Step 3: Wait for the attachment to be fully uploaded
echo "Waiting for attachment upload to complete..."
while [ "$upload_complete" = false ] && [ $retry_count -lt $max_retries ]; do
    # Describe the registration attachment
    describe_attachment_output=$(aws pinpoint-sms-voice-v2 --region "$region" describe-registration-attachments \
        --registration-attachment-ids "$attachment_id")
    
    # Extract the attachment status
    attachment_status=$(echo "$describe_attachment_output" | jq -r '.RegistrationAttachments[0].AttachmentStatus')

    # Check if the status is 'UPLOAD_COMPLETE'
    if [ "$attachment_status" == "UPLOAD_COMPLETE" ]; then
        echo "Attachment upload complete."
        upload_complete=true
    else
        echo "Attachment status: $attachment_status. Retrying in $retry_interval seconds... (attempt $((retry_count + 1))/$max_retries)"
        sleep "$retry_interval"
        retry_count=$((retry_count + 1))
    fi
done
if [ "$upload_complete" = false ]; then
    echo "Attachment upload did not complete within the retry limit."
    exit 1
fi
echo "Attachment upload complete."

# Step 4a: Put registration field values from environment variables
text_field_paths=(
    "companyInfo_companyName"
    "companyInfo_website"
    "companyInfo_address1"
    "companyInfo_address2"
    "companyInfo_city"
    "companyInfo_state"
    "companyInfo_zipCode"
    "companyInfo_isoCountryCode"
    "contactInfo_firstName"
    "contactInfo_lastName"
    "contactInfo_supportEmail"
    "contactInfo_supportPhoneNumber"
    "messagingUseCase_useCaseDetails"
    "messagingUseCase_optInDescription"
    "messageSamples_messageSample1"
)

for text_field_path in "${text_field_paths[@]}"; do
    echo "Putting registration field value for: $text_field_path"
    value=$(eval "echo \$$text_field_path")
    if [ -z "$value" ]; then
        echo "Error: $text_field_path is empty or not set. Skipping."
        continue
    fi
    echo "Value for $text_field_path is: '$value'"
    put_registration_field_value "${text_field_path//_/.}" "$value"
done

# Step 4b: Put other registration field values (Choice fields)
choice_field_paths=(
    "messagingUseCase_monthlyMessageVolume"
    "messagingUseCase_useCaseCategory"
)

for choice_field_path in "${choice_field_paths[@]}"; do
    echo "Putting registration field value for: $choice_field_path"
    value=$(eval "echo \$$choice_field_path")
    if [ -z "$value" ]; then
        echo "Error: $choice_field_path is empty or not set. Skipping."
        continue
    fi
    echo "Value for $choice_field_path is: '$value'"
    aws pinpoint-sms-voice-v2 --region "$region" put-registration-field-value \
        --registration-id "$registration_id" \
        --field-path "${choice_field_path//_/.}" \
        --select-choices "$value" || { echo "Failed to update $choice_field_path"; exit 1; }
done

# Step 5: Associate registration attachment with registration
echo "Associating registration attachment with registration..."
aws pinpoint-sms-voice-v2 --region "$region" put-registration-field-value \
      --registration-id "$registration_id" \
      --field-path 'messagingUseCase.optInImage' \
      --registration-attachment-id "$attachment_id" || { echo "Failed to associate registration attachment"; exit 1; }

# Step 6: Request phone number
echo "Requesting phone number..."
request_phone_number_output=$(aws pinpoint-sms-voice-v2 --region "$region" request-phone-number \
      --iso-country-code 'US' \
      --number-type 'TOLL_FREE' \
      --number-capabilities 'SMS' 'MMS' 'VOICE' \
      --message-type 'TRANSACTIONAL') || { echo "Failed to request phone number"; exit 1; }

# Extract PhoneNumberId
phone_number_id=$(echo "$request_phone_number_output" | jq -r '.PhoneNumberId')
if [ -z "$phone_number_id" ]; then
    echo "Error: Phone number ID not found!"
    exit 1
fi
echo "Phone Number ID: $phone_number_id"

# Step 7: Associate phone number with registration
echo "Associating phone number with registration..."
aws pinpoint-sms-voice-v2 --region "$region" create-registration-association \
      --registration-id "$registration_id" \
      --resource-id "$phone_number_id" || { echo "Failed to associate phone number with registration"; exit 1; }

# Step 8: Submit registration
echo "Submitting registration..."
aws pinpoint-sms-voice-v2 --region "$region" submit-registration-version \
     --registration-id "$registration_id" || { echo "Failed to submit registration"; exit 1; }

echo "Registration submitted successfully!"
  1. Run chmod command to make it executable. Run the script with the environment variable values you provided in Step 1 above.

chmod u+x register_us_toll_free_number.sh
./register_us_toll_free_number.sh
  1. The script completes with the following lines:

Submitting registration...
{
    "RegistrationArn": "arn:aws:sms-voice:us-west-2:637400000000:registration/registration-244aa3f91fcc49b598bdf1234569",
    "RegistrationId": "registration-244aa3f91fcc49b598bdf1234569",
    "VersionNumber": 1,
    "RegistrationVersionStatus": "SUBMITTED",
    "RegistrationVersionStatusHistory": {
        "DraftTimestamp": "2024-09-11T19:44:41+00:00",
        "SubmittedTimestamp": "2024-09-11T19:45:16+00:00"
    }
}
Registration submitted successfully!

Option 2 – Execute a Python script to register more than one Toll-Free number

For ISVs, SaaS providers, or large organizations registering multiple phone numbers on behalf of customers or business units, automating the process can save time and reduce errors. We’ve chosen to use Python because it’s CSV library handles file parsing complexities, and its boto3 library enables seamless interaction with AWS services, making it well-suited for programmatically managing these registrations.

  1. Below is a sample CSV file with the variables for 5 registrations, copy it and replace the sample data with your actual data (these data were listed in the prerequisites above). Save your file as data.csv:
companyInfo_companyName,companyInfo_website,companyInfo_address1,companyInfo_address2,companyInfo_city,companyInfo_state,companyInfo_zipCode,companyInfo_isoCountryCode,contactInfo_firstName,contactInfo_lastName,contactInfo_supportEmail,contactInfo_supportPhoneNumber,messagingUseCase_monthlyMessageVolume,messagingUseCase_useCaseCategory,messagingUseCase_useCaseDetails,messagingUseCase_optInDescription,messageSamples_messageSample1,attachmentFilePath
AnyCompany,https://example.com/example1,123 Any Street,Suite 200,Anytown,WA,98109,US,FirstName,LastName,[email protected],15553331234,10,One-time passcodes,Dev/Demo - Internal testing only,Internal testing only,Your AWS End User Messaging internal testing one time passcode is 123456,./companyA.png
Example Corp,https://example.net/example2,123 Main Street,,Anywhere,WA,98765,US,FirstName2,LastName2,[email protected],15553332222,10,Notifications,Dev/Demo - Internal testing only,Internal testing only,Your AWS End User Messaging internal testing one time passcode is 654321,./companyB.png
AnyDepartment,https://example.org/example3,123 Oak Avenue,Apt B,Nowhere,WA,54321,US,FirstName3,LastName3,[email protected],15553333333,10,Two-factor authentication,Dev/Demo - Internal testing only,Internal testing only,Your AWS End User Messaging internal testing one time passcode is 987654,./companyC.png
AnyOrganization,https://example.com/example4,123 Pine Blvd,,Anywhere Else,WA,12345,US,FirstName4,LastName4,[email protected],15553334444,100,One-time passcodes,Dev/Demo - Internal testing only,Internal testing only,Your AWS End User Messaging internal testing one time passcode is 654789,./companyD.png
AnyGovernment,https://example.org/example5,123 Oak St,,Nowhere Town,WA,67890,US,FirstName5,LastName5,[email protected],15553335555,"100",One-time passcodes,Dev/Demo - Internal testing only,Internal testing only,Your AWS End User Messaging internal testing one time passcode is 987654,./companyE.png
  1. Prepare opt-in screenshot image files for each registration, and upload them in the same directory as you will use for the data.csv and script files. Note: the allowed file types for the opt-in screenshot are PNG, JPG, and PDF with a max file size of 500 kb.
  2. Below is a Python script to create registrations using the data.csv file (above). Save this file as register_phone_numbers_bulk.py into your current directory.
import csv
import boto3
import sys
import argparse
import time

# Parse command line arguments
parser = argparse.ArgumentParser(description="AWS End User Messaging SMS Registration Script")
parser.add_argument("-r", "--region", default="us-west-2", help="AWS region")
parser.add_argument("-c", "--csv_file", default="data.csv", help="Path to the Comma-Separated Values file")
args = parser.parse_args()

# Initialize AWS End User Messaging SMS client
client = boto3.client('pinpoint-sms-voice-v2', region_name=args.region)

def process_csv(csv_file):
    with open(csv_file, newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        
        # Strip BOM from the first key (header) if it exists
        if '\ufeff' in reader.fieldnames[0]:
            reader.fieldnames[0] = reader.fieldnames[0].replace('\ufeff', '')
        
        for row in reader:
            process_row(row)

def process_row(row):
    print(f"================================================================================================")
    
    if 'companyInfo_companyName' not in row:
        print(f"Error: 'companyInfo_companyName' field is missing in the CSV file.")
        return
    
    print(f"Processing entry for: {row['companyInfo_companyName']}")
    print(f"================================================================================================")

    # Validate required fields
    required_fields = [
        'companyInfo_companyName', 'companyInfo_website', 'companyInfo_isoCountryCode', 
        'attachmentFilePath'
    ]
    for field in required_fields:
        if field not in row or not row[field]:
            print(f"Error: Required field '{field}' is missing or empty for entry: {row.get('companyInfo_companyName', 'Unknown Company')}")
            return

    # Validate field values
    if 'companyInfo_zipCode' not in row or not row['companyInfo_zipCode'].isdigit():
        print(f"Error: Invalid or missing zip code for entry: {row['companyInfo_companyName']}")
        return

    valid_volumes = ["10", "100", "1,000", "10,000", "100,000", "250,000", "500,000", "750,000", "1,000,000", "5,000,000", "10,000,000+"]
    if 'messagingUseCase_monthlyMessageVolume' not in row or row['messagingUseCase_monthlyMessageVolume'] not in valid_volumes:
        print(f"Error: Invalid or missing monthly_message_volume for entry: {row['companyInfo_companyName']}")
        return

    valid_categories = ["Two-factor authentication", "One-time passcodes", "Notifications", "Polling and surveys", "Info on demand", "Promotions & marketing", "Other"]
    if 'messagingUseCase_useCaseCategory' not in row or row['messagingUseCase_useCaseCategory'] not in valid_categories:
        print(f"Error: Invalid or missing use_case_category for entry: {row['companyInfo_companyName']}")
        return

    try:
        # Step 1: Create registration
        print("Creating registration...")
        create_registration_output = client.create_registration(
            RegistrationType='US_TOLL_FREE_REGISTRATION'
        )
        registration_id = create_registration_output['RegistrationId']

        # Step 2: Put registration field values from CSV
        print("Putting registration field values...")
        field_mappings = {
            "companyInfo.companyName": {"value": row['companyInfo_companyName'], "type": "text"},
            "companyInfo.website": {"value": row['companyInfo_website'], "type": "text"},
            "companyInfo.address1": {"value": row['companyInfo_address1'], "type": "text"},
            "companyInfo.address2": {"value": row['companyInfo_address2'], "type": "text"},            
            "companyInfo.city": {"value": row['companyInfo_city'], "type": "text"},
            "companyInfo.state": {"value": row['companyInfo_state'], "type": "text"},
            "companyInfo.zipCode": {"value": row['companyInfo_zipCode'], "type": "text"},
            "companyInfo.isoCountryCode": {"value": row['companyInfo_isoCountryCode'], "type": "text"},
            "contactInfo.firstName": {"value": row['contactInfo_firstName'], "type": "text"},
            "contactInfo.lastName": {"value": row['contactInfo_lastName'], "type": "text"},
            "contactInfo.supportEmail": {"value": row['contactInfo_supportEmail'], "type": "text"},
            "contactInfo.supportPhoneNumber": {"value": row['contactInfo_supportPhoneNumber'], "type": "text"},
            "messagingUseCase.useCaseDetails": {"value": row['messagingUseCase_useCaseDetails'], "type": "text"},
            "messagingUseCase.optInDescription": {"value": row['messagingUseCase_optInDescription'], "type": "text"},
            "messageSamples.messageSample1": {"value": row['messageSamples_messageSample1'], "type": "text"},
            "messagingUseCase.monthlyMessageVolume": {"value": row['messagingUseCase_monthlyMessageVolume'], "type": "select"},
            "messagingUseCase.useCaseCategory": {"value": row['messagingUseCase_useCaseCategory'], "type": "select"},
        }

        for field, field_data in field_mappings.items():
            if field_data['type'] == 'text' and field_data['value']:
                client.put_registration_field_value(
                    RegistrationId=registration_id,
                    FieldPath=field,
                    TextValue=field_data['value']
                )
            elif field_data['type'] == 'select' and field_data['value']:
                client.put_registration_field_value(
                    RegistrationId=registration_id,
                    FieldPath=field,
                    SelectChoices=[field_data['value']]
                )

        # Step 3: Create registration attachment
        print("Creating registration attachment...")
        with open(row['attachmentFilePath'], 'rb') as attachment_file:
            create_attachment_output = client.create_registration_attachment(
                AttachmentBody=attachment_file.read()
            )
            attachment_id = create_attachment_output['RegistrationAttachmentId']

        # Step 4: Wait for the attachment upload to finish
        print("Verifying attachment upload complete...")
        attachment_id = create_attachment_output['RegistrationAttachmentId']
        upload_complete = False
        max_retries = 10
        retry_count = 0

        while not upload_complete and retry_count < max_retries:
            try:
                describe_attachment_output = client.describe_registration_attachments(
                    RegistrationAttachmentIds=[attachment_id]
                )
                attachment_status = describe_attachment_output['RegistrationAttachments'][0]['AttachmentStatus']
                if attachment_status == 'UPLOAD_COMPLETE':
                    upload_complete = True
                else:
                    print(f"Attachment status: {attachment_status}. Waiting 2 seconds before retrying... (max {max_retries} retries)")
                    time.sleep(2)
                    retry_count += 1
            except Exception as e:
                print(f"Error occurred while checking attachment status: {str(e)}")
                time.sleep(10)
                retry_count += 1

        if not upload_complete:
            print(f"Error: Attachment upload did not complete for {row['companyInfo_companyName']}")
            return

        # Step 5: Associate registration attachment with registration
        print("Associating registration attachment with registration...")
        client.put_registration_field_value(
            RegistrationId=registration_id,
            FieldPath='messagingUseCase.optInImage',
            RegistrationAttachmentId=attachment_id
        )
        
        # Step 6: Request phone number
        print("Requesting phone number...")
        request_phone_number_output = client.request_phone_number(
            IsoCountryCode='US',
            NumberType='TOLL_FREE',
            NumberCapabilities=['SMS', 'MMS', 'VOICE'],
            MessageType='TRANSACTIONAL'
        )
        phone_number_id = request_phone_number_output['PhoneNumberId']

        # Step 7: Associate phone number with registration
        print("Associating phone number with registration...")
        client.create_registration_association(
            RegistrationId=registration_id,
            ResourceId=phone_number_id
        )
                
        # Step 8: Submit registration
        print("Submitting registration...")
        client.submit_registration_version(
            RegistrationId=registration_id
        )
        print(f"Processing completed for: {row['companyInfo_companyName']}\n")

    except Exception as e:
        print(f"Error occurred while processing {row['companyInfo_companyName']}: {str(e)}")

if __name__ == "__main__":
    process_csv(args.csv_file)
  1. Run the script: python register_phone_numbers_bulk.py -c data.csv -r us-west-2
    The 2 parameters are the name of the CSV file containing your data (shown here as data.csv) and specify the target AWS region (shown here as us-west-2) as parameters. Adjust these parameters as needed to match your environment and data location.

Check status:

Once you have successfully ran the script, you can check the status of your registration requests via AWS End User Messaging Console or with the API using the DescribeRegistrations API. If you want to use the console log in to the AWS End User Messaging Console in the target region and choose Configurations > Registrations from the left navigation. The registration status for each request will initially display “CREATED” and it will change to “REVIEWING” within 24 hours. As noted in the introduction, the actual registration review process is conducted by a third-party company and it can take up to 15 days to receive an acceptance (“COMPLETE”) or request for additional information or corrections (“Requires Update“) for each request.

Registration Status:

Registrations

Phone Number Status:

Phone Number status

Conclusion:

In this post you have learned how to automate the registration process for Toll-Free numbers with a Bash script or Python script and the AWS End User Messaging APIs. Using the API can significantly improve efficiency and reduce manual errors, but keep in mind that you will still need to wait up to 15 business days for the registrations to be approved (or not), and for the numbers to be set to “ACTIVE” status before you can begin sending messages with your TFN(s).

The AWS End User Messaging V2 API for SMS and Voice has other useful actions, and we encourage you to explore how it can further help you simplify and automate your applications.

Resources to help you plan for your SMS program:

Use this spreadsheet to plan for the countries you need to send SMS/MMS

To restrict your sending to only certain countries read this blog

Confirm the origination IDs you will need here

Check out the support tiers comparison

Ç като „калабалък“, ö като „остров“

Post Syndicated from original https://www.toest.bg/c-kato-kalabaluk-o-kato-ostrov/

Ç като „калабалък“, ö като „остров“

През изминалия месец и половина, откакто текат главозамайващите събития около разпада на ДПС и раздора между двамата му председатели, в главата ми непрестанно се върти – със същата настойчивост, като да беше песента Gimme! Gimme! Gimme! (A Man After Midnight) на ABBA – една от най-любимите ми шведски думи за всички времена.

И не, това не е думата lagom, която няма точен еквивалент на други езици и означава ‘достатъчно, точно колкото трябва, нито прекалено много, нито прекалено малко’; не е и livspussel, буквално „живот“ + „пъзел“, описваща баланса между работата и личния живот; нито пък е подвеждащият термин semester, който всъщност означава ‘ваканция’, или отдавна придобилият международно приложение ombudsman, понякога шеговито превеждан на български като „арменски поп“.

Въпросната шведска дума, която доста добре обобщава събитията около ДПС, всъщност е… kalabalik.

Когато миналата година я чух – субтитрирана като „хаос“ – от устата на участник в едно шведско телевизионно риалити, първоначално помислих, че халюцинирам. След няколко връщания и повторни слушания обаче се уверих, че думата наистина си е „калабалък“, макар и произнесена по необичаен за моето ухо, но типичен за шведския език напевен начин, който освен това е преобразувал ъ-то в ий.

Въпросното ъ в оригинал всъщност се означава с буквата ı, известна и като „i без точка“, характерна за турския език, откъдето, разбира се, идва и самата дума kalabalık. Там тя преминава от османския турски (قالابالق, kalabalık), като коренът ѝ може да бъде проследен до арабската дума غَلَبَة (ḡalaba), която означава ‘надмощие, преобладаване, триумф, победа’.

Освен в шведския, думата – с малки изменения в последната гласна – се среща както в българския, така и в останалите балкански езици, включително в македонския („калабалак“), сърбохърватския („калабалук“/kalabaluk), албанския (kallaballëk), румънския (calabalâc), гръцкия (καλαμπαλίκι) и даже в арменския (կալաբալըղ, kalabaləġ).

Но за разлика от обичайните исторически причини за преминаването на думата от турския в балканските езици и в арменския, поводът за ненадейното ѝ навлизане в шведския е доста по-вълнуващ, при все че той също е свързан с реално историческо събитие, или по-точно с едно също толкова ненадейно изгонване.¹

Въпросното събитие, известно на шведски под наименованието Kalabaliken i Bender (буквално „Калабалъкът в Бендер“), става на 1 февруари 1713 г. Целта му е отстраняването на шведския крал Карл XII от Османската империя, където той се установява през юли 1709 г., след съкрушителния разгром, нанесен му от руската армия в Битката при Полтава.

Настанявайки се край град Бендер (днешна Молдова), шведският крал създава нещо като двор в изгнание, „събирайки около себе си казашки ренегати, полски авантюристи, татари и остатъците от шведската армия, разбита при Полтава“, както цветущо е описано в посветена на Бендерския калабалък публикация в социалните мрежи. С течение на времето растящият антураж на краля налага изграждането на военен лагер във Варница, селище на няколко километра от Бендер, което става известно и като „новия Стокхолм“. Освен едноетажната сграда с дебели стени, където се помещава Карл XII, лагерът включва допълнителни постройки и казарми за кралските придворни и военни, наброяващи няколкостотин души.

По време на продължилия три години и половина престой Карл XII живее на издръжката на османската хазна, а многобройният му антураж натрупва сериозни заеми към местното население. След няколко любезни покани да напусне, които кралят отказва, като заедно с това не спира да кандърдисва султан Ахмед III да предприеме военни действия срещу Русия, множество еничари и тълпи от местни хора нападат лагера, където се помещават кралският двор.

Историческите източници се разминават относно числеността на участниците от двете страни на схватката: броят на османците варира между 8000 и 13 000, а на кралския антураж – между 700 и 1000. Но така или иначе, броят им несъмнено е достатъчен, за да създаде сериозна суматоха и събитието да заслужи наименованието си. Така нареченият калабалък продължава около седем часа, като накрая кралят е заловен и арестуван, а впоследствие получава прозвището Demirbaş Şarl, тоест Карл Желязната глава².

(Всякакви прилики със събитията около изгонването на почетния председател на ДПС от сараите в Росенец и „Бояна“, разбира се, са напълно случайни. А и както казва „великият комбинатор“ – и инцидентно, син на турски поданик, – чието фамилно име е същото като гореспоменатия град Бендер, „с парите човек трябва да се разделя леко, без стонове“.)

Така или иначе, експулсирането на краля от покрайнините на Бендер не слага край на неговото гостуване в Османската империя, нито на разходите по неговата издръжка. След ареста Карл XII е заточен в Димотика (днешна Североизточна Гърция), където прекарва времето си в игра на шах и в изучаване на корабната архитектура на османските галеони.³ Гостуването му продължава до 1715 г., когато той най-накрая напуска Османската империя и след двуседмична езда се завръща в Швеция.

Думата „калабалък“ не е единственото турско нещо, което кралят донася със себе си. Според историческите източници именно

благодарение на Карл XII в Швеция пристигат кафето и кюфтетата, както и зелевите и лозовите сарми –

все неща, които в наши дни се считат за неразделна, даже емблематична част от шведската кулинария и ежедневие⁴.

В случая със сармите шведските им наименования – kåldolmar и vinbladsdolmar – пазят етимологична следа за своя произход, като комбинират шведските думи kål (‘зеле’) и vinblads (‘лозови листа’) с турското понятие dolma, което от своя страна обединява всякакви пълнени ястия, включително и сармите, които пък на турски се наричат просто sarma. В едно чудесно преобръщане на значенията, в Швеция датата 30 ноември, която в недалечното минало се e почитала от носталгично настроени шведски националисти и неонацисти като деня на смъртта на Карл XII през 1718 г., от 2010 г. насам се отбелязва Kåldolmens dag, или Денят на зелевата сарма.

Но за да не бъде обменът съвсем едностранен, тук е мястото да отбележим, че Швеция също е дала нещо на Турция, което може и да не се яде, но поне в контекста на настоящата рубрика е не по-малко апетитно. Когато през второто десетилетие на XX век, като част от реформите на Ататюрк, Турция заменя персийско-арабската писменост със специално адаптирана към фонетичните изисквания на турския език латинска азбука, тя включва няколко „специални“ букви с диакритични знаци, взети „назаем“ от други езици. Редом с ç от албански, ş от румънски и ü от немски, в турската азбука фигурира и буквата ö, заета от изобилстващия от (често непроизносими за българския език) гласни шведски, където, освен че е буква, ö означава и ‘остров’.

С буквата ç пък започва думата çatışma, преведена в речника като ‘стълкновение, конфронтация, конфликт; престрелка, схватка; спор, препирня; пререкания’. За съжаление, тя е заменила чудесната и значително по-колоритна дума kalabalık в наименованието, с което историческото събитие е познато на турски: Bender Çatışması. Под подобни прозаични наименования от рода на „схватка“, „бой“ и „сблъсък“ събитието става известно и на много други езици с изключение на руския, където то е наречено с подобно на шведския название, а именно „Калабалык“.

За финал, имайки предвид, че Швеция в лицето на Карл XII губи не само конкретната битка срещу Османската империя, а впоследствие и цялата Велика северна война срещу Русия, Дания и Полша, в която Османската империя пък е неин съюзник, можем да заключим следното: дори да приемем, че историята винаги се пише от победителите, думите, с които тя се описва, принадлежат не само на тях, а и на победените. 

1 Посредством шведския език турската думата kalabalık навлиза и във финския като kalabaliikki. Това създава една доста забавна, макар и въображаема етимологична връзка между приемащия език и първоизточника, тъй като думата за „риба“ на фински е kala, а на турски (както знаем) е balık.

2 Според някои източници популярната интерпретация на прозвището Demirbaş Şarl всъщност е неправилна. Докато demir baş наистина означава „желязна глава“, когато двете думи са изписани заедно, те формират понятие с ново значение, което на български може да се преведе като „актив“, „имущество“ или „инвентар“ и съответно отразява дългия престой на крал Карл XII на издръжка на султанската хазна.

3 Освен в шведската кулинария престоят на Карл XII в Османската империя има отражения и в корабоплаването. След завръщането си кралят скицира и заповядва да се построят два бойни кораба за шведския флот – фрегатите Jarramas и Jilderim, пуснати на вода през 1716 г. Техните наименования всъщност са транскрибираните на шведски турски думи yaramaz (‘палав’) и yıldırım (‘гръмотевица’), които според някои източници са прякори (заедно с Demirbaş Şarl), дадени на Карл от османските му домакини.

4 Шведите от десетилетия са едни от най-големите консуматори на кафе в света, а кюфтенцата са толкова незаменима част от тяхната национална кухня, че замразените köttbullar в IKEA се продават под наименованието HUVUDROLL, или „главна роля“. По всичко изглежда, че основната им роля ще си остане безспорна въпреки откъслечните опити от време на време да се напомни географският им произход. През 2018 г. например в официален туит държавната агенция Svenski institutet, чиято цел е да промотира Швеция по света, напомня, че „шведските кюфтета всъщност са базирани на рецепта, която Карл XII донася от Турция в началото на XVIII в.“, и призовава „да се придържаме към фактите“.

В рубриката „От дума на дума“ Екатерина Петрова търси актуални, интересни или новопоявили се думи от нашето ежедневие и проследява често изненадващия им произход, развитието на значенията им във времето и взаимовръзките им с близки и далечни езици.

Последните данни за индустриалното замърсяване

Post Syndicated from Боян Юруков original https://yurukov.net/blog/2024/novi-danni-industrialno-zamarsqvane/

Обнових данните за индустриалното замърсяване. Сетих се, че не ги бях обновил тази година. Така графиката ми позволява разглеждане и филтриране на данни по замърсители и индустриални площадки за последните 14 години. На страницата ще видите как изглежда като изключим CO2 емисиите.

Според съобщеното, има намаление на емисиите, особено във въздуха, и почти достигат нивата от 2020-та г. Има увеличение при замърсяването на водите, но е пак под нивата от преди 10 години.

В същото време трябва да се каже, че това са „декларирано“ замърсяване и емисии. Все още над 27% от тях са изчислени, ако изключим CO2. Няколко поредни разкрития показаха, че дори измерените стойности не отговарят на истината. Не става ясно дали това отчитане се контролира и дали е имало някога санкции за грешно съобщаване. Ще питам пак.

Самата интерактивна графика пуснах преди 11 години. Обновявам я всяка година в края на лятото, когато се предполага, че всички задължени са подали данни. Последно писах през 2019-та по темата и отново миналата година конкретно за данните на инсталациите свързани с Ковачки. Може да ви е интересно да видите и останалите ми статии свързани с други аспекти на замърсяването.

The post Последните данни за индустриалното замърсяване first appeared on Блогът на Юруков.

The collective thoughts of the interwebz