-
Notifications
You must be signed in to change notification settings - Fork 0
248 lines (210 loc) · 16.6 KB
/
secrets-detection-pull-request.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
name: Secrets detection in pull requests
on:
repository_dispatch:
types: [secrets_detection_in_pull_request]
jobs:
secrets-detection:
if: ${{ github.event.client_payload.event.pull_request && contains(fromJSON('["opened", "synchronize", "reopened"]'), github.event.client_payload.event.action) }}
runs-on: ubuntu-latest
steps:
- name: Set environment variables
id: set-environment-variables
run: |
SCAN_UUID=$(uuidgen -r | tr '[:upper:]' '[:lower:]')
REPOSITORY_SCAN_UUID=$(uuidgen -r | tr '[:upper:]' '[:lower:]')
echo "SCAN_UUID=$SCAN_UUID" >> "$GITHUB_ENV"
echo "REPOSITORY_SCAN_UUID=$REPOSITORY_SCAN_UUID" >> "$GITHUB_ENV"
echo "SCAN_REPORT_FILE=$SCAN_UUID.json" >> "$GITHUB_ENV"
- name: Checkout scanning repository
id: checkout-scanning-repository
uses: actions/checkout@v4
with:
path: scanning-repository
- name: Checkout repository
id: checkout-repository
uses: actions/checkout@v4
with:
repository: ${{ github.event.client_payload.event.repository.full_name }}
token: ${{ secrets.ORG_TOKEN }}
fetch-depth: 0
path: repository
- name: Fetch information about repository
id: fetch-information-for-repository
working-directory: "${{ github.workspace }}/repository"
run: |
echo "Repository to scan: ${{ github.event.client_payload.event.repository.name }}"
CURRENT_BRANCH="${{ github.event.client_payload.event.pull_request.head }}"
BASE_BRANCH="${{ github.event.client_payload.event.pull_request.base }}"
FIRST_COMMIT_OF_CURRENT_BRANCH="$(git merge-base origin/$BASE_BRANCH origin/$CURRENT_BRANCH)"
echo "Current branch: $CURRENT_BRANCH"
echo "Base branch: $BASE_BRANCH"
echo "First commit of current branch: $FIRST_COMMIT_OF_CURRENT_BRANCH"
echo "CURRENT_BRANCH=$CURRENT_BRANCH" >> $GITHUB_ENV
echo "FIRST_COMMIT_OF_CURRENT_BRANCH=$FIRST_COMMIT_OF_CURRENT_BRANCH" >> $GITHUB_ENV
- name: Check for custom detectors config file
id: check-config
continue-on-error: true
if: ${{ vars.CUSTOM_DETECTORS_CONFIG_FILE != '' }}
run: |
custom_detectors_config_file_full_path="${GITHUB_WORKSPACE}/scanning-repository/${{ vars.CUSTOM_DETECTORS_CONFIG_FILE }}"
if [ -f "$custom_detectors_config_file_full_path" ]; then
echo "Custom detectors config file found: $custom_detectors_config_file_full_path"
echo "custom_config=$custom_detectors_config_file_full_path" >> $GITHUB_OUTPUT
else
echo "Custom detectors config file not found. Using default configuration."
echo "custom_config=" >> $GITHUB_OUTPUT
- name: Perform secrets detection
id: scan
timeout-minutes: ${{ vars.SCAN_TIMEOUT_MINUTES || 15 }}
continue-on-error: true
working-directory: "${{ github.workspace }}/repository"
run: |
set +e
start=$(date -u +"%Y-%m-%dT%H:%M:%S.%6N")
if [ -n "${{ steps.check-config.outputs.custom_config }}" ]; then
docker run --name secrets-finder -v "$(pwd):/repository" -v "${{ steps.check-config.outputs.custom_config }}:/configuration.yaml" -i ghcr.io/trufflesecurity/trufflehog@sha256:62d6e889cc2f647321617dcd9142b23f5ee7a577754c9dce3f453263e333de01 git file:///repository --branch "$CURRENT_BRANCH" --since-commit "$FIRST_COMMIT_OF_CURRENT_BRANCH" --fail --json --no-update --config=/configuration.yaml $(if [ "${{ vars.REPORT_ONLY_VERIFIED_SECRETS }}" = "true" ]; then echo "--only-verified"; fi); exit_code=$?
else
docker run --name secrets-finder -v "$(pwd):/repository" -i ghcr.io/trufflesecurity/trufflehog@sha256:62d6e889cc2f647321617dcd9142b23f5ee7a577754c9dce3f453263e333de01 git file:///repository --branch "$CURRENT_BRANCH" --since-commit "$FIRST_COMMIT_OF_CURRENT_BRANCH" --fail --json --no-update $(if [ "${{ vars.REPORT_ONLY_VERIFIED_SECRETS }}" = "true" ]; then echo "--only-verified"; fi); exit_code=$?
fi
end=$(date -u +"%Y-%m-%dT%H:%M:%S.%6N")
echo "exit_code=$exit_code" >> $GITHUB_OUTPUT
echo "start=$start" >> $GITHUB_OUTPUT
echo "end=$end" >> $GITHUB_OUTPUT
exit $exit_code
- name: Retrieve logs from container
id: retrieve-logs-container
continue-on-error: true
if: ${{ always() && steps.scan.outcome == 'failure' }}
run: |
docker logs secrets-finder | jq -s '[.[] | select(has("SourceMetadata"))] | unique' > $SCAN_REPORT_FILE
FOUND_SECRETS=$(jq 'length > 0' $SCAN_REPORT_FILE)
echo "found_secrets=$FOUND_SECRETS" >> $GITHUB_OUTPUT
- name: Remove container
id: remove-container
continue-on-error: true
run: |
docker rm secrets-finder
docker images | grep ghcr.io/trufflesecurity/trufflehog | awk '{print $3}' | xargs docker rmi
- name: Change repository visibility (if needed)
id: change-repo-visibility
if: ${{ always() && steps.scan.outcome == 'failure' && steps.retrieve-logs-container.outputs.found_secrets == 'true' && vars.HIDE_PUBLIC_REPOSITORIES_IF_SECRETS_FOUND == 'true' && github.event.client_payload.event.repository.visibility == 'public' }}
continue-on-error: true
run: |
echo "Findings found. Changing repository visibility to private."
curl -X PATCH -H "Authorization: token ${{ secrets.ORG_TOKEN }}" -H "Accept: application/vnd.github.nebula-preview+json" https://api.github.com/repos/${{ github.event.client_payload.event.repository.full_name }} -d '{"visibility": "private"}' &>/dev/null
- name: Push a review in the pull request if secrets have been detected
id: ask-for-review-if-secrets-detected
if: ${{ always() && steps.scan.outcome == 'failure' && steps.retrieve-logs-container.outputs.found_secrets == 'true' && ((steps.change-repo-visibility.outcome == 'success') || (github.event.client_payload.event.repository.visibility != 'public')) }}
continue-on-error: true
uses: actions/github-script@v7
with:
github-token: ${{ secrets.ORG_TOKEN }}
script: |
const fs = require('fs');
const path = require('path');
const call_api_with_retry_logic = require(path.join(process.env.GITHUB_WORKSPACE, 'scanning-repository', '.github', 'workflows', 'api.js'));
const SCAN_REPORT_FILE_CONTENT = fs.readFileSync('${{ env.SCAN_REPORT_FILE }}');
const SECRETS = JSON.parse(SCAN_REPORT_FILE_CONTENT);
const DEFAULT_VALUE = "N/A";
const LIST_OF_FINDINGS = SECRETS.map((entry, index) => {
const detector = entry.DetectorName || DEFAULT_VALUE;
const { email, commit, file, line } = entry.SourceMetadata?.Data?.Git ?? {};
const commitLink = commit ? `[${commit.substring(0, 7)}](${{ github.server_url }}/${{ github.event.client_payload.event.repository.full_name }}/commit/${commit})` : DEFAULT_VALUE;
const fileLink = file ? `[${file}](${{ github.server_url }}/${{ github.event.client_payload.event.repository.full_name }}/blob/${commit}/${ encodeURI(file) }?plain=1#L${ line })` : DEFAULT_VALUE;
return `**Finding ${index + 1}**\n`
+ `> **Type**\n ${detector}\n`
+ `> \n`
+ `> **Author**\n ${email ? email : DEFAULT_VALUE}\n`
+ `> \n`
+ `> **Commit**\n ${commitLink}\n`
+ `> \n`
+ `> **File**\n ${fileLink}\n\n`;
});
const issue = `# ⚠️ WARNING: SECRET${SECRETS.length > 1 ? 'S' : ''} FOUND IN PULL REQUEST
### ${SECRETS.length > 1 ? 'S' : 'A s'}ecret${SECRETS.length > 1 ? 's have' : ' has'} been found in this pull request.
<br/><br/>
## FINDINGS
${LIST_OF_FINDINGS.join('<br/>\n\n')}
You can find more information in the workflow run that generated this report:\\
${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
<br/><br/>
## REMEDIATION PROCEDURE
- You **MUST** rotate the credentials that were stored in plain text. Assume they have already been compromised.
- You **MUST** move the new credentials to an approved secrets management service and pattern.
- You **SHOULD** clear the plaintext secrets from Git history.
<br/><br/>
To clean-up your Git history, you can use the following guidance:
- [Removing Sensitive Data - GitHub](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository)
<br/><br/>
You can also find more information about how to rotate your secrets here:
https://howtorotate.com/docs/introduction/getting-started/
<br/><br/>
## INFORMATION
ℹ️ Upon completion of the remediation process, you can disregard this request for change and proceed with merging the pull request.`
const { data } = await call_api_with_retry_logic(() => github.rest.pulls.createReview({
owner: "${{ github.event.client_payload.event.repository.owner }}",
repo: "${{ github.event.client_payload.event.repository.name }}",
pull_number: "${{ github.event.client_payload.event.pull_request.number }}",
body: issue,
event: "REQUEST_CHANGES"
}));
console.log(`New review created in pull request: ${ data.html_url }`);
- name: Add 'leaked-secrets' label when secrets are found
id: add-label-to-pull-request
if: ${{ always() && steps.scan.outcome == 'failure' && steps.retrieve-logs-container.outputs.found_secrets == 'true' && steps.ask-for-review-if-secrets-detected.outcome == 'success' }}
continue-on-error: true
uses: actions/github-script@v7
with:
github-token: ${{ secrets.ORG_TOKEN }}
retries: 3
script: |
const path = require('path');
const call_api_with_retry_logic = require(path.join(process.env.GITHUB_WORKSPACE, 'scanning-repository', '.github', 'workflows', 'api.js'));
await call_api_with_retry_logic(() => github.rest.issues.addLabels({
owner: "${{ github.event.client_payload.event.repository.owner }}",
repo: "${{ github.event.client_payload.event.repository.name }}",
issue_number: "${{ github.event.client_payload.event.pull_request.number }}",
labels: ['leaked-secrets']
}));
- name: Display findings
id: display-findings
continue-on-error: true
if: ${{ always() && steps.scan.outcome == 'failure' && steps.retrieve-logs-container.outputs.found_secrets == 'true' && vars.DEBUG == 'true' }}
run: cat $SCAN_REPORT_FILE
- name: Generate final report
id: generate-final-report
if: ${{ always() }}
run: |
TMP_FILE=$(mktemp)
if [[ "${{ steps.scan.outcome }}" == "skipped" ]] || [[ "${{ steps.retrieve-logs-container.outcome }}" == "failure" ]]; then
jq -n '{ "scan_type": "prevention", "start": "${{ steps.scan.outputs.start || 'N/A' }}", "end": "${{ steps.scan.outputs.end || 'N/A' }}", "status": "failure", "scan_context": "pull_request", "scan_mode": "${{ vars.REPORT_ONLY_VERIFIED_SECRETS == 'true' && 'verified' || 'all' }}", "scan_uuid": "${{ env.SCAN_UUID }}", "scan_identifier": "github_secrets_finder", "scm": "github", "results": [ { "scan_uuid": "${{ env.REPOSITORY_SCAN_UUID }}", "start": "${{ steps.scan.outputs.start || 'N/A' }}", "end": "${{ steps.scan.outputs.end || 'N/A' }}", "organization": "${{ github.event.client_payload.event.repository.owner }}", "repository": "${{ github.event.client_payload.event.repository.name }}", "status": "failure", "metadata": { "identifier": "${{ github.event.client_payload.event.pull_request.number }}", "created_at": "${{ github.event.client_payload.event.pull_request.created_at }}" }, "findings": [] } ] }' > "$TMP_FILE"
else
if [[ "${{ steps.scan.outcome }}" == "failure" ]]; then
if [[ "${{ steps.scan.outputs.exit_code }}" == "183" ]]; then
cat $SCAN_REPORT_FILE | jq -c '{ "scan_type": "prevention", "start": "${{ steps.scan.outputs.start }}", "end": "${{ steps.scan.outputs.end }}", "status": "success", "scan_context": "pull_request", "scan_mode": "${{ vars.REPORT_ONLY_VERIFIED_SECRETS == 'true' && 'verified' || 'all' }}", "scan_uuid": "${{ env.SCAN_UUID }}", "scan_identifier": "github_secrets_finder", "scm": "github", "results": [{ "scan_uuid": "${{ env.REPOSITORY_SCAN_UUID }}", "start": "${{ steps.scan.outputs.start || 'N/A' }}", "end": "${{ steps.scan.outputs.end || 'N/A' }}", "organization": "${{ github.event.client_payload.event.repository.owner }}", "repository": "${{ github.event.client_payload.event.repository.name }}", "status": "success", "metadata": { "identifier": "${{ github.event.client_payload.event.pull_request.number }}", "created_at": "${{ github.event.client_payload.event.pull_request.created_at }}" }, "findings": . }] }' > "$TMP_FILE"
else
jq -n '{ "scan_type": "prevention", "start": "${{ steps.scan.outputs.start || 'N/A' }}", "end": "${{ steps.scan.outputs.end || 'N/A' }}", "status": "failure", "scan_mode": "${{ vars.REPORT_ONLY_VERIFIED_SECRETS == 'true' && 'verified' || 'all' }}", "scan_context": "pull_request", "scan_uuid": "${{ env.SCAN_UUID }}", "scan_identifier": "github_secrets_finder", "scm": "github", "results": [ { "scan_uuid": "${{ env.REPOSITORY_SCAN_UUID }}", "start": "${{ steps.scan.outputs.start || 'N/A' }}", "end": "${{ steps.scan.outputs.end || 'N/A' }}", "organization": "${{ github.event.client_payload.event.repository.owner }}", "repository": "${{ github.event.client_payload.event.repository.name }}", "status": "failure", "metadata": { "identifier": "${{ github.event.client_payload.event.pull_request.number }}", "created_at": "${{ github.event.client_payload.event.pull_request.created_at }}" }, "findings": [] } ] }' > "$TMP_FILE"
fi
else
jq -n '{ "scan_type": "prevention", "start": "${{ steps.scan.outputs.start }}", "end": "${{ steps.scan.outputs.end }}", "status": "success", "scan_mode": "${{ vars.REPORT_ONLY_VERIFIED_SECRETS == 'true' && 'verified' || 'all' }}", "scan_context": "pull_request", "scan_uuid": "${{ env.SCAN_UUID }}", "scan_identifier": "github_secrets_finder", "scm": "github", "results": [{ "scan_uuid": "${{ env.REPOSITORY_SCAN_UUID }}", "start": "${{ steps.scan.outputs.start || 'N/A' }}", "end": "${{ steps.scan.outputs.end || 'N/A' }}", "organization": "${{ github.event.client_payload.event.repository.owner }}", "repository": "${{ github.event.client_payload.event.repository.name }}", "status": "success", "metadata": { "identifier": "${{ github.event.client_payload.event.pull_request.number }}", "created_at": "${{ github.event.client_payload.event.pull_request.created_at }}" }, "findings": [ { "scan_uuid": "$REPOSITORY_SCAN_UUID", organization: "${{ github.event.client_payload.event.repository.owner }}", "repository": "${{ github.event.client_payload.event.repository.name }}", "status": "failure", "metadata": { "identifier": "${{ github.event.client_payload.event.pull_request.number }}", "created_at": "${{ github.event.client_payload.event.pull_request.created_at }}" }, "findings": [] } ] }] }' > "$TMP_FILE"
fi
fi
mv "$TMP_FILE" "$SCAN_REPORT_FILE"
- name: Configure AWS credentials
id: configure-aws-credentials
if: ${{ always() }}
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
role-to-assume: ${{ vars.AWS_ROLE_ARN }}
role-session-name: SecretsFinderOngoingScanGitHub
role-skip-session-tagging: true
role-duration-seconds: 3600
- name: Send findings to S3 bucket
id: send-findings-to-s3-bucket
if: ${{ always() && steps.configure-aws-credentials.outcome == 'success' }}
run: |
CURRENT_DATE="$(date +"%Y%m%d")"
aws s3 cp $SCAN_REPORT_FILE s3://${{ vars.AWS_S3_BUCKET_NAME }}/secrets-finder/ongoing-scans/results/