1 use sha2::Sha256;
2 use hmac::{Hmac, Mac, NewMac};
3 
4 use crate::secure::{base64, Key};
5 use crate::{Cookie, CookieJar};
6 
7 // Keep these in sync, and keep the key len synced with the `signed` docs as
8 // well as the `KEYS_INFO` const in secure::Key.
9 pub(crate) const BASE64_DIGEST_LEN: usize = 44;
10 pub(crate) const KEY_LEN: usize = 32;
11 
12 /// A child cookie jar that authenticates its cookies.
13 ///
14 /// A _signed_ child jar signs all the cookies added to it and verifies cookies
15 /// retrieved from it. Any cookies stored in a `SignedJar` are provided
16 /// integrity and authenticity. In other words, clients cannot tamper with the
17 /// contents of a cookie nor can they fabricate cookie values, but the data is
18 /// visible in plaintext.
19 #[cfg_attr(nightly, doc(cfg(feature = "signed")))]
20 pub struct SignedJar<'a> {
21     parent: &'a mut CookieJar,
22     key: [u8; KEY_LEN],
23 }
24 
25 impl<'a> SignedJar<'a> {
26     /// Creates a new child `SignedJar` with parent `parent` and key `key`. This
27     /// method is typically called indirectly via the `signed` method of
28     /// `CookieJar`.
new(parent: &'a mut CookieJar, key: &Key) -> SignedJar<'a>29     pub(crate) fn new(parent: &'a mut CookieJar, key: &Key) -> SignedJar<'a> {
30         SignedJar { parent, key: key.signing }
31     }
32 
33     /// Signs the cookie's value providing integrity and authenticity.
sign_cookie(&self, cookie: &mut Cookie)34     fn sign_cookie(&self, cookie: &mut Cookie) {
35         // Compute HMAC-SHA256 of the cookie's value.
36         let mut mac = Hmac::<Sha256>::new_varkey(&self.key).expect("good key");
37         mac.update(cookie.value().as_bytes());
38 
39         // Cookie's new value is [MAC | original-value].
40         let mut new_value = base64::encode(&mac.finalize().into_bytes());
41         new_value.push_str(cookie.value());
42         cookie.set_value(new_value);
43     }
44 
45     /// Given a signed value `str` where the signature is prepended to `value`,
46     /// verifies the signed value and returns it. If there's a problem, returns
47     /// an `Err` with a string describing the issue.
verify(&self, cookie_value: &str) -> Result<String, &'static str>48     fn verify(&self, cookie_value: &str) -> Result<String, &'static str> {
49         if cookie_value.len() < BASE64_DIGEST_LEN {
50             return Err("length of value is <= BASE64_DIGEST_LEN");
51         }
52 
53         // Split [MAC | original-value] into its two parts.
54         let (digest_str, value) = cookie_value.split_at(BASE64_DIGEST_LEN);
55         let digest = base64::decode(digest_str).map_err(|_| "bad base64 digest")?;
56 
57         // Perform the verification.
58         let mut mac = Hmac::<Sha256>::new_varkey(&self.key).expect("good key");
59         mac.update(value.as_bytes());
60         mac.verify(&digest)
61             .map(|_| value.to_string())
62             .map_err(|_| "value did not verify")
63     }
64 
65     /// Returns a reference to the `Cookie` inside this jar with the name `name`
66     /// and verifies the authenticity and integrity of the cookie's value,
67     /// returning a `Cookie` with the authenticated value. If the cookie cannot
68     /// be found, or the cookie fails to verify, `None` is returned.
69     ///
70     /// # Example
71     ///
72     /// ```rust
73     /// use cookie::{CookieJar, Cookie, Key};
74     ///
75     /// let key = Key::generate();
76     /// let mut jar = CookieJar::new();
77     /// let mut signed_jar = jar.signed(&key);
78     /// assert!(signed_jar.get("name").is_none());
79     ///
80     /// signed_jar.add(Cookie::new("name", "value"));
81     /// assert_eq!(signed_jar.get("name").unwrap().value(), "value");
82     /// ```
get(&self, name: &str) -> Option<Cookie<'static>>83     pub fn get(&self, name: &str) -> Option<Cookie<'static>> {
84         if let Some(cookie_ref) = self.parent.get(name) {
85             let mut cookie = cookie_ref.clone();
86             if let Ok(value) = self.verify(cookie.value()) {
87                 cookie.set_value(value);
88                 return Some(cookie);
89             }
90         }
91 
92         None
93     }
94 
95     /// Adds `cookie` to the parent jar. The cookie's value is signed assuring
96     /// integrity and authenticity.
97     ///
98     /// # Example
99     ///
100     /// ```rust
101     /// use cookie::{CookieJar, Cookie, Key};
102     ///
103     /// let key = Key::generate();
104     /// let mut jar = CookieJar::new();
105     /// jar.signed(&key).add(Cookie::new("name", "value"));
106     ///
107     /// assert_ne!(jar.get("name").unwrap().value(), "value");
108     /// assert!(jar.get("name").unwrap().value().contains("value"));
109     /// assert_eq!(jar.signed(&key).get("name").unwrap().value(), "value");
110     /// ```
add(&mut self, mut cookie: Cookie<'static>)111     pub fn add(&mut self, mut cookie: Cookie<'static>) {
112         self.sign_cookie(&mut cookie);
113         self.parent.add(cookie);
114     }
115 
116     /// Adds an "original" `cookie` to this jar. The cookie's value is signed
117     /// assuring integrity and authenticity. Adding an original cookie does not
118     /// affect the [`CookieJar::delta()`] computation. This method is intended
119     /// to be used to seed the cookie jar with cookies received from a client's
120     /// HTTP message.
121     ///
122     /// For accurate `delta` computations, this method should not be called
123     /// after calling `remove`.
124     ///
125     /// # Example
126     ///
127     /// ```rust
128     /// use cookie::{CookieJar, Cookie, Key};
129     ///
130     /// let key = Key::generate();
131     /// let mut jar = CookieJar::new();
132     /// jar.signed(&key).add_original(Cookie::new("name", "value"));
133     ///
134     /// assert_eq!(jar.iter().count(), 1);
135     /// assert_eq!(jar.delta().count(), 0);
136     /// ```
add_original(&mut self, mut cookie: Cookie<'static>)137     pub fn add_original(&mut self, mut cookie: Cookie<'static>) {
138         self.sign_cookie(&mut cookie);
139         self.parent.add_original(cookie);
140     }
141 
142     /// Removes `cookie` from the parent jar.
143     ///
144     /// For correct removal, the passed in `cookie` must contain the same `path`
145     /// and `domain` as the cookie that was initially set.
146     ///
147     /// See [`CookieJar::remove()`] for more details.
148     ///
149     /// # Example
150     ///
151     /// ```rust
152     /// use cookie::{CookieJar, Cookie, Key};
153     ///
154     /// let key = Key::generate();
155     /// let mut jar = CookieJar::new();
156     /// let mut signed_jar = jar.signed(&key);
157     ///
158     /// signed_jar.add(Cookie::new("name", "value"));
159     /// assert!(signed_jar.get("name").is_some());
160     ///
161     /// signed_jar.remove(Cookie::named("name"));
162     /// assert!(signed_jar.get("name").is_none());
163     /// ```
remove(&mut self, cookie: Cookie<'static>)164     pub fn remove(&mut self, cookie: Cookie<'static>) {
165         self.parent.remove(cookie);
166     }
167 }
168 
169 #[cfg(test)]
170 mod test {
171     use crate::{CookieJar, Cookie, Key};
172 
173     #[test]
simple()174     fn simple() {
175         let key = Key::generate();
176         let mut jar = CookieJar::new();
177         assert_simple_behaviour!(jar, jar.signed(&key));
178     }
179 
180     #[test]
private()181     fn private() {
182         let key = Key::generate();
183         let mut jar = CookieJar::new();
184         assert_secure_behaviour!(jar, jar.signed(&key));
185     }
186 
187     #[test]
roundtrip()188     fn roundtrip() {
189         // Secret is SHA-256 hash of 'Super secret!' passed through HKDF-SHA256.
190         let key = Key::from(&[89, 202, 200, 125, 230, 90, 197, 245, 166, 249,
191             34, 169, 135, 31, 20, 197, 94, 154, 254, 79, 60, 26, 8, 143, 254,
192             24, 116, 138, 92, 225, 159, 60, 157, 41, 135, 129, 31, 226, 196, 16,
193             198, 168, 134, 4, 42, 1, 196, 24, 57, 103, 241, 147, 201, 185, 233,
194             10, 180, 170, 187, 89, 252, 137, 110, 107]);
195 
196         let mut jar = CookieJar::new();
197         jar.add(Cookie::new("signed_with_ring014",
198                 "3tdHXEQ2kf6fxC7dWzBGmpSLMtJenXLKrZ9cHkSsl1w=Tamper-proof"));
199         jar.add(Cookie::new("signed_with_ring016",
200                 "3tdHXEQ2kf6fxC7dWzBGmpSLMtJenXLKrZ9cHkSsl1w=Tamper-proof"));
201 
202         let signed = jar.signed(&key);
203         assert_eq!(signed.get("signed_with_ring014").unwrap().value(), "Tamper-proof");
204         assert_eq!(signed.get("signed_with_ring016").unwrap().value(), "Tamper-proof");
205     }
206 }
207