hyperlane-plugin-security 22.14.0

A zero-allocation security hardening plugin for the Hyperlane framework providing prebuilt HSTS/CSP/COOP/COEP/CORP/Referrer headers, stateless HMAC-SHA256 CSRF protection, host/URI/body/path-traversal guards, and extensible SecurityRule hooks.
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use super::*;

/// Computes the FIPS 180-4 SHA-256 digest of `data`.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit SHA-256 digest.
#[inline]
pub fn sha256(data: &[u8]) -> [u8; 32] {
    sha256_finalize_from_state(SHA256_INIT, data, 0)
}

/// Completes a SHA-256 digest starting from an existing midstate after `prefix_bytes`.
///
/// # Arguments
///
/// - `[u32; 8]` - Starting SHA-256 state words.
/// - `&[u8]` - Remaining message bytes to absorb.
/// - `u64` - Number of bytes already compressed into `state`.
///
/// # Returns
///
/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
#[inline]
pub(crate) fn sha256_finalize_from_state(
    mut state: [u32; 8],
    data: &[u8],
    prefix_bytes: u64,
) -> [u8; 32] {
    let bit_len: u64 = prefix_bytes.wrapping_add(data.len() as u64).wrapping_mul(8);
    let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
    for block in blocks {
        sha256_compress(&mut state, block);
    }
    let rem: usize = rem_slice.len();
    let mut block: [u8; 64] = [0u8; 64];
    block[..rem].copy_from_slice(rem_slice);
    block[rem] = 0x80;
    if rem < 56 {
        block[56..64].copy_from_slice(&bit_len.to_be_bytes());
        sha256_compress(&mut state, &block);
    } else {
        sha256_compress(&mut state, &block);
        let mut last_block: [u8; 64] = [0u8; 64];
        last_block[56..64].copy_from_slice(&bit_len.to_be_bytes());
        sha256_compress(&mut state, &last_block);
    }
    let mut out: [u8; 32] = [0u8; 32];
    for (i, word) in state.iter().enumerate() {
        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// Finalizes a SHA-256 digest over a fixed 32-byte inner digest starting from an existing midstate.
///
/// # Arguments
///
/// - `[u32; 8]` - Starting outer SHA-256 state words.
/// - `&[u8; 32]` - 32-byte inner digest to absorb.
/// - `u64` - Number of bytes already compressed into `state`.
///
/// # Returns
///
/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
#[inline]
pub(crate) fn sha256_finalize_32(
    mut state: [u32; 8],
    digest: &[u8; 32],
    prefix_bytes: u64,
) -> [u8; 32] {
    let bit_len: u64 = prefix_bytes.wrapping_add(32).wrapping_mul(8);
    let mut block: [u8; 64] = [0u8; 64];
    block[..32].copy_from_slice(digest);
    block[32] = 0x80;
    block[56..64].copy_from_slice(&bit_len.to_be_bytes());
    sha256_compress(&mut state, &block);
    let mut out: [u8; 32] = [0u8; 32];
    for (i, word) in state.iter().enumerate() {
        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// Executes a single SHA-256 compression round updating `d` and `h` in place.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Eight working state words `[a, b, c, d, e, f, g, h]` indexed cyclically by `base`.
/// - `usize` - Rotation offset in `0..8`.
/// - `u32` - Pre-summed round constant plus schedule word (`K[i].wrapping_add(W[i])`).
#[inline(always)]
fn sha256_round_at(s: &mut [u32; 8], base: usize, kw: u32) {
    let a: u32 = s[base & 7];
    let b: u32 = s[(base + 1) & 7];
    let c: u32 = s[(base + 2) & 7];
    let d: u32 = s[(base + 3) & 7];
    let e: u32 = s[(base + 4) & 7];
    let f: u32 = s[(base + 5) & 7];
    let g: u32 = s[(base + 6) & 7];
    let h: u32 = s[(base + 7) & 7];
    let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
    let ch: u32 = (e & f) ^ ((!e) & g);
    let temp1: u32 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(kw);
    let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
    let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
    s[(base + 3) & 7] = d.wrapping_add(temp1);
    s[(base + 7) & 7] = temp1.wrapping_add(s0.wrapping_add(maj));
}

/// Processes one 64-byte SHA-256 message block into `state`.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running SHA-256 hash state.
/// - `&[u8; 64]` - 512-bit input block array.
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
    let mut w: [u32; 64] = [0u32; 64];
    let (words, _): (&[[u8; 4]], &[u8]) = block.as_chunks::<4>();
    for (slot, word) in w[..16].iter_mut().zip(words.iter()) {
        *slot = u32::from_be_bytes(*word);
    }
    for i in 16..64usize {
        let w15: u32 = w[i - 15];
        let w2: u32 = w[i - 2];
        let s0: u32 = w15.rotate_right(7) ^ w15.rotate_right(18) ^ (w15 >> 3);
        let s1: u32 = w2.rotate_right(17) ^ w2.rotate_right(19) ^ (w2 >> 10);
        w[i] = w[i - 16]
            .wrapping_add(s0)
            .wrapping_add(w[i - 7])
            .wrapping_add(s1);
    }
    let mut s: [u32; 8] = *state;
    let (k_chunks, _): (&[[u32; 8]], &[u32]) = SHA256_K.as_chunks::<8>();
    let (w_chunks, _): (&[[u32; 8]], &[u32]) = w.as_chunks::<8>();
    for (k, w8) in k_chunks.iter().zip(w_chunks.iter()) {
        sha256_round_at(&mut s, 0, k[0].wrapping_add(w8[0]));
        sha256_round_at(&mut s, 7, k[1].wrapping_add(w8[1]));
        sha256_round_at(&mut s, 6, k[2].wrapping_add(w8[2]));
        sha256_round_at(&mut s, 5, k[3].wrapping_add(w8[3]));
        sha256_round_at(&mut s, 4, k[4].wrapping_add(w8[4]));
        sha256_round_at(&mut s, 3, k[5].wrapping_add(w8[5]));
        sha256_round_at(&mut s, 2, k[6].wrapping_add(w8[6]));
        sha256_round_at(&mut s, 1, k[7].wrapping_add(w8[7]));
    }
    for (dst, &delta) in state.iter_mut().zip(s.iter()) {
        *dst = dst.wrapping_add(delta);
    }
}

/// Precomputes SHA-256 ipad and opad midstates for `key`.
///
/// # Arguments
///
/// - `&[u8]` - Secret HMAC key bytes.
///
/// # Returns
///
/// - `HmacSha256Key` - Precomputed inner and outer SHA-256 states.
#[inline]
pub(crate) fn precompute_hmac_sha256_key(key: &[u8]) -> HmacSha256Key {
    let mut pad: [u8; 64] = [0x36u8; 64];
    if key.len() > 64 {
        let hashed: [u8; 32] = sha256(key);
        for (slot, &byte) in pad[..32].iter_mut().zip(hashed.iter()) {
            *slot ^= byte;
        }
    } else {
        for (slot, &byte) in pad[..key.len()].iter_mut().zip(key.iter()) {
            *slot ^= byte;
        }
    }
    let mut ipad_state: [u32; 8] = SHA256_INIT;
    sha256_compress(&mut ipad_state, &pad);
    for slot in &mut pad {
        *slot ^= 0x6a;
    }
    let mut opad_state: [u32; 8] = SHA256_INIT;
    sha256_compress(&mut opad_state, &pad);
    HmacSha256Key {
        ipad_state,
        opad_state,
    }
}

/// Computes the RFC 4231 HMAC-SHA256 tag of `data` using a precomputed [`HmacSha256Key`] without heap allocation.
///
/// # Arguments
///
/// - `&HmacSha256Key` - Precomputed ipad and opad states.
/// - `&[u8]` - Message payload bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
#[inline]
pub(crate) fn hmac_sha256_with_key(pre: &HmacSha256Key, data: &[u8]) -> [u8; 32] {
    let inner_hash: [u8; 32] = sha256_finalize_from_state(pre.ipad_state, data, 64);
    sha256_finalize_32(pre.opad_state, &inner_hash, 64)
}

/// Computes the RFC 4231 HMAC-SHA256 authentication code of `data` under `key`.
///
/// # Arguments
///
/// - `&[u8]` - Secret HMAC key bytes.
/// - `&[u8]` - Message payload bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
#[inline]
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    let pre: HmacSha256Key = precompute_hmac_sha256_key(key);
    hmac_sha256_with_key(&pre, data)
}

/// Compares two byte slices in constant time with respect to their contents.
///
/// # Arguments
///
/// - `&[u8]` - First byte slice.
/// - `&[u8]` - Second byte slice.
///
/// # Returns
///
/// - `bool` - `true` iff both slices have identical length and contents.
#[inline]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for (&x, &y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

/// Encodes a 32-byte digest into a 64-byte stack ASCII lowercase hexadecimal array.
///
/// # Arguments
///
/// - `&[u8; 32]` - 256-bit digest.
///
/// # Returns
///
/// - `[u8; 64]` - Lowercase ASCII hexadecimal bytes.
#[inline]
pub(crate) fn encode_hex_32_stack(bytes: &[u8; 32]) -> [u8; 64] {
    let mut out: [u8; 64] = [0u8; 64];
    for (idx, &byte) in bytes.iter().enumerate() {
        out[idx * 2] = HEX_DIGITS[(byte >> 4) as usize];
        out[idx * 2 + 1] = HEX_DIGITS[(byte & 0x0F) as usize];
    }
    out
}

/// Issues a stateless HMAC-SHA256 signed CSRF token `"<nonce>.<hex_mac>"`.
///
/// # Arguments
///
/// - `&[u8]` - Server-side CSRF HMAC secret.
/// - `&str` - Caller-supplied unique nonce (must not contain `'.'`).
///
/// # Returns
///
/// - `String` - Signed CSRF token suitable for double-submit cookie and header transport.
pub fn issue_csrf_token(secret: &[u8], nonce: &str) -> String {
    let mac: [u8; 32] = hmac_sha256(secret, nonce.as_bytes());
    let sig_bytes: [u8; 64] = encode_hex_32_stack(&mac);
    let mut out: String = String::with_capacity(nonce.len() + 1 + sig_bytes.len());
    out.push_str(nonce);
    out.push('.');
    if let Ok(sig) = from_utf8(&sig_bytes) {
        out.push_str(sig);
    }
    out
}

/// Verifies a stateless HMAC-SHA256 signed CSRF token using a precomputed key without heap allocation.
///
/// # Arguments
///
/// - `&HmacSha256Key` - Precomputed CSRF HMAC key states.
/// - `&str` - Candidate CSRF token (`"<nonce>.<hex_mac>"`).
///
/// # Returns
///
/// - `bool` - `true` when the token signature is valid.
#[inline]
pub(crate) fn verify_csrf_token_with_key(pre: &HmacSha256Key, token: &str) -> bool {
    let Some((nonce, provided_sig)) = token.split_once('.') else {
        return false;
    };
    if nonce.is_empty() || provided_sig.len() != 64 {
        return false;
    }
    let expected_mac: [u8; 32] = hmac_sha256_with_key(pre, nonce.as_bytes());
    let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
    constant_time_eq(provided_sig.as_bytes(), &expected_sig)
}

/// Verifies a stateless HMAC-SHA256 signed CSRF token in constant time.
///
/// # Arguments
///
/// - `&[u8]` - Server-side CSRF HMAC secret.
/// - `&str` - Candidate CSRF token (`"<nonce>.<hex_mac>"`).
///
/// # Returns
///
/// - `bool` - `true` when the token signature is valid under `secret`.
#[inline]
pub fn verify_csrf_token(secret: &[u8], token: &str) -> bool {
    let Some((nonce, provided_sig)) = token.split_once('.') else {
        return false;
    };
    if nonce.is_empty() || provided_sig.len() != 64 {
        return false;
    }
    let expected_mac: [u8; 32] = hmac_sha256(secret, nonce.as_bytes());
    let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
    constant_time_eq(provided_sig.as_bytes(), &expected_sig)
}

/// Checks whether `bytes` starts with `%2e` or `%2E` at offset `idx`.
///
/// # Arguments
///
/// - `&[u8]` - Path byte slice.
/// - `usize` - Starting offset to check.
///
/// # Returns
///
/// - `bool` - `true` when `%2e`/`%2E` starts at `idx`.
#[inline]
pub(crate) fn is_encoded_dot_at(bytes: &[u8], idx: usize) -> bool {
    idx + 2 < bytes.len()
        && bytes[idx] == b'%'
        && bytes[idx + 1] == b'2'
        && (bytes[idx + 2] == b'e' || bytes[idx + 2] == b'E')
}

/// Detects raw or percent-encoded path traversal (`..`, `%2e%2e`), backslashes, or NUL bytes.
///
/// # Arguments
///
/// - `&str` - Incoming URL path.
///
/// # Returns
///
/// - `bool` - `true` when a suspicious path-traversal sequence is present.
#[inline]
pub fn has_path_traversal(path: &str) -> bool {
    let bytes: &[u8] = path.as_bytes();
    let len: usize = bytes.len();
    let mut i: usize = 0;
    while i < len {
        let b: u8 = bytes[i];
        if b == b'\\' || b == 0 {
            return true;
        }
        if b == b'.' {
            if (i + 1 < len && bytes[i + 1] == b'.') || is_encoded_dot_at(bytes, i + 1) {
                return true;
            }
        } else if b == b'%' && i + 2 < len {
            let b1: u8 = bytes[i + 1];
            let b2: u8 = bytes[i + 2];
            if b1 == b'0' && b2 == b'0' {
                return true;
            }
            if b1 == b'5' && (b2 == b'c' || b2 == b'C') {
                return true;
            }
            if b1 == b'2'
                && (b2 == b'e' || b2 == b'E')
                && ((i + 3 < len && bytes[i + 3] == b'.') || is_encoded_dot_at(bytes, i + 3))
            {
                return true;
            }
        }
        i += 1;
    }
    false
}

/// Reports whether `name` is a valid RFC 6265 cookie token.
///
/// # Arguments
///
/// - `&str` - Candidate cookie name.
///
/// # Returns
///
/// - `bool` - `true` when non-empty and all bytes are valid HTTP token characters.
#[inline]
pub(crate) fn is_valid_cookie_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b: u8| b.is_ascii_alphanumeric() || COOKIE_TOKEN_PUNCTUATION.contains(&b))
}

/// Extracts the first valid cookie value matching `target_name` directly from a raw `Cookie` header without allocating.
///
/// # Arguments
///
/// - `&'a str` - Raw `Cookie` request header value.
/// - `&str` - Target cookie name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed cookie value when found and valid.
#[inline]
pub(crate) fn find_cookie_value<'a>(raw_cookie: &'a str, target_name: &str) -> Option<&'a str> {
    if raw_cookie.trim().is_empty() {
        return None;
    }
    for part in raw_cookie.split(COOKIE_PAIR_DELIMITER) {
        let trimmed: &'a str = part.trim();
        if trimmed.is_empty() {
            continue;
        }
        if let Some((name, value)) = trimmed.split_once(COOKIE_KV_DELIMITER) {
            let name: &'a str = name.trim();
            if name != target_name {
                continue;
            }
            let value: &'a str = value.trim();
            if is_valid_cookie_name(name) && !value.bytes().any(|b: u8| b <= 0x1F || b == 0x7F) {
                return Some(value);
            }
        }
    }
    None
}

/// Borrows the last value of request header `lower_name` (or falls back to case-insensitive stack lookup).
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercased header name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline]
pub(crate) fn get_request_header_back_ref<'a>(
    request: &'a Request,
    lower_name: &str,
) -> Option<&'a str> {
    if let Some(values) = request.get_headers().get(lower_name) {
        return values.back().map(String::as_str);
    }
    if lower_name.len() <= STACK_HEADER_NAME_LEN
        && lower_name.bytes().any(|b: u8| b.is_ascii_uppercase())
    {
        let mut stack_buf: [u8; STACK_HEADER_NAME_LEN] = [0u8; STACK_HEADER_NAME_LEN];
        for (dst, &src) in stack_buf.iter_mut().zip(lower_name.as_bytes().iter()) {
            *dst = src.to_ascii_lowercase();
        }
        if let Ok(lower) = from_utf8(&stack_buf[..lower_name.len()]) {
            return request
                .get_headers()
                .get(lower)
                .and_then(|values: &RequestHeadersValue| values.back())
                .map(String::as_str);
        }
    }
    None
}

/// Reports whether `method` is a safe read-only HTTP method exempt from CSRF checks.
///
/// # Arguments
///
/// - `&Method` - Request HTTP method.
///
/// # Returns
///
/// - `bool` - `true` for `GET`, `HEAD`, `OPTIONS`, or `TRACE`.
#[inline]
pub(crate) fn is_csrf_safe_method(method: &Method) -> bool {
    method.is_get() || method.is_head() || method.is_options() || method.is_trace()
}