Find information about security best practices when you are writing workflows and using GitHub Actions security features.
Writing workflows
Use secrets for sensitive information
Because there are multiple ways a secret value can be transformed, automatic redaction is not guaranteed. Adhere to the following best practices to limit risks associated with secrets.
- Principal of least privilege
- Any user with write access to your repository has read access to all secrets configured in your repository. Therefore, you should ensure that the credentials being used within workflows have the least privileges required.
- Actions can use the
GITHUB_TOKEN
by accessing it from thegithub.token
context. For more information, see Contexts reference. You should therefore make sure that theGITHUB_TOKEN
is granted the minimum required permissions. It's good security practice to set the default permission for theGITHUB_TOKEN
to read access only for repository contents. The permissions can then be increased, as required, for individual jobs within the workflow file. For more information, see Use GITHUB_TOKEN in workflows.
- Mask sensitive data
- Sensitive data should never be stored as plaintext in workflow files. Mask all sensitive information that is not a GitHub secret by using
::add-mask::VALUE
. This causes the value to be treated as a secret and redacted from logs. For more information about masking data, see GitHub Actions 的工作流命令.
- Sensitive data should never be stored as plaintext in workflow files. Mask all sensitive information that is not a GitHub secret by using
- Delete and rotate exposed secrets
- Redacting of secrets is performed by your workflow runners. This means a secret will only be redacted if it was used within a job and is accessible by the runner. If an unredacted secret is sent to a workflow run log, you should delete the log and rotate the secret. For information on deleting logs, see 使用工作流运行日志.
- Never use structured data as a secret
- Structured data can cause secret redaction within logs to fail, because redaction largely relies on finding an exact match for the specific secret value. For example, do not use a blob of JSON, XML, or YAML (or similar) to encapsulate a secret value, as this significantly reduces the probability the secrets will be properly redacted. Instead, create individual secrets for each sensitive value.
- Register all secrets used within workflows
- If a secret is used to generate another sensitive value within a workflow, that generated value should be formally registered as a secret, so that it will be redacted if it ever appears in the logs. For example, if using a private key to generate a signed JWT to access a web API, be sure to register that JWT as a secret or else it won’t be redacted if it ever enters the log output.
- Registering secrets applies to any sort of transformation/encoding as well. If your secret is transformed in some way (such as Base64 or URL-encoded), be sure to register the new value as a secret too.
- Audit how secrets are handled
- Audit how secrets are used, to help ensure they’re being handled as expected. You can do this by reviewing the source code of the repository executing the workflow, and checking any actions used in the workflow. For example, check that they’re not sent to unintended hosts, or explicitly being printed to log output.
- View the run logs for your workflow after testing valid/invalid inputs, and check that secrets are properly redacted, or not shown. It's not always obvious how a command or tool you’re invoking will send errors to
STDOUT
andSTDERR
, and secrets might subsequently end up in error logs. As a result, it is good practice to manually review the workflow logs after testing valid and invalid inputs. For information on how to clean up workflow logs that may unintentionally contain sensitive data, see 使用工作流运行日志.
- Audit and rotate registered secrets
- Periodically review the registered secrets to confirm they are still required. Remove those that are no longer needed.
- Rotate secrets periodically to reduce the window of time during which a compromised secret is valid.
- Consider requiring review for access to secrets
- You can use required reviewers to protect environment secrets. A workflow job cannot access environment secrets until approval is granted by a reviewer. For more information about storing secrets in environments or requiring reviews for environments, see Using secrets in GitHub Actions and 管理部署环境.
Good practices for mitigating script injection attacks
Recommended approaches for mitigating the risk of script injection in your workflows:
Use an action instead of an inline script
The recommended approach is to create a JavaScript action that processes the context value as an argument. This approach is not vulnerable to the injection attack, since the context value is not used to generate a shell script, but is instead passed to the action as an argument:
uses: fakeaction/checktitle@v3
with:
title: ${{ github.event.pull_request.title }}
Use an intermediate environment variable
For inline scripts, the preferred approach to handling untrusted input is to set the value of the expression to an intermediate environment variable. The following example uses Bash to process the github.event.pull_request.title
value as an environment variable:
- name: Check PR title
env:
TITLE: ${{ github.event.pull_request.title }}
run: |
if [[ "$TITLE" =~ ^octocat ]]; then
echo "PR title starts with 'octocat'"
exit 0
else
echo "PR title did not start with 'octocat'"
exit 1
fi
In this example, the attempted script injection is unsuccessful, which is reflected by the following lines in the log:
env:
TITLE: a"; ls $GITHUB_WORKSPACE"
PR title did not start with 'octocat'
With this approach, the value of the ${{ github.event.pull_request.title }}
expression is stored in memory and used as a variable, and doesn't interact with the script generation process. In addition, consider using double quote shell variables to avoid word splitting, but this is one of many general recommendations for writing shell scripts, and is not specific to GitHub Actions.
Using workflow templates for code scanning
Code scanning allows you to find security vulnerabilities before they reach production. GitHub provides workflow templates for code scanning. You can use these suggested workflows to construct your code scanning workflows, instead of starting from scratch. GitHub's workflow, the CodeQL 分析工作流程, is powered by CodeQL. There are also third-party workflow templates available.
For more information, see 关于代码扫描 and 配置代码扫描的高级设置.
Restricting permissions for tokens
To help mitigate the risk of an exposed token, consider restricting the assigned permissions. For more information, see Use GITHUB_TOKEN in workflows.
Using third-party actions
The individual jobs in a workflow can interact with (and compromise) other jobs. For example, a job querying the environment variables used by a later job, writing files to a shared directory that a later job processes, or even more directly by interacting with the Docker socket and inspecting other running containers and executing commands in them.
This means that a compromise of a single action within a workflow can be very significant, as that compromised action would have access to all secrets configured on your repository, and may be able to use the GITHUB_TOKEN
to write to the repository. Consequently, there is significant risk in sourcing actions from third-party repositories on GitHub. For information on some of the steps an attacker could take, see Secure use reference.
You can help mitigate this risk by following these good practices:
-
Pin actions to a full length commit SHA
Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload. 选择 SHA 时,应验证它是否来自操作的存储库,而不是存储库分支。
-
Audit the source code of the action
Ensure that the action is handling the content of your repository and secrets as expected. For example, check that secrets are not sent to unintended hosts, or are not inadvertently logged.
-
Pin actions to a tag only if you trust the creator
Although pinning to a commit SHA is the most secure option, specifying a tag is more convenient and is widely used. If you’d like to specify a tag, then be sure that you trust the action's creators. The ‘Verified creator’ badge on GitHub Marketplace is a useful signal, as it indicates that the action was written by a team whose identity has been verified by GitHub. Note that there is risk to this approach even if you trust the author, because a tag can be moved or deleted if a bad actor gains access to the repository storing the action.
Reusing third-party workflows
The same principles described above for using third-party actions also apply to using third-party workflows. You can help mitigate the risks associated with reusing workflows by following the same good practices outlined above. For more information, see Reuse workflows.
GitHub's security features
GitHub provides many features to make your code more secure. You can use GitHub's built-in features to understand the actions your workflows depend on, ensure you are notified about vulnerabilities in the actions you consume, or automate the process of keeping the actions in your workflows up to date. If you publish and maintain actions, you can use GitHub to communicate with your community about vulnerabilities and how to fix them. For more information about security features that GitHub offers, see GitHub 安全功能.
Using CODEOWNERS
to monitor changes
You can use the CODEOWNERS
feature to control how changes are made to your workflow files. For example, if all your workflow files are stored .github/workflows
, you can add this directory to the code owners list, so that any proposed changes to these files will first require approval from a designated reviewer.
For more information, see 关于代码所有者.
Managing permissions for GitHub Actions settings in your organization
You can practice the principle of least privilege for your organization's CI/CD pipeline with GitHub Actions by administering custom organization roles. A custom organization role is a way to grant an individual or team in your organization the ability to control certain subsets of settings without granting full administrative control of the organization and its repositories.
对于 GitHub Actions,可以为组织中的个人或团队启用以下任何权限。
- 管理组织操作策略: 访问以管理“操作常规”设置页上的所有设置,但自托管运行器设置除外。
- 管理组织运行器和运行器组: 访问并创建和管理 GitHub 托管的运行器、自托管运行器和运行器组,并控制可以创建自托管运行器的位置。
- 管理组织操作机密:访问并创建和管理操作组织机密。
- 管理组织操作变量:访问并创建和管理操作组织变量。
For more information, see 关于自定义组织角色.
Using OpenID Connect to access cloud resources
如果 GitHub Actions 工作流需要访问支持 OpenID Connect (OIDC) 的云提供商提供的资源,则可以将工作流配置为直接向云提供商进行身份验证。 这样就可以停止将这些凭据存储为长期存在的机密,并提供其他安全优势。 有关详细信息,请参阅“OpenID Connect”。
注意
AWS 不支持 OIDC 的自定义声明。
Using Dependabot version updates to keep actions up to date
可使用 Dependabot 来确保对存储库中使用的操作和可重用工作流的引用保持最新。 操作通常使用漏洞修复和新功能进行更新,以使自动化流程更快速、更安全、更可靠。 Dependabot 使你无需维护依赖项,因为其会自动执行此操作。 有关详细信息,请参阅 使用 Dependabot 保持操作的最新状态 和 关于 Dependabot 安全更新。
Allowing workflows to access internal and private repositories
如果使专用存储库可供其他存储库中的 GitHub Actions 工作流访问,则其他存储库中的外部协作者可以间接访问专用存储库,即使他们没有直接访问这些存储库的权限。 当使用来自专用存储库的操作或工作流时,外部协作者可以查看工作流运行的日志。 For more information, see 与企业共享操作和工作流.
为了允许运行器下载这些操作,GitHub 向运行器传递一个作用域内的安装令牌。 此令牌具有对存储库的读取访问权限,会在一小时后自动过期。
Preventing GitHub Actions from creating or approving pull requests
可选择允许或阻止 GitHub Actions 工作流创建或审批拉取请求。 Allowing workflows, or any other automation, to create or approve pull requests could be a security risk if the pull request is merged without proper oversight.
For more information on how to configure this setting, see 在企业中为 GitHub Actions 实施策略, Disabling or limiting GitHub Actions for your organization, and 管理存储库的 GitHub Actions 设置.
Using code scanning to secure workflows
Code scanning can automatically detect and suggest improvements for common vulnerable patterns used in GitHub Actions workflows. For more information on how to enable code scanning, see 配置代码扫描的默认设置.
Using OpenSSF Scorecards to secure workflow dependencies
Scorecards is an automated security tool that flags risky supply chain practices. You can use the Scorecards action and workflow template to follow best security practices. Once configured, the Scorecards action runs automatically on repository changes, and alerts developers about risky supply chain practices using the built-in code scanning experience. The Scorecards project runs a number of checks, including script injection attacks, token permissions, and pinned actions.
Hardening for GitHub-hosted runners
GitHub-hosted runners take measures to help you mitigate security risks.
Reviewing the supply chain for GitHub-hosted runners
For GitHub-hosted runners created from images maintained by GitHub, you can view a software bill of materials (SBOM) to see what software was pre-installed on the runner. You can provide your users with the SBOM which they can run through a vulnerability scanner to validate if there are any vulnerabilities in the product. If you are building artifacts, you can include this SBOM in your bill of materials for a comprehensive list of everything that went into creating your software.
SBOMs are available for Ubuntu, Windows, and macOS runner images maintained by GitHub. You can locate the SBOM for your build in the release assets at https://github.com/actions/runner-images/releases. An SBOM with a filename in the format of sbom.IMAGE-NAME.json.zip
can be found in the attachments of each release.
For third-party images, such as the images for ARM-powered runners, you can find details of the software that's included in the image in the actions/partner-runner-images
repository.
Denying access to hosts
GitHub 托管的运行器预配有 etc/hosts
文件,可阻止对各种加密货币挖掘池和恶意站点的网络访问。 MiningMadness.com 和 cpu-pool.com 等主机会重新路由到 localhost,因此它们不会带来重大安全风险。 For more information, see About GitHub-hosted runners.
Hardening for self-hosted runners
GitHub-hosted runners execute code within ephemeral and clean isolated virtual machines, meaning there is no way to persistently compromise this environment, or otherwise gain access to more information than was placed in this environment during the bootstrap process.
Self-hosted runners for GitHub do not have guarantees around running in ephemeral clean virtual machines, and can be persistently compromised by untrusted code in a workflow.
As a result, self-hosted runners should almost never be used for public repositories on GitHub, because any user can open pull requests against the repository and compromise the environment. Similarly, be cautious when using self-hosted runners on private or internal repositories, as anyone who can fork the repository and open a pull request (generally those with read access to the repository) are able to compromise the self-hosted runner environment, including gaining access to secrets and the GITHUB_TOKEN
which, depending on its settings, can grant write access to the repository. Although workflows can control access to environment secrets by using environments and required reviews, these workflows are not run in an isolated environment and are still susceptible to the same risks when run on a self-hosted runner.
企业所有者和组织所有者可以选择允许哪些存储库创建存储库级别的自托管运行器。 拥有“管理组织运行器和运行器组”权限的用户只能选择允许哪些存储库为组织中的存储库创建存储库级自托管运行器。
有关自定义组织角色的详细信息,请参阅“关于自定义组织角色”。
有关详细信息,请参阅 在企业中为 GitHub Actions 实施策略 和 禁用或限制组织的 GitHub Actions。
When a self-hosted runner is defined at the organization or enterprise level, GitHub can schedule workflows from multiple repositories onto the same runner. Consequently, a security compromise of these environments can result in a wide impact. To help reduce the scope of a compromise, you can create boundaries by organizing your self-hosted runners into separate groups. You can restrict what workflows, organizations and repositories can access runner groups. For more information, see 使用组管理对自托管运行程序的访问.
You should also consider the environment of the self-hosted runner machines:
- What sensitive information resides on the machine configured as a self-hosted runner? For example, private SSH keys, API access tokens, among others.
- Does the machine have network access to sensitive services? For example, Azure or AWS metadata services. The amount of sensitive information in this environment should be kept to a minimum, and you should always be mindful that any user capable of invoking workflows has access to this environment.
Some customers might attempt to partially mitigate these risks by implementing systems that automatically destroy the self-hosted runner after each job execution. However, this approach might not be as effective as intended, as there is no way to guarantee that a self-hosted runner only runs one job. Some jobs will use secrets as command-line arguments which can be seen by another job running on the same runner, such as ps x -w
. This can lead to secret leaks.
Using just-in-time runners
To improve runner registration security, you can use the REST API to create ephemeral, just-in-time (JIT) runners. These self-hosted runners perform at most one job before being automatically removed from the repository, organization, or enterprise. For more information about configuring JIT runners, see 自托管运行器的 REST API 终结点.
注意
Re-using hardware to host JIT runners can risk exposing information from the environment. Use automation to ensure the JIT runner uses a clean environment. For more information, see 使用自托管运行器自动缩放.
Once you have the config file from the REST API response, you can pass it to the runner at startup.
./run.sh --jitconfig ${encoded_jit_config}
Planning your management strategy for self-hosted runners
A self-hosted runner can be added to various levels in your GitHub hierarchy: the enterprise, organization, or repository level. This placement determines who will be able to manage the runner:
Centralized management:
- If you plan to have a centralized team own the self-hosted runners, then the recommendation is to add your runners at the highest mutual organization or enterprise level. This gives your team a single location to view and manage your runners.
- If you only have a single organization, then adding your runners at the organization level is effectively the same approach, but you might encounter difficulties if you add another organization in the future.
Decentralized management:
- If each team will manage their own self-hosted runners, then the recommendation is to add the runners at the highest level of team ownership. For example, if each team owns their own organization, then it will be simplest if the runners are added at the organization level too.
- You could also add runners at the repository level, but this will add management overhead and also increases the numbers of runners you need, since you cannot share runners between repositories.
Authenticating to your cloud provider
If you are using GitHub Actions to deploy to a cloud provider, or intend to use HashiCorp Vault for secret management, then it's recommended that you consider using OpenID Connect to create short-lived, well-scoped access tokens for your workflow runs. For more information, see OpenID Connect.
Auditing GitHub Actions events
You can use the security log to monitor activity for your user account and the audit log to monitor activity in your organization or enterprise. The security and audit log records the type of action, when it was run, and which personal account performed the action.
For example, you can use the audit log to track the org.update_actions_secret
event, which tracks changes to organization secrets.
For the full list of events that you can find in the audit log for each account type, see the following articles:
Understanding dependencies in your workflows
You can use the dependency graph to explore the actions that the workflows in your repository use. The dependency graph is a summary of the manifest and lock files stored in a repository. It also recognizes files in ./github/workflows/
as manifests, which means that any actions or workflows referenced using the syntax jobs[*].steps[*].uses
or jobs.<job_id>.uses
will be parsed as dependencies.
The dependency graph shows the following information about actions used in workflows:
- The account or organization that owns the action.
- The workflow file that references the action.
- The version or SHA the action is pinned to.
In the dependency graph, dependencies are automatically sorted by vulnerability severity. If any of the actions you use have security advisories, they will display at the top of the list. You can navigate to the advisory from the dependency graph and access instructions for resolving the vulnerability.
The dependency graph is enabled for public repositories, and you can choose to enable it on private repositories. For more information about using the dependency graph, see 探索仓库的依赖项.
Being aware of security vulnerabilities in actions you use
For actions available on the marketplace, GitHub reviews related security advisories and then adds those advisories to the GitHub Advisory Database. You can search the database for actions that you use to find information about existing vulnerabilities and instructions for how to fix them. To streamline your search, use the GitHub Actions filter in the GitHub Advisory Database.
You can set up your repositories so that you:
- Receive alerts when actions used in your workflows receive a vulnerability report. For more information, see Monitoring the actions in your workflows.
- Are warned about existing advisories when you add or update an action in a workflow. For more information, see Screening actions for vulnerabilities in new or updated workflows.
Monitoring the actions in your workflows
You can use Dependabot to monitor the actions in your workflows and enable Dependabot alerts to notify you when an action you use has a reported vulnerability. Dependabot performs a scan of the default branch of the repositories where it is enabled to detect insecure dependencies. Dependabot generates Dependabot alerts when a new advisory is added to the GitHub Advisory Database or when an action you use is updated.
注意
Dependabot only creates alerts for vulnerable actions that use semantic versioning and will not create alerts for actions pinned to SHA values.
You can enable Dependabot alerts for your personal account, for a repository, or for an organization. For more information, see 配置 Dependabot 警报.
你可以在存储库的 Dependabot alerts 选项卡中查看所有打开和关闭的 Dependabot alerts 以及对应的 Dependabot security updates。 For more information, see 查看和更新 Dependabot 警报.
Screening actions for vulnerabilities in new or updated workflows
When you open pull requests to update your workflows, it is good practice to use dependency review to understand the security impact of changes you've made to the actions you use. 依赖项审查帮助您了解依赖项变化以及这些变化在每个拉取请求中的安全影响。 它提供了一个易于理解的依赖项变化可视化效果,多差异显示在拉取请求的“更改的文件”选项卡上。 依赖项审查告知您:
- 与发行日期一起添加、删除或更新的依赖项有哪些
- 有多少项目使用这些组件
- 这些依赖项的漏洞数据
If any of the changes you made to your workflows are flagged as vulnerable, you can avoid adding them to your project or update them to a secure version.
For more information about dependency review, see 关于依赖项评审.
“依赖项审查操作”指的是可以在 GitHub Actions 上下文中报告拉取请求差异的具体操作。 请参阅 dependency-review-action
。 可使用存储库中的 依赖项审查操作 对拉取请求强制实施依赖项审查。 该操作会扫描拉取请求中包版本更改引入的易受攻击的依赖项版本,并警告你相关的安全漏洞。 这样可以更好地了解拉取请求中发生的变化,并帮助防止漏洞添加到存储库中。 For more information, see 关于依赖项评审.
Keeping the actions in your workflows secure and up to date
可使用 Dependabot 来确保对存储库中使用的操作和可重用工作流的引用保持最新。 操作通常使用漏洞修复和新功能进行更新,以使自动化流程更快速、更安全、更可靠。 Dependabot 使你无需维护依赖项,因为其会自动执行此操作。 有关详细信息,请参阅 使用 Dependabot 保持操作的最新状态 和 关于 Dependabot 安全更新。
The following features can automatically update the actions in your workflows.
- Dependabot version updates open pull requests to update actions to the latest version when a new version is released.
- Dependabot security updates open pull requests to update actions with reported vulnerabilities to the minimum patched version.
注意
- Dependabot 仅支持使用 GitHub 存储库语法(例如
actions/checkout@v4
)更新 GitHub Actions。 Dependabot 将忽略本地引用的操作或可重用工作流(例如,./.github/actions/foo.yml
)。 - 目前不支持 Docker Hub 和 GitHub Packages Container registry URL。 例如,不支持使用
docker://
语法引用 Docker 容器操作。 - Dependabot 支持 GitHub Actions 的公共存储库和专用存储库。 有关专用注册表配置选项,请参阅“Dependabot 选项参考”中的“
git
”。
For information on how to configure Dependabot version updates, see 配置 Dependabot 版本更新.
For information on how to configure Dependabot security updates, see 配置 Dependabot 安全更新.
Protecting actions you've created
GitHub enables collaboration between people who publish and maintain actions and vulnerability reporters in order to promote secure coding. 使用存储库安全公告,公共存储库的维护人员可私下讨论和修复项目中的安全漏洞。 协作得到修补程序后,存储库维护人员可发布安全通知,向项目社区公开安全漏洞。 通过发布安全通知,存储库维护人员可使其社区更轻松地更新包依赖项并对安全漏洞的影响进行调查。
If you are someone who maintains an action that is used in other projects, you can use the following GitHub features to enhance the security of the actions you've published.
- Use the dependants view in the Dependency graph to see which projects depend on your code. If you receive a vulnerability report, this will give you an idea of who you need to communicate with about the vulnerability and how to fix it. For more information, see 探索仓库的依赖项.
- Use repository security advisories to create a security advisory, privately collaborate to fix the vulnerability in a temporary private fork, and publish a security advisory to alert your community of the vulnerability once a patch is released. For more information, see 为存储库配置私人漏洞报告 and 创建存储库安全公告.