forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBbcaef90Tahinli1 month ago164 commits

crypto.rs177 lines, 6.4 KiBHistoryRawDownload
1//! Thin glue over `web-push-native`, which does the cryptography: the RFC 8291 message encryption
2//! (aes128gcm content coding, RFC 8188) and the RFC 8292 VAPID authorization (an ES256 JWT). The
3//! crate is RustCrypto based and pure Rust. This module only converts the base64url values that
4//! browsers and the database hold into the types the crate takes, and builds the request.
5
6use base64::Engine;
7use base64::engine::general_purpose::URL_SAFE_NO_PAD;
8use p256::elliptic_curve::sec1::ToEncodedPoint;
9use web_push_native::jwt_simple::algorithms::ES256KeyPair;
10use web_push_native::{Auth, WebPushBuilder, p256};
11
12use forge_core::{Error, Result};
13
14/// The uncompressed P-256 point length: 0x04 followed by X and Y.
15const POINT_LEN: usize = 65;
16
17/// Decodes base64url, with or without padding.
18pub fn decode_b64(text: &str) -> Result<Vec<u8>> {
19 URL_SAFE_NO_PAD
20 .decode(text.trim_end_matches('='))
21 .map_err(|_| Error::Invalid("not base64url".into()))
22}
23
24/// Encodes base64url without padding, the form push services and browsers use.
25pub fn encode_b64(bytes: &[u8]) -> String {
26 URL_SAFE_NO_PAD.encode(bytes)
27}
28
29/// A new VAPID private key (32 bytes) from the system RNG.
30pub fn new_vapid_private() -> [u8; 32] {
31 let mut out = [0u8; 32];
32 out.copy_from_slice(&ES256KeyPair::generate().to_bytes());
33 out
34}
35
36/// The key pair the VAPID signature is made with, from its 32-byte private scalar.
37pub fn vapid_key_pair(private: &[u8; 32]) -> Result<ES256KeyPair> {
38 ES256KeyPair::from_bytes(private).map_err(|_| Error::Crypto("bad VAPID key".into()))
39}
40
41/// The public key of a VAPID private key, as the uncompressed point in base64url. This is the
42/// `applicationServerKey` the browser subscribes with.
43pub fn vapid_public_key(private: &[u8; 32]) -> Result<String> {
44 let secret =
45 p256::SecretKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))?;
46 let point = secret.public_key().to_encoded_point(false);
47 Ok(encode_b64(point.as_bytes()))
48}
49
50/// Builds the POST for one push: the body is encrypted for the browser's key and auth secret,
51/// and the request carries the VAPID `Authorization` for `endpoint`'s origin. `subject` is the
52/// contact URL (`mailto:` or `https:`).
53pub fn push_request(
54 endpoint: &str,
55 p256dh: &[u8],
56 auth: &[u8],
57 subject: &str,
58 key_pair: &ES256KeyPair,
59 payload: Vec<u8>,
60) -> Result<http::Request<Vec<u8>>> {
61 if p256dh.len() != POINT_LEN {
62 return Err(Error::Invalid(
63 "the browser key is not a P-256 point".into(),
64 ));
65 }
66 let ua_public = p256::PublicKey::from_sec1_bytes(p256dh)
67 .map_err(|_| Error::Invalid("the browser key is not on the curve".into()))?;
68 if auth.len() != 16 {
69 return Err(Error::Invalid(
70 "the browser auth secret is not 16 bytes".into(),
71 ));
72 }
73 let ua_auth = Auth::clone_from_slice(auth);
74 let uri: http::Uri = endpoint
75 .parse()
76 .map_err(|_| Error::Invalid("bad push endpoint".into()))?;
77 WebPushBuilder::new(uri, ua_public, ua_auth)
78 .with_vapid(key_pair, subject)
79 .build(payload)
80 .map_err(|e| Error::Crypto(format!("web push encryption failed: {e}")))
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86 use p256::elliptic_curve::sec1::ToEncodedPoint;
87
88 #[test]
89 fn a_browser_key_that_is_not_a_point_is_refused() {
90 let key_pair = vapid_key_pair(&new_vapid_private()).expect("key");
91 let auth = [7u8; 16];
92 let not_a_point = [4u8; 65];
93 assert!(
94 push_request(
95 "https://push.example.test/x",
96 &not_a_point,
97 &auth,
98 "mailto:tahinli@example.test",
99 &key_pair,
100 b"hi".to_vec()
101 )
102 .is_err()
103 );
104 assert!(
105 push_request(
106 "https://push.example.test/x",
107 &[0x04; 10],
108 &auth,
109 "mailto:tahinli@example.test",
110 &key_pair,
111 b"hi".to_vec()
112 )
113 .is_err()
114 );
115 }
116
117 #[test]
118 fn the_request_is_an_encrypted_vapid_post_to_the_endpoint() {
119 let private = new_vapid_private();
120 let key_pair = vapid_key_pair(&private).expect("key");
121 let browser = p256::SecretKey::from_slice(&new_vapid_private()).expect("scalar");
122 let point = browser
123 .public_key()
124 .to_encoded_point(false)
125 .as_bytes()
126 .to_vec();
127 let auth = [9u8; 16];
128 let endpoint = "https://push.example.test/send/abc";
129 let payload = br#"{"title":"tahinli/forge#1"}"#.to_vec();
130 let request = push_request(
131 endpoint,
132 &point,
133 &auth,
134 "mailto:tahinli@example.test",
135 &key_pair,
136 payload.clone(),
137 )
138 .expect("request");
139
140 assert_eq!(request.method(), http::Method::POST);
141 assert_eq!(request.uri().to_string(), endpoint);
142 assert_eq!(request.headers()["content-encoding"], "aes128gcm");
143 assert_eq!(request.headers()["ttl"], "43200");
144
145 // The VAPID header names the push service's origin and carries the instance's public key.
146 let auth_header = request.headers()["authorization"]
147 .to_str()
148 .expect("ascii")
149 .to_owned();
150 assert!(auth_header.starts_with("vapid "), "{auth_header}");
151 assert!(auth_header.contains(&format!(
152 "k={}",
153 vapid_public_key(&private).expect("public")
154 )));
155 let token = auth_header
156 .split("t=")
157 .nth(1)
158 .and_then(|rest| rest.split(',').next())
159 .expect("token");
160 let claims = token.split('.').nth(1).expect("claims");
161 let claims = decode_b64(claims).expect("base64");
162 let claims: serde_json::Value = serde_json::from_slice(&claims).expect("json");
163 assert_eq!(claims["aud"], "https://push.example.test");
164 assert_eq!(claims["sub"], "mailto:tahinli@example.test");
165
166 // The body is encrypted: it is longer than the plaintext and does not contain it.
167 let body = request.body();
168 assert!(body.len() > payload.len());
169 assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice()));
170 }
171
172 #[test]
173 fn the_public_key_is_the_uncompressed_point() {
174 let public = vapid_public_key(&new_vapid_private()).expect("public");
175 assert_eq!(decode_b64(&public).expect("b64").len(), POINT_LEN);
176 }
177}