CI / contracts (push) Canceled after 0s
Website / deploy (push) Canceled after 0s
CI / test (macos-latest) (push) Canceled after 0s
CI / test (ubuntu-24.04) (push) Canceled after 0s
CI / test (ubuntu-24.04-arm) (push) Canceled after 0s
CI / test (windows-latest) (push) Canceled after 0s
CI / Compact real-tool fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Compact real-tool fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / Code analysis fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Code analysis fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / Web engine fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Web engine fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / Chromium operation fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Chromium operation fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / operation-readiness (push) Canceled after 0s
CI / Supply chain fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Supply chain fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
1089 lines
48 KiB
Diff
1089 lines
48 KiB
Diff
diff --git a/catalog/tools.yaml b/catalog/tools.yaml
|
||
index c737642..e8c96bd 100644
|
||
--- a/catalog/tools.yaml
|
||
+++ b/catalog/tools.yaml
|
||
@@ -313,15 +313,16 @@
|
||
title: testssl.sh
|
||
description: TLS/SSL protocol and cipher suite testing.
|
||
purpose: Audit TLS configuration, detect weak ciphers, protocol downgrades, and certificate issues.
|
||
- version: 3.2.0
|
||
+ version: 3.2.1
|
||
kind: native
|
||
- binary: testssl.sh
|
||
+ binary: testssl
|
||
+ supported_os: [linux]
|
||
source_url: https://github.com/drwetter/testssl.sh
|
||
license: GPL-2.0
|
||
capabilities: [tls.audit]
|
||
- default_args: [--jsonfile-pretty, /dev/stdout, --quiet]
|
||
+ default_args: []
|
||
output_format: json
|
||
- parser: testssl.json.v1
|
||
+ parser: cybot.testssl.json.v1
|
||
risk: active-network
|
||
requires_network: true
|
||
- id: nikto
|
||
diff --git a/docker/toolbox/package-audit.lock.json b/docker/toolbox/package-audit.lock.json
|
||
index 4041c5a..8eba96f 100644
|
||
--- a/docker/toolbox/package-audit.lock.json
|
||
+++ b/docker/toolbox/package-audit.lock.json
|
||
@@ -34,7 +34,10 @@
|
||
"corscanner",
|
||
"corscanner-engine",
|
||
"dirsearch",
|
||
- "dirsearch-engine"
|
||
+ "dirsearch-engine",
|
||
+ "testssl",
|
||
+ "testssl-engine",
|
||
+ "openssl"
|
||
],
|
||
"browser": [
|
||
"agent-browser",
|
||
diff --git a/docker/toolbox/testssl.lock.json b/docker/toolbox/testssl.lock.json
|
||
new file mode 100644
|
||
index 0000000..6a760cc
|
||
--- /dev/null
|
||
+++ b/docker/toolbox/testssl.lock.json
|
||
@@ -0,0 +1,108 @@
|
||
+{
|
||
+ "schema": 1,
|
||
+ "version": "3.2.1",
|
||
+ "package": {
|
||
+ "name": "testssl.sh",
|
||
+ "version": "3.2.1+dfsg-1",
|
||
+ "url": "https://deb.debian.org/debian/pool/main/t/testssl.sh/testssl.sh_3.2.1+dfsg-1_all.deb",
|
||
+ "size": 846272,
|
||
+ "sha256": "c6920c9565820e25db2d991ea8c9db882ea339773b126e47e26d623624a6cbe3"
|
||
+ },
|
||
+ "runtime_files": [
|
||
+ {
|
||
+ "path": "/usr/bin/testssl",
|
||
+ "sha256": "68077696b3220745851dd061d337531744255c580c4ccec53b12e1f02561c7e0",
|
||
+ "size": 1257772
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/Apple.pem",
|
||
+ "sha256": "2db2490ebe7cef949addd87b7259aa3831affdda17f31daf6686e6a3771f7d03",
|
||
+ "size": 234615
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/DST Root CA X3.txt",
|
||
+ "sha256": "139a5e4a4e0fa505378c72c5f700934ce8333f4e6b1b508886c4b0eb14f4be99",
|
||
+ "size": 1200
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/Java.pem",
|
||
+ "sha256": "48b13b7934e542fd873fddb01a7e0f88cdc20f6a54c70c7d50acf23c82105295",
|
||
+ "size": 170495
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/Linux.pem",
|
||
+ "sha256": "d21b08e596d2ddc24fa66563a1fdf6fb80456b1d5bab1f2efb983d0cd55cca74",
|
||
+ "size": 213777
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/Microsoft.pem",
|
||
+ "sha256": "b2e104face67d028aeab3635beebd88d3cf4c20351b8a8240c57f8e79472c2e2",
|
||
+ "size": 837043
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/Mozilla.pem",
|
||
+ "sha256": "50a6277ec69113f00c5fd45f09e8b97a4b3e32daa35d3a95ab30137a55386cef",
|
||
+ "size": 233263
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/README.md",
|
||
+ "sha256": "7f2411afd384441e8a5b433fd218ab02693e8e9aa625991243c0836487ead287",
|
||
+ "size": 4385
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/SSLSocketClient.java",
|
||
+ "sha256": "7c966961a20b8bd2bd53ca941bda7b32cde235289533230158e87253b6b3a7f3",
|
||
+ "size": 3425
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/ca_hashes.txt",
|
||
+ "sha256": "7238e645585c9beb5ee17f4b7f970330cdd41648f79091a64d3932dad8838b65",
|
||
+ "size": 40887
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/cipher-mapping.txt",
|
||
+ "sha256": "7a5efe10907d68de2c4c9ac29e9944817fa647e6c4e5673e16ec9cf20b54d944",
|
||
+ "size": 71389
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/client-simulation.txt",
|
||
+ "sha256": "d80415728b267a1ca91d996f94d024847611dac24f8f6bb064c1b70d976d2dd9",
|
||
+ "size": 299435
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/client-simulation.wiresharked.md",
|
||
+ "sha256": "543eb79a1344276b57f20ecf2f5f0063cd817289845accd1561017b486dbf779",
|
||
+ "size": 3824
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/client-simulation.wiresharked.txt",
|
||
+ "sha256": "3ab9b97091173e17ee5c57ec360655f2e327164299145947d2e9129fd7d03bd9",
|
||
+ "size": 113832
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/common-primes.txt",
|
||
+ "sha256": "b8463ee06af11c3934cfdb6766a646b98db01779ee93161317ee98417066f305",
|
||
+ "size": 52655
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/curves-mapping.txt",
|
||
+ "sha256": "448fbc8ff0e20af3eeae5e0702895b89affdba4b1aa324b1b460eaeb3c2ca476",
|
||
+ "size": 2394
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/curves.txt",
|
||
+ "sha256": "4119b7a279d68b98397479b157517920dbda2f2cbf5b85762208210071349fc6",
|
||
+ "size": 688
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/openssl.cnf",
|
||
+ "sha256": "1f877b6a065b7f0147e3d0fcb5c93383cb3f1082bb5bfb4934f49385e898bc2c",
|
||
+ "size": 10771
|
||
+ },
|
||
+ {
|
||
+ "path": "/etc/testssl/tls_data.txt",
|
||
+ "sha256": "631112806887978e524f4ce9d2c2e41c393ab5973347fa8e5ca0b5e2a0e3cd83",
|
||
+ "size": 78196
|
||
+ }
|
||
+ ]
|
||
+}
|
||
diff --git a/docker/toolbox/testssl_metadata.py b/docker/toolbox/testssl_metadata.py
|
||
new file mode 100644
|
||
index 0000000..9ee8ef8
|
||
--- /dev/null
|
||
+++ b/docker/toolbox/testssl_metadata.py
|
||
@@ -0,0 +1,37 @@
|
||
+"""Verify installed TestSSL engine/data bytes against the checked Debian package."""
|
||
+import hashlib
|
||
+from pathlib import Path, PurePosixPath
|
||
+import re
|
||
+
|
||
+
|
||
+def verify(lock, root=Path('/')):
|
||
+ if lock.get('schema')!=1 or lock.get('version')!='3.2.1' or not isinstance(lock.get('runtime_files'),list) or not 1<=len(lock['runtime_files'])<=64:
|
||
+ raise RuntimeError('Invalid TestSSL source manifest')
|
||
+ root=root.resolve(strict=True)
|
||
+ expected={};digest=hashlib.sha256();total=0
|
||
+ for row in lock['runtime_files']:
|
||
+ name=row.get('path','');relative=PurePosixPath(name)
|
||
+ if not relative.is_absolute() or '..' in relative.parts or not (name=='/usr/bin/testssl' or name.startswith('/etc/testssl/')) or name in expected:
|
||
+ raise RuntimeError('Unexpected TestSSL source path')
|
||
+ if not re.fullmatch('[a-f0-9]{64}',row.get('sha256','')) or type(row.get('size')) is not int or not 0<row['size']<=4*1024**2:
|
||
+ raise RuntimeError('Invalid TestSSL source identity')
|
||
+ path=root.joinpath(*relative.parts[1:])
|
||
+ for candidate in [path,*path.parents]:
|
||
+ if candidate==root:break
|
||
+ if candidate.is_symlink():raise RuntimeError('Unexpected TestSSL source symlink')
|
||
+ if not path.is_file() or path.stat().st_size!=row['size']:
|
||
+ raise RuntimeError('TestSSL source size differs from the checked package')
|
||
+ actual=hashlib.sha256(path.read_bytes()).hexdigest()
|
||
+ if actual!=row['sha256']:raise RuntimeError('TestSSL source bytes differ from the checked package')
|
||
+ total+=row['size']
|
||
+ if total>8*1024**2:raise RuntimeError('TestSSL source exceeds its bound')
|
||
+ expected[name]=actual
|
||
+ actual=set()
|
||
+ base=root/'etc/testssl'
|
||
+ if not base.is_dir() or base.is_symlink():raise RuntimeError('Missing regular TestSSL data directory')
|
||
+ for index,path in enumerate(base.rglob('*')):
|
||
+ if index>256 or path.is_symlink():raise RuntimeError('Unexpected TestSSL data tree')
|
||
+ if path.is_file():actual.add('/'+str(path.relative_to(root)))
|
||
+ if actual|{'/usr/bin/testssl'}!=set(expected):raise RuntimeError('TestSSL runtime file set differs from the checked package')
|
||
+ for name,value in sorted(expected.items()):digest.update(name.encode()+b'\0'+bytes.fromhex(value))
|
||
+ return digest.hexdigest()
|
||
diff --git a/docker/toolbox/testssl_wrapper.py b/docker/toolbox/testssl_wrapper.py
|
||
new file mode 100644
|
||
index 0000000..7adcf67
|
||
--- /dev/null
|
||
+++ b/docker/toolbox/testssl_wrapper.py
|
||
@@ -0,0 +1,96 @@
|
||
+#!/usr/bin/env python3
|
||
+"""Emit one bounded JSON document from Debian's TestSSL engine."""
|
||
+import argparse
|
||
+import ipaddress
|
||
+import json
|
||
+import os
|
||
+from pathlib import Path
|
||
+import re
|
||
+import resource
|
||
+import subprocess
|
||
+import tempfile
|
||
+
|
||
+ENGINE=Path('/usr/bin/testssl')
|
||
+DATA=Path('/etc/testssl')
|
||
+OPENSSL=Path('/usr/bin/openssl')
|
||
+VERSION='3.2.1'
|
||
+MAXIMUM=16*1024*1024
|
||
+
|
||
+
|
||
+def endpoint(value):
|
||
+ if not isinstance(value,str) or not value or len(value)>512 or any(c.isspace() or ord(c)<32 for c in value):
|
||
+ raise ValueError('Expected one hostname/IP with an optional TCP port')
|
||
+ host,port=value,443
|
||
+ if '%' in value:raise ValueError('Scoped IPv6 addresses are not supported')
|
||
+ try:
|
||
+ ipaddress.ip_address(host)
|
||
+ except ValueError:
|
||
+ if value.startswith('['):
|
||
+ match=re.fullmatch(r'\[([^\]]+)\]:([0-9]{1,5})',value)
|
||
+ if not match:raise ValueError('IPv6 ports require [address]:port')
|
||
+ host,port=match[1],int(match[2])
|
||
+ if ipaddress.ip_address(host).version!=6:raise ValueError('Expected bracketed IPv6 address')
|
||
+ elif ':' in value:
|
||
+ if value.count(':')!=1:raise ValueError('Invalid TLS endpoint')
|
||
+ host,raw=value.split(':')
|
||
+ if not re.fullmatch(r'[0-9]{1,5}',raw):raise ValueError('Invalid TCP port')
|
||
+ port=int(raw)
|
||
+ try:ipaddress.ip_address(host)
|
||
+ except ValueError:
|
||
+ if len(host)>253 or not all(re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?',label) for label in host.split('.')):
|
||
+ raise ValueError('Invalid hostname')
|
||
+ if not 1<=port<=65535:raise ValueError('Invalid TCP port')
|
||
+ return ('['+host+']' if ':' in host else host)+':'+str(port)
|
||
+
|
||
+
|
||
+def limits():
|
||
+ resource.setrlimit(resource.RLIMIT_FSIZE,(MAXIMUM,MAXIMUM))
|
||
+ resource.setrlimit(resource.RLIMIT_CORE,(0,0))
|
||
+
|
||
+
|
||
+def main():
|
||
+ parser=argparse.ArgumentParser(description=__doc__)
|
||
+ parser.add_argument('--version',action='version',version='testssl '+VERSION+' (CYBOT structured adapter)')
|
||
+ parser.add_argument('--target',required=True)
|
||
+ parser.add_argument('--checks',choices=('full','protocols'),default='full')
|
||
+ options=parser.parse_args()
|
||
+ try:target=endpoint(options.target)
|
||
+ except ValueError as error:parser.error(str(error))
|
||
+ result={'schema':1,'engine':'testssl','version':VERSION,'target':options.target,'checks':options.checks,
|
||
+ 'completed':False,'exit_code':1,'report':None,'error':''}
|
||
+ with tempfile.TemporaryDirectory(prefix='cybot-tls-') as temp:
|
||
+ root=Path(temp);report=root/'scan.json'
|
||
+ env={'PATH':'/usr/bin:/bin','HOME':str(root),'TMPDIR':str(root),'LC_ALL':'C',
|
||
+ 'OPENSSL':str(OPENSSL),'TESTSSL_INSTALL_DIR':str(DATA)}
|
||
+ args=[str(ENGINE),'--warnings','batch','--color','0','--quiet','--ip','one',
|
||
+ '--connect-timeout','5','--openssl-timeout','5','--jsonfile-pretty',str(report)]
|
||
+ if options.checks=='protocols':args+=['--protocols']
|
||
+ args+=[target]
|
||
+ try:
|
||
+ with (root/'diagnostic.txt').open('wb') as output:
|
||
+ process=subprocess.run(args,cwd=root,env=env,stdin=subprocess.DEVNULL,stdout=output,stderr=subprocess.STDOUT,
|
||
+ timeout=900,preexec_fn=limits)
|
||
+ result['exit_code']=process.returncode
|
||
+ result['completed']=process.returncode==0
|
||
+ if process.returncode:result['error']='TestSSL engine failed; no complete TLS assessment is established'
|
||
+ except (OSError,subprocess.TimeoutExpired):
|
||
+ result['error']='TestSSL engine failed or timed out; no complete TLS assessment is established'
|
||
+ if report.is_file() and not report.is_symlink() and report.stat().st_size<=MAXIMUM:
|
||
+ try:
|
||
+ data=json.loads(report.read_bytes())
|
||
+ if not isinstance(data,dict):raise ValueError('Expected report object')
|
||
+ # These headers expose local host paths and the scratch command.
|
||
+ data.pop('Invocation',None);data.pop('at',None)
|
||
+ result['report']=data
|
||
+ except (ValueError,UnicodeError):result['error']='TestSSL did not emit a complete bounded JSON report'
|
||
+ else:result['error']='TestSSL did not emit a complete bounded JSON report'
|
||
+ if result['error']:result['completed']=False
|
||
+ encoded=json.dumps(result,separators=(',',':'))
|
||
+ if len(encoded.encode())>MAXIMUM:
|
||
+ result.update(completed=False,report=None,error='TestSSL structured output exceeded its bound')
|
||
+ encoded=json.dumps(result,separators=(',',':'))
|
||
+ print(encoded)
|
||
+ return 0 if result['completed'] else 1
|
||
+
|
||
+
|
||
+if __name__=='__main__':raise SystemExit(main())
|
||
diff --git a/docker/toolbox/web.lock.json b/docker/toolbox/web.lock.json
|
||
index fa7ee92..19c7f88 100644
|
||
--- a/docker/toolbox/web.lock.json
|
||
+++ b/docker/toolbox/web.lock.json
|
||
@@ -10,7 +10,9 @@
|
||
"ruby": "1:3.3+b1",
|
||
"ruby-json": "2.9.1+dfsg-1+b1",
|
||
"libruby3.3": "3.3.8-2",
|
||
- "ruby3.3": "3.3.8-2"
|
||
+ "ruby3.3": "3.3.8-2",
|
||
+ "testssl.sh": "3.2.1+dfsg-1",
|
||
+ "openssl": "3.5.7-1~deb13u3"
|
||
},
|
||
"arm64": {
|
||
"ca-certificates": "20250419+deb13u1",
|
||
@@ -19,7 +21,9 @@
|
||
"ruby": "1:3.3+b1",
|
||
"ruby-json": "2.9.1+dfsg-1+b1",
|
||
"libruby3.3": "3.3.8-2",
|
||
- "ruby3.3": "3.3.8-2"
|
||
+ "ruby3.3": "3.3.8-2",
|
||
+ "testssl.sh": "3.2.1+dfsg-1",
|
||
+ "openssl": "3.5.7-1~deb13u3"
|
||
}
|
||
},
|
||
"go_tools": {
|
||
diff --git a/internal/capability/external.go b/internal/capability/external.go
|
||
index adf8124..a3b1529 100644
|
||
--- a/internal/capability/external.go
|
||
+++ b/internal/capability/external.go
|
||
@@ -64,6 +64,13 @@ func (c externalCapability) Definition() schema.CapabilityDefinition {
|
||
d.Documentation.Description = "Extract HTTP(S) URL candidates from a bounded local text file using the pinned cybot-urls GF pattern, then deduplicate with Anew."
|
||
d.Documentation.Limitations = append(d.Documentation.Limitations, "Only the bundled URL pattern is selected; candidates do not establish endpoint reachability or a vulnerability.", "Target must be a regular local text file no larger than 1 MiB.")
|
||
}
|
||
+ if c.ID() == "tls.audit" {
|
||
+ d.Stability = "experimental"
|
||
+ d.Documentation.Description = "Audit one authorized TLS endpoint using TestSSL 3.2.1. Select full checks or protocol negotiation only."
|
||
+ d.Documentation.Arguments = append(d.Documentation.Arguments, schema.Argument{Name: "checks", Type: "string", Required: false, Description: "full (default) or protocols; provide in an input JSON object."})
|
||
+ d.Documentation.Limitations = append(d.Documentation.Limitations, "Only the first selected DNS address is tested. Optional cipher-engine/client limitations remain explicit and prevent complete full-scan assurance.", "External revocation services are not contacted. Findings require deployment-context review.")
|
||
+ d.InputSchema = jsonRaw(`{"type":"object","additionalProperties":false,"required":["target"],"properties":{"target":{"type":"string","minLength":1},"checks":{"type":"string","enum":["full","protocols"],"default":"full"}}}`)
|
||
+ }
|
||
if c.ID() == "js.extract" {
|
||
d.Stability = "experimental"
|
||
d.Documentation.Description = "Extract HTTP(S) endpoint candidates and unresolved relative paths from one bounded local JavaScript file using JSLuice and LinkFinder."
|
||
@@ -98,6 +105,9 @@ func (c externalCapability) Run(ctx context.Context, req schema.RunRequest, d De
|
||
if err := validateCapabilityTarget(c.ID(), target); err != nil {
|
||
return emptyResult(), err
|
||
}
|
||
+ if err := c.ValidateRequest(req); err != nil {
|
||
+ return emptyResult(), err
|
||
+ }
|
||
combined := emptyResult()
|
||
completed := 0
|
||
var previous []byte
|
||
@@ -328,10 +338,8 @@ func validateCapabilityTarget(id, target string) error {
|
||
case "web.map", "web.scan", "web.content.discover", "api.audit", "tech.fingerprint", "waf.detect", "dir.bruteforce", "vuln.scan", "sql.inject", "xss.detect", "cors.audit", "cms.detect":
|
||
return validateBrowserTarget(target)
|
||
case "tls.audit":
|
||
- if net.ParseIP(target) != nil {
|
||
- return nil
|
||
- }
|
||
- return validateHostname(target)
|
||
+ _, _, err := tlsEndpoint(target)
|
||
+ return err
|
||
case "code.audit", "secret.scan", "dependency.scan", "cloud.review", "js.analyse":
|
||
if _, err := os.Stat(target); err != nil {
|
||
return fmt.Errorf("target must be an existing local path: %w", err)
|
||
@@ -618,8 +626,9 @@ func gobusterArgs(target string, _ schema.RunRequest) []string {
|
||
base := strings.TrimRight(target, "/")
|
||
return []string{"dir", "-u", base, "-w", "/opt/cybot/share/seclists/Discovery/Web-Content/common.txt", "--expanded", "--no-color", "--no-progress", "--threads", "2", "--delay", "200ms", "--timeout", "5s", "-q"}
|
||
}
|
||
-func testsslArgs(target string, _ schema.RunRequest) []string {
|
||
- return []string{"--jsonfile-pretty", "/dev/stdout", "--quiet", target}
|
||
+func testsslArgs(target string, req schema.RunRequest) []string {
|
||
+ checks, _ := tlsChecks(req) // ValidateRequest rejects invalid input before execution.
|
||
+ return []string{"--target", target, "--checks", checks}
|
||
}
|
||
func niktoArgs(target string, _ schema.RunRequest) []string {
|
||
return []string{"-h", target, "-Format", "json", "-nointeractive"}
|
||
diff --git a/internal/capability/live_tls_test.go b/internal/capability/live_tls_test.go
|
||
new file mode 100644
|
||
index 0000000..c677d14
|
||
--- /dev/null
|
||
+++ b/internal/capability/live_tls_test.go
|
||
@@ -0,0 +1,80 @@
|
||
+package capability
|
||
+
|
||
+import (
|
||
+ "context"
|
||
+ "crypto/tls"
|
||
+ "net"
|
||
+ "net/http"
|
||
+ "net/http/httptest"
|
||
+ "os"
|
||
+ "strings"
|
||
+ "testing"
|
||
+ "time"
|
||
+
|
||
+ "encoding/json"
|
||
+
|
||
+ "github.com/s41r4j/cybot/pkg/schema"
|
||
+)
|
||
+
|
||
+func TestLiveWebTLSProtocols(t *testing.T) {
|
||
+ if testing.Short() {
|
||
+ t.Skip("real TLS protocol negotiation")
|
||
+ }
|
||
+ if os.Getenv("CYBOT_LIVE_WEB") != "1" {
|
||
+ t.Skip("requires installed web-profile TLS engine")
|
||
+ }
|
||
+ d := liveDeps(t)
|
||
+ d.Timeout = 90 * time.Second
|
||
+ server := func(weak bool) *httptest.Server {
|
||
+ t.Helper()
|
||
+ s := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
+ w.WriteHeader(http.StatusOK)
|
||
+ _, _ = w.Write([]byte("Owned CYBOT TLS fixture"))
|
||
+ }))
|
||
+ s.TLS = &tls.Config{MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS13}
|
||
+ if weak {
|
||
+ s.TLS.MinVersion, s.TLS.MaxVersion = tls.VersionTLS10, tls.VersionTLS12
|
||
+ s.TLS.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA}
|
||
+ }
|
||
+ s.StartTLS()
|
||
+ t.Cleanup(s.Close)
|
||
+ return s
|
||
+ }
|
||
+ c := liveCapability(t, "tls.audit")
|
||
+ request := func(target string) schema.RunRequest {
|
||
+ req := liveRequest(target)
|
||
+ req.Input = json.RawMessage(`{"checks":"protocols"}`)
|
||
+ return req
|
||
+ }
|
||
+ weak := server(true)
|
||
+ target := strings.TrimPrefix(weak.URL, "https://")
|
||
+ r, err := c.Run(context.Background(), request(target), d)
|
||
+ found := false
|
||
+ for _, finding := range r.Findings {
|
||
+ found = found || finding.Title == "TLS1" || finding.Title == "TLS1_1"
|
||
+ }
|
||
+ if err != nil || len(r.Errors) != 0 || r.Status == "partial" || !found || len(r.Evidence) != 1 {
|
||
+ t.Fatalf("real legacy TLS protocols were missed: %+v %v", r, err)
|
||
+ }
|
||
+ validateFixtureResult(t, r)
|
||
+ modern := server(false)
|
||
+ r, err = c.Run(context.Background(), request(strings.TrimPrefix(modern.URL, "https://")), d)
|
||
+ if err != nil || len(r.Errors) != 0 || len(r.Findings) != 0 || r.Status == "partial" || len(r.Evidence) != 1 {
|
||
+ t.Fatalf("modern protocol fixture produced a false issue: %+v %v", r, err)
|
||
+ }
|
||
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||
+ if err != nil {
|
||
+ t.Fatal(err)
|
||
+ }
|
||
+ closed := listener.Addr().String()
|
||
+ _ = listener.Close()
|
||
+ r, err = c.Run(context.Background(), request(closed), d)
|
||
+ if err == nil && r.Status != "partial" && len(r.Errors) == 0 {
|
||
+ t.Fatalf("closed TLS endpoint was reported clean: %+v", r)
|
||
+ }
|
||
+ certifyOperation(t, "testssl", "tls.audit", []operationCase{
|
||
+ passedCase("positive", "Real TestSSL protocol mode detects deprecated TLS 1.0/1.1 offered by an owned TLS fixture."),
|
||
+ passedCase("negative", "TLS 1.2/1.3-only fixture produces protocol observations with no invented vulnerability findings."),
|
||
+ passedCase("failure", "A closed loopback TLS endpoint fails explicitly; no clean assessment is established."),
|
||
+ })
|
||
+}
|
||
diff --git a/internal/capability/parsers.go b/internal/capability/parsers.go
|
||
index 3850cb3..74dd3a2 100644
|
||
--- a/internal/capability/parsers.go
|
||
+++ b/internal/capability/parsers.go
|
||
@@ -743,45 +743,6 @@ func parseTextLines(data []byte, req schema.RunRequest) (schema.Result, error) {
|
||
return r, nil
|
||
}
|
||
|
||
-func parseTestSSL(data []byte, req schema.RunRequest) (schema.Result, error) {
|
||
- var doc map[string]any
|
||
- if err := json.Unmarshal(data, &doc); err != nil {
|
||
- return emptyResult(), fmt.Errorf("testssl: %w", err)
|
||
- }
|
||
- if _, ok := doc["scanResult"].([]any); !ok {
|
||
- return emptyResult(), fmt.Errorf("testssl: missing scanResult array")
|
||
- }
|
||
- r := emptyResult()
|
||
- for _, scan := range array(doc["scanResult"]) {
|
||
- if m, ok := scan.(map[string]any); ok {
|
||
- id := text(m["id"])
|
||
- finding := text(m["finding"])
|
||
- severity := text(m["severity"])
|
||
- if id != "" && finding != "" {
|
||
- sev := schema.SeverityInfo
|
||
- switch strings.ToUpper(severity) {
|
||
- case "CRITICAL":
|
||
- sev = schema.SeverityCritical
|
||
- case "HIGH":
|
||
- sev = schema.SeverityHigh
|
||
- case "MEDIUM":
|
||
- sev = schema.SeverityMedium
|
||
- case "LOW":
|
||
- sev = schema.SeverityLow
|
||
- }
|
||
- h := sha256.Sum256([]byte("testssl" + id))
|
||
- r.Findings = append(r.Findings, schema.Finding{
|
||
- ID: hex.EncodeToString(h[:])[:8], Title: id,
|
||
- Description: finding, Severity: sev, Confidence: 0.9,
|
||
- })
|
||
- }
|
||
- }
|
||
- }
|
||
- r.Summary = fmt.Sprintf("TLS audit completed with %d finding(s).", len(r.Findings))
|
||
- r.Confidence = 0.85
|
||
- return r, nil
|
||
-}
|
||
-
|
||
func parseSQLMap(data []byte, req schema.RunRequest) (schema.Result, error) {
|
||
// Only a completed parameter block is positive evidence. Words in progress,
|
||
// negative, and error messages are not findings.
|
||
diff --git a/internal/capability/tls.go b/internal/capability/tls.go
|
||
new file mode 100644
|
||
index 0000000..fe35e08
|
||
--- /dev/null
|
||
+++ b/internal/capability/tls.go
|
||
@@ -0,0 +1,261 @@
|
||
+package capability
|
||
+
|
||
+import (
|
||
+ "bytes"
|
||
+ "crypto/sha256"
|
||
+ "encoding/hex"
|
||
+ "encoding/json"
|
||
+ "fmt"
|
||
+ "io"
|
||
+ "net"
|
||
+ "strconv"
|
||
+ "strings"
|
||
+
|
||
+ "github.com/s41r4j/cybot/internal/evidence"
|
||
+ "github.com/s41r4j/cybot/pkg/schema"
|
||
+)
|
||
+
|
||
+func tlsEndpoint(target string) (string, int, error) {
|
||
+ host, port := target, 443
|
||
+ if net.ParseIP(target) == nil && strings.Contains(target, ":") {
|
||
+ var raw string
|
||
+ var err error
|
||
+ host, raw, err = net.SplitHostPort(target)
|
||
+ if err != nil || raw == "" || len(raw) > 5 {
|
||
+ return "", 0, fmt.Errorf("TLS target must be a hostname/IP with an optional TCP port; bracket IPv6 ports")
|
||
+ }
|
||
+ if strings.HasPrefix(target, "[") && (net.ParseIP(host) == nil || !strings.Contains(host, ":")) {
|
||
+ return "", 0, fmt.Errorf("TLS brackets are reserved for IPv6 addresses")
|
||
+ }
|
||
+ for _, c := range raw {
|
||
+ if c < '0' || c > '9' {
|
||
+ return "", 0, fmt.Errorf("TLS target requires a numeric TCP port")
|
||
+ }
|
||
+ }
|
||
+ port, err = strconv.Atoi(raw)
|
||
+ if err != nil || port < 1 || port > 65535 {
|
||
+ return "", 0, fmt.Errorf("TLS target TCP port is outside 1–65535")
|
||
+ }
|
||
+ }
|
||
+ if net.ParseIP(host) == nil {
|
||
+ if err := validateHostname(host); err != nil {
|
||
+ return "", 0, err
|
||
+ }
|
||
+ }
|
||
+ return host, port, nil
|
||
+}
|
||
+
|
||
+type tlsCheck struct {
|
||
+ ID string `json:"id"`
|
||
+ Severity string `json:"severity"`
|
||
+ Finding string `json:"finding"`
|
||
+ CVE string `json:"cve,omitempty"`
|
||
+ CWE string `json:"cwe,omitempty"`
|
||
+ Hint string `json:"hint,omitempty"`
|
||
+}
|
||
+
|
||
+func tlsChecks(req schema.RunRequest) (string, error) {
|
||
+ data := bytes.TrimSpace(req.Input)
|
||
+ if len(data) == 0 {
|
||
+ return "full", nil
|
||
+ }
|
||
+ var input struct {
|
||
+ Target json.RawMessage `json:"target,omitempty"`
|
||
+ Checks json.RawMessage `json:"checks,omitempty"`
|
||
+ }
|
||
+ decoder := json.NewDecoder(bytes.NewReader(data))
|
||
+ decoder.DisallowUnknownFields()
|
||
+ if len(data) > 4096 || data[0] != '{' || decoder.Decode(&input) != nil || decoder.Decode(new(any)) != io.EOF {
|
||
+ return "", fmt.Errorf("TLS input must be one bounded object containing target and optional checks")
|
||
+ }
|
||
+ if len(input.Target) != 0 {
|
||
+ var target string
|
||
+ if json.Unmarshal(input.Target, &target) != nil || target != req.Target {
|
||
+ return "", fmt.Errorf("TLS input cannot change the requested target")
|
||
+ }
|
||
+ }
|
||
+ if len(input.Checks) == 0 {
|
||
+ return "full", nil
|
||
+ }
|
||
+ var checks string
|
||
+ if json.Unmarshal(input.Checks, &checks) != nil || checks != "full" && checks != "protocols" {
|
||
+ return "", fmt.Errorf("TLS checks must be full or protocols")
|
||
+ }
|
||
+ return checks, nil
|
||
+}
|
||
+
|
||
+func (c externalCapability) ValidateRequest(req schema.RunRequest) error {
|
||
+ if c.ID() != "tls.audit" {
|
||
+ return nil
|
||
+ }
|
||
+ if _, _, err := tlsEndpoint(req.Target); err != nil {
|
||
+ return err
|
||
+ }
|
||
+ _, err := tlsChecks(req)
|
||
+ return err
|
||
+}
|
||
+
|
||
+func parseTestSSL(data []byte, req schema.RunRequest) (schema.Result, error) {
|
||
+ r := emptyResult()
|
||
+ var wrapper struct {
|
||
+ Schema int `json:"schema"`
|
||
+ Engine string `json:"engine"`
|
||
+ Version string `json:"version"`
|
||
+ Target string `json:"target"`
|
||
+ Checks string `json:"checks"`
|
||
+ Completed bool `json:"completed"`
|
||
+ ExitCode *int `json:"exit_code"`
|
||
+ Report json.RawMessage `json:"report"`
|
||
+ Error string `json:"error"`
|
||
+ }
|
||
+ decoder := json.NewDecoder(bytes.NewReader(data))
|
||
+ decoder.DisallowUnknownFields()
|
||
+ if len(data) > 16*1024*1024 || decoder.Decode(&wrapper) != nil || decoder.Decode(new(any)) != io.EOF {
|
||
+ return r, fmt.Errorf("testssl: missing bounded structured report")
|
||
+ }
|
||
+ if wrapper.Schema != 1 || wrapper.Engine != "testssl" || wrapper.Version != "3.2.1" || wrapper.ExitCode == nil || wrapper.Target != strings.TrimSpace(req.Target) || wrapper.Checks != "full" && wrapper.Checks != "protocols" {
|
||
+ return r, fmt.Errorf("testssl: unsupported or differently scoped report")
|
||
+ }
|
||
+ expected, err := tlsChecks(req)
|
||
+ if err != nil || wrapper.Checks != expected {
|
||
+ return r, fmt.Errorf("testssl: report does not match the requested TLS check scope")
|
||
+ }
|
||
+ host, port, err := tlsEndpoint(wrapper.Target)
|
||
+ if err != nil {
|
||
+ return r, err
|
||
+ }
|
||
+ incomplete := func(detail string) {
|
||
+ r.Status = "partial"
|
||
+ r.Errors = append(r.Errors, schema.RunError{Tool: "testssl", Code: "TLS_ASSESSMENT_INCOMPLETE", Message: detail})
|
||
+ }
|
||
+ if !wrapper.Completed || *wrapper.ExitCode != 0 || wrapper.Error != "" {
|
||
+ incomplete("TestSSL did not establish a completed operation.")
|
||
+ }
|
||
+ var report map[string]json.RawMessage
|
||
+ if json.Unmarshal(wrapper.Report, &report) != nil || report == nil {
|
||
+ if r.Status == "partial" {
|
||
+ return r, nil
|
||
+ }
|
||
+ return r, fmt.Errorf("testssl: engine report is missing")
|
||
+ }
|
||
+ var version string
|
||
+ if json.Unmarshal(report["version"], &version) != nil || len(strings.Fields(version)) == 0 || strings.Fields(version)[0] != wrapper.Version {
|
||
+ if r.Status == "partial" {
|
||
+ return r, nil
|
||
+ }
|
||
+ return emptyResult(), fmt.Errorf("testssl: engine version differs from its adapter")
|
||
+ }
|
||
+ var duration *float64
|
||
+ if json.Unmarshal(report["scanTime"], &duration) != nil || duration == nil || *duration < 0 {
|
||
+ incomplete("TestSSL scan footer is missing or reports interruption.")
|
||
+ }
|
||
+ var scans []map[string]json.RawMessage
|
||
+ if json.Unmarshal(report["scanResult"], &scans) != nil || scans == nil || len(scans) > 1 {
|
||
+ return emptyResult(), fmt.Errorf("testssl: expected one scoped TLS endpoint")
|
||
+ }
|
||
+ if len(scans) == 0 {
|
||
+ incomplete("TestSSL did not test a TLS endpoint.")
|
||
+ return r, nil
|
||
+ }
|
||
+ var actualHost, actualIP, actualPort string
|
||
+ scan := scans[0]
|
||
+ if json.Unmarshal(scan["targetHost"], &actualHost) != nil || json.Unmarshal(scan["ip"], &actualIP) != nil || json.Unmarshal(scan["port"], &actualPort) != nil || net.ParseIP(actualIP) == nil {
|
||
+ return emptyResult(), fmt.Errorf("testssl: endpoint identity is incomplete")
|
||
+ }
|
||
+ p, err := strconv.Atoi(actualPort)
|
||
+ sameHost := strings.EqualFold(host, actualHost)
|
||
+ if ip := net.ParseIP(host); ip != nil {
|
||
+ sameHost = ip.Equal(net.ParseIP(actualHost)) && ip.Equal(net.ParseIP(actualIP))
|
||
+ }
|
||
+ if err != nil || p != port || !sameHost {
|
||
+ return emptyResult(), fmt.Errorf("testssl: report describes a different TLS endpoint")
|
||
+ }
|
||
+ sections := []string{"pretest", "protocols", "grease", "ciphers", "serverPreferences", "fs", "serverDefaults", "headerResponse", "vulnerabilities", "cipherTests", "browserSimulations", "rating"}
|
||
+ known := map[string]bool{"targetHost": true, "ip": true, "port": true, "rDNS": true, "service": true, "hostname": true}
|
||
+ checks, seen := 0, map[string]bool{}
|
||
+ consume := func(raw json.RawMessage, section string, client bool) {
|
||
+ var rows []json.RawMessage
|
||
+ if json.Unmarshal(raw, &rows) != nil || rows == nil || len(rows) > 10000 {
|
||
+ incomplete("TestSSL returned an invalid check section.")
|
||
+ return
|
||
+ }
|
||
+ for _, row := range rows {
|
||
+ var check tlsCheck
|
||
+ decoder := json.NewDecoder(bytes.NewReader(row))
|
||
+ decoder.DisallowUnknownFields()
|
||
+ if decoder.Decode(&check) != nil || check.ID == "" || len(check.ID) > 256 || check.Finding == "" || len(check.Finding) > 16384 || len(check.Hint) > 16384 || len(check.CVE) > 4096 || len(check.CWE) > 1024 {
|
||
+ incomplete("TestSSL returned an invalid check record.")
|
||
+ continue
|
||
+ }
|
||
+ identity := section + "/" + check.ID
|
||
+ if seen[identity] {
|
||
+ incomplete("TestSSL repeated a check identity.")
|
||
+ continue
|
||
+ }
|
||
+ seen[identity] = true
|
||
+ text := evidence.DefaultHygieneRules.SanitizeText(check.ID + ": " + check.Finding)
|
||
+ if client {
|
||
+ r.Warnings = append(r.Warnings, text)
|
||
+ // GOST cipher-engine support is outside protocol negotiation.
|
||
+ if wrapper.Checks != "protocols" || check.ID != "engine_problem" || check.Severity != "WARN" || !strings.HasPrefix(check.Finding, "No engine or GOST support via engine with your ") {
|
||
+ incomplete("The scanner reported a client-side limitation.")
|
||
+ }
|
||
+ continue
|
||
+ }
|
||
+ checks++
|
||
+ severity := map[string]schema.Severity{"LOW": schema.SeverityLow, "MEDIUM": schema.SeverityMedium, "HIGH": schema.SeverityHigh, "CRITICAL": schema.SeverityCritical}[check.Severity]
|
||
+ if severity != "" {
|
||
+ digest := sha256.Sum256([]byte(net.JoinHostPort(host, strconv.Itoa(port)) + "\x00" + identity))
|
||
+ r.Findings = append(r.Findings, schema.Finding{ID: hex.EncodeToString(digest[:])[:16], Title: check.ID, Description: text + ". Review deployment context and supporting handshake evidence before assigning impact.", Severity: severity, Confidence: .9, EvidenceIDs: []string{}})
|
||
+ } else if check.Severity == "OK" || check.Severity == "INFO" || check.Severity == "WARN" {
|
||
+ r.Observations = append(r.Observations, text)
|
||
+ if check.Severity == "WARN" {
|
||
+ r.Warnings = append(r.Warnings, text)
|
||
+ }
|
||
+ } else {
|
||
+ incomplete("TestSSL returned a fatal or unsupported check severity.")
|
||
+ checks--
|
||
+ }
|
||
+ }
|
||
+ }
|
||
+ for key, raw := range report {
|
||
+ if strings.HasPrefix(key, "clientProblem") {
|
||
+ consume(raw, key, true)
|
||
+ } else if key != "version" && key != "openssl" && key != "startTime" && key != "scanResult" && key != "scanTime" {
|
||
+ incomplete("TestSSL returned an unsupported report section.")
|
||
+ }
|
||
+ }
|
||
+ for _, section := range sections {
|
||
+ known[section] = true
|
||
+ if raw, ok := scan[section]; ok {
|
||
+ consume(raw, section, false)
|
||
+ }
|
||
+ }
|
||
+ required := []string{"protocols"}
|
||
+ if wrapper.Checks == "full" {
|
||
+ required = append(required, "ciphers", "serverPreferences", "serverDefaults", "vulnerabilities")
|
||
+ }
|
||
+ for _, section := range required {
|
||
+ var rows []json.RawMessage
|
||
+ if json.Unmarshal(scan[section], &rows) != nil || len(rows) == 0 {
|
||
+ incomplete("TestSSL did not complete requested check group: " + section)
|
||
+ }
|
||
+ }
|
||
+ for key := range scan {
|
||
+ if !known[key] {
|
||
+ incomplete("TestSSL returned an unsupported target section.")
|
||
+ }
|
||
+ }
|
||
+ if checks == 0 {
|
||
+ incomplete("TestSSL returned no completed check records.")
|
||
+ }
|
||
+ if checks > 0 {
|
||
+ r.Services = append(r.Services, schema.Service{Host: actualIP, Port: port, Protocol: "tcp", Technology: "TLS", Confidence: .9})
|
||
+ }
|
||
+ r.Observations = append(r.Observations, "TLS assessment covers one selected address; additional DNS addresses and external revocation services are not assessed.")
|
||
+ r.Summary = fmt.Sprintf("TestSSL normalized %d check(s) for one TLS endpoint, retaining %d finding(s).", checks, len(r.Findings))
|
||
+ if r.Status != "partial" {
|
||
+ r.Confidence = .9
|
||
+ }
|
||
+ return r, nil
|
||
+}
|
||
diff --git a/internal/capability/tls_test.go b/internal/capability/tls_test.go
|
||
new file mode 100644
|
||
index 0000000..79494c0
|
||
--- /dev/null
|
||
+++ b/internal/capability/tls_test.go
|
||
@@ -0,0 +1,139 @@
|
||
+package capability
|
||
+
|
||
+import (
|
||
+ "context"
|
||
+ "encoding/json"
|
||
+ "strings"
|
||
+ "testing"
|
||
+
|
||
+ "github.com/s41r4j/cybot/pkg/schema"
|
||
+)
|
||
+
|
||
+func tlsFixture() map[string]any {
|
||
+ // Shape and protocol identifiers from a real Debian TestSSL 3.2.1 run.
|
||
+ return map[string]any{"schema": 1, "engine": "testssl", "version": "3.2.1", "target": "fixture.invalid:8443", "checks": "protocols", "completed": true, "exit_code": 0, "error": "",
|
||
+ "report": map[string]any{"version": "3.2.1", "scanTime": 18, "scanResult": []any{map[string]any{"targetHost": "fixture.invalid", "ip": "127.0.0.1", "port": "8443", "service": "HTTP", "protocols": []any{
|
||
+ map[string]any{"id": "TLS1", "severity": "LOW", "finding": "offered (deprecated)"},
|
||
+ map[string]any{"id": "TLS1_1", "severity": "LOW", "finding": "offered (deprecated)"},
|
||
+ map[string]any{"id": "TLS1_2", "severity": "OK", "finding": "offered"},
|
||
+ map[string]any{"id": "TLS1_3", "severity": "INFO", "finding": "not offered + downgraded to weaker protocol"},
|
||
+ }}}}}
|
||
+}
|
||
+
|
||
+func decodeTLSFixture(t *testing.T, doc map[string]any) (schema.Result, error) {
|
||
+ t.Helper()
|
||
+ data, err := json.Marshal(doc)
|
||
+ if err != nil {
|
||
+ t.Fatal(err)
|
||
+ }
|
||
+ input, _ := json.Marshal(map[string]any{"checks": doc["checks"]})
|
||
+ return parseTestSSL(data, schema.RunRequest{Target: "fixture.invalid:8443", Input: input})
|
||
+}
|
||
+
|
||
+func TestTLSRequestCheckScopeIsValidatedBeforeExecution(t *testing.T) {
|
||
+ c := liveCapability(t, "tls.audit")
|
||
+ for _, input := range []string{`null`, `{"checks":null}`, `{"checks":"--proxy"}`, `{"checks":""}`, `{"target":"elsewhere.invalid"}`, `{"unexpected":true}`, `{} {}`} {
|
||
+ if err := c.ValidateRequest(schema.RunRequest{Target: "fixture.invalid:8443", Input: json.RawMessage(input)}); err == nil {
|
||
+ t.Fatal("invalid TLS scope accepted", input)
|
||
+ }
|
||
+ if _, err := c.Run(context.Background(), schema.RunRequest{Target: "fixture.invalid:8443", Input: json.RawMessage(input)}, Dependencies{}); err == nil {
|
||
+ t.Fatal("TLS execution accepted invalid input before dependency lookup", input)
|
||
+ }
|
||
+ }
|
||
+ data, _ := json.Marshal(tlsFixture())
|
||
+ if _, err := parseTestSSL(data, schema.RunRequest{Target: "fixture.invalid:8443"}); err == nil {
|
||
+ t.Fatal("protocol report satisfied a requested full scan")
|
||
+ }
|
||
+}
|
||
+
|
||
+func TestTLSFullScanCannotBeSatisfiedByOnlyProtocolGroups(t *testing.T) {
|
||
+ doc := tlsFixture()
|
||
+ doc["checks"] = "full"
|
||
+ r, err := decodeTLSFixture(t, doc)
|
||
+ if err != nil || r.Status != "partial" || len(r.Errors) == 0 || len(r.Findings) != 2 {
|
||
+ t.Fatalf("missing full-scan groups were accepted or erased matches: %+v %v", r, err)
|
||
+ }
|
||
+}
|
||
+
|
||
+func TestTLSNestedProtocolFindingsAndCleanObservations(t *testing.T) {
|
||
+ doc := tlsFixture()
|
||
+ r, err := decodeTLSFixture(t, doc)
|
||
+ if err != nil || r.Status == "partial" || len(r.Findings) != 2 || len(r.Observations) < 2 || len(r.Services) != 1 || r.Services[0].Port != 8443 {
|
||
+ t.Fatalf("real nested protocol report was not normalized: %+v %v", r, err)
|
||
+ }
|
||
+ for _, f := range r.Findings {
|
||
+ if f.Severity != schema.SeverityLow || !strings.Contains(f.Title, "TLS1") {
|
||
+ t.Fatalf("OK/INFO records became vulnerabilities: %+v", f)
|
||
+ }
|
||
+ }
|
||
+ scan := doc["report"].(map[string]any)["scanResult"].([]any)[0].(map[string]any)
|
||
+ scan["protocols"] = []any{map[string]any{"id": "TLS1_2", "severity": "OK", "finding": "offered"}}
|
||
+ r, err = decodeTLSFixture(t, doc)
|
||
+ if err != nil || r.Status == "partial" || len(r.Findings) != 0 {
|
||
+ t.Fatalf("clean protocol observations created a vulnerability: %+v %v", r, err)
|
||
+ }
|
||
+}
|
||
+
|
||
+func TestTLSFailuresRetainValidatedFindingsWithoutCleanAssurance(t *testing.T) {
|
||
+ for _, mutate := range []func(map[string]any){
|
||
+ func(d map[string]any) { d["completed"] = false; d["exit_code"] = 1 },
|
||
+ func(d map[string]any) { d["report"].(map[string]any)["scanTime"] = "Scan interrupted" },
|
||
+ func(d map[string]any) { d["report"].(map[string]any)["scanTime"] = nil },
|
||
+ func(d map[string]any) { d["report"].(map[string]any)["unhandledChecks"] = []any{} },
|
||
+ } {
|
||
+ doc := tlsFixture()
|
||
+ mutate(doc)
|
||
+ r, err := decodeTLSFixture(t, doc)
|
||
+ if err != nil || len(r.Findings) != 2 || r.Status != "partial" || len(r.Errors) == 0 || r.Confidence != 0 {
|
||
+ t.Fatalf("partial TLS report lost matches or became clean: %+v %v", r, err)
|
||
+ }
|
||
+ }
|
||
+ doc := tlsFixture()
|
||
+ doc["completed"], doc["exit_code"], doc["report"] = false, 1, nil
|
||
+ r, err := decodeTLSFixture(t, doc)
|
||
+ if err != nil || r.Status != "partial" || len(r.Errors) == 0 || len(r.Findings) != 0 {
|
||
+ t.Fatalf("missing failed-engine report looked clean: %+v %v", r, err)
|
||
+ }
|
||
+}
|
||
+
|
||
+func TestTLSReportCannotChangeEndpointOrEngineVersion(t *testing.T) {
|
||
+ for key, value := range map[string]string{"targetHost": "elsewhere.invalid", "ip": "not-an-address", "port": "443"} {
|
||
+ doc := tlsFixture()
|
||
+ doc["report"].(map[string]any)["scanResult"].([]any)[0].(map[string]any)[key] = value
|
||
+ if _, err := decodeTLSFixture(t, doc); err == nil {
|
||
+ t.Fatal("foreign/incomplete endpoint was accepted", key)
|
||
+ }
|
||
+ }
|
||
+ doc := tlsFixture()
|
||
+ doc["report"].(map[string]any)["version"] = "3.2.0"
|
||
+ if _, err := decodeTLSFixture(t, doc); err == nil {
|
||
+ t.Fatal("unvalidated engine version was accepted")
|
||
+ }
|
||
+}
|
||
+
|
||
+func TestTLSClientLimitationsRemainExplicit(t *testing.T) {
|
||
+ doc := tlsFixture()
|
||
+ doc["report"].(map[string]any)["clientProblem1"] = []any{map[string]any{"id": "engine_problem", "severity": "WARN", "finding": "No engine or GOST support via engine with your /fixture/openssl"}}
|
||
+ r, err := decodeTLSFixture(t, doc)
|
||
+ if err != nil || r.Status == "partial" || len(r.Warnings) == 0 {
|
||
+ t.Fatalf("protocol-only GOST limitation was not explained: %+v %v", r, err)
|
||
+ }
|
||
+ doc["checks"] = "full"
|
||
+ r, err = decodeTLSFixture(t, doc)
|
||
+ if err != nil || r.Status != "partial" || len(r.Errors) == 0 || len(r.Findings) != 2 {
|
||
+ t.Fatalf("full TLS scan hid a missing cipher engine: %+v %v", r, err)
|
||
+ }
|
||
+}
|
||
+
|
||
+func TestTLSTargetPortsRemainBoundedData(t *testing.T) {
|
||
+ for _, valid := range []string{"fixture.invalid", "fixture.invalid:8443", "127.0.0.1:443", "::1", "[::1]:8443"} {
|
||
+ if _, _, err := tlsEndpoint(valid); err != nil {
|
||
+ t.Fatal("valid endpoint rejected", valid, err)
|
||
+ }
|
||
+ }
|
||
+ for _, invalid := range []string{"--proxy=elsewhere", "fixture.invalid:0", "fixture.invalid:65536", "fixture.invalid:+443", "fixture.invalid:443/path", "https://fixture.invalid", "[::1]", "[fixture.invalid]:443", "[127.0.0.1]:443", "fe80::1%lo0", "fixture.invalid\n--file"} {
|
||
+ if _, _, err := tlsEndpoint(invalid); err == nil {
|
||
+ t.Fatal("unsafe/malformed TLS target accepted", invalid)
|
||
+ }
|
||
+ }
|
||
+}
|
||
diff --git a/release/catalog-baseline.json b/release/catalog-baseline.json
|
||
index af6161e..31fc196 100644
|
||
--- a/release/catalog-baseline.json
|
||
+++ b/release/catalog-baseline.json
|
||
@@ -250,7 +250,10 @@
|
||
"corscanner",
|
||
"corscanner-engine",
|
||
"dirsearch",
|
||
- "dirsearch-engine"
|
||
+ "dirsearch-engine",
|
||
+ "testssl",
|
||
+ "testssl-engine",
|
||
+ "openssl"
|
||
],
|
||
"browser": [
|
||
"agent-browser",
|
||
diff --git a/scripts/package_audit_report.py b/scripts/package_audit_report.py
|
||
index fa80992..8399d1b 100644
|
||
--- a/scripts/package_audit_report.py
|
||
+++ b/scripts/package_audit_report.py
|
||
@@ -110,6 +110,8 @@ def mapped_components(profile, measured, packages, required):
|
||
'supplychain': {},
|
||
'analysis': {'semgrep': [('python','semgrep','1.172.0')]},
|
||
'web': {'wafw00f':[('python','wafw00f','2.4.2')], 'wafw00f-engine':[('python','wafw00f','2.4.2')],
|
||
+ 'testssl':[('deb','testssl.sh',source_packages.get('testssl.sh'))], 'testssl-engine':[('deb','testssl.sh',source_packages.get('testssl.sh'))],
|
||
+ 'openssl':[('deb','openssl',source_packages.get('openssl'))],
|
||
'corscanner':[('python','corscanner','0.9.7')], 'corscanner-engine':[('python','corscanner','0.9.7')],
|
||
'dirsearch':[('python','dirsearch','0.5.0')], 'dirsearch-engine':[('python','dirsearch','0.5.0')],
|
||
'ruby':[('deb','ruby3.3',source_packages.get('ruby3.3'))], 'python':[('deb','python3.13',source_packages.get('python3.13'))]},
|
||
diff --git a/scripts/test_testssl_metadata.py b/scripts/test_testssl_metadata.py
|
||
new file mode 100644
|
||
index 0000000..c995346
|
||
--- /dev/null
|
||
+++ b/scripts/test_testssl_metadata.py
|
||
@@ -0,0 +1,39 @@
|
||
+import hashlib
|
||
+import importlib.util
|
||
+from pathlib import Path
|
||
+import tempfile
|
||
+import unittest
|
||
+
|
||
+spec=importlib.util.spec_from_file_location('testssl_metadata',Path(__file__).resolve().parents[1]/'docker/toolbox/testssl_metadata.py')
|
||
+metadata=importlib.util.module_from_spec(spec);spec.loader.exec_module(metadata)
|
||
+
|
||
+
|
||
+class TestSSLMetadataTests(unittest.TestCase):
|
||
+ def fixture(self,root):
|
||
+ rows=[]
|
||
+ for name,data in [('usr/bin/testssl',b'checked engine'),('etc/testssl/cipher-mapping.txt',b'checked cipher data')]:
|
||
+ path=root/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(data)
|
||
+ rows.append({'path':'/'+name,'size':len(data),'sha256':hashlib.sha256(data).hexdigest()})
|
||
+ return {'schema':1,'version':'3.2.1','runtime_files':rows}
|
||
+
|
||
+ def test_installed_source_changes_and_extra_data_fail_verification(self):
|
||
+ with tempfile.TemporaryDirectory() as temp:
|
||
+ root=Path(temp);lock=self.fixture(root)
|
||
+ self.assertEqual(len(metadata.verify(lock,root)),64)
|
||
+ (root/'usr/bin/testssl').write_bytes(b'changed engine')
|
||
+ with self.assertRaisesRegex(RuntimeError,'bytes differ'):metadata.verify(lock,root)
|
||
+ lock=self.fixture(root)
|
||
+ (root/'etc/testssl/untracked').write_bytes(b'untracked')
|
||
+ with self.assertRaisesRegex(RuntimeError,'file set'):metadata.verify(lock,root)
|
||
+
|
||
+ def test_manifest_escape_and_runtime_symlinks_fail_verification(self):
|
||
+ with tempfile.TemporaryDirectory() as temp:
|
||
+ root=Path(temp);lock=self.fixture(root)
|
||
+ lock['runtime_files'][0]['path']='/usr/bin/../testssl'
|
||
+ with self.assertRaisesRegex(RuntimeError,'source path'):metadata.verify(lock,root)
|
||
+ lock=self.fixture(root)
|
||
+ path=root/'etc/testssl/cipher-mapping.txt';path.unlink();path.symlink_to(root/'usr/bin/testssl')
|
||
+ with self.assertRaisesRegex(RuntimeError,'symlink'):metadata.verify(lock,root)
|
||
+
|
||
+
|
||
+if __name__=='__main__':unittest.main()
|
||
diff --git a/scripts/toolbox-web-entrypoint.sh b/scripts/toolbox-web-entrypoint.sh
|
||
index 34dbcad..07e9f9e 100644
|
||
--- a/scripts/toolbox-web-entrypoint.sh
|
||
+++ b/scripts/toolbox-web-entrypoint.sh
|
||
@@ -7,7 +7,7 @@ case "$action" in
|
||
exec) exec "$@" ;;
|
||
shell) exec /bin/sh "$@" ;;
|
||
health)
|
||
- for tool in cybot httpx ffuf gobuster whatweb wafw00f corscanner dirsearch ruby python3; do
|
||
+ for tool in cybot httpx ffuf gobuster whatweb wafw00f corscanner dirsearch testssl openssl ruby python3; do
|
||
command -v "$tool" >/dev/null || { echo "Missing web runtime dependency: $tool" >&2; exit 1; }
|
||
done
|
||
echo 'Web runtime executables are present; real operation validation is separate.' ;;
|
||
@@ -19,7 +19,9 @@ case "$action" in
|
||
whatweb --version
|
||
wafw00f --version
|
||
corscanner --version
|
||
- dirsearch --version ;;
|
||
+ dirsearch --version
|
||
+ testssl --version
|
||
+ openssl version ;;
|
||
help) echo 'CYBOT web toolbox: cybot | exec | health | versions | shell' ;;
|
||
*) echo "Unsupported web entrypoint action: $action" >&2; exit 2 ;;
|
||
esac
|
||
diff --git a/scripts/web_profile.py b/scripts/web_profile.py
|
||
index af82866..e440ef1 100644
|
||
--- a/scripts/web_profile.py
|
||
+++ b/scripts/web_profile.py
|
||
@@ -66,6 +66,11 @@ def prepare(dest):
|
||
prepare_cors(dest)
|
||
from dirsearch_profile import prepare as prepare_dirsearch
|
||
prepare_dirsearch(dest)
|
||
+ tls=dest/'lib/testssl';tls.mkdir()
|
||
+ shutil.copyfile(toolbox.ROOT/'docker/toolbox/testssl_wrapper.py',tls/'adapter.py')
|
||
+ shutil.copyfile(toolbox.ROOT/'docker/toolbox/testssl_metadata.py',tls/'metadata.py')
|
||
+ shutil.copyfile(toolbox.ROOT/'docker/toolbox/testssl.lock.json',tls/'source.lock.json')
|
||
+ binary=dest/'bin/testssl';binary.write_text('#!/bin/sh\nset -eu\nexec python3 -B /opt/cybot/lib/testssl/adapter.py "$@"\n');binary.chmod(0o755)
|
||
shutil.copyfile(toolbox.ROOT/'scripts/library_metadata.py',dest/'lib/source_library_metadata.py')
|
||
builds = dest/'share/builds'; builds.mkdir(parents=True, exist_ok=True)
|
||
(builds/'web-source.json').write_text(json.dumps({'source_lock_sha256': hashlib.sha256((toolbox.ROOT/'docker/toolbox/web.lock.json').read_bytes()).hexdigest(), 'patches': patches}, indent=2)+'\n')
|
||
@@ -105,13 +110,16 @@ def probe(image):
|
||
'corscanner-engine': ('/opt/cybot/lib/cors/CORScanner/common/corscheck.py', ''),
|
||
'dirsearch': ('/opt/cybot/bin/dirsearch', '--version'),
|
||
'dirsearch-engine': ('/opt/cybot/lib/dirsearch/dirsearch/lib/core/api.py', ''),
|
||
+ 'testssl': ('/opt/cybot/bin/testssl','--version'),
|
||
+ 'testssl-engine': ('/usr/bin/testssl','--version'),
|
||
+ 'openssl': ('/usr/bin/openssl','version'),
|
||
'ruby': ('/usr/bin/ruby', '-e "puts RUBY_VERSION"'),
|
||
'python': ('/usr/bin/python3', '-c "import platform; print(platform.python_version())"'),
|
||
}
|
||
lines = ['set -eu']
|
||
for name, (path, flag) in commands.items():
|
||
command = path+' '+flag
|
||
- if name.endswith('-engine'):
|
||
+ if name.endswith('-engine') and name!='testssl-engine':
|
||
command = commands[name.removesuffix('-engine')][0]+' --version'
|
||
lines += [f"printf '\\nCYBOT_HASH {name} '", 'sha256sum '+path,
|
||
f"printf 'CYBOT_VERSION {name}\\n'", command+' 2>&1', "printf '\\nCYBOT_END\\n'"]
|
||
@@ -137,6 +145,9 @@ def probe(image):
|
||
'libraries='+repr(libraries),
|
||
"sources={name:verify(pathlib.Path(row['root']),name,row['version'],row['lock'],row['adapter']) for name,row in libraries.items()}",
|
||
"data['source-metadata-helper']=hashlib.sha256(pathlib.Path('/opt/cybot/lib/source_library_metadata.py').read_bytes()).hexdigest()",
|
||
+ "sys.path.insert(0,'/opt/cybot/lib/testssl')",'from metadata import verify as verify_testssl',
|
||
+ "data['testssl-files']=verify_testssl(json.loads(pathlib.Path('/opt/cybot/lib/testssl/source.lock.json').read_bytes()))",
|
||
+ "for name in ['adapter.py','metadata.py','source.lock.json']:data['testssl-'+name]=hashlib.sha256((pathlib.Path('/opt/cybot/lib/testssl')/name).read_bytes()).hexdigest()",
|
||
'print(json.dumps({"data":data,"packages":packages,"ruby_gems":gems,"python_packages":wheels,"source_libraries":sources}))', 'PY', "printf 'CYBOT_END\\n'"]
|
||
toolbox.STATE.mkdir(parents=True, exist_ok=True)
|
||
with tempfile.TemporaryDirectory(prefix='probe-', dir=toolbox.STATE) as temp:
|
||
@@ -151,6 +162,9 @@ def probe(image):
|
||
if not extra:
|
||
raise RuntimeError('Missing web runtime dependency inventory')
|
||
report = dict(json.loads(extra[1]), binaries={})
|
||
+ for target,source in [('adapter.py','testssl_wrapper.py'),('metadata.py','testssl_metadata.py'),('source.lock.json','testssl.lock.json')]:
|
||
+ if report['data'].get('testssl-'+target)!=hashlib.sha256((toolbox.ROOT/'docker/toolbox'/source).read_bytes()).hexdigest():
|
||
+ raise RuntimeError('TestSSL adapter/source manifest differs from the checked build')
|
||
if report['source_libraries']!={name:row['version'] for name,row in libraries.items()} or report['data']['source-metadata-helper']!=hashlib.sha256((toolbox.ROOT/'scripts/library_metadata.py').read_bytes()).hexdigest():
|
||
raise RuntimeError('Interpreted source metadata differs from its checked library/adapter')
|
||
wheels = dict(lock['wafw00f']['wheels'], **json.loads((toolbox.ROOT/'docker/toolbox/cors.lock.json').read_text())['wheels'])
|
||
@@ -164,6 +178,8 @@ def probe(image):
|
||
expected = lock['go_tools'].get(name) or lock.get(name.removesuffix('-engine'), {}).get('version')
|
||
if name in ('corscanner','corscanner-engine'): expected = '0.9.7'
|
||
if name in ('dirsearch','dirsearch-engine'): expected = '0.5.0'
|
||
+ if name in ('testssl','testssl-engine'): expected = '3.2.1'
|
||
+ if name=='openssl':expected=lock['packages'][toolbox.ARCH]['openssl'].split('-')[0]
|
||
if expected and version[1] != expected: raise RuntimeError('Web runtime version mismatch: '+name)
|
||
report['binaries'][name] = {'path':digest[2], 'sha256':digest[1], 'reported_version':version[1]}
|
||
return report
|