mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-12-05 10:34:31 +01:00
Merge pull request #84 from JoasASantos/feat/deterministic-probes-dns-ssl-cloud-graphql
feat: DNS, TLS/SSL, cloud, and GraphQL deterministic probes + cloud doctrines
This commit is contained in:
7 files changed
+2671
No files matched your search
@@ -0,0 +1,45 @@
|
||||
# Cloud Infrastructure Security Assessment
|
||||
## User Prompt
|
||||
You are assessing cloud infrastructure for **{target}** on an authorized engagement. The goal is to identify misconfigurations, excessive permissions, exposed credentials, and insecure defaults across AWS, Azure, and GCP environments. CWE-16
|
||||
|
||||
**Context:**
|
||||
{recon_json}
|
||||
|
||||
### Method — IMDS exploitation
|
||||
1. Test Instance Metadata Service reachability (IMDSv1 direct curl, IMDSv2 token-based). IMDSv1 without hop limit is a critical finding — attacker can steal IAM role credentials via SSRF. Test from application context if SSRF exists.
|
||||
|
||||
### Method — IAM enumeration
|
||||
2. Enumerate IAM permissions via `aws iam get-user`, `aws iam list-attached-user-policies`, `az ad user list`, `gcloud iam roles list`. Identify over-permissioned roles, wildcard policies (`*:*`), and cross-account trust relationships.
|
||||
|
||||
### Method — storage misconfiguration
|
||||
3. Test S3 buckets for public ACLs (`aws s3api get-bucket-acl`), Azure blob containers for anonymous access, GCP buckets for `allUsers`/`allAuthenticatedUsers` bindings. Check for sensitive data in public storage (backups, logs, credentials).
|
||||
|
||||
### Method — serverless analysis
|
||||
4. Review Lambda/Azure Functions/Cloud Functions source code for hardcoded secrets, overprivileged execution roles, unrestricted invocation policies, and environment variable leaks via `aws lambda get-function-configuration`.
|
||||
|
||||
### Method — container escape
|
||||
5. Assess ECS/EKS/AKS/GKE pod security context: privileged containers, hostPath mounts, service account tokens mounted by default. Check for container escape vectors via capabilities (SYS_ADMIN, SYS_PTRACE).
|
||||
|
||||
### Method — network segmentation
|
||||
6. Audit VPC peering, security groups, and NSG rules for overly permissive ingress (0.0.0.0/0 on sensitive ports). Check for missing egress controls, flow logs disabled, and default VPC usage.
|
||||
|
||||
### Method — secrets management
|
||||
7. Search for hardcoded API keys and secrets in environment variables, SSM Parameter Store, Azure Key Vault, and GCP Secret Manager. Check for unrotated credentials and service account keys older than 90 days.
|
||||
|
||||
### Method — cross-account and subscription access
|
||||
8. Map assume-role chains, service principal credentials, and cross-subscription access. Identify delegation paths that allow lateral movement between cloud accounts or tenants.
|
||||
|
||||
### Method — logging and monitoring
|
||||
9. Verify CloudTrail/Azure Monitor/Cloud Audit Logs are enabled and not tampered with. Check for trails limited to specific regions, disabled S3 access logging, and missing alert rules for privilege escalation.
|
||||
|
||||
### Method — identity federation
|
||||
10. Test SAML/OIDC federation configurations for misconfigured audience restrictions, overly broad trust policies, and token exchange vulnerabilities. Check for federation that grants admin-equivalent access.
|
||||
|
||||
### Boundaries
|
||||
- **Read-only reconnaissance**: enumerate configurations and permissions without modifying them. Never delete or modify IAM policies, storage ACLs, or security groups.
|
||||
- **Credential handling**: if IAM credentials are discovered, report them as findings but do not use them to access additional services without explicit authorization.
|
||||
- **Scope**: only assess cloud resources belonging to the authorized target. Cross-account findings are reported but not explored without additional authorization.
|
||||
|
||||
Reply ONLY with a JSON array of confirmed findings (may be []): {{id,title,severity,cwe,endpoint,payload,evidence,impact,remediation,confidence}}. `evidence` = exact command output proving the misconfiguration — a theoretical "this could be misconfigured" without evidence is NOT a finding.
|
||||
## System Prompt
|
||||
You are a cloud security specialist assessing cloud infrastructure on an authorized engagement. You enumerate IMDS endpoints, IAM policies, storage ACLs, serverless configurations, container security contexts, network segmentation, secrets management, cross-account access, logging, and identity federation. You test deterministically, report with exact evidence (command output, API responses, policy documents), and never modify cloud resources. You prioritize credential exposure and public data access over configuration weaknesses.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Container and Kubernetes Security Assessment
|
||||
## User Prompt
|
||||
You are assessing container and Kubernetes infrastructure for **{target}** on an authorized engagement. The goal is to identify misconfigurations, escape vectors, weak RBAC, exposed secrets, and supply chain risks in containerized environments. CWE-250
|
||||
|
||||
**Context:**
|
||||
{recon_json}
|
||||
|
||||
### Method — container image analysis
|
||||
1. Scan container images with `trivy image` or `grype` for known CVEs. Review Dockerfiles for secrets in build args, running as root, unnecessary packages, and multi-stage build leaks. Check image layers with `docker history --no-trunc` for embedded credentials.
|
||||
|
||||
### Method — Kubernetes API access
|
||||
2. Test for anonymous authentication to the Kubernetes API (`curl -k https://<api>:6443/api/v1/namespaces`). Enumerate RBAC with `kubectl auth can-i --list`. Check for default service account tokens with excessive permissions and cluster-admin bindings.
|
||||
|
||||
### Method — pod security
|
||||
3. Audit pod security contexts: privileged containers, hostPID, hostNetwork, hostIPC, SYS_ADMIN/SYS_PTRACE capabilities, writable hostPath mounts. Check for `securityContext.runAsRoot: true` and missing `readOnlyRootFilesystem`.
|
||||
|
||||
### Method — network policies
|
||||
4. Check for missing or overly permissive NetworkPolicies (`kubectl get networkpolicies -A`). Test pod-to-pod communication across namespaces. Identify DNS-based exfiltration paths and unrestricted egress.
|
||||
|
||||
### Method — secrets management
|
||||
5. Enumerate Kubernetes secrets (`kubectl get secrets -A`). Check for base64-encoded credentials in etcd without encryption-at-rest. Verify that secrets are mounted as volumes, not environment variables, and that RBAC restricts access.
|
||||
|
||||
### Method — supply chain
|
||||
6. Audit image pull policies (ensure `Always`, not `IfNotPresent` for mutable tags). Check registry authentication, admission controllers (OPA/Gatekeeper/Kyverno), image signing verification, and allowed registries.
|
||||
|
||||
### Method — node access
|
||||
7. Test kubelet API access (`curl -k https://<node>:10250/pods`). Check for container escape to host via privileged containers, cgroup escape (`nsenter`), or mounted Docker socket. Verify kubelet authentication is not set to anonymous.
|
||||
|
||||
### Method — service mesh
|
||||
8. Assess Istio/Linkerd configuration: mTLS enforcement (`PeerAuthentication`), permissive mode misconfigurations, sidecar injection bypasses, and AuthorizationPolicy gaps.
|
||||
|
||||
### Method — Helm and GitOps
|
||||
9. Check Helm releases for secrets in values files (`helm get values`). Audit ArgoCD/Flux access controls, Git repository credentials, and CI/CD pipeline injection vectors through Helm chart dependencies.
|
||||
|
||||
### Method — multi-tenancy
|
||||
10. Verify namespace isolation: ResourceQuotas, LimitRanges, PodSecurity admission (Restricted/Baseline/Privileged). Check for cross-namespace service access, shared service accounts, and tenant escape paths.
|
||||
|
||||
### Boundaries
|
||||
- **Read-only**: enumerate configurations without modifying RBAC, NetworkPolicies, or pod specs. Never deploy pods or modify running workloads.
|
||||
- **Node access**: if kubelet API is accessible, enumerate pods and containers but do not execute commands on nodes without explicit authorization.
|
||||
- **Scope**: assess only clusters and namespaces within the authorized target scope.
|
||||
|
||||
Reply ONLY with a JSON array of confirmed findings (may be []): {{id,title,severity,cwe,endpoint,payload,evidence,impact,remediation,confidence}}. `evidence` = exact command output or API response proving the misconfiguration — not theoretical analysis.
|
||||
## System Prompt
|
||||
You are a container and Kubernetes security specialist on an authorized assessment. You scan container images for CVEs and secrets, test Kubernetes API and kubelet access, audit RBAC and pod security contexts, verify network policies and secrets management, assess supply chain controls and service mesh configurations, and check multi-tenancy isolation. You report with exact evidence and prioritize container escape vectors and cluster-admin access over configuration hardening gaps.
|
||||
@@ -0,0 +1,532 @@
|
||||
//! Deterministic cloud metadata and misconfiguration probe.
|
||||
//!
|
||||
//! Tests IMDS reachability, S3/Azure/GCP bucket ACLs, cloud metadata
|
||||
//! endpoints, and common cloud misconfigurations. Read-only, non-destructive.
|
||||
|
||||
use regex::Regex;
|
||||
use std::future::Future;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CloudProvider {
|
||||
Aws,
|
||||
Azure,
|
||||
Gcp,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CloudTarget {
|
||||
pub provider: CloudProvider,
|
||||
pub resource_type: String,
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CloudFacts {
|
||||
pub provider: Option<CloudProvider>,
|
||||
pub imds_accessible: bool,
|
||||
pub targets: Vec<CloudTarget>,
|
||||
pub loot: Vec<String>,
|
||||
pub evidence: String,
|
||||
}
|
||||
|
||||
fn sq(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
pub fn imds_v1_command(timeout: u64) -> String {
|
||||
format!("curl -s -m {} http://169.254.169.254/latest/meta-data/", timeout)
|
||||
}
|
||||
|
||||
pub fn imds_v2_token_command(timeout: u64) -> String {
|
||||
format!(
|
||||
"curl -s -m {} -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600' http://169.254.169.254/latest/api/token",
|
||||
timeout
|
||||
)
|
||||
}
|
||||
|
||||
pub fn azure_imds_command(timeout: u64) -> String {
|
||||
format!(
|
||||
"curl -s -m {} -H 'Metadata:true' 'http://169.254.169.254/metadata/instance?api-version=2021-02-01'",
|
||||
timeout
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gcp_metadata_command(timeout: u64) -> String {
|
||||
format!(
|
||||
"curl -s -m {} -H 'Metadata-Flavor: Google' 'http://metadata.google.internal/computeMetadata/v1/'",
|
||||
timeout
|
||||
)
|
||||
}
|
||||
|
||||
pub fn s3_bucket_acl_command(bucket: &str) -> String {
|
||||
format!("curl -sI https://{}.s3.amazonaws.com/", sq_bare(bucket))
|
||||
}
|
||||
|
||||
pub fn azure_blob_anon_command(account: &str, container: &str) -> String {
|
||||
format!(
|
||||
"curl -sI 'https://{}.blob.core.windows.net/{}?restype=container&comp=list'",
|
||||
sq_bare(account),
|
||||
sq_bare(container)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gcs_bucket_command(bucket: &str) -> String {
|
||||
format!("curl -sI https://storage.googleapis.com/{}/", sq_bare(bucket))
|
||||
}
|
||||
|
||||
fn sq_bare(s: &str) -> String {
|
||||
s.replace(['\'', '"', ';', '&', '|', '$', '`', '(', ')', '{', '}'], "")
|
||||
}
|
||||
|
||||
pub fn parse_imds_response(output: &str) -> Option<CloudProvider> {
|
||||
if output.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if output.contains("ami-id") || output.contains("instance-id") || output.contains("meta-data") {
|
||||
return Some(CloudProvider::Aws);
|
||||
}
|
||||
if output.contains("\"compute\"") && output.contains("\"azEnvironment\"") {
|
||||
return Some(CloudProvider::Azure);
|
||||
}
|
||||
if output.contains("computeMetadata") || output.contains("instance/") {
|
||||
return Some(CloudProvider::Gcp);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn parse_http_status(headers: &str) -> Option<u16> {
|
||||
for line in headers.lines() {
|
||||
let t = line.trim();
|
||||
if t.starts_with("HTTP/") {
|
||||
let parts: Vec<&str> = t.split_whitespace().collect();
|
||||
if parts.len() >= 2 {
|
||||
if let Ok(code) = parts[1].parse::<u16>() {
|
||||
return Some(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn extract_cloud_targets(recon: &str) -> Vec<CloudTarget> {
|
||||
let mut targets = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
|
||||
let s3_subdomain = Regex::new(r"([a-zA-Z0-9][a-zA-Z0-9._-]*)\.s3\.amazonaws\.com").unwrap();
|
||||
let s3_uri = Regex::new(r"s3://([a-zA-Z0-9._-]+)").unwrap();
|
||||
let s3_path = Regex::new(r"://s3\.amazonaws\.com/([a-zA-Z0-9._-]+)").unwrap();
|
||||
|
||||
for cap in s3_subdomain.captures_iter(recon) {
|
||||
let name = cap[1].to_string();
|
||||
seen.insert(format!("s3:{}", name));
|
||||
targets.push(CloudTarget {
|
||||
provider: CloudProvider::Aws,
|
||||
resource_type: "s3-bucket".into(),
|
||||
name: name.clone(),
|
||||
url: format!("https://{}.s3.amazonaws.com/", name),
|
||||
});
|
||||
}
|
||||
for pat in &[&s3_uri, &s3_path] {
|
||||
for cap in pat.captures_iter(recon) {
|
||||
let name = cap[1].to_string();
|
||||
if seen.insert(format!("s3:{}", name)) {
|
||||
targets.push(CloudTarget {
|
||||
provider: CloudProvider::Aws,
|
||||
resource_type: "s3-bucket".into(),
|
||||
name: name.clone(),
|
||||
url: format!("https://{}.s3.amazonaws.com/", name),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let azure_re = Regex::new(r"([a-zA-Z0-9]+)\.blob\.core\.windows\.net/([a-zA-Z0-9_-]+)").unwrap();
|
||||
for cap in azure_re.captures_iter(recon) {
|
||||
let account = cap[1].to_string();
|
||||
let container = cap[2].to_string();
|
||||
let key = format!("azure:{}:{}", account, container);
|
||||
if seen.insert(key) {
|
||||
targets.push(CloudTarget {
|
||||
provider: CloudProvider::Azure,
|
||||
resource_type: "blob-container".into(),
|
||||
name: format!("{}/{}", account, container),
|
||||
url: format!("https://{}.blob.core.windows.net/{}", account, container),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let gcs_patterns = [
|
||||
Regex::new(r"storage\.googleapis\.com/([a-zA-Z0-9._-]+)").unwrap(),
|
||||
Regex::new(r"gs://([a-zA-Z0-9._-]+)").unwrap(),
|
||||
Regex::new(r"([a-zA-Z0-9._-]+)\.storage\.googleapis\.com").unwrap(),
|
||||
];
|
||||
for pat in &gcs_patterns {
|
||||
for cap in pat.captures_iter(recon) {
|
||||
let name = cap[1].to_string();
|
||||
if seen.insert(format!("gcs:{}", name)) {
|
||||
targets.push(CloudTarget {
|
||||
provider: CloudProvider::Gcp,
|
||||
resource_type: "gcs-bucket".into(),
|
||||
name: name.clone(),
|
||||
url: format!("https://storage.googleapis.com/{}/", name),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
targets
|
||||
}
|
||||
|
||||
pub async fn probe_cloud<F, Fut>(
|
||||
host: &str,
|
||||
recon: &str,
|
||||
timeout_secs: u64,
|
||||
runner: F,
|
||||
) -> CloudFacts
|
||||
where
|
||||
F: Fn(String) -> Fut,
|
||||
Fut: Future<Output = Option<String>>,
|
||||
{
|
||||
let mut facts = CloudFacts::default();
|
||||
let mut evidence_lines: Vec<String> = Vec::new();
|
||||
|
||||
let imds_v1_out = runner(imds_v1_command(timeout_secs)).await;
|
||||
if let Some(ref out) = imds_v1_out {
|
||||
if let Some(provider) = parse_imds_response(out) {
|
||||
facts.imds_accessible = true;
|
||||
facts.provider = Some(provider.clone());
|
||||
match provider {
|
||||
CloudProvider::Aws => {
|
||||
facts.loot.push(format!(
|
||||
"cloud:imds-v1:{} \u{2014} IMDSv1 accessible (credential theft risk)", host
|
||||
));
|
||||
evidence_lines.push(format!("[IMDS-v1] AWS metadata accessible on {}", host));
|
||||
}
|
||||
_ => {
|
||||
facts.loot.push(format!(
|
||||
"cloud:imds-accessible:{} \u{2014} cloud metadata endpoint reachable", host
|
||||
));
|
||||
evidence_lines.push(format!("[IMDS] metadata accessible on {}", host));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if facts.provider.is_none() {
|
||||
let azure_out = runner(azure_imds_command(timeout_secs)).await;
|
||||
if let Some(ref out) = azure_out {
|
||||
if parse_imds_response(out) == Some(CloudProvider::Azure) {
|
||||
facts.imds_accessible = true;
|
||||
facts.provider = Some(CloudProvider::Azure);
|
||||
facts.loot.push(format!(
|
||||
"cloud:imds-accessible:{} \u{2014} Azure IMDS reachable", host
|
||||
));
|
||||
evidence_lines.push(format!("[IMDS] Azure metadata accessible on {}", host));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if facts.provider.is_none() {
|
||||
let gcp_out = runner(gcp_metadata_command(timeout_secs)).await;
|
||||
if let Some(ref out) = gcp_out {
|
||||
if parse_imds_response(out) == Some(CloudProvider::Gcp) {
|
||||
facts.imds_accessible = true;
|
||||
facts.provider = Some(CloudProvider::Gcp);
|
||||
facts.loot.push(format!(
|
||||
"cloud:imds-accessible:{} \u{2014} GCP metadata endpoint reachable", host
|
||||
));
|
||||
evidence_lines.push(format!("[IMDS] GCP metadata accessible on {}", host));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let targets = extract_cloud_targets(recon);
|
||||
for target in &targets {
|
||||
match target.provider {
|
||||
CloudProvider::Aws => {
|
||||
let cmd = s3_bucket_acl_command(&target.name);
|
||||
if let Some(ref headers) = runner(cmd).await {
|
||||
if let Some(status) = parse_http_status(headers) {
|
||||
if status == 200 {
|
||||
facts.loot.push(format!(
|
||||
"cloud:s3-public:{} \u{2014} S3 bucket allows anonymous listing",
|
||||
target.name
|
||||
));
|
||||
evidence_lines.push(format!(
|
||||
"[S3] bucket {} returned HTTP 200 (anonymous access)", target.name
|
||||
));
|
||||
} else {
|
||||
evidence_lines.push(format!(
|
||||
"[S3] bucket {} returned HTTP {}", target.name, status
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CloudProvider::Azure => {
|
||||
let parts: Vec<&str> = target.name.splitn(2, '/').collect();
|
||||
if parts.len() == 2 {
|
||||
let cmd = azure_blob_anon_command(parts[0], parts[1]);
|
||||
if let Some(ref headers) = runner(cmd).await {
|
||||
if let Some(status) = parse_http_status(headers) {
|
||||
if status == 200 {
|
||||
facts.loot.push(format!(
|
||||
"cloud:azure-blob-public:{} \u{2014} anonymous access",
|
||||
target.name
|
||||
));
|
||||
evidence_lines.push(format!(
|
||||
"[Azure] blob {}/{} returned HTTP 200", parts[0], parts[1]
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CloudProvider::Gcp => {
|
||||
let cmd = gcs_bucket_command(&target.name);
|
||||
if let Some(ref headers) = runner(cmd).await {
|
||||
if let Some(status) = parse_http_status(headers) {
|
||||
if status == 200 {
|
||||
facts.loot.push(format!(
|
||||
"cloud:gcs-public:{} \u{2014} GCS bucket allows anonymous listing",
|
||||
target.name
|
||||
));
|
||||
evidence_lines.push(format!(
|
||||
"[GCS] bucket {} returned HTTP 200 (anonymous access)", target.name
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
facts.targets = targets;
|
||||
|
||||
facts.evidence = evidence_lines.join("\n");
|
||||
facts
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_imds_v1_command() {
|
||||
let cmd = imds_v1_command(5);
|
||||
assert!(cmd.contains("-m 5"));
|
||||
assert!(cmd.contains("169.254.169.254/latest/meta-data/"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_imds_v2_token_command() {
|
||||
let cmd = imds_v2_token_command(3);
|
||||
assert!(cmd.contains("-X PUT"));
|
||||
assert!(cmd.contains("X-aws-ec2-metadata-token-ttl-seconds"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_azure_imds_command() {
|
||||
let cmd = azure_imds_command(5);
|
||||
assert!(cmd.contains("Metadata:true"));
|
||||
assert!(cmd.contains("api-version=2021-02-01"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gcp_metadata_command() {
|
||||
let cmd = gcp_metadata_command(5);
|
||||
assert!(cmd.contains("Metadata-Flavor: Google"));
|
||||
assert!(cmd.contains("metadata.google.internal"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_s3_bucket_acl_command() {
|
||||
let cmd = s3_bucket_acl_command("my-bucket");
|
||||
assert!(cmd.contains("my-bucket.s3.amazonaws.com"));
|
||||
assert!(cmd.contains("-sI"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_azure_blob_anon_command() {
|
||||
let cmd = azure_blob_anon_command("myaccount", "mycontainer");
|
||||
assert!(cmd.contains("myaccount.blob.core.windows.net/mycontainer"));
|
||||
assert!(cmd.contains("restype=container"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gcs_bucket_command() {
|
||||
let cmd = gcs_bucket_command("my-gcs-bucket");
|
||||
assert!(cmd.contains("storage.googleapis.com/my-gcs-bucket"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_imds_aws() {
|
||||
let out = "ami-id\ninstance-id\nhostname\nlocal-ipv4";
|
||||
assert_eq!(parse_imds_response(out), Some(CloudProvider::Aws));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_imds_azure() {
|
||||
let out = r#"{"compute":{"azEnvironment":"AzurePublicCloud"}}"#;
|
||||
assert_eq!(parse_imds_response(out), Some(CloudProvider::Azure));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_imds_gcp() {
|
||||
let out = "computeMetadata/v1/\ninstance/\nproject/";
|
||||
assert_eq!(parse_imds_response(out), Some(CloudProvider::Gcp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_imds_empty() {
|
||||
assert_eq!(parse_imds_response(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_imds_unknown() {
|
||||
assert_eq!(parse_imds_response("some random text"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_http_status_200() {
|
||||
let headers = "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\n";
|
||||
assert_eq!(parse_http_status(headers), Some(200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_http_status_403() {
|
||||
let headers = "HTTP/2 403 Forbidden\r\n";
|
||||
assert_eq!(parse_http_status(headers), Some(403));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_http_status_missing() {
|
||||
assert_eq!(parse_http_status("no status here"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_s3_subdomain() {
|
||||
let recon = "found https://my-bucket.s3.amazonaws.com/file.txt";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].provider, CloudProvider::Aws);
|
||||
assert_eq!(targets[0].name, "my-bucket");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_s3_uri() {
|
||||
let recon = "s3://data-lake/path/to/file";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].name, "data-lake");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_s3_path_style() {
|
||||
let recon = "https://s3.amazonaws.com/company-assets/logo.png";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].name, "company-assets");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_azure_blob() {
|
||||
let recon = "https://myaccount.blob.core.windows.net/images/photo.jpg";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].provider, CloudProvider::Azure);
|
||||
assert_eq!(targets[0].name, "myaccount/images");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_gcs_url() {
|
||||
let recon = "https://storage.googleapis.com/pub-data/file.csv";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].provider, CloudProvider::Gcp);
|
||||
assert_eq!(targets[0].name, "pub-data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_gcs_uri() {
|
||||
let recon = "gs://ml-models/v2/weights.bin";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].name, "ml-models");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_mixed() {
|
||||
let recon = "s3://bucket-a/file and https://store1.blob.core.windows.net/cont1/x gs://gcs-b/y";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_dedup() {
|
||||
let recon = "s3://my-bucket/a s3://my-bucket/b https://my-bucket.s3.amazonaws.com/c";
|
||||
let targets = extract_cloud_targets(recon);
|
||||
assert_eq!(targets.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_empty() {
|
||||
assert!(extract_cloud_targets("nothing here").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sq_bare_sanitizes() {
|
||||
assert_eq!(sq_bare("test;rm -rf"), "testrm -rf");
|
||||
assert_eq!(sq_bare("clean-name"), "clean-name");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_probe_cloud_imds_aws() {
|
||||
let facts = probe_cloud("10.0.0.1", "", 3, |cmd| async move {
|
||||
if cmd.contains("169.254.169.254/latest/meta-data") && !cmd.contains("PUT") {
|
||||
Some("ami-id\ninstance-id\nhostname".into())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}).await;
|
||||
assert!(facts.imds_accessible);
|
||||
assert_eq!(facts.provider, Some(CloudProvider::Aws));
|
||||
assert!(facts.loot.iter().any(|l| l.contains("imds-v1")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_probe_cloud_azure_fallback() {
|
||||
let facts = probe_cloud("10.0.0.1", "", 3, |cmd| async move {
|
||||
if cmd.contains("Metadata:true") {
|
||||
Some(r#"{"compute":{"azEnvironment":"AzurePublicCloud"}}"#.into())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}).await;
|
||||
assert!(facts.imds_accessible);
|
||||
assert_eq!(facts.provider, Some(CloudProvider::Azure));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_probe_cloud_s3_public() {
|
||||
let recon = "found https://leaky-bucket.s3.amazonaws.com/data.csv";
|
||||
let facts = probe_cloud("10.0.0.1", recon, 3, |cmd| async move {
|
||||
if cmd.contains("leaky-bucket.s3.amazonaws.com") {
|
||||
Some("HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\n".into())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}).await;
|
||||
assert_eq!(facts.targets.len(), 1);
|
||||
assert!(facts.loot.iter().any(|l| l.contains("s3-public:leaky-bucket")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_probe_cloud_no_imds() {
|
||||
let facts = probe_cloud("10.0.0.1", "", 3, |_| async { None }).await;
|
||||
assert!(!facts.imds_accessible);
|
||||
assert!(facts.provider.is_none());
|
||||
assert!(facts.loot.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
//! Deterministic DNS reconnaissance probe.
|
||||
//!
|
||||
//! Extracts DNS facts before agents run: zone transfer (AXFR), subdomain
|
||||
//! enumeration, SPF/DKIM/DMARC record analysis, DNSSEC validation, reverse
|
||||
//! DNS, NS/MX/SOA/TXT record enumeration. All read-only, non-destructive.
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DnsRecord {
|
||||
pub name: String,
|
||||
pub record_type: String,
|
||||
pub value: String,
|
||||
pub ttl: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SpfAnalysis {
|
||||
pub raw: String,
|
||||
pub policy: String,
|
||||
pub includes: Vec<String>,
|
||||
pub permissive: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DmarcAnalysis {
|
||||
pub raw: String,
|
||||
pub policy: String,
|
||||
pub pct: u8,
|
||||
pub rua: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DkimInfo {
|
||||
pub selector: String,
|
||||
pub key_type: String,
|
||||
pub key_bits: Option<u16>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DnsFacts {
|
||||
pub records: Vec<DnsRecord>,
|
||||
pub spf: Option<SpfAnalysis>,
|
||||
pub dmarc: Option<DmarcAnalysis>,
|
||||
pub dkim: Vec<DkimInfo>,
|
||||
pub zone_transfer: Option<String>,
|
||||
pub dnssec: bool,
|
||||
pub loot: Vec<String>,
|
||||
pub evidence: String,
|
||||
}
|
||||
|
||||
const DKIM_SELECTORS: &[&str] = &["google", "default", "selector1", "selector2", "k1", "dkim", "mail", "s1", "s2"];
|
||||
const RECORD_TYPES: &[&str] = &["SOA", "NS", "MX", "TXT", "A", "AAAA"];
|
||||
|
||||
pub fn parse_dig_output(output: &str) -> Vec<DnsRecord> {
|
||||
let mut records = Vec::new();
|
||||
for line in output.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with(';') || line.starts_with(";;") {
|
||||
continue;
|
||||
}
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() < 4 {
|
||||
continue;
|
||||
}
|
||||
let name = parts[0].trim_end_matches('.').to_string();
|
||||
let ttl = parts[1].parse::<u32>().ok();
|
||||
let (record_type, value_start) = if parts.len() >= 5 && (parts[2] == "IN" || parts[2] == "CH" || parts[2] == "HS") {
|
||||
(parts[3].to_string(), 4)
|
||||
} else if ttl.is_some() {
|
||||
(parts[2].to_string(), 3)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let value = parts[value_start..].join(" ").trim_end_matches('.').to_string();
|
||||
if value.is_empty() {
|
||||
continue;
|
||||
}
|
||||
records.push(DnsRecord { name, record_type, value, ttl });
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
pub fn parse_spf(txt_records: &[String]) -> Option<SpfAnalysis> {
|
||||
let spf_record = txt_records.iter().find(|r| {
|
||||
let lower = r.to_lowercase();
|
||||
lower.starts_with("v=spf1") || lower.contains("v=spf1")
|
||||
})?;
|
||||
|
||||
let raw = spf_record.clone();
|
||||
let lower = raw.to_lowercase();
|
||||
|
||||
let mut includes = Vec::new();
|
||||
for part in lower.split_whitespace() {
|
||||
if let Some(inc) = part.strip_prefix("include:") {
|
||||
includes.push(inc.to_string());
|
||||
} else if let Some(redir) = part.strip_prefix("redirect=") {
|
||||
includes.push(format!("redirect:{}", redir));
|
||||
}
|
||||
}
|
||||
|
||||
let policy = if lower.contains("-all") {
|
||||
"reject".to_string()
|
||||
} else if lower.contains("~all") {
|
||||
"softfail".to_string()
|
||||
} else if lower.contains("?all") {
|
||||
"neutral".to_string()
|
||||
} else if lower.contains("+all") {
|
||||
"pass".to_string()
|
||||
} else {
|
||||
"unknown".to_string()
|
||||
};
|
||||
|
||||
let permissive = lower.contains("~all") || lower.contains("?all") || lower.contains("+all") || !lower.contains("all");
|
||||
|
||||
Some(SpfAnalysis { raw, policy, includes, permissive })
|
||||
}
|
||||
|
||||
pub fn parse_dmarc(txt_records: &[String]) -> Option<DmarcAnalysis> {
|
||||
let dmarc_record = txt_records.iter().find(|r| {
|
||||
let lower = r.to_lowercase();
|
||||
lower.starts_with("v=dmarc1") || lower.contains("v=dmarc1")
|
||||
})?;
|
||||
|
||||
let raw = dmarc_record.clone();
|
||||
let lower = raw.to_lowercase();
|
||||
|
||||
let mut policy = "none".to_string();
|
||||
let mut pct: u8 = 100;
|
||||
let mut rua = Vec::new();
|
||||
|
||||
for part in lower.split(';') {
|
||||
let part = part.trim();
|
||||
if let Some(p) = part.strip_prefix("p=") {
|
||||
policy = p.trim().to_string();
|
||||
} else if let Some(p) = part.strip_prefix("pct=") {
|
||||
pct = p.trim().parse().unwrap_or(100);
|
||||
} else if let Some(r) = part.strip_prefix("rua=") {
|
||||
for addr in r.split(',') {
|
||||
rua.push(addr.trim().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(DmarcAnalysis { raw, policy, pct, rua })
|
||||
}
|
||||
|
||||
pub fn parse_dkim_selector(output: &str, selector: &str) -> Option<DkimInfo> {
|
||||
let output = output.trim();
|
||||
if output.is_empty() || output.contains("NXDOMAIN") || output.contains("SERVFAIL") || output.contains("no servers") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let lower = output.to_lowercase();
|
||||
let key_type = if lower.contains("k=rsa") {
|
||||
"rsa".to_string()
|
||||
} else if lower.contains("k=ed25519") {
|
||||
"ed25519".to_string()
|
||||
} else {
|
||||
"unknown".to_string()
|
||||
};
|
||||
|
||||
let key_bits = if let Some(p_start) = lower.find("p=") {
|
||||
let p_val = &output[p_start + 2..];
|
||||
let p_end = p_val.find(';').unwrap_or(p_val.len());
|
||||
let p_key = p_val[..p_end].trim().replace('"', "").replace(' ', "");
|
||||
if !p_key.is_empty() {
|
||||
let decoded_len = (p_key.len() * 3) / 4;
|
||||
Some((decoded_len * 8) as u16)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Some(DkimInfo { selector: selector.to_string(), key_type, key_bits })
|
||||
}
|
||||
|
||||
pub fn zone_transfer_command(domain: &str, nameserver: &str) -> String {
|
||||
format!("dig axfr @{} {} +noall +answer +nocmd", nameserver, domain)
|
||||
}
|
||||
|
||||
pub fn record_query_command(domain: &str, record_type: &str) -> String {
|
||||
format!("dig {} {} +short", domain, record_type)
|
||||
}
|
||||
|
||||
pub fn reverse_dns_command(ip: &str) -> String {
|
||||
format!("dig -x {} +short", ip)
|
||||
}
|
||||
|
||||
pub fn dnssec_check_command(domain: &str) -> String {
|
||||
format!("dig {} DNSKEY +dnssec +short", domain)
|
||||
}
|
||||
|
||||
pub fn dkim_query_command(domain: &str, selector: &str) -> String {
|
||||
format!("dig {}._domainkey.{} TXT +short", selector, domain)
|
||||
}
|
||||
|
||||
pub fn subdomain_enum_command(domain: &str) -> String {
|
||||
format!("curl -s 'https://crt.sh/?q=%.{}&output=json' | grep -oP '\"name_value\":\"[^\"]+\"' | cut -d'\"' -f4 | sort -u", domain)
|
||||
}
|
||||
|
||||
pub async fn probe_dns<F, Fut>(
|
||||
domain: &str,
|
||||
nameservers: &[String],
|
||||
_timeout_secs: u64,
|
||||
runner: F,
|
||||
) -> DnsFacts
|
||||
where
|
||||
F: Fn(String) -> Fut,
|
||||
Fut: std::future::Future<Output = Option<String>>,
|
||||
{
|
||||
let mut facts = DnsFacts::default();
|
||||
let mut evidence_lines: Vec<String> = Vec::new();
|
||||
|
||||
// 1. Query all standard record types
|
||||
for rtype in RECORD_TYPES {
|
||||
let cmd = record_query_command(domain, rtype);
|
||||
if let Some(output) = runner(cmd.clone()).await {
|
||||
if !output.trim().is_empty() {
|
||||
evidence_lines.push(format!("[{}] {}: {}", rtype, domain, output.trim()));
|
||||
for line in output.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with(';') {
|
||||
continue;
|
||||
}
|
||||
facts.records.push(DnsRecord {
|
||||
name: domain.to_string(),
|
||||
record_type: rtype.to_string(),
|
||||
value: line.to_string(),
|
||||
ttl: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Collect TXT values for SPF/DMARC parsing
|
||||
let txt_values: Vec<String> = facts.records.iter()
|
||||
.filter(|r| r.record_type == "TXT")
|
||||
.map(|r| r.value.trim_matches('"').to_string())
|
||||
.collect();
|
||||
|
||||
// 2. Parse SPF
|
||||
if let Some(spf) = parse_spf(&txt_values) {
|
||||
if spf.permissive {
|
||||
facts.loot.push(format!(
|
||||
"dns:spf-permissive:{} — SPF uses {} (spoofable)",
|
||||
domain, spf.policy
|
||||
));
|
||||
}
|
||||
evidence_lines.push(format!("[SPF] policy={} permissive={} includes={:?}", spf.policy, spf.permissive, spf.includes));
|
||||
facts.spf = Some(spf);
|
||||
} else {
|
||||
facts.loot.push(format!("dns:no-spf:{} — no SPF record", domain));
|
||||
evidence_lines.push("[SPF] no record found".to_string());
|
||||
}
|
||||
|
||||
// 3. Query DMARC
|
||||
let dmarc_cmd = record_query_command(&format!("_dmarc.{}", domain), "TXT");
|
||||
if let Some(dmarc_output) = runner(dmarc_cmd).await {
|
||||
let dmarc_txts: Vec<String> = dmarc_output.lines()
|
||||
.map(|l| l.trim().trim_matches('"').to_string())
|
||||
.filter(|l| !l.is_empty())
|
||||
.collect();
|
||||
if let Some(dmarc) = parse_dmarc(&dmarc_txts) {
|
||||
if dmarc.policy == "none" {
|
||||
facts.loot.push(format!("dns:dmarc-none:{} — DMARC policy is none", domain));
|
||||
}
|
||||
evidence_lines.push(format!("[DMARC] policy={} pct={} rua={:?}", dmarc.policy, dmarc.pct, dmarc.rua));
|
||||
facts.dmarc = Some(dmarc);
|
||||
} else {
|
||||
facts.loot.push(format!("dns:no-dmarc:{} — no DMARC record", domain));
|
||||
evidence_lines.push("[DMARC] no record found".to_string());
|
||||
}
|
||||
} else {
|
||||
facts.loot.push(format!("dns:no-dmarc:{} — no DMARC record", domain));
|
||||
evidence_lines.push("[DMARC] query failed".to_string());
|
||||
}
|
||||
|
||||
// 4. Zone transfer attempts
|
||||
let ns_records: Vec<String> = if nameservers.is_empty() {
|
||||
facts.records.iter()
|
||||
.filter(|r| r.record_type == "NS")
|
||||
.map(|r| r.value.clone())
|
||||
.collect()
|
||||
} else {
|
||||
nameservers.to_vec()
|
||||
};
|
||||
|
||||
for ns in &ns_records {
|
||||
let cmd = zone_transfer_command(domain, ns);
|
||||
if let Some(output) = runner(cmd).await {
|
||||
let trimmed = output.trim();
|
||||
if !trimmed.is_empty() && !trimmed.contains("Transfer failed") && !trimmed.contains("connection refused") && !trimmed.contains("; Transfer size") {
|
||||
let axfr_records = parse_dig_output(trimmed);
|
||||
if !axfr_records.is_empty() {
|
||||
facts.zone_transfer = Some(trimmed.to_string());
|
||||
facts.loot.push(format!("dns:axfr:{}@{} — zone transfer ALLOWED", domain, ns));
|
||||
evidence_lines.push(format!("[AXFR] {} allowed transfer ({} records)", ns, axfr_records.len()));
|
||||
for rec in &axfr_records {
|
||||
if rec.record_type == "A" || rec.record_type == "AAAA" {
|
||||
facts.loot.push(format!("dns:subdomain:{}.{} — {}", rec.name, domain, rec.value));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. DNSSEC check
|
||||
let dnssec_cmd = dnssec_check_command(domain);
|
||||
if let Some(output) = runner(dnssec_cmd).await {
|
||||
let trimmed = output.trim();
|
||||
facts.dnssec = !trimmed.is_empty() && !trimmed.contains("NXDOMAIN") && !trimmed.contains("SERVFAIL");
|
||||
if !facts.dnssec {
|
||||
facts.loot.push(format!("dns:no-dnssec:{} — DNSSEC not enabled", domain));
|
||||
}
|
||||
evidence_lines.push(format!("[DNSSEC] enabled={}", facts.dnssec));
|
||||
} else {
|
||||
facts.loot.push(format!("dns:no-dnssec:{} — DNSSEC not enabled", domain));
|
||||
evidence_lines.push("[DNSSEC] check failed".to_string());
|
||||
}
|
||||
|
||||
// 6. DKIM selector probing
|
||||
for selector in DKIM_SELECTORS {
|
||||
let cmd = dkim_query_command(domain, selector);
|
||||
if let Some(output) = runner(cmd).await {
|
||||
if let Some(info) = parse_dkim_selector(&output, selector) {
|
||||
evidence_lines.push(format!("[DKIM] selector={} type={} bits={:?}", selector, info.key_type, info.key_bits));
|
||||
facts.dkim.push(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Reverse DNS on A records
|
||||
let a_records: Vec<String> = facts.records.iter()
|
||||
.filter(|r| r.record_type == "A")
|
||||
.map(|r| r.value.clone())
|
||||
.collect();
|
||||
for ip in &a_records {
|
||||
let cmd = reverse_dns_command(ip);
|
||||
if let Some(output) = runner(cmd).await {
|
||||
let rdns = output.trim().to_string();
|
||||
if !rdns.is_empty() && !rdns.contains("NXDOMAIN") {
|
||||
evidence_lines.push(format!("[rDNS] {} -> {}", ip, rdns));
|
||||
facts.records.push(DnsRecord {
|
||||
name: ip.clone(),
|
||||
record_type: "PTR".to_string(),
|
||||
value: rdns,
|
||||
ttl: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
facts.evidence = evidence_lines.join("\n");
|
||||
facts
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_dig_a_record() {
|
||||
let output = "example.com.\t\t300\tIN\tA\t93.184.216.34\n";
|
||||
let records = parse_dig_output(output);
|
||||
assert_eq!(records.len(), 1);
|
||||
assert_eq!(records[0].record_type, "A");
|
||||
assert_eq!(records[0].value, "93.184.216.34");
|
||||
assert_eq!(records[0].ttl, Some(300));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_dig_mx_record() {
|
||||
let output = "example.com.\t3600\tIN\tMX\t10 mail.example.com.\n";
|
||||
let records = parse_dig_output(output);
|
||||
assert_eq!(records.len(), 1);
|
||||
assert_eq!(records[0].record_type, "MX");
|
||||
assert_eq!(records[0].value, "10 mail.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_dig_txt_record() {
|
||||
let output = "example.com.\t3600\tIN\tTXT\t\"v=spf1 include:_spf.google.com ~all\"\n";
|
||||
let records = parse_dig_output(output);
|
||||
assert_eq!(records.len(), 1);
|
||||
assert_eq!(records[0].record_type, "TXT");
|
||||
assert!(records[0].value.contains("v=spf1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_dig_skips_comments() {
|
||||
let output = ";; ANSWER SECTION:\n;; comment\nexample.com.\t300\tIN\tA\t1.2.3.4\n";
|
||||
let records = parse_dig_output(output);
|
||||
assert_eq!(records.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_dig_multiple_records() {
|
||||
let output = "example.com.\t300\tIN\tA\t1.2.3.4\nexample.com.\t300\tIN\tA\t5.6.7.8\n";
|
||||
let records = parse_dig_output(output);
|
||||
assert_eq!(records.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spf_strict_reject() {
|
||||
let txts = vec!["v=spf1 include:_spf.google.com -all".to_string()];
|
||||
let spf = parse_spf(&txts).unwrap();
|
||||
assert_eq!(spf.policy, "reject");
|
||||
assert!(!spf.permissive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spf_permissive_softfail() {
|
||||
let txts = vec!["v=spf1 include:_spf.google.com ~all".to_string()];
|
||||
let spf = parse_spf(&txts).unwrap();
|
||||
assert_eq!(spf.policy, "softfail");
|
||||
assert!(spf.permissive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spf_permissive_pass_all() {
|
||||
let txts = vec!["v=spf1 +all".to_string()];
|
||||
let spf = parse_spf(&txts).unwrap();
|
||||
assert_eq!(spf.policy, "pass");
|
||||
assert!(spf.permissive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spf_extracts_includes() {
|
||||
let txts = vec!["v=spf1 include:_spf.google.com include:spf.protection.outlook.com -all".to_string()];
|
||||
let spf = parse_spf(&txts).unwrap();
|
||||
assert_eq!(spf.includes.len(), 2);
|
||||
assert!(spf.includes.contains(&"_spf.google.com".to_string()));
|
||||
assert!(spf.includes.contains(&"spf.protection.outlook.com".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spf_extracts_redirect() {
|
||||
let txts = vec!["v=spf1 redirect=_spf.example.com".to_string()];
|
||||
let spf = parse_spf(&txts).unwrap();
|
||||
assert!(spf.includes.iter().any(|i| i.contains("redirect:")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spf_no_record_returns_none() {
|
||||
let txts = vec!["some random txt record".to_string()];
|
||||
assert!(parse_spf(&txts).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dmarc_policy_none() {
|
||||
let txts = vec!["v=DMARC1; p=none; rua=mailto:dmarc@example.com".to_string()];
|
||||
let dmarc = parse_dmarc(&txts).unwrap();
|
||||
assert_eq!(dmarc.policy, "none");
|
||||
assert_eq!(dmarc.rua.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dmarc_policy_reject() {
|
||||
let txts = vec!["v=DMARC1; p=reject; pct=100".to_string()];
|
||||
let dmarc = parse_dmarc(&txts).unwrap();
|
||||
assert_eq!(dmarc.policy, "reject");
|
||||
assert_eq!(dmarc.pct, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dmarc_extracts_rua() {
|
||||
let txts = vec!["v=DMARC1; p=quarantine; rua=mailto:a@x.com,mailto:b@x.com".to_string()];
|
||||
let dmarc = parse_dmarc(&txts).unwrap();
|
||||
assert_eq!(dmarc.rua.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dmarc_no_record_returns_none() {
|
||||
let txts = vec!["not a dmarc record".to_string()];
|
||||
assert!(parse_dmarc(&txts).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dkim_parses_rsa_key() {
|
||||
let output = "\"v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w\"";
|
||||
let info = parse_dkim_selector(output, "google").unwrap();
|
||||
assert_eq!(info.selector, "google");
|
||||
assert_eq!(info.key_type, "rsa");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dkim_nxdomain_returns_none() {
|
||||
assert!(parse_dkim_selector("NXDOMAIN", "default").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dkim_empty_returns_none() {
|
||||
assert!(parse_dkim_selector("", "default").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zone_transfer_command_format() {
|
||||
let cmd = zone_transfer_command("example.com", "ns1.example.com");
|
||||
assert!(cmd.contains("axfr"));
|
||||
assert!(cmd.contains("@ns1.example.com"));
|
||||
assert!(cmd.contains("example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_query_command_format() {
|
||||
let cmd = record_query_command("example.com", "MX");
|
||||
assert!(cmd.contains("example.com"));
|
||||
assert!(cmd.contains("MX"));
|
||||
assert!(cmd.contains("+short"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_dns_command_format() {
|
||||
let cmd = reverse_dns_command("1.2.3.4");
|
||||
assert!(cmd.contains("-x"));
|
||||
assert!(cmd.contains("1.2.3.4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dnssec_check_command_format() {
|
||||
let cmd = dnssec_check_command("example.com");
|
||||
assert!(cmd.contains("DNSKEY"));
|
||||
assert!(cmd.contains("+dnssec"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_dns_axfr_success_produces_loot() {
|
||||
let runner = |cmd: String| async move {
|
||||
if cmd.contains("axfr") {
|
||||
Some("sub.example.com.\t300\tIN\tA\t10.0.0.1\nmail.example.com.\t300\tIN\tA\t10.0.0.2\n".to_string())
|
||||
} else if cmd.contains("+short") && cmd.contains("NS") {
|
||||
Some("ns1.example.com\n".to_string())
|
||||
} else if cmd.contains("+short") && cmd.contains("TXT") && cmd.contains("_dmarc") {
|
||||
Some("\"v=DMARC1; p=reject\"".to_string())
|
||||
} else if cmd.contains("+short") && cmd.contains("TXT") {
|
||||
Some("\"v=spf1 -all\"".to_string())
|
||||
} else if cmd.contains("+short") && cmd.contains("A") && !cmd.contains("AAAA") {
|
||||
Some("93.184.216.34".to_string())
|
||||
} else if cmd.contains("DNSKEY") {
|
||||
Some("257 3 13 key...".to_string())
|
||||
} else if cmd.contains("_domainkey") {
|
||||
None
|
||||
} else if cmd.contains("-x") {
|
||||
Some("host.example.com.".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let facts = probe_dns("example.com", &[], 10, runner).await;
|
||||
assert!(facts.zone_transfer.is_some());
|
||||
assert!(facts.loot.iter().any(|l| l.contains("axfr") && l.contains("ALLOWED")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_dns_permissive_spf_produces_loot() {
|
||||
let runner = |cmd: String| async move {
|
||||
if cmd.contains("+short") && cmd.contains("TXT") && !cmd.contains("_dmarc") && !cmd.contains("_domainkey") {
|
||||
Some("\"v=spf1 include:_spf.google.com ~all\"".to_string())
|
||||
} else if cmd.contains("_dmarc") {
|
||||
Some("\"v=DMARC1; p=reject\"".to_string())
|
||||
} else if cmd.contains("DNSKEY") {
|
||||
Some("257 3 13 key...".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let facts = probe_dns("example.com", &[], 10, runner).await;
|
||||
assert!(facts.spf.is_some());
|
||||
assert!(facts.spf.as_ref().unwrap().permissive);
|
||||
assert!(facts.loot.iter().any(|l| l.contains("spf-permissive")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_dns_no_dmarc_produces_loot() {
|
||||
let runner = |cmd: String| async move {
|
||||
if cmd.contains("_dmarc") {
|
||||
Some("".to_string())
|
||||
} else if cmd.contains("+short") && cmd.contains("TXT") && !cmd.contains("_domainkey") {
|
||||
Some("\"v=spf1 -all\"".to_string())
|
||||
} else if cmd.contains("DNSKEY") {
|
||||
Some("".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let facts = probe_dns("example.com", &[], 10, runner).await;
|
||||
assert!(facts.dmarc.is_none());
|
||||
assert!(facts.loot.iter().any(|l| l.contains("no-dmarc")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_dns_no_dnssec_produces_loot() {
|
||||
let runner = |cmd: String| async move {
|
||||
if cmd.contains("DNSKEY") {
|
||||
Some("".to_string())
|
||||
} else if cmd.contains("_dmarc") {
|
||||
Some("\"v=DMARC1; p=reject\"".to_string())
|
||||
} else if cmd.contains("+short") && cmd.contains("TXT") && !cmd.contains("_domainkey") {
|
||||
Some("\"v=spf1 -all\"".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let facts = probe_dns("example.com", &[], 10, runner).await;
|
||||
assert!(!facts.dnssec);
|
||||
assert!(facts.loot.iter().any(|l| l.contains("no-dnssec")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_dns_collects_evidence() {
|
||||
let runner = |cmd: String| async move {
|
||||
if cmd.contains("+short") && cmd.contains("A") && !cmd.contains("AAAA") && !cmd.contains("_dmarc") && !cmd.contains("_domainkey") {
|
||||
Some("1.2.3.4".to_string())
|
||||
} else if cmd.contains("DNSKEY") {
|
||||
Some("257 3 13 key".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let facts = probe_dns("example.com", &[], 10, runner).await;
|
||||
assert!(!facts.evidence.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
//! Deterministic GraphQL security probe.
|
||||
//!
|
||||
//! Tests for introspection exposure, field suggestion abuse, batch query
|
||||
//! DoS potential, debug mode, and common GraphQL misconfigurations.
|
||||
//! Read-only, non-destructive.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Data structures
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct GraphqlType {
|
||||
pub name: String,
|
||||
pub fields: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct GraphqlSchema {
|
||||
pub types: Vec<GraphqlType>,
|
||||
pub mutations: Vec<String>,
|
||||
pub subscriptions: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct GraphqlEndpoint {
|
||||
pub url: String,
|
||||
pub introspection_enabled: bool,
|
||||
pub schema: Option<GraphqlSchema>,
|
||||
pub batch_enabled: bool,
|
||||
pub debug_mode: bool,
|
||||
pub sensitive_fields: Vec<String>,
|
||||
pub field_suggestions: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct GraphqlFacts {
|
||||
pub endpoints: Vec<GraphqlEndpoint>,
|
||||
pub loot: Vec<String>,
|
||||
pub evidence: String,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sensitive field patterns
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SENSITIVE_NAMES: &[&str] = &[
|
||||
"password", "passwd", "secret", "token", "apikey", "api_key", "apitoken",
|
||||
"api_token", "accesstoken", "access_token", "refreshtoken", "refresh_token",
|
||||
"ssn", "social_security", "credit_card", "creditcard", "card_number",
|
||||
"cardnumber", "cvv", "cvc", "pin", "private_key", "privatekey",
|
||||
"secret_key", "secretkey", "auth_token", "authtoken", "session_token",
|
||||
"sessiontoken", "jwt", "bearer", "otp", "mfa_secret", "totp_secret",
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Command builders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn introspection_command(url: &str) -> String {
|
||||
let query = r#"{"query":"{ __schema { types { name fields { name } } } }"}"#;
|
||||
format!(
|
||||
"curl -s -X POST -H 'Content-Type: application/json' -d '{}' '{}'",
|
||||
query, url
|
||||
)
|
||||
}
|
||||
|
||||
pub fn introspection_full_command(url: &str) -> String {
|
||||
let query = r#"{"query":"{ __schema { queryType { name } mutationType { name } subscriptionType { name } types { kind name description fields(includeDeprecated: true) { name description args { name type { name kind ofType { name kind } } } type { name kind ofType { name kind } } isDeprecated deprecationReason } inputFields { name type { name kind ofType { name kind } } } enumValues { name } possibleTypes { name } } directives { name description locations args { name type { name kind ofType { name kind } } } } } }"}"#;
|
||||
format!(
|
||||
"curl -s -X POST -H 'Content-Type: application/json' -d '{}' '{}'",
|
||||
query, url
|
||||
)
|
||||
}
|
||||
|
||||
pub fn field_suggestion_command(url: &str, type_name: &str) -> String {
|
||||
let query = format!(
|
||||
r#"{{"query":"{{ {}__typo_field }}"}}"#,
|
||||
type_name
|
||||
);
|
||||
format!(
|
||||
"curl -s -X POST -H 'Content-Type: application/json' -d '{}' '{}'",
|
||||
query, url
|
||||
)
|
||||
}
|
||||
|
||||
pub fn batch_test_command(url: &str) -> String {
|
||||
format!(
|
||||
r#"curl -s -X POST -H 'Content-Type: application/json' -d '[{{"query":"{{__typename}}"}},{{"query":"{{__typename}}"}}]' '{}'"#,
|
||||
url
|
||||
)
|
||||
}
|
||||
|
||||
pub fn debug_mode_command(url: &str) -> String {
|
||||
let query = r#"{"query":"{ __INVALID_QUERY_FOR_DEBUG_CHECK }"}"#;
|
||||
format!(
|
||||
"curl -s -X POST -H 'Content-Type: application/json' -H 'X-Debug: 1' -H 'X-Request-Type: debug' -d '{}' '{}'",
|
||||
query, url
|
||||
)
|
||||
}
|
||||
|
||||
pub fn mutation_list_command(url: &str) -> String {
|
||||
let query = r#"{"query":"{ __schema { mutationType { fields { name description args { name type { name kind } } } } } }"}"#;
|
||||
format!(
|
||||
"curl -s -X POST -H 'Content-Type: application/json' -d '{}' '{}'",
|
||||
query, url
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Parsers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn detect_graphql_endpoint(response: &str) -> bool {
|
||||
let Ok(val) = serde_json::from_str::<Value>(response) else { return false };
|
||||
val.get("data").is_some() || val.get("errors").is_some()
|
||||
}
|
||||
|
||||
pub fn parse_introspection(response: &str) -> Option<GraphqlSchema> {
|
||||
let val: Value = serde_json::from_str(response).ok()?;
|
||||
let schema = val.get("data")?.get("__schema")?;
|
||||
|
||||
let mut types = Vec::new();
|
||||
if let Some(arr) = schema.get("types").and_then(|t| t.as_array()) {
|
||||
for t in arr {
|
||||
let name = t.get("name").and_then(|n| n.as_str()).unwrap_or("").to_string();
|
||||
if name.starts_with("__") {
|
||||
continue;
|
||||
}
|
||||
let fields: Vec<String> = t.get("fields")
|
||||
.and_then(|f| f.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|f| f.get("name").and_then(|n| n.as_str()).map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
types.push(GraphqlType { name, fields });
|
||||
}
|
||||
}
|
||||
|
||||
let mutations = schema.get("mutationType")
|
||||
.and_then(|mt| mt.get("fields"))
|
||||
.and_then(|f| f.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|f| f.get("name").and_then(|n| n.as_str()).map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let subscriptions = schema.get("subscriptionType")
|
||||
.and_then(|st| st.get("fields"))
|
||||
.and_then(|f| f.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|f| f.get("name").and_then(|n| n.as_str()).map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
Some(GraphqlSchema { types, mutations, subscriptions })
|
||||
}
|
||||
|
||||
pub fn parse_field_suggestions(response: &str) -> Vec<String> {
|
||||
let mut suggestions = Vec::new();
|
||||
let Ok(val) = serde_json::from_str::<Value>(response) else { return suggestions };
|
||||
let Some(errors) = val.get("errors").and_then(|e| e.as_array()) else { return suggestions };
|
||||
|
||||
for err in errors {
|
||||
let msg = err.get("message").and_then(|m| m.as_str()).unwrap_or("");
|
||||
// "Did you mean" pattern from graphql-js error messages
|
||||
for pattern in &["Did you mean", "did you mean", "Perhaps you meant"] {
|
||||
if let Some(pos) = msg.find(pattern) {
|
||||
let after = &msg[pos..];
|
||||
// Extract quoted field names: "fieldName", 'fieldName', or `fieldName`
|
||||
let mut chars = after.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '"' || ch == '\'' || ch == '`' {
|
||||
let close = ch;
|
||||
let name: String = chars.by_ref().take_while(|&c| c != close).collect();
|
||||
if !name.is_empty() && name.len() < 100 {
|
||||
suggestions.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
suggestions.sort();
|
||||
suggestions.dedup();
|
||||
suggestions
|
||||
}
|
||||
|
||||
pub fn find_sensitive_fields(schema: &GraphqlSchema) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
for t in &schema.types {
|
||||
for f in &t.fields {
|
||||
let lower = f.to_lowercase();
|
||||
for sensitive in SENSITIVE_NAMES {
|
||||
if lower == *sensitive || lower.contains(sensitive) {
|
||||
found.push(format!("{}.{}", t.name, f));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
found.dedup();
|
||||
found
|
||||
}
|
||||
|
||||
pub fn find_mutations(schema: &GraphqlSchema) -> Vec<String> {
|
||||
schema.mutations.clone()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main probe
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn probe_graphql<F, Fut>(urls: &[String], _timeout_secs: u64, runner: F) -> GraphqlFacts
|
||||
where
|
||||
F: Fn(String) -> Fut,
|
||||
Fut: std::future::Future<Output = Option<String>>,
|
||||
{
|
||||
let mut facts = GraphqlFacts::default();
|
||||
let mut evidence_lines: Vec<String> = Vec::new();
|
||||
|
||||
for url in urls {
|
||||
let mut endpoint = GraphqlEndpoint {
|
||||
url: url.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// 1. Try introspection
|
||||
let intro_cmd = introspection_command(url);
|
||||
if let Some(resp) = runner(intro_cmd).await {
|
||||
if let Some(schema) = parse_introspection(&resp) {
|
||||
endpoint.introspection_enabled = true;
|
||||
let type_count = schema.types.len();
|
||||
let mutation_count = schema.mutations.len();
|
||||
|
||||
let sensitive = find_sensitive_fields(&schema);
|
||||
endpoint.sensitive_fields = sensitive.clone();
|
||||
|
||||
facts.loot.push(format!(
|
||||
"graphql:introspection:{} — full schema exposed ({} types, {} mutations)",
|
||||
url, type_count, mutation_count
|
||||
));
|
||||
evidence_lines.push(format!(
|
||||
"[introspection] {} — {} types, {} mutations exposed",
|
||||
url, type_count, mutation_count
|
||||
));
|
||||
|
||||
if !sensitive.is_empty() {
|
||||
let field_list = sensitive.join(", ");
|
||||
facts.loot.push(format!(
|
||||
"graphql:sensitive-fields:{} — {} exposed in schema",
|
||||
url, field_list
|
||||
));
|
||||
evidence_lines.push(format!(
|
||||
"[sensitive] {} — fields: {}",
|
||||
url, field_list
|
||||
));
|
||||
}
|
||||
|
||||
endpoint.schema = Some(schema);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. If introspection disabled, try field suggestion abuse
|
||||
if !endpoint.introspection_enabled {
|
||||
let suggest_cmd = field_suggestion_command(url, "Query");
|
||||
if let Some(resp) = runner(suggest_cmd).await {
|
||||
let suggestions = parse_field_suggestions(&resp);
|
||||
if !suggestions.is_empty() {
|
||||
endpoint.field_suggestions = suggestions.clone();
|
||||
let field_list = suggestions.join(", ");
|
||||
facts.loot.push(format!(
|
||||
"graphql:field-suggestions:{} — field suggestions leak schema ({})",
|
||||
url, field_list
|
||||
));
|
||||
evidence_lines.push(format!(
|
||||
"[suggestions] {} — leaked fields: {}",
|
||||
url, field_list
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Test batch query support
|
||||
let batch_cmd = batch_test_command(url);
|
||||
if let Some(resp) = runner(batch_cmd).await {
|
||||
if let Ok(val) = serde_json::from_str::<Value>(&resp) {
|
||||
if val.is_array() {
|
||||
endpoint.batch_enabled = true;
|
||||
facts.loot.push(format!(
|
||||
"graphql:batch-enabled:{} — batch queries allowed (DoS amplification risk)",
|
||||
url
|
||||
));
|
||||
evidence_lines.push(format!("[batch] {} — batch queries accepted", url));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Check for debug mode / verbose errors
|
||||
let debug_cmd = debug_mode_command(url);
|
||||
if let Some(resp) = runner(debug_cmd).await {
|
||||
if let Ok(val) = serde_json::from_str::<Value>(&resp) {
|
||||
let has_debug = if let Some(errors) = val.get("errors").and_then(|e| e.as_array()) {
|
||||
errors.iter().any(|e| {
|
||||
let msg = e.get("message").and_then(|m| m.as_str()).unwrap_or("");
|
||||
let has_extensions = e.get("extensions").is_some();
|
||||
let has_stack = msg.contains("stacktrace")
|
||||
|| msg.contains("stack trace")
|
||||
|| msg.contains("at /")
|
||||
|| msg.contains("at \\")
|
||||
|| msg.contains("node_modules")
|
||||
|| msg.contains(".py:")
|
||||
|| msg.contains(".rb:")
|
||||
|| msg.contains(".java:");
|
||||
let has_locations = e.get("locations").is_some();
|
||||
has_extensions || has_stack || (has_locations && msg.len() > 200)
|
||||
})
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if has_debug {
|
||||
endpoint.debug_mode = true;
|
||||
facts.loot.push(format!(
|
||||
"graphql:debug-mode:{} — debug/verbose error messages enabled",
|
||||
url
|
||||
));
|
||||
evidence_lines.push(format!("[debug] {} — verbose errors detected", url));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
facts.endpoints.push(endpoint);
|
||||
}
|
||||
|
||||
facts.evidence = evidence_lines.join("\n");
|
||||
facts
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_introspection_response() -> String {
|
||||
r#"{
|
||||
"data": {
|
||||
"__schema": {
|
||||
"queryType": { "name": "Query" },
|
||||
"mutationType": {
|
||||
"name": "Mutation",
|
||||
"fields": [
|
||||
{ "name": "createUser" },
|
||||
{ "name": "deleteUser" },
|
||||
{ "name": "updatePassword" }
|
||||
]
|
||||
},
|
||||
"subscriptionType": null,
|
||||
"types": [
|
||||
{
|
||||
"name": "User",
|
||||
"fields": [
|
||||
{ "name": "id" },
|
||||
{ "name": "email" },
|
||||
{ "name": "password" },
|
||||
{ "name": "name" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Query",
|
||||
"fields": [
|
||||
{ "name": "users" },
|
||||
{ "name": "me" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "__Schema",
|
||||
"fields": [
|
||||
{ "name": "types" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Token",
|
||||
"fields": [
|
||||
{ "name": "accessToken" },
|
||||
{ "name": "refreshToken" },
|
||||
{ "name": "expiresIn" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}"#.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_introspection_extracts_types() {
|
||||
let schema = parse_introspection(&sample_introspection_response()).unwrap();
|
||||
// Should skip __Schema (internal type)
|
||||
assert_eq!(schema.types.len(), 3);
|
||||
assert_eq!(schema.types[0].name, "User");
|
||||
assert!(schema.types[0].fields.contains(&"email".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_introspection_extracts_mutations() {
|
||||
let schema = parse_introspection(&sample_introspection_response()).unwrap();
|
||||
assert_eq!(schema.mutations.len(), 3);
|
||||
assert!(schema.mutations.contains(&"createUser".to_string()));
|
||||
assert!(schema.mutations.contains(&"deleteUser".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_sensitive_fields_detects_password() {
|
||||
let schema = parse_introspection(&sample_introspection_response()).unwrap();
|
||||
let sensitive = find_sensitive_fields(&schema);
|
||||
assert!(sensitive.iter().any(|s| s.contains("password")), "Should detect User.password");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_sensitive_fields_detects_token() {
|
||||
let schema = parse_introspection(&sample_introspection_response()).unwrap();
|
||||
let sensitive = find_sensitive_fields(&schema);
|
||||
assert!(sensitive.iter().any(|s| s.contains("accessToken") || s.contains("Token")),
|
||||
"Should detect Token.accessToken or Token.refreshToken");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_field_suggestions_extracts_names() {
|
||||
let response = r#"{
|
||||
"errors": [
|
||||
{
|
||||
"message": "Cannot query field \"Query__typo_field\" on type \"Query\". Did you mean \"users\", \"me\", or \"admin\"?"
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
let suggestions = parse_field_suggestions(response);
|
||||
assert!(suggestions.contains(&"users".to_string()));
|
||||
assert!(suggestions.contains(&"me".to_string()));
|
||||
assert!(suggestions.contains(&"admin".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_graphql_endpoint_recognizes_data() {
|
||||
assert!(detect_graphql_endpoint(r#"{"data":{"__typename":"Query"}}"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_graphql_endpoint_recognizes_errors() {
|
||||
assert!(detect_graphql_endpoint(r#"{"errors":[{"message":"syntax error"}]}"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_graphql_endpoint_rejects_non_graphql() {
|
||||
assert!(!detect_graphql_endpoint("<html>Not Found</html>"));
|
||||
assert!(!detect_graphql_endpoint(r#"{"status":"ok"}"#));
|
||||
assert!(!detect_graphql_endpoint(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn introspection_command_builds_correct_curl() {
|
||||
let cmd = introspection_command("http://target/graphql");
|
||||
assert!(cmd.contains("curl"));
|
||||
assert!(cmd.contains("-X POST"));
|
||||
assert!(cmd.contains("__schema"));
|
||||
assert!(cmd.contains("http://target/graphql"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_test_command_sends_array() {
|
||||
let cmd = batch_test_command("http://target/graphql");
|
||||
assert!(cmd.contains("[{"));
|
||||
assert!(cmd.contains("__typename"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_graphql_introspection_enabled_produces_loot() {
|
||||
let intro_resp = sample_introspection_response();
|
||||
let runner = |cmd: String| {
|
||||
let intro_resp = intro_resp.clone();
|
||||
async move {
|
||||
if cmd.contains("__schema") && !cmd.contains("mutationType { fields") {
|
||||
Some(intro_resp)
|
||||
} else if cmd.contains("[{") {
|
||||
// batch test — not an array response
|
||||
Some(r#"{"data":{"__typename":"Query"}}"#.to_string())
|
||||
} else if cmd.contains("__INVALID_QUERY") {
|
||||
Some(r#"{"errors":[{"message":"syntax error"}]}"#.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let urls = vec!["http://target/graphql".to_string()];
|
||||
let facts = probe_graphql(&urls, 30, runner).await;
|
||||
assert!(!facts.loot.is_empty());
|
||||
assert!(facts.loot.iter().any(|l| l.contains("graphql:introspection")));
|
||||
assert!(facts.loot.iter().any(|l| l.contains("graphql:sensitive-fields")));
|
||||
assert_eq!(facts.endpoints.len(), 1);
|
||||
assert!(facts.endpoints[0].introspection_enabled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_graphql_batch_enabled_produces_loot() {
|
||||
let runner = |cmd: String| async move {
|
||||
if cmd.contains("__schema") {
|
||||
// introspection disabled
|
||||
Some(r#"{"errors":[{"message":"introspection is disabled"}]}"#.to_string())
|
||||
} else if cmd.contains("[{") {
|
||||
// batch test — returns array
|
||||
Some(r#"[{"data":{"__typename":"Query"}},{"data":{"__typename":"Query"}}]"#.to_string())
|
||||
} else if cmd.contains("__typo_field") {
|
||||
Some(r#"{"errors":[{"message":"Cannot query field. Did you mean \"users\"?"}]}"#.to_string())
|
||||
} else if cmd.contains("__INVALID_QUERY") {
|
||||
Some(r#"{"errors":[{"message":"syntax error"}]}"#.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let urls = vec!["http://target/graphql".to_string()];
|
||||
let facts = probe_graphql(&urls, 30, runner).await;
|
||||
assert!(facts.loot.iter().any(|l| l.contains("graphql:batch-enabled")));
|
||||
assert!(facts.endpoints[0].batch_enabled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_graphql_no_introspection_tries_suggestions() {
|
||||
let runner = |cmd: String| async move {
|
||||
if cmd.contains("__schema") {
|
||||
Some(r#"{"errors":[{"message":"introspection is disabled"}]}"#.to_string())
|
||||
} else if cmd.contains("__typo_field") {
|
||||
Some(r#"{"errors":[{"message":"Cannot query field \"Query__typo_field\" on type \"Query\". Did you mean \"users\", \"admin\"?"}]}"#.to_string())
|
||||
} else if cmd.contains("[{") {
|
||||
Some(r#"{"data":{"__typename":"Query"}}"#.to_string())
|
||||
} else if cmd.contains("__INVALID_QUERY") {
|
||||
Some(r#"{"errors":[{"message":"syntax error"}]}"#.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let urls = vec!["http://target/graphql".to_string()];
|
||||
let facts = probe_graphql(&urls, 30, runner).await;
|
||||
assert!(!facts.endpoints[0].introspection_enabled);
|
||||
assert!(facts.loot.iter().any(|l| l.contains("graphql:field-suggestions")));
|
||||
assert!(!facts.endpoints[0].field_suggestions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_mutations_returns_mutation_names() {
|
||||
let schema = parse_introspection(&sample_introspection_response()).unwrap();
|
||||
let mutations = find_mutations(&schema);
|
||||
assert_eq!(mutations.len(), 3);
|
||||
assert!(mutations.contains(&"updatePassword".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_suggestion_command_includes_type_name() {
|
||||
let cmd = field_suggestion_command("http://target/graphql", "Query");
|
||||
assert!(cmd.contains("Query__typo_field"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_mode_command_includes_debug_headers() {
|
||||
let cmd = debug_mode_command("http://target/graphql");
|
||||
assert!(cmd.contains("X-Debug"));
|
||||
}
|
||||
}
|
||||
@@ -98,6 +98,10 @@ pub mod svc_probe;
|
||||
pub mod jwt_probe;
|
||||
pub mod nday_restore;
|
||||
pub mod deep_sast;
|
||||
pub mod dns_probe;
|
||||
pub mod ssl_probe;
|
||||
pub mod graphql_probe;
|
||||
pub mod cloud_probe;
|
||||
pub mod goals;
|
||||
pub mod keystore;
|
||||
pub mod threat_actors;
|
||||
|
||||
@@ -0,0 +1,837 @@
|
||||
//! Deterministic TLS/SSL probe — certificate chain, cipher suites, protocol
|
||||
//! versions, HSTS, certificate transparency, and common misconfigurations.
|
||||
//! All read-only, non-destructive.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Data structures
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CertInfo {
|
||||
pub subject: String,
|
||||
pub issuer: String,
|
||||
pub san: Vec<String>,
|
||||
pub not_before: String,
|
||||
pub not_after: String,
|
||||
pub key_size: Option<u16>,
|
||||
pub sig_algo: String,
|
||||
pub serial: String,
|
||||
pub self_signed: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CipherSuite {
|
||||
pub name: String,
|
||||
pub bits: u16,
|
||||
pub protocol: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct HstsInfo {
|
||||
pub max_age: u64,
|
||||
pub include_subdomains: bool,
|
||||
pub preload: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ExpiryStatus {
|
||||
Valid,
|
||||
ExpiringSoon(u32),
|
||||
Expired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TlsInfo {
|
||||
pub protocol: String,
|
||||
pub cipher: String,
|
||||
pub cert: Option<CertInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct PortTls {
|
||||
pub port: u16,
|
||||
pub cert: Option<CertInfo>,
|
||||
pub protocols: Vec<String>,
|
||||
pub hsts: Option<HstsInfo>,
|
||||
pub weak_protocols: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TlsFacts {
|
||||
pub ports: Vec<PortTls>,
|
||||
pub loot: Vec<String>,
|
||||
pub evidence: String,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Command builders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn openssl_connect_command(host: &str, port: u16, sni: Option<&str>) -> String {
|
||||
let servername = sni.unwrap_or(host);
|
||||
format!(
|
||||
"echo | openssl s_client -connect {host}:{port} -servername {servername} 2>/dev/null"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn cert_text_command(host: &str, port: u16) -> String {
|
||||
format!(
|
||||
"echo | openssl s_client -connect {host}:{port} -servername {host} 2>/dev/null | openssl x509 -text -noout 2>/dev/null"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn check_protocol_command(host: &str, port: u16, protocol: &str) -> String {
|
||||
let flag = match protocol {
|
||||
"ssl3" => "-ssl3",
|
||||
"tls1" => "-tls1",
|
||||
"tls1_1" => "-tls1_1",
|
||||
"tls1_2" => "-tls1_2",
|
||||
"tls1_3" => "-tls1_3",
|
||||
other => other,
|
||||
};
|
||||
format!(
|
||||
"echo | openssl s_client -connect {host}:{port} {flag} 2>&1"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn hsts_check_command(host: &str, port: u16) -> String {
|
||||
format!(
|
||||
"curl -sI https://{host}:{port}/ 2>/dev/null | grep -i strict-transport"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn cert_chain_command(host: &str, port: u16) -> String {
|
||||
format!(
|
||||
"echo | openssl s_client -connect {host}:{port} -servername {host} -showcerts 2>/dev/null"
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Output parsing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn parse_openssl_connect(output: &str) -> TlsInfo {
|
||||
let mut info = TlsInfo::default();
|
||||
|
||||
for line in output.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with("Protocol :") || trimmed.starts_with("Protocol:") {
|
||||
info.protocol = trimmed
|
||||
.splitn(2, ':')
|
||||
.nth(1)
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
} else if trimmed.starts_with("Cipher :") || trimmed.starts_with("Cipher:") {
|
||||
info.cipher = trimmed
|
||||
.splitn(2, ':')
|
||||
.nth(1)
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
info
|
||||
}
|
||||
|
||||
pub fn parse_cert_text(output: &str) -> CertInfo {
|
||||
let mut cert = CertInfo::default();
|
||||
|
||||
for line in output.lines() {
|
||||
let trimmed = line.trim();
|
||||
|
||||
if trimmed.starts_with("Issuer:") {
|
||||
cert.issuer = trimmed
|
||||
.strip_prefix("Issuer:")
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
} else if trimmed.starts_with("Subject:") && !trimmed.contains("Subject Alternative") && !trimmed.contains("Subject Key") {
|
||||
cert.subject = trimmed
|
||||
.strip_prefix("Subject:")
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
} else if trimmed.starts_with("Not Before:") {
|
||||
cert.not_before = trimmed
|
||||
.strip_prefix("Not Before:")
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
} else if trimmed.starts_with("Not After :") || trimmed.starts_with("Not After:") {
|
||||
let val = if let Some(rest) = trimmed.strip_prefix("Not After :") {
|
||||
rest
|
||||
} else {
|
||||
trimmed.strip_prefix("Not After:").unwrap_or("")
|
||||
};
|
||||
cert.not_after = val.trim().to_string();
|
||||
} else if trimmed.starts_with("Serial Number:") {
|
||||
cert.serial = trimmed
|
||||
.strip_prefix("Serial Number:")
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
} else if trimmed.starts_with("Signature Algorithm:") {
|
||||
cert.sig_algo = trimmed
|
||||
.strip_prefix("Signature Algorithm:")
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
} else if trimmed.starts_with("Public-Key:") || trimmed.starts_with("RSA Public-Key:") {
|
||||
if let Some(start) = trimmed.find('(') {
|
||||
if let Some(end) = trimmed.find(" bit") {
|
||||
if let Ok(bits) = trimmed[start + 1..end].trim().parse::<u16>() {
|
||||
cert.key_size = Some(bits);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if trimmed.contains("DNS:") {
|
||||
for part in trimmed.split(',') {
|
||||
let p = part.trim();
|
||||
if let Some(dns) = p.strip_prefix("DNS:") {
|
||||
cert.san.push(dns.trim().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cert.self_signed = !cert.subject.is_empty()
|
||||
&& !cert.issuer.is_empty()
|
||||
&& cert.subject == cert.issuer;
|
||||
|
||||
cert
|
||||
}
|
||||
|
||||
pub fn parse_cipher_list(output: &str) -> Vec<CipherSuite> {
|
||||
let mut ciphers = Vec::new();
|
||||
|
||||
for line in output.lines() {
|
||||
let trimmed = line.trim();
|
||||
// openssl ciphers -v format: NAME PROTO Kx=... Au=... Enc=ALGO(BITS) ...
|
||||
if trimmed.contains("Kx=") || trimmed.contains("Au=") {
|
||||
let parts: Vec<&str> = trimmed.split_whitespace().collect();
|
||||
if parts.len() >= 2 {
|
||||
let name = parts[0].to_string();
|
||||
let protocol = parts[1].to_string();
|
||||
let mut bits: u16 = 0;
|
||||
for p in &parts {
|
||||
if p.starts_with("Enc=") {
|
||||
if let Some(start) = p.find('(') {
|
||||
if let Some(end) = p.find(')') {
|
||||
bits = p[start + 1..end].parse().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ciphers.push(CipherSuite { name, bits, protocol });
|
||||
}
|
||||
}
|
||||
// nmap ssl-enum-ciphers format: | TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|
||||
if trimmed.starts_with('|') && trimmed.contains("TLS_") {
|
||||
let inner = trimmed.trim_start_matches('|').trim();
|
||||
let parts: Vec<&str> = inner.split_whitespace().collect();
|
||||
if !parts.is_empty() {
|
||||
let name = parts[0].to_string();
|
||||
let mut bits: u16 = 0;
|
||||
for p in &parts {
|
||||
if let Ok(b) = p.trim_matches(|c: char| !c.is_ascii_digit()).parse::<u16>() {
|
||||
if b > 0 {
|
||||
bits = b;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
ciphers.push(CipherSuite {
|
||||
name,
|
||||
bits,
|
||||
protocol: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ciphers
|
||||
}
|
||||
|
||||
pub fn check_expiry(not_after: &str) -> ExpiryStatus {
|
||||
let parsed = parse_date_manual(not_after);
|
||||
|
||||
match parsed {
|
||||
Some(days_remaining) => {
|
||||
if days_remaining < 0 {
|
||||
ExpiryStatus::Expired
|
||||
} else if days_remaining <= 30 {
|
||||
ExpiryStatus::ExpiringSoon(days_remaining as u32)
|
||||
} else {
|
||||
ExpiryStatus::Valid
|
||||
}
|
||||
}
|
||||
None => ExpiryStatus::Valid,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_date_manual(date_str: &str) -> Option<i64> {
|
||||
let months = [
|
||||
("Jan", 1), ("Feb", 2), ("Mar", 3), ("Apr", 4),
|
||||
("May", 5), ("Jun", 6), ("Jul", 7), ("Aug", 8),
|
||||
("Sep", 9), ("Oct", 10), ("Nov", 11), ("Dec", 12),
|
||||
];
|
||||
|
||||
let parts: Vec<&str> = date_str.split_whitespace().collect();
|
||||
if parts.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// "Nov 29 12:00:00 2026 GMT"
|
||||
let month = months.iter().find(|(m, _)| *m == parts[0])?.1;
|
||||
let day: u32 = parts[1].parse().ok()?;
|
||||
// parts[2] is time, parts[3] is year
|
||||
let year: i64 = parts[3].parse().ok()?;
|
||||
|
||||
let now_epoch = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()?
|
||||
.as_secs() as i64;
|
||||
|
||||
// Approximate days from epoch for target date
|
||||
let target_epoch = approx_epoch(year, month, day)?;
|
||||
let diff_secs = target_epoch - now_epoch;
|
||||
Some(diff_secs / 86400)
|
||||
}
|
||||
|
||||
fn approx_epoch(year: i64, month: u32, day: u32) -> Option<i64> {
|
||||
// Days from 1970-01-01 to year-month-day (approximate, sufficient for 30-day check)
|
||||
let mut y = year;
|
||||
let mut m = month as i64;
|
||||
if m <= 2 {
|
||||
y -= 1;
|
||||
m += 12;
|
||||
}
|
||||
let days = 365 * y + y / 4 - y / 100 + y / 400 + (153 * (m - 3) + 2) / 5 + day as i64 - 719469;
|
||||
Some(days * 86400)
|
||||
}
|
||||
|
||||
pub fn parse_hsts(headers: &str) -> Option<HstsInfo> {
|
||||
let lower = headers.to_lowercase();
|
||||
let line = lower
|
||||
.lines()
|
||||
.find(|l| l.contains("strict-transport-security"))?;
|
||||
|
||||
let value = line.splitn(2, ':').nth(1)?.trim();
|
||||
|
||||
let mut info = HstsInfo::default();
|
||||
|
||||
for part in value.split(';') {
|
||||
let p = part.trim();
|
||||
if let Some(age) = p.strip_prefix("max-age=") {
|
||||
info.max_age = age.trim().trim_matches('"').parse().unwrap_or(0);
|
||||
} else if p == "includesubdomains" {
|
||||
info.include_subdomains = true;
|
||||
} else if p == "preload" {
|
||||
info.preload = true;
|
||||
}
|
||||
}
|
||||
|
||||
Some(info)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hostname matching
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn hostname_matches_san(host: &str, san_entries: &[String]) -> bool {
|
||||
let host_lower = host.to_lowercase();
|
||||
for entry in san_entries {
|
||||
let e = entry.to_lowercase();
|
||||
if e == host_lower {
|
||||
return true;
|
||||
}
|
||||
// Wildcard: *.example.com matches sub.example.com
|
||||
if let Some(rest) = e.strip_prefix("*.") {
|
||||
if let Some(dot_pos) = host_lower.find('.') {
|
||||
if host_lower[dot_pos + 1..] == *rest {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main probe
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub async fn probe_tls<F, Fut>(
|
||||
host: &str,
|
||||
ports: &[u16],
|
||||
_timeout_secs: u64,
|
||||
runner: F,
|
||||
) -> TlsFacts
|
||||
where
|
||||
F: Fn(String) -> Fut,
|
||||
Fut: std::future::Future<Output = Option<String>>,
|
||||
{
|
||||
let mut facts = TlsFacts::default();
|
||||
let mut evidence_lines = Vec::new();
|
||||
|
||||
for &port in ports {
|
||||
let mut port_tls = PortTls {
|
||||
port,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// 1. Connect and get certificate text
|
||||
let cert_cmd = cert_text_command(host, port);
|
||||
if let Some(cert_out) = runner(cert_cmd).await {
|
||||
if !cert_out.trim().is_empty() {
|
||||
let cert = parse_cert_text(&cert_out);
|
||||
evidence_lines.push(format!("[{host}:{port}] subject={}", cert.subject));
|
||||
|
||||
// Check expiry
|
||||
if !cert.not_after.is_empty() {
|
||||
match check_expiry(&cert.not_after) {
|
||||
ExpiryStatus::Expired => {
|
||||
facts.loot.push(format!(
|
||||
"tls:expired:{host}:{port} — certificate expired {}",
|
||||
cert.not_after
|
||||
));
|
||||
}
|
||||
ExpiryStatus::ExpiringSoon(days) => {
|
||||
facts.loot.push(format!(
|
||||
"tls:expiring-soon:{host}:{port} — expires in {days} days"
|
||||
));
|
||||
}
|
||||
ExpiryStatus::Valid => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Check self-signed
|
||||
if cert.self_signed {
|
||||
facts.loot.push(format!(
|
||||
"tls:self-signed:{host}:{port} — self-signed certificate"
|
||||
));
|
||||
}
|
||||
|
||||
// Check weak key
|
||||
if let Some(bits) = cert.key_size {
|
||||
if bits < 2048 {
|
||||
facts.loot.push(format!(
|
||||
"tls:weak-key:{host}:{port} — RSA {bits} bits (< 2048)"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Check SHA-1 signature
|
||||
let sig_lower = cert.sig_algo.to_lowercase();
|
||||
if sig_lower.contains("sha1") || sig_lower.contains("sha-1") {
|
||||
facts.loot.push(format!(
|
||||
"tls:sha1-sig:{host}:{port} — certificate uses SHA-1 signature"
|
||||
));
|
||||
}
|
||||
|
||||
// Check hostname mismatch
|
||||
if !cert.san.is_empty() && !hostname_matches_san(host, &cert.san) {
|
||||
facts.loot.push(format!(
|
||||
"tls:hostname-mismatch:{host}:{port} — SAN does not match host"
|
||||
));
|
||||
}
|
||||
|
||||
port_tls.cert = Some(cert);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Check for weak protocols
|
||||
let weak_protos = [
|
||||
("ssl3", "SSLv3"),
|
||||
("tls1", "TLS 1.0"),
|
||||
("tls1_1", "TLS 1.1"),
|
||||
];
|
||||
for (flag, label) in &weak_protos {
|
||||
let cmd = check_protocol_command(host, port, flag);
|
||||
if let Some(out) = runner(cmd).await {
|
||||
let lower = out.to_lowercase();
|
||||
// Connection succeeded if no "error" / "wrong version" / "alert"
|
||||
if !lower.contains("error")
|
||||
&& !lower.contains("wrong version")
|
||||
&& !lower.contains("no protocols available")
|
||||
&& !lower.contains("alert handshake failure")
|
||||
&& (lower.contains("protocol :") || lower.contains("cipher :") || lower.contains("connected"))
|
||||
{
|
||||
port_tls.weak_protocols.push(label.to_string());
|
||||
port_tls.protocols.push(label.to_string());
|
||||
facts.loot.push(format!(
|
||||
"tls:weak-protocol:{host}:{port} — {label} supported"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check TLS 1.2 and 1.3 support (not weak, just record)
|
||||
for (flag, label) in &[("tls1_2", "TLS 1.2"), ("tls1_3", "TLS 1.3")] {
|
||||
let cmd = check_protocol_command(host, port, flag);
|
||||
if let Some(out) = runner(cmd).await {
|
||||
let lower = out.to_lowercase();
|
||||
if !lower.contains("error")
|
||||
&& !lower.contains("wrong version")
|
||||
&& !lower.contains("no protocols available")
|
||||
{
|
||||
port_tls.protocols.push(label.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Check HSTS
|
||||
let hsts_cmd = hsts_check_command(host, port);
|
||||
if let Some(hsts_out) = runner(hsts_cmd).await {
|
||||
if let Some(hsts) = parse_hsts(&hsts_out) {
|
||||
port_tls.hsts = Some(hsts);
|
||||
} else if hsts_out.trim().is_empty() {
|
||||
facts.loot.push(format!(
|
||||
"tls:no-hsts:{host}:{port} — HSTS not set"
|
||||
));
|
||||
}
|
||||
} else {
|
||||
facts.loot.push(format!(
|
||||
"tls:no-hsts:{host}:{port} — HSTS not set"
|
||||
));
|
||||
}
|
||||
|
||||
facts.ports.push(port_tls);
|
||||
}
|
||||
|
||||
facts.evidence = evidence_lines.join("\n");
|
||||
facts
|
||||
}
|
||||
|
||||
/// Format TLS findings as a FACTS block for LLM consumption.
|
||||
pub fn facts_block(facts: &TlsFacts, host: &str) -> String {
|
||||
if facts.ports.is_empty() && facts.loot.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut lines = vec![format!("### TLS/SSL probe — {host}")];
|
||||
for pt in &facts.ports {
|
||||
lines.push(format!("Port {}: protocols=[{}], weak=[{}]",
|
||||
pt.port,
|
||||
pt.protocols.join(", "),
|
||||
pt.weak_protocols.join(", "),
|
||||
));
|
||||
if let Some(cert) = &pt.cert {
|
||||
lines.push(format!(" subject={} issuer={} san=[{}] expires={} key={}bit sig={}",
|
||||
cert.subject, cert.issuer,
|
||||
cert.san.join(", "),
|
||||
cert.not_after,
|
||||
cert.key_size.map_or("?".into(), |b| b.to_string()),
|
||||
cert.sig_algo,
|
||||
));
|
||||
}
|
||||
if let Some(hsts) = &pt.hsts {
|
||||
lines.push(format!(" HSTS: max-age={} includeSubDomains={} preload={}",
|
||||
hsts.max_age, hsts.include_subdomains, hsts.preload));
|
||||
}
|
||||
}
|
||||
if !facts.loot.is_empty() {
|
||||
lines.push("Findings:".into());
|
||||
for l in &facts.loot {
|
||||
lines.push(format!(" - {l}"));
|
||||
}
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const CERT_TEXT: &str = r#"Certificate:
|
||||
Data:
|
||||
Version: 3 (0x2)
|
||||
Serial Number: 04:00:00:00:00:01:15:4b:5a:c3:94
|
||||
Signature Algorithm: sha256WithRSAEncryption
|
||||
Issuer: C = US, O = DigiCert, CN = DigiCert Global Root CA
|
||||
Validity
|
||||
Not Before: Nov 20 09:12:33 2020 GMT
|
||||
Not After : Dec 15 09:12:33 2028 GMT
|
||||
Subject: C = US, O = Example Corp, CN = www.example.com
|
||||
Subject Public Key Info:
|
||||
Public Key Algorithm: rsaEncryption
|
||||
RSA Public-Key: (4096 bit)
|
||||
X509v3 extensions:
|
||||
X509v3 Subject Alternative Name:
|
||||
DNS:www.example.com, DNS:example.com, DNS:mail.example.com
|
||||
"#;
|
||||
|
||||
const SELF_SIGNED_CERT: &str = r#"Certificate:
|
||||
Data:
|
||||
Version: 3 (0x2)
|
||||
Serial Number: 01
|
||||
Signature Algorithm: sha256WithRSAEncryption
|
||||
Issuer: CN = localhost
|
||||
Validity
|
||||
Not Before: Jan 1 00:00:00 2020 GMT
|
||||
Not After : Jan 1 00:00:00 2021 GMT
|
||||
Subject: CN = localhost
|
||||
Subject Public Key Info:
|
||||
Public Key Algorithm: rsaEncryption
|
||||
RSA Public-Key: (1024 bit)
|
||||
"#;
|
||||
|
||||
const SHA1_CERT: &str = r#"Certificate:
|
||||
Data:
|
||||
Serial Number: 02
|
||||
Signature Algorithm: sha1WithRSAEncryption
|
||||
Issuer: CN = Old CA
|
||||
Validity
|
||||
Not Before: Jan 1 00:00:00 2020 GMT
|
||||
Not After : Dec 31 00:00:00 2030 GMT
|
||||
Subject: CN = old.example.com
|
||||
Subject Public Key Info:
|
||||
Public Key Algorithm: rsaEncryption
|
||||
RSA Public-Key: (2048 bit)
|
||||
"#;
|
||||
|
||||
const OPENSSL_CONNECT: &str = r#"CONNECTED(00000003)
|
||||
---
|
||||
SSL handshake has read 3456 bytes and written 456 bytes
|
||||
---
|
||||
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
|
||||
Protocol : TLSv1.3
|
||||
Cipher : TLS_AES_256_GCM_SHA384
|
||||
---
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_extracts_subject() {
|
||||
let cert = parse_cert_text(CERT_TEXT);
|
||||
assert_eq!(cert.subject, "C = US, O = Example Corp, CN = www.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_extracts_issuer() {
|
||||
let cert = parse_cert_text(CERT_TEXT);
|
||||
assert_eq!(cert.issuer, "C = US, O = DigiCert, CN = DigiCert Global Root CA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_extracts_san() {
|
||||
let cert = parse_cert_text(CERT_TEXT);
|
||||
assert_eq!(cert.san, vec!["www.example.com", "example.com", "mail.example.com"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_extracts_key_size() {
|
||||
let cert = parse_cert_text(CERT_TEXT);
|
||||
assert_eq!(cert.key_size, Some(4096));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_extracts_sig_algo() {
|
||||
let cert = parse_cert_text(CERT_TEXT);
|
||||
assert_eq!(cert.sig_algo, "sha256WithRSAEncryption");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_extracts_dates() {
|
||||
let cert = parse_cert_text(CERT_TEXT);
|
||||
assert_eq!(cert.not_before, "Nov 20 09:12:33 2020 GMT");
|
||||
assert_eq!(cert.not_after, "Dec 15 09:12:33 2028 GMT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_detects_self_signed() {
|
||||
let cert = parse_cert_text(SELF_SIGNED_CERT);
|
||||
assert!(cert.self_signed);
|
||||
assert_eq!(cert.subject, "CN = localhost");
|
||||
assert_eq!(cert.issuer, "CN = localhost");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cert_text_not_self_signed() {
|
||||
let cert = parse_cert_text(CERT_TEXT);
|
||||
assert!(!cert.self_signed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_expiry_detects_expired() {
|
||||
let status = check_expiry("Jan 1 00:00:00 2021 GMT");
|
||||
assert_eq!(status, ExpiryStatus::Expired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_expiry_reports_valid() {
|
||||
let status = check_expiry("Dec 31 00:00:00 2030 GMT");
|
||||
assert_eq!(status, ExpiryStatus::Valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_hsts_extracts_max_age() {
|
||||
let headers = "Strict-Transport-Security: max-age=31536000; includeSubDomains; preload\r\n";
|
||||
let hsts = parse_hsts(headers).unwrap();
|
||||
assert_eq!(hsts.max_age, 31536000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_hsts_detects_include_subdomains() {
|
||||
let headers = "strict-transport-security: max-age=86400; includeSubDomains\r\n";
|
||||
let hsts = parse_hsts(headers).unwrap();
|
||||
assert!(hsts.include_subdomains);
|
||||
assert!(!hsts.preload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_hsts_returns_none_when_missing() {
|
||||
let headers = "Content-Type: text/html\r\n";
|
||||
assert!(parse_hsts(headers).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_openssl_connect_extracts_protocol() {
|
||||
let info = parse_openssl_connect(OPENSSL_CONNECT);
|
||||
assert_eq!(info.protocol, "TLSv1.3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_openssl_connect_extracts_cipher() {
|
||||
let info = parse_openssl_connect(OPENSSL_CONNECT);
|
||||
assert_eq!(info.cipher, "TLS_AES_256_GCM_SHA384");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openssl_connect_command_builds_correctly() {
|
||||
let cmd = openssl_connect_command("example.com", 443, None);
|
||||
assert!(cmd.contains("-connect example.com:443"));
|
||||
assert!(cmd.contains("-servername example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openssl_connect_command_with_sni() {
|
||||
let cmd = openssl_connect_command("1.2.3.4", 443, Some("example.com"));
|
||||
assert!(cmd.contains("-connect 1.2.3.4:443"));
|
||||
assert!(cmd.contains("-servername example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cert_text_command_pipes_correctly() {
|
||||
let cmd = cert_text_command("example.com", 8443);
|
||||
assert!(cmd.contains("-connect example.com:8443"));
|
||||
assert!(cmd.contains("x509 -text -noout"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_key_detection() {
|
||||
let cert = parse_cert_text(SELF_SIGNED_CERT);
|
||||
assert_eq!(cert.key_size, Some(1024));
|
||||
assert!(cert.key_size.unwrap() < 2048);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha1_sig_detection() {
|
||||
let cert = parse_cert_text(SHA1_CERT);
|
||||
assert!(cert.sig_algo.to_lowercase().contains("sha1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostname_match_exact() {
|
||||
let san = vec!["www.example.com".into()];
|
||||
assert!(hostname_matches_san("www.example.com", &san));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostname_match_wildcard() {
|
||||
let san = vec!["*.example.com".into()];
|
||||
assert!(hostname_matches_san("sub.example.com", &san));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostname_mismatch() {
|
||||
let san = vec!["other.com".into()];
|
||||
assert!(!hostname_matches_san("example.com", &san));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_tls_expired_cert_produces_loot() {
|
||||
let result = probe_tls("test.local", &[443], 10, |cmd| async move {
|
||||
if cmd.contains("x509 -text") {
|
||||
Some(SELF_SIGNED_CERT.to_string()) // expired: 2021
|
||||
} else if cmd.contains("curl") {
|
||||
None
|
||||
} else {
|
||||
Some("error\n".to_string())
|
||||
}
|
||||
}).await;
|
||||
|
||||
assert!(result.loot.iter().any(|l| l.contains("tls:expired") || l.contains("tls:self-signed")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_tls_weak_protocol_produces_loot() {
|
||||
let result = probe_tls("test.local", &[443], 10, |cmd| async move {
|
||||
if cmd.contains("x509 -text") {
|
||||
Some(CERT_TEXT.to_string())
|
||||
} else if cmd.contains("-tls1 ") || cmd.contains("-ssl3") {
|
||||
Some("Protocol : TLSv1\nCipher : AES128-SHA\nconnected\n".to_string())
|
||||
} else if cmd.contains("-tls1_1") {
|
||||
Some("error\n".to_string())
|
||||
} else if cmd.contains("curl") {
|
||||
None
|
||||
} else {
|
||||
Some("error\n".to_string())
|
||||
}
|
||||
}).await;
|
||||
|
||||
assert!(result.loot.iter().any(|l| l.contains("tls:weak-protocol")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probe_tls_no_hsts_produces_loot() {
|
||||
let result = probe_tls("test.local", &[443], 10, |cmd| async move {
|
||||
if cmd.contains("x509 -text") {
|
||||
Some(CERT_TEXT.to_string())
|
||||
} else if cmd.contains("curl") {
|
||||
Some(String::new()) // empty = no HSTS header
|
||||
} else {
|
||||
Some("error\n".to_string())
|
||||
}
|
||||
}).await;
|
||||
|
||||
assert!(result.loot.iter().any(|l| l.contains("tls:no-hsts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn facts_block_formats_correctly() {
|
||||
let facts = TlsFacts {
|
||||
ports: vec![PortTls {
|
||||
port: 443,
|
||||
cert: Some(CertInfo {
|
||||
subject: "CN=example.com".into(),
|
||||
issuer: "CN=CA".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
protocols: vec!["TLS 1.2".into(), "TLS 1.3".into()],
|
||||
weak_protocols: vec![],
|
||||
hsts: Some(HstsInfo { max_age: 31536000, include_subdomains: true, preload: false }),
|
||||
}],
|
||||
loot: vec![],
|
||||
evidence: String::new(),
|
||||
};
|
||||
let block = facts_block(&facts, "example.com");
|
||||
assert!(block.contains("TLS/SSL probe"));
|
||||
assert!(block.contains("443"));
|
||||
assert!(block.contains("TLS 1.2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_cipher_list_openssl_format() {
|
||||
let output = "ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD\n";
|
||||
let ciphers = parse_cipher_list(output);
|
||||
assert_eq!(ciphers.len(), 1);
|
||||
assert_eq!(ciphers[0].name, "ECDHE-RSA-AES256-GCM-SHA384");
|
||||
assert_eq!(ciphers[0].bits, 256);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user