1
//! Handle the middle document of an onion service descriptor.
2

            
3
use once_cell::sync::Lazy;
4
use subtle::ConstantTimeEq;
5
use tor_hscrypto::pk::{HsBlindId, HsClientDescEncSecretKey, HsSvcDescEncKey};
6
use tor_hscrypto::{RevisionCounter, Subcredential};
7
use tor_llcrypto::pk::curve25519;
8
use tor_llcrypto::util::ct::CtByteArray;
9

            
10
use crate::doc::hsdesc::desc_enc::build_descriptor_cookie_key;
11
use crate::parse::tokenize::{Item, NetDocReader};
12
use crate::parse::{keyword::Keyword, parser::SectionRules};
13
use crate::types::misc::B64;
14
use crate::{Pos, Result};
15

            
16
use super::desc_enc::{
17
    HsDescEncNonce, HsDescEncryption, HS_DESC_CLIENT_ID_LEN, HS_DESC_ENC_NONCE_LEN, HS_DESC_IV_LEN,
18
};
19
use super::HsDescError;
20

            
21
/// The only currently recognized `desc-auth-type`.
22
//
23
// TODO: In theory this should be an enum, if we ever add a second value here.
24
pub(super) const HS_DESC_AUTH_TYPE: &str = "x25519";
25

            
26
/// A more-or-less verbatim representation of the middle document of an onion
27
/// service descriptor.
28
#[derive(Debug, Clone)]
29
#[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
30
pub(super) struct HsDescMiddle {
31
    /// A public key used by authorized clients to decrypt the key used to
32
    /// decrypt the encryption layer and decode the inner document.  This is
33
    /// ignored if client authorization is not in use.
34
    ///
35
    /// This is `KP_hss_desc_enc`, and appears as `desc-auth-ephemeral-key` in
36
    /// the document format; It is used along with `KS_hsc_desc_enc` to perform
37
    /// a diffie-hellman operation and decrypt the encryption layer.
38
    svc_desc_enc_key: HsSvcDescEncKey,
39
    /// One or more authorized clients, and the key exchange information that
40
    /// they use to compute shared keys for decrypting the encryption layer.
41
    ///
42
    /// Each of these is parsed from a `auth-client` line.
43
    auth_clients: Vec<AuthClient>,
44
    /// The (encrypted) inner document of the onion service descriptor.
45
    encrypted: Vec<u8>,
46
}
47

            
48
impl HsDescMiddle {
49
    /// Decrypt the encrypted inner document contained within this middle
50
    /// document.
51
    ///
52
    /// If present, `key` is an authorization key, and we assume that the
53
    /// decryption is nontrivial.
54
    ///
55
    /// A failure may mean either that the encryption was corrupted, or that we
56
    /// didn't have the right key.
57
    #[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
58
    pub(super) fn decrypt_inner(
59
        &self,
60
        blinded_id: &HsBlindId,
61
        revision: RevisionCounter,
62
        subcredential: &Subcredential,
63
        key: Option<&HsClientDescEncSecretKey>,
64
    ) -> std::result::Result<Vec<u8>, super::HsDescError> {
65
        let desc_enc_nonce = key.and_then(|k| self.find_cookie(subcredential, k));
66
        let decrypt = HsDescEncryption {
67
            blinded_id,
68
            desc_enc_nonce: desc_enc_nonce.as_ref(),
69
            subcredential,
70
            revision,
71
            string_const: b"hsdir-encrypted-data",
72
        };
73

            
74
        match decrypt.decrypt(&self.encrypted) {
75
            Ok(mut v) => {
76
                // Work around a bug in an implementation we presume to be
77
                // OnionBalance: it doesn't NL-terminate the final line of the
78
                // inner document.
79
                if !v.ends_with(b"\n") {
80
                    v.push(b'\n');
81
                }
82
                Ok(v)
83
            }
84
            Err(_) => match (key, desc_enc_nonce) {
85
                (Some(_), None) => Err(HsDescError::WrongDecryptionKey),
86
                (Some(_), Some(_)) => Err(HsDescError::DecryptionFailed),
87
                (None, _) => Err(HsDescError::MissingDecryptionKey),
88
            },
89
        }
90
    }
91

            
92
    /// Use a `ClientDescAuthSecretKey` (`KS_hsc_desc_enc`) to see if there is any `auth-client`
93
    /// entry for us (a client who holds that secret key) in this descriptor.
94
    /// If so, decrypt it and return its
95
    /// corresponding "Descriptor Cookie" (`N_hs_desc_enc`)
96
    ///
97
    /// If no such `N_hs_desc_enc` is found, then either we do not have
98
    /// permission to decrypt the encryption layer, OR no permission is required.
99
    ///
100
    /// (The protocol makes it intentionally impossible to distinguish any error
101
    /// conditions here other than "no cookie for you.")
102
    fn find_cookie(
103
        &self,
104
        subcredential: &Subcredential,
105
        ks_hsc_desc_enc: &HsClientDescEncSecretKey,
106
    ) -> Option<HsDescEncNonce> {
107
        use cipher::{KeyIvInit, StreamCipher};
108
        use tor_llcrypto::cipher::aes::Aes256Ctr as Cipher;
109
        use tor_llcrypto::util::ct::ct_lookup;
110

            
111
        let (client_id, cookie_key) = build_descriptor_cookie_key(
112
            ks_hsc_desc_enc.as_ref(),
113
            &self.svc_desc_enc_key,
114
            subcredential,
115
        );
116
        // See whether there is any matching client_id in self.auth_ids.
117
        let auth_client = ct_lookup(&self.auth_clients, |c| c.client_id.ct_eq(&client_id))?;
118

            
119
        // We found an auth client entry: Take and decrypt the cookie `N_hs_desc_enc` at last.
120
        let mut cookie = auth_client.encrypted_cookie;
121
        let mut cipher = Cipher::new(&cookie_key.into(), &auth_client.iv.into());
122
        cipher.apply_keystream(&mut cookie);
123
        Some(cookie.into())
124
    }
125
}
126

            
127
/// Information that a single authorized client can use to decrypt the onion
128
/// service descriptor.
129
#[derive(Debug, Clone)]
130
pub(super) struct AuthClient {
131
    /// A check field that clients can use to see if this [`AuthClient`] entry corresponds to a key they hold.
132
    ///
133
    /// This is the first part of the `auth-client` line.
134
    pub(super) client_id: CtByteArray<HS_DESC_CLIENT_ID_LEN>,
135
    /// An IV used to decrypt `encrypted_cookie`.
136
    ///
137
    /// This is the second item on the `auth-client` line.
138
    pub(super) iv: [u8; HS_DESC_IV_LEN],
139
    /// An encrypted value used to find the descriptor cookie `N_hs_desc_enc`,
140
    /// which in turn is
141
    /// needed to decrypt the [HsDescMiddle]'s `encrypted_body`.
142
    ///
143
    /// This is the third item on the `auth-client` line.  When decrypted, it
144
    /// reveals a `DescEncEncryptionCookie` (`N_hs_desc_enc`, not yet so named
145
    /// in the spec).
146
    pub(super) encrypted_cookie: [u8; HS_DESC_ENC_NONCE_LEN],
147
}
148

            
149
impl AuthClient {
150
    /// Try to extract an AuthClient from a single AuthClient item.
151
    fn from_item(item: &Item<'_, HsMiddleKwd>) -> Result<Self> {
152
        use crate::NetdocErrorKind as EK;
153

            
154
        if item.kwd() != HsMiddleKwd::AUTH_CLIENT {
155
            return Err(EK::Internal.with_msg("called with invalid argument."));
156
        }
157
        let client_id = item.parse_arg::<B64>(0)?.into_array()?.into();
158
        let iv = item.parse_arg::<B64>(1)?.into_array()?;
159
        let encrypted_cookie = item.parse_arg::<B64>(2)?.into_array()?;
160
        Ok(AuthClient {
161
            client_id,
162
            iv,
163
            encrypted_cookie,
164
        })
165
    }
166
}
167

            
168
decl_keyword! {
169
    pub(crate) HsMiddleKwd {
170
        "desc-auth-type" => DESC_AUTH_TYPE,
171
        "desc-auth-ephemeral-key" => DESC_AUTH_EPHEMERAL_KEY,
172
        "auth-client" => AUTH_CLIENT,
173
        "encrypted" => ENCRYPTED,
174
    }
175
}
176

            
177
/// Rules about how keywords appear in the middle document of an onion service
178
/// descriptor.
179
static HS_MIDDLE_RULES: Lazy<SectionRules<HsMiddleKwd>> = Lazy::new(|| {
180
    use HsMiddleKwd::*;
181

            
182
    let mut rules = SectionRules::builder();
183
    rules.add(DESC_AUTH_TYPE.rule().required().args(1..));
184
    rules.add(DESC_AUTH_EPHEMERAL_KEY.rule().required().args(1..));
185
    rules.add(AUTH_CLIENT.rule().required().may_repeat().args(3..));
186
    rules.add(ENCRYPTED.rule().required().obj_required());
187
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
188

            
189
    rules.build()
190
});
191

            
192
impl HsDescMiddle {
193
    /// Try to parse the middle document of an onion service descriptor from a provided
194
    /// string.
195
    #[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
196
    pub(super) fn parse(s: &str) -> Result<HsDescMiddle> {
197
        let mut reader = NetDocReader::new(s);
198
        let result = HsDescMiddle::take_from_reader(&mut reader).map_err(|e| e.within(s))?;
199
        Ok(result)
200
    }
201

            
202
    /// Extract an HsDescMiddle from a reader.
203
    ///
204
    /// The reader must contain a single HsDescOuter; we return an error if not.
205
    fn take_from_reader(reader: &mut NetDocReader<'_, HsMiddleKwd>) -> Result<HsDescMiddle> {
206
        use crate::NetdocErrorKind as EK;
207
        use HsMiddleKwd::*;
208

            
209
        let body = HS_MIDDLE_RULES.parse(reader)?;
210

            
211
        // Check for the only currently recognized `desc-auth-type`
212
        {
213
            let auth_type = body.required(DESC_AUTH_TYPE)?.required_arg(0)?;
214
            if auth_type != HS_DESC_AUTH_TYPE {
215
                return Err(EK::BadDocumentVersion
216
                    .at_pos(Pos::at(auth_type))
217
                    .with_msg(format!("Unrecognized desc-auth-type {auth_type:?}")));
218
            }
219
        }
220

            
221
        // Extract `KP_hss_desc_enc` from DESC_AUTH_EPHEMERAL_KEY
222
        let ephemeral_key: HsSvcDescEncKey = {
223
            let token = body.required(DESC_AUTH_EPHEMERAL_KEY)?;
224
            let key = curve25519::PublicKey::from(token.parse_arg::<B64>(0)?.into_array()?);
225
            key.into()
226
        };
227

            
228
        // Parse all the auth-client lines.
229
        let auth_clients: Vec<AuthClient> = body
230
            .slice(AUTH_CLIENT)
231
            .iter()
232
            .map(AuthClient::from_item)
233
            .collect::<Result<Vec<_>>>()?;
234

            
235
        // The encrypted body is taken verbatim.
236
        let encrypted_body: Vec<u8> = body.required(ENCRYPTED)?.obj("MESSAGE")?;
237

            
238
        Ok(HsDescMiddle {
239
            svc_desc_enc_key: ephemeral_key,
240
            auth_clients,
241
            encrypted: encrypted_body,
242
        })
243
    }
244
}
245

            
246
#[cfg(test)]
247
mod test {
248
    // @@ begin test lint list maintained by maint/add_warning @@
249
    #![allow(clippy::bool_assert_comparison)]
250
    #![allow(clippy::clone_on_copy)]
251
    #![allow(clippy::dbg_macro)]
252
    #![allow(clippy::print_stderr)]
253
    #![allow(clippy::print_stdout)]
254
    #![allow(clippy::single_char_pattern)]
255
    #![allow(clippy::unwrap_used)]
256
    #![allow(clippy::unchecked_duration_subtraction)]
257
    #![allow(clippy::useless_vec)]
258
    #![allow(clippy::needless_pass_by_value)]
259
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
260

            
261
    use hex_literal::hex;
262
    use tor_checkable::{SelfSigned, Timebound};
263

            
264
    use super::*;
265
    use crate::doc::hsdesc::{
266
        outer::HsDescOuter,
267
        test_data::{TEST_DATA, TEST_SUBCREDENTIAL},
268
    };
269

            
270
    #[test]
271
    fn parse_good() -> Result<()> {
272
        let desc = HsDescOuter::parse(TEST_DATA)?
273
            .dangerously_assume_wellsigned()
274
            .dangerously_assume_timely();
275
        let subcred = TEST_SUBCREDENTIAL.into();
276
        let body = desc.decrypt_body(&subcred).unwrap();
277
        let body = std::str::from_utf8(&body[..]).unwrap();
278

            
279
        let middle = HsDescMiddle::parse(body)?;
280
        assert_eq!(
281
            middle.svc_desc_enc_key.as_bytes(),
282
            &hex!("161090571E6DB517C0C8591CE524A56DF17BAE3FF8DCD50735F9AEB89634073E")
283
        );
284
        assert_eq!(middle.auth_clients.len(), 16);
285

            
286
        // Here we make sure that decryption "works" minimally and returns some
287
        // bytes for a descriptor with no HsClientDescEncSecretKey.
288
        //
289
        // We make sure that the actual decrypted value is reasonable elsewhere,
290
        // in the tests in inner.rs.
291
        //
292
        // We test the case where a HsClientDescEncSecretKey is needed
293
        // elsewhere, in `hsdesc::test::parse_desc_auth_good`.
294
        let _inner_body = middle
295
            .decrypt_inner(&desc.blinded_id(), desc.revision_counter(), &subcred, None)
296
            .unwrap();
297

            
298
        Ok(())
299
    }
300
}