Skip to main content

stem/descriptor/
server.rs

1use std::collections::BTreeSet;
2use std::ops::Deref;
3
4use chrono::NaiveDateTime;
5use rsa::traits::PublicKeyParts;
6use rsa::{BigUint, RsaPrivateKey, RsaPublicKey};
7use sha1::{Digest, Sha1};
8
9use crate::address::{is_valid_ipv4_address, is_valid_ipv6_address, parse_port};
10use crate::descriptor::certificate::{Ed25519Certificate, SIG_PREFIX_SERVER_DESC};
11use crate::descriptor::router_status::RouterStatusEntryV3;
12use crate::descriptor::{
13    AttrValue, Attributes, DigestEncoding, DigestHash, Entries, History, LineCursor,
14    Protocols, ReadOptions, attr, bytes_for_block, content_range, decode_base64,
15    descriptor_components, descriptor_content, encode_digest, hash_bytes, key_block,
16    lenient, lenient_option, parse_bytes_line, parse_forty_hex, parse_history,
17    parse_integer, parse_protocol_line, parse_timestamp_line, random_crypto_blob,
18    random_date, random_ipv4_address, random_nickname, truncated_base64,
19};
20use crate::error::{Error, Result};
21use crate::exit_policy::{ExitPolicy, MicroExitPolicy};
22use crate::validation::{is_hex_digits, is_valid_fingerprint, is_valid_nickname};
23use crate::version::Version;
24
25const REQUIRED_FIELDS: [&str; 6] = [
26    "router",
27    "bandwidth",
28    "published",
29    "onion-key",
30    "signing-key",
31    "router-signature",
32];
33
34const SINGLE_FIELDS: [&str; 23] = [
35    "identity-ed25519",
36    "master-key-ed25519",
37    "platform",
38    "fingerprint",
39    "hibernating",
40    "uptime",
41    "contact",
42    "read-history",
43    "write-history",
44    "eventdns",
45    "bridge-distribution-request",
46    "family",
47    "caches-extra-info",
48    "extra-info-digest",
49    "hidden-service-dir",
50    "protocols",
51    "allow-single-hop-exits",
52    "tunnelled-dir-server",
53    "proto",
54    "onion-key-crosscert",
55    "ntor-onion-key",
56    "ntor-onion-key-crosscert",
57    "router-sig-ed25519",
58];
59
60const COMMON_KEYWORDS: [&str; 23] = [
61    "router",
62    "bandwidth",
63    "platform",
64    "published",
65    "fingerprint",
66    "contact",
67    "hibernating",
68    "extra-info-digest",
69    "hidden-service-dir",
70    "uptime",
71    "protocols",
72    "ntor-onion-key",
73    "or-address",
74    "read-history",
75    "write-history",
76    "ipv6-policy",
77    "allow-single-hop-exits",
78    "tunnelled-dir-server",
79    "proto",
80    "caches-extra-info",
81    "bridge-distribution-request",
82    "family",
83    "eventdns",
84];
85
86const RELAY_KEYWORDS: [&str; 8] = [
87    "identity-ed25519",
88    "master-key-ed25519",
89    "router-sig-ed25519",
90    "onion-key",
91    "onion-key-crosscert",
92    "ntor-onion-key-crosscert",
93    "signing-key",
94    "router-signature",
95];
96
97const BRIDGE_KEYWORDS: [&str; 3] = [
98    "master-key-ed25519",
99    "router-digest-sha256",
100    "router-digest",
101];
102
103#[derive(Debug, Clone, PartialEq, serde::Serialize)]
104pub struct ServerDescriptor {
105    #[serde(skip)]
106    pub raw_contents: Vec<u8>,
107    pub unrecognized_lines: Vec<String>,
108    pub annotation_lines: Vec<String>,
109    pub nickname: Option<String>,
110    pub fingerprint: Option<String>,
111    #[serde(serialize_with = "crate::descriptor::serialize_optional_text")]
112    pub contact: Option<Vec<u8>>,
113    pub published: Option<NaiveDateTime>,
114    pub exit_policy: ExitPolicy,
115    pub address: Option<String>,
116    pub or_port: Option<u16>,
117    pub socks_port: Option<u16>,
118    pub dir_port: Option<u16>,
119    #[serde(serialize_with = "crate::descriptor::serialize_optional_text")]
120    pub platform: Option<Vec<u8>>,
121    pub tor_version: Option<Version>,
122    pub operating_system: Option<String>,
123    pub uptime: Option<i64>,
124    pub exit_policy_v6: MicroExitPolicy,
125    pub bridge_distribution: String,
126    pub family: BTreeSet<String>,
127    pub average_bandwidth: Option<u64>,
128    pub burst_bandwidth: Option<u64>,
129    pub observed_bandwidth: Option<u64>,
130    pub link_protocols: Option<Vec<String>>,
131    pub circuit_protocols: Option<Vec<String>>,
132    pub is_hidden_service_dir: bool,
133    pub hibernating: bool,
134    pub allow_single_hop_exits: bool,
135    pub allow_tunneled_dir_requests: bool,
136    pub protocols: Protocols,
137    pub extra_info_cache: bool,
138    pub extra_info_digest: Option<String>,
139    pub extra_info_sha256_digest: Option<String>,
140    pub eventdns: Option<bool>,
141    pub ntor_onion_key: Option<String>,
142    pub or_addresses: Vec<(String, u16, bool)>,
143    pub read_history: Option<History>,
144    pub write_history: Option<History>,
145    pub hidden_service_dir: Vec<String>,
146}
147
148#[derive(Debug, Clone, PartialEq, serde::Serialize)]
149pub struct RelayServerDescriptor {
150    #[serde(flatten)]
151    pub common: ServerDescriptor,
152    pub certificate: Option<Ed25519Certificate>,
153    pub ed25519_certificate: Option<String>,
154    pub ed25519_master_key: Option<String>,
155    pub ed25519_signature: Option<String>,
156    pub onion_key: Option<String>,
157    pub onion_key_crosscert: Option<String>,
158    pub ntor_onion_key_crosscert: Option<String>,
159    pub ntor_onion_key_crosscert_sign: Option<String>,
160    pub signing_key: Option<String>,
161    pub signature: Option<String>,
162}
163
164#[derive(Debug, Clone, PartialEq, serde::Serialize)]
165pub struct BridgeServerDescriptor {
166    #[serde(flatten)]
167    pub common: ServerDescriptor,
168    pub ed25519_certificate_hash: Option<String>,
169    pub router_digest_sha256: Option<String>,
170    digest: Option<String>,
171}
172
173impl Deref for RelayServerDescriptor {
174    type Target = ServerDescriptor;
175
176    fn deref(&self) -> &ServerDescriptor {
177        &self.common
178    }
179}
180
181impl Deref for BridgeServerDescriptor {
182    type Target = ServerDescriptor;
183
184    fn deref(&self) -> &ServerDescriptor {
185        &self.common
186    }
187}
188
189struct RouterLine {
190    nickname: String,
191    address: String,
192    or_port: u16,
193    socks_port: Option<u16>,
194    dir_port: Option<u16>,
195}
196
197fn parse_router_line(entries: &Entries) -> Result<RouterLine> {
198    let value = entries.value("router")?;
199    let parts: Vec<&str> = value.split_whitespace().collect();
200    if parts.len() < 5 {
201        return Err(Error::parse(format!(
202            "Router line must have five values: router {value}"
203        )));
204    }
205    if !is_valid_nickname(parts[0]) {
206        return Err(Error::parse(format!(
207            "Router line entry isn't a valid nickname: {}",
208            parts[0]
209        )));
210    }
211    if !is_valid_ipv4_address(parts[1]) {
212        return Err(Error::parse(format!(
213            "Router line entry isn't a valid IPv4 address: {}",
214            parts[1]
215        )));
216    }
217    let port = |index: usize, label: &str| {
218        parse_port(parts[index], true).ok_or_else(|| {
219            Error::parse(format!(
220                "Router line's {label} is invalid: {}",
221                parts[index]
222            ))
223        })
224    };
225    let (or_port, socks_port, dir_port) = (
226        port(2, "ORPort")?,
227        port(3, "SocksPort")?,
228        port(4, "DirPort")?,
229    );
230    Ok(RouterLine {
231        nickname: parts[0].to_string(),
232        address: parts[1].to_string(),
233        or_port,
234        socks_port: Some(socks_port).filter(|port| *port != 0),
235        dir_port: Some(dir_port).filter(|port| *port != 0),
236    })
237}
238
239fn parse_bandwidth_line(entries: &Entries) -> Result<(u64, u64, u64)> {
240    let value = entries.value("bandwidth")?;
241    let parts: Vec<&str> = value.split_whitespace().collect();
242    if parts.len() < 3 {
243        return Err(Error::parse(format!(
244            "Bandwidth line must have three values: bandwidth {value}"
245        )));
246    }
247    let number = |index: usize, label: &str| -> Result<u64> {
248        let text = parts[index];
249        match !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()) {
250            true => text.parse().map_err(|_| {
251                Error::parse(format!("Bandwidth line's {label} isn't numeric: {text}"))
252            }),
253            false => Err(Error::parse(format!(
254                "Bandwidth line's {label} isn't numeric: {text}"
255            ))),
256        }
257    };
258    Ok((
259        number(0, "average rate")?,
260        number(1, "burst rate")?,
261        number(2, "observed rate")?,
262    ))
263}
264
265fn parse_platform(value: &str) -> Option<(String, String)> {
266    let rest = value
267        .strip_prefix("node-")
268        .unwrap_or(value)
269        .strip_prefix("Tor ")?;
270    let version_end = rest.find(char::is_whitespace).unwrap_or(rest.len());
271    let version = &rest[..version_end];
272    let after = &rest[version_end..];
273    let split = after.rfind(" on ")?;
274    Some((version.to_string(), after[split + 4..].to_string()))
275}
276
277fn parse_fingerprint_line(value: &str) -> Result<String> {
278    if value.split(' ').any(|group| group.len() != 4) {
279        return Err(Error::parse(format!(
280            "Fingerprint line should have groupings of four hex digits: {value}"
281        )));
282    }
283    let fingerprint = value.replace(' ', "");
284    match is_valid_fingerprint(&fingerprint, false) {
285        true => Ok(fingerprint),
286        false => Err(Error::parse(format!(
287            "Tor relay fingerprints consist of forty hex digits: {value}"
288        ))),
289    }
290}
291
292fn parse_extra_info_digest(value: &str) -> Result<(String, Option<String>)> {
293    let parts: Vec<&str> = value.split(' ').collect();
294    match is_hex_digits(parts[0], 40) {
295        true => Ok((
296            parts[0].to_string(),
297            parts.get(1).map(|digest| digest.to_string()),
298        )),
299        false => Err(Error::parse(format!(
300            "extra-info-digest should be 40 hex characters: {}",
301            parts[0]
302        ))),
303    }
304}
305
306fn parse_protocols_line(value: &str) -> Result<(Vec<String>, Vec<String>)> {
307    let invalid = || {
308        Error::parse(format!(
309            "Protocols line did not match the expected pattern: protocols {value}"
310        ))
311    };
312    let rest = value.strip_prefix("Link ").ok_or_else(invalid)?;
313    let split = rest.find(" Circuit ").ok_or_else(invalid)?;
314    let link = rest[..split].split(' ').map(str::to_string).collect();
315    let circuit = rest[split + 9..].split(' ').map(str::to_string).collect();
316    Ok((link, circuit))
317}
318
319fn parse_or_addresses(entries: &Entries) -> Result<Vec<(String, u16, bool)>> {
320    let mut addresses = Vec::new();
321    for entry in entries.values("or-address") {
322        let Some((address, port)) = entry.rsplit_once(':') else {
323            return Err(Error::parse(format!(
324                "or-address line missing a colon: or-address {entry}"
325            )));
326        };
327        let is_ipv6 = is_valid_ipv6_address(address, true);
328        if !is_valid_ipv4_address(address) && !is_ipv6 {
329            return Err(Error::parse(format!(
330                "or-address line has a malformed address: or-address {entry}"
331            )));
332        }
333        let Some(port) = parse_port(port, false) else {
334            return Err(Error::parse(format!(
335                "or-address line has a malformed port: or-address {entry}"
336            )));
337        };
338        addresses.push((
339            address
340                .trim_start_matches('[')
341                .trim_end_matches(']')
342                .to_string(),
343            port,
344            is_ipv6,
345        ));
346    }
347    Ok(addresses)
348}
349
350fn required_fields(is_bridge: bool) -> Vec<&'static str> {
351    match is_bridge {
352        false => REQUIRED_FIELDS.to_vec(),
353        true => {
354            let mut fields = vec!["router-digest"];
355            fields.extend(REQUIRED_FIELDS.iter().filter(|field| {
356                !matches!(**field, "onion-key" | "signing-key" | "router-signature")
357            }));
358            fields
359        }
360    }
361}
362
363fn check_constraints(
364    entries: &Entries,
365    is_bridge: bool,
366    has_exit_policy: bool,
367    has_ed25519: bool,
368) -> Result<()> {
369    let required = required_fields(is_bridge);
370    for keyword in &required {
371        if !entries.contains(keyword) {
372            return Err(Error::parse(format!(
373                "Descriptor must have a '{keyword}' entry"
374            )));
375        }
376    }
377    for keyword in required.iter().chain(SINGLE_FIELDS.iter()) {
378        if entries.get(keyword).is_some_and(|values| values.len() > 1) {
379            return Err(Error::parse(format!(
380                "The '{keyword}' entry can only appear once in a descriptor"
381            )));
382        }
383    }
384    if entries.first_key() != Some("router") {
385        return Err(Error::parse("Descriptor must start with a 'router' entry"));
386    }
387    if !is_bridge && entries.last_key() != Some("router-signature") {
388        return Err(Error::parse(
389            "Descriptor must end with a 'router-signature' entry",
390        ));
391    }
392    if has_ed25519 {
393        if !entries.contains("router-sig-ed25519") {
394            return Err(Error::parse(
395                "Descriptor must have router-sig-ed25519 entry to accompany \
396                identity-ed25519",
397            ));
398        }
399        let keys: Vec<&String> = entries.keys().collect();
400        let tail = &keys[keys.len().saturating_sub(2)..];
401        if !tail.iter().any(|key| key.as_str() == "router-sig-ed25519") {
402            return Err(Error::parse(
403                "Descriptor must have 'router-sig-ed25519' as the next-to-last entry",
404            ));
405        }
406    }
407    match has_exit_policy {
408        true => Ok(()),
409        false => Err(Error::parse(
410            "Descriptor must have at least one 'accept' or 'reject' entry",
411        )),
412    }
413}
414
415fn parse_common(
416    content: &[u8],
417    entries: &Entries,
418    policy_lines: &[String],
419    annotation_lines: Vec<String>,
420    validate: bool,
421    is_bridge: bool,
422) -> Result<ServerDescriptor> {
423    let mut common = ServerDescriptor {
424        raw_contents: content.to_vec(),
425        unrecognized_lines: Vec::new(),
426        annotation_lines,
427        nickname: None,
428        fingerprint: None,
429        contact: None,
430        published: None,
431        exit_policy: ExitPolicy::new::<&str>(&[])?,
432        address: None,
433        or_port: None,
434        socks_port: None,
435        dir_port: None,
436        platform: None,
437        tor_version: None,
438        operating_system: None,
439        uptime: None,
440        exit_policy_v6: MicroExitPolicy::new("reject 1-65535")?,
441        bridge_distribution: "any".to_string(),
442        family: BTreeSet::new(),
443        average_bandwidth: None,
444        burst_bandwidth: None,
445        observed_bandwidth: None,
446        link_protocols: None,
447        circuit_protocols: None,
448        is_hidden_service_dir: false,
449        hibernating: false,
450        allow_single_hop_exits: false,
451        allow_tunneled_dir_requests: false,
452        protocols: Protocols::new(),
453        extra_info_cache: false,
454        extra_info_digest: None,
455        extra_info_sha256_digest: None,
456        eventdns: None,
457        ntor_onion_key: None,
458        or_addresses: Vec::new(),
459        read_history: None,
460        write_history: None,
461        hidden_service_dir: vec!["2".to_string()],
462    };
463    let mut recognized: Vec<&str> = COMMON_KEYWORDS.to_vec();
464    recognized.extend(match is_bridge {
465        true => BRIDGE_KEYWORDS.as_slice(),
466        false => RELAY_KEYWORDS.as_slice(),
467    });
468    common.unrecognized_lines = entries.unrecognized_lines(&recognized);
469    if entries.contains("router")
470        && let Some(line) = lenient_option(validate, parse_router_line(entries))?
471    {
472        common.nickname = Some(line.nickname);
473        common.address = Some(line.address);
474        common.or_port = Some(line.or_port);
475        common.socks_port = line.socks_port;
476        common.dir_port = line.dir_port;
477    }
478    if entries.contains("bandwidth")
479        && let Some((average, burst, observed)) =
480            lenient_option(validate, parse_bandwidth_line(entries))?
481    {
482        common.average_bandwidth = Some(average);
483        common.burst_bandwidth = Some(burst);
484        common.observed_bandwidth = Some(observed);
485    }
486    common.platform = parse_bytes_line(content, "platform");
487    if let Ok(value) = entries.value("platform")
488        && let Some((version, operating_system)) = parse_platform(value)
489    {
490        common.tor_version = Version::new(&version).ok();
491        common.operating_system = Some(operating_system);
492    }
493    if let Ok(value) = entries.value("published") {
494        common.published =
495            lenient_option(validate, parse_timestamp_line("published", value))?;
496    }
497    if let Ok(value) = entries.value("fingerprint") {
498        common.fingerprint = lenient_option(validate, parse_fingerprint_line(value))?;
499    }
500    common.contact = parse_bytes_line(content, "contact");
501    if let Ok(value) = entries.value("hibernating") {
502        match value {
503            "0" | "1" => common.hibernating = value == "1",
504            _ => {
505                lenient::<()>(
506                    validate,
507                    Err(Error::parse(format!(
508                        "Hibernating line had an invalid value, must be zero or one: \
509                        {value}"
510                    ))),
511                )?;
512            }
513        }
514    }
515    if let Ok(value) = entries.value("extra-info-digest")
516        && let Some((digest, sha256)) =
517            lenient_option(validate, parse_extra_info_digest(value))?
518    {
519        common.extra_info_digest = Some(digest);
520        common.extra_info_sha256_digest = sha256;
521    }
522    common.is_hidden_service_dir = entries.contains("hidden-service-dir");
523    if let Ok(value) = entries.value("uptime") {
524        common.uptime = lenient_option(validate, parse_integer("uptime", value, true))?;
525    }
526    if let Ok(value) = entries.value("protocols")
527        && let Some((link, circuit)) =
528            lenient_option(validate, parse_protocols_line(value))?
529    {
530        common.link_protocols = Some(link);
531        common.circuit_protocols = Some(circuit);
532    }
533    if let Ok(value) = entries.value("ntor-onion-key") {
534        common.ntor_onion_key = Some(value.to_string());
535    }
536    if entries.contains("or-address") {
537        common.or_addresses = lenient(validate, parse_or_addresses(entries))?;
538    }
539    for (keyword, target) in [
540        ("read-history", &mut common.read_history),
541        ("write-history", &mut common.write_history),
542    ] {
543        if let Ok(value) = entries.value(keyword) {
544            *target = lenient_option(validate, parse_history(keyword, value))?;
545        }
546    }
547    if let Ok(value) = entries.value("ipv6-policy")
548        && let Some(policy) = lenient_option(validate, MicroExitPolicy::new(value))?
549    {
550        common.exit_policy_v6 = policy;
551    }
552    common.allow_single_hop_exits = entries.contains("allow-single-hop-exits");
553    common.allow_tunneled_dir_requests = entries.contains("tunnelled-dir-server");
554    if let Ok(value) = entries.value("proto") {
555        common.protocols = lenient(validate, parse_protocol_line("proto", value))?;
556    }
557    common.extra_info_cache = entries.contains("caches-extra-info");
558    if let Ok(value) = entries.value("bridge-distribution-request") {
559        common.bridge_distribution = value.to_string();
560    }
561    if let Ok(value) = entries.value("family") {
562        common.family = value.split(' ').map(str::to_string).collect();
563    }
564    if let Ok(value) = entries.value("eventdns") {
565        common.eventdns = Some(value == "1");
566    }
567    common.exit_policy = match policy_lines.first().map(String::as_str) {
568        Some("reject *:*") => ExitPolicy::new(&["reject *:*"])?,
569        _ => match ExitPolicy::new(policy_lines) {
570            Ok(policy) => policy,
571            Err(error) if validate => return Err(error),
572            Err(_) => ExitPolicy::from_rules(
573                policy_lines
574                    .iter()
575                    .filter_map(|line| {
576                        crate::exit_policy::ExitPolicyRule::new(line.trim()).ok()
577                    })
578                    .collect(),
579                true,
580            ),
581        },
582    };
583    if validate
584        && let (Some(uptime), Some(version)) = (common.uptime, &common.tor_version)
585        && uptime < 0
586        && *version >= Version::new("0.1.2.7")?
587    {
588        return Err(Error::parse(format!(
589            "Descriptor for version '{version}' had a negative uptime value: {uptime}"
590        )));
591    }
592    Ok(common)
593}
594
595pub fn parse_annotations(raw: &[u8]) -> Vec<String> {
596    raw.split(|byte| *byte == b'\n')
597        .map(|line| String::from_utf8_lossy(line.trim_ascii()).into_owned())
598        .filter(|line| !line.is_empty())
599        .collect()
600}
601
602pub fn annotation_map(lines: &[String]) -> indexmap::IndexMap<String, Option<String>> {
603    lines
604        .iter()
605        .map(|line| match line.split_once(' ') {
606            Some((key, value)) => (key.to_string(), Some(value.to_string())),
607            None => (line.clone(), None),
608        })
609        .collect()
610}
611
612fn rsa_public_key(block: &str) -> Result<RsaPublicKey> {
613    use rsa::pkcs1::DecodeRsaPublicKey;
614    let der = bytes_for_block(block)?;
615    RsaPublicKey::from_pkcs1_der(&der)
616        .map_err(|error| Error::parse(format!("Invalid RSA public key: {error}")))
617}
618
619pub fn digest_for_signature(
620    signing_key_block: &str,
621    signature_block: &str,
622) -> Result<Vec<u8>> {
623    let key = rsa_public_key(signing_key_block)?;
624    if key.n().bits() > 4096 {
625        return Err(Error::parse(
626            "RSA keys larger than 4096 bits aren't supported",
627        ));
628    }
629    let signature = bytes_for_block(signature_block)?;
630    let modulus_length = key.size();
631    if signature.len() != modulus_length {
632        return Err(Error::parse("Verification failed, malformed data"));
633    }
634    let decrypted = BigUint::from_bytes_be(&signature).modpow(key.e(), key.n());
635    let mut block = decrypted.to_bytes_be();
636    if block.len() > modulus_length {
637        return Err(Error::parse("Verification failed, malformed data"));
638    }
639    block.splice(0..0, vec![0u8; modulus_length - block.len()]);
640    if block[..2] != [0x00, 0x01] {
641        return Err(Error::parse("Verification failed, identifier missing"));
642    }
643    let separator = block[2..]
644        .iter()
645        .position(|byte| *byte != 0xff)
646        .map(|offset| offset + 2)
647        .ok_or_else(|| Error::parse("Verification failed, seperator not found"))?;
648    if block[separator] != 0x00 || separator < 10 {
649        return Err(Error::parse("Verification failed, seperator not found"));
650    }
651    Ok(block[separator + 1..].to_vec())
652}
653
654impl RelayServerDescriptor {
655    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
656        Self::parse_with_options(content, validate, Vec::new(), false)
657    }
658
659    pub fn parse_with_options(
660        content: &[u8],
661        validate: bool,
662        annotations: Vec<String>,
663        skip_crypto_validation: bool,
664    ) -> Result<Self> {
665        let (entries, policy_lines) = descriptor_components(
666            content,
667            validate,
668            &["accept", "reject"],
669            &["contact", "platform"],
670        )?;
671        let common = parse_common(
672            content,
673            &entries,
674            &policy_lines,
675            annotations,
676            validate,
677            false,
678        )?;
679        if validate {
680            check_constraints(
681                &entries,
682                false,
683                !common.exit_policy.is_empty(),
684                entries.contains("identity-ed25519"),
685            )?;
686        }
687        let mut descriptor = Self {
688            common,
689            certificate: None,
690            ed25519_certificate: None,
691            ed25519_master_key: None,
692            ed25519_signature: None,
693            onion_key: None,
694            onion_key_crosscert: None,
695            ntor_onion_key_crosscert: None,
696            ntor_onion_key_crosscert_sign: None,
697            signing_key: None,
698            signature: None,
699        };
700        if entries.contains("identity-ed25519")
701            && let Some((_, block)) = lenient_option(
702                validate,
703                key_block(&entries, "identity-ed25519", "ED25519 CERT"),
704            )?
705        {
706            descriptor.certificate =
707                lenient_option(validate, Ed25519Certificate::from_base64(&block))?;
708            descriptor.ed25519_certificate = Some(block);
709        }
710        if let Ok(value) = entries.value("master-key-ed25519") {
711            descriptor.ed25519_master_key = Some(value.to_string());
712        }
713        if let Ok(value) = entries.value("router-sig-ed25519") {
714            descriptor.ed25519_signature = Some(value.to_string());
715        }
716        for (keyword, kind, target) in [
717            ("onion-key", "RSA PUBLIC KEY", &mut descriptor.onion_key),
718            (
719                "onion-key-crosscert",
720                "CROSSCERT",
721                &mut descriptor.onion_key_crosscert,
722            ),
723            ("signing-key", "RSA PUBLIC KEY", &mut descriptor.signing_key),
724            ("router-signature", "SIGNATURE", &mut descriptor.signature),
725        ] {
726            if entries.contains(keyword) {
727                *target = lenient_option(
728                    validate,
729                    key_block(&entries, keyword, kind).map(|(_, block)| block),
730                )?;
731            }
732        }
733        if entries.contains("ntor-onion-key-crosscert")
734            && let Some((sign, block)) = lenient_option(
735                validate,
736                key_block(&entries, "ntor-onion-key-crosscert", "ED25519 CERT"),
737            )?
738        {
739            descriptor.ntor_onion_key_crosscert = Some(block);
740            descriptor.ntor_onion_key_crosscert_sign = Some(sign);
741        }
742        if validate {
743            descriptor.check_relay_constraints()?;
744            descriptor.validate_signatures(skip_crypto_validation)?;
745        }
746        Ok(descriptor)
747    }
748
749    fn check_relay_constraints(&self) -> Result<()> {
750        if self.ed25519_certificate.is_some() {
751            if self.onion_key_crosscert.is_none() {
752                return Err(Error::parse(
753                    "Descriptor must have a 'onion-key-crosscert' when identity-ed25519 \
754                    is present",
755                ));
756            }
757            if self.ed25519_signature.is_none() {
758                return Err(Error::parse(
759                    "Descriptor must have a 'router-sig-ed25519' when identity-ed25519 \
760                    is present",
761                ));
762            }
763        }
764        Ok(())
765    }
766
767    fn validate_signatures(&self, skip_crypto_validation: bool) -> Result<()> {
768        if let (Some(fingerprint), Some(signing_key)) =
769            (&self.common.fingerprint, &self.signing_key)
770        {
771            let key_hash = hex::encode(Sha1::digest(bytes_for_block(signing_key)?));
772            if key_hash != fingerprint.to_lowercase() {
773                return Err(Error::parse(format!(
774                    "Fingerprint does not match the hash of our signing key \
775                    (fingerprint: {}, signing key hash: {key_hash})",
776                    fingerprint.to_lowercase()
777                )));
778            }
779        }
780        if !skip_crypto_validation {
781            self.validate_rsa_signatures()?;
782        }
783        if let Some(certificate) = &self.certificate {
784            self.validate_ed25519(certificate)?;
785        }
786        Ok(())
787    }
788
789    fn validate_rsa_signatures(&self) -> Result<()> {
790        let (Some(signing_key), Some(signature)) = (&self.signing_key, &self.signature)
791        else {
792            return Ok(());
793        };
794        let signed = digest_for_signature(signing_key, signature)?;
795        let local = self.digest_bytes(DigestHash::Sha1)?;
796        if signed != local {
797            return Err(Error::parse(format!(
798                "Decrypted digest does not match local digest (calculated: {}, local: \
799                {})",
800                hex::encode_upper(&signed),
801                hex::encode_upper(&local)
802            )));
803        }
804        if let (Some(crosscert), Some(onion_key)) =
805            (&self.onion_key_crosscert, &self.onion_key)
806        {
807            let crosscert_digest = digest_for_signature(onion_key, crosscert)?;
808            let expected = self.onion_key_crosscert_digest()?;
809            if crosscert_digest != expected {
810                return Err(Error::parse(format!(
811                    "Decrypted onion-key-crosscert digest does not match local digest \
812                    (calculated: {}, local: {})",
813                    hex::encode_upper(&crosscert_digest),
814                    hex::encode_upper(&expected)
815                )));
816            }
817        }
818        Ok(())
819    }
820
821    fn onion_key_crosscert_digest(&self) -> Result<Vec<u8>> {
822        let signing_key = self
823            .signing_key
824            .as_ref()
825            .ok_or_else(|| Error::parse("Descriptor lacks a signing-key"))?;
826        let master = self
827            .ed25519_master_key
828            .as_ref()
829            .ok_or_else(|| Error::parse("Descriptor lacks a master-key-ed25519"))?;
830        let mut data = Sha1::digest(bytes_for_block(signing_key)?).to_vec();
831        data.extend(decode_base64(master)?);
832        Ok(data)
833    }
834
835    fn validate_ed25519(&self, certificate: &Ed25519Certificate) -> Result<()> {
836        let prefix_end = "router-sig-ed25519 ";
837        let signed = content_range(&self.common.raw_contents, None, Some(prefix_end))?;
838        let signed_content =
839            sha2::Sha256::digest([SIG_PREFIX_SERVER_DESC, &signed].concat());
840        let signature = decode_base64(
841            self.ed25519_signature
842                .as_deref()
843                .ok_or_else(|| Error::parse("Descriptor lacks a router-sig-ed25519"))?,
844        )?;
845        let master_key = match &self.ed25519_master_key {
846            Some(master) => decode_base64(master)?,
847            None => certificate
848                .signing_key()
849                .map(<[u8]>::to_vec)
850                .ok_or_else(|| {
851                    Error::parse("Server descriptor missing an ed25519 signing key")
852                })?,
853        };
854        certificate.verify_certificate_signature(&master_key)?;
855        certificate.verify_signature(&signed_content, &signature)
856    }
857
858    pub fn digest_bytes(&self, hash: DigestHash) -> Result<Vec<u8>> {
859        let content = content_range(
860            &self.common.raw_contents,
861            Some("router"),
862            Some("\nrouter-signature\n"),
863        )?;
864        Ok(hash_bytes(hash, &content))
865    }
866
867    pub fn digest(&self, hash: DigestHash, encoding: DigestEncoding) -> Result<String> {
868        Ok(encode_digest(&self.digest_bytes(hash)?, encoding))
869    }
870
871    pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
872        let mut descriptors = Vec::new();
873        for (annotations, text) in split_server_descriptors(content, false, validate)? {
874            descriptors.push(Self::parse_with_options(
875                &text,
876                validate,
877                annotations,
878                false,
879            )?);
880        }
881        Ok(descriptors)
882    }
883
884    pub fn make_router_status_entry(&self) -> Result<RouterStatusEntryV3> {
885        let fingerprint = self.common.fingerprint.as_ref().ok_or_else(|| {
886            Error::invalid_input(
887                "Server descriptor lacks a fingerprint. This is an \
888                optional field, but required to make a router status entry.",
889            )
890        })?;
891        let published = self.common.published.ok_or_else(|| {
892            Error::invalid_input("Server descriptor lacks a published time")
893        })?;
894        let digest = self.digest_bytes(DigestHash::Sha1)?;
895        let nickname = self.common.nickname.clone().unwrap_or_default();
896        let r_line = [
897            nickname,
898            truncated_base64(
899                &hex::decode(fingerprint)
900                    .map_err(|error| Error::parse(error.to_string()))?,
901            ),
902            truncated_base64(&digest),
903            published.format("%Y-%m-%d %H:%M:%S").to_string(),
904            self.common.address.clone().unwrap_or_default(),
905            self.common.or_port.unwrap_or(0).to_string(),
906            self.common.dir_port.unwrap_or(0).to_string(),
907        ]
908        .join(" ");
909        let mut attributes: Attributes = vec![
910            attr("r", &r_line),
911            attr(
912                "w",
913                &format!("Bandwidth={}", self.common.average_bandwidth.unwrap_or(0)),
914            ),
915            attr("p", &self.common.exit_policy.summary().replace(", ", ",")),
916        ];
917        if let Some(version) = &self.common.tor_version {
918            attributes.push(attr("v", &format!("Tor {version}")));
919        }
920        if !self.common.or_addresses.is_empty() {
921            attributes.push((
922                "a".to_string(),
923                AttrValue::Lines(
924                    self.common
925                        .or_addresses
926                        .iter()
927                        .map(|(address, port, _)| format!("{address}:{port}"))
928                        .collect(),
929                ),
930            ));
931        }
932        if let Some(certificate) = &self.certificate {
933            attributes.push(attr(
934                "id",
935                &format!("ed25519 {}", truncated_base64(&certificate.key)),
936            ));
937        }
938        RouterStatusEntryV3::create(&attributes, &[], true)
939    }
940
941    pub fn content(
942        attributes: &Attributes,
943        exclude: &[&str],
944        signing_key: Option<&RsaPrivateKey>,
945        exit_policy: Option<&ExitPolicy>,
946    ) -> Result<Vec<u8>> {
947        let default_policy = ExitPolicy::new(&["reject *:*"])?;
948        let policy = exit_policy.unwrap_or(&default_policy);
949        let mut header: Vec<(String, AttrValue)> = vec![
950            attr(
951                "router",
952                &format!("{} {} 9001 0 0", random_nickname(), random_ipv4_address()),
953            ),
954            attr("published", &random_date()),
955            attr("bandwidth", "153600 256000 104590"),
956        ];
957        for rule in policy.iter() {
958            let line = rule.to_string();
959            let (keyword, value) = line.split_once(' ').unwrap_or((&line, ""));
960            header.push((keyword.to_string(), AttrValue::Text(value.to_string())));
961        }
962        header.push(attr(
963            "onion-key",
964            &random_crypto_blob(Some("RSA PUBLIC KEY")),
965        ));
966        header.push(attr(
967            "signing-key",
968            &random_crypto_blob(Some("RSA PUBLIC KEY")),
969        ));
970        let borrowed: Vec<(&str, AttrValue)> = header
971            .iter()
972            .map(|(key, value)| (key.as_str(), value.clone()))
973            .collect();
974        let Some(private_key) = signing_key else {
975            let footer = [
976                ("router-sig-ed25519", AttrValue::Remove),
977                (
978                    "router-signature",
979                    AttrValue::Text(random_crypto_blob(Some("SIGNATURE"))),
980                ),
981            ];
982            return Ok(descriptor_content(attributes, exclude, &borrowed, &footer));
983        };
984        if attributes
985            .iter()
986            .any(|(key, _)| key == "signing-key" || key == "router-signature")
987        {
988            return Err(Error::invalid_input(
989                "Cannot sign the descriptor if a signing-key or router-signature has \
990                been provided",
991            ));
992        }
993        let public_block = signing_key_block(private_key)?;
994        let mut attributes = attributes.clone();
995        if !attributes.iter().any(|(key, _)| key == "fingerprint") {
996            let fingerprint =
997                hex::encode_upper(Sha1::digest(bytes_for_block(&public_block)?));
998            let grouped = crate::formatting::split_by_length(&fingerprint, 4).join(" ");
999            attributes.push(attr("fingerprint", &grouped));
1000        }
1001        attributes.push((
1002            "signing-key".to_string(),
1003            AttrValue::Text(format!("\n{public_block}")),
1004        ));
1005        let mut content = descriptor_content(&attributes, exclude, &borrowed, &[]);
1006        content.extend_from_slice(b"\nrouter-signature\n");
1007        append_router_signature(content, private_key)
1008    }
1009
1010    pub fn create(
1011        attributes: &Attributes,
1012        exclude: &[&str],
1013        validate: bool,
1014        signing_key: Option<&RsaPrivateKey>,
1015        exit_policy: Option<&ExitPolicy>,
1016    ) -> Result<Self> {
1017        let content = Self::content(attributes, exclude, signing_key, exit_policy)?;
1018        Self::parse_with_options(&content, validate, Vec::new(), signing_key.is_none())
1019    }
1020}
1021
1022pub fn create_signing_key() -> Result<RsaPrivateKey> {
1023    RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 1024).map_err(|error| {
1024        Error::invalid_input(format!("Unable to generate a signing key: {error}"))
1025    })
1026}
1027
1028pub fn signing_key_block(private_key: &RsaPrivateKey) -> Result<String> {
1029    use rsa::pkcs1::EncodeRsaPublicKey;
1030    let der = private_key
1031        .to_public_key()
1032        .to_pkcs1_der()
1033        .map_err(|error| Error::invalid_input(error.to_string()))?;
1034    let encoded = base64_standard(der.as_bytes());
1035    Ok(format!(
1036        "-----BEGIN RSA PUBLIC KEY-----\n{}\n-----END RSA PUBLIC KEY-----",
1037        crate::formatting::split_by_length(&encoded, 64).join("\n")
1038    ))
1039}
1040
1041fn base64_standard(content: &[u8]) -> String {
1042    use base64::Engine;
1043    base64::engine::general_purpose::STANDARD.encode(content)
1044}
1045
1046pub fn append_router_signature(
1047    mut content: Vec<u8>,
1048    private_key: &RsaPrivateKey,
1049) -> Result<Vec<u8>> {
1050    let digest = Sha1::digest(&content);
1051    let signature = private_key
1052        .sign(rsa::Pkcs1v15Sign::new_unprefixed(), &digest)
1053        .map_err(|error| {
1054            Error::invalid_input(format!("Unable to sign the descriptor: {error}"))
1055        })?;
1056    let encoded = base64_standard(&signature);
1057    content.extend_from_slice(b"-----BEGIN SIGNATURE-----\n");
1058    content.extend_from_slice(
1059        crate::formatting::split_by_length(&encoded, 64)
1060            .join("\n")
1061            .as_bytes(),
1062    );
1063    content.extend_from_slice(b"\n-----END SIGNATURE-----\n");
1064    Ok(content)
1065}
1066
1067impl BridgeServerDescriptor {
1068    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
1069        Self::parse_with_annotations(content, validate, Vec::new())
1070    }
1071
1072    pub fn parse_with_annotations(
1073        content: &[u8],
1074        validate: bool,
1075        annotations: Vec<String>,
1076    ) -> Result<Self> {
1077        let (entries, policy_lines) = descriptor_components(
1078            content,
1079            validate,
1080            &["accept", "reject"],
1081            &["contact", "platform"],
1082        )?;
1083        let common = parse_common(
1084            content,
1085            &entries,
1086            &policy_lines,
1087            annotations,
1088            validate,
1089            true,
1090        )?;
1091        if validate {
1092            check_constraints(&entries, true, !common.exit_policy.is_empty(), false)?;
1093        }
1094        let digest = match entries.value("router-digest") {
1095            Ok(value) => {
1096                lenient_option(validate, parse_forty_hex("router-digest", value))?
1097            }
1098            Err(_) => None,
1099        };
1100        Ok(Self {
1101            common,
1102            ed25519_certificate_hash: entries
1103                .value("master-key-ed25519")
1104                .ok()
1105                .map(str::to_string),
1106            router_digest_sha256: entries
1107                .value("router-digest-sha256")
1108                .ok()
1109                .map(str::to_string),
1110            digest,
1111        })
1112    }
1113
1114    pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
1115        let mut descriptors = Vec::new();
1116        for (annotations, text) in split_server_descriptors(content, true, validate)? {
1117            descriptors.push(Self::parse_with_annotations(&text, validate, annotations)?);
1118        }
1119        Ok(descriptors)
1120    }
1121
1122    pub fn digest(&self) -> Option<&str> {
1123        self.digest.as_deref()
1124    }
1125
1126    pub fn is_scrubbed(&self) -> bool {
1127        self.scrubbing_issues().is_empty()
1128    }
1129
1130    pub fn scrubbing_issues(&self) -> Vec<String> {
1131        let mut issues = Vec::new();
1132        let address = self.common.address.clone().unwrap_or_default();
1133        if !address.starts_with("10.") {
1134            issues.push(format!(
1135                "Router line's address should be scrubbed to be '10.x.x.x': {address}"
1136            ));
1137        }
1138        if let Some(contact) = &self.common.contact {
1139            let text = String::from_utf8_lossy(contact);
1140            if text != "somebody" {
1141                issues.push(format!(
1142                    "Contact line should be scrubbed to be 'somebody', \
1143                    but instead had '{text}'"
1144                ));
1145            }
1146        }
1147        for (address, _, is_ipv6) in &self.common.or_addresses {
1148            if !is_ipv6 && !address.starts_with("10.") {
1149                issues.push(format!(
1150                    "or-address line's address should be scrubbed to be \
1151                    '10.x.x.x': {address}"
1152                ));
1153            } else if *is_ipv6 && !address.starts_with("fd9f:2e19:3bcf::") {
1154                issues.push(format!(
1155                    "or-address line's address should be scrubbed to be \
1156                    'fd9f:2e19:3bcf::xx:xxxx': {address}"
1157                ));
1158            }
1159        }
1160        for line in &self.common.unrecognized_lines {
1161            for (prefix, label) in [
1162                ("onion-key ", "onion-key"),
1163                ("signing-key ", "signing-key"),
1164                ("router-signature ", "signature"),
1165            ] {
1166                if line.starts_with(prefix) {
1167                    issues.push(format!(
1168                        "Bridge descriptors should have their {label} scrubbed: {line}"
1169                    ));
1170                }
1171            }
1172        }
1173        issues
1174    }
1175
1176    pub fn content(attributes: &Attributes, exclude: &[&str]) -> Vec<u8> {
1177        descriptor_content(
1178            attributes,
1179            exclude,
1180            &[
1181                (
1182                    "router",
1183                    AttrValue::Text(format!(
1184                        "{} {} 9001 0 0",
1185                        random_nickname(),
1186                        random_ipv4_address()
1187                    )),
1188                ),
1189                (
1190                    "router-digest",
1191                    AttrValue::Text(
1192                        "006FD96BA35E7785A6A3B8B75FE2E2435A13BDB4".to_string(),
1193                    ),
1194                ),
1195                ("published", AttrValue::Text(random_date())),
1196                (
1197                    "bandwidth",
1198                    AttrValue::Text("409600 819200 5120".to_string()),
1199                ),
1200                ("reject", AttrValue::Text("*:*".to_string())),
1201            ],
1202            &[],
1203        )
1204    }
1205
1206    pub fn create(
1207        attributes: &Attributes,
1208        exclude: &[&str],
1209        validate: bool,
1210    ) -> Result<Self> {
1211        Self::parse(&Self::content(attributes, exclude), validate)
1212    }
1213}
1214
1215fn split_server_descriptors(
1216    content: &[u8],
1217    is_bridge: bool,
1218    validate: bool,
1219) -> Result<Vec<(Vec<String>, Vec<u8>)>> {
1220    let mut cursor = LineCursor::new(content);
1221    let mut found = Vec::new();
1222    loop {
1223        let annotations = cursor.read_until_keywords(&["router"], ReadOptions::default());
1224        let annotation_lines = parse_annotations(&annotations.content);
1225        let mut body = if is_bridge {
1226            cursor
1227                .read_until_keywords(
1228                    &["router-digest"],
1229                    ReadOptions {
1230                        inclusive: true,
1231                        ..Default::default()
1232                    },
1233                )
1234                .content
1235        } else {
1236            let mut body = cursor
1237                .read_until_keywords(&["router-signature"], ReadOptions::default())
1238                .content;
1239            body.extend(
1240                cursor
1241                    .read_until_keywords(
1242                        &["-----END"],
1243                        ReadOptions {
1244                            inclusive: true,
1245                            ..Default::default()
1246                        },
1247                    )
1248                    .content,
1249            );
1250            body
1251        };
1252        if body.is_empty() {
1253            if validate && !annotation_lines.is_empty() {
1254                return Err(Error::parse(format!(
1255                    "Content conform to being a server descriptor:\n{}",
1256                    annotation_lines.join("\n")
1257                )));
1258            }
1259            break;
1260        }
1261        if body.starts_with(b"@type") {
1262            body = body
1263                .splitn(2, |byte| *byte == b'\n')
1264                .nth(1)
1265                .unwrap_or_default()
1266                .to_vec();
1267        }
1268        found.push((annotation_lines, body));
1269    }
1270    Ok(found)
1271}