forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompat.rs
More file actions
2139 lines (1943 loc) · 82.1 KB
/
Copy pathcompat.rs
File metadata and controls
2139 lines (1943 loc) · 82.1 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// spell-checker: ignore webpki ssleof sslerror akid certsign sslerr aesgcm
// OpenSSL compatibility layer for rustls
//
// This module provides OpenSSL-like abstractions over rustls APIs,
// making the code more readable and maintainable. Each function is named
// after its OpenSSL equivalent (e.g., ssl_do_handshake corresponds to SSL_do_handshake).
// SSL error code data tables (shared with OpenSSL backend for compatibility)
// These map OpenSSL error codes to human-readable strings
#[allow(
clippy::duplicate_mod,
reason = "This is duplicated only when running clippy. The two features are mutually exclusive"
)]
#[path = "../openssl/ssl_data_31.rs"]
mod ssl_data;
use crate::socket::{SockWaitKind, timeout_error_msg};
use crate::vm::VirtualMachine;
use alloc::sync::Arc;
use parking_lot::RwLock as ParkingRwLock;
use rustls::Connection;
use rustls::client::ClientConfig;
use rustls::crypto::{CryptoProvider, SupportedKxGroup};
use rustls::pki_types::{CertificateDer, CertificateRevocationListDer, PrivateKeyDer};
use rustls::server::{ProducesTickets, ResolvesServerCert, ServerConfig, WebPkiClientVerifier};
use rustls::sign::CertifiedKey;
use rustls::{RootCertStore, SupportedCipherSuite};
use rustpython_vm::builtins::{PyBaseException, PyBaseExceptionRef};
use rustpython_vm::convert::IntoPyException;
use rustpython_vm::function::ArgBytesLike;
use rustpython_vm::{AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject};
use std::io::Read;
use super::providers::CryptoExt;
// Import PySSLSocket from parent module
use super::_ssl::{
PySSLSocket, SSL3_RT_MAX_PACKET_SIZE, VERIFY_X509_PARTIAL_CHAIN, VERIFY_X509_STRICT,
};
// Import error types and helper functions from error module
use super::error::{
PySSLCertVerificationError, PySSLError, create_ssl_eof_error, create_ssl_syscall_error,
create_ssl_want_read_error, create_ssl_want_write_error, create_ssl_zero_return_error,
};
// OpenSSL Constants:
// OpenSSL error library codes (include/openssl/err.h)
// #define ERR_LIB_SSL 20
const ERR_LIB_SSL: i32 = 20;
// OpenSSL SSL error reason codes (include/openssl/sslerr.h)
// #define SSL_R_NO_SHARED_CIPHER 193
const SSL_R_NO_SHARED_CIPHER: i32 = 193;
// OpenSSL X509 verification flags (include/openssl/x509_vfy.h)
// #define X509_V_FLAG_CRL_CHECK 4
const X509_V_FLAG_CRL_CHECK: i32 = 4;
// X509 Certificate Verification Error Codes (OpenSSL Compatible):
//
// These constants match OpenSSL's X509_V_ERR_* values for certificate
// verification. They are used to map rustls certificate errors to OpenSSL
// error codes for compatibility.
pub(super) const X509_V_ERR_UNSPECIFIED: i32 = 1;
pub(super) const X509_V_ERR_UNABLE_TO_GET_CRL: i32 = 3;
pub(super) const X509_V_ERR_CERT_NOT_YET_VALID: i32 = 9;
pub(super) const X509_V_ERR_CERT_HAS_EXPIRED: i32 = 10;
pub(super) const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: i32 = 20;
pub(super) const X509_V_ERR_CERT_REVOKED: i32 = 23;
pub(super) const X509_V_ERR_INVALID_PURPOSE: i32 = 26;
pub(super) const X509_V_ERR_HOSTNAME_MISMATCH: i32 = 62;
pub(super) const X509_V_ERR_IP_ADDRESS_MISMATCH: i32 = 64;
// Certificate Error Conversion Functions:
/// Convert rustls CertificateError to X509 verification code and message
///
/// Maps rustls certificate errors to OpenSSL X509_V_ERR_* codes for compatibility.
/// Returns (verify_code, verify_message) tuple.
fn rustls_cert_error_to_verify_info(cert_err: &rustls::CertificateError) -> (i32, &'static str) {
use rustls::CertificateError;
match cert_err {
CertificateError::UnknownIssuer => (
X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY,
"unable to get local issuer certificate",
),
CertificateError::Expired => (X509_V_ERR_CERT_HAS_EXPIRED, "certificate has expired"),
CertificateError::NotValidYet => (
X509_V_ERR_CERT_NOT_YET_VALID,
"certificate is not yet valid",
),
CertificateError::Revoked => (X509_V_ERR_CERT_REVOKED, "certificate revoked"),
CertificateError::UnknownRevocationStatus => (
X509_V_ERR_UNABLE_TO_GET_CRL,
"unable to get certificate CRL",
),
CertificateError::InvalidPurpose => (
X509_V_ERR_INVALID_PURPOSE,
"unsupported certificate purpose",
),
CertificateError::Other(other_err) => {
// Check if this is a hostname mismatch error from our verify_hostname function
let err_msg = format!("{other_err:?}");
if err_msg.contains("Hostname mismatch") || err_msg.contains("not valid for") {
(
X509_V_ERR_HOSTNAME_MISMATCH,
"Hostname mismatch, certificate is not valid for",
)
} else if err_msg.contains("IP address mismatch") {
(
X509_V_ERR_IP_ADDRESS_MISMATCH,
"IP address mismatch, certificate is not valid for",
)
} else {
(X509_V_ERR_UNSPECIFIED, "certificate verification failed")
}
}
_ => (X509_V_ERR_UNSPECIFIED, "certificate verification failed"),
}
}
/// Create SSLCertVerificationError with proper attributes
///
/// Matches CPython's _ssl.c fill_and_set_sslerror() behavior.
/// This function creates a Python SSLCertVerificationError exception with verify_code
/// and verify_message attributes set appropriately for the given rustls certificate error.
///
/// # Note
/// If attribute setting fails (extremely rare), returns the exception without attributes
pub(super) fn create_ssl_cert_verification_error(
vm: &VirtualMachine,
cert_err: &rustls::CertificateError,
) -> PyResult<PyBaseExceptionRef> {
let (verify_code, verify_message) = rustls_cert_error_to_verify_info(cert_err);
let msg =
format!("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: {verify_message}",);
let exc = vm.new_os_subtype_error(
PySSLCertVerificationError::class(&vm.ctx).to_owned(),
None,
msg,
);
// Set verify_code and verify_message attributes
// Ignore errors as they're extremely rare (e.g., out of memory)
exc.as_object().set_attr(
"verify_code",
vm.ctx.new_int(verify_code).as_object().to_owned(),
vm,
)?;
exc.as_object().set_attr(
"verify_message",
vm.ctx.new_str(verify_message).as_object().to_owned(),
vm,
)?;
exc.as_object()
.set_attr("library", vm.ctx.new_str("SSL").as_object().to_owned(), vm)?;
exc.as_object().set_attr(
"reason",
vm.ctx
.new_str("CERTIFICATE_VERIFY_FAILED")
.as_object()
.to_owned(),
vm,
)?;
Ok(exc.upcast())
}
/// Error types matching OpenSSL error codes
#[derive(Debug)]
pub(super) enum SslError {
/// SSL_ERROR_WANT_READ
WantRead,
/// SSL_ERROR_WANT_WRITE
WantWrite,
/// SSL_ERROR_SYSCALL
Syscall(String),
/// SSL_ERROR_SSL
Ssl(String),
/// SSL_ERROR_ZERO_RETURN (clean closure with close_notify)
ZeroReturn,
/// Unexpected EOF without close_notify (protocol violation)
Eof,
/// Non-TLS data received before handshake completed
PreauthData,
/// Certificate verification error
CertVerification(rustls::CertificateError),
/// I/O error
Io(std::io::Error),
/// Timeout error (socket.timeout)
Timeout(String),
/// SNI callback triggered - need to restart handshake
SniCallbackRestart,
/// Python exception (pass through directly)
Py(PyBaseExceptionRef),
/// TLS alert received with OpenSSL-compatible error code
AlertReceived { lib: i32, reason: i32 },
/// NO_SHARED_CIPHER error (OpenSSL SSL_R_NO_SHARED_CIPHER)
NoCipherSuites,
}
impl SslError {
/// Convert TLS alert code to OpenSSL error reason code
/// OpenSSL uses reason = 1000 + alert_code for TLS alerts
fn alert_to_openssl_reason(alert: rustls::AlertDescription) -> i32 {
// AlertDescription can be converted to u8 via as u8 cast
1000 + (u8::from(alert) as i32)
}
/// Convert rustls error to SslError
pub(super) fn from_rustls(err: rustls::Error) -> Self {
match err {
rustls::Error::InvalidCertificate(cert_err) => Self::CertVerification(cert_err),
rustls::Error::AlertReceived(alert_desc) => {
// Map TLS alerts to OpenSSL-compatible error codes
// lib = 20 (ERR_LIB_SSL), reason = 1000 + alert_code
match alert_desc {
rustls::AlertDescription::CloseNotify => {
// Special case: close_notify is handled as ZeroReturn
Self::ZeroReturn
}
_ => {
// All other alerts: convert to OpenSSL error code
// This includes InternalError (80 -> reason 1080)
Self::AlertReceived {
lib: ERR_LIB_SSL,
reason: Self::alert_to_openssl_reason(alert_desc),
}
}
}
}
// OpenSSL 3.0 changed transport EOF from SSL_ERROR_SYSCALL with
// zero return value to SSL_ERROR_SSL with SSL_R_UNEXPECTED_EOF_WHILE_READING.
// In rustls, these cases correspond to unexpected connection closure:
rustls::Error::InvalidMessage(_) => {
// UnexpectedMessage, CorruptMessage, etc. → SSLEOFError
// Matches CPython's "EOF occurred in violation of protocol"
Self::Eof
}
rustls::Error::PeerIncompatible(peer_err) => {
// Check for specific incompatibility types
use rustls::PeerIncompatible;
match peer_err {
PeerIncompatible::NoCipherSuitesInCommon => {
// Maps to OpenSSL SSL_R_NO_SHARED_CIPHER (lib=20, reason=193)
Self::NoCipherSuites
}
_ => {
// Other protocol incompatibilities → SSLEOFError
Self::Eof
}
}
}
_ => Self::Ssl(format!("{err}")),
}
}
/// Create SSLError with library and reason from string values
///
/// This is the base helper for creating SSLError with _library and _reason
/// attributes when you already have the string values.
///
/// # Arguments
/// * `vm` - Virtual machine reference
/// * `library` - Library name (e.g., "PEM", "SSL")
/// * `reason` - Error reason (e.g., "PEM lib", "NO_SHARED_CIPHER")
/// * `message` - Main error message
///
/// # Returns
/// PyBaseExceptionRef with _library and _reason attributes set
///
/// # Note
/// If attribute setting fails (extremely rare), returns the exception without attributes
pub(super) fn create_ssl_error_with_reason(
vm: &VirtualMachine,
library: Option<&str>,
reason: &str,
message: impl Into<String>,
) -> PyBaseExceptionRef {
let msg = message.into();
// SSLError args should be (errno, message) format
// FIXME: Use 1 as generic SSL error code
let exc = vm.new_os_subtype_error(PySSLError::class(&vm.ctx).to_owned(), Some(1), msg);
// Set library and reason attributes
// Ignore errors as they're extremely rare (e.g., out of memory)
let library_obj = match library {
Some(lib) => vm.ctx.new_str(lib).as_object().to_owned(),
None => vm.ctx.none(),
};
let _ = exc.as_object().set_attr("library", library_obj, vm);
let _ =
exc.as_object()
.set_attr("reason", vm.ctx.new_str(reason).as_object().to_owned(), vm);
exc.upcast()
}
/// Create SSLError with library and reason from ssl_data codes
///
/// This helper converts OpenSSL numeric error codes to Python SSLError exceptions
/// with proper _library and _reason attributes by looking up the error strings
/// in ssl_data tables, then delegates to create_ssl_error_with_reason.
///
/// # Arguments
/// * `vm` - Virtual machine reference
/// * `lib` - OpenSSL library code (e.g., ERR_LIB_SSL = 20)
/// * `reason` - OpenSSL reason code (e.g., SSL_R_NO_SHARED_CIPHER = 193)
///
/// # Returns
/// PyBaseExceptionRef with _library and _reason attributes set
fn create_ssl_error_from_codes(
vm: &VirtualMachine,
lib: i32,
reason: i32,
) -> PyBaseExceptionRef {
// Look up error strings from ssl_data tables
let key = ssl_data::encode_error_key(lib, reason);
let reason_str = ssl_data::ERROR_CODES
.get(&key)
.copied()
.unwrap_or("unknown error");
let lib_str = ssl_data::LIBRARY_CODES
.get(&(lib as u32))
.copied()
.unwrap_or("UNKNOWN");
// Delegate to create_ssl_error_with_reason for actual exception creation
Self::create_ssl_error_with_reason(
vm,
Some(lib_str),
reason_str,
format!("[SSL] {reason_str}"),
)
}
/// Convert to Python exception
pub(super) fn into_py_err(self, vm: &VirtualMachine) -> PyBaseExceptionRef {
match self {
Self::WantRead => create_ssl_want_read_error(vm).upcast(),
Self::WantWrite => create_ssl_want_write_error(vm).upcast(),
Self::Timeout(msg) => timeout_error_msg(vm, msg).upcast(),
Self::Syscall(msg) => {
// SSLSyscallError with errno=SSL_ERROR_SYSCALL (5)
create_ssl_syscall_error(vm, msg).upcast()
}
Self::Ssl(msg) => vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
format!("SSL error: {msg}"),
)
.upcast(),
Self::ZeroReturn => create_ssl_zero_return_error(vm).upcast(),
Self::Eof => create_ssl_eof_error(vm).upcast(),
Self::PreauthData => {
// Non-TLS data received before handshake
Self::create_ssl_error_with_reason(
vm,
None,
"before TLS handshake with data",
"before TLS handshake with data",
)
}
Self::CertVerification(cert_err) => {
// Use the proper cert verification error creator
create_ssl_cert_verification_error(vm, &cert_err).expect("unlikely to happen")
}
Self::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => {
create_ssl_eof_error(vm).upcast()
}
Self::Io(err) if err.raw_os_error().is_none() => vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
format!("SSL error: {err}"),
)
.upcast(),
Self::Io(err) => err.into_pyexception(vm),
Self::SniCallbackRestart => {
// This should be handled at PySSLSocket level
unreachable!("SniCallbackRestart should not reach Python layer")
}
Self::Py(exc) => exc,
Self::AlertReceived { lib, reason } => {
Self::create_ssl_error_from_codes(vm, lib, reason)
}
Self::NoCipherSuites => {
// OpenSSL error: lib=20 (ERR_LIB_SSL), reason=193 (SSL_R_NO_SHARED_CIPHER)
Self::create_ssl_error_from_codes(vm, ERR_LIB_SSL, SSL_R_NO_SHARED_CIPHER)
}
}
}
}
pub(super) type SslResult<T> = Result<T, SslError>;
/// Common protocol settings shared between client and server connections
#[derive(Debug)]
pub(super) struct ProtocolSettings {
pub versions: &'static [&'static rustls::SupportedProtocolVersion],
pub kx_groups: Option<Vec<&'static dyn rustls::crypto::SupportedKxGroup>>,
pub cipher_suites: Option<Vec<rustls::SupportedCipherSuite>>,
pub alpn_protocols: Vec<Vec<u8>>,
}
/// Options for creating a server TLS configuration
#[derive(Debug)]
pub(super) struct ServerConfigOptions {
/// Common protocol settings (versions, ALPN, KX groups, cipher suites)
pub protocol_settings: ProtocolSettings,
/// Server certificate chain
pub cert_chain: Vec<CertificateDer<'static>>,
/// Server private key
pub private_key: PrivateKeyDer<'static>,
/// Root certificates for client verification (if required)
pub root_store: Option<RootCertStore>,
/// Whether to request client certificate
pub request_client_cert: bool,
/// Whether to use deferred client certificate validation (TLS 1.3)
pub use_deferred_validation: bool,
/// Custom certificate resolver (for SNI support)
pub cert_resolver: Option<Arc<dyn ResolvesServerCert>>,
/// Deferred certificate error storage (for TLS 1.3)
pub deferred_cert_error: Option<Arc<ParkingRwLock<Option<String>>>>,
/// Session storage for server-side session resumption
pub session_storage: Option<Arc<rustls::server::ServerSessionMemoryCache>>,
/// Shared ticketer for TLS 1.2 session tickets (stateless resumption)
pub ticketer: Option<Arc<dyn ProducesTickets>>,
}
/// Options for creating a client TLS configuration
#[derive(Debug)]
pub(super) struct ClientConfigOptions {
/// Common protocol settings (versions, ALPN, KX groups, cipher suites)
pub protocol_settings: ProtocolSettings,
/// Root certificates for server verification
pub root_store: Option<RootCertStore>,
/// DER-encoded CA certificates (for partial chain verification)
pub ca_certs_der: Vec<Vec<u8>>,
/// Client certificate chain (for mTLS)
pub cert_chain: Option<Vec<CertificateDer<'static>>>,
/// Client private key (for mTLS)
pub private_key: Option<PrivateKeyDer<'static>>,
/// Whether to verify server certificates (CERT_NONE disables verification)
pub verify_server_cert: bool,
/// Whether to check hostname against certificate (check_hostname)
pub check_hostname: bool,
/// SSL verification flags (e.g., VERIFY_X509_STRICT)
pub verify_flags: i32,
/// Session store for client-side session resumption
pub session_store: Option<Arc<dyn rustls::client::ClientSessionStore>>,
/// Certificate Revocation Lists for CRL checking
pub crls: Vec<CertificateRevocationListDer<'static>>,
}
/// Create custom CryptoProvider with specified cipher suites and key exchange groups
///
/// This helper function consolidates the duplicated CryptoProvider creation logic
/// for both server and client configurations.
fn create_custom_crypto_provider(
cipher_suites: Option<Vec<SupportedCipherSuite>>,
kx_groups: Option<Vec<&'static dyn SupportedKxGroup>>,
) -> Arc<CryptoProvider> {
let default_provider = CryptoExt::get_provider();
Arc::new(CryptoProvider {
cipher_suites: cipher_suites.unwrap_or_else(|| default_provider.cipher_suites.clone()),
kx_groups: kx_groups.unwrap_or_else(|| default_provider.kx_groups.clone()),
signature_verification_algorithms: default_provider.signature_verification_algorithms,
secure_random: default_provider.secure_random,
key_provider: default_provider.key_provider,
})
}
/// Create a server TLS configuration
///
/// This abstracts the complex rustls ServerConfig building logic,
/// matching SSL_CTX initialization for server sockets.
pub(super) fn create_server_config(options: ServerConfigOptions) -> Result<ServerConfig, String> {
// Create custom crypto provider using helper function
let custom_provider = create_custom_crypto_provider(
options.protocol_settings.cipher_suites.clone(),
options.protocol_settings.kx_groups.clone(),
);
// Step 1: Build the appropriate client cert verifier based on settings
let client_cert_verifier: Option<Arc<dyn rustls::server::danger::ClientCertVerifier>> =
if let Some(root_store) = options.root_store {
if options.request_client_cert {
// Client certificate verification required
let base_verifier = WebPkiClientVerifier::builder(Arc::new(root_store))
.build()
.map_err(|e| format!("Failed to create client verifier: {e}"))?;
if options.use_deferred_validation {
// TLS 1.3: Use deferred validation
if let Some(deferred_error) = options.deferred_cert_error {
use crate::ssl::cert::DeferredClientCertVerifier;
let deferred_verifier =
DeferredClientCertVerifier::new(base_verifier, deferred_error);
Some(Arc::new(deferred_verifier))
} else {
// No deferred error storage provided, use immediate validation
Some(base_verifier)
}
} else {
// TLS 1.2 or non-deferred: Use immediate validation
Some(base_verifier)
}
} else {
// No client authentication
None
}
} else {
// No root store - no client authentication
None
};
// Step 2: Create ServerConfig builder once with the selected verifier
let builder = ServerConfig::builder_with_provider(custom_provider)
.with_protocol_versions(options.protocol_settings.versions)
.map_err(|e| format!("Failed to create server config builder: {e}"))?;
let builder = if let Some(verifier) = client_cert_verifier {
builder.with_client_cert_verifier(verifier)
} else {
builder.with_no_client_auth()
};
// Add certificate
let mut config = if let Some(resolver) = options.cert_resolver {
// Use custom cert resolver (e.g., for SNI)
builder.with_cert_resolver(resolver)
} else {
// Use single certificate
builder
.with_single_cert(options.cert_chain, options.private_key)
.map_err(|e| format!("Failed to set server certificate: {e}"))?
};
// Set ALPN protocols with fallback
apply_alpn_with_fallback(
&mut config.alpn_protocols,
&options.protocol_settings.alpn_protocols,
);
// Set session storage for server-side session resumption (TLS 1.3)
if let Some(session_storage) = options.session_storage {
config.session_storage = session_storage;
}
// Set ticketer for TLS 1.2 session tickets (stateless resumption)
if let Some(ticketer) = options.ticketer {
config.ticketer = ticketer.clone();
}
Ok(config)
}
/// Build WebPki verifier with CRL support
///
/// This helper function consolidates the duplicated CRL setup logic for both
/// check_hostname=True and check_hostname=False cases.
fn build_webpki_verifier_with_crls(
root_store: Arc<RootCertStore>,
crls: Vec<CertificateRevocationListDer<'static>>,
verify_flags: i32,
) -> Result<Arc<dyn rustls::client::danger::ServerCertVerifier>, String> {
use rustls::client::WebPkiServerVerifier;
let mut verifier_builder = WebPkiServerVerifier::builder(root_store);
// Check if CRL verification is requested
let crl_check_requested = verify_flags & X509_V_FLAG_CRL_CHECK != 0;
let has_crls = !crls.is_empty();
// Add CRLs if provided OR if CRL checking is explicitly requested
// (even with empty CRLs, rustls will fail verification if CRL checking is enabled)
if has_crls || crl_check_requested {
verifier_builder = verifier_builder.with_crls(crls);
// Check if we should only verify end-entity (leaf) certificates
if verify_flags & X509_V_FLAG_CRL_CHECK != 0 {
verifier_builder = verifier_builder.only_check_end_entity_revocation();
}
}
let webpki_verifier = verifier_builder
.build()
.map_err(|e| format!("Failed to build WebPkiServerVerifier: {e}"))?;
Ok(webpki_verifier as Arc<dyn rustls::client::danger::ServerCertVerifier>)
}
/// Apply verifier wrappers (CRLCheckVerifier and StrictCertVerifier)
///
/// This helper function consolidates the duplicated verifier wrapping logic.
fn apply_verifier_wrappers(
verifier: Arc<dyn rustls::client::danger::ServerCertVerifier>,
verify_flags: i32,
has_crls: bool,
ca_certs_der: Vec<Vec<u8>>,
) -> Arc<dyn rustls::client::danger::ServerCertVerifier> {
let crl_check_requested = verify_flags & X509_V_FLAG_CRL_CHECK != 0;
// Wrap with CRLCheckVerifier to enforce CRL checking when flags are set
let verifier = if crl_check_requested {
use crate::ssl::cert::CRLCheckVerifier;
Arc::new(CRLCheckVerifier::new(
verifier,
has_crls,
crl_check_requested,
))
} else {
verifier
};
// Always use PartialChainVerifier when trust store is not empty
// This allows self-signed certificates in trust store to be trusted
// (OpenSSL behavior: self-signed certs are always trusted, non-self-signed require flag)
let verifier = if !ca_certs_der.is_empty() {
use crate::ssl::cert::PartialChainVerifier;
Arc::new(PartialChainVerifier::new(
verifier,
ca_certs_der,
verify_flags,
))
} else {
verifier
};
// Wrap with StrictCertVerifier if VERIFY_X509_STRICT flag is set
if verify_flags & VERIFY_X509_STRICT != 0 {
Arc::new(super::cert::StrictCertVerifier::new(verifier, verify_flags))
} else {
verifier
}
}
/// Apply ALPN protocols
///
/// OpenSSL 1.1.0f+ allows ALPN negotiation to fail without aborting handshake.
/// rustls follows RFC 7301 strictly and rejects connections with no matching protocol.
/// To emulate OpenSSL behavior, we add a special fallback protocol (null byte).
fn apply_alpn_with_fallback(config_alpn: &mut Vec<Vec<u8>>, alpn_protocols: &[Vec<u8>]) {
if !alpn_protocols.is_empty() {
*config_alpn = alpn_protocols.to_vec();
config_alpn.push(vec![0u8]); // Add null byte as fallback marker
}
}
/// Create a client TLS configuration
///
/// This abstracts the complex rustls ClientConfig building logic,
/// matching SSL_CTX initialization for client sockets.
pub(super) fn create_client_config(options: ClientConfigOptions) -> Result<ClientConfig, String> {
// Create custom crypto provider using helper function
let custom_provider = create_custom_crypto_provider(
options.protocol_settings.cipher_suites.clone(),
options.protocol_settings.kx_groups.clone(),
);
// Step 1: Build the appropriate verifier based on verification settings
let verifier: Arc<dyn rustls::client::danger::ServerCertVerifier> = if options
.verify_server_cert
{
// Verify server certificates
let root_store = options
.root_store
.ok_or("Root store required for server verification")?;
let root_store_arc = Arc::new(root_store);
// Check if root_store is empty (no CA certs loaded)
// CPython allows this and fails during handshake with SSLCertVerificationError
if root_store_arc.is_empty() {
// Use EmptyRootStoreVerifier - always fails with UnknownIssuer during handshake
use crate::ssl::cert::EmptyRootStoreVerifier;
Arc::new(EmptyRootStoreVerifier)
} else {
// Calculate has_crls once for both hostname verification paths
let has_crls = !options.crls.is_empty();
if options.check_hostname {
// Default behavior: verify both certificate chain and hostname
let base_verifier = build_webpki_verifier_with_crls(
root_store_arc,
options.crls,
options.verify_flags,
)?;
// Apply CRL and Strict verifier wrappers using helper function
apply_verifier_wrappers(
base_verifier,
options.verify_flags,
has_crls,
options.ca_certs_der.clone(),
)
} else {
// check_hostname=False: verify certificate chain but ignore hostname
use crate::ssl::cert::HostnameIgnoringVerifier;
// Build verifier with CRL support using helper function
let webpki_verifier = build_webpki_verifier_with_crls(
root_store_arc,
options.crls,
options.verify_flags,
)?;
// Apply CRL verifier wrapper if needed (without Strict wrapper yet)
let crl_check_requested = options.verify_flags & X509_V_FLAG_CRL_CHECK != 0;
let verifier = if crl_check_requested {
use crate::ssl::cert::CRLCheckVerifier;
Arc::new(CRLCheckVerifier::new(
webpki_verifier,
has_crls,
crl_check_requested,
)) as Arc<dyn rustls::client::danger::ServerCertVerifier>
} else {
webpki_verifier
};
// Wrap with PartialChainVerifier if VERIFY_X509_PARTIAL_CHAIN is set
let verifier = if options.verify_flags & VERIFY_X509_PARTIAL_CHAIN != 0 {
use crate::ssl::cert::PartialChainVerifier;
Arc::new(PartialChainVerifier::new(
verifier,
options.ca_certs_der.clone(),
options.verify_flags,
)) as Arc<dyn rustls::client::danger::ServerCertVerifier>
} else {
verifier
};
// Wrap with HostnameIgnoringVerifier to bypass hostname checking
let hostname_ignoring_verifier: Arc<
dyn rustls::client::danger::ServerCertVerifier,
> = Arc::new(HostnameIgnoringVerifier::new_with_verifier(verifier));
// Apply Strict verifier wrapper once at the end if needed
if options.verify_flags & VERIFY_X509_STRICT != 0 {
Arc::new(crate::ssl::cert::StrictCertVerifier::new(
hostname_ignoring_verifier,
options.verify_flags,
))
} else {
hostname_ignoring_verifier
}
}
}
} else {
// CERT_NONE: disable all verification
use crate::ssl::cert::NoVerifier;
Arc::new(NoVerifier)
};
// Step 2: Create ClientConfig builder once with the selected verifier
let builder = ClientConfig::builder_with_provider(custom_provider)
.with_protocol_versions(options.protocol_settings.versions)
.map_err(|e| format!("Failed to create client config builder: {e}"))?
.dangerous()
.with_custom_certificate_verifier(verifier);
// Add client certificate if provided (mTLS)
let mut config =
if let (Some(cert_chain), Some(private_key)) = (options.cert_chain, options.private_key) {
builder
.with_client_auth_cert(cert_chain, private_key)
.map_err(|e| format!("Failed to set client certificate: {e}"))?
} else {
builder.with_no_client_auth()
};
// Set ALPN protocols
apply_alpn_with_fallback(
&mut config.alpn_protocols,
&options.protocol_settings.alpn_protocols,
);
// Set session resumption
if let Some(session_store) = options.session_store {
use rustls::client::Resumption;
config.resumption = Resumption::store(session_store);
}
Ok(config)
}
/// Helper function - check if error is BlockingIOError
pub(super) fn is_blocking_io_error(err: &Py<PyBaseException>, vm: &VirtualMachine) -> bool {
err.fast_isinstance(vm.ctx.exceptions.blocking_io_error)
}
// Socket I/O Helper Functions
/// Send all bytes to socket, handling partial sends with blocking wait
///
/// Loops until all bytes are sent. For blocking sockets, this will wait
/// until all data is sent. For non-blocking sockets, returns WantWrite
/// if no progress can be made.
/// Optional deadline parameter allows respecting a read deadline during flush.
fn send_all_bytes(
socket: &PySSLSocket,
buf: Vec<u8>,
vm: &VirtualMachine,
deadline: Option<std::time::Instant>,
) -> SslResult<()> {
// First, flush any previously pending TLS data with deadline
socket
.flush_pending_tls_output(vm, deadline)
.map_err(SslError::Py)?;
if buf.is_empty() {
return Ok(());
}
let mut sent_total = 0;
while sent_total < buf.len() {
// Check deadline before each send attempt
if let Some(dl) = deadline
&& std::time::Instant::now() >= dl
{
socket
.pending_tls_output
.lock()
.extend_from_slice(&buf[sent_total..]);
return Err(SslError::Timeout("The operation timed out".to_string()));
}
// Wait for socket to be writable before sending
let timed_out = if let Some(dl) = deadline {
let now = std::time::Instant::now();
if now >= dl {
socket
.pending_tls_output
.lock()
.extend_from_slice(&buf[sent_total..]);
return Err(SslError::Timeout(
"The write operation timed out".to_string(),
));
}
socket
.sock_wait_for_io_with_timeout(SockWaitKind::Write, Some(dl - now), vm)
.map_err(SslError::Py)?
} else {
socket
.sock_wait_for_io_impl(SockWaitKind::Write, vm)
.map_err(SslError::Py)?
};
if timed_out {
socket
.pending_tls_output
.lock()
.extend_from_slice(&buf[sent_total..]);
return Err(SslError::Timeout(
"The write operation timed out".to_string(),
));
}
match socket.sock_send(&buf[sent_total..], vm) {
Ok(result) => {
let sent: usize = result
.try_to_value::<isize>(vm)
.map_err(SslError::Py)?
.try_into()
.map_err(|_| SslError::Syscall("Invalid send return value".to_string()))?;
if sent == 0 {
// No progress - save unsent bytes to pending buffer
socket
.pending_tls_output
.lock()
.extend_from_slice(&buf[sent_total..]);
return Err(SslError::WantWrite);
}
sent_total += sent;
}
Err(e) => {
if is_blocking_io_error(&e, vm) {
// Save unsent bytes to pending buffer
socket
.pending_tls_output
.lock()
.extend_from_slice(&buf[sent_total..]);
return Err(SslError::WantWrite);
}
// For other errors, also save unsent bytes
socket
.pending_tls_output
.lock()
.extend_from_slice(&buf[sent_total..]);
return Err(SslError::Py(e));
}
}
}
Ok(())
}
// Handshake Helper Functions
/// Write TLS handshake data to socket/BIO
///
/// Drains all pending TLS data from rustls and sends it to the peer.
/// Returns whether any progress was made.
fn handshake_write_loop(
conn: &mut Connection,
socket: &PySSLSocket,
force_initial_write: bool,
vm: &VirtualMachine,
) -> SslResult<bool> {
let mut made_progress = false;
// Flush any previously pending TLS data before generating new output
// Must succeed before sending new data to maintain order
socket
.flush_pending_tls_output(vm, None)
.map_err(SslError::Py)?;
while conn.wants_write() || force_initial_write {
if force_initial_write && !conn.wants_write() {
// No data to write on first iteration - break to avoid infinite loop
break;
}
let mut buf = Vec::new();
let written = conn
.write_tls(&mut buf as &mut dyn std::io::Write)
.map_err(SslError::Io)?;
if written > 0 && !buf.is_empty() {
// Send all bytes to socket, handling partial sends
send_all_bytes(socket, buf, vm, None)?;
made_progress = true;
} else if written == 0 {
// No data written but wants_write is true - should not happen normally
// Break to avoid infinite loop
break;
}
// Check if there's more to write
if !conn.wants_write() {
break;
}
}
Ok(made_progress)
}
/// Read at most one TLS record from the TCP socket.
///
/// May return incomplete data but never returns more when completes a
/// previously incomplete TLS record.
///
/// OpenSSL reads one TLS record at a time (no read-ahead by default).
/// Rustls, however, consumes all available TCP data when fed via read_tls().
/// If a close_notify or other control record arrives alongside application
/// data, the eager read drains the TCP buffer, leaving the control record in
/// rustls's internal buffer where select() cannot see it. This causes
/// asyncore-based servers (which rely on select() for readability) to miss
/// the data and the peer times out.
///
/// Fix: peek at the TCP buffer to find the first complete TLS record boundary
/// and recv() only that many bytes. Any remaining data stays in the kernel
/// buffer and remains visible to select().
fn recv_at_most_one_tls_record(
socket: &PySSLSocket,
vm: &VirtualMachine,
) -> SslResult<PyObjectRef> {
let bytes = socket.sock_recv_at_most_one_tls_record(vm).map_err(|e| {
if is_blocking_io_error(&e, vm) {
SslError::WantRead
} else {
SslError::Py(e)
}
})?;
if bytes.is_empty() {
Err(SslError::Eof)
} else {
Ok(bytes.into())
}
}
/// Read up to a single TLS record for post-handshake I/O while preserving the
/// SSL-vs-socket error precedence from the old sock_recv() path.
fn recv_at_most_one_tls_record_for_data(
conn: &mut Connection,
socket: &PySSLSocket,
vm: &VirtualMachine,
) -> SslResult<PyObjectRef> {
match recv_at_most_one_tls_record(socket, vm) {
Ok(data) => Ok(data),
Err(SslError::Eof) => {