2018-11-24 12:44:17 +01:00
|
|
|
use chrono::{offset::Utc, DateTime};
|
2018-05-04 17:18:00 +02:00
|
|
|
use openssl::hash::{Hasher, MessageDigest};
|
2019-03-20 17:56:17 +01:00
|
|
|
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE, DATE, USER_AGENT};
|
2018-10-03 09:31:38 +02:00
|
|
|
use std::ops::Deref;
|
2018-07-26 21:35:35 +02:00
|
|
|
use std::time::SystemTime;
|
2021-02-04 07:44:06 +01:00
|
|
|
use tracing::warn;
|
2018-05-04 17:18:00 +02:00
|
|
|
|
2020-01-21 07:02:03 +01:00
|
|
|
use crate::activity_pub::sign::Signer;
|
|
|
|
use crate::activity_pub::{ap_accept_header, AP_CONTENT_TYPE};
|
2018-05-04 17:18:00 +02:00
|
|
|
|
2018-11-26 10:21:52 +01:00
|
|
|
const PLUME_USER_AGENT: &str = concat!("Plume/", env!("CARGO_PKG_VERSION"));
|
2018-05-04 17:18:00 +02:00
|
|
|
|
2021-01-15 16:43:41 +01:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct Error();
|
|
|
|
|
2018-10-11 13:51:45 +02:00
|
|
|
pub struct Digest(String);
|
2018-05-04 17:18:00 +02:00
|
|
|
|
2018-10-03 09:31:38 +02:00
|
|
|
impl Digest {
|
2018-11-26 10:21:52 +01:00
|
|
|
pub fn digest(body: &str) -> HeaderValue {
|
2018-11-24 12:44:17 +01:00
|
|
|
let mut hasher =
|
|
|
|
Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
|
|
|
hasher
|
2018-11-26 10:21:52 +01:00
|
|
|
.update(body.as_bytes())
|
2018-11-24 12:44:17 +01:00
|
|
|
.expect("Digest::digest: content insertion error");
|
2018-10-20 08:44:33 +02:00
|
|
|
let res = base64::encode(&hasher.finish().expect("Digest::digest: finalizing error"));
|
2018-11-24 12:44:17 +01:00
|
|
|
HeaderValue::from_str(&format!("SHA-256={}", res))
|
|
|
|
.expect("Digest::digest: header creation error")
|
2018-10-03 09:31:38 +02:00
|
|
|
}
|
|
|
|
|
2018-11-26 10:21:52 +01:00
|
|
|
pub fn verify(&self, body: &str) -> bool {
|
2018-11-24 12:44:17 +01:00
|
|
|
if self.algorithm() == "SHA-256" {
|
|
|
|
let mut hasher =
|
|
|
|
Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
|
|
|
hasher
|
2018-11-26 10:21:52 +01:00
|
|
|
.update(body.as_bytes())
|
2018-11-24 12:44:17 +01:00
|
|
|
.expect("Digest::digest: content insertion error");
|
|
|
|
self.value().deref()
|
|
|
|
== hasher
|
|
|
|
.finish()
|
|
|
|
.expect("Digest::digest: finalizing error")
|
|
|
|
.deref()
|
2018-10-03 09:31:38 +02:00
|
|
|
} else {
|
|
|
|
false //algorithm not supported
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-22 18:27:21 +01:00
|
|
|
pub fn verify_header(&self, other: &Digest) -> bool {
|
2019-03-20 17:56:17 +01:00
|
|
|
self.value() == other.value()
|
2018-12-22 18:27:21 +01:00
|
|
|
}
|
|
|
|
|
2018-10-03 09:31:38 +02:00
|
|
|
pub fn algorithm(&self) -> &str {
|
2018-11-24 12:44:17 +01:00
|
|
|
let pos = self
|
|
|
|
.0
|
|
|
|
.find('=')
|
|
|
|
.expect("Digest::algorithm: invalid header error");
|
2018-10-03 09:31:38 +02:00
|
|
|
&self.0[..pos]
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn value(&self) -> Vec<u8> {
|
2018-11-24 12:44:17 +01:00
|
|
|
let pos = self
|
|
|
|
.0
|
|
|
|
.find('=')
|
2019-03-20 17:56:17 +01:00
|
|
|
.expect("Digest::value: invalid header error")
|
|
|
|
+ 1;
|
2018-10-20 08:44:33 +02:00
|
|
|
base64::decode(&self.0[pos..]).expect("Digest::value: invalid encoding error")
|
2018-10-03 09:31:38 +02:00
|
|
|
}
|
|
|
|
|
2021-01-15 16:43:41 +01:00
|
|
|
pub fn from_header(dig: &str) -> Result<Self, Error> {
|
2018-10-03 09:31:38 +02:00
|
|
|
if let Some(pos) = dig.find('=') {
|
2018-11-24 12:44:17 +01:00
|
|
|
let pos = pos + 1;
|
2018-11-26 10:21:52 +01:00
|
|
|
if base64::decode(&dig[pos..]).is_ok() {
|
2018-10-03 09:31:38 +02:00
|
|
|
Ok(Digest(dig.to_owned()))
|
|
|
|
} else {
|
2021-01-15 16:43:41 +01:00
|
|
|
Err(Error())
|
2018-10-03 09:31:38 +02:00
|
|
|
}
|
|
|
|
} else {
|
2021-01-15 16:43:41 +01:00
|
|
|
Err(Error())
|
2018-10-03 09:31:38 +02:00
|
|
|
}
|
|
|
|
}
|
2018-12-22 18:27:21 +01:00
|
|
|
|
|
|
|
pub fn from_body(body: &str) -> Self {
|
2019-03-20 17:56:17 +01:00
|
|
|
let mut hasher =
|
|
|
|
Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
|
|
|
hasher
|
|
|
|
.update(body.as_bytes())
|
|
|
|
.expect("Digest::digest: content insertion error");
|
2018-12-22 18:27:21 +01:00
|
|
|
let res = base64::encode(&hasher.finish().expect("Digest::digest: finalizing error"));
|
|
|
|
Digest(format!("SHA-256={}", res))
|
|
|
|
}
|
2018-10-03 09:31:38 +02:00
|
|
|
}
|
|
|
|
|
2018-10-11 13:51:45 +02:00
|
|
|
pub fn headers() -> HeaderMap {
|
|
|
|
let date: DateTime<Utc> = SystemTime::now().into();
|
2019-03-25 14:13:54 +01:00
|
|
|
let date = format!("{}", date.format("%a, %d %b %Y %T GMT"));
|
2018-10-11 13:51:45 +02:00
|
|
|
|
|
|
|
let mut headers = HeaderMap::new();
|
|
|
|
headers.insert(USER_AGENT, HeaderValue::from_static(PLUME_USER_AGENT));
|
2018-11-24 12:44:17 +01:00
|
|
|
headers.insert(
|
|
|
|
DATE,
|
|
|
|
HeaderValue::from_str(&date).expect("request::headers: date error"),
|
|
|
|
);
|
|
|
|
headers.insert(
|
|
|
|
ACCEPT,
|
|
|
|
HeaderValue::from_str(
|
|
|
|
&ap_accept_header()
|
|
|
|
.into_iter()
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.join(", "),
|
2019-03-20 17:56:17 +01:00
|
|
|
)
|
|
|
|
.expect("request::headers: accept error"),
|
2018-11-24 12:44:17 +01:00
|
|
|
);
|
2018-11-23 13:18:33 +01:00
|
|
|
headers.insert(CONTENT_TYPE, HeaderValue::from_static(AP_CONTENT_TYPE));
|
2018-05-04 17:18:00 +02:00
|
|
|
headers
|
|
|
|
}
|
|
|
|
|
2021-01-20 18:45:29 +01:00
|
|
|
type Method<'a> = &'a str;
|
|
|
|
type Path<'a> = &'a str;
|
|
|
|
type Query<'a> = &'a str;
|
2021-01-24 16:13:53 +01:00
|
|
|
type RequestTarget<'a> = (Method<'a>, Path<'a>, Option<Query<'a>>);
|
2021-01-20 18:45:29 +01:00
|
|
|
|
|
|
|
pub fn signature<S: Signer>(
|
|
|
|
signer: &S,
|
|
|
|
headers: &HeaderMap,
|
2021-01-24 16:13:53 +01:00
|
|
|
request_target: RequestTarget,
|
2021-01-20 18:45:29 +01:00
|
|
|
) -> Result<HeaderValue, Error> {
|
2021-01-24 16:13:53 +01:00
|
|
|
let (method, path, query) = request_target;
|
2021-01-20 18:45:29 +01:00
|
|
|
let origin_form = if let Some(query) = query {
|
|
|
|
format!("{}?{}", path, query)
|
|
|
|
} else {
|
|
|
|
path.to_string()
|
|
|
|
};
|
|
|
|
|
2021-02-04 07:44:06 +01:00
|
|
|
let mut headers_vec = Vec::with_capacity(headers.len());
|
|
|
|
for (h, v) in headers.iter() {
|
|
|
|
let v = v.to_str();
|
|
|
|
if v.is_err() {
|
|
|
|
warn!("invalid header error: {:?}", v.unwrap_err());
|
|
|
|
return Err(Error());
|
|
|
|
}
|
|
|
|
headers_vec.push((h.as_str().to_lowercase(), v.expect("Unreachable")));
|
|
|
|
}
|
2021-01-20 18:45:29 +01:00
|
|
|
let request_target = format!("{} {}", method.to_lowercase(), origin_form);
|
2021-02-04 07:44:06 +01:00
|
|
|
headers_vec.push(("(request-target)".to_string(), &request_target));
|
2021-01-20 18:45:29 +01:00
|
|
|
|
2021-02-04 07:44:06 +01:00
|
|
|
let signed_string = headers_vec
|
2021-01-20 18:45:29 +01:00
|
|
|
.iter()
|
|
|
|
.map(|(h, v)| format!("{}: {}", h, v))
|
2018-11-24 12:44:17 +01:00
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join("\n");
|
2021-02-04 07:44:06 +01:00
|
|
|
let signed_headers = headers_vec
|
2018-11-24 12:44:17 +01:00
|
|
|
.iter()
|
2021-01-20 18:45:29 +01:00
|
|
|
.map(|(h, _)| h.as_ref())
|
2018-11-24 12:44:17 +01:00
|
|
|
.collect::<Vec<&str>>()
|
2021-01-20 18:45:29 +01:00
|
|
|
.join(" ");
|
2018-09-11 20:53:14 +02:00
|
|
|
|
2021-01-15 16:43:41 +01:00
|
|
|
let data = signer.sign(&signed_string).map_err(|_| Error())?;
|
2018-11-26 10:21:52 +01:00
|
|
|
let sign = base64::encode(&data);
|
2018-05-04 17:18:00 +02:00
|
|
|
|
2018-10-11 13:51:45 +02:00
|
|
|
HeaderValue::from_str(&format!(
|
2018-05-08 21:38:37 +02:00
|
|
|
"keyId=\"{key_id}\",algorithm=\"rsa-sha256\",headers=\"{signed_headers}\",signature=\"{signature}\"",
|
2018-06-21 17:31:42 +02:00
|
|
|
key_id = signer.get_key_id(),
|
2018-05-04 17:18:00 +02:00
|
|
|
signed_headers = signed_headers,
|
|
|
|
signature = sign
|
2021-01-15 16:43:41 +01:00
|
|
|
)).map_err(|_| Error())
|
2018-05-04 17:18:00 +02:00
|
|
|
}
|
2021-02-05 02:23:54 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::{signature, Error};
|
|
|
|
use crate::activity_pub::sign::{gen_keypair, Signer};
|
|
|
|
use openssl::{hash::MessageDigest, pkey::PKey, rsa::Rsa};
|
|
|
|
use reqwest::header::HeaderMap;
|
|
|
|
|
|
|
|
struct MySigner {
|
|
|
|
public_key: String,
|
|
|
|
private_key: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl MySigner {
|
|
|
|
fn new() -> Self {
|
|
|
|
let (pub_key, priv_key) = gen_keypair();
|
|
|
|
Self {
|
|
|
|
public_key: String::from_utf8(pub_key).unwrap(),
|
|
|
|
private_key: String::from_utf8(priv_key).unwrap(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Signer for MySigner {
|
|
|
|
type Error = Error;
|
|
|
|
|
|
|
|
fn get_key_id(&self) -> String {
|
|
|
|
"mysigner".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn sign(&self, to_sign: &str) -> Result<Vec<u8>, Self::Error> {
|
|
|
|
let key = PKey::from_rsa(Rsa::private_key_from_pem(self.private_key.as_ref()).unwrap())
|
|
|
|
.unwrap();
|
|
|
|
let mut signer = openssl::sign::Signer::new(MessageDigest::sha256(), &key).unwrap();
|
|
|
|
signer.update(to_sign.as_bytes()).unwrap();
|
|
|
|
signer.sign_to_vec().map_err(|_| Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn verify(&self, data: &str, signature: &[u8]) -> Result<bool, Self::Error> {
|
|
|
|
let key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).unwrap())
|
|
|
|
.unwrap();
|
|
|
|
let mut verifier = openssl::sign::Verifier::new(MessageDigest::sha256(), &key).unwrap();
|
|
|
|
verifier.update(data.as_bytes()).unwrap();
|
|
|
|
verifier.verify(&signature).map_err(|_| Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_signature_request_target() {
|
|
|
|
let signer = MySigner::new();
|
|
|
|
let headers = HeaderMap::new();
|
|
|
|
let result = signature(&signer, &headers, ("post", "/inbox", None)).unwrap();
|
|
|
|
let fields: Vec<&str> = result.to_str().unwrap().split(",").collect();
|
|
|
|
assert_eq!(r#"headers="(request-target)""#, fields[2]);
|
|
|
|
let sign = &fields[3][11..(fields[3].len() - 1)];
|
|
|
|
assert!(signer.verify("post /inbox", sign.as_bytes()).is_ok());
|
|
|
|
}
|
|
|
|
}
|