Skip to main content

stem/descriptor/
hidden_service.rs

1use std::net::{Ipv4Addr, Ipv6Addr};
2
3use aes::{Aes128, Aes256};
4use base64::Engine;
5use chrono::{DateTime, Duration, NaiveDateTime, Utc};
6use ctr::Ctr128BE;
7use ctr::cipher::{KeyIvInit, StreamCipher};
8use curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
9use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
10use curve25519_dalek::scalar::Scalar;
11use data_encoding::BASE32_NOPAD;
12use ed25519_dalek::{Signer, SigningKey};
13use sha1::Sha1;
14use sha2::{Digest, Sha512};
15use sha3::Sha3_256;
16use shake::Shake256;
17use shake::digest::{ExtendableOutput, Update, XofReader};
18use subtle::ConstantTimeEq;
19use x25519_dalek::{PublicKey, StaticSecret};
20
21use crate::address::{is_valid_ipv4_address, parse_port};
22use crate::client::datatypes::{CertType, LinkSpecifier, Reader};
23use crate::descriptor::certificate::{
24    Ed25519Certificate, Ed25519Extension, SIG_PREFIX_HS_V3,
25};
26use crate::descriptor::server::digest_for_signature;
27use crate::descriptor::{
28    AttrValue, Attributes, Entries, LineCursor, ReadOptions, attr, bytes_for_block,
29    content_range, decode_base64, descriptor_components, descriptor_content, key_block,
30    lenient, lenient_option, parse_integer, parse_timestamp_line, random_crypto_blob,
31    random_date, split_into_lines,
32};
33use crate::error::{Error, Result};
34use crate::validation::is_valid_hidden_service_address;
35
36const REQUIRED_V2_FIELDS: [&str; 7] = [
37    "rendezvous-service-descriptor",
38    "version",
39    "permanent-key",
40    "secret-id-part",
41    "publication-time",
42    "protocol-versions",
43    "signature",
44];
45const REQUIRED_V3_FIELDS: [&str; 6] = [
46    "hs-descriptor",
47    "descriptor-lifetime",
48    "descriptor-signing-key-cert",
49    "revision-counter",
50    "superencrypted",
51    "signature",
52];
53const SINGLE_INTRODUCTION_POINT_FIELDS: [&str; 5] = [
54    "introduction-point",
55    "ip-address",
56    "onion-port",
57    "onion-key",
58    "service-key",
59];
60const BASIC_AUTH: u8 = 1;
61const STEALTH_AUTH: u8 = 2;
62const CHECKSUM_CONSTANT: &[u8] = b".onion checksum";
63const BLIND_STRING: &[u8] = b"Derive temporary signing key\0";
64const BASEPOINT_STRING: &[u8] = concat!(
65    "(15112221349535400772501151409588531511454012693041857206046113283949847762202, ",
66    "46316835694926478169428394003475163141307993866256225615783033603165251855960)"
67)
68.as_bytes();
69const PERIOD_ROTATION_MINUTES: i64 = 12 * 60;
70pub const DEFAULT_TIME_PERIOD_LENGTH: u64 = 1440;
71const SALT_LENGTH: usize = 16;
72const MAC_LENGTH: usize = 32;
73const KEY_LENGTH: usize = 32;
74const IV_LENGTH: usize = 16;
75const PLAINTEXT_PADDING_MULTIPLE: usize = 10000;
76const MESSAGE_START: &str = "-----BEGIN MESSAGE-----\n";
77const MESSAGE_END: &str = "\n-----END MESSAGE-----";
78
79type Aes256Ctr = Ctr128BE<Aes256>;
80type Aes128Ctr = Ctr128BE<Aes128>;
81
82#[derive(Debug, thiserror::Error)]
83#[error("{0}")]
84pub struct DecryptionFailure(pub String);
85
86impl From<DecryptionFailure> for Error {
87    fn from(failure: DecryptionFailure) -> Self {
88        Error::Parse(failure.0)
89    }
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
93pub struct IntroductionPoints {
94    pub identifier: Option<String>,
95    pub address: Option<String>,
96    pub port: Option<u16>,
97    pub onion_key: Option<String>,
98    pub service_key: Option<String>,
99    pub intro_authentication: Vec<(String, String)>,
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
103pub struct IntroductionPointV3 {
104    pub link_specifiers: Vec<LinkSpecifier>,
105    pub onion_key_raw: Option<String>,
106    pub auth_key_cert: Ed25519Certificate,
107    pub enc_key_raw: Option<String>,
108    pub enc_key_cert: Ed25519Certificate,
109    pub legacy_key_raw: Option<String>,
110    pub legacy_key_cert: Option<String>,
111}
112
113fn standard_base64(content: &[u8]) -> String {
114    base64::engine::general_purpose::STANDARD.encode(content)
115}
116
117fn certificate_block(entries: &Entries, keyword: &str) -> Result<Ed25519Certificate> {
118    let entry = entries.entry(keyword)?;
119    let (Some(contents), Some("ED25519 CERT")) =
120        (&entry.block_contents, entry.block_type.as_deref())
121    else {
122        return Err(Error::parse(format!(
123            "Expected {keyword} to have an ed25519 certificate, but was {}",
124            entry.block_type.as_deref().unwrap_or("None")
125        )));
126    };
127    Ed25519Certificate::from_base64(contents)
128}
129
130fn ntor_key(line: &str) -> Option<String> {
131    line.strip_prefix("ntor ").map(str::to_string)
132}
133
134impl IntroductionPointV3 {
135    pub fn parse(content: &[u8]) -> Result<Self> {
136        let (entries, _) = descriptor_components(content, false, &[], &[])?;
137        let link_specifiers =
138            Self::parse_link_specifiers(entries.value("introduction-point")?)?;
139        let legacy = |keyword: &str| {
140            entries
141                .get(keyword)
142                .and_then(|values| values.first())
143                .and_then(|entry| entry.block_contents.clone())
144        };
145        Ok(Self {
146            link_specifiers,
147            onion_key_raw: ntor_key(entries.value("onion-key")?),
148            auth_key_cert: certificate_block(&entries, "auth-key")?,
149            enc_key_raw: ntor_key(entries.value("enc-key")?),
150            enc_key_cert: certificate_block(&entries, "enc-key-cert")?,
151            legacy_key_raw: legacy("legacy-key"),
152            legacy_key_cert: legacy("legacy-key-cert"),
153        })
154    }
155
156    fn parse_link_specifiers(content: &str) -> Result<Vec<LinkSpecifier>> {
157        let decoded = decode_base64(content).map_err(|error| {
158            Error::parse(format!(
159                "Unable to base64 decode introduction point ({error}): {content}"
160            ))
161        })?;
162        let mut reader = Reader::new(&decoded);
163        let count = reader.u8()?;
164        let mut specifiers = Vec::new();
165        for _ in 0..count {
166            specifiers.push(LinkSpecifier::pop(&mut reader)?);
167        }
168        match reader.remaining() {
169            0 => Ok(specifiers),
170            _ => Err(Error::parse(format!(
171                "Introduction point had excessive data ({content})"
172            ))),
173        }
174    }
175
176    pub fn create_for_address(
177        address: &str,
178        port: u16,
179        expiration: Option<NaiveDateTime>,
180    ) -> Result<Self> {
181        if port == 0 {
182            return Err(Error::invalid_input(format!("'{port}' is an invalid port")));
183        }
184        let specifier = if let Ok(parsed) = address.parse::<Ipv4Addr>() {
185            LinkSpecifier::Ipv4 {
186                address: parsed,
187                port,
188            }
189        } else if let Ok(parsed) = address.parse::<Ipv6Addr>() {
190            LinkSpecifier::Ipv6 {
191                address: parsed,
192                port,
193            }
194        } else {
195            return Err(Error::invalid_input(format!(
196                "'{address}' is not a valid IPv4 or IPv6 address"
197            )));
198        };
199        Self::create_for_link_specifiers(vec![specifier], expiration)
200    }
201
202    pub fn create_for_link_specifiers(
203        link_specifiers: Vec<LinkSpecifier>,
204        expiration: Option<NaiveDateTime>,
205    ) -> Result<Self> {
206        let expiration =
207            expiration.unwrap_or_else(|| Utc::now().naive_utc() + Duration::hours(54));
208        let onion_key = standard_base64(
209            PublicKey::from(&StaticSecret::from(rand::random::<[u8; 32]>())).as_bytes(),
210        );
211        let enc_key = standard_base64(
212            PublicKey::from(&StaticSecret::from(rand::random::<[u8; 32]>())).as_bytes(),
213        );
214        let auth_secret = SigningKey::from_bytes(&rand::random());
215        let signing_key = SigningKey::from_bytes(&rand::random());
216        let auth_key = auth_secret.verifying_key().to_bytes();
217        let extensions = vec![Ed25519Extension::signing_key_extension(
218            signing_key.verifying_key().to_bytes(),
219        )];
220        let auth_key_cert = Ed25519Certificate::new(
221            CertType::HsV3IntroAuth,
222            Some(expiration),
223            Some(1),
224            auth_key,
225            extensions.clone(),
226            None,
227            Some(&signing_key),
228        )?;
229        let enc_key_cert = Ed25519Certificate::new(
230            CertType::HsV3NtorEnc,
231            Some(expiration),
232            Some(1),
233            auth_key,
234            extensions,
235            None,
236            Some(&signing_key),
237        )?;
238        Ok(Self {
239            link_specifiers,
240            onion_key_raw: Some(onion_key),
241            auth_key_cert,
242            enc_key_raw: Some(enc_key),
243            enc_key_cert,
244            legacy_key_raw: None,
245            legacy_key_cert: None,
246        })
247    }
248
249    pub fn encode(&self) -> Result<String> {
250        let mut specifiers = vec![self.link_specifiers.len() as u8];
251        self.link_specifiers
252            .iter()
253            .for_each(|link| specifiers.extend_from_slice(&link.pack()));
254        let mut lines = vec![format!(
255            "introduction-point {}",
256            standard_base64(&specifiers)
257        )];
258        lines.push(format!(
259            "onion-key ntor {}",
260            self.onion_key_raw.clone().unwrap_or_default()
261        ));
262        lines.push(format!("auth-key\n{}", self.auth_key_cert.to_base64(true)?));
263        if let Some(key) = &self.enc_key_raw {
264            lines.push(format!("enc-key ntor {key}"));
265        }
266        lines.push(format!(
267            "enc-key-cert\n{}",
268            self.enc_key_cert.to_base64(true)?
269        ));
270        if let Some(key) = &self.legacy_key_raw {
271            lines.push(format!("legacy-key\n{key}"));
272        }
273        if let Some(cert) = &self.legacy_key_cert {
274            lines.push(format!("legacy-key-cert\n{cert}"));
275        }
276        Ok(lines.join("\n"))
277    }
278
279    fn x25519_bytes(value: &Option<String>) -> Result<Option<[u8; 32]>> {
280        value
281            .as_ref()
282            .map(|encoded| {
283                decode_base64(encoded)?
284                    .try_into()
285                    .map_err(|_| Error::parse("x25519 keys are 32 bytes"))
286            })
287            .transpose()
288    }
289
290    pub fn onion_key(&self) -> Result<Option<PublicKey>> {
291        Ok(Self::x25519_bytes(&self.onion_key_raw)?.map(PublicKey::from))
292    }
293
294    pub fn enc_key(&self) -> Result<Option<PublicKey>> {
295        Ok(Self::x25519_bytes(&self.enc_key_raw)?.map(PublicKey::from))
296    }
297
298    pub fn auth_key(&self) -> &[u8; 32] {
299        &self.auth_key_cert.key
300    }
301}
302
303#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
304pub struct AuthorizedClient {
305    pub id: String,
306    pub iv: String,
307    pub cookie: String,
308}
309
310impl AuthorizedClient {
311    pub fn random() -> Self {
312        let encode = |bytes: &[u8]| crate::descriptor::truncated_base64(bytes);
313        Self {
314            id: encode(&rand::random::<[u8; 8]>()),
315            iv: encode(&rand::random::<[u8; 16]>()),
316            cookie: encode(&rand::random::<[u8; 16]>()),
317        }
318    }
319}
320
321fn layer_cipher(
322    constant: &[u8],
323    revision_counter: u64,
324    subcredential: &[u8],
325    secret_data: &[u8],
326    salt: &[u8],
327) -> (Aes256Ctr, Vec<u8>) {
328    let mut hasher = Shake256::default();
329    hasher.update(secret_data);
330    hasher.update(subcredential);
331    hasher.update(&revision_counter.to_be_bytes());
332    hasher.update(salt);
333    hasher.update(constant);
334    let mut keys = [0u8; KEY_LENGTH + IV_LENGTH + MAC_LENGTH];
335    hasher.finalize_xof().read(&mut keys);
336    let cipher = Aes256Ctr::new_from_slices(
337        &keys[..KEY_LENGTH],
338        &keys[KEY_LENGTH..KEY_LENGTH + IV_LENGTH],
339    )
340    .expect("derived key sizes are fixed");
341    let mac_key = &keys[KEY_LENGTH + IV_LENGTH..];
342    let mut mac_prefix = (mac_key.len() as u64).to_be_bytes().to_vec();
343    mac_prefix.extend_from_slice(mac_key);
344    mac_prefix.extend_from_slice(&(salt.len() as u64).to_be_bytes());
345    mac_prefix.extend_from_slice(salt);
346    (cipher, mac_prefix)
347}
348
349fn layer_mac(mac_prefix: &[u8], ciphertext: &[u8]) -> Vec<u8> {
350    let mut hasher = Sha3_256::new();
351    sha3::Digest::update(&mut hasher, mac_prefix);
352    sha3::Digest::update(&mut hasher, ciphertext);
353    sha3::Digest::finalize(hasher).to_vec()
354}
355
356fn decrypt_layer(
357    encrypted_block: &str,
358    constant: &[u8],
359    revision_counter: u64,
360    subcredential: &[u8],
361    secret_data: &[u8],
362) -> Result<Vec<u8>> {
363    let body = match encrypted_block.starts_with(MESSAGE_START)
364        && encrypted_block.ends_with(MESSAGE_END)
365    {
366        true => {
367            &encrypted_block
368                [MESSAGE_START.len()..encrypted_block.len() - MESSAGE_END.len()]
369        }
370        false => encrypted_block,
371    };
372    let encrypted = decode_base64(body)
373        .map_err(|_| Error::parse("Unable to decode encrypted block as base64"))?;
374    if encrypted.len() < SALT_LENGTH + MAC_LENGTH {
375        return Err(Error::parse(format!(
376            "Encrypted block malformed (only {} bytes)",
377            encrypted.len()
378        )));
379    }
380    let salt = &encrypted[..SALT_LENGTH];
381    let ciphertext = &encrypted[SALT_LENGTH..encrypted.len() - MAC_LENGTH];
382    let expected_mac = &encrypted[encrypted.len() - MAC_LENGTH..];
383    let (mut cipher, mac_prefix) =
384        layer_cipher(constant, revision_counter, subcredential, secret_data, salt);
385    let actual_mac = layer_mac(&mac_prefix, ciphertext);
386    if !bool::from(actual_mac.as_slice().ct_eq(expected_mac)) {
387        return Err(Error::parse(format!(
388            "Malformed mac (expected {}, but was {})",
389            hex::encode(expected_mac),
390            hex::encode(&actual_mac)
391        )));
392    }
393    let mut plaintext = ciphertext.to_vec();
394    cipher.apply_keystream(&mut plaintext);
395    Ok(plaintext)
396}
397
398fn encrypt_layer(
399    plaintext: &[u8],
400    constant: &[u8],
401    revision_counter: u64,
402    subcredential: &[u8],
403    secret_data: &[u8],
404) -> String {
405    let salt: [u8; SALT_LENGTH] = rand::random();
406    let padded_length = plaintext.len().div_ceil(PLAINTEXT_PADDING_MULTIPLE).max(1)
407        * PLAINTEXT_PADDING_MULTIPLE;
408    let mut ciphertext = plaintext.to_vec();
409    ciphertext.resize(padded_length, 0);
410    let (mut cipher, mac_prefix) = layer_cipher(
411        constant,
412        revision_counter,
413        subcredential,
414        secret_data,
415        &salt,
416    );
417    cipher.apply_keystream(&mut ciphertext);
418    let mac = layer_mac(&mac_prefix, &ciphertext);
419    let encoded = standard_base64(&[salt.as_slice(), &ciphertext, &mac].concat());
420    format!(
421        "{MESSAGE_START}{}{MESSAGE_END}",
422        split_into_lines(&encoded, 64).join("\n")
423    )
424}
425
426fn trim_padding(mut plaintext: Vec<u8>) -> Vec<u8> {
427    while plaintext.last() == Some(&0) {
428        plaintext.pop();
429    }
430    plaintext
431}
432
433#[derive(Debug, Clone, PartialEq, serde::Serialize)]
434pub struct HiddenServiceDescriptorV2 {
435    #[serde(skip)]
436    pub raw_contents: Vec<u8>,
437    pub unrecognized_lines: Vec<String>,
438    pub descriptor_id: Option<String>,
439    pub version: Option<u32>,
440    pub permanent_key: Option<String>,
441    pub secret_id_part: Option<String>,
442    pub published: Option<NaiveDateTime>,
443    pub protocol_versions: Vec<u32>,
444    pub introduction_points_encoded: Option<String>,
445    #[serde(serialize_with = "crate::descriptor::serialize_optional_text")]
446    pub introduction_points_content: Option<Vec<u8>>,
447    pub signature: Option<String>,
448}
449
450impl HiddenServiceDescriptorV2 {
451    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
452        Self::parse_with_options(content, validate, false)
453    }
454
455    pub fn parse_with_options(
456        content: &[u8],
457        validate: bool,
458        skip_crypto_validation: bool,
459    ) -> Result<Self> {
460        let (entries, _) =
461            descriptor_components(content, validate, &[], &["introduction-points"])?;
462        if validate {
463            for keyword in REQUIRED_V2_FIELDS {
464                match entries.get(keyword) {
465                    None => {
466                        return Err(Error::parse(format!(
467                            "Hidden service descriptor must have a '{keyword}' entry"
468                        )));
469                    }
470                    Some(values) if values.len() > 1 => {
471                        return Err(Error::parse(format!(
472                            "The '{keyword}' entry can only appear once in a hidden \
473                            service descriptor"
474                        )));
475                    }
476                    Some(_) => {}
477                }
478            }
479            if entries.first_key() != Some("rendezvous-service-descriptor") {
480                return Err(Error::parse(
481                    "Hidden service descriptor must start with a \
482                    'rendezvous-service-descriptor' entry",
483                ));
484            }
485            if entries.last_key() != Some("signature") {
486                return Err(Error::parse(
487                    "Hidden service descriptor must end with a 'signature' entry",
488                ));
489            }
490        }
491        let mut descriptor = Self {
492            raw_contents: content.to_vec(),
493            unrecognized_lines: entries.unrecognized_lines(&REQUIRED_V2_FIELDS_PLUS),
494            descriptor_id: entries
495                .value("rendezvous-service-descriptor")
496                .ok()
497                .map(str::to_string),
498            version: None,
499            permanent_key: None,
500            secret_id_part: entries.value("secret-id-part").ok().map(str::to_string),
501            published: None,
502            protocol_versions: Vec::new(),
503            introduction_points_encoded: None,
504            introduction_points_content: None,
505            signature: None,
506        };
507        if let Ok(value) = entries.value("version") {
508            descriptor.version = lenient_option(
509                validate,
510                parse_integer("version", value, false).map(|v| v as u32),
511            )?;
512        }
513        if entries.contains("permanent-key") {
514            descriptor.permanent_key = lenient_option(
515                validate,
516                key_block(&entries, "permanent-key", "RSA PUBLIC KEY")
517                    .map(|(_, block)| block),
518            )?;
519        }
520        if let Ok(value) = entries.value("publication-time") {
521            descriptor.published = lenient_option(
522                validate,
523                parse_timestamp_line("publication-time", value),
524            )?;
525        }
526        if let Ok(value) = entries.value("protocol-versions") {
527            let parsed: Result<Vec<u32>> = value
528                .split(',')
529                .map(|entry| match entry.parse::<u32>() {
530                    Ok(version) if version > 0 => Ok(version),
531                    Ok(_) => Err(Error::parse(format!(
532                        "protocol-versions must be \
533                        positive integers: {value}"
534                    ))),
535                    Err(_) => Err(Error::parse(format!(
536                        "protocol-versions line has non-numeric versoins: \
537                        protocol-versions {value}"
538                    ))),
539                })
540                .collect();
541            descriptor.protocol_versions = lenient(validate, parsed)?;
542        }
543        if entries.contains("introduction-points") {
544            let parsed = key_block(&entries, "introduction-points", "MESSAGE").and_then(
545                |(_, block)| bytes_for_block(&block).map(|bytes| (block, bytes)),
546            );
547            if let Some((block, bytes)) = lenient_option(validate, parsed)? {
548                descriptor.introduction_points_encoded = Some(block);
549                descriptor.introduction_points_content = Some(bytes);
550            }
551        }
552        if entries.contains("signature") {
553            descriptor.signature = lenient_option(
554                validate,
555                key_block(&entries, "signature", "SIGNATURE").map(|(_, block)| block),
556            )?;
557        }
558        if validate && !skip_crypto_validation {
559            descriptor.validate_signature()?;
560        }
561        Ok(descriptor)
562    }
563
564    fn validate_signature(&self) -> Result<()> {
565        let (Some(key), Some(signature)) = (&self.permanent_key, &self.signature) else {
566            return Ok(());
567        };
568        let signed = digest_for_signature(key, signature)?;
569        let digest_content = content_range(
570            &self.raw_contents,
571            Some("rendezvous-service-descriptor "),
572            Some("\nsignature\n"),
573        )?;
574        let local = Sha1::digest(digest_content).to_vec();
575        match signed == local {
576            true => Ok(()),
577            false => Err(Error::parse(format!(
578                "Decrypted digest does not match local digest (calculated: {}, local: \
579                {})",
580                hex::encode_upper(signed),
581                hex::encode_upper(local)
582            ))),
583        }
584    }
585
586    pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
587        let mut cursor = LineCursor::new(content);
588        let mut descriptors = Vec::new();
589        loop {
590            let mut body = cursor
591                .read_until_keywords(
592                    &["signature"],
593                    ReadOptions {
594                        inclusive: true,
595                        ..Default::default()
596                    },
597                )
598                .content;
599            body.extend(
600                cursor
601                    .read_until_keywords(
602                        &["-----END"],
603                        ReadOptions {
604                            inclusive: true,
605                            ..Default::default()
606                        },
607                    )
608                    .content,
609            );
610            if body.is_empty() {
611                break;
612            }
613            if body.starts_with(b"@type") {
614                body = body
615                    .splitn(2, |byte| *byte == b'\n')
616                    .nth(1)
617                    .unwrap_or_default()
618                    .to_vec();
619            }
620            descriptors.push(Self::parse(&body, validate)?);
621        }
622        Ok(descriptors)
623    }
624
625    pub fn introduction_points(
626        &self,
627        authentication_cookie: Option<&str>,
628    ) -> Result<Vec<IntroductionPoints>> {
629        let Some(content) = self
630            .introduction_points_content
631            .as_ref()
632            .filter(|content| !content.is_empty())
633        else {
634            return Ok(Vec::new());
635        };
636        let decrypted = match authentication_cookie {
637            Some(cookie) => {
638                let cookie = decode_base64(cookie).map_err(|error| {
639                    DecryptionFailure(format!(
640                        "authentication_cookie must be a base64 encoded string ({error})"
641                    ))
642                })?;
643                let plaintext = match content.first().copied() {
644                    Some(BASIC_AUTH) => Self::decrypt_basic_auth(content, &cookie)?,
645                    Some(STEALTH_AUTH) => Self::decrypt_stealth_auth(content, &cookie)?,
646                    other => {
647                        return Err(DecryptionFailure(format!(
648                            "Unrecognized authentication type '{}', currently we only \
649                            support basic auth ({BASIC_AUTH}) and stealth auth \
650                            ({STEALTH_AUTH})",
651                            other.unwrap_or(0)
652                        ))
653                        .into());
654                    }
655                };
656                if !plaintext.starts_with(b"introduction-point ") {
657                    return Err(DecryptionFailure(
658                        "Unable to decrypt the introduction-points, maybe this is the \
659                        wrong key?"
660                            .to_string(),
661                    )
662                    .into());
663                }
664                plaintext
665            }
666            None if content.starts_with(b"introduction-point ") => content.clone(),
667            None => {
668                return Err(DecryptionFailure(
669                    "introduction-points content is encrypted, you need to provide its \
670                    authentication_cookie"
671                        .to_string(),
672                )
673                .into());
674            }
675        };
676        Self::parse_introduction_points(&decrypted)
677    }
678
679    fn decrypt_basic_auth(content: &[u8], cookie: &[u8]) -> Result<Vec<u8>> {
680        let blocks = usize::from(*content.get(1).ok_or_else(|| {
681            DecryptionFailure("Basic auth content is truncated".to_string())
682        })?);
683        let entries_length = blocks * 16 * 20;
684        let entries = content.get(2..2 + entries_length).ok_or_else(|| {
685            DecryptionFailure("Basic auth content is truncated".to_string())
686        })?;
687        let iv = content
688            .get(2 + entries_length..2 + entries_length + 16)
689            .ok_or_else(|| {
690                DecryptionFailure("Basic auth content is truncated".to_string())
691            })?;
692        let encrypted = &content[2 + entries_length + 16..];
693        let mut hasher = Sha1::new();
694        sha1::Digest::update(&mut hasher, cookie);
695        sha1::Digest::update(&mut hasher, iv);
696        let client_id = sha1::Digest::finalize(hasher);
697        for entry in entries.as_chunks::<20>().0 {
698            if entry[..4] != client_id[..4] {
699                continue;
700            }
701            let mut session_key = entry[4..20].to_vec();
702            let mut key_cipher =
703                Aes128Ctr::new_from_slices(cookie, &[0u8; 16]).map_err(|_| {
704                    DecryptionFailure(
705                        "The authentication cookie must be 16 bytes".to_string(),
706                    )
707                })?;
708            key_cipher.apply_keystream(&mut session_key);
709            let mut decrypted = encrypted.to_vec();
710            let mut cipher = Aes128Ctr::new_from_slices(&session_key, iv)
711                .map_err(|_| DecryptionFailure("Invalid session key".to_string()))?;
712            cipher.apply_keystream(&mut decrypted);
713            if decrypted.starts_with(b"introduction-point ") {
714                return Ok(decrypted);
715            }
716        }
717        Ok(content.to_vec())
718    }
719
720    fn decrypt_stealth_auth(content: &[u8], cookie: &[u8]) -> Result<Vec<u8>> {
721        let (iv, encrypted) = (
722            content.get(1..17).ok_or_else(|| {
723                DecryptionFailure("Stealth auth content is truncated".to_string())
724            })?,
725            &content[17..],
726        );
727        let mut decrypted = encrypted.to_vec();
728        let mut cipher = Aes128Ctr::new_from_slices(cookie, iv).map_err(|_| {
729            DecryptionFailure("The authentication cookie must be 16 bytes".to_string())
730        })?;
731        cipher.apply_keystream(&mut decrypted);
732        Ok(decrypted)
733    }
734
735    fn parse_introduction_points(content: &[u8]) -> Result<Vec<IntroductionPoints>> {
736        let mut cursor = LineCursor::new(content);
737        let mut points = Vec::new();
738        loop {
739            let block = cursor
740                .read_until_keywords(
741                    &["introduction-point"],
742                    ReadOptions {
743                        ignore_first: true,
744                        ..Default::default()
745                    },
746                )
747                .content;
748            if block.is_empty() {
749                break;
750            }
751            let (entries, _) = descriptor_components(&block, false, &[], &[])?;
752            let mut point = IntroductionPoints {
753                identifier: None,
754                address: None,
755                port: None,
756                onion_key: None,
757                service_key: None,
758                intro_authentication: Vec::new(),
759            };
760            for (keyword, values) in entries.iter() {
761                if SINGLE_INTRODUCTION_POINT_FIELDS.contains(&keyword.as_str())
762                    && values.len() > 1
763                {
764                    return Err(Error::parse(format!(
765                        "'{keyword}' can only appear once in an introduction-point \
766                        block, but appeared {} times",
767                        values.len()
768                    )));
769                }
770                let first = &values[0];
771                match keyword.as_str() {
772                    "introduction-point" => point.identifier = Some(first.value.clone()),
773                    "ip-address" => {
774                        if !is_valid_ipv4_address(&first.value) {
775                            return Err(Error::parse(format!(
776                                "'{}' is an invalid IPv4 address",
777                                first.value
778                            )));
779                        }
780                        point.address = Some(first.value.clone());
781                    }
782                    "onion-port" => {
783                        point.port =
784                            Some(parse_port(&first.value, false).ok_or_else(|| {
785                                Error::parse(format!(
786                                    "'{}' is an invalid port",
787                                    first.value
788                                ))
789                            })?);
790                    }
791                    "onion-key" => point.onion_key = first.block_contents.clone(),
792                    "service-key" => point.service_key = first.block_contents.clone(),
793                    "intro-authentication" => {
794                        for entry in values {
795                            let parts: Vec<&str> = entry.value.split(' ').collect();
796                            if parts.len() < 2 {
797                                return Err(Error::parse(format!(
798                                    "We expected 'intro-authentication [auth_type] \
799                                    [auth_data]', but had '{}'",
800                                    entry.value
801                                )));
802                            }
803                            point
804                                .intro_authentication
805                                .push((parts[0].to_string(), parts[1].to_string()));
806                        }
807                    }
808                    _ => {}
809                }
810            }
811            points.push(point);
812        }
813        Ok(points)
814    }
815
816    pub fn content(attributes: &Attributes, exclude: &[&str]) -> Vec<u8> {
817        descriptor_content(
818            attributes,
819            exclude,
820            &[
821                (
822                    "rendezvous-service-descriptor",
823                    AttrValue::Text("y3olqqblqw2gbh6phimfuiroechjjafa".to_string()),
824                ),
825                ("version", AttrValue::Text("2".to_string())),
826                (
827                    "permanent-key",
828                    AttrValue::Text(random_crypto_blob(Some("RSA PUBLIC KEY"))),
829                ),
830                (
831                    "secret-id-part",
832                    AttrValue::Text("e24kgecavwsznj7gpbktqsiwgvngsf4e".to_string()),
833                ),
834                ("publication-time", AttrValue::Text(random_date())),
835                ("protocol-versions", AttrValue::Text("2,3".to_string())),
836                (
837                    "introduction-points",
838                    AttrValue::Text(
839                        "\n-----BEGIN MESSAGE-----\n-----END MESSAGE-----".to_string(),
840                    ),
841                ),
842            ],
843            &[(
844                "signature",
845                AttrValue::Text(random_crypto_blob(Some("SIGNATURE"))),
846            )],
847        )
848    }
849
850    pub fn create(
851        attributes: &Attributes,
852        exclude: &[&str],
853        validate: bool,
854    ) -> Result<Self> {
855        Self::parse_with_options(&Self::content(attributes, exclude), validate, true)
856    }
857}
858
859const REQUIRED_V2_FIELDS_PLUS: [&str; 8] = [
860    "rendezvous-service-descriptor",
861    "version",
862    "permanent-key",
863    "secret-id-part",
864    "publication-time",
865    "protocol-versions",
866    "introduction-points",
867    "signature",
868];
869
870#[derive(Debug, Clone, PartialEq, serde::Serialize)]
871pub struct HiddenServiceDescriptorV3 {
872    #[serde(skip)]
873    pub raw_contents: Vec<u8>,
874    pub unrecognized_lines: Vec<String>,
875    pub version: Option<u32>,
876    pub lifetime: Option<u32>,
877    pub signing_cert: Option<Ed25519Certificate>,
878    pub revision_counter: Option<u64>,
879    pub superencrypted: Option<String>,
880    pub signature: Option<String>,
881}
882
883#[derive(Debug, Clone, PartialEq, serde::Serialize)]
884pub struct OuterLayer {
885    #[serde(skip)]
886    pub raw_contents: Vec<u8>,
887    pub auth_type: Option<String>,
888    pub ephemeral_key: Option<String>,
889    pub clients: indexmap::IndexMap<String, AuthorizedClient>,
890    pub encrypted: Option<String>,
891}
892
893#[derive(Debug, Clone, PartialEq, serde::Serialize)]
894pub struct InnerLayer {
895    #[serde(skip)]
896    pub raw_contents: Vec<u8>,
897    pub formats: Vec<u32>,
898    pub intro_auth: Vec<String>,
899    pub is_single_service: bool,
900    pub introduction_points: Vec<IntroductionPointV3>,
901}
902
903pub fn address_from_identity_key(key: &[u8; 32], suffix: bool) -> String {
904    let mut hasher = Sha3_256::new();
905    sha3::Digest::update(&mut hasher, CHECKSUM_CONSTANT);
906    sha3::Digest::update(&mut hasher, key);
907    sha3::Digest::update(&mut hasher, [3u8]);
908    let checksum = sha3::Digest::finalize(hasher);
909    let mut payload = key.to_vec();
910    payload.extend_from_slice(&checksum[..2]);
911    payload.push(3);
912    let address = BASE32_NOPAD.encode(&payload).to_lowercase();
913    match suffix {
914        true => format!("{address}.onion"),
915        false => address,
916    }
917}
918
919pub fn identity_key_from_address(onion_address: &str) -> Result<[u8; 32]> {
920    let address = onion_address
921        .strip_suffix(".onion")
922        .unwrap_or(onion_address);
923    if !is_valid_hidden_service_address(address, &[3]) {
924        return Err(Error::invalid_input(format!(
925            "'{address}.onion' isn't a valid hidden service v3 address"
926        )));
927    }
928    let decoded = BASE32_NOPAD
929        .decode(address.to_uppercase().as_bytes())
930        .map_err(|error| Error::invalid_input(error.to_string()))?;
931    let (public_key, tail) = decoded.split_at(32);
932    let mut hasher = Sha3_256::new();
933    sha3::Digest::update(&mut hasher, CHECKSUM_CONSTANT);
934    sha3::Digest::update(&mut hasher, public_key);
935    sha3::Digest::update(&mut hasher, &tail[2..3]);
936    let checksum = sha3::Digest::finalize(hasher);
937    if tail[..2] != checksum[..2] {
938        return Err(Error::invalid_input(format!(
939            "Bad checksum (expected {} but was {})",
940            hex::encode(&tail[..2]),
941            hex::encode(&checksum[..2])
942        )));
943    }
944    Ok(public_key.try_into().expect("32 bytes"))
945}
946
947pub fn subcredential(identity_key: &[u8], blinded_key: &[u8]) -> Vec<u8> {
948    let mut credential = Sha3_256::new();
949    sha3::Digest::update(&mut credential, b"credential");
950    sha3::Digest::update(&mut credential, identity_key);
951    let credential = sha3::Digest::finalize(credential);
952    let mut hasher = Sha3_256::new();
953    sha3::Digest::update(&mut hasher, b"subcredential");
954    sha3::Digest::update(&mut hasher, credential);
955    sha3::Digest::update(&mut hasher, blinded_key);
956    sha3::Digest::finalize(hasher).to_vec()
957}
958
959pub struct LayerSecrets<'a> {
960    pub subcredential: &'a [u8],
961    pub blinded_key: &'a [u8],
962    pub descriptor_cookie: &'a [u8],
963}
964
965impl OuterLayer {
966    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
967        let trimmed = trim_padding(content.to_vec());
968        let (entries, _) = descriptor_components(&trimmed, validate, &[], &[])?;
969        let mut layer = Self {
970            raw_contents: trimmed,
971            auth_type: entries.value("desc-auth-type").ok().map(str::to_string),
972            ephemeral_key: entries
973                .value("desc-auth-ephemeral-key")
974                .ok()
975                .map(str::to_string),
976            clients: indexmap::IndexMap::new(),
977            encrypted: None,
978        };
979        if entries.contains("auth-client") {
980            let parsed: Result<Vec<AuthorizedClient>> = entries
981                .values("auth-client")
982                .into_iter()
983                .map(|value| {
984                    let parts: Vec<&str> = value.split_whitespace().collect();
985                    match parts.as_slice() {
986                        [id, iv, cookie, ..] => Ok(AuthorizedClient {
987                            id: id.to_string(),
988                            iv: iv.to_string(),
989                            cookie: cookie.to_string(),
990                        }),
991                        _ => Err(Error::parse(format!(
992                            "auth-client should have a client-id, iv, and cookie: \
993                            auth-client {value}"
994                        ))),
995                    }
996                })
997                .collect();
998            layer.clients = lenient(validate, parsed)?
999                .into_iter()
1000                .map(|client| (client.id.clone(), client))
1001                .collect();
1002        }
1003        if entries.contains("encrypted") {
1004            layer.encrypted = lenient_option(
1005                validate,
1006                key_block(&entries, "encrypted", "MESSAGE").map(|(_, block)| block),
1007            )?;
1008        }
1009        Ok(layer)
1010    }
1011
1012    fn decrypt(
1013        encrypted: &str,
1014        revision_counter: u64,
1015        subcredential: &[u8],
1016        blinded_key: &[u8],
1017    ) -> Result<Self> {
1018        let plaintext = decrypt_layer(
1019            encrypted,
1020            b"hsdir-superencrypted-data",
1021            revision_counter,
1022            subcredential,
1023            blinded_key,
1024        )?;
1025        Self::parse(&plaintext, false)
1026    }
1027
1028    pub fn descriptor_cookie_for_client(
1029        &self,
1030        subcredential: &[u8],
1031        client_private_key: &[u8; 32],
1032    ) -> Result<Vec<u8>> {
1033        let ephemeral = self.ephemeral_key.as_ref().ok_or_else(|| {
1034            Error::parse("The outer layer has no desc-auth-ephemeral-key")
1035        })?;
1036        let ephemeral: [u8; 32] = decode_base64(ephemeral)?.try_into().map_err(|_| {
1037            Error::parse("desc-auth-ephemeral-key must be an x25519 public key")
1038        })?;
1039        let secret = StaticSecret::from(*client_private_key);
1040        let shared = secret.diffie_hellman(&PublicKey::from(ephemeral));
1041        let mut hasher = Shake256::default();
1042        hasher.update(subcredential);
1043        hasher.update(shared.as_bytes());
1044        let mut keys = [0u8; 40];
1045        hasher.finalize_xof().read(&mut keys);
1046        let client_id = crate::descriptor::truncated_base64(&keys[..8]);
1047        let client = self.clients.get(&client_id).ok_or_else(|| {
1048            DecryptionFailure(
1049                "None of the auth-client entries are for this client key".to_string(),
1050            )
1051        })?;
1052        let iv = decode_base64(&client.iv)?;
1053        let mut cookie = decode_base64(&client.cookie)?;
1054        let mut cipher = Aes256Ctr::new_from_slices(&keys[8..], &iv)
1055            .map_err(|_| Error::parse("auth-client has a malformed iv"))?;
1056        cipher.apply_keystream(&mut cookie);
1057        Ok(cookie)
1058    }
1059
1060    pub fn content(
1061        attributes: &Attributes,
1062        exclude: &[&str],
1063        inner_layer: &InnerLayer,
1064        revision_counter: u64,
1065        authorized_clients: Option<&[AuthorizedClient]>,
1066        secrets: &LayerSecrets,
1067    ) -> Result<Vec<u8>> {
1068        if authorized_clients.is_some()
1069            && attributes.iter().any(|(key, _)| key == "auth-client")
1070        {
1071            return Err(Error::invalid_input(
1072                "Authorized clients cannot be specified through both attr and \
1073                authorized_clients",
1074            ));
1075        }
1076        let generated: Vec<AuthorizedClient> = match authorized_clients {
1077            Some(clients) => clients.to_vec(),
1078            None if attributes.iter().any(|(key, _)| key == "auth-client") => Vec::new(),
1079            None => (0..16).map(|_| AuthorizedClient::random()).collect(),
1080        };
1081        let ephemeral = PublicKey::from(&StaticSecret::from(rand::random::<[u8; 32]>()));
1082        let mut header: Vec<(String, AttrValue)> = vec![
1083            attr("desc-auth-type", "x25519"),
1084            attr(
1085                "desc-auth-ephemeral-key",
1086                &standard_base64(ephemeral.as_bytes()),
1087            ),
1088        ];
1089        for client in &generated {
1090            header.push(attr(
1091                "auth-client",
1092                &format!("{} {} {}", client.id, client.iv, client.cookie),
1093            ));
1094        }
1095        let borrowed: Vec<(&str, AttrValue)> = header
1096            .iter()
1097            .map(|(key, value)| (key.as_str(), value.clone()))
1098            .collect();
1099        let secret_data = [secrets.blinded_key, secrets.descriptor_cookie].concat();
1100        let encrypted =
1101            inner_layer.encrypt(revision_counter, secrets.subcredential, &secret_data);
1102        Ok(descriptor_content(
1103            attributes,
1104            exclude,
1105            &borrowed,
1106            &[("encrypted", AttrValue::Text(format!("\n{encrypted}")))],
1107        ))
1108    }
1109}
1110
1111impl InnerLayer {
1112    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
1113        let trimmed = trim_padding(content.to_vec());
1114        let split = trimmed
1115            .windows(b"\nintroduction-point ".len())
1116            .position(|window| window == b"\nintroduction-point ");
1117        let (head, unparsed_points) = match split {
1118            Some(position) => (&trimmed[..position], Some(&trimmed[position + 1..])),
1119            None => (trimmed.as_slice(), None),
1120        };
1121        let (entries, _) = descriptor_components(head, validate, &[], &[])?;
1122        let mut layer = Self {
1123            raw_contents: trimmed.clone(),
1124            formats: Vec::new(),
1125            intro_auth: Vec::new(),
1126            is_single_service: entries.contains("single-onion-service"),
1127            introduction_points: Vec::new(),
1128        };
1129        if let Ok(value) = entries.value("create2-formats") {
1130            let parsed: Result<Vec<u32>> = value
1131                .split(' ')
1132                .map(|entry| {
1133                    entry
1134                        .parse::<u32>()
1135                        .ok()
1136                        .filter(|_| entry.bytes().all(|b| b.is_ascii_digit()))
1137                        .ok_or_else(|| {
1138                            Error::parse(format!(
1139                                "create2-formats should only contain \
1140                            integers, but was '{value}'"
1141                            ))
1142                        })
1143                })
1144                .collect();
1145            layer.formats = lenient(validate, parsed)?;
1146        }
1147        if let Ok(value) = entries.value("intro-auth-required") {
1148            layer.intro_auth = value.split(' ').map(str::to_string).collect();
1149        }
1150        if let Some(mut remaining) = unparsed_points {
1151            let mut points = Vec::new();
1152            while !remaining.is_empty() {
1153                let search = &remaining[10.min(remaining.len())..];
1154                let next = search
1155                    .windows(b"\nintroduction-point ".len())
1156                    .position(|window| window == b"\nintroduction-point ")
1157                    .map(|position| position + 10.min(remaining.len()));
1158                let (chunk, rest) = match next {
1159                    Some(position) => {
1160                        (&remaining[..position], &remaining[position + 1..])
1161                    }
1162                    None => (remaining, &remaining[remaining.len()..]),
1163                };
1164                points.push(IntroductionPointV3::parse(chunk));
1165                remaining = rest;
1166            }
1167            layer.introduction_points =
1168                match points.into_iter().collect::<Result<Vec<_>>>() {
1169                    Ok(points) => points,
1170                    Err(error) if validate => return Err(error),
1171                    Err(_) => Vec::new(),
1172                };
1173        }
1174        Ok(layer)
1175    }
1176
1177    fn decrypt(
1178        outer: &OuterLayer,
1179        revision_counter: u64,
1180        subcredential: &[u8],
1181        blinded_key: &[u8],
1182        descriptor_cookie: &[u8],
1183    ) -> Result<Self> {
1184        let encrypted = outer
1185            .encrypted
1186            .as_ref()
1187            .ok_or_else(|| Error::parse("The outer layer has no encrypted block"))?;
1188        let secret_data = [blinded_key, descriptor_cookie].concat();
1189        let plaintext = decrypt_layer(
1190            encrypted,
1191            b"hsdir-encrypted-data",
1192            revision_counter,
1193            subcredential,
1194            &secret_data,
1195        )?;
1196        Self::parse(&plaintext, true)
1197    }
1198
1199    fn encrypt(
1200        &self,
1201        revision_counter: u64,
1202        subcredential: &[u8],
1203        secret_data: &[u8],
1204    ) -> String {
1205        encrypt_layer(
1206            &self.raw_contents,
1207            b"hsdir-encrypted-data",
1208            revision_counter,
1209            subcredential,
1210            secret_data,
1211        )
1212    }
1213
1214    pub fn content(
1215        attributes: &Attributes,
1216        exclude: &[&str],
1217        introduction_points: &[IntroductionPointV3],
1218    ) -> Result<Vec<u8>> {
1219        let mut content = descriptor_content(
1220            attributes,
1221            exclude,
1222            &[("create2-formats", AttrValue::Text("2".to_string()))],
1223            &[],
1224        );
1225        content.push(b'\n');
1226        if !introduction_points.is_empty() {
1227            let encoded: Result<Vec<String>> = introduction_points
1228                .iter()
1229                .map(IntroductionPointV3::encode)
1230                .collect();
1231            content.extend_from_slice(encoded?.join("\n").as_bytes());
1232            content.push(b'\n');
1233        }
1234        Ok(content)
1235    }
1236
1237    pub fn create(
1238        attributes: &Attributes,
1239        exclude: &[&str],
1240        validate: bool,
1241        introduction_points: &[IntroductionPointV3],
1242    ) -> Result<Self> {
1243        Self::parse(
1244            &Self::content(attributes, exclude, introduction_points)?,
1245            validate,
1246        )
1247    }
1248}
1249
1250pub fn blinded_public_key(
1251    identity_key: &[u8; 32],
1252    blinding_nonce: &[u8; 32],
1253) -> Result<[u8; 32]> {
1254    let point = CompressedEdwardsY(*identity_key)
1255        .decompress()
1256        .ok_or_else(|| {
1257            Error::invalid_input("The identity key isn't a valid ed25519 point")
1258        })?;
1259    Ok(point.mul_clamped(*blinding_nonce).compress().to_bytes())
1260}
1261
1262pub fn time_period_number(time: DateTime<Utc>, period_length: u64) -> Result<u64> {
1263    if period_length == 0 {
1264        return Err(Error::invalid_input(
1265            "Time periods can't be zero minutes long",
1266        ));
1267    }
1268    let minutes = (time.timestamp() / 60 - PERIOD_ROTATION_MINUTES).max(0);
1269    Ok(minutes.unsigned_abs() / period_length)
1270}
1271
1272pub fn blinding_nonce(
1273    identity_key: &[u8; 32],
1274    period_number: u64,
1275    period_length: u64,
1276) -> [u8; 32] {
1277    let mut hasher = Sha3_256::new();
1278    sha3::Digest::update(&mut hasher, BLIND_STRING);
1279    sha3::Digest::update(&mut hasher, identity_key);
1280    sha3::Digest::update(&mut hasher, BASEPOINT_STRING);
1281    sha3::Digest::update(&mut hasher, b"key-blind");
1282    sha3::Digest::update(&mut hasher, period_number.to_be_bytes());
1283    sha3::Digest::update(&mut hasher, period_length.to_be_bytes());
1284    sha3::Digest::finalize(hasher).into()
1285}
1286
1287pub fn blinded_key_for_period(
1288    identity_key: &[u8; 32],
1289    period_number: u64,
1290    period_length: u64,
1291) -> Result<[u8; 32]> {
1292    let nonce = blinding_nonce(identity_key, period_number, period_length);
1293    blinded_public_key(identity_key, &nonce)
1294}
1295
1296fn clamp(bytes: [u8; 32]) -> [u8; 32] {
1297    let mut clamped = bytes;
1298    clamped[0] &= 248;
1299    clamped[31] &= 127;
1300    clamped[31] |= 64;
1301    clamped
1302}
1303
1304pub fn blinded_sign(
1305    message: &[u8],
1306    identity_key: &SigningKey,
1307    blinded_key: &[u8; 32],
1308    blinding_nonce: &[u8; 32],
1309) -> Vec<u8> {
1310    let hashed = Sha512::digest(identity_key.to_bytes());
1311    let secret =
1312        Scalar::from_bytes_mod_order(clamp(hashed[..32].try_into().expect("32 bytes")));
1313    let multiplier = Scalar::from_bytes_mod_order(clamp(*blinding_nonce));
1314    let blinded_secret = secret * multiplier;
1315    let mut derive = b"Derive temporary signing key hash input".to_vec();
1316    derive.extend_from_slice(&hashed[32..]);
1317    let blinded_prefix = Sha512::digest(&derive);
1318    let mut prefixed = blinded_prefix[..32].to_vec();
1319    prefixed.extend_from_slice(message);
1320    let random = Scalar::from_bytes_mod_order_wide(&Sha512::digest(&prefixed).into());
1321    let commitment: EdwardsPoint = ED25519_BASEPOINT_POINT * random;
1322    let commitment_bytes = commitment.compress().to_bytes();
1323    let mut challenge_input = commitment_bytes.to_vec();
1324    challenge_input.extend_from_slice(blinded_key);
1325    challenge_input.extend_from_slice(message);
1326    let challenge =
1327        Scalar::from_bytes_mod_order_wide(&Sha512::digest(&challenge_input).into());
1328    let response = random + challenge * blinded_secret;
1329    [commitment_bytes.as_slice(), response.as_bytes().as_slice()].concat()
1330}
1331
1332#[derive(Default)]
1333pub struct HiddenServiceV3Options {
1334    pub inner_layer: Option<InnerLayer>,
1335    pub identity_key: Option<SigningKey>,
1336    pub signing_key: Option<SigningKey>,
1337    pub signing_cert: Option<Ed25519Certificate>,
1338    pub revision_counter: Option<u64>,
1339    pub blinding_nonce: Option<[u8; 32]>,
1340    pub authorized_clients: Option<Vec<AuthorizedClient>>,
1341    pub descriptor_cookie: Option<Vec<u8>>,
1342}
1343
1344impl HiddenServiceDescriptorV3 {
1345    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
1346        let (entries, _) = descriptor_components(content, validate, &[], &[])?;
1347        if validate {
1348            for keyword in REQUIRED_V3_FIELDS {
1349                match entries.get(keyword) {
1350                    None => {
1351                        return Err(Error::parse(format!(
1352                            "Hidden service descriptor must have a '{keyword}' entry"
1353                        )));
1354                    }
1355                    Some(values) if values.len() > 1 => {
1356                        return Err(Error::parse(format!(
1357                            "The '{keyword}' entry can only appear once in a hidden \
1358                            service descriptor"
1359                        )));
1360                    }
1361                    Some(_) => {}
1362                }
1363            }
1364            if entries.first_key() != Some("hs-descriptor") {
1365                return Err(Error::parse(
1366                    "Hidden service descriptor must start with a 'hs-descriptor' entry",
1367                ));
1368            }
1369            if entries.last_key() != Some("signature") {
1370                return Err(Error::parse(
1371                    "Hidden service descriptor must end with a 'signature' entry",
1372                ));
1373            }
1374        }
1375        let mut descriptor = Self {
1376            raw_contents: content.to_vec(),
1377            unrecognized_lines: entries.unrecognized_lines(&REQUIRED_V3_FIELDS),
1378            version: None,
1379            lifetime: None,
1380            signing_cert: None,
1381            revision_counter: None,
1382            superencrypted: None,
1383            signature: entries.value("signature").ok().map(str::to_string),
1384        };
1385        for (keyword, target) in [
1386            ("hs-descriptor", &mut descriptor.version),
1387            ("descriptor-lifetime", &mut descriptor.lifetime),
1388        ] {
1389            if let Ok(value) = entries.value(keyword) {
1390                *target = lenient_option(
1391                    validate,
1392                    parse_integer(keyword, value, false).map(|number| number as u32),
1393                )?;
1394            }
1395        }
1396        if entries.contains("descriptor-signing-key-cert") {
1397            descriptor.signing_cert = lenient_option(
1398                validate,
1399                certificate_block(&entries, "descriptor-signing-key-cert"),
1400            )?;
1401        }
1402        if let Ok(value) = entries.value("revision-counter") {
1403            descriptor.revision_counter = lenient_option(
1404                validate,
1405                parse_integer("revision-counter", value, false)
1406                    .map(|number| number as u64),
1407            )?;
1408        }
1409        if entries.contains("superencrypted") {
1410            descriptor.superencrypted = lenient_option(
1411                validate,
1412                key_block(&entries, "superencrypted", "MESSAGE").map(|(_, block)| block),
1413            )?;
1414        }
1415        if validate && let Some(certificate) = descriptor.signing_cert.clone() {
1416            descriptor.validate_signature(&certificate)?;
1417        }
1418        Ok(descriptor)
1419    }
1420
1421    fn validate_signature(&self, certificate: &Ed25519Certificate) -> Result<()> {
1422        let signed = content_range(&self.raw_contents, None, Some("signature "))?;
1423        let signed_without_marker = &signed[..signed.len() - "signature ".len()];
1424        let message = [SIG_PREFIX_HS_V3, signed_without_marker].concat();
1425        let signature = decode_base64(self.signature.as_deref().ok_or_else(|| {
1426            Error::parse("Malformed descriptor missing signature line")
1427        })?)?;
1428        certificate.verify_signature(&message, &signature)
1429    }
1430
1431    pub fn verify_signing_certificate(&self) -> Result<()> {
1432        let certificate = self
1433            .signing_cert
1434            .as_ref()
1435            .ok_or_else(|| Error::parse("No signing certificate is present"))?;
1436        let blinded_key = certificate
1437            .signing_key()
1438            .ok_or_else(|| Error::parse("No signing key is present"))?;
1439        certificate.verify_certificate_signature(blinded_key)
1440    }
1441
1442    pub fn verify_blinded_key(
1443        &self,
1444        onion_address: &str,
1445        time: DateTime<Utc>,
1446        period_length: u64,
1447    ) -> Result<()> {
1448        let blinded_key = self
1449            .signing_cert
1450            .as_ref()
1451            .and_then(Ed25519Certificate::signing_key)
1452            .ok_or_else(|| Error::parse("No signing key is present"))?;
1453        let identity_key = identity_key_from_address(onion_address)?;
1454        let current = time_period_number(time, period_length)?;
1455        for period_number in [current.saturating_sub(1), current, current + 1] {
1456            let expected =
1457                blinded_key_for_period(&identity_key, period_number, period_length)?;
1458            if expected.as_slice() == blinded_key {
1459                return Ok(());
1460            }
1461        }
1462        Err(Error::parse(
1463            "The blinded key doesn't belong to the address' current time period",
1464        ))
1465    }
1466
1467    pub fn decrypt(&self, onion_address: &str) -> Result<InnerLayer> {
1468        self.decrypt_with_cookie_source(onion_address, None)
1469    }
1470
1471    pub fn decrypt_with_client_auth(
1472        &self,
1473        onion_address: &str,
1474        client_private_key: &[u8; 32],
1475    ) -> Result<InnerLayer> {
1476        self.decrypt_with_cookie_source(onion_address, Some(client_private_key))
1477    }
1478
1479    fn decrypt_with_cookie_source(
1480        &self,
1481        onion_address: &str,
1482        client_key: Option<&[u8; 32]>,
1483    ) -> Result<InnerLayer> {
1484        let blinded_key = self
1485            .signing_cert
1486            .as_ref()
1487            .and_then(Ed25519Certificate::signing_key)
1488            .ok_or_else(|| Error::invalid_input("No signing key is present"))?;
1489        let identity_public_key = identity_key_from_address(onion_address)?;
1490        let credential = subcredential(&identity_public_key, blinded_key);
1491        let revision_counter = self
1492            .revision_counter
1493            .ok_or_else(|| Error::parse("Descriptor lacks a revision-counter"))?;
1494        let superencrypted = self
1495            .superencrypted
1496            .as_ref()
1497            .ok_or_else(|| Error::parse("Descriptor lacks a superencrypted block"))?;
1498        let outer = OuterLayer::decrypt(
1499            superencrypted,
1500            revision_counter,
1501            &credential,
1502            blinded_key,
1503        )?;
1504        let cookie = match client_key {
1505            Some(key) => outer.descriptor_cookie_for_client(&credential, key)?,
1506            None => Vec::new(),
1507        };
1508        InnerLayer::decrypt(&outer, revision_counter, &credential, blinded_key, &cookie)
1509    }
1510
1511    pub fn content(
1512        attributes: &Attributes,
1513        exclude: &[&str],
1514        options: HiddenServiceV3Options,
1515    ) -> Result<Vec<u8>> {
1516        let nonce = options.blinding_nonce;
1517        let inner_layer = match options.inner_layer {
1518            Some(layer) => layer,
1519            None => InnerLayer::create(&Vec::new(), exclude, true, &[])?,
1520        };
1521        let identity_key = options
1522            .identity_key
1523            .unwrap_or_else(|| SigningKey::from_bytes(&rand::random()));
1524        let signing_key = options
1525            .signing_key
1526            .unwrap_or_else(|| SigningKey::from_bytes(&rand::random()));
1527        let revision_counter = options
1528            .revision_counter
1529            .unwrap_or_else(|| Utc::now().timestamp() as u64);
1530        let identity_public = identity_key.verifying_key().to_bytes();
1531        let blinded_key = match &nonce {
1532            Some(nonce) => blinded_public_key(&identity_public, nonce)?,
1533            None => [b'a'; 32],
1534        };
1535        let credential = subcredential(&identity_public, &blinded_key);
1536        let mut attributes = attributes.clone();
1537        let custom_signature = attributes
1538            .iter()
1539            .position(|(key, _)| key == "signature")
1540            .map(|index| attributes.remove(index).1);
1541        let cookie = options.descriptor_cookie.unwrap_or_default();
1542        let outer_content = OuterLayer::content(
1543            &attributes,
1544            exclude,
1545            &inner_layer,
1546            revision_counter,
1547            options.authorized_clients.as_deref(),
1548            &LayerSecrets {
1549                subcredential: &credential,
1550                blinded_key: &blinded_key,
1551                descriptor_cookie: &cookie,
1552            },
1553        );
1554        let outer_content =
1555            match attributes.iter().any(|(key, _)| key == "superencrypted") {
1556                true => Vec::new(),
1557                false => outer_content?,
1558            };
1559        let signing_cert = match options.signing_cert {
1560            Some(cert) => cert,
1561            None => {
1562                let extensions =
1563                    vec![Ed25519Extension::signing_key_extension(blinded_key)];
1564                let mut cert = Ed25519Certificate::new(
1565                    CertType::HsV3DescSigning,
1566                    None,
1567                    None,
1568                    signing_key.verifying_key().to_bytes(),
1569                    extensions,
1570                    None,
1571                    None,
1572                )?;
1573                cert.signature = Some(match &nonce {
1574                    Some(nonce) => {
1575                        blinded_sign(&cert.pack()?, &identity_key, &blinded_key, nonce)
1576                    }
1577                    None => vec![b'b'; 64],
1578                });
1579                cert
1580            }
1581        };
1582        let superencrypted = encrypt_layer(
1583            &outer_content,
1584            b"hsdir-superencrypted-data",
1585            revision_counter,
1586            &credential,
1587            &blinded_key,
1588        );
1589        let mut content = descriptor_content(
1590            &attributes,
1591            exclude,
1592            &[
1593                ("hs-descriptor", AttrValue::Text("3".to_string())),
1594                ("descriptor-lifetime", AttrValue::Text("180".to_string())),
1595                (
1596                    "descriptor-signing-key-cert",
1597                    AttrValue::Text(format!("\n{}", signing_cert.to_base64(true)?)),
1598                ),
1599                (
1600                    "revision-counter",
1601                    AttrValue::Text(revision_counter.to_string()),
1602                ),
1603                (
1604                    "superencrypted",
1605                    AttrValue::Text(format!("\n{superencrypted}")),
1606                ),
1607            ],
1608            &[],
1609        );
1610        content.push(b'\n');
1611        match custom_signature {
1612            Some(AttrValue::Text(text)) => {
1613                content.extend_from_slice(format!("signature {text}").as_bytes())
1614            }
1615            Some(_) => {}
1616            None if exclude.contains(&"signature") => {}
1617            None => {
1618                let message = [SIG_PREFIX_HS_V3, &content].concat();
1619                let signature = signing_key.sign(&message).to_bytes();
1620                content.extend_from_slice(
1621                    format!(
1622                        "signature {}",
1623                        crate::descriptor::truncated_base64(&signature)
1624                    )
1625                    .as_bytes(),
1626                );
1627            }
1628        }
1629        Ok(content)
1630    }
1631
1632    pub fn create(
1633        attributes: &Attributes,
1634        exclude: &[&str],
1635        validate: bool,
1636        options: HiddenServiceV3Options,
1637    ) -> Result<Self> {
1638        Self::parse(&Self::content(attributes, exclude, options)?, validate)
1639    }
1640
1641    pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
1642        let mut cursor = LineCursor::new(content);
1643        let mut descriptors = Vec::new();
1644        loop {
1645            let mut body = cursor
1646                .read_until_keywords(
1647                    &["signature"],
1648                    ReadOptions {
1649                        inclusive: true,
1650                        ..Default::default()
1651                    },
1652                )
1653                .content;
1654            if body.is_empty() {
1655                break;
1656            }
1657            if body.starts_with(b"@type") {
1658                body = body
1659                    .splitn(2, |byte| *byte == b'\n')
1660                    .nth(1)
1661                    .unwrap_or_default()
1662                    .to_vec();
1663            }
1664            descriptors.push(Self::parse(&body, validate)?);
1665        }
1666        Ok(descriptors)
1667    }
1668}
1669
1670#[derive(Debug, Clone, PartialEq, serde::Serialize)]
1671#[serde(untagged)]
1672pub enum HiddenServiceDescriptor {
1673    V2(Box<HiddenServiceDescriptorV2>),
1674    V3(Box<HiddenServiceDescriptorV3>),
1675}
1676
1677impl HiddenServiceDescriptor {
1678    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
1679        let trimmed = content.trim_ascii_start();
1680        match trimmed.starts_with(b"hs-descriptor ") {
1681            true => Ok(Self::V3(Box::new(HiddenServiceDescriptorV3::parse(
1682                content, validate,
1683            )?))),
1684            false => Ok(Self::V2(Box::new(HiddenServiceDescriptorV2::parse(
1685                content, validate,
1686            )?))),
1687        }
1688    }
1689
1690    pub fn raw_contents(&self) -> &[u8] {
1691        match self {
1692            Self::V2(descriptor) => &descriptor.raw_contents,
1693            Self::V3(descriptor) => &descriptor.raw_contents,
1694        }
1695    }
1696}