forked from NetSPI/django.nV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJenkinsfile
428 lines (351 loc) · 16.1 KB
/
Jenkinsfile
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
pipeline {
agent {
label 'slave-jenkins-deb' // Replace with the label of your slave node
}
environment{
DOCKER_REGISTRY = 'https://index.docker.io/v1/'
DOCKER_IMAGE = 'aatikah/django-app'
remoteHost = '34.134.182.0'
DEFECTDOJO_API_KEY = credentials('DEFECTDOJO_API_KEY')
DEFECTDOJO_URL = 'http://34.42.127.145:8080'
PRODUCT_NAME = 'django-project'
}
stages{
stage('Testing Node') {
steps {
script {
sh 'echo "Hello from Node"'
}
}
}
stage('Run Gitleaks with Custom Config') {
steps {
script {
// Pull and run the Gitleaks Docker image with a custom config file
sh '''
docker run --rm -v $(pwd):/path -v $(pwd)/.gitleaks.toml:/.gitleaks.toml zricethezav/gitleaks:latest detect --source /path --config /.gitleaks.toml --report-format json --report-path /path/gitleaks-report.json || true
'''
// Archive the reports as artifacts
archiveArtifacts artifacts: 'gitleaks-report.json', allowEmptyArchive: true
}
// Display the contents of the report in a separate step
//script {
// echo "Gitleaks Report:"
// sh 'cat gitleaks-report.json || echo "Report not found or empty."'
//}
}
}
stage('Source Composition Analysis'){
steps{
script{
sh 'rm owasp* || true'
sh 'wget "https://raw.githubusercontent.com/aatikah/django.nV/master/owasp-dependency-check.sh"'
// sh 'chmod +x owasp-dependency-check.sh'
sh 'bash owasp-dependency-check.sh'
//sh 'cat /home/jenkins/workspace/django/report/dependency-check-report.xml'
//sh 'cat /home/jenkins/workspace/django/report/dependency-check-report.json'
// Archive the reports as artifacts
archiveArtifacts artifacts: 'report/dependency-check-report.json,report/dependency-check-report.html,report/dependency-check-report.xml', allowEmptyArchive: true
// Publish HTML report
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: './report',
reportFiles: 'dependency-check-report.html',
reportName: 'OWASP Dependency Checker Report'
])
// Parse JSON report to check for issues
// This if block can be added in another script block outside this script block to fail pipeline if cvssv is above 7
if (fileExists('report/dependency-check-report.json')) {
def jsonReport = readJSON file: 'report/dependency-check-report.json'
def vulnerabilities = jsonReport.dependencies.collect { it.vulnerabilities ?: [] }.flatten()
def highVulnerabilities = vulnerabilities.findAll { it.cvssv3?.baseScore >= 7 }
echo "OWASP Dependency-Check found ${vulnerabilities.size()} vulnerabilities, ${highVulnerabilities.size()} of which are high severity (CVSS >= 7.0)"
} else {
echo "Dependency-Check JSON report not found. The scan may have failed."
}
}
}
}
//BANDIT STAGE
stage('SAST With Bandit Security Scan') {
steps {
script {
// Run Bandit scan and generate reports
sh '''
python3 -m venv bandit_venv
. bandit_venv/bin/activate
pip install --upgrade pip
pip install bandit
bandit -r . -f json -o bandit-report.json --exit-zero
bandit -r . -f html -o bandit-report.html --exit-zero
deactivate
'''
// Archive the reports as artifacts
archiveArtifacts artifacts: 'bandit-report.json,bandit-report.html', allowEmptyArchive: true
// Publish HTML report
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: '.',
reportFiles: 'bandit-report.html',
reportName: 'Bandit Security Scan Report'
])
// Parse JSON report to check for issues
script {
def jsonReport = readJSON file: 'bandit-report.json'
def issueCount = jsonReport.results.size()
if (issueCount > 0) {
echo "Bandit found ${issueCount} potential security issue(s). Please review the report."
} else {
echo "Bandit scan completed successfully with no issues found."
}
}
}
}
}
stage('Build and Push Docker Image') {
steps {
script {
// Wrap the Docker commands with withCredentials to securely access the Docker credentials
withCredentials([usernamePassword(credentialsId: 'DOCKER_CREDENTIALS_ID', usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {
// Build the Docker image
sh "docker build -t ${DOCKER_IMAGE} ."
//sh "docker build -t ${DOCKER_IMAGE}:v5 ."
// Log in to the Docker registry using a more secure method. set +x set -x This turns off command echoing temporarily
sh '''
set +x
echo "$DOCKER_PASSWORD" | docker login $DOCKER_REGISTRY -u "$DOCKER_USERNAME" --password-stdin
set -x
'''
// Push the Docker image
//sh "docker push ${DOCKER_IMAGE}:v5"
sh "docker push ${DOCKER_IMAGE}"
// Log out from the Docker registry
sh "docker logout $DOCKER_REGISTRY"
// Clean up: remove any leftover Docker credentials
sh "rm -f /home/jenkins/.docker/config.json"
}
}
}
}
stage('Deploy to GCP VM') {
steps {
script {
//def remoteHost = '34.134.182.0'
def remoteUser = 'jenkins-slave'
def dockerImage = 'aatikah/django-app'
sshagent(['slave-jenkins-key']) {
// Stop and remove the old container if it exists
sh """
ssh -o StrictHostKeyChecking=no ${remoteUser}@${remoteHost} '
container_id=\$(docker ps -q --filter ancestor=${dockerImage})
if [ ! -z "\$container_id" ]; then
docker stop \$container_id
docker rm \$container_id
fi
'
"""
// Pull the latest image and run the new container
sh """
ssh -o StrictHostKeyChecking=no ${remoteUser}@${remoteHost} '
docker pull ${dockerImage} &&
docker run -d --restart unless-stopped -p 8000:8000 --name my-django-app ${dockerImage}
'
"""
// Verify the deployment
sh """
ssh -o StrictHostKeyChecking=no ${remoteUser}@${remoteHost} '
if docker ps | grep -q ${dockerImage}; then
echo "Deployment successful"
else
echo "Deployment failed"
exit 1
fi
'
"""
}
}
}
}
stage('DAST OWASP ZAP Scan') {
steps {
script {
def zapHome ='/opt/zaproxy' // Path to ZAP installation
//def targetURL = 'http://34.134.182.0' // Update this to your application's URL
def reportNameHtml = "zap-scan-report.html"
def reportNameXml = "zap-scan-report.xml"
// Perform ZAP scan
//sh """
// ${zapHome}/zap.sh -cmd \
// -quickurl http://${remoteHost} \
// -quickprogress \
// -quickout ${WORKSPACE}/${reportNameHtml}
// """
sh """
${zapHome}/zap.sh -cmd \
-quickurl http://${remoteHost} \
-quickprogress \
-quickout ${WORKSPACE}/${reportNameHtml}
${zapHome}/zap.sh -cmd \
-quickurl http://${remoteHost} \
-quickprogress \
-quickout ${WORKSPACE}/${reportNameXml}
"""
// Archive the ZAP reports
archiveArtifacts artifacts: "${reportNameHtml},${reportNameXml}", fingerprint: true
// Read and parse the HTML report
def htmlReportContent = readFile(reportNameHtml)
// Example: Check for high alerts in HTML using regex (customize based on your report structure)
def highRiskPattern = ~/<span class="risk"><strong>High<\/strong><\/span>.*?<a href="(.*?)">(.*?)<\/a>/
def highAlerts = []
htmlReportContent.eachMatch(highRiskPattern) { match ->
highAlerts.add([url: match[1], alert: match[2]])
}
if (highAlerts.size() > 0) {
echo "Found ${highAlerts.size()} high-risk vulnerabilities!"
highAlerts.each { alert ->
echo "High Risk Alert: ${alert.alert} at ${alert.url}"
}
// Exit with code 1 if high-risk vulnerabilities are found
error "OWASP ZAP scan found high-risk vulnerabilities. Check the ZAP report for details."
}else {
echo "No high-risk vulnerabilities found."
}
// Read and parse JSON report
// def zapJson = readJSON file: reportNameJson
// Example: Check for high alerts in JSON
// def highAlerts = zapJson.site[0].alerts.findAll { it.riskcode >= 3 }
// if (highAlerts.size() > 0) {
// echo "Found ${highAlerts.size()} high-risk vulnerabilities!"
// highAlerts.each { alert ->
// echo "High Risk Alert: ${alert.alert} at ${alert.url}"
// }
// error "OWASP ZAP scan found high-risk vulnerabilities. Check the ZAP report for details."
// }
// Publish HTML report
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: '.',
reportFiles: 'zap-scan-report.html',
reportName: "ZAP Security Report"
])
// Optional: Publish JSON report as a build artifact
//archiveArtifacts artifacts: 'zap-scan-report.json', fingerprint: true
}
}
}
stage('DAST with Nikto') {
steps {
script {
//def TARGET_URL = 'http://34.134.182.0'
// Run Nikto scan
sh """
/home/abuabdillah5444/nikto/program/nikto.pl -h http://${remoteHost} -output nikto_output.json -Format json
/home/abuabdillah5444/nikto/program/nikto.pl -h http://${remoteHost} -output nikto_output.html -Format html
"""
// Archive the results
archiveArtifacts artifacts: 'nikto_output.*', allowEmptyArchive: true
// Optional: Publish HTML report
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: '.',
reportFiles: 'nikto_output.html',
reportName: 'Nikto DAST Report'
])
}
}
}
stage('Forward Reports to DefectDojo') {
steps {
script {
// Create a virtual environment and install requests using bash
sh '''
python3 -m venv venv
bash -c "source venv/bin/activate && pip install requests"
'''
// Use Jenkins credentials binding to securely inject sensitive values
withCredentials([string(credentialsId: 'DEFECTDOJO_API_KEY', variable: 'DEFECTDOJO_API_KEY')]) {
// Function to upload reports to DefectDojo
def uploadToDefectDojo = {
def scriptContent = """
import requests
import json
import sys
import os
def upload_report(report_path, report_type, engagement_id):
url = "${DEFECTDOJO_URL}/api/v2/import-scan/"
headers = {
'Authorization': f'Token {os.getenv("DEFECTDOJO_API_KEY")}',
'Accept': 'application/json'
}
data = {
'product_name': '${PRODUCT_NAME}',
'engagement': engagement_id,
'scan_type': report_type,
'active': 'true',
'verified': 'true',
}
print(f"--- Attempting to upload {report_type} report ---")
print(f"Report path: {report_path}")
print(f"URL: {url}")
print(f"Headers: {json.dumps({k: v if k != 'Authorization' else '[REDACTED]' for k, v in headers.items()}, indent=2)}")
print(f"Data: {json.dumps(data, indent=2)}")
try:
if not os.path.exists(report_path):
print(f"Error: Report file {report_path} does not exist")
return False
file_size = os.path.getsize(report_path)
print(f"File size: {file_size} bytes")
with open(report_path, 'rb') as file:
files = {'file': file}
response = requests.post(url, headers=headers, data=data, files=files)
print(f"Response status code: {response.status_code}")
print(f"Response content: {response.text}")
if response.status_code == 201:
print(f"Successfully uploaded {report_type} report")
return True
else:
print(f"Failed to upload {report_type} report. Status code: {response.status_code}")
return False
except Exception as e:
print(f"Error occurred while uploading {report_type} report: {str(e)}")
return False
# Attempt to upload each report
reports = [
('gitleaks-report.json', 'Gitleaks Scan', '3'),
('report/dependency-check-report.xml', 'Dependency Check Scan', '4'),
('bandit-report.json', 'Bandit Scan', '5'),
('zap-scan-report.xml', 'ZAP Scan', '6'),
('nikto_output.json', 'Nikto Scan', '7')
]
success_count = 0
for report_path, report_type, engagement_id in reports:
if upload_report(report_path, report_type, engagement_id ):
success_count += 1
else:
print(f"Failed to upload {report_type} report")
print(f"Summary: Successfully uploaded {success_count} out of {len(reports)} reports")
if success_count < len(reports):
sys.exit(1) # Exit with error if not all reports were uploaded
"""
writeFile file: 'upload_to_defectdojo.py', text: scriptContent
// Run the Python script in the virtual environment using bash
return sh(script: 'bash -c "source venv/bin/activate && python3 upload_to_defectdojo.py"', returnStatus: true)
}
def uploadStatus = uploadToDefectDojo()
if (uploadStatus != 0) {
unstable('Some reports failed to upload to DefectDojo')
}
}
}
}
}
}
}