keyhog-verifier 0.5.73

keyhog-verifier: parallel async credential verification framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::collections::HashMap;
use std::time::Duration;

use keyhog_core::VerificationResult;
use quick_xml::de::{Deserializer, PredefinedEntityResolver};
use quick_xml::events::Event;
use reqwest::Client;
use serde::Deserialize;
use sha2::{Digest, Sha256};

use crate::interpolate::CompanionKey;
use crate::verify::request::{execute_request, resolved_client_for_url, RequestError};
use crate::verify::response::read_response_body;

const AWS_VALID_ACCESS_KEY_PREFIXES: &[&str] = &["AKIA", "ASIA", "AROA", "AIDA", "AGPA"];
const AWS_ACCESS_KEY_LEN: usize = 20;
const AWS_MIN_SECRET_KEY_LEN: usize = 40;

/// Operator-facing reason when the region fails the SigV4 region-format check.
/// Leads with the legacy `invalid AWS region` phrase, then names the exact format
/// requirement and where to correct it.
pub const INVALID_AWS_REGION_ERROR: &str = "invalid AWS region: the region must be \
     non-empty, at most 30 characters, and contain only letters, digits, and \
     hyphens (e.g. us-east-1). Fix: correct the AWS region in the detector \
     verification spec or the credential's companion fields";

pub(crate) async fn build_aws_probe(
    access_key: &str,
    secret_key: &str,
    session_token_template: &Option<String>,
    region: &str,
    credential: &str,
    companions: &HashMap<impl CompanionKey, String>,
    timeout: Duration,
    client: &Client,
    allow_private_ips: bool,
    allow_http: bool,
    proxy_in_use: bool,
    insecure_tls: bool,
) -> super::request::RequestBuildResult {
    // Sanitize+resolve every credential field the SigV4 probe signs. A captured
    // value can carry a trailing newline / control byte (line-anchored capture),
    // and `valid_aws_format` requires an EXACT 20-char all-alphanumeric access key,
    // so an unsanitized `AKIA…\n` would be misreported `Dead`: a LIVE key silently
    // missed. This mirrors the sibling `AuthSpec::Query` arm in `auth.rs`, which
    // already resolves + `sanitize_raw_value`s its field. `region` is resolved the
    // same way so a `companion.region` reference actually resolves instead of being
    // fed verbatim to the region-format screen (which only ever rejects it).
    let resolve = |field: &str| {
        crate::interpolate::sanitize_raw_value(&crate::interpolate::resolve_field(
            field, credential, companions,
        ))
    };
    let access_key = resolve(access_key);
    let secret_key = resolve(secret_key);
    let session_token = session_token_template
        .as_ref()
        .map(|template| resolve(template))
        .filter(|token| !token.is_empty());
    let region = resolve(region);

    // Canary short-circuit (fail-closed BEFORE any network egress): an access
    // key whose offline-decoded account belongs to a known canary issuer is a
    // tripwire, the STS `GetCallerIdentity` probe below would alert whoever
    // planted it. Refuse to verify it and surface the canary marker so the
    // operator learns why. Uses the fleet-canonical classifier in
    // `keyhog_core::aws` (same decode + list the scanner attaches as metadata),
    // so there is exactly one canary source of truth.
    match keyhog_core::key_id_canary_status(&access_key) {
        Ok(true) => {
            let metadata = match keyhog_core::finding_metadata(&access_key) {
                Some(metadata) => metadata,
                None => HashMap::from([("is_canary".to_string(), "true".to_string())]),
            }; // LAW10: canary classifier already matched; fallback preserves the canary marker if metadata enrichment is unavailable
            return super::request::RequestBuildResult::Final {
                result: VerificationResult::Unverifiable,
                metadata,
                transient: false,
            };
        }
        Ok(false) => {}
        Err(error) => {
            return super::request::RequestBuildResult::Final {
                result: VerificationResult::Error(format!(
                    "AWS canary account configuration invalid: {error}"
                )),
                metadata: HashMap::from([("canary_config_error".into(), error)]),
                transient: false,
            };
        }
    }

    if secret_key.is_empty() {
        return super::request::RequestBuildResult::Final {
            result: VerificationResult::Unverifiable,
            metadata: HashMap::new(),
            transient: false,
        };
    }

    if !valid_aws_format(&access_key, &secret_key) {
        return super::request::RequestBuildResult::Final {
            result: VerificationResult::Dead,
            metadata: HashMap::from([("format_valid".into(), "false".into())]),
            transient: false,
        };
    }

    if let Err(result) = validate_aws_region(&region) {
        return super::request::RequestBuildResult::Final {
            result,
            metadata: HashMap::new(),
            transient: false,
        };
    }

    let host = format!("sts.{region}.amazonaws.com");
    let url = format!("https://{host}/");
    let body = "Action=GetCallerIdentity&Version=2011-06-15";
    let resolved_target = match resolved_client_for_url(
        client,
        &url,
        timeout,
        allow_private_ips,
        allow_http,
        proxy_in_use,
        insecure_tls,
    )
    .await
    {
        Ok(resolved_target) => resolved_target,
        Err(result) => {
            return super::request::RequestBuildResult::Final {
                result,
                metadata: HashMap::from([("format_valid".into(), "true".into())]),
                transient: false,
            };
        }
    };

    match build_sigv4_request(
        &resolved_target.client,
        resolved_target.url.as_str(),
        &host,
        body,
        &access_key,
        &secret_key,
        session_token.as_deref(),
        &region,
        "sts",
        timeout,
    )
    .await
    {
        Ok((result, metadata, transient)) => super::request::RequestBuildResult::Final {
            result,
            metadata,
            transient,
        },
        Err(error) => super::request::RequestBuildResult::Final {
            result: error.result,
            metadata: HashMap::from([("format_valid".into(), "true".into())]),
            transient: error.transient,
        },
    }
}

pub(crate) fn valid_aws_format(access_key: &str, secret_key: &str) -> bool {
    AWS_VALID_ACCESS_KEY_PREFIXES
        .iter()
        .any(|p| access_key.starts_with(p))
        && access_key.len() == AWS_ACCESS_KEY_LEN
        && keyhog_core::ascii_ci::is_ascii_alphanumeric_str(access_key)
        && secret_key.len() >= AWS_MIN_SECRET_KEY_LEN
        && secret_key
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=')
}

pub(crate) fn validate_aws_region(region: &str) -> std::result::Result<(), VerificationResult> {
    // Validate region to prevent SSRF via malicious detector specs.
    // AWS regions are alphanumeric with hyphens only (e.g., us-east-1).
    if region
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-')
        && !region.is_empty()
        && region.len() <= 30
    {
        Ok(())
    } else {
        Err(VerificationResult::Error(INVALID_AWS_REGION_ERROR.into()))
    }
}

async fn build_sigv4_request(
    client: &Client,
    url: &str,
    host: &str,
    body: &str,
    access_key: &str,
    secret_key: &str,
    session_token: Option<&str>,
    region: &str,
    service: &str,
    timeout: Duration,
) -> std::result::Result<(VerificationResult, HashMap<String, String>, bool), RequestError> {
    use std::time::{SystemTime, UNIX_EPOCH};

    let now_secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|error| RequestError {
            result: VerificationResult::Error(format!("failed to read system clock: {error}")),
            transient: false,
        })?
        .as_secs();
    let canonical_uri = "/";
    let payload_hash = hex::encode(Sha256::digest(body.as_bytes()));
    let (auth_header, amz_date, _) = crate::sigv4::sign_request_authorization(
        access_key,
        secret_key,
        session_token,
        region,
        service,
        "POST",
        canonical_uri,
        &[],
        host,
        &payload_hash,
        now_secs,
        &[],
    )
    .map_err(|error| RequestError {
        result: VerificationResult::Error(error),
        transient: false,
    })?;

    let mut request = client
        .post(url)
        .header("Authorization", auth_header)
        .header("x-amz-date", amz_date)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body(body.to_string())
        .timeout(timeout);

    if let Some(token) = session_token {
        request = request.header("x-amz-security-token", token);
    }

    crate::rate_limit::get_rate_limiter().wait(service).await;

    let response = execute_request(request).await?;
    let status = response.status().as_u16();
    // Profile: streaming the STS response body is async live-verification work.
    let resp_body = keyhog_profile::instrument_future(
        keyhog_profile::Stage::LiveVerification,
        read_response_body(response),
    )
    .await?;

    if resp_body.contains("RequestTimeTooSkewed") || resp_body.contains("SignatureDoesNotMatch") {
        tracing::warn!(
            status,
            "AWS verification failure indicates clock skew or invalid signature. Check system time."
        );
    }

    if status == 200 {
        Ok(classify_aws_sts_http_200(&resp_body))
    } else {
        let (result, transient) = classify_aws_sts_failure(status, &resp_body);
        Ok((result, HashMap::new(), transient))
    }
}

/// HTTP 200 alone is not proof of a live credential: STS must return parseable
/// caller-identity metadata (Arn + Account). Interstitials, wrong endpoints, or
/// truncated bodies must fail closed as `Error`, never `Live`.
pub(crate) fn classify_aws_sts_http_200(
    body: &str,
) -> (VerificationResult, HashMap<String, String>, bool) {
    match parse_aws_sts_success_metadata(body) {
        Ok(metadata) => (VerificationResult::Live, metadata, false),
        Err(error) => {
            tracing::warn!(
                %error,
                "AWS STS GetCallerIdentity returned HTTP 200 but identity metadata could not be parsed; refusing to report the credential as live"
            );
            (
                VerificationResult::Error(format!(
                    "AWS STS GetCallerIdentity returned HTTP 200 but identity metadata could not be parsed: {error}"
                )),
                HashMap::from([("metadata_parse_error".into(), error)]),
                false,
            )
        }
    }
}

pub(crate) fn classify_aws_sts_failure(status: u16, body: &str) -> (VerificationResult, bool) {
    // Profile: STS failure classification inspects the parsed response body.
    let _span = keyhog_profile::span(keyhog_profile::Stage::LiveVerification);
    if status == 403 {
        if body.contains("RequestTimeTooSkewed") {
            return (
                VerificationResult::Error(
                    "AWS STS rejected the request because system time is skewed; fix the host clock and retry verification"
                        .into(),
                ),
                true,
            );
        }
        return (VerificationResult::Dead, false);
    }
    (VerificationResult::RateLimited, true)
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct StsGetCallerIdentityResponse {
    #[serde(default)]
    get_caller_identity_result: StsGetCallerIdentityResult,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct StsGetCallerIdentityResult {
    #[serde(default)]
    arn: Option<String>,
    #[serde(default)]
    account: Option<String>,
    #[serde(default)]
    user_id: Option<String>,
}

pub(crate) fn parse_aws_sts_success_metadata(
    body: &str,
) -> Result<HashMap<String, String>, String> {
    // Profile: STS success parsing is response-parse work.
    let _span = keyhog_profile::span(keyhog_profile::Stage::LiveVerification);
    if body.trim_start().starts_with('{') {
        return parse_aws_sts_json_success_metadata(body);
    }
    parse_aws_sts_xml_success_metadata(body)
}

fn parse_aws_sts_json_success_metadata(body: &str) -> Result<HashMap<String, String>, String> {
    let json = serde_json::from_str::<serde_json::Value>(body)
        .map_err(|error| format!("failed to parse AWS STS success JSON: {error}"))?;
    let result = json
        .pointer("/GetCallerIdentityResponse/GetCallerIdentityResult")
        .ok_or_else(|| "AWS STS success JSON missing GetCallerIdentityResult".to_string())?;
    let mut metadata = HashMap::new();
    insert_json_string_field(&mut metadata, result, "arn", "Arn")?;
    insert_json_string_field(&mut metadata, result, "account_id", "Account")?;
    insert_json_string_field(&mut metadata, result, "user_id", "UserId")?;
    require_identity_metadata(metadata)
}

fn insert_json_string_field(
    metadata: &mut HashMap<String, String>,
    result: &serde_json::Value,
    key: &str,
    field: &str,
) -> Result<(), String> {
    let Some(value) = result.get(field) else {
        return Ok(());
    };
    let Some(value) = value.as_str() else {
        return Err(format!(
            "AWS STS GetCallerIdentity {field} field was not a string"
        ));
    };
    metadata.insert(key.to_string(), value.to_string());
    Ok(())
}

fn parse_aws_sts_xml_success_metadata(body: &str) -> Result<HashMap<String, String>, String> {
    reject_aws_sts_xml_doctype(body)?;
    let mut deserializer = Deserializer::from_str_with_resolver(body, PredefinedEntityResolver);
    let response = StsGetCallerIdentityResponse::deserialize(&mut deserializer)
        .map_err(|error| format!("failed to parse AWS STS success XML: {error}"))?;
    let mut metadata = HashMap::new();
    if let Some(arn) = response.get_caller_identity_result.arn {
        metadata.insert("arn".into(), arn);
    }
    if let Some(account) = response.get_caller_identity_result.account {
        metadata.insert("account_id".into(), account);
    }
    if let Some(user_id) = response.get_caller_identity_result.user_id {
        metadata.insert("user_id".into(), user_id);
    }
    require_identity_metadata(metadata)
}

fn reject_aws_sts_xml_doctype(body: &str) -> Result<(), String> {
    let mut reader = quick_xml::Reader::from_str(body);
    loop {
        match reader.read_event() {
            Ok(Event::DocType(_)) => {
                return Err("AWS STS success XML contains unsupported DOCTYPE declarations".into());
            }
            Ok(Event::Eof) => return Ok(()),
            Ok(_) => {}
            Err(error) => {
                return Err(format!("failed to validate AWS STS success XML: {error}"));
            }
        }
    }
}

fn require_identity_metadata(
    metadata: HashMap<String, String>,
) -> Result<HashMap<String, String>, String> {
    if metadata.contains_key("arn") && metadata.contains_key("account_id") {
        Ok(metadata)
    } else {
        Err("AWS STS success response missing Arn or Account metadata".into())
    }
}