Merge branch 'main' into dependabot/github_actions/step-security/harden-runner-2.10.0

This commit is contained in:
Varun Sharma 2025-02-17 21:03:38 -08:00 committed by GitHub
commit b3f2cfe291
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 542 additions and 429 deletions

View file

@ -0,0 +1,28 @@
name: 'Publish Immutable Action Version'
on:
release:
types: [published]
permissions:
contents: read
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
packages: write
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@cb605e52c26070c328afc4562f0b4ada7618a84e # v2.10.4
with:
egress-policy: audit
- name: Checking out
uses: actions/checkout@v4
- name: Publish
id: publish
uses: actions/publish-immutable-action@0.0.4

176
.github/workflows/runs-on.yml vendored Normal file
View file

@ -0,0 +1,176 @@
name: RunsOn Tests
on:
workflow_dispatch:
jobs:
test-host-outbound:
runs-on:
- runs-on=${{ github.run_id }}
- runner=2cpu-linux-x64
- image=ubuntu22-stepsecurity-x64
steps:
- name: Harden Runner
uses: step-security/harden-runner@rc
with:
egress-policy: audit
allowed-endpoints: >
github.com:443
goreleaser.com:443
- name: Checkout code
uses: actions/checkout@v3
- name: Run outbound calls from host
run: |
start_time=$(date +%s)
end_time=$((start_time + 90)) # 5 minutes = 300 seconds
while [ $(date +%s) -lt $end_time ]; do
curl -I https://www.google.com
curl -I https://goreleaser.com
sleep 10 # wait 10 seconds between calls
done
test-docker-outbound:
runs-on:
- runs-on=${{ github.run_id }}
- runner=2cpu-linux-x64
- image=ubuntu22-stepsecurity-x64
steps:
- name: Harden Runner
uses: step-security/harden-runner@rc
with:
egress-policy: block
allowed-endpoints: >
archive.ubuntu.com:80
github.com:443
goreleaser.com:443
production.cloudflare.docker.com:443
docker-images-prod.6aa30f8b08e16409b46e0173d6de2f56.r2.cloudflarestorage.com:443
*.docker.io:443
security.ubuntu.com:80
- name: Checkout code
uses: actions/checkout@v3
- name: Run outbound calls from within Docker container
continue-on-error: true
run: |
# Start the container
docker run --rm -d --name test-container ubuntu:latest sleep 90
# Install curl in the container
docker exec test-container apt-get update
docker exec test-container apt-get install -y curl
# Print /etc/resolv.conf from the container
docker exec test-container cat /etc/resolv.conf
# Make outbound calls
for i in {1..9}; do
docker exec test-container curl -I https://www.google.com
docker exec test-container curl -I https://goreleaser.com
sleep 10 # wait 10 seconds between calls
done
# Stop the container
docker stop test-container
test-docker-build-outbound:
runs-on:
- runs-on=${{ github.run_id }}
- runner=2cpu-linux-x64
- image=ubuntu22-stepsecurity-x64
steps:
- name: Harden Runner
uses: step-security/harden-runner@rc
with:
egress-policy: audit
allowed-endpoints: >
archive.ubuntu.com:80
auth.docker.io:443
github.com:443
goreleaser.com:443
production.cloudflare.docker.com:443
docker-images-prod.6aa30f8b08e16409b46e0173d6de2f56.r2.cloudflarestorage.com:443
registry-1.docker.io:443
security.ubuntu.com:80
- name: Checkout code
uses: actions/checkout@v3
- name: Build Docker image and test outbound calls during build
continue-on-error: true
run: |
# Create a Dockerfile that installs curl and makes outbound calls
cat <<EOF > Dockerfile
FROM ubuntu:latest
RUN apt-get update && apt-get install -y curl
RUN for i in {1..9}; do curl -I https://www.google.com && curl -I https://goreleaser.com; sleep 10; done
EOF
# Build the Docker image
docker build -t test-image .
# Print /etc/resolv.conf from the build container (temporary container used during build)
container_id=$(docker create test-image)
docker start $container_id
docker exec $container_id cat /etc/resolv.conf
docker stop $container_id
docker rm $container_id
- name: Print Docker logs with journalctl
run: |
sudo journalctl -u docker.service --no-pager
shell: bash
test-long-running-docker:
runs-on:
- runs-on=${{ github.run_id }}
- runner=2cpu-linux-x64
- image=ubuntu22-stepsecurity-x64
steps:
- name: Harden Runner
uses: step-security/harden-runner@rc
with:
egress-policy: block
allowed-endpoints: >
archive.ubuntu.com:80
auth.docker.io:443
github.com:443
goreleaser.com:443
production.cloudflare.docker.com:443
registry-1.docker.io:443
docker-images-prod.6aa30f8b08e16409b46e0173d6de2f56.r2.cloudflarestorage.com:443
security.ubuntu.com:80
- name: Checkout code
uses: actions/checkout@v3
- name: Run long-running Docker container with outbound calls
continue-on-error: true
run: |
# Start the long-running container
docker run --rm -d --name long-running-container ubuntu:latest bash -c "
apt-get update && apt-get install -y curl &&
while true; do
curl -I https://www.google.com;
curl -I https://goreleaser.com;
sleep 10;
done
"
# Print /etc/resolv.conf from the container
docker exec long-running-container cat /etc/resolv.conf
# Let the container run for 5 minutes
sleep 90
# Stop the container
docker stop long-running-container

View file

@ -35,7 +35,7 @@ jobs:
persist-credentials: false
- name: "Run analysis"
uses: ossf/scorecard-action@dc50aa9510b46c811795eb24b2f1ba02a914e534 # tag=v1.1.1
uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # tag=v1.1.1
with:
results_file: results.sarif
results_format: sarif

440
README.md
View file

@ -13,360 +13,150 @@
</div>
## Table of Contents
# Harden-Runner
- [Introduction](#introduction)
- [4,000+ open source projects use Harden-Runner](#4000-open-source-projects-use-harden-runner)
- [Trusted By](#trusted-by)
- [Case Studies](#case-studies)
- [Why use Harden-Runner](#why-use-harden-runner)
- [Getting Started](#getting-started)
- [Hardening GitHub-Hosted Runners](#hardening-github-hosted-runners)
- [Hands-On Tutorials](#hands-on-tutorials)
- [Support for Private Repositories](#support-for-private-repositories)
- [Hardening Self-Hosted Runners](#hardening-self-hosted-runners)
- [Self-Hosted Actions Runner Controller (ARC) Runners](#self-hosted-actions-runner-controller-arc-runners)
- [Self-Hosted VM Runners (e.g. on EC2)](#self-hosted-vm-runners-eg-on-ec2)
- [Features at a glance](#features-at-a-glance)
- [View outbound network traffic at the job level](#view-outbound-network-traffic-at-the-job-level)
- [View outbound network traffic at the organization level](#view-outbound-network-traffic-at-the-organization-level)
- [View outbound HTTPS traffic at the job level](#view-outbound-https-traffic-at-the-job-level)
- [Detect anomalous outbound network traffic](#detect-anomalous-outbound-network-traffic)
- [Filter outbound network traffic to allowed endpoints](#filter-outbound-network-traffic-to-allowed-endpoints)
- [Determine minimum GITHUB_TOKEN permissions using Harden-Runner](#determine-minimum-github_token-permissions-using-harden-runner)
- [View the name and path of every file written during the build process](#view-the-name-and-path-of-every-file-written-during-the-build-process)
- [View process names and arguments](#view-process-names-and-arguments)
- [Detect tampering of source code during build](#detect-tampering-of-source-code-during-build)
- [Run your job without sudo access](#run-your-job-without-sudo-access)
- [Get real-time security alerts](#get-real-time-security-alerts)
- [Discussions](#discussions)
- [How does it work?](#how-does-it-work)
- [GitHub-Hosted Runners](#github-hosted-runners-1)
- [Self-Hosted Actions Runner Controller (ARC) Runners](#self-hosted-actions-runner-controller-arc-runners-1)
- [Self-Hosted VM Runners (e.g. on EC2)](#self-hosted-vm-runners-eg-on-ec2-1)
- [Limitations](#limitations)
- [GitHub-Hosted Runners](#github-hosted-runners-2)
- [Self-Hosted Actions Runner Controller (ARC) Runners](#self-hosted-actions-runner-controller-arc-runners-2)
- [Self-Hosted VM Runners (e.g. on EC2)](#self-hosted-vm-runners-eg-on-ec2-2)
Harden-Runner secures CI/CD workflows by controlling network access and monitoring activities on GitHub-hosted and self-hosted runners. It blocks unauthorized network traffic and detects unusual activity to protect against potential threats. The name "Harden-Runner" comes from its purpose: strengthening the security of the runners used in GitHub Actions workflows.
## Quick Links
- [Getting Started Guide](#getting-started)
- [Why Choose Harden-Runner](#why-choose-harden-runner)
- [Features and Capabilities](#features)
- [Case Studies and Trusted Projects](#trusted-by-and-case-studies)
- [How It Works](docs/how-it-works.md)
- [Known Limitations](docs/limitations.md)
- [Join the Discussions](#discussions)
---
## Introduction
Harden-Runner provides network egress filtering and runtime security for GitHub-hosted and self-hosted runners. It is called Harden-Runner because it `hardens` the `runner` on which GitHub Actions workflows run.
Learn how Harden-Runner works through the video below, which shows how it detected a supply chain attack on a **Google** open-source project.
Learn how Harden-Runner works through the video below, which shows how it detected a supply chain attack on a Google open-source project.
<a href="https://youtu.be/Yz72qAOrN9s" target="_blank">
<img src="images/case-study-thumbnail1.png" alt="Harden-Runner detected supply chain attack in a Google open-source project" title="This case study video shows how StepSecurity Harden-Runner detected a CI/CD supply chain attack in real-time in Googles open-source project Flank">
</a>
<a href="https://youtu.be/Yz72qAOrN9s" target="_blank"><img src="images/case-study-thumbnail1.png" alt="Harden-Runner detected supply chain attack in a Google open-source project" title="This case study video shows how StepSecurity Harden-Runner detected a CI/CD supply chain attack in real-time in Googles open-source project Flank"></a>
---
## Getting Started
## 4,000+ open source projects use Harden-Runner
This guide walks you through the steps to set up and use Harden-Runner in your CI/CD workflows.
Harden-Runner is trusted by leading open source projects and enterprises to secure their CI/CD pipelines.
### **Step 1: Add Harden-Runner to Your Workflow**
To integrate Harden-Runner, follow these steps:
- Open your GitHub Actions workflow file (e.g., `.github/workflows/<workflow-name>.yml`).
- Add the following code as the first step in each job:
```yaml
steps:
- uses: step-security/harden-runner@446798f8213ac2e75931c1b0769676d927801858 # v2.10.3
with:
egress-policy: audit
**Tip**: Automate this step by pasting your workflow into the [StepSecurity online tool](https://app.stepsecurity.io/secureworkflow)
<details>
<summary>Click to view the full Getting Started Guide</summary>
### **Step 2: Access Security Insights**
Run your workflow. Once completed:
- Review the **workflow logs** and the **job markdown summary**.
- Look for a link to **security insights and recommendations**.
<p align="left">
<img src="images/buildlog1.png" alt="Link in workflow log" >
</p>
- Click on the provided link (e.g., [example link](https://appv2.stepsecurity.io/github/step-security/github-actions-goat/actions/runs/7704454287?jobid=20996777560&tab=network-events)) to access the **Process Monitor View**, which displays:
- **Network events**: Outbound network calls correlated with each step.
- **File events**: File writes tracked during the job.
<p align="left">
<img src="images/network-events.png" alt="Link in network events" >
</p>
</details>
---
## Why Choose Harden-Runner?
- **Prevent Exfiltration:** Prevent the exfiltration of CI/CD secrets and source code.
- **Detect Tampering:** Identify source code modifications during builds.
- **Anomaly Detection:** Spot unusual dependencies and workflow behaviors.
- **Simplify Permissions:** Determine the minimum required `GITHUB_TOKEN` permissions.
---
## Features
Harden-Runner offers a comprehensive suite of features to enhance the security of your CI/CD workflows, available in two tiers: **Community** (Free) and **Enterprise** (Paid).
### Community (Free)
- **Block Network Egress Traffic with Domain Allowlist:** Control outbound network traffic by specifying allowed domains, preventing unauthorized data exfiltration.
- **Detect Compromised Packages, Dependencies & Build Tools:** Identify and mitigate risks from malicious or vulnerable components in your build process.
- **Detect Modification of Source Code:** Monitor and alert on unauthorized changes to your source code during the CI/CD pipeline.
- **Disable Sudo Access:** Restrict the use of superuser privileges in your workflows to minimize security risks.
- **Insights Page for CI/CD Runs:** Access detailed reports and analytics for each CI/CD run to monitor security events and compliance.
### Enterprise (Paid)
Includes all features in the **Community** tier, plus:
- **Support for Private Repositories:** Extend Harden-Runner's security capabilities to your private GitHub repositories.
- **Support for Self-Hosted Runners:** Apply security controls and monitoring to self-hosted GitHub Actions runners.
- **View Outbound GitHub API calls at the Job Level:** Monitor HTTPS requests to GitHub APIs
- **Determine Minimum GITHUB_TOKEN Permissions:** Monitor outbound HTTPS requests to GitHub APIs to recommend the least-privilege permissions needed for your workflows, enhancing security by reducing unnecessary access.
- **View the Name and Path of Every File Written During the Build Process:** Gain visibility into every file written to the build environment, including the ability to correlate file writes with processes, ensuring complete transparency.
- **View Process Names and Arguments:** Monitor every process executed during the build process, along with its arguments, and navigate the process tree to detect suspicious activities.
- **Github Checks:** Display Harden Runner insights in the GitHub Checks UI, giving quick feedback on unusual network activity in pull requests.
For a detailed comparison and more information, please visit our [Pricing Page](https://www.stepsecurity.io/pricing).
Explore the full feature set in the [Features Documentation](https://docs.stepsecurity.io/harden-runner).
---
## Trusted By and Case Studies
Harden-Runner is trusted by over 5000 leading open-source projects and enterprises, including Microsoft, Google, Kubernetes, and more.
### Trusted by
| [![CISA](https://avatars.githubusercontent.com/u/18539691?s=60&v=4)](https://app.stepsecurity.io/github/cisagov/skeleton-generic/actions/runs/9947319332?jobid=27479776091&tab=network-events) | [![Microsoft](https://avatars.githubusercontent.com/u/6154722?s=60&v=4)](https://app.stepsecurity.io/github/microsoft/ebpf-for-windows/actions/runs/7587031851) | [![Google](https://avatars.githubusercontent.com/u/2810941?s=60&v=4)](https://app.stepsecurity.io/github/GoogleCloudPlatform/functions-framework-ruby/actions/runs/7576989995) | [![DataDog](https://avatars.githubusercontent.com/u/365230?s=60&v=4)](https://app.stepsecurity.io/github/DataDog/stratus-red-team/actions/runs/7446169664) | [![Intel](https://avatars.githubusercontent.com/u/17888862?s=60&v=4)](https://app.stepsecurity.io/github/intel/cve-bin-tool/actions/runs/7590975903) | [![Kubernetes](https://avatars.githubusercontent.com/u/36015203?s=60&v=4)](https://app.stepsecurity.io/github/kubernetes-sigs/cluster-api-provider-azure/actions/runs/7591172950) | [![Node.js](https://avatars.githubusercontent.com/u/9950313?s=60&v=4)](https://app.stepsecurity.io/github/nodejs/node/actions/runs/7591405720) | [![AWS](https://avatars.githubusercontent.com/u/2232217?s=60&v=4)](https://app.stepsecurity.io/github/aws/aperf/actions/runs/7631366761) |
| [![CISA](https://avatars.githubusercontent.com/u/18539691?s=60&v=4)](https://appv2.stepsecurity.io/github/cisagov/skeleton-generic/actions/runs/9947319332?jobid=27479776091&tab=network-events) | [![Microsoft](https://avatars.githubusercontent.com/u/6154722?s=60&v=4)](https://appv2.stepsecurity.io/github/microsoft/ebpf-for-windows/actions/runs/7587031851) | [![Google](https://avatars.githubusercontent.com/u/2810941?s=60&v=4)](https://appv2.stepsecurity.io/github/GoogleCloudPlatform/functions-framework-ruby/actions/runs/7576989995) | [![DataDog](https://avatars.githubusercontent.com/u/365230?s=60&v=4)](https://appv2.stepsecurity.io/github/DataDog/stratus-red-team/actions/runs/7446169664) | [![Intel](https://avatars.githubusercontent.com/u/17888862?s=60&v=4)](https://appv2.stepsecurity.io/github/intel/cve-bin-tool/actions/runs/7590975903) | [![Kubernetes](https://avatars.githubusercontent.com/u/36015203?s=60&v=4)](https://appv2.stepsecurity.io/github/kubernetes-sigs/cluster-api-provider-azure/actions/runs/7591172950) | [![Node.js](https://avatars.githubusercontent.com/u/9950313?s=60&v=4)](https://appv2.stepsecurity.io/github/nodejs/node/actions/runs/7591405720) | [![AWS](https://avatars.githubusercontent.com/u/2232217?s=60&v=4)](https://appv2.stepsecurity.io/github/aws/aperf/actions/runs/7631366761) |
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **CISA**<br>[Explore](https://app.stepsecurity.io/github/cisagov/skeleton-generic/actions/runs/9947319332?jobid=27479776091&tab=network-events) | **Microsoft**<br>[Explore](https://app.stepsecurity.io/github/microsoft/ebpf-for-windows/actions/runs/7587031851) | **Google**<br>[Explore](https://app.stepsecurity.io/github/GoogleCloudPlatform/functions-framework-ruby/actions/runs/7576989995) | **DataDog**<br>[Explore](https://app.stepsecurity.io/github/DataDog/stratus-red-team/actions/runs/7446169664) | **Intel**<br>[Explore](https://app.stepsecurity.io/github/intel/cve-bin-tool/actions/runs/7590975903) | **Kubernetes**<br>[Explore](https://app.stepsecurity.io/github/kubernetes-sigs/cluster-api-provider-azure/actions/runs/7591172950) | **Node.js**<br>[Explore](https://app.stepsecurity.io/github/nodejs/node/actions/runs/7591405720) | **AWS**<br>[Explore](https://app.stepsecurity.io/github/aws/aperf/actions/runs/7631366761) |
| **CISA**<br>[Explore](https://appv2.stepsecurity.io/github/cisagov/skeleton-generic/actions/runs/9947319332?jobid=27479776091&tab=network-events) | **Microsoft**<br>[Explore](https://appv2.stepsecurity.io/github/microsoft/ebpf-for-windows/actions/runs/7587031851) | **Google**<br>[Explore](https://appv2.stepsecurity.io/github/GoogleCloudPlatform/functions-framework-ruby/actions/runs/7576989995) | **DataDog**<br>[Explore](https://appv2.stepsecurity.io/github/DataDog/stratus-red-team/actions/runs/7446169664) | **Intel**<br>[Explore](https://appv2.stepsecurity.io/github/intel/cve-bin-tool/actions/runs/7590975903) | **Kubernetes**<br>[Explore](https://appv2.stepsecurity.io/github/kubernetes-sigs/cluster-api-provider-azure/actions/runs/7591172950) | **Node.js**<br>[Explore](https://appv2.stepsecurity.io/github/nodejs/node/actions/runs/7591405720) | **AWS**<br>[Explore](https://appv2.stepsecurity.io/github/aws/aperf/actions/runs/7631366761) |
### Case Studies
- [Harden-Runner Detects CI/CD Supply Chain Attack in Googles Open-Source Project Flank](https://www.stepsecurity.io/case-studies/flank)
- [StepSecurity Detects CI/CD Supply Chain Attack in Microsofts Open-Source Project Azure Karpenter Provider in Real-Time](https://www.stepsecurity.io/case-studies/azure-karpenter-provider)
- [How Coveo Strengthened GitHub Actions Security with StepSecurity](https://www.stepsecurity.io/case-studies/coveo)
- [Hashgraph Achieves Comprehensive CI/CD Security Without Compromising Development Speed](https://www.stepsecurity.io/case-studies/hashgraph)
- [Kapiche secures their GitHub Actions software supply chain with Harden-Runner](https://www.stepsecurity.io/case-studies/kapiche)
- [Arcjet Enhances CI/CD Security with Harden-Runner](https://www.stepsecurity.io/case-studies/arcjet)
---
## Why use Harden-Runner
## How It Works
There are two main threats from compromised workflows, dependencies, and build tools in a CI/CD environment:
Want to know the technical details? Dive into the architecture of Harden-Runner and its integrations for GitHub-hosted and self-hosted runners in our [How Harden-Runner Works Documentation](docs/how-it-works.md).
1. Exfiltration of CI/CD credentials and source code
2. Tampering of source code, dependencies, or artifacts during the build to inject a backdoor
Harden-Runner monitors process, file, and network activity to:
| | Countermeasure | Prevent Security Breach |
| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. | Monitor and block outbound network traffic at the DNS, HTTPS (Layer 7), and network layers (Layers 3 and 4) to prevent exfiltration of code and CI/CD credentials | To prevent the [Codecov breach](https://github.com/step-security/github-actions-goat/blob/main/docs/Vulnerabilities/ExfiltratingCICDSecrets.md) scenario |
| 2. | Detect if source code is being tampered during the build process to inject a backdoor | To detect the [XZ Utils](https://www.stepsecurity.io/blog/analysis-of-backdoored-xz-utils-build-process-with-harden-runner) and [SolarWinds incident](https://github.com/step-security/github-actions-goat/blob/main/docs/Vulnerabilities/TamperingDuringBuild.md) scenarios |
| 3. | Detect poisoned workflows and compromised dependencies that exhibit suspicious behavior | To detect [Dependency confusion](https://github.com/step-security/github-actions-goat/blob/main/docs/Vulnerabilities/ExfiltratingCICDSecrets.md#dependency-confusion-attacks) and [Malicious dependencies](https://github.com/step-security/github-actions-goat/blob/main/docs/Vulnerabilities/ExfiltratingCICDSecrets.md#compromised-dependencies) scenarios |
| 4. | Determine minimum GITHUB_TOKEN permissions by monitoring HTTPS calls to GitHub APIs | To set [minimum GITHUB_TOKEN permissions](https://www.stepsecurity.io/blog/determine-minimum-github-token-permissions-using-ebpf-with-stepsecurity-harden-runner) to reduce the impact of exfiltration |
## Getting Started
### Hardening GitHub-Hosted Runners
1. Add the `step-security/harden-runner` GitHub Action to your GitHub Actions workflow file as the first step in each job. You can automate adding Harden-Runner Action to your workflow file by pasting your workflow in the [StepSecurity online tool](https://app.stepsecurity.io/secureworkflow).
```yaml
steps:
- uses: step-security/harden-runner@446798f8213ac2e75931c1b0769676d927801858 # v2.10.0
with:
egress-policy: audit
```
2. In the workflow logs and the job markdown summary, you will see a link to security insights and recommendations.
<p align="left">
<img src="images/buildlog1.png" alt="Link in build log" >
</p>
3. Click on the link ([example link](https://app.stepsecurity.io/github/step-security/github-actions-goat/actions/runs/7704454287)). You will see a process monitor view of network and file events correlated with each step of the job.
<p align="left">
<img src="images/network-events1.png" alt="Insights from harden-runner" >
</p>
4. In the `Recommended Policy` tab, you'll find a recommended block policy based on outbound calls aggregated from the current and past runs of the job. You can update your workflow file with this policy, or alternatively, use the [Policy Store](https://docs.stepsecurity.io/harden-runner/how-tos/block-egress-traffic#2-add-the-policy-using-the-policy-store) to apply the policy without modifying the workflow file. From now on, any outbound calls not in the allowed list will be blocked.
<p align="left">
<img src="images/recommended-policy1.png" alt="Policy recommended by harden-runner" >
</p>
#### Hands-On Tutorials
You can use [GitHub Actions Goat](https://github.com/step-security/github-actions-goat) to try Harden-Runner. You only need a GitHub Account and a web browser.
Hands-on Tutorials for GitHub Actions Runtime Security:
1. [Filter Egress Network Traffic](https://github.com/step-security/github-actions-goat/blob/main/docs/Solutions/RestrictOutboundTraffic.md)
2. [Detect File Tampering](https://github.com/step-security/github-actions-goat/blob/main/docs/Solutions/MonitorSourceCode.md)
### Support for Private Repositories
Hardening of runners used in private repositories is supported with a commercial license. Check out the [documentation](https://docs.stepsecurity.io/stepsecurity-platform/billing) for more details.
- To use Harden-Runner in a `Private` repository, you must install the [StepSecurity GitHub App](https://github.com/apps/stepsecurity-actions-security).
- This is needed to access the GitHub Actions API and to authenticate users to access the dashboard for private repositories.
- If you use Harden-Runner GitHub Action in a private repository, the generated insights URL is NOT public. Only those who have access to the repository can view it.
Read this [case study on how Kapiche uses Harden-Runner](https://www.stepsecurity.io/case-studies/kapiche/) to improve software supply chain security in their private repositories.
### Hardening Self-Hosted Runners
Hardening of self-hosted runners is supported with a commercial license. Check out the [documentation](https://docs.stepsecurity.io/stepsecurity-platform/billing) for more details. For hardening of self-hosted runners you must install the [StepSecurity GitHub App](https://github.com/apps/stepsecurity-actions-security).
#### Self-Hosted Actions Runner Controller (ARC) Runners
> Explore demo workflows using self-hosted ARC Runner and ARC Harden-Runner [here](https://docs.stepsecurity.io/harden-runner/how-tos/enable-runtime-security-arc).
Actions Runner Controller (ARC) is a Kubernetes operator that orchestrates self-hosted runners for GitHub Actions.
- Instead of adding the Harden-Runner GitHub Action in each job, you'll need to install the ARC Harden-Runner daemonset on your Kubernetes cluster.
- Upon installation, the ARC Harden-Runner daemonset monitors all jobs run on the cluster; you do NOT need to add the Harden-Runner GitHub Action to each job for `audit` mode. You do need to add the Harden-Runner GitHub Action to jobs where you want to enable `block` mode.
- The instructions for installing the ARC-Harden-Runner daemonset are shown in the dashboard. To enable access to these instructions, please email support@stepsecurity.io.
#### Self-Hosted VM Runners (e.g. on EC2)
> Explore demo workflows using self-hosted VM Runners and Harden-Runner [here](https://docs.stepsecurity.io/harden-runner/how-tos/enable-runtime-security-vm).
- Instead of adding the Harden-Runner GitHub Action in each job, you'll need to install the Harden-Runner agent on your runner image (e.g. AMI). This is typically done using packer or as a post-install step when using the https://github.com/philips-labs/terraform-aws-github-runner project to setup runners.
- The Harden-Runner agent monitors all jobs run on the VM, both ephemeral and persistent runners are supported; you do NOT need to add the Harden-Runner GitHub Action to each job for `audit` mode. You do need to add the Harden-Runner GitHub Action to jobs where you want to enable `block` mode.
- The instructions for installing the Harden-Runner agent on your self-hosted VM runners are shown in the dashboard. To enable access to these instructions, please email support@stepsecurity.io. This agent is different than the one used for GitHub-hosted runners.
## Features at a glance
For details, check out the documentation at https://docs.stepsecurity.io
### View outbound network traffic at the job level
> Applies to both GitHub-hosted and self-hosted runners
Harden-Runner monitors all outbound traffic from each job at the DNS and network layers
- After the workflow completes, each outbound call is correlated with each step of the job, and shown in the insights page
- For self-hosted runners, no changes are needed to workflow files to monitor egress traffic
- A filtering (block) egress policy is suggested in the insights page based on the current and past job runs
<p align="left">
<img src="images/network-events1.png" alt="Insights from harden-runner" >
</p>
### View outbound network traffic at the organization level
> Applies to both GitHub-hosted and self-hosted runners
You can view all unique network destinations from all workflow runs in your organization on the `Runtime Security` tab.
- The `All Observed Endpoints` menu provides a detailed list of all network destinations contacted by your Actions runners.
- For each listed endpoint, the `View Sample Workflow Runs` option enables you to examine individual GitHub Actions workflow runs that interacted with the endpoint.
For more details refer [Unified Network Egress View: Centralize GitHub Actions Network Destinations for Your Enterprise](https://www.stepsecurity.io/blog/unified-network-egress-view-centralize-github-actions-network-destinations-for-your-enterprise)
<p align="left">
<img src="images/org-level.png" width="400" alt="View outbound network traffic at the organization level" >
</p>
### View outbound HTTPS traffic at the job level
> Applies to GitHub-hosted and self-hosted VM runners
Harden-Runner can monitor outbound HTTPS requests. This feature is supported with a commercial license.
- HTTPS events are monitored using eBPF (no MITM proxy is used)
- If a HTTP PUT/ POST/ PATCH call is made to GitHub APIs to a HTTP Path with a different organization than where the workflow is running, the call is marked as anomalous
- As of now, only HTTPS calls to `github.com`, `api.github.com`, `*.pkg.github.com`, and `ghcr.io` hosts are monitoried.
<p align="left">
<img src="images/https-events.png" alt="View outbound HTTPS traffic at the job level" >
</p>
### Detect anomalous outbound network traffic
> Applies to both GitHub-hosted and self-hosted runners
You can detect suspicious/ anomalous traffic using this feature even in `egress-policy:audit` mode.
- Anomaly detection feature creates a machine learning model of outbound network calls by analyzing the historical data of the same workflow in previous runs
- After the baseline is created, any anomalous outbound destinations are marked as anomalous in the insights page, and real-time alerts are triggered
- You can view the list of all anomalous outbound network traffic in the `Runtime detections` page on the dashboard
For more details, refer to [Anomalous Outbound Call Detection Using Machine Learning](https://www.stepsecurity.io/blog/announcing-anomalous-outbound-call-detection-using-machine-learning)
### Filter outbound network traffic to allowed endpoints
> Applies to both GitHub-hosted and self-hosted runners
You can see recommended egress block policy in the `Recommendations` tab for each job. This is based on observed traffic across multiple runs of the job.
<p align="left">
<img src="images/recommended-policy1.png" alt="Policy recommended by harden-runner" >
</p>
Once you set these allowed endpoints in the workflow file, or in the [Policy Store](https://docs.stepsecurity.io/harden-runner/how-tos/block-egress-traffic#2-add-the-policy-using-the-policy-store) and switch to using `egress-policy:block`
- Harden-Runner blocks egress traffic at the DNS (Layer 7) and network layers (Layers 3 and 4)
- It blocks DNS exfiltration, where attacker tries to send data out using DNS resolution
- Wildcard domains are supported, e.g. you can add `*.data.mcr.microsoft.com:443` to the allowed list, and egress traffic will be allowed to `eastus.data.mcr.microsoft.com:443` and `westus.data.mcr.microsoft.com:443`
<p align="left">
<img src="images/blocked-outbound-call-3.png" alt="Policy recommended by harden-runner" >
</p>
### Determine minimum GITHUB_TOKEN permissions using Harden-Runner
> Applies to GitHub-hosted runners
Harden-Runner monitors outbound HTTPS requests using eBPF and uses the PATHs and VERBs of these HTTPS calls to recommend the minimum GITHUB_TOKEN permissions for each job in your workflow. This feature is supported with a commercial license.
- GITHUB_TOKEN is an automatically generated secret used to authenticate to GitHub APIs from GitHub Actions workflows.
- Harden-Runner can monitor the VERBs (e.g., `GET`, `POST`) and PATHs (e.g., `/repos/owner/repo/issues`) for calls made to the GitHub APIs from the runner.
- Each GitHub Actions API call requires a corresponding GITHUB_TOKEN permission. For instance, a GET request to the `/repos/org/repo/info/refs?service=git-upload-pack` endpoint requires the `contents: read` permission.
- The recommendation for the minimum GITHUB_TOKEN permissions are show in the `Recommendations` tab.
For more details, refer to [Determine Minimum GITHUB_TOKEN Permissions Using eBPF with Harden-Runner.
](https://www.stepsecurity.io/blog/determine-minimum-github-token-permissions-using-ebpf-with-stepsecurity-harden-runner)
<p align="left">
<img src="images/token-perms-recommendation.png" alt="View recommendation for minimum GITHUB_TOKEN permissions" >
</p>
### View the name and path of every file written during the build process
> Applies to both GitHub-hosted and self-hosted runners
View the name and path of every file that was written during the build process. This feature is supported with a commercial license.
- Harden-Runner tracks every file written to the GitHub Actions working directory during the build process.
- In the insights page in the `File Write Events` tab you can see a file explorer view of each file that was written to.
- Clicking on any file reveals a list of processes that wrote to it, providing complete transparency.
<p align="left">
<img src="images/file-write-events.png" alt="View the name and path of every file written during the build process" >
</p>
### View process names and arguments
> Applies to both GitHub-hosted and self-hosted runners
View process names, PIDs, and process arguments. This feature is supported with a commercial license.
- Harden-Runner tracks every process that is run during the build process.
- Clicking on any process ID (PID) in the network events, file events, or HTTPS events shows the process that caused the event, along with the process arguments.
- You can walk up the process tree by clicking `View Parent Process` to understand the build process and detect suspicious activity.
<p align="left">
<img src="images/process-events-3.png" alt="View process names and arguments" >
</p>
### Detect tampering of source code during build
> Applies to both GitHub-hosted and self-hosted runners
Harden-Runner monitors file writes and can detect if a file is overwritten.
- Source code overwrite is not expected in a release build
- All source code files are monitored, which means even changes to IaC files (Kubernetes manifest, Terraform) are detected
- You can enable notifications to get one-time alert when source code is overwritten
- For self-hosted runners, no changes are needed to workflow files for file monitoring
<p align="left">
<img src="images/file-events.png" alt="Policy recommended by harden-runner" >
</p>
### Run your job without sudo access
> Applies to GitHub-hosted runners
GitHub-hosted runner uses passwordless sudo for running jobs.
- This means compromised build tools or dependencies can install attack tools
- If your job does not need sudo access, you see a policy
recommendation to disable sudo in the insights page
- When you set `disable-sudo` to `true`, the job steps run without sudo access to the GitHub-hosted Ubuntu VM
<p align="left">
<img src="images/recommended-policy1.png" alt="Policy recommended by harden-runner" >
</p>
### Get real-time security alerts
> Applies to both GitHub-hosted and self-hosted runners
Install the [StepSecurity GitHub App](https://github.com/apps/stepsecurity-actions-security) to get security alerts/ notifications.
- Email, Slack, and Teams notifications are supported
- Notifications are sent when anomalous outbound network/ HTTPS traffic is detected, outbound traffic is blocked, or source code is overwritten
- Notifications are not repeated for the same alert for a given workflow
## Discussions
- If you have questions or ideas, please use [discussions](https://github.com/step-security/harden-runner/discussions).
- For support for self-hosted runners and private repositories, email support@stepsecurity.io.
- If you use a different CI/CD Provider (e.g. Jenkins, Gitlab CI, etc), and would like to use Harden Runner in your environment, please email interest@stepsecurity.io
## How does it work?
### GitHub-Hosted Runners
For GitHub-hosted runners, Harden-Runner GitHub Action downloads and installs the StepSecurity Agent.
- The code to monitor file, process, and network activity is in the Agent.
- The agent is written in Go and is open source at https://github.com/step-security/agent
- The agent's build is reproducible. You can view the steps to reproduce the build [here](http://app.stepsecurity.io/github/step-security/agent/releases/latest)
### Self-Hosted Actions Runner Controller (ARC) Runners
- ARC Harden Runner daemonset uses eBPF
- You can find more details in this blog post: https://www.stepsecurity.io/blog/introducing-harden-runner-for-kubernetes-based-self-hosted-actions-runners
- ARC Harden Runner is NOT open source.
### Self-Hosted VM Runners (e.g. on EC2)
- For self-hosted VMs, you add the Harden-Runner agent into your runner image (e.g. AMI).
- Agent for self-hosted VMs is NOT open source.
---
## Limitations
### GitHub-Hosted Runners
While Harden-Runner offers powerful features, there are certain limitations based on the environment, such as OS support. See the complete list in [Known Limitations](docs/limitations.md).
1. Only Ubuntu VM is supported. Windows and MacOS GitHub-hosted runners are not supported. There is a discussion about that [here](https://github.com/step-security/harden-runner/discussions/121).
2. Harden-Runner is not supported when [job is run in a container](https://docs.github.com/en/actions/using-jobs/running-jobs-in-a-container) as it needs sudo access on the Ubuntu VM to run. It can be used to monitor jobs that use containers to run steps. The limitation is if the entire job is run in a container. That is not common for GitHub Actions workflows, as most of them run directly on `ubuntu-latest`. Note: This is not a limitation for Self-Hosted runners.
---
### Self-Hosted Actions Runner Controller (ARC) Runners
## Discussions
1. Since ARC Harden Runner uses eBPF, only Linux jobs are supported. Windows and MacOS jobs are not supported.
Join the conversation! For questions, ideas, or feedback, visit our [Discussions Page](https://github.com/step-security/harden-runner/discussions).
### Self-Hosted VM Runners (e.g. on EC2)
For enterprise support, email support@stepsecurity.io. Interested in using Harden-Runner in other CI/CD platforms? Reach out to interest@stepsecurity.io.
1. Only Ubuntu VM is supported. Windows and MacOS jobs are not supported.
---
## License
Harden-Runner is open source. See the [LICENSE](LICENSE) file for details.

48
dist/index.js vendored
View file

@ -2838,7 +2838,7 @@ var lib_core = __nccwpck_require__(186);
var external_fs_ = __nccwpck_require__(747);
;// CONCATENATED MODULE: ./src/configs.ts
const STEPSECURITY_ENV = "agent"; // agent or int
const STEPSECURITY_API_URL = `https://${STEPSECURITY_ENV}.api.stepsecurity.io/v1`;
const configs_STEPSECURITY_API_URL = `https://${STEPSECURITY_ENV}.api.stepsecurity.io/v1`;
const configs_STEPSECURITY_WEB_URL = "https://app.stepsecurity.io";
;// CONCATENATED MODULE: ./src/common.ts
@ -3014,6 +3014,49 @@ function isDocker() {
return isDockerCached;
}
// EXTERNAL MODULE: ./node_modules/@actions/http-client/lib/index.js
var lib = __nccwpck_require__(255);
;// CONCATENATED MODULE: ./src/tls-inspect.ts
var tls_inspect_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
function isTLSEnabled(owner) {
return tls_inspect_awaiter(this, void 0, void 0, function* () {
let tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
let httpClient = new HttpClient();
httpClient.requestOptions = { socketTimeout: 3 * 1000 };
core.info(`[!] Checking TLS_STATUS: ${owner}`);
let isEnabled = false;
try {
let resp = yield httpClient.get(tlsStatusEndpoint);
if (resp.message.statusCode === 200) {
isEnabled = true;
core.info(`[!] TLS_ENABLED: ${owner}`);
}
else {
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
}
}
catch (e) {
core.info(`[!] Unable to check TLS_STATUS`);
}
return isEnabled;
});
}
function isGithubHosted() {
const runnerEnvironment = process.env.RUNNER_ENVIRONMENT || "";
return runnerEnvironment === "github-hosted";
}
;// CONCATENATED MODULE: ./src/index.ts
var src_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@ -3028,13 +3071,14 @@ var src_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _argu
(() => src_awaiter(void 0, void 0, void 0, function* () {
console.log("[harden-runner] main-step");
if (process.platform !== "linux") {
console.log(UBUNTU_MESSAGE);
return;
}
if (isDocker()) {
if (isGithubHosted() && isDocker()) {
console.log(CONTAINER_MESSAGE);
return;
}

2
dist/index.js.map vendored

File diff suppressed because one or more lines are too long

105
dist/post/index.js vendored
View file

@ -139,7 +139,7 @@ const command_1 = __nccwpck_require__(351);
const file_command_1 = __nccwpck_require__(717);
const utils_1 = __nccwpck_require__(278);
const os = __importStar(__nccwpck_require__(87));
const path = __importStar(__nccwpck_require__(277));
const path = __importStar(__nccwpck_require__(622));
const oidc_utils_1 = __nccwpck_require__(41);
/**
* The code to exit an action
@ -618,7 +618,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;
const path = __importStar(__nccwpck_require__(277));
const path = __importStar(__nccwpck_require__(622));
/**
* toPosixPath converts the given path to the posix form. On Windows, \\ will be
* replaced with /.
@ -2752,7 +2752,7 @@ module.exports = require("os");
/***/ }),
/***/ 277:
/***/ 622:
/***/ ((module) => {
"use strict";
@ -2837,10 +2837,10 @@ var external_fs_ = __nccwpck_require__(747);
;// CONCATENATED MODULE: external "child_process"
const external_child_process_namespaceObject = require("child_process");
// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js
var core = __nccwpck_require__(186);
var lib_core = __nccwpck_require__(186);
;// CONCATENATED MODULE: ./src/configs.ts
const STEPSECURITY_ENV = "agent"; // agent or int
const STEPSECURITY_API_URL = `https://${STEPSECURITY_ENV}.api.stepsecurity.io/v1`;
const configs_STEPSECURITY_API_URL = `https://${STEPSECURITY_ENV}.api.stepsecurity.io/v1`;
const STEPSECURITY_WEB_URL = "https://app.stepsecurity.io";
;// CONCATENATED MODULE: ./src/common.ts
@ -2905,9 +2905,9 @@ function addSummary() {
//console.error(err);
}
if (needsSubscription) {
yield core.summary.addSeparator()
yield lib_core.summary.addSeparator()
.addRaw(`<h2>⚠️ Your GitHub Actions Runtime Security is currently disabled!</h2>`);
yield core.summary.addRaw(`
yield lib_core.summary.addRaw(`
<p>It appears that you're using the <a href="https://github.com/step-security/harden-runner">Harden-Runner GitHub Action</a> by StepSecurity within a private repository. However, runtime security is not enabled as your organization hasn't signed up for a free trial or a paid subscription yet.</p>
<p>To enable runtime security, start a free trial today by installing the <a href="https://github.com/apps/stepsecurity-actions-security">StepSecurity Actions Security GitHub App</a>. For more information or assistance, feel free to reach out to us through our <a href="https://www.stepsecurity.io/contact">contact form</a>.</p>
`)
@ -2925,7 +2925,7 @@ function addSummary() {
return;
}
const insightsRow = `<p><b><a href="${insights_url}">📄 View Full Report</a></b></p>`;
yield core.summary.addSeparator().addRaw(`<h2>🛡 StepSecurity Report</h2>`);
yield lib_core.summary.addSeparator().addRaw(`<h2>🛡 StepSecurity Report</h2>`);
tableEntries.sort((a, b) => {
if (a.status === "❌ Blocked" && b.status !== "❌ Blocked") {
return -1;
@ -2938,7 +2938,7 @@ function addSummary() {
}
});
tableEntries = tableEntries.slice(0, 3);
yield core.summary.addRaw(`
yield lib_core.summary.addRaw(`
<blockquote>
<p>Preview of the outbound network calls during this workflow run.</p></blockquote>
<h3>Network Calls</h3>
@ -2967,7 +2967,7 @@ function addSummary() {
</table>
${insightsRow}
`);
yield core.summary.addRaw(`<p><i>Markdown generated by the <a href="https://github.com/step-security/harden-runner">Harden-Runner GitHub Action</a>.</i></p>`)
yield lib_core.summary.addRaw(`<p><i>Markdown generated by the <a href="https://github.com/step-security/harden-runner">Harden-Runner GitHub Action</a>.</i></p>`)
.addSeparator()
.write();
});
@ -3031,19 +3031,13 @@ function isSecondaryPod() {
const workDir = "/__w";
return external_fs_.existsSync(workDir);
}
function getRunnerTempDir() {
const isTest = process.env["isTest"];
if (isTest === "1") {
return "/tmp";
}
return process.env["RUNNER_TEMP"] || "/tmp";
}
function sendAllowedEndpoints(endpoints) {
const allowedEndpoints = endpoints.split(" "); // endpoints are space separated
for (const endpoint of allowedEndpoints) {
if (endpoint) {
const encodedEndpoint = Buffer.from(endpoint).toString("base64");
cp.execSync(`echo "${endpoint}" > "${getRunnerTempDir()}/step_policy_endpoint_${encodedEndpoint}"`);
let encodedEndpoint = Buffer.from(endpoint).toString("base64");
let endpointPolicyStr = `step_policy_endpoint_${encodedEndpoint}`;
echo(endpointPolicyStr);
}
}
if (allowedEndpoints.length > 0) {
@ -3051,14 +3045,54 @@ function sendAllowedEndpoints(endpoints) {
}
}
function applyPolicy(count) {
const fileName = `step_policy_apply_${count}`;
cp.execSync(`echo "${fileName}" > "${getRunnerTempDir()}/${fileName}"`);
let applyPolicyStr = `step_policy_apply_${count}`;
echo(applyPolicyStr);
}
function removeStepPolicyFiles() {
external_child_process_namespaceObject.execSync(`rm ${getRunnerTempDir()}/step_policy_*`);
function echo(content) {
cp.execFileSync("echo", [content]);
}
function arcCleanUp() {
external_child_process_namespaceObject.execSync(`echo "cleanup" > "${getRunnerTempDir()}/step_policy_cleanup"`);
// EXTERNAL MODULE: ./node_modules/@actions/http-client/lib/index.js
var lib = __nccwpck_require__(255);
;// CONCATENATED MODULE: ./src/tls-inspect.ts
var tls_inspect_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
function isTLSEnabled(owner) {
return tls_inspect_awaiter(this, void 0, void 0, function* () {
let tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
let httpClient = new HttpClient();
httpClient.requestOptions = { socketTimeout: 3 * 1000 };
core.info(`[!] Checking TLS_STATUS: ${owner}`);
let isEnabled = false;
try {
let resp = yield httpClient.get(tlsStatusEndpoint);
if (resp.message.statusCode === 200) {
isEnabled = true;
core.info(`[!] TLS_ENABLED: ${owner}`);
}
else {
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
}
}
catch (e) {
core.info(`[!] Unable to check TLS_STATUS`);
}
return isEnabled;
});
}
function isGithubHosted() {
const runnerEnvironment = process.env.RUNNER_ENVIRONMENT || "";
return runnerEnvironment === "github-hosted";
}
;// CONCATENATED MODULE: ./src/cleanup.ts
@ -3076,20 +3110,19 @@ var cleanup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _
(() => cleanup_awaiter(void 0, void 0, void 0, function* () {
console.log("[harden-runner] post-step");
if (process.platform !== "linux") {
console.log(UBUNTU_MESSAGE);
return;
}
if (isDocker()) {
if (isGithubHosted() && isDocker()) {
console.log(CONTAINER_MESSAGE);
return;
}
if (isArcRunner()) {
console.log(`[!] ${ARC_RUNNER_MESSAGE}`);
arcCleanUp();
removeStepPolicyFiles();
return;
}
if (process.env.STATE_selfHosted === "true") {
@ -3139,11 +3172,17 @@ var cleanup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _
}
var disable_sudo = process.env.STATE_disableSudo;
if (disable_sudo !== "true") {
var journalLog = external_child_process_namespaceObject.execSync("sudo journalctl -u agent.service", {
encoding: "utf8",
});
console.log("Service log:");
console.log(journalLog);
try {
var journalLog = external_child_process_namespaceObject.execSync("sudo journalctl -u agent.service --lines=1000", {
encoding: "utf8",
maxBuffer: 1024 * 1024 * 10 // 10MB buffer
});
console.log("agent.service log:");
console.log(journalLog);
}
catch (error) {
console.log("Warning: Could not fetch service logs:", error.message);
}
}
try {
yield addSummary();

File diff suppressed because one or more lines are too long

40
dist/pre/index.js vendored
View file

@ -71535,19 +71535,13 @@ function isSecondaryPod() {
const workDir = "/__w";
return external_fs_.existsSync(workDir);
}
function getRunnerTempDir() {
const isTest = process.env["isTest"];
if (isTest === "1") {
return "/tmp";
}
return process.env["RUNNER_TEMP"] || "/tmp";
}
function sendAllowedEndpoints(endpoints) {
const allowedEndpoints = endpoints.split(" "); // endpoints are space separated
for (const endpoint of allowedEndpoints) {
if (endpoint) {
const encodedEndpoint = Buffer.from(endpoint).toString("base64");
external_child_process_.execSync(`echo "${endpoint}" > "${getRunnerTempDir()}/step_policy_endpoint_${encodedEndpoint}"`);
let encodedEndpoint = Buffer.from(endpoint).toString("base64");
let endpointPolicyStr = `step_policy_endpoint_${encodedEndpoint}`;
echo(endpointPolicyStr);
}
}
if (allowedEndpoints.length > 0) {
@ -71555,14 +71549,11 @@ function sendAllowedEndpoints(endpoints) {
}
}
function applyPolicy(count) {
const fileName = `step_policy_apply_${count}`;
external_child_process_.execSync(`echo "${fileName}" > "${getRunnerTempDir()}/${fileName}"`);
let applyPolicyStr = `step_policy_apply_${count}`;
echo(applyPolicyStr);
}
function removeStepPolicyFiles() {
cp.execSync(`rm ${getRunnerTempDir()}/step_policy_*`);
}
function arcCleanUp() {
cp.execSync(`echo "cleanup" > "${getRunnerTempDir()}/step_policy_cleanup"`);
function echo(content) {
external_child_process_.execFileSync("echo", [content]);
}
;// CONCATENATED MODULE: ./src/tls-inspect.ts
@ -71616,8 +71607,8 @@ var external_crypto_ = __nccwpck_require__(6417);
const CHECKSUMS = {
tls: {
amd64: "0bd500769646f0a90c0dfe9ac59699d5165bed549a9870c031b861146af337b2",
arm64: "c2448ac205fd90f46abba31c13cf34c3b997824881502f736315fb08ac0a5a5c",
amd64: "38e7ed97ced6fe0c1cf0fb5ee3b3d521dfe28d5ddf1cdca72d130c8d1b4a314e",
arm64: "f67c80cc578c996d4f882c14fcdb63df57927d907cd22f1ec65f9fa940c08cf3",
},
non_tls: {
amd64: "a9f1842e3d7f3d38c143dbe8ffe1948e6c8173cd04da072d9f9d128bb400844a", // v0.13.7
@ -71670,7 +71661,7 @@ function installAgent(isTLS, configStr) {
encoding: "utf8",
});
if (isTLS) {
downloadPath = yield tool_cache.downloadTool(`https://packages.stepsecurity.io/github-hosted/harden-runner_1.3.2_linux_${variant}.tar.gz`);
downloadPath = yield tool_cache.downloadTool(`https://packages.stepsecurity.io/github-hosted/harden-runner_1.4.2_linux_${variant}.tar.gz`);
}
else {
if (variant === "arm64") {
@ -71735,7 +71726,7 @@ var setup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _ar
console.log(UBUNTU_MESSAGE);
return;
}
if (isDocker()) {
if (isGithubHosted() && isDocker()) {
console.log(CONTAINER_MESSAGE);
return;
}
@ -71836,7 +71827,7 @@ var setup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _ar
if (confg.egress_policy === "block") {
try {
if (process.env.USER) {
external_child_process_.execSync(`sudo chown -R ${process.env.USER} /home/agent`);
chownForFolder(process.env.USER, "/home/agent");
}
const confgStr = JSON.stringify(confg);
external_fs_.writeFileSync("/home/agent/block_event.json", confgStr);
@ -71882,7 +71873,7 @@ var setup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _ar
}
const confgStr = JSON.stringify(confg);
external_child_process_.execSync("sudo mkdir -p /home/agent");
external_child_process_.execSync("sudo chown -R $USER /home/agent");
chownForFolder(process.env.USER, "/home/agent");
let isTLS = yield isTLSEnabled(github.context.repo.owner);
const agentInstalled = yield installAgent(isTLS, confgStr);
if (agentInstalled) {
@ -71923,6 +71914,11 @@ function setup_sleep(ms) {
setTimeout(resolve, ms);
});
}
function chownForFolder(newOwner, target) {
let cmd = "sudo";
let args = ["chown", "-R", newOwner, target];
external_child_process_.execFileSync(cmd, args);
}
})();

File diff suppressed because one or more lines are too long

21
docs/how-it-works.md Normal file
View file

@ -0,0 +1,21 @@
## How Harden-Runner Works?
### GitHub-Hosted Runners
For GitHub-hosted runners, Harden-Runner GitHub Action downloads and installs the StepSecurity Agent.
- The code to monitor file, process, and network activity is in the Agent.
- The community tier agent is open-source and can be found [here](https://github.com/step-security/agent). The enterprise tier agent is closed-source. Both agents are written in Go.
- The agent's build is reproducible. You can view the steps to reproduce the build [here](http://app.stepsecurity.io/github/step-security/agent/releases/latest)
### Self-Hosted Actions Runner Controller (ARC) Runners
- ARC Harden Runner daemonset uses eBPF
- You can find more details in this [blog post](https://www.stepsecurity.io/blog/introducing-harden-runner-for-kubernetes-based-self-hosted-actions-runners)
- ARC Harden Runner is NOT open source.
### Self-Hosted VM Runners (e.g. on EC2)
- For self-hosted VMs, you add the Harden-Runner agent into your runner image (e.g. AMI).
- You can find more details in this [blog post](https://www.stepsecurity.io/blog/ci-cd-security-for-self-hosted-vm-runners)
- Agent for self-hosted VMs is NOT open source.

14
docs/limitations.md Normal file
View file

@ -0,0 +1,14 @@
## Limitations
### GitHub-Hosted Runners
* Only Ubuntu VM is supported. Windows and MacOS GitHub-hosted runners are not supported. There is a discussion about that [here](https://github.com/step-security/harden-runner/discussions/121).
* Harden-Runner is not supported when [job is run in a container](https://docs.github.com/en/actions/using-jobs/running-jobs-in-a-container) as it needs sudo access on the Ubuntu VM to run. It can be used to monitor jobs that use containers to run steps. The limitation is if the entire job is run in a container. That is not common for GitHub Actions workflows, as most of them run directly on `ubuntu-latest`. Note: This is not a limitation for Self-Hosted runners.
### Self-Hosted Actions Runner Controller (ARC) Runners
* Since ARC Harden Runner uses eBPF, only Linux jobs are supported. Windows and MacOS jobs are not supported.
### Self-Hosted VM Runners (e.g. on EC2)
* Only Ubuntu VM is supported. Windows and MacOS jobs are not supported.

BIN
images/network-events.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 188 KiB

49
package-lock.json generated
View file

@ -3021,9 +3021,9 @@
"dev": true
},
"node_modules/cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"dependencies": {
"path-key": "^3.1.0",
@ -3749,6 +3749,20 @@
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
"dev": true
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
@ -5852,12 +5866,12 @@
}
},
"node_modules/micromatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
"integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==",
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"dependencies": {
"braces": "^3.0.2",
"braces": "^3.0.3",
"picomatch": "^2.3.1"
},
"engines": {
@ -9555,9 +9569,9 @@
"dev": true
},
"cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"requires": {
"path-key": "^3.1.0",
@ -10100,6 +10114,13 @@
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
"dev": true
},
"fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"optional": true
},
"function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
@ -11699,12 +11720,12 @@
"dev": true
},
"micromatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
"integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==",
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"requires": {
"braces": "^3.0.2",
"braces": "^3.0.3",
"picomatch": "^2.3.1"
}
},

View file

@ -1,20 +1,9 @@
import { isArcRunner, sendAllowedEndpoints } from "./arc-runner";
it("should correctly recognize arc based runner", async () => {
process.env["GITHUB_ACTIONS_RUNNER_EXTRA_USER_AGENT"] =
"actions-runner-controller/2.0.1";
let isArc: boolean = await isArcRunner();
let isArc: boolean = await isArcRunner();
expect(isArc).toBe(true);
});
it("should write endpoint files", ()=>{
process.env["isTest"] = "1"
let allowed_endpoints = ["github.com:443", "*.google.com:443", "youtube.com"].join(" ");
sendAllowedEndpoints(allowed_endpoints);
})

View file

@ -1,6 +1,6 @@
import * as cp from "child_process";
import * as fs from "fs";
import { sleep } from "./setup";
import path from "path";
export function isArcRunner(): boolean {
const runnerUserAgent = process.env["GITHUB_ACTIONS_RUNNER_EXTRA_USER_AGENT"];
@ -21,25 +21,14 @@ function isSecondaryPod(): boolean {
return fs.existsSync(workDir);
}
function getRunnerTempDir(): string {
const isTest = process.env["isTest"];
if (isTest === "1") {
return "/tmp";
}
return process.env["RUNNER_TEMP"] || "/tmp";
}
export function sendAllowedEndpoints(endpoints: string): void {
const allowedEndpoints = endpoints.split(" "); // endpoints are space separated
for (const endpoint of allowedEndpoints) {
if (endpoint) {
const encodedEndpoint = Buffer.from(endpoint).toString("base64");
cp.execSync(
`echo "${endpoint}" > "${getRunnerTempDir()}/step_policy_endpoint_${encodedEndpoint}"`
);
let encodedEndpoint = Buffer.from(endpoint).toString("base64");
let endpointPolicyStr = `step_policy_endpoint_${encodedEndpoint}`;
echo(endpointPolicyStr);
}
}
@ -49,14 +38,10 @@ export function sendAllowedEndpoints(endpoints: string): void {
}
function applyPolicy(count: number): void {
const fileName = `step_policy_apply_${count}`;
cp.execSync(`echo "${fileName}" > "${getRunnerTempDir()}/${fileName}"`);
let applyPolicyStr = `step_policy_apply_${count}`;
echo(applyPolicyStr);
}
export function removeStepPolicyFiles() {
cp.execSync(`rm ${getRunnerTempDir()}/step_policy_*`);
}
export function arcCleanUp() {
cp.execSync(`echo "cleanup" > "${getRunnerTempDir()}/step_policy_cleanup"`);
function echo(content: string) {
cp.execFileSync("echo", [content]);
}

View file

@ -4,8 +4,8 @@ import * as fs from "fs";
const CHECKSUMS = {
tls: {
amd64: "0bd500769646f0a90c0dfe9ac59699d5165bed549a9870c031b861146af337b2", // v1.3.2
arm64: "c2448ac205fd90f46abba31c13cf34c3b997824881502f736315fb08ac0a5a5c",
amd64: "38e7ed97ced6fe0c1cf0fb5ee3b3d521dfe28d5ddf1cdca72d130c8d1b4a314e", // v1.4.2
arm64: "f67c80cc578c996d4f882c14fcdb63df57927d907cd22f1ec65f9fa940c08cf3",
},
non_tls: {
amd64: "a9f1842e3d7f3d38c143dbe8ffe1948e6c8173cd04da072d9f9d128bb400844a", // v0.13.7

View file

@ -2,8 +2,8 @@ import * as fs from "fs";
import * as cp from "child_process";
import * as common from "./common";
import isDocker from "is-docker";
import { arcCleanUp, isArcRunner, removeStepPolicyFiles } from "./arc-runner";
import { isArcRunner } from "./arc-runner";
import { isGithubHosted } from "./tls-inspect";
(async () => {
console.log("[harden-runner] post-step");
@ -11,15 +11,13 @@ import { arcCleanUp, isArcRunner, removeStepPolicyFiles } from "./arc-runner";
console.log(common.UBUNTU_MESSAGE);
return;
}
if (isDocker()) {
if (isGithubHosted() && isDocker()) {
console.log(common.CONTAINER_MESSAGE);
return;
}
if (isArcRunner()) {
console.log(`[!] ${common.ARC_RUNNER_MESSAGE}`);
arcCleanUp();
removeStepPolicyFiles();
return;
}
@ -84,11 +82,16 @@ import { arcCleanUp, isArcRunner, removeStepPolicyFiles } from "./arc-runner";
var disable_sudo = process.env.STATE_disableSudo;
if (disable_sudo !== "true") {
var journalLog = cp.execSync("sudo journalctl -u agent.service", {
encoding: "utf8",
});
console.log("Service log:");
console.log(journalLog);
try {
var journalLog = cp.execSync("sudo journalctl -u agent.service --lines=1000", {
encoding: "utf8",
maxBuffer: 1024 * 1024 * 10 // 10MB buffer
});
console.log("agent.service log:");
console.log(journalLog);
} catch (error) {
console.log("Warning: Could not fetch service logs:", error.message);
}
}
try {

View file

@ -2,7 +2,7 @@ import * as common from "./common";
import * as core from "@actions/core";
import isDocker from "is-docker";
import { STEPSECURITY_WEB_URL } from "./configs";
import { isGithubHosted } from "./tls-inspect";
(async () => {
console.log("[harden-runner] main-step");
@ -10,7 +10,7 @@ import { STEPSECURITY_WEB_URL } from "./configs";
console.log(common.UBUNTU_MESSAGE);
return;
}
if (isDocker()) {
if (isGithubHosted() && isDocker()) {
console.log(common.CONTAINER_MESSAGE);
return;
}

View file

@ -25,7 +25,7 @@ export async function installAgent(
if (isTLS) {
downloadPath = await tc.downloadTool(
`https://packages.stepsecurity.io/github-hosted/harden-runner_1.3.2_linux_${variant}.tar.gz`
`https://packages.stepsecurity.io/github-hosted/harden-runner_1.4.2_linux_${variant}.tar.gz`
);
} else {
if (variant === "arm64") {

View file

@ -39,7 +39,7 @@ interface MonitorResponse {
console.log(common.UBUNTU_MESSAGE);
return;
}
if (isDocker()) {
if (isGithubHosted() && isDocker()) {
console.log(common.CONTAINER_MESSAGE);
return;
}
@ -165,8 +165,9 @@ interface MonitorResponse {
if (confg.egress_policy === "block") {
try {
if (process.env.USER) {
cp.execSync(`sudo chown -R ${process.env.USER} /home/agent`);
chownForFolder(process.env.USER, "/home/agent");
}
const confgStr = JSON.stringify(confg);
fs.writeFileSync("/home/agent/block_event.json", confgStr);
await sleep(5000);
@ -225,7 +226,7 @@ interface MonitorResponse {
const confgStr = JSON.stringify(confg);
cp.execSync("sudo mkdir -p /home/agent");
cp.execSync("sudo chown -R $USER /home/agent");
chownForFolder(process.env.USER, "/home/agent");
let isTLS = await isTLSEnabled(context.repo.owner);
@ -269,3 +270,9 @@ export function sleep(ms) {
setTimeout(resolve, ms);
});
}
function chownForFolder(newOwner: string, target: string) {
let cmd = "sudo";
let args = ["chown", "-R", newOwner, target];
cp.execFileSync(cmd, args);
}