Compare commits

..

6 Commits

7 changed files with 550 additions and 96 deletions

288
Cargo.lock generated
View File

@ -2,6 +2,21 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "addr2line"
version = "0.24.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1"
dependencies = [
"gimli",
]
[[package]]
name = "adler2"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
[[package]] [[package]]
name = "aho-corasick" name = "aho-corasick"
version = "1.1.3" version = "1.1.3"
@ -67,18 +82,65 @@ version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"
[[package]]
name = "async-trait"
version = "0.1.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d556ec1359574147ec0c4fc5eb525f3f23263a592b1a9c07e0a75b427de55c97"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "backtrace"
version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a"
dependencies = [
"addr2line",
"cfg-if",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
"windows-targets",
]
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.22.1" version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]] [[package]]
name = "bytes" name = "bytes"
version = "1.10.0" version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9" checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "clap" name = "clap"
version = "4.5.31" version = "4.5.31"
@ -125,6 +187,44 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "colored"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e"
dependencies = [
"windows-sys",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]] [[package]]
name = "displaydoc" name = "displaydoc"
version = "0.2.5" version = "0.2.5"
@ -159,6 +259,22 @@ dependencies = [
"log", "log",
] ]
[[package]]
name = "errno"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]] [[package]]
name = "fnv" name = "fnv"
version = "1.0.7" version = "1.0.7"
@ -174,12 +290,46 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8"
dependencies = [
"cfg-if",
"libc",
"wasi",
"windows-targets",
]
[[package]]
name = "gimli"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.5.0" version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]] [[package]]
name = "http" name = "http"
version = "1.2.0" version = "1.2.0"
@ -348,6 +498,18 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "libc"
version = "0.2.170"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "875b3680cb2f8f71bdcf9a30f38d48282f5d3c95cbf9b3fa57269bb5d5c06828"
[[package]]
name = "linux-raw-sys"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db9c683daf087dc577b7506e9695b3d556a9f3849903fa28186283afd6809e9"
[[package]] [[package]]
name = "litemap" name = "litemap"
version = "0.7.5" version = "0.7.5"
@ -366,6 +528,24 @@ version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "miniz_oxide"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5"
dependencies = [
"adler2",
]
[[package]]
name = "object"
version = "0.36.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.20.3" version = "1.20.3"
@ -378,6 +558,12 @@ version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.94" version = "1.0.94"
@ -425,6 +611,25 @@ version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "rustc-demangle"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "rustix"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17f8dcd64f141950290e45c99f7710ede1b600297c91818bb30b3667c0f45dc0"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]] [[package]]
name = "scep_req_parser" name = "scep_req_parser"
version = "0.1.0" version = "0.1.0"
@ -432,9 +637,13 @@ dependencies = [
"anyhow", "anyhow",
"base64", "base64",
"clap", "clap",
"colored",
"env_logger", "env_logger",
"hex",
"http", "http",
"log", "log",
"sha256",
"tempfile",
"url", "url",
] ]
@ -458,6 +667,30 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "sha2"
version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha256"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f880fc8562bdeb709793f00eb42a2ad0e672c4f883bbe59122b926eca935c8f6"
dependencies = [
"async-trait",
"bytes",
"hex",
"sha2",
"tokio",
]
[[package]] [[package]]
name = "smallvec" name = "smallvec"
version = "1.14.0" version = "1.14.0"
@ -498,6 +731,20 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "tempfile"
version = "3.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c317e0a526ee6120d8dabad239c8dadca62b24b6f168914bbbc8e2fb1f0e567"
dependencies = [
"cfg-if",
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]] [[package]]
name = "tinystr" name = "tinystr"
version = "0.7.6" version = "0.7.6"
@ -508,6 +755,23 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "tokio"
version = "1.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e"
dependencies = [
"backtrace",
"bytes",
"pin-project-lite",
]
[[package]]
name = "typenum"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.18" version = "1.0.18"
@ -543,6 +807,21 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasi"
version = "0.13.3+wasi-0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2"
dependencies = [
"wit-bindgen-rt",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.59.0" version = "0.59.0"
@ -616,6 +895,15 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "wit-bindgen-rt"
version = "0.33.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c"
dependencies = [
"bitflags",
]
[[package]] [[package]]
name = "write16" name = "write16"
version = "1.0.0" version = "1.0.0"

View File

@ -10,4 +10,8 @@ clap = { version = "4.5.31", features = ["derive", "env"] }
http = { version = "1.2.0" } http = { version = "1.2.0" }
anyhow = "1.0.97" anyhow = "1.0.97"
url = "2.5.4" url = "2.5.4"
base64 = "0.22.1" base64 = "0.22.1"
sha256 = "1.6.0"
colored = "3.0.0"
tempfile = "3.18.0"
hex = "0.4.3"

View File

@ -1,3 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
}

135
src/asn_parsing.rs Normal file
View File

@ -0,0 +1,135 @@
use std::io::Write;
use std::process::{Command};
use anyhow::Context;
use tempfile::NamedTempFile;
#[derive(Debug, Default)]
pub struct SCEPRequest {
cn: String,
alt_name: String,
}
#[derive(Debug, Default)]
pub struct SCEPResponse {
encrypted_data_len: usize,
}
/// Parse asn1 content
fn parse_asn1(openssl: &str, req: &[u8]) -> anyhow::Result<String> {
let mut tmpfile: NamedTempFile = NamedTempFile::new()?;
tmpfile.write_all(req)?;
tmpfile.flush()?;
let stdout = Command::new(openssl)
.arg("asn1parse")
.arg("-inform")
.arg("DER")
.arg("-in")
.arg(tmpfile.path().to_str().unwrap())
.output()?;
Ok(String::from_utf8_lossy(&stdout.stdout).to_string())
}
/// Decode SCEP request
pub fn decode_request(openssl: &str, req: &[u8]) -> anyhow::Result<SCEPRequest> {
let output = parse_asn1(openssl, req)?;
let output = output.trim().replace('\r', "");
log::debug!("ASN1 request output: {output}");
let lines = output.split('\n').collect::<Vec<&str>>();
let mut res = SCEPRequest::default();
for (num, line) in lines.iter().enumerate() {
// Extract common name
if line.contains(":commonName") {
res.cn = lines[num + 1].split_once("PRINTABLESTRING").unwrap().1.split_once(':').unwrap().1.to_string();
}
// Extract subject alternative name
if line.contains("Subject Alternative Name") {
let subj_rev = lines[num + 2].rsplit_once(':').unwrap().1;
let sub_alt_name = hex::decode(subj_rev.trim()).context("Subject Alternative Name")?;
let res_decode_alt_name = parse_asn1(openssl, &sub_alt_name)?;
let res_decode_alt_name = res_decode_alt_name.replace('\r', "");
log::debug!("Subject alternative name: {res_decode_alt_name}");
// Extract Microsoft User Principal Name
let subj_alt_name_lines = res_decode_alt_name.split('\n').collect::<Vec<&str>>();
for (num, line) in subj_alt_name_lines.iter().enumerate() {
if line.contains("Microsoft User Principal Name") {
res.alt_name = subj_alt_name_lines[num + 2].split_once("UTF8STRING").unwrap().1.split_once(':').unwrap().1.to_string();
}
}
}
}
Ok(res)
}
/// Decode SCEP response
pub fn decode_response(openssl: &str, res: &[u8]) -> anyhow::Result<SCEPResponse> {
let output = parse_asn1(openssl, res)?;
let output = output.trim().replace('\r', "");
log::debug!("ASN1 response output: {output}");
let lines = output.split('\n').collect::<Vec<&str>>();
let mut byte_string = String::new();
// Extract PKCS7 payload
let mut extracting = false;
for (num, line) in lines.iter().enumerate() {
// Wait for payload
if !extracting {
if !line.contains(":pkcs7-data") {
extracting = true;
}
continue;
}
if line.contains("EOC") {
break;
}
if !line.contains("[HEX DUMP]:") {
continue;
}
byte_string.push_str(&line.split_once("[HEX DUMP]:").unwrap().1);
}
let mut res = SCEPResponse::default();
let pkcs7_data = hex::decode(byte_string.trim()).context("Decode PKCS7")?;
let pkcs7_decoded = parse_asn1(openssl, &pkcs7_data)?;
log::debug!("PKCS7 decoded data: {}", pkcs7_decoded);
// Extract encrypted payload
let mut byte_string = String::new();
let mut extracting = false;
for (num, line) in lines.iter().enumerate() {
// Wait for payload
if !extracting {
if !line.contains(":aes-128-cbc") {
extracting = true;
}
continue;
}
if line.contains("EOC") {
break;
}
if !line.contains("[HEX DUMP]:") {
continue;
}
byte_string.push_str(&line.split_once("[HEX DUMP]:").unwrap().1);
}
let encrypted_data = hex::decode(byte_string.trim()).context("Decode encrypted data")?;
res.encrypted_data_len = encrypted_data.len();
Ok(res)
}

87
src/http_decoder.rs Normal file
View File

@ -0,0 +1,87 @@
use std::str::FromStr;
use http::StatusCode;
/// Find a byte position in an array of bytes
fn find_in_bytes(haystack: &[u8], needle: u8) -> Option<usize> {
haystack.iter().position(|&x| x == needle)
}
/// Parse HTTP request
pub fn parse_request(req: &[u8]) -> anyhow::Result<http::Request<Vec<u8>>> {
// Extract first list
let first_line_end = find_in_bytes(req, b'\r').expect("No newline found in req");
let first_line = String::from_utf8_lossy(&req[..first_line_end]);
let first_line = first_line.split(' ').collect::<Vec<_>>();
let method = first_line[0];
let uri = first_line[1];
//let version = first_line[2];
let mut builder = http::Request::builder()
.method(http::method::Method::from_str(method)?)
.uri(uri)
.version(http::version::Version::HTTP_10); // FIXME: parse version properly
let mut remainder = &req[first_line_end + 2..];
// Parse following lines
while remainder.len() > 2 {
let line_end =
find_in_bytes(remainder, b'\r').expect("No newline found while parsing headers");
if line_end == 0 {
break;
}
let line = String::from_utf8_lossy(&remainder[..line_end]);
let (key, value) = line.split_once(": ").unwrap();
builder = builder.header(key, value);
remainder = &remainder[line_end + 2..];
}
if remainder.len() > 2 {
Ok(builder.body(remainder[2..].to_vec())?)
} else {
Ok(builder.body(Vec::new())?)
}
}
/// Parse HTTP response
pub fn parse_response(req: &[u8]) -> anyhow::Result<http::Response<Vec<u8>>> {
// Extract first list
let first_line_end = find_in_bytes(req, b'\r').expect("No newline found in req");
let first_line = String::from_utf8_lossy(&req[..first_line_end]);
let first_line = first_line.split(' ').collect::<Vec<_>>();
// let version = first_line[0];
let status = first_line[1].parse::<u16>()?;
let mut builder = http::Response::builder()
.status(StatusCode::from_u16(status)?)
.version(http::version::Version::HTTP_10); // FIXME: parse version properly
let mut remainder = &req[first_line_end + 2..];
// Parse following lines
while remainder.len() > 2 {
let line_end =
find_in_bytes(remainder, b'\r').expect("No newline found while parsing headers");
if line_end == 0 {
break;
}
let line = String::from_utf8_lossy(&remainder[..line_end]);
let (key, value) = line.split_once(": ").unwrap();
builder = builder.header(key, value);
remainder = &remainder[line_end + 2..];
}
if remainder.len() > 2 {
Ok(builder.body(remainder[2..].to_vec())?)
} else {
Ok(builder.body(Vec::new())?)
}
}

2
src/lib.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod http_decoder;
pub mod asn_parsing;

View File

@ -1,12 +1,11 @@
use clap::Parser; use clap::Parser;
use http::StatusCode;
use std::collections::HashMap; use std::collections::HashMap;
use std::str::FromStr;
use base64::alphabet::STANDARD;
use url::Url; use url::Url;
use base64::prelude::*; use base64::prelude::*;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE as BASE64_URL_URL_SAFE; use base64::engine::general_purpose::URL_SAFE as BASE64_URL_URL_SAFE;
use colored::Colorize;
use scep_req_parser::asn_parsing::{decode_request, decode_response};
use scep_req_parser::http_decoder::{parse_request, parse_response};
/// Simple SCEP parser program /// Simple SCEP parser program
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
@ -19,92 +18,16 @@ struct Args {
/// Name of the file containing the response (WITH HTTP headers) /// Name of the file containing the response (WITH HTTP headers)
#[arg(short('R'), long)] #[arg(short('R'), long)]
res_file: String, res_file: String,
/// Display decoding URL (lapo.it)
#[arg(short('d'), long)]
decode_url: bool,
/// OpenSSL command path
#[arg(short('o'), long, default_value = "openssl", env)]
openssl_command: String,
} }
/// Find a byte position in an array of bytes
fn find_in_bytes(haystack: &[u8], needle: u8) -> Option<usize> {
haystack.iter().position(|&x| x == needle)
}
/// Parse HTTP request
fn parse_request(req: &[u8]) -> anyhow::Result<http::Request<Vec<u8>>> {
// Extract first list
let first_line_end = find_in_bytes(req, b'\r').expect("No newline found in req");
let first_line = String::from_utf8_lossy(&req[..first_line_end]);
let first_line = first_line.split(' ').collect::<Vec<_>>();
let method = first_line[0];
let uri = first_line[1];
//let version = first_line[2];
let mut builder = http::Request::builder()
.method(http::method::Method::from_str(method)?)
.uri(uri)
.version(http::version::Version::HTTP_10); // FIXME: parse version properly
let mut remainder = &req[first_line_end + 2..];
// Parse following lines
while remainder.len() > 2 {
let line_end =
find_in_bytes(remainder, b'\r').expect("No newline found while parsing headers");
if line_end == 0 {
break;
}
let line = String::from_utf8_lossy(&remainder[..line_end]);
let (key, value) = line.split_once(": ").unwrap();
builder = builder.header(key, value);
remainder = &remainder[line_end + 2..];
}
if remainder.len() > 2 {
Ok(builder.body(remainder[2..].to_vec())?)
} else {
Ok(builder.body(Vec::new())?)
}
}
/// Parse HTTP response
fn parse_response(req: &[u8]) -> anyhow::Result<http::Response<Vec<u8>>> {
// Extract first list
let first_line_end = find_in_bytes(req, b'\r').expect("No newline found in req");
let first_line = String::from_utf8_lossy(&req[..first_line_end]);
let first_line = first_line.split(' ').collect::<Vec<_>>();
// let version = first_line[0];
let status = first_line[1].parse::<u16>()?;
let mut builder = http::Response::builder()
.status(StatusCode::from_u16(status)?)
.version(http::version::Version::HTTP_10); // FIXME: parse version properly
let mut remainder = &req[first_line_end + 2..];
// Parse following lines
while remainder.len() > 2 {
let line_end =
find_in_bytes(remainder, b'\r').expect("No newline found while parsing headers");
if line_end == 0 {
break;
}
let line = String::from_utf8_lossy(&remainder[..line_end]);
let (key, value) = line.split_once(": ").unwrap();
builder = builder.header(key, value);
remainder = &remainder[line_end + 2..];
}
if remainder.len() > 2 {
Ok(builder.body(remainder[2..].to_vec())?)
} else {
Ok(builder.body(Vec::new())?)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Operation { enum Operation {
@ -138,15 +61,33 @@ fn main() {
_ => panic!("Unsupported operation {}!", operation), _ => panic!("Unsupported operation {}!", operation),
}; };
let status = match response.status().as_u16() {
100..=199=> response.status().as_u16().to_string().blue(),
200..=299 => response.status().as_u16().to_string().green(),
400..=999 => response.status().as_u16().to_string().red(),
_ => response.status().as_u16().to_string().white().on_red(),
};
let date = response.headers().get("Date").unwrap().to_str().unwrap();
println!("{} - {} - {op:?}", response.headers().get("Date").unwrap().to_str().unwrap(), response.status().as_u16()); let sha_req = sha256::digest(request.body()).chars().take(10).collect::<String>();
let sha_res = sha256::digest(response.body()).chars().take(10).collect::<String>();
println!("{date} - {status} - {op:?}\t - Req: {sha_req}\t - Res: {sha_res}");
// Parse details about PKIOperation request // Parse details about PKIOperation request
// https://www.rfc-editor.org/rfc/rfc8894.html#section-4.3 // https://www.rfc-editor.org/rfc/rfc8894.html#section-4.3
if op == Operation::PKIOperation { if op == Operation::PKIOperation && args.decode_url {
let req_b64 = BASE64_URL_URL_SAFE.encode(&request.body()); let req_b64 = BASE64_URL_URL_SAFE.encode(&request.body());
let res_b64 = BASE64_URL_URL_SAFE.encode(&response.body()); let res_b64 = BASE64_URL_URL_SAFE.encode(&response.body());
println!("https://lapo.it/asn1js/#{req_b64}"); println!("=> REQ https://lapo.it/asn1js/#{req_b64}");
println!("https://lapo.it/asn1js/#{res_b64}"); println!("=> RES https://lapo.it/asn1js/#{res_b64}");
} }
if op == Operation::PKIOperation {
let req = decode_request(&args.openssl_command, request.body()).expect("Failed to decode request!");
let res = decode_response(&args.openssl_command, response.body()).expect("Failed to decode response!");
println!("{req:?}");
println!("{res:?}");
}
} }