~zethra/stargazer

ref: a6ad2542353c48c5cfc1b9261549be671231df15 stargazer/src/tls.rs -rw-r--r-- 7.8 KiB
a6ad2542 — Ben Aaron Goldberg Merge branch 'f/cert-conf' 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// stargazer - A Gemini Server
// Copyright (C) 2021 Ben Aaron Goldberg <ben@benaaron.dev>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::router::Route;
use crate::CONF;
use anyhow::{anyhow, bail, Context, Result};
use async_rustls::rustls::internal::msgs::handshake::DigitallySignedStruct;
use async_rustls::rustls::{
    internal::pemfile::{certs, pkcs8_private_keys},
    sign::{self, CertifiedKey},
    Certificate, ClientCertVerified, ClientCertVerifier, DistinguishedNames,
    HandshakeSignatureValid, PrivateKey, ProtocolVersion,
    ResolvesServerCertUsingSNI, ServerConfig, TLSError,
};
use async_rustls::webpki;
use chrono::{DateTime, NaiveDateTime, Utc};
use log::debug;
use rcgen::{
    Certificate as GenCert, CertificateParams, DistinguishedName, DnType,
};
use std::time::{Duration, UNIX_EPOCH};
use std::{
    fs::{self, File},
    io::BufReader,
    path::{Path, PathBuf},
    sync::Arc,
};
use x509_parser::parse_x509_certificate;

/// Allow but don't require client auth accepting any client cert.
struct GeminiClientAuth;

impl ClientCertVerifier for GeminiClientAuth {
    fn offer_client_auth(&self) -> bool {
        true
    }

    fn client_auth_mandatory(
        &self,
        _sni: Option<&webpki::DNSName>,
    ) -> Option<bool> {
        Some(false)
    }

    fn client_auth_root_subjects(
        &self,
        _sni: Option<&webpki::DNSName>,
    ) -> Option<DistinguishedNames> {
        Some(Vec::new())
    }

    fn verify_client_cert(
        &self,
        _presented_certs: &[Certificate],
        _sni: Option<&webpki::DNSName>,
    ) -> Result<ClientCertVerified, TLSError> {
        Ok(ClientCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &Certificate,
        _dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, TLSError> {
        Ok(HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &Certificate,
        _dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, TLSError> {
        Ok(HandshakeSignatureValid::assertion())
    }
}

/// Load the passed certificates file
fn load_cert(path: &Path) -> Result<Vec<Certificate>> {
    match certs(&mut BufReader::new(
        File::open(path).context("error reading certificate file")?,
    ))
    .map_err(|_| anyhow!("invalid certificate"))
    {
        Ok(certs) => {
            if !certs.is_empty() {
                Ok(certs)
            } else {
                Err(anyhow!(
                    "cert file {} doesn't contain a cert",
                    path.display()
                ))
            }
        }
        Err(e) => Err(e),
    }
}

/// Load the passed keys file
fn load_key(path: &Path) -> Result<PrivateKey> {
    match pkcs8_private_keys(&mut BufReader::new(
        File::open(path).context("error reading key file")?,
    ))
    .map_err(|_| anyhow!("invalid key"))
    {
        Ok(keys) => {
            if keys.len() == 1 {
                Ok(keys[0].clone())
            } else {
                Err(anyhow!(
                    "key file {} doesn't contain exactly 1 key",
                    path.display()
                ))
            }
        }
        Err(e) => Err(e),
    }
}

/// Configure the server using rustls
/// See https://docs.rs/rustls/0.16.0/rustls/struct.ServerConfig.html for details
///
/// A TLS server needs a certificate and a fitting private key
pub fn load_config(routes: &[Route]) -> Result<ServerConfig> {
    let mut resolver = ResolvesServerCertUsingSNI::new();
    for route in routes {
        let (cert_chain, key) = get_cert_and_key(route)?;

        let signing_key = sign::any_supported_type(&key)
            .map_err(|_| anyhow!("Invalid key for domain {}", route.domain))?;

        log::debug!("Loaded cert+key for domain {}", route.domain);
        resolver
            .add(
                &route.domain,
                CertifiedKey::new(cert_chain, Arc::new(signing_key)),
            )
            .with_context(|| {
                format!(
                    "Error adding cert/key for domain `{}` to tls config",
                    route.domain
                )
            })?;
    }

    // we don't use client authentication
    let mut config = ServerConfig::new(Arc::new(GeminiClientAuth));
    config.cert_resolver = Arc::new(resolver);
    config.versions = vec![ProtocolVersion::TLSv1_3, ProtocolVersion::TLSv1_2];

    Ok(config)
}

fn get_cert_and_key(route: &Route) -> Result<(Vec<Certificate>, PrivateKey)> {
    let (cert_path, key_path, default_paths) = match route.cert_key_path.clone() {
        Some((cert_path, key_path)) => (cert_path, key_path, false),
        None => (
            CONF.store.join(format!("{}.crt", route.domain)),
            CONF.store.join(format!("{}.key", route.domain)),
            true,
        ),
    };
    if default_paths && (!cert_path.exists() || !key_path.exists()) {
        let (cert_path, key_path) = gen_cert_and_key(&route.domain)?;
        return Ok((load_cert(&cert_path)?, load_key(&key_path)?));
    }
    let cert_chain = load_cert(&cert_path)?;
    for cert in &cert_chain {
        let (_, cert) =
            parse_x509_certificate(cert.as_ref()).with_context(|| {
                format!("Error parsing cert for {}", route.domain)
            })?;
        if CONF.regen_certs && !cert.validity().is_valid() {
            let (cert_path, key_path) = gen_cert_and_key(&route.domain)?;
            return Ok((load_cert(&cert_path)?, load_key(&key_path)?));
        }
    }
    Ok((cert_chain, load_key(&key_path)?))
}

fn gen_cert_and_key(domain: &str) -> Result<(PathBuf, PathBuf)> {
    if !CONF.generate_certs {
        bail!(
            "Cert not found for domain {} and cert generation is disabled",
            domain
        );
    }
    debug!("Generating cert+key for {}", domain);
    let mut params = CertificateParams::new(vec![domain.to_owned()]);
    let mut distinguished_name = DistinguishedName::new();
    distinguished_name.push(DnType::CommonName, domain);
    distinguished_name.push(DnType::OrganizationName, &CONF.organization);
    params.distinguished_name = distinguished_name;
    let not_before = UNIX_EPOCH.elapsed().context("Time is broken")?;
    // Plus 5 years
    let not_after = not_before + Duration::from_secs(5 * 365 * 24 * 60 * 60);
    params.not_before = DateTime::<Utc>::from_utc(
        NaiveDateTime::from_timestamp(not_before.as_secs() as i64, 0),
        Utc,
    );
    params.not_after = DateTime::<Utc>::from_utc(
        NaiveDateTime::from_timestamp(not_after.as_secs() as i64, 0),
        Utc,
    );
    let cert = GenCert::from_params(params).with_context(|| {
        format!("Error generating cert for domain: `{}`", domain)
    })?;
    let crt = cert.serialize_pem().with_context(|| {
        format!("Error serializing cert for domain: `{}`", domain)
    })?;
    let key = cert.serialize_private_key_pem();

    let crt_path = CONF.store.join(format!("{}.crt", domain));
    let key_path = CONF.store.join(format!("{}.key", domain));

    fs::write(&crt_path, crt).with_context(|| {
        format!("Error writing cert for domain: `{}`", domain)
    })?;
    fs::write(&key_path, key)
        .with_context(|| format!("Error write key for domain: `{}`", domain))?;
    Ok((crt_path, key_path))
}