tls.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{io, sync::Arc};
  19. use futures_rustls::{
  20. rustls::{
  21. self,
  22. client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
  23. pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime},
  24. server::danger::{ClientCertVerified, ClientCertVerifier},
  25. version::TLS13,
  26. ClientConfig, DigitallySignedStruct, DistinguishedName, ServerConfig, SignatureScheme,
  27. },
  28. TlsAcceptor, TlsConnector, TlsStream,
  29. };
  30. use rcgen::string::Ia5String;
  31. use tracing::error;
  32. use x509_parser::{
  33. parse_x509_certificate,
  34. prelude::{GeneralName, ParsedExtension, X509Certificate},
  35. };
  36. /// The DNS name used for certificate validation across all transports
  37. pub(crate) const TLS_DNS_NAME: &str = "dark.fi";
  38. /// Validate certificate DNSName.
  39. fn validate_dnsname(cert: &X509Certificate) -> std::result::Result<(), rustls::Error> {
  40. #[rustfmt::skip]
  41. let oid = x509_parser::oid_registry::asn1_rs::oid!(2.5.29.17);
  42. let Ok(Some(extension)) = cert.get_extension_unique(&oid) else {
  43. return Err(rustls::CertificateError::BadEncoding.into())
  44. };
  45. let dns_name = match extension.parsed_extension() {
  46. ParsedExtension::SubjectAlternativeName(altname) => {
  47. if altname.general_names.len() != 1 {
  48. return Err(rustls::CertificateError::BadEncoding.into())
  49. }
  50. match altname.general_names[0] {
  51. GeneralName::DNSName(dns_name) => dns_name,
  52. _ => return Err(rustls::CertificateError::BadEncoding.into()),
  53. }
  54. }
  55. _ => return Err(rustls::CertificateError::BadEncoding.into()),
  56. };
  57. if dns_name != TLS_DNS_NAME {
  58. return Err(rustls::CertificateError::BadEncoding.into())
  59. }
  60. Ok(())
  61. }
  62. fn verify_ed25519_signature(
  63. message: &[u8],
  64. cert: &CertificateDer,
  65. dss: &DigitallySignedStruct,
  66. ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
  67. if dss.scheme != SignatureScheme::ED25519 {
  68. return Err(rustls::CertificateError::BadSignature.into())
  69. }
  70. // Read the DER-encoded certificate into a buffer
  71. let buf: Vec<u8> = cert.iter().copied().collect();
  72. // Parse the cert and extract the public key
  73. let Ok((_, cert)) = parse_x509_certificate(&buf) else {
  74. error!(target: "net::tls::verify_ed25519_signature", "[net::tls] Failed parsing TLS certificate");
  75. return Err(rustls::CertificateError::BadEncoding.into())
  76. };
  77. let Ok(public_key) = ed25519_compact::PublicKey::from_der(cert.public_key().raw) else {
  78. error!(target: "net::tls::verify_ed25519_signature", "[net::tls] Failed parsing public key");
  79. return Err(rustls::CertificateError::BadEncoding.into())
  80. };
  81. let Ok(signature) = ed25519_compact::Signature::from_slice(dss.signature()) else {
  82. error!(target: "net::tls::verify_ed25519_signature", "[net::tls] Failed verifying signature");
  83. return Err(rustls::CertificateError::BadSignature.into())
  84. };
  85. if let Err(e) = public_key.verify(message, &signature) {
  86. error!(target: "net::tls::verify_ed25519_signature", "[net::tls] Failed verifying signature: {e}");
  87. return Err(rustls::CertificateError::BadSignature.into())
  88. }
  89. Ok(HandshakeSignatureValid::assertion())
  90. }
  91. #[derive(Debug)]
  92. pub(crate) struct ServerCertificateVerifier;
  93. impl ServerCertVerifier for ServerCertificateVerifier {
  94. fn verify_server_cert(
  95. &self,
  96. end_entity: &CertificateDer,
  97. _intermediates: &[CertificateDer],
  98. _server_name: &ServerName,
  99. _ocsp_response: &[u8],
  100. _now: UnixTime,
  101. ) -> std::result::Result<ServerCertVerified, rustls::Error> {
  102. // Read the DER-encoded certificate into a buffer
  103. let buf: Vec<u8> = end_entity.iter().copied().collect();
  104. // Parse the certificate
  105. let Ok((_, cert)) = parse_x509_certificate(&buf) else {
  106. error!(target: "net::tls::verify_server_cert", "[net::tls] Failed parsing server TLS certificate");
  107. return Err(rustls::CertificateError::BadEncoding.into())
  108. };
  109. // Validate DNSName
  110. validate_dnsname(&cert)?;
  111. Ok(ServerCertVerified::assertion())
  112. }
  113. fn verify_tls12_signature(
  114. &self,
  115. _message: &[u8],
  116. _cert: &CertificateDer,
  117. _dss: &DigitallySignedStruct,
  118. ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
  119. unreachable!()
  120. }
  121. fn verify_tls13_signature(
  122. &self,
  123. message: &[u8],
  124. cert: &CertificateDer,
  125. dss: &DigitallySignedStruct,
  126. ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
  127. verify_ed25519_signature(message, cert, dss)
  128. }
  129. fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
  130. vec![SignatureScheme::ED25519]
  131. }
  132. }
  133. #[derive(Debug)]
  134. pub(crate) struct ClientCertificateVerifier;
  135. impl ClientCertVerifier for ClientCertificateVerifier {
  136. fn offer_client_auth(&self) -> bool {
  137. true
  138. }
  139. fn client_auth_mandatory(&self) -> bool {
  140. true
  141. }
  142. fn root_hint_subjects(&self) -> &[DistinguishedName] {
  143. &[]
  144. }
  145. fn verify_client_cert(
  146. &self,
  147. end_entity: &CertificateDer,
  148. _intermediates: &[CertificateDer],
  149. _now: UnixTime,
  150. ) -> std::result::Result<ClientCertVerified, rustls::Error> {
  151. // Read the DER-encoded certificate into a buffer
  152. let buf: Vec<u8> = end_entity.iter().copied().collect();
  153. // Parse the certificate
  154. let Ok((_, cert)) = parse_x509_certificate(&buf) else {
  155. error!(target: "net::tls::verify_server_cert", "[net::tls] Failed parsing server TLS certificate");
  156. return Err(rustls::CertificateError::BadEncoding.into())
  157. };
  158. // Validate DNSName
  159. validate_dnsname(&cert)?;
  160. Ok(ClientCertVerified::assertion())
  161. }
  162. fn verify_tls12_signature(
  163. &self,
  164. _message: &[u8],
  165. _cert: &CertificateDer,
  166. _dss: &DigitallySignedStruct,
  167. ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
  168. unreachable!()
  169. }
  170. fn verify_tls13_signature(
  171. &self,
  172. message: &[u8],
  173. cert: &CertificateDer,
  174. dss: &DigitallySignedStruct,
  175. ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
  176. verify_ed25519_signature(message, cert, dss)
  177. }
  178. fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
  179. vec![SignatureScheme::ED25519]
  180. }
  181. }
  182. /// Generate a self-signed Ed25519 certificate for TLS.
  183. /// Returns the certificate and private key in DER format.
  184. pub(crate) fn generate_certificate() -> io::Result<(CertificateDer<'static>, PrivateKeyDer<'static>)>
  185. {
  186. let Ok(keypair) = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519) else {
  187. return Err(io::Error::other("Failed to generate TLS keypair"))
  188. };
  189. let Ok(mut cert_params) = rcgen::CertificateParams::new(&[]) else {
  190. return Err(io::Error::other("Failed to generate TLS params"))
  191. };
  192. cert_params.subject_alt_names =
  193. vec![rcgen::SanType::DnsName(Ia5String::try_from(TLS_DNS_NAME).unwrap())];
  194. cert_params.extended_key_usages = vec![
  195. rcgen::ExtendedKeyUsagePurpose::ClientAuth,
  196. rcgen::ExtendedKeyUsagePurpose::ServerAuth,
  197. ];
  198. let Ok(certificate) = cert_params.self_signed(&keypair) else {
  199. return Err(io::Error::other("Failed to sign TLS certificate"))
  200. };
  201. let certificate = certificate.der().clone();
  202. let keypair_der = keypair.serialize_der();
  203. let Ok(secret_key_der) = PrivateKeyDer::try_from(keypair_der) else {
  204. return Err(io::Error::other("Failed to deserialize DER TLS secret"))
  205. };
  206. Ok((certificate, secret_key_der))
  207. }
  208. pub struct TlsUpgrade {
  209. /// TLS server configuration
  210. server_config: Arc<ServerConfig>,
  211. /// TLS client configuration
  212. client_config: Arc<ClientConfig>,
  213. }
  214. impl TlsUpgrade {
  215. pub async fn new() -> io::Result<Self> {
  216. // On each instantiation, generate a new keypair and certificate
  217. let (certificate, secret_key_der) = generate_certificate()?;
  218. // Server-side config
  219. let client_cert_verifier = Arc::new(ClientCertificateVerifier {});
  220. let server_config = Arc::new(
  221. ServerConfig::builder_with_protocol_versions(&[&TLS13])
  222. .with_client_cert_verifier(client_cert_verifier)
  223. .with_single_cert(vec![certificate.clone()], secret_key_der.clone_key())
  224. .unwrap(),
  225. );
  226. // Client-side config
  227. let server_cert_verifier = Arc::new(ServerCertificateVerifier {});
  228. let client_config = Arc::new(
  229. ClientConfig::builder_with_protocol_versions(&[&TLS13])
  230. .dangerous()
  231. .with_custom_certificate_verifier(server_cert_verifier)
  232. .with_client_auth_cert(vec![certificate.clone()], secret_key_der)
  233. .unwrap(),
  234. );
  235. Ok(Self { server_config, client_config })
  236. }
  237. pub async fn upgrade_dialer_tls<IO>(self, stream: IO) -> io::Result<TlsStream<IO>>
  238. where
  239. IO: super::PtStream,
  240. {
  241. let server_name = ServerName::try_from(TLS_DNS_NAME).unwrap();
  242. let connector = TlsConnector::from(self.client_config);
  243. let stream = connector.connect(server_name, stream).await?;
  244. Ok(TlsStream::Client(stream))
  245. }
  246. // TODO: Try to find a transparent way for this instead of implementing
  247. // the function separately for every transport type.
  248. pub async fn upgrade_listener_tcp_tls(
  249. self,
  250. listener: smol::net::TcpListener,
  251. ) -> io::Result<(TlsAcceptor, smol::net::TcpListener)> {
  252. Ok((TlsAcceptor::from(self.server_config), listener))
  253. }
  254. }