Skip to content

Commit

Permalink
Merge pull request #116 from TeamPiped/blake3-query-hashing
Browse files Browse the repository at this point in the history
Implement blake3 cryptographic hash verification for query string
  • Loading branch information
FireMasterK authored Nov 20, 2023
2 parents c136f79 + 2aa3053 commit 0a6feb8
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 1 deletion.
26 changes: 26 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ rgb = { version = "0.8.37", optional = true }

once_cell = "1.18.0"
regex = "1.10.2"
blake3 = { version = "1.5.0", optional = true }

[features]
default = ["webp", "mimalloc", "reqwest-rustls"]
default = ["webp", "mimalloc", "reqwest-rustls", "qhash"]

reqwest-rustls = ["reqwest/rustls-tls"]
reqwest-native-tls = ["reqwest/default-tls"]
Expand All @@ -37,5 +38,7 @@ mimalloc = ["dep:mimalloc"]

optimized = ["libwebp-sys?/sse41", "libwebp-sys?/avx2", "libwebp-sys?/neon"]

qhash = ["blake3"]

[profile.release]
lto = true
51 changes: 51 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,57 @@ async fn index(req: HttpRequest) -> Result<HttpResponse, Box<dyn Error>> {
// parse query string
let query = QString::from(req.query_string());

#[cfg(feature = "qhash")]
{
use std::collections::BTreeSet;

let secret = env::var("HASH_SECRET");
if let Ok(secret) = secret {
let qhash = query.get("qhash");

if qhash.is_none() {
return Err("No qhash provided".into());
}

let qhash = qhash.unwrap();

if qhash.len() != 8 {
return Err("Invalid qhash provided".into());
}

// Store sorted key-value pairs
let mut set = BTreeSet::new();
{
let pairs = query.to_pairs();
for (key, value) in &pairs {
if matches!(*key, "qhash" | "range" | "rewrite") {
continue;
}
set.insert((key.as_bytes().to_owned(), value.as_bytes().to_owned()));
}
}

let hash = spawn_blocking(move || {
let mut hasher = blake3::Hasher::new();

for (key, value) in set {
hasher.update(&key);
hasher.update(&value);
}

hasher.update(secret.as_bytes());

let hash = hasher.finalize().to_hex();
let hash = hash[..8].to_owned();
hash
}).await.unwrap();

if hash != qhash {
return Err("Invalid qhash provided".into());
}
}
}

let res = query.get("host");
let res = res.map(|s| s.to_string());

Expand Down

0 comments on commit 0a6feb8

Please sign in to comment.