1
//! Helpers for building and representing hidden service descriptors.
2

            
3
use super::*;
4
use crate::config::OnionServiceConfigPublisherView;
5
use tor_cell::chancell::msg::HandshakeType;
6

            
7
/// Build the descriptor.
8
///
9
/// The `now` argument is used for computing the expiry of the `intro_{auth, enc}_key_cert`
10
/// certificates included in the descriptor. The expiry will be set to 54 hours from `now`.
11
///
12
/// Note: `blind_id_kp` is the blinded hidden service signing keypair used to sign descriptor
13
/// signing keys (KP_hs_blind_id, KS_hs_blind_id).
14
#[allow(clippy::too_many_arguments)]
15
128
pub(super) fn build_sign<Rng: RngCore + CryptoRng>(
16
128
    keymgr: &Arc<KeyMgr>,
17
128
    config: &Arc<OnionServiceConfigPublisherView>,
18
128
    authorized_clients: Option<&RestrictedDiscoveryKeys>,
19
128
    ipt_set: &IptSet,
20
128
    period: TimePeriod,
21
128
    revision_counter: RevisionCounter,
22
128
    rng: &mut Rng,
23
128
    now: SystemTime,
24
128
) -> Result<VersionedDescriptor, FatalError> {
25
    // TODO: should this be configurable? If so, we should read it from the svc config.
26
    //
27
    /// The CREATE handshake type we support.
28
    const CREATE2_FORMATS: &[HandshakeType] = &[HandshakeType::NTOR];
29

            
30
    /// Lifetime of the intro_{auth, enc}_key_cert certificates in the descriptor.
31
    ///
32
    /// From C-Tor src/feature/hs/hs_descriptor.h:
33
    ///
34
    /// "This defines the lifetime of the descriptor signing key and the cross certification cert of
35
    /// that key. It is set to 54 hours because a descriptor can be around for 48 hours and because
36
    /// consensuses are used after the hour, add an extra 6 hours to give some time for the service
37
    /// to stop using it."
38
    const HS_DESC_CERT_LIFETIME_SEC: Duration = Duration::from_secs(54 * 60 * 60);
39

            
40
128
    let intro_points = ipt_set
41
128
        .ipts
42
128
        .iter()
43
384
        .map(|ipt_in_set| ipt_in_set.ipt.clone())
44
128
        .collect::<Vec<_>>();
45
128

            
46
128
    let nickname = &config.nickname;
47
128

            
48
128
    let svc_key_spec = HsIdPublicKeySpecifier::new(nickname.clone());
49
128
    let hsid = keymgr
50
128
        .get::<HsIdKey>(&svc_key_spec)?
51
128
        .ok_or_else(|| FatalError::MissingHsIdKeypair(nickname.clone()))?;
52

            
53
    // TODO: make the keystore selector configurable
54
128
    let keystore_selector = Default::default();
55
128
    let blind_id_kp = read_blind_id_keypair(keymgr, nickname, period)?
56
128
        .ok_or_else(|| internal!("hidden service offline mode not supported"))?;
57

            
58
128
    let blind_id_key = HsBlindIdKey::from(&blind_id_kp);
59
128
    let subcredential = hsid.compute_subcredential(&blind_id_key, period);
60
128

            
61
128
    let hs_desc_sign_key_spec = DescSigningKeypairSpecifier::new(nickname.clone(), period);
62
128
    let hs_desc_sign = keymgr.get_or_generate::<HsDescSigningKeypair>(
63
128
        &hs_desc_sign_key_spec,
64
128
        keystore_selector,
65
128
        rng,
66
128
    )?;
67

            
68
    // TODO #1028: support introduction-layer authentication.
69
128
    let auth_required = None;
70
128

            
71
128
    // TODO(#727): add support for single onion services
72
128
    let is_single_onion_service = false;
73
128

            
74
128
    // TODO (#955): perhaps the certificates should be read from the keystore, rather than created
75
128
    // when building the descriptor. See #1048
76
128
    let intro_auth_key_cert_expiry = now + HS_DESC_CERT_LIFETIME_SEC;
77
128
    let intro_enc_key_cert_expiry = now + HS_DESC_CERT_LIFETIME_SEC;
78
128
    let hs_desc_sign_cert_expiry = now + HS_DESC_CERT_LIFETIME_SEC;
79

            
80
    cfg_if::cfg_if! {
81
        if #[cfg(feature = "restricted-discovery")] {
82
128
            let auth_clients: Option<Vec<curve25519::PublicKey>> = authorized_clients
83
128
                .as_ref()
84
128
                .map(|authorized_clients| {
85
                    if authorized_clients.is_empty() {
86
                        return Err(internal!("restricted discovery enabled, but no authorized clients?!"));
87
                    }
88
                    let auth_clients = authorized_clients
89
                        .iter()
90
                        .map(|(nickname, key)| {
91
                            trace!("encrypting descriptor for client {nickname}");
92
                            (*key).clone().into()
93
                        })
94
                        .collect_vec();
95
                    Ok(auth_clients)
96
128
                })
97
128
                .transpose()?;
98
        } else {
99
            let auth_clients: Option<Vec<curve25519::PublicKey>> = None;
100
        }
101
    }
102

            
103
128
    if let Some(ref auth_clients) = auth_clients {
104
        debug!("Encrypting descriptor for {} clients", auth_clients.len());
105
128
    }
106

            
107
128
    let desc_signing_key_cert = create_desc_sign_key_cert(
108
128
        &hs_desc_sign.as_ref().verifying_key(),
109
128
        &blind_id_kp,
110
128
        hs_desc_sign_cert_expiry,
111
128
    )
112
128
    .map_err(into_bad_api_usage!(
113
128
        "failed to sign the descriptor signing key"
114
128
    ))?;
115

            
116
128
    let desc = HsDescBuilder::default()
117
128
        .blinded_id(&(&blind_id_kp).into())
118
128
        .hs_desc_sign(hs_desc_sign.as_ref())
119
128
        .hs_desc_sign_cert(desc_signing_key_cert)
120
128
        .create2_formats(CREATE2_FORMATS)
121
128
        .auth_required(auth_required)
122
128
        .is_single_onion_service(is_single_onion_service)
123
128
        .intro_points(&intro_points[..])
124
128
        .intro_auth_key_cert_expiry(intro_auth_key_cert_expiry)
125
128
        .intro_enc_key_cert_expiry(intro_enc_key_cert_expiry)
126
128
        .lifetime(((ipt_set.lifetime.as_secs() / 60) as u16).into())
127
128
        .revision_counter(revision_counter)
128
128
        .subcredential(subcredential)
129
128
        .auth_clients(auth_clients.as_deref())
130
128
        .build_sign(rng)
131
128
        .map_err(|e| into_internal!("failed to build descriptor")(e))?;
132

            
133
128
    Ok(VersionedDescriptor {
134
128
        desc,
135
128
        revision_counter,
136
128
    })
137
128
}
138

            
139
/// The freshness status of a descriptor at a particular HsDir.
140
#[derive(Copy, Clone, Debug, Default, PartialEq)]
141
pub(super) enum DescriptorStatus {
142
    #[default]
143
    /// Dirty, needs to be (re)uploaded.
144
    Dirty,
145
    /// Clean, does not need to be reuploaded.
146
    Clean,
147
}
148

            
149
/// A descriptor and its revision.
150
#[derive(Clone)]
151
pub(super) struct VersionedDescriptor {
152
    /// The serialized descriptor.
153
    pub(super) desc: String,
154
    /// The revision counter.
155
    pub(super) revision_counter: RevisionCounter,
156
}