@@ -15,21 +15,20 @@ use crate::socket::{SelectKind, timeout_error_msg};
1515use crate :: vm:: VirtualMachine ;
1616use alloc:: sync:: Arc ;
1717use parking_lot:: RwLock as ParkingRwLock ;
18- use rustls:: RootCertStore ;
19- use rustls:: client:: ClientConfig ;
20- use rustls:: client:: ClientConnection ;
21- use rustls:: crypto:: SupportedKxGroup ;
18+ use rustls:: client:: { ClientConfig , ClientConnection } ;
19+ use rustls:: crypto:: { CryptoProvider , SupportedKxGroup } ;
2220use rustls:: pki_types:: { CertificateDer , CertificateRevocationListDer , PrivateKeyDer } ;
23- use rustls:: server:: ResolvesServerCert ;
24- use rustls:: server:: ServerConfig ;
25- use rustls:: server:: ServerConnection ;
26- use rustls:: sign:: CertifiedKey ;
21+ use rustls:: server:: {
22+ ProducesTickets , ResolvesServerCert , ServerConfig , ServerConnection , WebPkiClientVerifier ,
23+ } ;
24+ use rustls:: sign:: { CertifiedKey , SigningKey } ;
25+ use rustls:: { RootCertStore , SignatureScheme , SupportedCipherSuite } ;
2726use rustpython_vm:: builtins:: { PyBaseException , PyBaseExceptionRef } ;
2827use rustpython_vm:: convert:: IntoPyException ;
2928use rustpython_vm:: function:: ArgBytesLike ;
3029use rustpython_vm:: { AsObject , Py , PyObjectRef , PyPayload , PyResult , TryFromObject } ;
3130use std:: io:: Read ;
32- use std:: sync:: Once ;
31+ use std:: sync:: OnceLock ;
3332
3433// Import PySSLSocket from parent module
3534use super :: _ssl:: PySSLSocket ;
@@ -55,16 +54,120 @@ pub(super) const VERIFY_X509_PARTIAL_CHAIN: i32 = 0x80000;
5554/// Ensure the default CryptoProvider is installed (thread-safe, runs once)
5655///
5756/// This is necessary because rustls 0.23+ requires a process-level CryptoProvider
58- /// to be installed before using default_provider(). We use Once to ensure this
57+ /// to be installed before using default_provider(). We use OnceLock to ensure this
5958/// happens exactly once, even if called from multiple threads.
60- static INIT_PROVIDER : Once = Once :: new ( ) ;
61-
62- pub ( super ) fn ensure_default_provider ( ) {
63- INIT_PROVIDER . call_once ( || {
64- let _ = rustls:: crypto:: CryptoProvider :: install_default (
65- rustls:: crypto:: aws_lc_rs:: default_provider ( ) ,
66- ) ;
67- } ) ;
59+ pub ( super ) static CRYPTO_EXT : OnceLock < CryptoExt > = OnceLock :: new ( ) ;
60+
61+ #[ derive( Clone , Copy ) ]
62+ pub struct CryptoExt {
63+ pub all_cipher_suites : Option < & ' static [ SupportedCipherSuite ] > ,
64+ pub all_kx_groups : Option < & ' static [ & ' static dyn SupportedKxGroup ] > ,
65+ #[ allow( clippy:: type_complexity) ]
66+ pub any_supported_key :
67+ Option < fn ( & PrivateKeyDer < ' _ > ) -> Result < Arc < dyn SigningKey > , rustls:: Error > > ,
68+ pub ticketer : fn ( ) -> Result < Arc < dyn ProducesTickets > , rustls:: Error > ,
69+ }
70+
71+ impl CryptoExt {
72+ /// Returns all [`SupportedCipherSuite`] or the provider's defaults.
73+ ///
74+ /// # Panics
75+ /// Panics if a [`CryptoProvider`] hasn't been set.
76+ #[ must_use]
77+ pub fn all_ciphers_or_default ( & self ) -> & ' static [ SupportedCipherSuite ] {
78+ self . all_cipher_suites . unwrap_or_else ( || {
79+ CryptoProvider :: get_default ( )
80+ . expect ( "A CryptoProvider has been set if CryptoExt is set" )
81+ . cipher_suites
82+ . as_slice ( )
83+ } )
84+ }
85+
86+ /// Returns all [`SupportedKxGroup`] or the provider's defaults.
87+ ///
88+ /// # Panics
89+ /// Panics if a [`CryptoProvider`] hasn't been set.
90+ #[ must_use]
91+ pub fn all_kx_or_default ( & self ) -> & ' static [ & ' static dyn SupportedKxGroup ] {
92+ self . all_kx_groups . unwrap_or_else ( || {
93+ CryptoProvider :: get_default ( )
94+ . expect ( "A CryptoProvider has been set if CryptoExt is set" )
95+ . kx_groups
96+ . as_slice ( )
97+ } )
98+ }
99+
100+ /// Return the first supported [`SigningKey`] for a [`PrivateKeyDer`].
101+ ///
102+ /// Ideally, this function should be provided by the backend implementation or
103+ /// the user. This fallback filters out insecure algorithms then picks the first available key
104+ /// if it exists.
105+ ///
106+ /// # Panics
107+ /// Panics if a [`CryptoProvider`] hasn't been set.
108+ pub fn any_supported_key (
109+ & self ,
110+ der : & PrivateKeyDer < ' _ > ,
111+ ) -> Result < Arc < dyn SigningKey > , rustls:: Error > {
112+ self . any_supported_key . map ( |f| f ( der) ) . unwrap_or_else ( || {
113+ let provider = CryptoProvider :: get_default ( )
114+ . expect ( "A CryptoProvider has been set if CryptoExt is set" ) ;
115+ let key = provider. key_provider . load_private_key ( der. clone_key ( ) ) ?;
116+
117+ for scheme in provider
118+ . signature_verification_algorithms
119+ . mapping
120+ . iter ( )
121+ . filter_map ( |( scheme, _) | {
122+ ( !matches ! (
123+ scheme,
124+ SignatureScheme :: RSA_PKCS1_SHA1
125+ | SignatureScheme :: ECDSA_SHA1_Legacy
126+ | SignatureScheme :: Unknown ( _) ,
127+ ) )
128+ . then_some ( * scheme)
129+ } )
130+ {
131+ if key. choose_scheme ( & [ scheme] ) . is_some ( ) {
132+ return Ok ( key) ;
133+ }
134+ }
135+
136+ Err ( rustls:: Error :: General (
137+ "failed to parse private key as RSA, ECDSA, or EdDSA" . into ( ) ,
138+ ) )
139+ } )
140+ }
141+ }
142+
143+ /// Use AWS-LC as the default cryptography provider.
144+ #[ cfg( all( feature = "ssl-rustls" , not( feature = "ssl-rustls-no-provider" ) ) ) ]
145+ pub fn set_aws_lc_provider ( ) -> Result < ( ) , rustls:: Error > {
146+ use rustls:: crypto:: aws_lc_rs;
147+ let provider = aws_lc_rs:: default_provider ( ) ;
148+ let ext = CryptoExt {
149+ all_cipher_suites : Some ( aws_lc_rs:: ALL_CIPHER_SUITES ) ,
150+ all_kx_groups : Some ( aws_lc_rs:: ALL_KX_GROUPS ) ,
151+ any_supported_key : Some ( aws_lc_rs:: sign:: any_supported_type) ,
152+ ticketer : aws_lc_rs:: Ticketer :: new,
153+ } ;
154+ set_crypto_provider ( provider, ext)
155+ }
156+
157+ /// Set a process [`CryptoProvider`].
158+ ///
159+ /// A provider must be set before any cryptographic operations. All crypto ops panic if a provider
160+ /// is unset. See [`set_aws_lc_provider`] for the default provider.
161+ pub fn set_crypto_provider (
162+ provider : CryptoProvider ,
163+ extension : CryptoExt ,
164+ ) -> Result < ( ) , rustls:: Error > {
165+ provider
166+ . install_default ( )
167+ . map_err ( |_| rustls:: Error :: General ( "A default CryptoProvider is already set" . into ( ) ) ) ?;
168+ CRYPTO_EXT
169+ . set ( extension)
170+ . map_err ( |_| rustls:: Error :: General ( "A CryptoExt is already set" . into ( ) ) )
68171}
69172
70173// OpenSSL Constants:
@@ -662,13 +765,13 @@ pub(super) struct ClientConfigOptions {
662765/// This helper function consolidates the duplicated CryptoProvider creation logic
663766/// for both server and client configurations.
664767fn create_custom_crypto_provider (
665- cipher_suites : Option < Vec < rustls :: SupportedCipherSuite > > ,
666- kx_groups : Option < Vec < & ' static dyn rustls :: crypto :: SupportedKxGroup > > ,
667- ) -> Arc < rustls :: crypto :: CryptoProvider > {
668- let default_provider = rustls :: crypto :: CryptoProvider :: get_default ( )
669- . expect ( "A CryptoProvider should have been set earlier " ) ;
768+ cipher_suites : Option < Vec < SupportedCipherSuite > > ,
769+ kx_groups : Option < Vec < & ' static dyn SupportedKxGroup > > ,
770+ ) -> Arc < CryptoProvider > {
771+ let default_provider =
772+ CryptoProvider :: get_default ( ) . expect ( "A CryptoProvider must be set before SSL " ) ;
670773
671- Arc :: new ( rustls :: crypto :: CryptoProvider {
774+ Arc :: new ( CryptoProvider {
672775 cipher_suites : cipher_suites. unwrap_or_else ( || default_provider. cipher_suites . clone ( ) ) ,
673776 kx_groups : kx_groups. unwrap_or_else ( || default_provider. kx_groups . clone ( ) ) ,
674777 signature_verification_algorithms : default_provider. signature_verification_algorithms ,
@@ -682,11 +785,6 @@ fn create_custom_crypto_provider(
682785/// This abstracts the complex rustls ServerConfig building logic,
683786/// matching SSL_CTX initialization for server sockets.
684787pub ( super ) fn create_server_config ( options : ServerConfigOptions ) -> Result < ServerConfig , String > {
685- use rustls:: server:: WebPkiClientVerifier ;
686-
687- // Ensure default CryptoProvider is installed
688- ensure_default_provider ( ) ;
689-
690788 // Create custom crypto provider using helper function
691789 let custom_provider = create_custom_crypto_provider (
692790 options. protocol_settings . cipher_suites . clone ( ) ,
@@ -864,9 +962,6 @@ fn apply_alpn_with_fallback(config_alpn: &mut Vec<Vec<u8>>, alpn_protocols: &[Ve
864962/// This abstracts the complex rustls ClientConfig building logic,
865963/// matching SSL_CTX initialization for client sockets.
866964pub ( super ) fn create_client_config ( options : ClientConfigOptions ) -> Result < ClientConfig , String > {
867- // Ensure default CryptoProvider is installed
868- ensure_default_provider ( ) ;
869-
870965 // Create custom crypto provider using helper function
871966 let custom_provider = create_custom_crypto_provider (
872967 options. protocol_settings . cipher_suites . clone ( ) ,
@@ -2365,9 +2460,10 @@ pub(super) fn curve_name_to_kx_group(
23652460 curve : & str ,
23662461) -> Result < Vec < & ' static dyn SupportedKxGroup > , String > {
23672462 // Get the default crypto provider's key exchange groups
2368- let provider = rustls:: crypto:: CryptoProvider :: get_default ( )
2369- . expect ( "A CryptoProvider should have been set earlier" ) ;
2370- let all_groups = & provider. kx_groups ;
2463+ let crypto_ext = CRYPTO_EXT
2464+ . get ( )
2465+ . expect ( "A CryptoProvider must be set before SSL" ) ;
2466+ let all_groups = crypto_ext. all_kx_or_default ( ) ;
23712467
23722468 match curve {
23732469 // P-256 (also known as secp256r1 or prime256v1)
0 commit comments