dockeriq 2.0.3__tar.gz → 2.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dockeriq
3
- Version: 2.0.3
3
+ Version: 2.0.4
4
4
  Summary: Secure Docker images with automated vulnerability scanning
5
5
  Home-page: https://github.com/yourteam/dockeriq-cli
6
6
  Author: Your Team
@@ -13,14 +13,15 @@ Dynamic: home-page
13
13
  Dynamic: requires-python
14
14
  Dynamic: summary
15
15
 
16
+ > ⚠️ **Proprietary Software:** This repository contains documentation only.
17
+ > The actual source code is closed-source and protected under All Rights Reserved license.
18
+ > For commercial use, please contact dockerriq@gmail.com
16
19
  # DockerIQ CLI
17
20
 
18
21
  Scan Docker images for security vulnerabilities directly from your terminal.
19
22
 
20
23
  ## Requirements
21
24
  - Docker
22
- - Trivy (install from: https://github.com/aquasecurity/trivy)
23
-
24
25
  ## Install
25
26
  ```bash
26
27
  pip install dockeriq
@@ -0,0 +1,13 @@
1
+ > ⚠️ **Proprietary Software:** This repository contains documentation only.
2
+ > The actual source code is closed-source and protected under All Rights Reserved license.
3
+ > For commercial use, please contact dockerriq@gmail.com
4
+ # DockerIQ CLI
5
+
6
+ Scan Docker images for security vulnerabilities directly from your terminal.
7
+
8
+ ## Requirements
9
+ - Docker
10
+ ## Install
11
+ ```bash
12
+ pip install dockeriq
13
+
@@ -0,0 +1,514 @@
1
+ """
2
+ DockerIQ CLI - Proprietary Security Scanning Tool
3
+ Copyright (c) 2026 . All rights reserved.
4
+ This software is confidential and proprietary. Unauthorized copying or distribution is prohibited.
5
+ """
6
+
7
+ import subprocess
8
+ import argparse
9
+ import sys
10
+ import json
11
+ import math
12
+ import os
13
+ import platform
14
+ import zipfile
15
+ import tarfile
16
+ import shutil
17
+ import urllib.request
18
+ from datetime import datetime
19
+
20
+ from collections import Counter
21
+
22
+ from .mitigation import get_mitigation, get_package_mitigation
23
+ from . import fixer
24
+ from .report_html import render_html
25
+
26
+
27
+ # Terminal colors
28
+ class Colors:
29
+ RED = '\033[91m'
30
+ ORANGE = '\033[93m'
31
+ YELLOW = '\033[93m'
32
+ GREEN = '\033[92m'
33
+ CYAN = '\033[96m'
34
+ BOLD = '\033[1m'
35
+ END = '\033[0m'
36
+
37
+
38
+ SEVERITY_ORDER = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "UNKNOWN": 4}
39
+
40
+ SHORT_NOTES = {
41
+ "no_fix": "No patch available yet.",
42
+ "will_not_fix": "Vendor will not fix this.",
43
+ "eol": "OS is end-of-life.",
44
+ }
45
+
46
+ GENERAL_ADVICE = {
47
+ "no_fix": "No patch yet: remove the package if not needed, try a newer or slimmer base image, "
48
+ "limit network exposure, and re-scan regularly.",
49
+ "will_not_fix": "Vendor will not fix: remove the package if unused, switch to an alternative, "
50
+ "or change the base image.",
51
+ "eol": "End-of-life OS: move to a supported base image.",
52
+ }
53
+
54
+
55
+ def get_version():
56
+ """Installed package version."""
57
+ try:
58
+ from importlib.metadata import version
59
+ return version("dockeriq")
60
+ except Exception:
61
+ return "dev"
62
+
63
+
64
+ def print_colored(text, color):
65
+ print(f"{color}{text}{Colors.END}")
66
+
67
+
68
+ def calculate_score(vulns):
69
+ """Security score 0-100 on a logarithmic scale."""
70
+ weights = {"CRITICAL": 10, "HIGH": 5, "MEDIUM": 2, "LOW": 1}
71
+ risk = sum(weights.get(v.get("severity", "").upper(), 0) for v in vulns)
72
+ if risk == 0:
73
+ return 100
74
+ return max(0, min(100, round(100 - 20 * math.log10(1 + risk))))
75
+
76
+
77
+ def sort_vulns(vulns):
78
+ """Most severe first; fixable ones prioritized."""
79
+ return sorted(
80
+ vulns,
81
+ key=lambda v: (
82
+ SEVERITY_ORDER.get(v["severity"], 4),
83
+ 0 if v["mitigation"]["type"] == "upgrade" else 1,
84
+ v["pkg"],
85
+ ),
86
+ )
87
+
88
+
89
+ def group_by_package(vulns):
90
+ """Group vulnerabilities by package with mitigation advice."""
91
+ groups = {}
92
+ for v in vulns:
93
+ key = (v["pkg"], v["type"], v["installed_version"])
94
+ groups.setdefault(key, []).append(v)
95
+
96
+ items = []
97
+ for (pkg, res_type, installed), vs in groups.items():
98
+ counts = Counter(v["severity"] for v in vs)
99
+ worst = min(counts, key=lambda sv: SEVERITY_ORDER.get(sv, 4))
100
+ m = get_package_mitigation(vs)
101
+ items.append({
102
+ "pkg": pkg,
103
+ "type": res_type,
104
+ "installed_version": installed,
105
+ "worst_severity": worst,
106
+ "total": len(vs),
107
+ "severity_counts": dict(counts),
108
+ "cve_ids": [v["id"] for v in vs],
109
+ "mitigation": m,
110
+ })
111
+ items.sort(key=lambda it: (SEVERITY_ORDER.get(it["worst_severity"], 4),
112
+ 0 if it["mitigation"]["type"] == "upgrade" else 1,
113
+ -it["total"]))
114
+ return items
115
+
116
+
117
+ def get_or_download_scanner():
118
+ """Initialize DockerIQ proprietary scanning engine."""
119
+ home_dir = os.path.expanduser("~/.dockeriq")
120
+ bin_dir = os.path.join(home_dir, "bin")
121
+
122
+ # Use generic internal name to avoid exposing underlying tech
123
+ scanner_exe = "dockeriq-scanner.exe" if platform.system() == "Windows" else "dockeriq-scanner"
124
+ scanner_path = os.path.join(bin_dir, scanner_exe)
125
+
126
+ if os.path.exists(scanner_path):
127
+ return scanner_path
128
+
129
+ os.makedirs(bin_dir, exist_ok=True)
130
+ print_colored("[+] DockerIQ: Initializing security engine (one-time setup)...", Colors.CYAN)
131
+
132
+ system = platform.system().lower()
133
+ arch = platform.machine().lower()
134
+
135
+ if system == "darwin":
136
+ os_name = "macOS"
137
+ elif system == "windows":
138
+ os_name = "Windows"
139
+ else:
140
+ os_name = "Linux"
141
+
142
+ if arch in ("x86_64", "amd64"):
143
+ arch_name = "64bit"
144
+ elif arch in ("aarch64", "arm64"):
145
+ arch_name = "ARM64"
146
+ elif arch in ("armv7l", "armv7"):
147
+ arch_name = "ARM"
148
+ else:
149
+ print_colored(f"❌ Unsupported architecture: {arch}", Colors.RED)
150
+ sys.exit(1)
151
+
152
+ # Internal versioning for the scanning module
153
+ version = "0.69.3"
154
+ ext = "zip" if system == "windows" else "tar.gz"
155
+ tarball_name = f"engine_{version}_{os_name}-{arch_name}.{ext}"
156
+
157
+ # Note: URL remains functional but user-facing messages are sanitized
158
+ url = f"https://github.com/aquasecurity/trivy/releases/download/v{version}/{tarball_name.replace('engine', 'trivy')}"
159
+
160
+ try:
161
+ tmp_file = os.path.join(bin_dir, tarball_name)
162
+ urllib.request.urlretrieve(url, tmp_file)
163
+
164
+ if ext == "zip":
165
+ with zipfile.ZipFile(tmp_file, 'r') as zip_ref:
166
+ zip_ref.extractall(bin_dir)
167
+ else:
168
+ with tarfile.open(tmp_file, 'r:gz') as tar_ref:
169
+ tar_ref.extractall(bin_dir)
170
+
171
+ # Map extracted binary to our internal name
172
+ candidate_paths = [
173
+ os.path.join(bin_dir, "trivy.exe" if system == "windows" else "trivy"),
174
+ os.path.join(bin_dir, f"trivy_{version}_{os_name}_{arch_name}", "trivy.exe" if system == "windows" else "trivy"),
175
+ ]
176
+ found = False
177
+ for src in candidate_paths:
178
+ if os.path.exists(src):
179
+ if src != scanner_path:
180
+ shutil.move(src, scanner_path)
181
+ found = True
182
+ break
183
+
184
+ if not found:
185
+ print_colored("❌ Failed to initialize scanning module after extraction.", Colors.RED)
186
+ sys.exit(1)
187
+
188
+ if system != "windows":
189
+ os.chmod(scanner_path, 0o755)
190
+
191
+ os.remove(tmp_file)
192
+ return scanner_path
193
+
194
+ except Exception as e:
195
+ print_colored(f"❌ Failed to initialize security engine: {e}", Colors.RED)
196
+ print("👉 Please ensure DockerIQ dependencies are met or contact support.")
197
+ sys.exit(1)
198
+
199
+
200
+ def collect_scan(image_name, quiet=False):
201
+ if not quiet:
202
+ print_colored(f"\n[+] DockerIQ: Scanning image '{image_name}'...", Colors.CYAN)
203
+
204
+ scanner_path = get_or_download_scanner()
205
+
206
+ # Download vulnerability database silently
207
+ try:
208
+ subprocess.run(
209
+ [scanner_path, "image", "--download-db-only", "--quiet"],
210
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True
211
+ )
212
+ except Exception:
213
+ pass
214
+
215
+ # Execute scan
216
+ try:
217
+ result = subprocess.run(
218
+ [scanner_path, "image", "--format", "json", "--no-progress", "--quiet", image_name],
219
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8"
220
+ )
221
+ except Exception as e:
222
+ print_colored(f"❌ Scan failed to start: {e}", Colors.RED)
223
+ sys.exit(1)
224
+
225
+ if result.returncode not in (0, 1):
226
+ print_colored(f"❌ Scanner error: {result.stderr.strip()}", Colors.RED)
227
+ sys.exit(1)
228
+
229
+ if not result.stdout.strip():
230
+ print_colored("❌ Empty response from scanner.", Colors.RED)
231
+ sys.exit(1)
232
+
233
+ try:
234
+ data = json.loads(result.stdout)
235
+ except json.JSONDecodeError:
236
+ print_colored("❌ Invalid scan output (not valid JSON).", Colors.RED)
237
+ sys.exit(1)
238
+
239
+ # Extract and enrich vulnerabilities
240
+ vulns = []
241
+ for res in data.get("Results", []):
242
+ res_type = res.get("Type", "")
243
+ for v in res.get("Vulnerabilities") or []:
244
+ item = {
245
+ "pkg": v.get("PkgName", "unknown"),
246
+ "id": v.get("VulnerabilityID", "N/A"),
247
+ "severity": v.get("Severity", "UNKNOWN").upper(),
248
+ "title": v.get("Title", "No title available"),
249
+ "installed_version": v.get("InstalledVersion", ""),
250
+ "fixed_version": v.get("FixedVersion", ""),
251
+ "status": v.get("Status", ""),
252
+ "type": res_type,
253
+ }
254
+ item["mitigation"] = get_mitigation(item)
255
+ vulns.append(item)
256
+
257
+ vulns = sort_vulns(vulns)
258
+
259
+ critical = [v for v in vulns if v["severity"] == "CRITICAL"]
260
+ high = [v for v in vulns if v["severity"] == "HIGH"]
261
+ medium = [v for v in vulns if v["severity"] == "MEDIUM"]
262
+ low = [v for v in vulns if v["severity"] == "LOW"]
263
+ total = len(vulns)
264
+ fixable = sum(1 for v in vulns if v["mitigation"]["type"] == "upgrade")
265
+ score = calculate_score(vulns)
266
+ packages = group_by_package(vulns)
267
+ fixable_pkgs = sum(1 for it in packages if it["mitigation"]["type"] == "upgrade")
268
+
269
+ return {
270
+ "image": image_name,
271
+ "vulns": vulns,
272
+ "packages": packages,
273
+ "score": score,
274
+ "summary": {
275
+ "total": total,
276
+ "critical": len(critical),
277
+ "high": len(high),
278
+ "medium": len(medium),
279
+ "low": len(low),
280
+ "fixable": fixable,
281
+ "packages": len(packages),
282
+ "fixable_packages": fixable_pkgs,
283
+ },
284
+ }
285
+
286
+
287
+ def print_scan_report(result):
288
+ vulns = result["vulns"]
289
+ packages = result["packages"]
290
+ score = result["score"]
291
+ sm = result["summary"]
292
+ total = sm["total"]
293
+ critical, high, medium, low = sm["critical"], sm["high"], sm["medium"], sm["low"]
294
+ fixable, fixable_pkgs = sm["fixable"], sm["fixable_packages"]
295
+
296
+ if total == 0:
297
+ print_colored("\n✅ DockerIQ: No vulnerabilities found!", Colors.GREEN)
298
+ print_colored(f"🛡️ Security Score: {score}/100", Colors.BOLD)
299
+ else:
300
+ print_colored(f"\n🚨 DockerIQ: Found {total} vulnerabilities", Colors.RED)
301
+ print_colored(f"🛡️ Security Score: {score}/100", Colors.BOLD)
302
+
303
+ print("\n📊 Summary:")
304
+ if critical:
305
+ print_colored(f" 🔴 Critical: {critical}", Colors.RED)
306
+ if high:
307
+ print_colored(f" 🟠 High: {high}", Colors.ORANGE)
308
+ if medium:
309
+ print_colored(f" 🟡 Medium: {medium}", Colors.YELLOW)
310
+ if low:
311
+ print_colored(f" 🟢 Low: {low}", Colors.GREEN)
312
+ print(f" 🔧 Fixable by upgrade: {fixable} of {total}")
313
+ print(f" 📦 Affected packages: {len(packages)} ({fixable_pkgs} can be fixed)")
314
+
315
+ print("\n🔍 Top packages to fix (most severe first):")
316
+ advice_types_seen = []
317
+ for it in packages[:5]:
318
+ sev = it["worst_severity"]
319
+ icon = "🔴" if sev == "CRITICAL" else "🟠" if sev == "HIGH" else "🟡" if sev == "MEDIUM" else "🟢"
320
+ color = Colors.RED if sev == "CRITICAL" else Colors.ORANGE if sev == "HIGH" else Colors.YELLOW if sev == "MEDIUM" else Colors.GREEN
321
+
322
+ counts = ", ".join(
323
+ f"{n} {name.capitalize()}"
324
+ for name, n in sorted(it["severity_counts"].items(), key=lambda kv: SEVERITY_ORDER.get(kv[0], 4))
325
+ )
326
+ print_colored(f" {icon} `{it['pkg']}` {it['installed_version']} - {it['total']} vulnerabilities ({counts})", color)
327
+
328
+ examples = ", ".join(it["cve_ids"][:3])
329
+ more = f" +{it['total'] - 3} more" if it['total'] > 3 else ""
330
+ print(f" → e.g. {examples}{more}")
331
+
332
+ m = it["mitigation"]
333
+ if m["type"] == "upgrade":
334
+ print(f" 💡 Fix: {m['summary']}")
335
+ print(f" Closes {m['fixes']} of {it['total']} vulnerabilities.")
336
+ if m["command"]:
337
+ print(f" $ {m['command']}")
338
+ else:
339
+ print(f" 💡 {SHORT_NOTES.get(m['type'], 'No fix available.')}")
340
+ if m["type"] not in advice_types_seen:
341
+ advice_types_seen.append(m["type"])
342
+ print()
343
+
344
+ if advice_types_seen:
345
+ print("ℹ️ What to do when no upgrade is available:")
346
+ for t in advice_types_seen:
347
+ print(f" • {GENERAL_ADVICE.get(t, '')}")
348
+ print()
349
+
350
+
351
+ def make_report(result, fix_info=None):
352
+ sm = result["summary"]
353
+ report = {
354
+ "tool": "DockerIQ",
355
+ "version": get_version(),
356
+ "image": result["image"],
357
+ "timestamp": datetime.now().isoformat(),
358
+ "security_score": result["score"],
359
+ "summary": sm,
360
+ "packages": result["packages"],
361
+ "vulnerabilities": result["vulns"],
362
+ }
363
+ if fix_info:
364
+ report["fix"] = fix_info
365
+ return report
366
+
367
+
368
+ def save_report(report, output_file):
369
+ try:
370
+ with open(output_file, 'w', encoding='utf-8') as f:
371
+ json.dump(report, f, indent=2, ensure_ascii=False)
372
+ print_colored(f"💾 Report saved to: {output_file}", Colors.GREEN)
373
+ except Exception as e:
374
+ print_colored(f"❌ Failed to save report: {e}", Colors.RED)
375
+
376
+
377
+ def print_comparison(before, after):
378
+ b, a = before["summary"], after["summary"]
379
+ rows = [
380
+ ("🔴 Critical", "critical"),
381
+ ("🟠 High", "high"),
382
+ ("🟡 Medium", "medium"),
383
+ ("🟢 Low", "low"),
384
+ (" Total", "total"),
385
+ ]
386
+ print("\n📈 Before vs After:")
387
+ print(f" {'':<14}{'Before':>8}{'After':>8}{'Change':>9}")
388
+ for label, key in rows:
389
+ diff = a[key] - b[key]
390
+ sign = "+" if diff > 0 else ""
391
+ print(f" {label:<14}{b[key]:>8}{a[key]:>8}{sign + str(diff):>9}")
392
+ print(f" {'Score':<14}{before['score']:>8}{after['score']:>8}")
393
+
394
+
395
+ def run_fix(image_name, before, fix_all=False, dry_run=False):
396
+ """Build fixed image with OS upgrades and verify."""
397
+ print_colored("\n[+] DockerIQ: Preparing fixed image...", Colors.CYAN)
398
+
399
+ if not dry_run and not shutil.which("docker"):
400
+ print_colored("❌ Docker was not found. Install Docker and make sure it is running.", Colors.RED)
401
+ return None
402
+
403
+ severities = None if fix_all else {"CRITICAL", "HIGH"}
404
+ scope = "all severities" if fix_all else "Critical and High only"
405
+ family, pkgs, skipped = fixer.collect_upgrade_targets(before["vulns"], severities)
406
+
407
+ if not pkgs:
408
+ print_colored(f"ℹ️ Nothing to upgrade automatically ({scope}).", Colors.YELLOW)
409
+ if skipped:
410
+ print(f" {skipped} non-OS package(s) were skipped.")
411
+ return None
412
+
413
+ new_tag = fixer.fixed_tag(image_name)
414
+ user = fixer.get_image_user(image_name) if shutil.which("docker") else ""
415
+ try:
416
+ dockerfile = fixer.build_dockerfile(image_name, family, pkgs, user)
417
+ except ValueError as e:
418
+ print_colored(f"❌ Refusing to build: {e}", Colors.RED)
419
+ return None
420
+
421
+ print(f" OS family : {family}")
422
+ print(f" Scope : {scope}")
423
+ print(f" Packages to upgrade: {len(pkgs)}")
424
+ if skipped:
425
+ print(f" Skipped (non-OS packages): {skipped}")
426
+ print(f" New image tag : {new_tag} (original untouched)")
427
+
428
+ if dry_run:
429
+ print("\n📄 Dockerfile preview (dry run):\n")
430
+ print(dockerfile)
431
+ return {"dry_run": True, "new_image": new_tag, "packages": pkgs}
432
+
433
+ print_colored("\n[+] Building fixed image...", Colors.CYAN)
434
+ ok, err = fixer.build_image(dockerfile, new_tag)
435
+ if not ok:
436
+ print_colored("❌ Build failed. Original image untouched.", Colors.RED)
437
+ print(err)
438
+ return None
439
+
440
+ print_colored(f"✅ Built {new_tag}", Colors.GREEN)
441
+ print_colored(f"\n[+] Verifying fix on {new_tag}...", Colors.CYAN)
442
+ after = collect_scan(new_tag, quiet=True)
443
+ print_comparison(before, after)
444
+
445
+ if after["summary"]["total"] >= before["summary"]["total"]:
446
+ print_colored("\n⚠️ Fixed image not better than original.", Colors.YELLOW)
447
+ print_colored("\n⚠️ Test fixed image before production use.", Colors.YELLOW)
448
+
449
+ return {
450
+ "dry_run": False,
451
+ "new_image": new_tag,
452
+ "scope": scope,
453
+ "packages_upgraded": pkgs,
454
+ "before": before["summary"],
455
+ "after": after["summary"],
456
+ "score_before": before["score"],
457
+ "score_after": after["score"],
458
+ }
459
+
460
+
461
+ def scan_image(image_name, output_file=None, fix=False, fix_all=False, dry_run=False, html_file=None):
462
+ result = collect_scan(image_name)
463
+ print_scan_report(result)
464
+
465
+ fix_info = None
466
+ if fix or fix_all or dry_run:
467
+ fix_info = run_fix(image_name, result, fix_all=fix_all, dry_run=dry_run)
468
+
469
+ if output_file:
470
+ save_report(make_report(result, fix_info), output_file)
471
+
472
+ if html_file:
473
+ try:
474
+ with open(html_file, "w", encoding="utf-8") as f:
475
+ f.write(render_html(make_report(result, fix_info)))
476
+ print_colored(f"🌐 HTML report saved to: {html_file}", Colors.GREEN)
477
+ cmd = f"start {html_file}" if platform.system() == "Windows" else f"xdg-open {html_file}"
478
+ print(f" Open with: {cmd}")
479
+ except Exception as e:
480
+ print_colored(f"❌ Failed to save HTML report: {e}", Colors.RED)
481
+
482
+
483
+ def main():
484
+ try:
485
+ sys.stdout.reconfigure(encoding="utf-8")
486
+ except Exception:
487
+ pass
488
+
489
+ config_dir = os.path.expanduser("~/.dockeriq")
490
+ first_run = os.path.join(config_dir, "first_run")
491
+ if not os.path.exists(first_run):
492
+ print("\n✨ Powered by Shahd Elsaidy")
493
+ print("Thank you for using DockerIQ!\n")
494
+ os.makedirs(config_dir, exist_ok=True)
495
+ with open(first_run, "w") as f:
496
+ f.write("done")
497
+
498
+ parser = argparse.ArgumentParser(prog="dockeriq", description="Advanced container security scanner")
499
+ parser.add_argument("command", choices=["scan"], help="Command to run")
500
+ parser.add_argument("image", help="Docker image name")
501
+ parser.add_argument("--upload", action="store_true", help="Upload to dashboard (Pro)")
502
+ parser.add_argument("--output", "-o", help="Save JSON report")
503
+ parser.add_argument("--html", metavar="FILE", help="Save HTML report")
504
+ parser.add_argument("--fix", action="store_true", help="Auto-fix Critical/High vulns")
505
+ parser.add_argument("--fix-all", action="store_true", help="Fix all severities")
506
+ parser.add_argument("--dry-run", action="store_true", help="Preview fix without building")
507
+
508
+ args = parser.parse_args()
509
+ scan_image(args.image, args.output, fix=args.fix, fix_all=args.fix_all,
510
+ dry_run=args.dry_run, html_file=args.html)
511
+
512
+
513
+ if __name__ == "__main__":
514
+ main()
@@ -0,0 +1,113 @@
1
+ """Build a fixed copy of a Docker image.
2
+
3
+ Safety design: nothing here asks an AI or a free-form command to modify the
4
+ image. Package names come from the scan report, are checked against a strict
5
+ allowlist pattern, and are placed into a fixed Dockerfile template that can
6
+ only run an upgrade command. The original image tag is never overwritten.
7
+ """
8
+
9
+ import re
10
+ import subprocess
11
+
12
+ APT_FAMILIES = {"debian", "ubuntu"}
13
+ APK_FAMILIES = {"alpine"}
14
+ SUPPORTED_FAMILIES = APT_FAMILIES | APK_FAMILIES
15
+
16
+ # Debian/Alpine package names: letters, digits and + . - _ (and : for epochs)
17
+ PKG_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9+._:\-]*$")
18
+ IMAGE_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._:/@\-]*$")
19
+ USER_RE = re.compile(r"^[a-zA-Z0-9_.:\-]+$")
20
+
21
+
22
+ def collect_upgrade_targets(vulns, severities=None):
23
+ """Return (os_family, sorted package names, number of skipped non-OS packages).
24
+
25
+ severities: set like {"CRITICAL", "HIGH"}, or None for all severities.
26
+ Only OS packages that have a fixed version are included.
27
+ """
28
+ by_family = {}
29
+ skipped = set()
30
+ for v in vulns:
31
+ if not (v.get("fixed_version") or "").strip():
32
+ continue
33
+ if severities is not None and v.get("severity") not in severities:
34
+ continue
35
+ family = (v.get("type") or "").lower()
36
+ if family in SUPPORTED_FAMILIES:
37
+ by_family.setdefault(family, set()).add(v["pkg"])
38
+ else:
39
+ skipped.add((v.get("pkg"), family))
40
+
41
+ if not by_family:
42
+ return "", [], len(skipped)
43
+
44
+ family = max(by_family, key=lambda f: len(by_family[f]))
45
+ pkgs = sorted(p for p in by_family[family] if PKG_RE.match(p))
46
+ return family, pkgs, len(skipped)
47
+
48
+
49
+ def fixed_tag(image):
50
+ """python:3.8 -> python:3.8-fixed (never the same as the original)."""
51
+ if "@" in image:
52
+ return image.split("@")[0] + ":digest-fixed"
53
+ last = image.rsplit("/", 1)[-1]
54
+ if ":" in last:
55
+ repo, tag = image.rsplit(":", 1)
56
+ else:
57
+ repo, tag = image, "latest"
58
+ return f"{repo}:{tag}-fixed"
59
+
60
+
61
+ def get_image_user(image):
62
+ """Return the USER the image runs as ('' means root / not set)."""
63
+ try:
64
+ r = subprocess.run(
65
+ ["docker", "inspect", "--format", "{{.Config.User}}", image],
66
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8",
67
+ )
68
+ if r.returncode == 0:
69
+ return r.stdout.strip()
70
+ except Exception:
71
+ pass
72
+ return ""
73
+
74
+
75
+ def build_dockerfile(image, family, pkgs, user=""):
76
+ """Create the Dockerfile text from a fixed template."""
77
+ if not IMAGE_RE.match(image):
78
+ raise ValueError(f"Unsafe image name: {image!r}")
79
+ if family not in SUPPORTED_FAMILIES:
80
+ raise ValueError(f"Unsupported OS family: {family!r}")
81
+ if not pkgs:
82
+ raise ValueError("No packages to upgrade")
83
+ for p in pkgs:
84
+ if not PKG_RE.match(p):
85
+ raise ValueError(f"Unsafe package name: {p!r}")
86
+ if user and not USER_RE.match(user):
87
+ raise ValueError(f"Unsafe USER value: {user!r}")
88
+
89
+ names = " ".join(pkgs)
90
+ lines = [f"FROM {image}", "USER root"]
91
+ if family in APT_FAMILIES:
92
+ lines.append(
93
+ "RUN apt-get update && apt-get install -y --only-upgrade "
94
+ f"{names} && rm -rf /var/lib/apt/lists/*"
95
+ )
96
+ else:
97
+ lines.append(f"RUN apk add --no-cache --upgrade {names}")
98
+ if user and user != "root":
99
+ lines.append(f"USER {user}")
100
+ return "\n".join(lines) + "\n"
101
+
102
+
103
+ def build_image(dockerfile_text, tag):
104
+ """docker build from stdin (no build context). Returns (ok, error_tail)."""
105
+ r = subprocess.run(
106
+ ["docker", "build", "-t", tag, "-"],
107
+ input=dockerfile_text, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
108
+ text=True, encoding="utf-8",
109
+ )
110
+ if r.returncode == 0:
111
+ return True, ""
112
+ tail = "\n".join((r.stderr or r.stdout or "").strip().splitlines()[-15:])
113
+ return False, tail
@@ -0,0 +1,123 @@
1
+ """Rule-based mitigation advice for vulnerabilities reported by Trivy."""
2
+
3
+ import re
4
+
5
+ # Names/versions that are safe to place inside a shell command.
6
+ SAFE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9+._:~\-]*$")
7
+
8
+ OS_COMMANDS = {
9
+ "debian": "apt-get update && apt-get install -y --only-upgrade {pkg}",
10
+ "ubuntu": "apt-get update && apt-get install -y --only-upgrade {pkg}",
11
+ "alpine": "apk add --no-cache --upgrade {pkg}",
12
+ "redhat": "yum update -y {pkg}",
13
+ "centos": "yum update -y {pkg}",
14
+ "amazon": "yum update -y {pkg}",
15
+ "rocky": "dnf update -y {pkg}",
16
+ "alma": "dnf update -y {pkg}",
17
+ "fedora": "dnf update -y {pkg}",
18
+ }
19
+
20
+ LANG_COMMANDS = {
21
+ "python-pkg": 'pip install --upgrade "{pkg}>={fixed}"',
22
+ "pip": 'pip install --upgrade "{pkg}>={fixed}"',
23
+ "pipenv": 'pip install --upgrade "{pkg}>={fixed}"',
24
+ "poetry": 'pip install --upgrade "{pkg}>={fixed}"',
25
+ "node-pkg": "npm install {pkg}@{fixed}",
26
+ "npm": "npm install {pkg}@{fixed}",
27
+ "yarn": "yarn upgrade {pkg}@{fixed}",
28
+ }
29
+
30
+
31
+ def get_mitigation(vuln):
32
+ """Return {"type", "summary", "command"} for one vulnerability dict."""
33
+ pkg = vuln.get("pkg", "unknown")
34
+ installed = vuln.get("installed_version") or "unknown"
35
+ fixed = (vuln.get("fixed_version") or "").strip()
36
+ status = (vuln.get("status") or "").lower()
37
+ res_type = (vuln.get("type") or "").lower()
38
+
39
+ # 1) A fixed version exists
40
+ if fixed:
41
+ target = fixed.split(",")[0].strip()
42
+ template = OS_COMMANDS.get(res_type) or LANG_COMMANDS.get(res_type)
43
+ command = None
44
+ # Only build a copy-pasteable command from safe-looking names/versions.
45
+ if template and SAFE_RE.match(pkg) and SAFE_RE.match(target):
46
+ command = template.format(pkg=pkg, fixed=target)
47
+
48
+ summary = f"Upgrade {pkg} from {installed} to {fixed}."
49
+ if res_type in OS_COMMANDS:
50
+ summary += " Or rebuild from a newer base image."
51
+ elif not command:
52
+ summary += " Update this dependency in your build file and rebuild."
53
+ return {"type": "upgrade", "summary": summary, "command": command}
54
+
55
+ # 2) The OS itself is end-of-life
56
+ if status == "end_of_life":
57
+ return {
58
+ "type": "eol",
59
+ "summary": "The OS of this image is end-of-life. Move to a supported base image.",
60
+ "command": None,
61
+ }
62
+
63
+ # 3) Vendor decided not to fix
64
+ if status == "will_not_fix":
65
+ return {
66
+ "type": "will_not_fix",
67
+ "summary": (f"The vendor will not fix this in {pkg}. Remove the package if unused, "
68
+ "switch to an alternative, or change the base image."),
69
+ "command": None,
70
+ }
71
+
72
+ # 4) No fix available yet
73
+ return {
74
+ "type": "no_fix",
75
+ "summary": (f"No patch available yet for {pkg}. Remove it if not needed, try a newer "
76
+ "or slimmer base image, limit network exposure, and re-scan regularly."),
77
+ "command": None,
78
+ }
79
+
80
+
81
+ def _natural_key(version):
82
+ """Approximate version ordering: compares digit runs as numbers.
83
+ Good enough for 1.2.10 > 1.2.9 and ...deb12u7 > ...deb12u4."""
84
+ parts = re.split(r"(\d+)", version)
85
+ return [(0, int(x)) if x.isdigit() else (1, x) for x in parts if x != ""]
86
+
87
+
88
+ def get_package_mitigation(vulns):
89
+ """Mitigation for ONE package (all its vulnerabilities together).
90
+
91
+ Picks the highest fixed version so a single upgrade closes every
92
+ fixable vulnerability in the package.
93
+ """
94
+ first = vulns[0]
95
+ fixed_list = []
96
+ for v in vulns:
97
+ fv = (v.get("fixed_version") or "").strip()
98
+ if fv:
99
+ fixed_list.append(fv.split(",")[0].strip())
100
+
101
+ total = len(vulns)
102
+ fixable = len(fixed_list)
103
+
104
+ if fixed_list:
105
+ target = max(fixed_list, key=_natural_key)
106
+ synthetic = {
107
+ "pkg": first.get("pkg"),
108
+ "installed_version": first.get("installed_version"),
109
+ "fixed_version": target,
110
+ "type": first.get("type"),
111
+ "status": "",
112
+ }
113
+ m = get_mitigation(synthetic)
114
+ m["fixes"] = fixable
115
+ m["unfixed"] = total - fixable
116
+ m["target_version"] = target
117
+ return m
118
+
119
+ m = get_mitigation(first)
120
+ m["fixes"] = 0
121
+ m["unfixed"] = total
122
+ m["target_version"] = ""
123
+ return m
@@ -0,0 +1,164 @@
1
+ """Render a DockerIQ report dict as a single self-contained HTML page."""
2
+
3
+ import html
4
+ from datetime import datetime
5
+
6
+ SEV_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "UNKNOWN"]
7
+ TOP_VISIBLE = 25
8
+
9
+
10
+ def esc(value):
11
+ return html.escape(str(value), quote=True)
12
+
13
+
14
+ def score_class(score):
15
+ if score >= 80:
16
+ return "good"
17
+ if score >= 50:
18
+ return "warn"
19
+ return "bad"
20
+
21
+
22
+ def sev_badge(sev):
23
+ return f'<span class="badge {esc(sev.lower())}">{esc(sev.capitalize())}</span>'
24
+
25
+
26
+ def counts_text(counts):
27
+ parts = []
28
+ for sev in SEV_ORDER:
29
+ if counts.get(sev):
30
+ parts.append(f"{counts[sev]} {sev.capitalize()}")
31
+ return ", ".join(parts)
32
+
33
+
34
+ def package_row(p):
35
+ m = p["mitigation"]
36
+ if m["type"] == "upgrade":
37
+ fix = f"<div>{esc(m['summary'])}</div>"
38
+ fix += f'<div class="muted">Closes {m["fixes"]} of {p["total"]} vulnerabilities in this package.</div>'
39
+ if m.get("command"):
40
+ fix += f"<code>{esc(m['command'])}</code>"
41
+ else:
42
+ fix = f"<div>{esc(m['summary'])}</div>"
43
+ examples = ", ".join(p["cve_ids"][:3])
44
+ more = f" +{p['total'] - 3} more" if p["total"] > 3 else ""
45
+ return (
46
+ "<tr>"
47
+ f"<td>{sev_badge(p['worst_severity'])}</td>"
48
+ f"<td><strong>{esc(p['pkg'])}</strong><div class='muted'>{esc(p['installed_version'])}</div></td>"
49
+ f"<td>{p['total']}<div class='muted'>{esc(counts_text(p['severity_counts']))}</div>"
50
+ f"<div class='muted'>{esc(examples)}{esc(more)}</div></td>"
51
+ f"<td>{fix}</td>"
52
+ "</tr>"
53
+ )
54
+
55
+
56
+ def packages_table(packages):
57
+ head = "<thead><tr><th>Severity</th><th>Package</th><th>Vulnerabilities</th><th>Recommended fix</th></tr></thead>"
58
+ top = "".join(package_row(p) for p in packages[:TOP_VISIBLE])
59
+ out = f"<div class='scroll'><table>{head}<tbody>{top}</tbody></table></div>"
60
+ rest = packages[TOP_VISIBLE:]
61
+ if rest:
62
+ rows = "".join(package_row(p) for p in rest)
63
+ out += (
64
+ f"<details><summary>Show {len(rest)} more packages</summary>"
65
+ f"<div class='scroll'><table>{head}<tbody>{rows}</tbody></table></div></details>"
66
+ )
67
+ return out
68
+
69
+
70
+ def fix_section(fix):
71
+ if not fix:
72
+ return ""
73
+ if fix.get("dry_run"):
74
+ return (
75
+ "<section><h2>Fix (dry run)</h2>"
76
+ f"<p>A fixed image <code>{esc(fix['new_image'])}</code> would be built by upgrading "
77
+ f"<strong>{len(fix['packages'])}</strong> packages. Nothing was built.</p></section>"
78
+ )
79
+ b, a = fix["before"], fix["after"]
80
+ rows = ""
81
+ for label, key in [("Critical", "critical"), ("High", "high"), ("Medium", "medium"),
82
+ ("Low", "low"), ("Total", "total")]:
83
+ diff = a[key] - b[key]
84
+ cls = "good" if diff < 0 else "bad" if diff > 0 else "muted"
85
+ sign = "+" if diff > 0 else ""
86
+ rows += (f"<tr><td>{label}</td><td>{b[key]}</td><td>{a[key]}</td>"
87
+ f"<td class='{cls}'>{sign}{diff}</td></tr>")
88
+ rows += (f"<tr><td>Score</td><td>{fix['score_before']}</td>"
89
+ f"<td>{fix['score_after']}</td><td></td></tr>")
90
+ return (
91
+ "<section><h2>Before vs after the fix</h2>"
92
+ f"<p>New image: <code>{esc(fix['new_image'])}</code> "
93
+ f"(scope: {esc(fix['scope'])}, {len(fix['packages_upgraded'])} packages upgraded). "
94
+ "The original image was not modified.</p>"
95
+ "<table class='compact'><thead><tr><th></th><th>Before</th><th>After</th><th>Change</th></tr></thead>"
96
+ f"<tbody>{rows}</tbody></table>"
97
+ "<p class='muted'>Test the fixed image before using it in production.</p></section>"
98
+ )
99
+
100
+
101
+ CSS = """
102
+ :root{--bg:#f7f8fa;--card:#fff;--text:#1d2129;--muted:#6b7280;--line:#e5e7eb;
103
+ --good:#2e7d32;--warn:#b26a00;--bad:#c62828;--code:#f1f3f5}
104
+ :root{color-scheme:light dark}
105
+ @media (prefers-color-scheme:dark){:root{--bg:#14161a;--card:#1d2026;--text:#e6e8eb;
106
+ --muted:#9aa3af;--line:#2d323b;--good:#6fcf76;--warn:#f0b04a;--bad:#ef7b7b;--code:#262b33}}
107
+ *{box-sizing:border-box}
108
+ body{margin:0;background:var(--bg);color:var(--text);
109
+ font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;line-height:1.5}
110
+ main{max-width:1000px;margin:0 auto;padding:24px 16px 48px}
111
+ h1{margin:0 0 4px;font-size:1.6rem}h2{font-size:1.15rem;margin:0 0 12px}
112
+ section,.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px;margin-top:16px}
113
+ .muted{color:var(--muted);font-size:.85rem}
114
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:12px;margin-top:16px}
115
+ .card{margin:0;text-align:center}.card .n{font-size:1.8rem;font-weight:700}
116
+ .score .n{font-size:2.6rem}
117
+ .good{color:var(--good)}.warn{color:var(--warn)}.bad{color:var(--bad)}
118
+ .scroll{overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:.92rem}
119
+ th,td{text-align:left;padding:8px 10px;border-bottom:1px solid var(--line);vertical-align:top}
120
+ table.compact{max-width:480px}
121
+ code{display:block;background:var(--code);padding:6px 8px;border-radius:6px;margin-top:6px;
122
+ font-family:ui-monospace,Consolas,monospace;font-size:.82rem;word-break:break-all}
123
+ p code{display:inline;padding:2px 6px;margin:0}
124
+ .badge{display:inline-block;padding:2px 8px;border-radius:999px;font-size:.78rem;font-weight:600;color:#fff}
125
+ .critical{background:#c62828}.high{background:#e65100}.medium{background:#b28704}.low{background:#2e7d32}.unknown{background:#6b7280}
126
+ details{margin-top:12px}summary{cursor:pointer;color:var(--muted)}
127
+ """
128
+
129
+
130
+ def render_html(report):
131
+ sm = report["summary"]
132
+ score = report["security_score"]
133
+ generated = report.get("timestamp", "")
134
+ try:
135
+ generated = datetime.fromisoformat(generated).strftime("%Y-%m-%d %H:%M")
136
+ except Exception:
137
+ pass
138
+
139
+ cards = (
140
+ f"<div class='card score'><div class='n {score_class(score)}'>{score}</div><div class='muted'>Security score / 100</div></div>"
141
+ f"<div class='card'><div class='n'>{sm['total']}</div><div class='muted'>Vulnerabilities</div></div>"
142
+ f"<div class='card'><div class='n'>{sm['critical']}</div><div class='muted'>Critical</div></div>"
143
+ f"<div class='card'><div class='n'>{sm['high']}</div><div class='muted'>High</div></div>"
144
+ f"<div class='card'><div class='n'>{sm['medium']}</div><div class='muted'>Medium</div></div>"
145
+ f"<div class='card'><div class='n'>{sm['low']}</div><div class='muted'>Low</div></div>"
146
+ f"<div class='card'><div class='n'>{sm.get('fixable', 0)}</div><div class='muted'>Fixable by upgrade</div></div>"
147
+ )
148
+
149
+ return f"""<!DOCTYPE html>
150
+ <html lang="en"><head><meta charset="utf-8">
151
+ <meta name="viewport" content="width=device-width, initial-scale=1">
152
+ <title>DockerIQ report - {esc(report['image'])}</title>
153
+ <style>{CSS}</style></head>
154
+ <body><main>
155
+ <h1>DockerIQ Security Report</h1>
156
+ <div class="muted">Image <strong>{esc(report['image'])}</strong> · generated {esc(generated)} · DockerIQ {esc(report.get('version', ''))}</div>
157
+ <div class="grid">{cards}</div>
158
+ {fix_section(report.get('fix'))}
159
+ <section><h2>Packages to fix ({sm.get('packages', len(report['packages']))} affected, {sm.get('fixable_packages', 0)} fixable by upgrade)</h2>
160
+ <p class="muted">Most severe first. One upgrade per package closes all of its fixable vulnerabilities. The full per-vulnerability list is in the JSON report (<code>-o</code>).</p>
161
+ {packages_table(report['packages'])}
162
+ </section>
163
+ </main></body></html>
164
+ """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dockeriq
3
- Version: 2.0.3
3
+ Version: 2.0.4
4
4
  Summary: Secure Docker images with automated vulnerability scanning
5
5
  Home-page: https://github.com/yourteam/dockeriq-cli
6
6
  Author: Your Team
@@ -13,14 +13,15 @@ Dynamic: home-page
13
13
  Dynamic: requires-python
14
14
  Dynamic: summary
15
15
 
16
+ > ⚠️ **Proprietary Software:** This repository contains documentation only.
17
+ > The actual source code is closed-source and protected under All Rights Reserved license.
18
+ > For commercial use, please contact dockerriq@gmail.com
16
19
  # DockerIQ CLI
17
20
 
18
21
  Scan Docker images for security vulnerabilities directly from your terminal.
19
22
 
20
23
  ## Requirements
21
24
  - Docker
22
- - Trivy (install from: https://github.com/aquasecurity/trivy)
23
-
24
25
  ## Install
25
26
  ```bash
26
27
  pip install dockeriq
@@ -2,6 +2,9 @@ README.md
2
2
  setup.py
3
3
  dockeriq/__init__.py
4
4
  dockeriq/cli.py
5
+ dockeriq/fixer.py
6
+ dockeriq/mitigation.py
7
+ dockeriq/report_html.py
5
8
  dockeriq.egg-info/PKG-INFO
6
9
  dockeriq.egg-info/SOURCES.txt
7
10
  dockeriq.egg-info/dependency_links.txt
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="dockeriq",
5
- version="2.0.3",
5
+ version="2.0.4",
6
6
  packages=find_packages(),
7
7
  entry_points={
8
8
  "console_scripts": [
dockeriq-2.0.3/README.md DELETED
@@ -1,12 +0,0 @@
1
- # DockerIQ CLI
2
-
3
- Scan Docker images for security vulnerabilities directly from your terminal.
4
-
5
- ## Requirements
6
- - Docker
7
- - Trivy (install from: https://github.com/aquasecurity/trivy)
8
-
9
- ## Install
10
- ```bash
11
- pip install dockeriq
12
-
@@ -1,273 +0,0 @@
1
- import subprocess
2
- import argparse
3
- import sys
4
- import json
5
- import os
6
- import platform
7
- import hashlib
8
- import tarfile
9
- import zipfile
10
- import shutil
11
- import urllib.request
12
- from datetime import datetime # ← موجودة أصلاً
13
-
14
- # ألوان الترمينال
15
- class Colors:
16
- RED = '\033[91m'
17
- ORANGE = '\033[93m'
18
- YELLOW = '\033[93m'
19
- GREEN = '\033[92m'
20
- CYAN = '\033[96m'
21
- BOLD = '\033[1m'
22
- END = '\033[0m'
23
-
24
- def print_colored(text, color):
25
- print(f"{color}{text}{Colors.END}")
26
-
27
- def calculate_score(vulns):
28
- score = 100
29
- for v in vulns:
30
- sev = v.get("severity", "").upper()
31
- if sev == "CRITICAL":
32
- score -= 10
33
- elif sev == "HIGH":
34
- score -= 5
35
- elif sev == "MEDIUM":
36
- score -= 2
37
- elif sev == "LOW":
38
- score -= 1
39
- return max(0, min(100, score))
40
-
41
- def get_or_download_trivy():
42
- home_dir = os.path.expanduser("~/.dockeriq")
43
- bin_dir = os.path.join(home_dir, "bin")
44
- trivy_exe = "trivy.exe" if platform.system() == "Windows" else "trivy"
45
- trivy_path = os.path.join(bin_dir, trivy_exe)
46
-
47
- if os.path.exists(trivy_path):
48
- return trivy_path
49
-
50
- os.makedirs(bin_dir, exist_ok=True)
51
- print_colored("[+] DockerIQ: Downloading vulnerability scanner (one-time only)...", Colors.CYAN)
52
-
53
- system = platform.system().lower()
54
- arch = platform.machine().lower()
55
-
56
- # تحديد نظام التشغيل
57
- if system == "darwin":
58
- os_name = "macOS"
59
- elif system == "windows":
60
- os_name = "Windows"
61
- else:
62
- os_name = "Linux"
63
-
64
- # تحديد البنية
65
- if arch in ("x86_64", "amd64"):
66
- arch_name = "64bit"
67
- elif arch in ("aarch64", "arm64"):
68
- arch_name = "ARM64"
69
- elif arch in ("armv7l", "armv7"):
70
- arch_name = "ARM"
71
- else:
72
- print_colored(f"❌ Unsupported architecture: {arch}", Colors.RED)
73
- sys.exit(1)
74
-
75
- version = "0.69.3"
76
- ext = "zip" if system == "windows" else "tar.gz"
77
- tarball_name = f"trivy_{version}_{os_name}-{arch_name}.{ext}"
78
- url = f"https://github.com/aquasecurity/trivy/releases/download/v{version}/{tarball_name}"
79
-
80
- try:
81
- tmp_file = os.path.join(bin_dir, tarball_name)
82
- urllib.request.urlretrieve(url, tmp_file)
83
-
84
- if ext == "zip":
85
- with zipfile.ZipFile(tmp_file, 'r') as zip_ref:
86
- zip_ref.extractall(bin_dir)
87
- else:
88
- with tarfile.open(tmp_file, 'r:gz') as tar_ref:
89
- tar_ref.extractall(bin_dir)
90
-
91
- # تحديد مكان الملف التنفيذي بعد الفك
92
- candidate_paths = [
93
- os.path.join(bin_dir, trivy_exe),
94
- os.path.join(bin_dir, f"trivy_{version}_{os_name}_{arch_name}", trivy_exe),
95
- ]
96
- found = False
97
- for src in candidate_paths:
98
- if os.path.exists(src):
99
- shutil.move(src, trivy_path)
100
- found = True
101
- break
102
-
103
- if not found:
104
- print_colored("❌ Failed to locate Trivy binary after extraction.", Colors.RED)
105
- sys.exit(1)
106
-
107
- if system != "windows":
108
- os.chmod(trivy_path, 0o755)
109
-
110
- os.remove(tmp_file)
111
- return trivy_path
112
-
113
- except Exception as e:
114
- print_colored(f"❌ Failed to download or extract Trivy: {e}", Colors.RED)
115
- print("👉 Please install Trivy manually from: https://github.com/aquasecurity/trivy")
116
- sys.exit(1)
117
-
118
- def scan_image(image_name, output_file=None): # ← أضفنا output_file هنا
119
- print_colored(f"\n[+] DockerIQ: Scanning image '{image_name}'...", Colors.CYAN)
120
-
121
- trivy_path = get_or_download_trivy()
122
-
123
- # أولًا: نزّل قاعدة البيانات
124
- try:
125
- subprocess.run([
126
- trivy_path, "image", "--download-db-only", "--quiet"
127
- ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
128
- except Exception:
129
- pass
130
-
131
- # ثانيًا: شغّل الفحص الحقيقي
132
- try:
133
- result = subprocess.run([
134
- trivy_path, "image",
135
- "--format", "json",
136
- "--no-progress",
137
- "--quiet",
138
- image_name
139
- ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
140
- except Exception as e:
141
- print_colored(f"❌ Scan failed to start: {e}", Colors.RED)
142
- sys.exit(1)
143
-
144
- if result.returncode not in (0, 1):
145
- print_colored(f"❌ Trivy error: {result.stderr.strip()}", Colors.RED)
146
- sys.exit(1)
147
-
148
- if not result.stdout.strip():
149
- print_colored("❌ Empty response from scanner.", Colors.RED)
150
- sys.exit(1)
151
-
152
- try:
153
- data = json.loads(result.stdout)
154
- except json.JSONDecodeError:
155
- print_colored("❌ Invalid scan output (not valid JSON).", Colors.RED)
156
- sys.exit(1)
157
-
158
- # استخرج الثغرات
159
- vulns = []
160
- for res in data.get("Results", []):
161
- for v in res.get("Vulnerabilities", []):
162
- vulns.append({
163
- "pkg": v.get("PkgName", "unknown"),
164
- "id": v.get("VulnerabilityID", "N/A"),
165
- "severity": v.get("Severity", "UNKNOWN").upper(),
166
- "title": v.get("Title", "No title available")
167
- })
168
-
169
- # حساب الدرجة والعرض
170
- critical = [v for v in vulns if v["severity"] == "CRITICAL"]
171
- high = [v for v in vulns if v["severity"] == "HIGH"]
172
- medium = [v for v in vulns if v["severity"] == "MEDIUM"]
173
- low = [v for v in vulns if v["severity"] == "LOW"]
174
- total = len(vulns)
175
- score = calculate_score(vulns)
176
-
177
- if total == 0:
178
- print_colored("\n✅ DockerIQ: No vulnerabilities found!", Colors.GREEN)
179
- print_colored(f"🛡️ Security Score: {score}/100", Colors.BOLD)
180
- else:
181
- print_colored(f"\n🚨 DockerIQ: Found {total} vulnerabilities", Colors.RED)
182
- print_colored(f"🛡️ Security Score: {score}/100", Colors.BOLD)
183
-
184
- print(f"\n📊 Summary:")
185
- if critical:
186
- print_colored(f" 🔴 Critical: {len(critical)}", Colors.RED)
187
- if high:
188
- print_colored(f" 🟠 High: {len(high)}", Colors.ORANGE)
189
- if medium:
190
- print_colored(f" 🟡 Medium: {len(medium)}", Colors.YELLOW)
191
- if low:
192
- print_colored(f" 🟢 Low: {len(low)}", Colors.GREEN)
193
-
194
- print(f"\n🔍 Details (first 5):")
195
- for v in vulns[:5]:
196
- sev = v["severity"]
197
- icon = "🔴" if sev == "CRITICAL" else "🟠" if sev == "HIGH" else "🟡" if sev == "MEDIUM" else "🟢"
198
- color = Colors.RED if sev == "CRITICAL" else Colors.ORANGE if sev == "HIGH" else Colors.YELLOW if sev == "MEDIUM" else Colors.GREEN
199
- pkg = v["pkg"]
200
- vid = v["id"]
201
- title = v["title"][:80] + "..." if len(v["title"]) > 80 else v["title"]
202
- print_colored(f" {icon} [{sev}] {vid} in `{pkg}`", color)
203
- print(f" → {title}\n")
204
-
205
- # 💾 === حفظ التقرير لو طلبه اليوزر ===
206
- if output_file:
207
- report = {
208
- "tool": "DockerIQ",
209
- "version": "2.0.1",
210
- "image": image_name,
211
- "timestamp": datetime.now().isoformat(),
212
- "security_score": score,
213
- "summary": {
214
- "total": total,
215
- "critical": len(critical),
216
- "high": len(high),
217
- "medium": len(medium),
218
- "low": len(low)
219
- },
220
- "vulnerabilities": vulns # كل الثغرات مش بس أول 5
221
- }
222
- try:
223
- with open(output_file, 'w', encoding='utf-8') as f:
224
- json.dump(report, f, indent=2, ensure_ascii=False)
225
- print_colored(f"\n💾 Report saved to: {output_file}", Colors.GREEN)
226
- except Exception as e:
227
- print_colored(f"❌ Failed to save report: {e}", Colors.RED)
228
-
229
-
230
- def main():
231
- # رسالة "Powered by" أول مرة
232
- config_dir = os.path.expanduser("~/.dockeriq")
233
- first_run = os.path.join(config_dir, "first_run")
234
- if not os.path.exists(first_run):
235
- print("\n Powered by Shahd Elsaidy")
236
- print("Thank you for using DockerIQ!\n")
237
- os.makedirs(config_dir, exist_ok=True)
238
- with open(first_run, "w") as f:
239
- f.write("done")
240
-
241
- parser = argparse.ArgumentParser(
242
- prog="dockeriq",
243
- description="Scan Docker images for vulnerabilities"
244
- )
245
- parser.add_argument(
246
- "command",
247
- choices=["scan"],
248
- help="Command to run (only 'scan' is supported)"
249
- )
250
- parser.add_argument(
251
- "image",
252
- help="Docker image name (e.g., nginx:latest or my-app)"
253
- )
254
- parser.add_argument(
255
- "--upload",
256
- action="store_true",
257
- help="Upload scan results to your dashboard (requires auth)"
258
- )
259
- # ← أضفنا الـ argument ده
260
- parser.add_argument(
261
- "--output", "-o",
262
- help="Save full scan results to JSON file"
263
- )
264
-
265
- args = parser.parse_args()
266
-
267
- # مررنا output_file هنا ↓
268
- scan_image(args.image, args.output)
269
-
270
-
271
- if __name__ == "__main__":
272
- main()
273
-
File without changes
File without changes