Skip to content

Commit ed9a44e

Browse files
abdullahkhawerAbdullah Khawer
authored and
Abdullah Khawer
committedJun 6, 2024
feat!: Develop a solution which can be executed on any macOS or Linux system either locally or on a remote server or via a CI/CD pipeline that finds secrets in a git repository using Gitleaks, generates a JSON report based on the findings from Gitleaks by extracting only the relevant information, finds the commit id and commit author for each finding, updates an Atlassian Confluence page with the secrets found based on that generated report and finally sends an alert on Slack.
0 parents  commit ed9a44e

File tree

13 files changed

+942
-0
lines changed

13 files changed

+942
-0
lines changed
 

‎.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
gitleaks-report.json
2+
gitleaks-report-detailed.json
3+
temp.json

‎.gitleaks.toml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Title for the gitleaks configuration file.
2+
title = "Custom Gitleaks Config"
3+
4+
[extend]
5+
# useDefault will extend the base configuration with the default gitleaks config:
6+
# https://github.com/zricethezav/gitleaks/blob/master/config/gitleaks.toml
7+
useDefault = true
8+
9+
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
10+
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
11+
# secrets will be detected for said commit. The same logic applies for regexes and paths.
12+
[allowlist]
13+
description = "Global allowlisted paths, regexes and stopwords"
14+
paths = [
15+
'''\.gitleaks\.toml''',
16+
'''\.gitleaks\.toml''',
17+
'''gitleaks-report-detailed.json''',
18+
'''gitleaks-report.json'''
19+
]
20+
21+
regexTarget = "match"
22+
23+
regexes = []
24+
25+
stopwords = []

‎CHANGELOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Changelog
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
6+
## [1.0.0] - 2024-07-05
7+
8+
[1.0.0]: https://github.com/abdullahkhawer/find-and-report-secrets-in-code/releases/tag/v1.0.0
9+
10+
### Features
11+
12+
- Develop a Python script and a Shell script to find secrets in a git repository using Gitleaks and to add the fingerprints and descriptions of the found secrets on an Atlassian Confluence page.

‎LICENSE

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction,
10+
and distribution as defined by Sections 1 through 9 of this document.
11+
12+
"Licensor" shall mean the copyright owner or entity authorized by
13+
the copyright owner that is granting the License.
14+
15+
"Legal Entity" shall mean the union of the acting entity and all
16+
other entities that control, are controlled by, or are under common
17+
control with that entity. For the purposes of this definition,
18+
"control" means (i) the power, direct or indirect, to cause the
19+
direction or management of such entity, whether by contract or
20+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+
outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+
"You" (or "Your") shall mean an individual or Legal Entity
24+
exercising permissions granted by this License.
25+
26+
"Source" form shall mean the preferred form for making modifications,
27+
including but not limited to software source code, documentation
28+
source, and configuration files.
29+
30+
"Object" form shall mean any form resulting from mechanical
31+
transformation or translation of a Source form, including but
32+
not limited to compiled object code, generated documentation,
33+
and conversions to other media types.
34+
35+
"Work" shall mean the work of authorship, whether in Source or
36+
Object form, made available under the License, as indicated by a
37+
copyright notice that is included in or attached to the work
38+
(an example is provided in the Appendix below).
39+
40+
"Derivative Works" shall mean any work, whether in Source or Object
41+
form, that is based on (or derived from) the Work and for which the
42+
editorial revisions, annotations, elaborations, or other modifications
43+
represent, as a whole, an original work of authorship. For the purposes
44+
of this License, Derivative Works shall not include works that remain
45+
separable from, or merely link (or bind by name) to the interfaces of,
46+
the Work and Derivative Works thereof.
47+
48+
"Contribution" shall mean any work of authorship, including
49+
the original version of the Work and any modifications or additions
50+
to that Work or Derivative Works thereof, that is intentionally
51+
submitted to Licensor for inclusion in the Work by the copyright owner
52+
or by an individual or Legal Entity authorized to submit on behalf of
53+
the copyright owner. For the purposes of this definition, "submitted"
54+
means any form of electronic, verbal, or written communication sent
55+
to the Licensor or its representatives, including but not limited to
56+
communication on electronic mailing lists, source code control systems,
57+
and issue tracking systems that are managed by, or on behalf of, the
58+
Licensor for the purpose of discussing and improving the Work, but
59+
excluding communication that is conspicuously marked or otherwise
60+
designated in writing by the copyright owner as "Not a Contribution."
61+
62+
"Contributor" shall mean Licensor and any individual or Legal Entity
63+
on behalf of whom a Contribution has been received by Licensor and
64+
subsequently incorporated within the Work.
65+
66+
2. Grant of Copyright License. Subject to the terms and conditions of
67+
this License, each Contributor hereby grants to You a perpetual,
68+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+
copyright license to reproduce, prepare Derivative Works of,
70+
publicly display, publicly perform, sublicense, and distribute the
71+
Work and such Derivative Works in Source or Object form.
72+
73+
3. Grant of Patent License. Subject to the terms and conditions of
74+
this License, each Contributor hereby grants to You a perpetual,
75+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+
(except as stated in this section) patent license to make, have made,
77+
use, offer to sell, sell, import, and otherwise transfer the Work,
78+
where such license applies only to those patent claims licensable
79+
by such Contributor that are necessarily infringed by their
80+
Contribution(s) alone or by combination of their Contribution(s)
81+
with the Work to which such Contribution(s) was submitted. If You
82+
institute patent litigation against any entity (including a
83+
cross-claim or counterclaim in a lawsuit) alleging that the Work
84+
or a Contribution incorporated within the Work constitutes direct
85+
or contributory patent infringement, then any patent licenses
86+
granted to You under this License for that Work shall terminate
87+
as of the date such litigation is filed.
88+
89+
4. Redistribution. You may reproduce and distribute copies of the
90+
Work or Derivative Works thereof in any medium, with or without
91+
modifications, and in Source or Object form, provided that You
92+
meet the following conditions:
93+
94+
(a) You must give any other recipients of the Work or
95+
Derivative Works a copy of this License; and
96+
97+
(b) You must cause any modified files to carry prominent notices
98+
stating that You changed the files; and
99+
100+
(c) You must retain, in the Source form of any Derivative Works
101+
that You distribute, all copyright, patent, trademark, and
102+
attribution notices from the Source form of the Work,
103+
excluding those notices that do not pertain to any part of
104+
the Derivative Works; and
105+
106+
(d) If the Work includes a "NOTICE" text file as part of its
107+
distribution, then any Derivative Works that You distribute must
108+
include a readable copy of the attribution notices contained
109+
within such NOTICE file, excluding those notices that do not
110+
pertain to any part of the Derivative Works, in at least one
111+
of the following places: within a NOTICE text file distributed
112+
as part of the Derivative Works; within the Source form or
113+
documentation, if provided along with the Derivative Works; or,
114+
within a display generated by the Derivative Works, if and
115+
wherever such third-party notices normally appear. The contents
116+
of the NOTICE file are for informational purposes only and
117+
do not modify the License. You may add Your own attribution
118+
notices within Derivative Works that You distribute, alongside
119+
or as an addendum to the NOTICE text from the Work, provided
120+
that such additional attribution notices cannot be construed
121+
as modifying the License.
122+
123+
You may add Your own copyright statement to Your modifications and
124+
may provide additional or different license terms and conditions
125+
for use, reproduction, or distribution of Your modifications, or
126+
for any such Derivative Works as a whole, provided Your use,
127+
reproduction, and distribution of the Work otherwise complies with
128+
the conditions stated in this License.
129+
130+
5. Submission of Contributions. Unless You explicitly state otherwise,
131+
any Contribution intentionally submitted for inclusion in the Work
132+
by You to the Licensor shall be under the terms and conditions of
133+
this License, without any additional terms or conditions.
134+
Notwithstanding the above, nothing herein shall supersede or modify
135+
the terms of any separate license agreement you may have executed
136+
with Licensor regarding such Contributions.
137+
138+
6. Trademarks. This License does not grant permission to use the trade
139+
names, trademarks, service marks, or product names of the Licensor,
140+
except as required for reasonable and customary use in describing the
141+
origin of the Work and reproducing the content of the NOTICE file.
142+
143+
7. Disclaimer of Warranty. Unless required by applicable law or
144+
agreed to in writing, Licensor provides the Work (and each
145+
Contributor provides its Contributions) on an "AS IS" BASIS,
146+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+
implied, including, without limitation, any warranties or conditions
148+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+
PARTICULAR PURPOSE. You are solely responsible for determining the
150+
appropriateness of using or redistributing the Work and assume any
151+
risks associated with Your exercise of permissions under this License.
152+
153+
8. Limitation of Liability. In no event and under no legal theory,
154+
whether in tort (including negligence), contract, or otherwise,
155+
unless required by applicable law (such as deliberate and grossly
156+
negligent acts) or agreed to in writing, shall any Contributor be
157+
liable to You for damages, including any direct, indirect, special,
158+
incidental, or consequential damages of any character arising as a
159+
result of this License or out of the use or inability to use the
160+
Work (including but not limited to damages for loss of goodwill,
161+
work stoppage, computer failure or malfunction, or any and all
162+
other commercial damages or losses), even if such Contributor
163+
has been advised of the possibility of such damages.
164+
165+
9. Accepting Warranty or Additional Liability. While redistributing
166+
the Work or Derivative Works thereof, You may choose to offer,
167+
and charge a fee for, acceptance of support, warranty, indemnity,
168+
or other liability obligations and/or rights consistent with this
169+
License. However, in accepting such obligations, You may act only
170+
on Your own behalf and on Your sole responsibility, not on behalf
171+
of any other Contributor, and only if You agree to indemnify,
172+
defend, and hold each Contributor harmless for any liability
173+
incurred by, or claims asserted against, such Contributor by reason
174+
of your accepting any such warranty or additional liability.
175+
176+
END OF TERMS AND CONDITIONS
177+
178+
APPENDIX: How to apply the Apache License to your work.
179+
180+
To apply the Apache License to your work, attach the following
181+
boilerplate notice, with the fields enclosed by brackets "[]"
182+
replaced with your own identifying information. (Don't include
183+
the brackets!) The text should be enclosed in the appropriate
184+
comment syntax for the file format. We also recommend that a
185+
file or class name and description of purpose be included on the
186+
same "printed page" as the copyright notice for easier
187+
identification within third-party archives.
188+
189+
Copyright [yyyy] [name of copyright owner]
190+
191+
Licensed under the Apache License, Version 2.0 (the "License");
192+
you may not use this file except in compliance with the License.
193+
You may obtain a copy of the License at
194+
195+
http://www.apache.org/licenses/LICENSE-2.0
196+
197+
Unless required by applicable law or agreed to in writing, software
198+
distributed under the License is distributed on an "AS IS" BASIS,
199+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+
See the License for the specific language governing permissions and
201+
limitations under the License.

‎README.md

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
# Find and Report Secrets in Code
2+
3+
- Founder: Abdullah Khawer (LinkedIn: https://www.linkedin.com/in/abdullah-khawer/)
4+
5+
# Introduction
6+
7+
A security solution that finds secrets in a git repository using Gitleaks, generates a JSON report based on the findings from Gitleaks by extracting only the relevant information, finds the commit id and commit author for each finding, updates an Atlassian Confluence page with the secrets found based on that generated report and finally sends an alert on Slack.
8+
9+
❓ Where I can run this?
10+
11+
👉🏻 This solution can be executed on any macOS or Linux system either locally or on a remote server. It can also be executed on a CI/CD pipeline.
12+
13+
Below you can find an example of the JSON report generated:
14+
15+
```json
16+
[
17+
{
18+
"Description": "Identified a HashiCorp Terraform password field, risking unauthorized infrastructure configuration and security breaches.",
19+
"File": "./code/main.py",
20+
"Line No.": "11",
21+
"Secret Type": "hashicorp-tf-password",
22+
"Commit": "__REDACTED__",
23+
"Author": "__REDACTED__"
24+
},
25+
{
26+
"Description": "Identified a HashiCorp Terraform password field, risking unauthorized infrastructure configuration and security breaches.",
27+
"File": "./code/main.conf",
28+
"Line No.": "30",
29+
"Secret Type": "hashicorp-tf-password",
30+
"Commit": "__REDACTED__",
31+
"Author": "__REDACTED__"
32+
}
33+
]
34+
```
35+
36+
Note: In the actual execution, you will see the actual values instead of `__REDACTED__` values.
37+
38+
Below you can find an example of the Slack notification:
39+
40+
![image](https://github.com/abdullahkhawer/find-and-report-secrets-in-code/assets/27900716/fc798318-7373-4437-a205-4d71065fb2f7)
41+
42+
# Usage Notes
43+
44+
## Manually on a Local or Remote Server
45+
46+
### Prerequisites
47+
48+
Following are the prerequisites to be met once before you begin:
49+
50+
- Following packages are installed on your system:
51+
- In case of Linux, install the following packages using either `./installation/linux_install_packages.sh` script or manually:
52+
- `git`
53+
- `jq`
54+
- `bash`
55+
- `make`
56+
- `wget`
57+
- `python3`
58+
- `py3-pip`
59+
- `golang`
60+
- `gitleaks`
61+
- `atlassian-python-api`
62+
- Using `pip`
63+
- `pytz`
64+
- Using `pip`
65+
- `requests`
66+
- Using `pip`
67+
- In case of macOS, install the following packages using either `./installation/macos_install_packages.sh` script or manually:
68+
- `git`
69+
- `jq`
70+
- `bash`
71+
- `python`
72+
- `python@3`
73+
- `gitleaks`
74+
- `atlassian-python-api`
75+
- Using `pip`
76+
- `pytz`
77+
- Using `pip`
78+
- `requests`
79+
- Using `pip`
80+
81+
### Execution Instructions
82+
83+
Once all the prerequisites are met, set the following environment variables:
84+
- `PATH_TO_GIT_REPO`
85+
- Description: To keep the size of the git repository to be cloned lower to make the job faster.
86+
- Example: `/Users/Abdullah.Khawer/Desktop/myrepo`
87+
- Requirement: REQUIRED
88+
- `CONFLUENCE_ENABLED`
89+
- Description: Whether to enable reporting on Atlassian Confluence or not.
90+
- Example: `1`
91+
- Requirement: REQUIRED
92+
- Possible Values: `1` or `0`
93+
- `CONFLUENCE_SITE`
94+
- Description: Atlassian Confluence host link.
95+
- Example: `https://mydomain.atlassian.net`
96+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
97+
- `CONFLUENCE_USER_EMAIL_ID`
98+
- Description: Atlassian Confluence user email ID.
99+
- Example: `myname@mydomain.com`
100+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
101+
- `CONFLUENCE_USER_TOKEN`
102+
- Description: Atlassian Confluence user token.
103+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
104+
- `CONFLUENCE_PAGE_TITLE`
105+
- Description: Atlassian Confluence page title.
106+
- Example: `Secrets Detected in the Git Repositories`
107+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
108+
- `CONFLUENCE_PAGE_SPACE`
109+
- Description: Atlassian Confluence page space.
110+
- Example: `docs`
111+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
112+
- `SLACK_ENABLED`
113+
- Description: Whether to enable notifications on Slack or not.
114+
- Example: `1`
115+
- Requirement: REQUIRED
116+
- Possible Values: `1` or `0`
117+
- `SLACK_WEBHOOK_URL`
118+
- Description: Slack Webhook URL.
119+
- Example: `[https://mydomain.atlassian.net](https://hooks.slack.com/services/__REDACTED__/__REDACTED__/__REDACTED__)`
120+
- Requirement: REQUIRED (if `SLACK_ENABLED` is set to `1`)
121+
122+
And then simply run the following 3 commands in the correct order:
123+
- `bash gitleaks.sh`
124+
- `python3 main.py TIME_ZONE REPOSITORY_NAME BRANCH_NAME [JSON_REPORT_URL]`
125+
- Example: `python3 main.py Europe/Amsterdam myproj/myrepo master`
126+
- Note: Details about supported time zones and their constant names can be found here: [pypi.org > project > pytz > Helpers](https://pypi.org/project/pytz/#:~:text=through%20multiple%20timezones.-,Helpers,-There%20are%20two)
127+
128+
## Automatically via CI/CD Pipeline
129+
130+
### Setup Instructions
131+
132+
In order to run it on any GitLab repository, add the following in the `.gitlab-ci.yml` file that is in the repository:
133+
134+
```
135+
include:
136+
- remote: 'https://raw.githubusercontent.com/abdullahkhawer/find-and-report-secrets-in-code/master/ci/.gitlab-ci.yml'
137+
138+
stages:
139+
- scan
140+
141+
secrets_detection:
142+
stage: scan
143+
extends:
144+
- .find-secrets:scan
145+
variables:
146+
CONFLUENCE_ENABLED: "1"
147+
CONFLUENCE_SITE: $CONFLUENCE_SITE
148+
CONFLUENCE_USER_EMAIL_ID: $CONFLUENCE_USER_EMAIL_ID
149+
CONFLUENCE_USER_TOKEN: $CONFLUENCE_USER_TOKEN
150+
CONFLUENCE_PAGE_TITLE: $CONFLUENCE_PAGE_TITLE
151+
CONFLUENCE_PAGE_SPACE: $CONFLUENCE_PAGE_SPACE
152+
SLACK_ENABLED: "1"
153+
SLACK_WEBHOOK_URL: $SLACK_WEBHOOK_URL
154+
retry:
155+
max: 2
156+
rules:
157+
- if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_NAME == "master"
158+
when: always
159+
allow_failure: false
160+
```
161+
162+
In the `rules` section, you specify rules for execution as `if` conditions. In the above example, the job is only allowed to execute if it is a scheduled job for the `master` branch.
163+
164+
The variables referred using `$` are supposed to be created on the repository under `CI/CD Settings` page.
165+
166+
The image used in this GitLab CI job is built using the Dockerfile that is present in this repository here: https://github.com/abdullahkhawer/find-and-report-secrets-in-code/tree/master/docker
167+
168+
The image used is publicly available here: https://hub.docker.com/r/abdullahkhawer/find-and-report-secrets-in-code/
169+
170+
## Notes
171+
172+
- A sample Gitleaks configuration file can be found here if interested in using it: `.gitleaks.toml`
173+
- The Atlassian user should have access to the Confluence app, the `View` and `Add` permissions in the space on it and the `Can edit` permission on the page in that space. Also, you need to create an API token as the password won't work.
174+
175+
#### Any contributions, improvements and suggestions will be highly appreciated. 😊

‎VERSION

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
v1.0.0

‎ci/.gitlab-ci.yml

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# This job finds secrets in a git repository using Gitleaks, generates a JSON report based on the findings from Gitleaks
2+
# by extracting only the relevant information, finds the commit id and commit author for each finding, updates an Atlassian
3+
# Confluence page with the secrets found based on that generated report and finally sends an alert on Slack.
4+
5+
.find-secrets:variables:
6+
variables:
7+
# Whether to enable reporting on Atlassian Confluence or not
8+
CONFLUENCE_ENABLED: "0"
9+
# Atlassian Confluence host link (e.g., https://mydomain.atlassian.net)
10+
CONFLUENCE_SITE: ""
11+
# Atlassian Confluence user email ID (e.g., myname@mydomain.com)
12+
CONFLUENCE_USER_EMAIL_ID: ""
13+
# Atlassian Confluence user token
14+
CONFLUENCE_USER_TOKEN: ""
15+
# Atlassian Confluence page title (e.g., "Secrets Detected in the Git Repositories")
16+
CONFLUENCE_PAGE_TITLE: ""
17+
# Atlassian Confluence page space (e.g., docs)
18+
CONFLUENCE_PAGE_SPACE: ""
19+
# Whether to enable notifications on Slack or not
20+
SLACK_ENABLED: "0"
21+
# Slack Webhook URL (e.g., https://hooks.slack.com/services/__REDACTED__/__REDACTED__/__REDACTED__)
22+
SLACK_WEBHOOK_URL: ""
23+
24+
.find-secrets:scan:
25+
stage: scan
26+
extends:
27+
- .find-secrets:variables
28+
image: abdullahkhawer/find-and-report-secrets-in-code:1.0.0
29+
before_script:
30+
- |
31+
if [ -n "$CONFLUENCE_ENABLED" ] && [ "$CONFLUENCE_ENABLED" -eq 1 ]; then
32+
if [ -z "$CONFLUENCE_SITE" ]; then
33+
echo "CONFLUENCE_SITE is empty or null. Exiting with error."
34+
exit 1
35+
fi
36+
37+
if [ -z "$CONFLUENCE_USER_EMAIL_ID" ]; then
38+
echo "CONFLUENCE_USER_EMAIL_ID is empty or null. Exiting with error."
39+
exit 1
40+
fi
41+
42+
if [ -z "$CONFLUENCE_USER_TOKEN" ]; then
43+
echo "CONFLUENCE_USER_TOKEN is empty or null. Exiting with error."
44+
exit 1
45+
fi
46+
47+
if [ -z "$CONFLUENCE_PAGE_TITLE" ]; then
48+
echo "CONFLUENCE_PAGE_TITLE is empty or null. Exiting with error."
49+
exit 1
50+
fi
51+
52+
if [ -z "$CONFLUENCE_PAGE_SPACE" ]; then
53+
echo "CONFLUENCE_PAGE_SPACE is empty or null. Exiting with error."
54+
exit 1
55+
fi
56+
fi
57+
58+
if [ -n "$SLACK_ENABLED" ] && [ "$SLACK_ENABLED" -eq 1 ]; then
59+
if [ -z "$SLACK_WEBHOOK_URL" ]; then
60+
echo "SLACK_WEBHOOK_URL is empty or null. Exiting with error."
61+
exit 1
62+
fi
63+
fi
64+
- git fetch origin $CI_COMMIT_BRANCH
65+
script:
66+
- export PATH=$PATH:/usr/local/gitleaks
67+
- export PATH_TO_GIT_REPO=$(pwd)
68+
- export REPO_NAME=$(echo "$CI_PROJECT_DIR" | sed 's|/builds/||')
69+
- cd /find-and-report-secrets-in-code/
70+
- bash ./gitleaks.sh
71+
- python3 main.py "Europe/Amsterdam" $REPO_NAME $CI_COMMIT_BRANCH $CI_JOB_URL/artifacts/raw/gitleaks-report.json
72+
- cp ./gitleaks-report.json $PATH_TO_GIT_REPO/gitleaks-report.json
73+
artifacts:
74+
paths:
75+
- gitleaks-report.json

‎docker/Dockerfile

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FROM --platform=linux/amd64 alpine:3.20.0
2+
3+
COPY installation/linux_install_packages.sh .gitleaks.toml gitleaks.sh main.py ./find-and-report-secrets-in-code/
4+
5+
RUN sh ./find-and-report-secrets-in-code/linux_install_packages.sh

‎docker/README.md

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# Find and Report Secrets in Code
2+
3+
- Founder: Abdullah Khawer (LinkedIn: https://www.linkedin.com/in/abdullah-khawer/)
4+
5+
# Introduction
6+
7+
This repository has a Docker image that finds secrets in a git repository using Gitleaks, generates a JSON report based on the findings from Gitleaks by extracting only the relevant information, finds the commit id and commit author for each finding, updates an Atlassian Confluence page with the secrets found based on that generated report and finally sends an alert on Slack.
8+
9+
❓ Where I can run this?
10+
11+
👉🏻 This Docker image can be executed on any Windows, macOS or Linux system either locally or on a remote server. It can also be executed on a CI/CD pipeline.
12+
13+
Below you can find an example of the JSON report generated:
14+
15+
```json
16+
[
17+
{
18+
"Description": "Identified a HashiCorp Terraform password field, risking unauthorized infrastructure configuration and security breaches.",
19+
"File": "./code/main.py",
20+
"Line No.": "11",
21+
"Secret Type": "hashicorp-tf-password",
22+
"Commit": "__REDACTED__",
23+
"Author": "__REDACTED__"
24+
},
25+
{
26+
"Description": "Identified a HashiCorp Terraform password field, risking unauthorized infrastructure configuration and security breaches.",
27+
"File": "./code/main.conf",
28+
"Line No.": "30",
29+
"Secret Type": "hashicorp-tf-password",
30+
"Commit": "__REDACTED__",
31+
"Author": "__REDACTED__"
32+
}
33+
]
34+
```
35+
36+
Note: In the actual execution, you will see the actual values instead of `__REDACTED__` values.
37+
38+
Below you can find an example of the Slack notification:
39+
40+
![image](https://github.com/abdullahkhawer/find-and-report-secrets-in-code/assets/27900716/fc798318-7373-4437-a205-4d71065fb2f7)
41+
42+
# Usage Notes
43+
44+
## Manually on a Local or Remote Server
45+
46+
### Execution Instructions
47+
48+
Set the following environment variables:
49+
- `PATH_TO_GIT_REPO`
50+
- Description: To keep the size of the git repository to be cloned lower to make the job faster.
51+
- Example: `/Users/Abdullah.Khawer/Desktop/myrepo`
52+
- Requirement: REQUIRED
53+
- `CONFLUENCE_ENABLED`
54+
- Description: Whether to enable reporting on Atlassian Confluence or not.
55+
- Example: `1`
56+
- Requirement: REQUIRED
57+
- Possible Values: `1` or `0`
58+
- `CONFLUENCE_SITE`
59+
- Description: Atlassian Confluence host link.
60+
- Example: `https://mydomain.atlassian.net`
61+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
62+
- `CONFLUENCE_USER_EMAIL_ID`
63+
- Description: Atlassian Confluence user email ID.
64+
- Example: `myname@mydomain.com`
65+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
66+
- `CONFLUENCE_USER_TOKEN`
67+
- Description: Atlassian Confluence user token.
68+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
69+
- `CONFLUENCE_PAGE_TITLE`
70+
- Description: Atlassian Confluence page title.
71+
- Example: `Secrets Detected in the Git Repositories`
72+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
73+
- `CONFLUENCE_PAGE_SPACE`
74+
- Description: Atlassian Confluence page space.
75+
- Example: `docs`
76+
- Requirement: REQUIRED (if `CONFLUENCE_ENABLED` is set to `1`)
77+
- `SLACK_ENABLED`
78+
- Description: Whether to enable notifications on Slack or not.
79+
- Example: `1`
80+
- Requirement: REQUIRED
81+
- Possible Values: `1` or `0`
82+
- `SLACK_WEBHOOK_URL`
83+
- Description: Slack Webhook URL.
84+
- Example: `[https://mydomain.atlassian.net](https://hooks.slack.com/services/__REDACTED__/__REDACTED__/__REDACTED__)`
85+
- Requirement: REQUIRED (if `SLACK_ENABLED` is set to `1`)
86+
87+
And then simply run the following 4 commands:
88+
- `docker run --platform linux/amd64 -it -e PATH_TO_GIT_REPO=/git_repo -e CONFLUENCE_ENABLED=1 -e CONFLUENCE_SITE=$CONFLUENCE_SITE -e CONFLUENCE_USER_EMAIL_ID=$CONFLUENCE_USER_EMAIL_ID -e CONFLUENCE_USER_TOKEN=$CONFLUENCE_USER_TOKEN -e CONFLUENCE_PAGE_TITLE=$CONFLUENCE_PAGE_TITLE -e CONFLUENCE_PAGE_SPACE=$CONFLUENCE_PAGE_SPACE -e SLACK_ENABLED=1 -e SLACK_WEBHOOK_URL=$SLACK_WEBHOOK_URL -v $PATH_TO_GIT_REPO:/git_repo abdullahkhawer/find-and-report-secrets-in-code:latest`
89+
- `export PATH=$PATH:/usr/local/gitleaks`
90+
- `bash /find-and-report-secrets-in-code/gitleaks.sh`
91+
- `python3 /find-and-report-secrets-in-code/main.py TIME_ZONE REPOSITORY_NAME BRANCH_NAME [JSON_REPORT_URL]`
92+
- Example: `python3 /find-and-report-secrets-in-code/main.py Europe/Amsterdam myproj/myrepo master`
93+
- Note: Details about supported time zones and their constant names can be found here: [pypi.org > project > pytz > Helpers](https://pypi.org/project/pytz/#:~:text=through%20multiple%20timezones.-,Helpers,-There%20are%20two)
94+
95+
## Automatically via CI/CD Pipeline
96+
97+
### Setup Instructions
98+
99+
In order to run it on any GitLab repository, add the following in the `.gitlab-ci.yml` file that is in the repository:
100+
101+
```
102+
include:
103+
- remote: 'https://raw.githubusercontent.com/abdullahkhawer/find-and-report-secrets-in-code/master/ci/.gitlab-ci.yml'
104+
105+
stages:
106+
- scan
107+
108+
secrets_detection:
109+
stage: scan
110+
extends:
111+
- .find-secrets:scan
112+
variables:
113+
CONFLUENCE_ENABLED: "1"
114+
CONFLUENCE_SITE: $CONFLUENCE_SITE
115+
CONFLUENCE_USER_EMAIL_ID: $CONFLUENCE_USER_EMAIL_ID
116+
CONFLUENCE_USER_TOKEN: $CONFLUENCE_USER_TOKEN
117+
CONFLUENCE_PAGE_TITLE: $CONFLUENCE_PAGE_TITLE
118+
CONFLUENCE_PAGE_SPACE: $CONFLUENCE_PAGE_SPACE
119+
SLACK_ENABLED: "1"
120+
SLACK_WEBHOOK_URL: $SLACK_WEBHOOK_URL
121+
retry:
122+
max: 2
123+
rules:
124+
- if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_NAME == "master"
125+
when: always
126+
allow_failure: false
127+
```
128+
129+
In the `rules` section, you specify rules for execution as `if` conditions. In the above example, the job is only allowed to execute if it is a scheduled job for the `master` branch.
130+
131+
The variables referred using `$` are supposed to be created on the repository under `CI/CD Settings` page.
132+
133+
The image used in this GitLab CI job is built using the Dockerfile that is present in a repository here: `https://github.com/abdullahkhawer/find-and-report-secrets-in-code/blob/master/docker/Dockerfile`
134+
135+
The image used is this one which is publicly available.
136+
137+
## Notes
138+
139+
- A sample Gitleaks configuration file can be found here if interested in using it: `https://github.com/abdullahkhawer/find-and-report-secrets-in-code/blob/master/.gitleaks.toml`
140+
- The Atlassian user should have access to the Confluence app, the `View` and `Add` permissions in the space on it and the `Can edit` permission on the page in that space. Also, you need to create an API token as the password won't work.
141+
142+
For more details, check the following repository on GitHub: https://github.com/abdullahkhawer/find-and-report-secrets-in-code/
143+
144+
#### Any contributions, improvements and suggestions will be highly appreciated. 😊

‎gitleaks.sh

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/bin/bash
2+
3+
echo "Script Execution Started!"
4+
5+
# remove Gitleaks reports if they exist already
6+
echo "Removing Gitleaks reports if they exist already..."
7+
rm -rf ${PATH_TO_GIT_REPO}/gitleaks-report-detailed.json
8+
rm -rf ./gitleaks-report.json
9+
10+
# run Gitleaks to find secrets and generate a detailed report in JSON for the secrets found
11+
echo "Running Gitleaks to find secrets and generate a detailed report in JSON for the secrets found..."
12+
gitleaks detect -r ${PATH_TO_GIT_REPO}/gitleaks-report-detailed.json -f json -s ${PATH_TO_GIT_REPO} --redact --no-git
13+
14+
# create a final report in JSON using the detailed report having relevant information only
15+
echo "Creating a final report in JSON using the detailed report having relevant information only..."
16+
echo "[" > ./gitleaks-report.json
17+
cat ${PATH_TO_GIT_REPO}/gitleaks-report-detailed.json | jq -c '.[]' | while read -r line; do
18+
description=$(jq -r '.Description' <<< "$line")
19+
start_line=$(jq -r '.StartLine' <<< "$line")
20+
file=$(jq -r '.File' <<< "$line")
21+
file=$(echo "$file" | sed "s|^${PATH_TO_GIT_REPO}|.|")
22+
secret_type=$(jq -r '.RuleID' <<< "$line")
23+
24+
# use 'git blame' to find the commit id and author for each finding
25+
blame=$(cd ${PATH_TO_GIT_REPO} && git blame -L "$start_line","$start_line" "$file" --porcelain)
26+
commit_id=$(echo "$blame" | awk 'NR==1' | awk -F ' ' '{print $1}')
27+
author=$(echo "$blame" | awk 'NR==2' | awk -F 'author ' '{print $2}')
28+
29+
# append final JSON objects to the new report
30+
jq -n \
31+
--arg desc "$description" \
32+
--arg file "$file" \
33+
--arg line_no "$start_line" \
34+
--arg type "$secret_type" \
35+
--arg commit "$commit_id" \
36+
--arg author "$author" \
37+
'{"Description": $desc, "File": $file, "Line No.": $line_no, "Secret Type": $type, "Commit": $commit, "Author": $author}' >> ./gitleaks-report.json
38+
39+
echo "," >> ./gitleaks-report.json
40+
done
41+
head -n $(($(wc -l < ./gitleaks-report.json) - 1)) ./gitleaks-report.json > ./temp.json && mv ./temp.json ./gitleaks-report.json
42+
echo "]" >> ./gitleaks-report.json
43+
cat ./gitleaks-report.json | jq > ./temp.json && mv ./temp.json ./gitleaks-report.json
44+
45+
echo "Script Execution Completed!"
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/bin/bash
2+
set -ex
3+
4+
# update package lists
5+
apk update
6+
7+
# install Git, jq, Bash, Make, wget, Python3, pip, Go (Golang)
8+
apk add git jq bash make wget python3 py3-pip go
9+
git --version && jq --version && bash --version && make --version && wget --version && python3 --version && pip --version && go version
10+
11+
# install "Python Atlassian REST API Wrapper", "World timezone definitions, modern and historical" and "Requests" Python libraries
12+
pip install atlassian-python-api pytz requests --break-system-packages
13+
14+
# install Gitleaks
15+
rm -rf /usr/local/gitleaks && git clone https://github.com/gitleaks/gitleaks.git /usr/local/gitleaks
16+
cd /usr/local/gitleaks
17+
make build
18+
cd /
19+
export PATH=$PATH:/usr/local/gitleaks
20+
echo -n "gitleaks " && gitleaks version
21+
22+
echo "Installation completed successfully."
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/bin/bash
2+
set -ex
3+
4+
# install Git, jq, Bash, pip, Python3, Gitleaks
5+
brew install git jq bash python python@3 gitleaks
6+
git --version && jq --version && bash --version && pip --version && python3 --version && echo -n "gitleaks " && gitleaks version
7+
8+
# install "Python Atlassian REST API Wrapper", "World timezone definitions, modern and historical" and "Requests" Python libraries
9+
pip install atlassian-python-api pytz requests || pip install atlassian-python-api pytz requests --break-system-packages
10+
11+
echo "Installation completed successfully."

‎main.py

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
import json
2+
import os
3+
import pytz
4+
import re
5+
import requests
6+
import sys
7+
from atlassian import Confluence
8+
from datetime import datetime
9+
10+
# get time zone, repository name and branch name from the arguments passed to the script
11+
if len(sys.argv) < 4 or len(sys.argv) > 5:
12+
print("ERROR: Invalid arguments passed.")
13+
print("Usage: python main.py TIME_ZONE REPOSITORY_NAME BRANCH_NAME [JSON_REPORT_URL]")
14+
print("Example: python main.py Europe/Amsterdam myproj/myrepo master")
15+
sys.exit(1)
16+
time_zone = sys.argv[1]
17+
repo_name = sys.argv[2]
18+
branch_name = sys.argv[3]
19+
json_report_url = ""
20+
if len(sys.argv) == 5:
21+
json_report_url = sys.argv[4]
22+
23+
# Get the current time in UTC and convert it into the desired time zone's time
24+
time_now = datetime.now()
25+
target_timezone = pytz.timezone(time_zone)
26+
time_now = time_now.astimezone(target_timezone)
27+
time_now = time_now.strftime('%Y-%m-%d %H:%M:%S %Z')
28+
29+
# get environment variables related to Confluence
30+
confluence_enabled = os.getenv("CONFLUENCE_ENABLED")
31+
if confluence_enabled is None:
32+
print("ERROR: CONFLUENCE_ENABLED environment variable is not set.")
33+
sys.exit(1)
34+
elif confluence_enabled == "1":
35+
confluence_site = os.getenv("CONFLUENCE_SITE")
36+
confluence_user = os.getenv("CONFLUENCE_USER_EMAIL_ID")
37+
confluence_pass = os.getenv("CONFLUENCE_USER_TOKEN")
38+
page_title = os.getenv("CONFLUENCE_PAGE_TITLE")
39+
page_space = os.getenv("CONFLUENCE_PAGE_SPACE")
40+
if confluence_site is None:
41+
print("ERROR: CONFLUENCE_SITE environment variable is not set.")
42+
sys.exit(1)
43+
if confluence_user is None:
44+
print("ERROR: CONFLUENCE_USER_EMAIL_ID environment variable is not set.")
45+
sys.exit(1)
46+
if confluence_pass is None:
47+
print("ERROR: CONFLUENCE_USER_TOKEN environment variable is not set.")
48+
sys.exit(1)
49+
if page_title is None:
50+
print("ERROR: CONFLUENCE_PAGE_TITLE environment variable is not set.")
51+
sys.exit(1)
52+
if page_space is None:
53+
print("ERROR: CONFLUENCE_PAGE_SPACE environment variable is not set.")
54+
sys.exit(1)
55+
56+
# get environment variables related to Slack
57+
slack_enabled = os.getenv("SLACK_ENABLED")
58+
if slack_enabled is None:
59+
print("ERROR: SLACK_ENABLED environment variable is not set.")
60+
sys.exit(1)
61+
elif slack_enabled == "1":
62+
slack_webhook_url = os.getenv("SLACK_WEBHOOK_URL")
63+
if slack_webhook_url is None:
64+
print("ERROR: SLACK_WEBHOOK_URL environment variable is not set.")
65+
sys.exit(1)
66+
67+
# define HTML page template
68+
if confluence_enabled == "1":
69+
html_template = """
70+
<h2>Repository: {} - Branch: {}</h2>
71+
<h4>Last Scan Time: {}</h4>
72+
<h3>Secrets Found: {}</h3>
73+
<table data-number-column="true" data-table-width="1400" data-layout="default">
74+
<tbody>
75+
<tr>
76+
<th class="numberingColumn"/>
77+
<th>
78+
<p><strong>Description</strong></p>
79+
</th>
80+
<th>
81+
<p><strong>File</strong></p>
82+
</th>
83+
<th>
84+
<p><strong>Line No.</strong></p>
85+
</th>
86+
<th>
87+
<p><strong>Secret Type</strong></p>
88+
</th>
89+
<th>
90+
<p><strong>Commit ID</strong></p>
91+
</th>
92+
<th>
93+
<p><strong>Commit Author</strong></p>
94+
</th>
95+
</tr>
96+
{}
97+
</tbody>
98+
</table>
99+
"""
100+
101+
# define HTML row template
102+
if confluence_enabled == "1":
103+
row_template = """
104+
<tr>
105+
<td class="numberingColumn">
106+
{}
107+
</td>
108+
<td>
109+
<p>{}</p>
110+
</td>
111+
<td>
112+
<p>{}</p>
113+
</td>
114+
<td>
115+
<p>{}</p>
116+
</td>
117+
<td>
118+
<p>{}</p>
119+
</td>
120+
<td>
121+
<p>{}</p>
122+
</td>
123+
<td>
124+
<p>{}</p>
125+
</td>
126+
</tr>
127+
"""
128+
129+
# connect to Confluence
130+
if confluence_enabled == "1":
131+
confluence = Confluence(url=confluence_site, username=confluence_user, password=confluence_pass)
132+
133+
# resolve page ID
134+
if confluence_enabled == "1":
135+
page_id = confluence.get_page_id(page_space, page_title)
136+
137+
# get current page content
138+
if confluence_enabled == "1":
139+
page = confluence.get_page_by_id(page_id, expand='body.storage')
140+
page_content = page['body']['storage']['value']
141+
142+
# read JSON from file
143+
with open("./gitleaks-report.json", "r") as file:
144+
data = json.load(file)
145+
146+
# update HTML page template and find unique commit authors from the data read from JSON file
147+
authors = []
148+
rows = ""
149+
rows_count = 1
150+
for entry in data:
151+
author = entry["Author"]
152+
if confluence_enabled == "1":
153+
description = entry["Description"]
154+
file = entry["File"]
155+
line_no = entry["Line No."]
156+
secret_type = entry["Secret Type"]
157+
commit = entry["Commit"]
158+
rows += row_template.format(rows_count, description, file, line_no, secret_type, commit, author)
159+
if slack_enabled == "1":
160+
authors.append(author)
161+
rows_count = rows_count + 1
162+
if confluence_enabled == "1":
163+
html_template = html_template.format(repo_name, branch_name, time_now, len(data), rows)
164+
if slack_enabled == "1":
165+
authors = list(set(authors))
166+
authors.sort()
167+
168+
# define the pattern to replace the respective div
169+
if confluence_enabled == "1":
170+
pattern = r'<h2>Repository: {} - Branch: {}.*?</table>'.format(repo_name, branch_name)
171+
172+
# Check if pattern is found or not and update the page content accordingly
173+
if confluence_enabled == "1":
174+
new_page_content = page_content
175+
if re.search(pattern, page_content, flags=re.DOTALL):
176+
# pattern found; replace matching pattern in the existing content with the new HTML page template
177+
new_page_content = re.sub(pattern, html_template, page_content, flags=re.DOTALL)
178+
else:
179+
# pattern not found; add the new HTML page template at the end of the existing content
180+
new_page_content = new_page_content + "\n" + html_template
181+
182+
# update page with new content
183+
if confluence_enabled == "1":
184+
try:
185+
confluence.update_page(page_id, page_title, new_page_content, type='page', representation='storage', minor_edit=False, full_width=True)
186+
print("Confluence page updated successfully.")
187+
except Exception as err:
188+
print("ERROR: Failed to update Confluence page.")
189+
print(f'ERROR: {err}')
190+
sys.exit(1)
191+
192+
# send notification to Slack
193+
if slack_enabled == "1":
194+
message = "*Secrets Detection Notification*"
195+
message += f'\n>:file_folder: *Repository:* `{repo_name}`'
196+
message += f'\n>:git: *Branch:* `{branch_name}`'
197+
message += f'\n>:clock1: *Last Scan Time:* `{time_now}`'
198+
message += f'\n>:warning: *Secrets Found:* `{len(data)}`'
199+
message += f'\n>:technologist: *Commit Authors:* \n>• *{'*\n>• *'.join(authors)}*'
200+
if confluence_enabled == "1":
201+
message += f'\n:link: More details can be found here: <{confluence_site}/wiki/spaces/{page_space}/pages/{page_id}/{page_title}|Confluence Page>'
202+
if json_report_url != "":
203+
message += f'\n:link: JSON report can be found here: <{json_report_url}|JSON Report>'
204+
slack_data = {
205+
"blocks": [
206+
{
207+
"type": "section",
208+
"text": {
209+
"type": "mrkdwn",
210+
"text": message
211+
}
212+
}
213+
]
214+
}
215+
headers = {'Content-Type': "application/json"}
216+
try:
217+
response = requests.post(slack_webhook_url, data=json.dumps(slack_data), headers=headers)
218+
response.raise_for_status()
219+
print("Notification sent to Slack successfully.")
220+
except Exception as err:
221+
print("ERROR: Failed to send notification to Slack.")
222+
print(f'ERROR: {err}')
223+
sys.exit(1)

0 commit comments

Comments
 (0)
Please sign in to comment.