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
use tor_llcrypto::rng::EntropicRng;
7

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

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

            
44
144
    let intro_points = ipt_set
45
144
        .ipts
46
144
        .iter()
47
432
        .map(|ipt_in_set| ipt_in_set.ipt.clone())
48
144
        .collect::<Vec<_>>();
49

            
50
144
    let nickname = &config.nickname;
51

            
52
144
    let svc_key_spec = HsIdPublicKeySpecifier::new(nickname.clone());
53
144
    let hsid = keymgr
54
144
        .get::<HsIdKey>(&svc_key_spec)?
55
144
        .ok_or_else(|| FatalError::MissingHsIdKeypair(nickname.clone()))?;
56

            
57
    // TODO: make the keystore selector configurable
58
144
    let keystore_selector = Default::default();
59
144
    let blind_id_kp = read_blind_id_keypair(keymgr, nickname, period)?
60
144
        .ok_or_else(|| internal!("hidden service offline mode not supported"))?;
61

            
62
144
    let blind_id_key = HsBlindIdKey::from(&blind_id_kp);
63
144
    let subcredential = hsid.compute_subcredential(&blind_id_key, period);
64

            
65
144
    let hs_desc_sign_key_spec = DescSigningKeypairSpecifier::new(nickname.clone(), period);
66
144
    let hs_desc_sign = keymgr.get_or_generate::<HsDescSigningKeypair>(
67
144
        &hs_desc_sign_key_spec,
68
144
        keystore_selector,
69
144
        key_rng,
70
144
    )?;
71

            
72
    // TODO #1028: support introduction-layer authentication.
73
144
    let auth_required = None;
74

            
75
    // TODO(#727): add support for single onion services
76
144
    let is_single_onion_service = false;
77

            
78
    // TODO (#955): perhaps the certificates should be read from the keystore, rather than created
79
    // when building the descriptor. See #1048
80
144
    let intro_auth_key_cert_expiry = now + HS_DESC_CERT_LIFETIME_SEC;
81
144
    let intro_enc_key_cert_expiry = now + HS_DESC_CERT_LIFETIME_SEC;
82
144
    let hs_desc_sign_cert_expiry = now + HS_DESC_CERT_LIFETIME_SEC;
83

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

            
107
144
    if let Some(ref auth_clients) = auth_clients {
108
        debug!("Encrypting descriptor for {} clients", auth_clients.len());
109
144
    }
110

            
111
144
    let desc_signing_key_cert = create_desc_sign_key_cert(
112
144
        &hs_desc_sign.as_ref().verifying_key(),
113
144
        &blind_id_kp,
114
144
        hs_desc_sign_cert_expiry,
115
    )
116
144
    .map_err(into_bad_api_usage!(
117
        "failed to sign the descriptor signing key"
118
    ))?;
119

            
120
144
    let blind_id_kp = (&blind_id_kp).into();
121

            
122
144
    let mut desc = HsDescBuilder::default()
123
144
        .blinded_id(&blind_id_kp)
124
144
        .hs_desc_sign(hs_desc_sign.as_ref())
125
144
        .hs_desc_sign_cert(desc_signing_key_cert)
126
144
        .create2_formats(CREATE2_FORMATS)
127
144
        .auth_required(auth_required)
128
144
        .is_single_onion_service(is_single_onion_service)
129
144
        .intro_points(&intro_points[..])
130
144
        .intro_auth_key_cert_expiry(intro_auth_key_cert_expiry)
131
144
        .intro_enc_key_cert_expiry(intro_enc_key_cert_expiry)
132
144
        .lifetime(((ipt_set.lifetime.as_secs() / 60) as u16).into())
133
144
        .revision_counter(revision_counter)
134
144
        .subcredential(subcredential)
135
144
        .auth_clients(auth_clients.as_deref())
136
144
        .max_generated_len(max_hsdesc_len);
137

            
138
    cfg_if::cfg_if! {
139
        if #[cfg(feature = "hs-pow-full")] {
140
144
            let pow_params = pow_manager.get_pow_params(period, &mut rand::rng());
141
144
            match pow_params {
142
144
                Ok(ref pow_params) => {
143
144
                    if config.enable_pow {
144
                        desc = desc.pow_params(Some(pow_params));
145
144
                    }
146
                },
147
                Err(err) => {
148
                    warn!(?err, "Couldn't get PoW params");
149
                }
150
            }
151
        }
152
    }
153

            
154
144
    let desc = desc.build_sign(rng).map_err(|e| match e {
155
        tor_bytes::EncodeError::BadLengthValue => FatalError::HsDescTooLong,
156
        e => into_internal!("failed to build descriptor")(e).into(),
157
    })?;
158

            
159
144
    Ok(VersionedDescriptor {
160
144
        desc,
161
144
        revision_counter,
162
144
    })
163
144
}
164

            
165
/// The freshness status of a descriptor at a particular HsDir.
166
#[derive(Copy, Clone, Debug, Default, PartialEq)]
167
pub(super) enum DescriptorStatus {
168
    #[default]
169
    /// Dirty, needs to be (re)uploaded.
170
    Dirty,
171
    /// Clean, does not need to be reuploaded.
172
    Clean,
173
}
174

            
175
/// A descriptor and its revision.
176
#[derive(Clone)]
177
pub(super) struct VersionedDescriptor {
178
    /// The serialized descriptor.
179
    pub(super) desc: String,
180
    /// The revision counter.
181
    pub(super) revision_counter: RevisionCounter,
182
}