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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
// spell-checker: ignore ssleof aesccm aesgcm capath getblocking setblocking ENDTLS TLSEXT
//! Pure Rust SSL/TLS implementation using rustls
//!
//! This module provides SSL/TLS support without requiring C dependencies.
//! It implements the Python ssl module API using:
//! - rustls: TLS protocol implementation
//! - x509-parser: Certificate parsing
//! - ring: Cryptographic primitives
//!
//! DO NOT add openssl dependency here.
//!
//! Warning: This library contains AI-generated code and comments. Do not trust any code or comment without verification. Please have a qualified expert review the code and remove this notice after review.
// Certificate operations module (parsing, validation, conversion)
mod cert;
// OpenSSL compatibility layer (abstracts rustls operations)
mod compat;
// SSL exception types (shared with openssl backend)
mod error;
mod handshake;
mod keylog;
mod msg;
pub use rustpython_host_env::ssl::{chain, cipher, oid, providers};
#[cfg(target_arch = "wasm32")]
mod sock_wait_stub {
use rustpython_vm::{PyRef, VirtualMachine, builtins::PyOSError};
#[derive(Copy, Clone)]
pub(crate) enum SockWaitKind {
Read,
Write,
#[allow(dead_code, reason = "kept in lockstep with the native wait kinds")]
Connect,
}
pub(crate) fn timeout_error_msg(vm: &VirtualMachine, msg: String) -> PyRef<PyOSError> {
vm.new_os_subtype_error(vm.ctx.exceptions.timeout_error.to_owned(), None, msg)
}
}
pub(crate) use _ssl::module_def;
#[allow(non_snake_case)]
#[allow(non_upper_case_globals)]
#[pymodule(with(error::ssl_error))]
mod _ssl {
use crate::{
common::{
hash::PyHash,
lock::{PyMutex, PyRwLock},
},
vm::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine,
builtins::{
PyBaseExceptionRef, PyBytesRef, PyListRef, PyStrRef, PyType, PyTypeRef,
PyUtf8StrRef, PyWeak,
},
convert::IntoPyException,
function::{
ArgBytesLike, ArgMemoryBuffer, Either, FsPath, FuncArgs, OptionalArg,
PyComparisonValue, PySetterValue,
},
stdlib::_warnings,
types::{Comparable, Constructor, Hashable, PyComparisonOp, Representable},
},
};
#[cfg(target_arch = "wasm32")]
use super::sock_wait_stub::{SockWaitKind, timeout_error_msg};
#[cfg(not(target_arch = "wasm32"))]
use crate::socket::{PySocket, SockWaitKind, sock_wait, timeout_error_msg};
// Import error types used in this module (others are exposed via pymodule(with(...)))
use super::error::{
PySSLError, PySSLWantReadError, PySSLWantWriteError, create_ssl_eof_error,
create_ssl_want_read_error, create_ssl_want_write_error, create_ssl_zero_return_error,
};
use alloc::sync::Arc;
use core::{
hash::{Hash, Hasher},
hint::cold_path,
sync::atomic::{AtomicUsize, Ordering},
time::Duration,
};
use rustpython_vm::exceptions;
use std::{
collections::{HashMap, hash_map::DefaultHasher},
time::SystemTime,
};
// Rustls imports
use parking_lot::RwLock as ParkingRwLock;
use pem_rfc7468::{LineEnding, encode_string};
use rustls::{
ClientConnection, Connection, HandshakeKind, RootCertStore,
crypto::SupportedKxGroup,
pki_types::{CertificateDer, CertificateRevocationListDer, PrivateKeyDer, ServerName},
server::{Accepted, ResolvesServerCert},
sign::CertifiedKey,
};
use rustpython_host_env::ssl::{
CapturingClientSessionStore, ClientSessionKind, RecordCursor, SessionCache, SessionData,
TlsConnection,
};
/// Caps unsent TLS so BIO writes stay inside asyncio's 64 KiB
/// socket-transport high-water mark when SO_SNDBUF is small.
const TLS_IO_BUFFER_LIMIT: Option<usize> = Some(4 * 1024);
// Import certificate operations module
use super::cert;
use rustpython_host_env::ssl::{
chain::{self, VerifiedChainBuilder},
cipher, oid,
providers::CryptoExt,
};
// Import compat module (OpenSSL compatibility layer)
use super::compat::{
ClientConfigOptions, MultiCertResolver, ProtocolSettings, ServerConfigOptions, SslError,
create_client_config, create_server_config, curve_name_to_kx_group, is_blocking_io_error,
ssl_do_handshake,
};
use super::handshake::TlsState;
// Type aliases for better readability
// Additional type alias for certificate/key pairs (SessionCache defined below)
/// Certificate and private key pair used in SSL contexts
type CertKeyPair = (Arc<CertifiedKey>, PrivateKeyDer<'static>);
type CapathStamp = (String, Option<SystemTime>);
type CapathCache = (Vec<CapathStamp>, Arc<Vec<Vec<u8>>>);
#[derive(Debug, Default)]
struct CapathState {
directories: Vec<String>,
cache: Option<CapathCache>,
}
// Constants matching Python ssl module
// SSL/TLS Protocol versions
#[pyattr]
const PROTOCOL_TLS: i32 = rustpython_host_env::ssl::PROTOCOL_TLS; // Auto-negotiate best version
#[pyattr]
const PROTOCOL_SSLv23: i32 = PROTOCOL_TLS; // Alias for PROTOCOL_TLS
#[pyattr]
const PROTOCOL_TLS_CLIENT: i32 = rustpython_host_env::ssl::PROTOCOL_TLS_CLIENT;
#[pyattr]
const PROTOCOL_TLS_SERVER: i32 = rustpython_host_env::ssl::PROTOCOL_TLS_SERVER;
// Note: rustls doesn't support TLS 1.0/1.1 for security reasons
// These are defined for API compatibility but will raise errors if used
#[pyattr]
const PROTOCOL_TLSv1: i32 = rustpython_host_env::ssl::PROTOCOL_TLSV1;
#[pyattr]
const PROTOCOL_TLSv1_1: i32 = rustpython_host_env::ssl::PROTOCOL_TLSV1_1;
#[pyattr]
const PROTOCOL_TLSv1_2: i32 = rustpython_host_env::ssl::PROTOCOL_TLSV1_2;
#[pyattr]
const PROTOCOL_TLSv1_3: i32 = rustpython_host_env::ssl::PROTOCOL_TLSV1_3;
#[pyattr]
use rustpython_host_env::ssl::{
PROTO_MAXIMUM_SUPPORTED, PROTO_MINIMUM_SUPPORTED, PROTO_SSL3 as PROTO_SSLv3,
PROTO_TLSV1 as PROTO_TLSv1, PROTO_TLSV1_1 as PROTO_TLSv1_1, PROTO_TLSV1_2 as PROTO_TLSv1_2,
PROTO_TLSV1_3 as PROTO_TLSv1_3,
};
// Internal constants for rustls actual supported versions
// rustls only supports TLS 1.2 and TLS 1.3
const MINIMUM_VERSION: i32 = PROTO_TLSv1_2; // 0x0303
const MAXIMUM_VERSION: i32 = PROTO_TLSv1_3; // 0x0304
// Buffer sizes and limits (OpenSSL/CPython compatibility)
const PEM_BUFSIZE: usize = 1024;
pub(crate) const SSL3_RT_MAX_PACKET_SIZE: usize =
rustpython_host_env::ssl::SSL3_RT_MAX_PACKET_SIZE;
const SSL_SESSION_CACHE_SIZE: usize = rustpython_host_env::ssl::SESSION_CACHE_SIZE;
// Certificate verification modes
#[pyattr]
const CERT_NONE: i32 = rustpython_host_env::ssl::CERT_NONE;
#[pyattr]
const CERT_OPTIONAL: i32 = rustpython_host_env::ssl::CERT_OPTIONAL;
#[pyattr]
const CERT_REQUIRED: i32 = rustpython_host_env::ssl::CERT_REQUIRED;
// SSL Verification Flags / Certificate requirements
#[pyattr]
const VERIFY_DEFAULT: i32 = rustpython_host_env::ssl::VERIFY_DEFAULT;
#[pyattr]
const VERIFY_CRL_CHECK_LEAF: i32 = rustpython_host_env::ssl::VERIFY_CRL_CHECK_LEAF;
#[pyattr]
const VERIFY_CRL_CHECK_CHAIN: i32 = rustpython_host_env::ssl::VERIFY_CRL_CHECK_CHAIN;
// VERIFY_X509_STRICT flag for RFC 5280 strict compliance
// When set, performs additional validation including AKI extension checks
#[pyattr]
pub(crate) const VERIFY_X509_STRICT: i32 = rustpython_host_env::ssl::VERIFY_X509_STRICT;
#[pyattr]
const VERIFY_ALLOW_PROXY_CERTS: i32 = rustpython_host_env::ssl::VERIFY_ALLOW_PROXY_CERTS;
#[pyattr]
const VERIFY_X509_TRUSTED_FIRST: i32 = rustpython_host_env::ssl::VERIFY_X509_TRUSTED_FIRST;
// VERIFY_X509_PARTIAL_CHAIN flag for partial chain validation
// When set, accept certificates if any certificate in the chain is in the trust store
// (not just root CAs). This matches OpenSSL's X509_V_FLAG_PARTIAL_CHAIN behavior.
#[pyattr]
pub(crate) const VERIFY_X509_PARTIAL_CHAIN: i32 =
rustpython_host_env::ssl::VERIFY_X509_PARTIAL_CHAIN;
#[pyattr]
const HOSTFLAG_NEVER_CHECK_SUBJECT: i32 =
rustpython_host_env::ssl::HOSTFLAG_NEVER_CHECK_SUBJECT;
#[pyattr]
use rustpython_host_env::ssl::{
OP_ALL, OP_CIPHER_SERVER_PREFERENCE, OP_ENABLE_MIDDLEBOX_COMPAT, OP_IGNORE_UNEXPECTED_EOF,
OP_LEGACY_SERVER_CONNECT, OP_NO_COMPRESSION, OP_NO_RENEGOTIATION, OP_NO_SSLv2, OP_NO_SSLv3,
OP_NO_TICKET, OP_NO_TLSV1 as OP_NO_TLSv1, OP_NO_TLSV1_1 as OP_NO_TLSv1_1,
OP_NO_TLSV1_2 as OP_NO_TLSv1_2, OP_NO_TLSV1_3 as OP_NO_TLSv1_3, OP_SINGLE_DH_USE,
OP_SINGLE_ECDH_USE,
};
#[pyattr]
use rustpython_host_env::ssl::{
ALERT_DESCRIPTION_ACCESS_DENIED, ALERT_DESCRIPTION_BAD_CERTIFICATE,
ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE,
ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE, ALERT_DESCRIPTION_BAD_RECORD_MAC,
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED, ALERT_DESCRIPTION_CERTIFICATE_REQUIRED,
ALERT_DESCRIPTION_CERTIFICATE_REVOKED, ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN,
ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE, ALERT_DESCRIPTION_CLOSE_NOTIFY,
ALERT_DESCRIPTION_DECODE_ERROR, ALERT_DESCRIPTION_DECOMPRESSION_FAILURE,
ALERT_DESCRIPTION_DECRYPT_ERROR, ALERT_DESCRIPTION_DECRYPTION_FAILED,
ALERT_DESCRIPTION_EXPORT_RESTRICTION, ALERT_DESCRIPTION_HANDSHAKE_FAILURE,
ALERT_DESCRIPTION_ILLEGAL_PARAMETER, ALERT_DESCRIPTION_INAPPROPRIATE_FALLBACK,
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY, ALERT_DESCRIPTION_INTERNAL_ERROR,
ALERT_DESCRIPTION_MISSING_EXTENSION, ALERT_DESCRIPTION_NO_APPLICATION_PROTOCOL,
ALERT_DESCRIPTION_NO_CERTIFICATE, ALERT_DESCRIPTION_NO_RENEGOTIATION,
ALERT_DESCRIPTION_PROTOCOL_VERSION, ALERT_DESCRIPTION_RECORD_OVERFLOW,
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE, ALERT_DESCRIPTION_UNKNOWN_CA,
ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY, ALERT_DESCRIPTION_UNRECOGNIZED_NAME,
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE, ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION,
ALERT_DESCRIPTION_USER_CANCELLED,
};
// `ssl.py` still requires OpenSSL-shaped numeric compatibility fields even
// for non-OpenSSL TLS providers. Keep them in the supported 3.x ABI range,
// but report the actual rustls/AWS-LC backend in the human-readable string.
#[pyattr]
const OPENSSL_VERSION_NUMBER: i32 = 0x30300000;
#[pyattr]
const OPENSSL_VERSION: &str = "OpenSSL 3.3.0-compatible (AWS-LC/rustls 0.23)";
#[pyattr]
const OPENSSL_VERSION_INFO: (i32, i32, i32, i32, i32) = (3, 3, 0, 0, 15);
#[pyattr]
const _OPENSSL_API_VERSION: (i32, i32, i32, i32, i32) = (3, 3, 0, 0, 15);
#[pyattr(once)]
fn _DEFAULT_CIPHERS(_vm: &VirtualMachine) -> String {
cipher::default_cipher_string()
}
// Has features
#[pyattr]
const HAS_SNI: bool = true;
#[pyattr]
const HAS_TLS_UNIQUE: bool = true;
#[pyattr]
const HAS_ECDH: bool = true;
#[pyattr]
const HAS_NPN: bool = false; // Deprecated, use ALPN
#[pyattr]
const HAS_ALPN: bool = true;
#[pyattr]
const HAS_PSK: bool = false; // PSK not supported in rustls
#[pyattr]
const HAS_SSLv2: bool = false;
#[pyattr]
const HAS_SSLv3: bool = false;
#[pyattr]
const HAS_TLSv1: bool = false; // Not supported for security
#[pyattr]
const HAS_TLSv1_1: bool = false; // Not supported for security
#[pyattr]
const HAS_TLSv1_2: bool = true; // rustls supports TLS 1.2
#[pyattr]
const HAS_TLSv1_3: bool = true;
#[pyattr]
const HAS_PHA: bool = false; // Post-Handshake Auth not supported in rustls
#[pyattr]
use rustpython_host_env::ssl::{ENCODING_DER, ENCODING_PEM, ENCODING_PEM_AUX};
/// Validate server hostname for TLS SNI.
fn validate_hostname(hostname: &str, vm: &VirtualMachine) -> PyResult<()> {
use rustpython_host_env::ssl::HostnameError;
match rustpython_host_env::ssl::validate_hostname(hostname) {
Ok(()) => Ok(()),
Err(HostnameError::EmbeddedNul) => {
cold_path();
Err(exceptions::nul_char_type_error(vm))
}
Err(error) => Err(vm.new_value_error(error.message().to_owned())),
}
}
/// Parse `[len][proto]...` the way `ssl.py` hands it to `_set_alpn_protocols`.
fn parse_length_prefixed_alpn(bytes: &[u8], vm: &VirtualMachine) -> PyResult<Vec<Vec<u8>>> {
rustpython_host_env::ssl::parse_length_prefixed_alpn(bytes)
.map_err(|error| vm.new_value_error(error.0))
}
// SSLContext - manages TLS configuration
#[pyattr]
#[pyclass(name = "_SSLContext", module = "_ssl", traverse)]
#[derive(Debug, PyPayload)]
struct PySSLContext {
#[pytraverse(skip)]
context_identity: Arc<()>,
#[pytraverse(skip)]
protocol: i32,
#[pytraverse(skip)]
check_hostname: PyRwLock<bool>,
#[pytraverse(skip)]
host_flags: PyRwLock<i32>,
#[pytraverse(skip)]
verify_mode: PyRwLock<i32>,
#[pytraverse(skip)]
verify_flags: PyRwLock<i32>,
// Rustls configuration (built lazily)
#[pytraverse(skip)]
server_config: PyRwLock<Option<chain::ServerConfig>>,
// Certificate store
#[pytraverse(skip)]
root_certs: PyRwLock<RootCertStore>,
// Store full CA certificates for get_ca_certs()
// RootCertStore only keeps TrustAnchors, not full certificates
#[pytraverse(skip)]
ca_certs_der: PyRwLock<Vec<Vec<u8>>>,
// OpenSSL-style hashed CA directories, materialized when a connection
// needs an immutable rustls configuration.
#[pytraverse(skip)]
capath_state: PyRwLock<CapathState>,
// Certificate Revocation Lists for CRL checking
#[pytraverse(skip)]
crls: PyRwLock<Vec<CertificateRevocationListDer<'static>>>,
// Server certificate/key pairs (supports multiple for RSA+ECC dual mode)
// OpenSSL allows multiple cert/key pairs to be loaded, and selects the appropriate
// one based on client capabilities during handshake
// Stored as (CertifiedKey, PrivateKeyDer) to support both server and client usage
#[pytraverse(skip)]
cert_keys: PyRwLock<Vec<CertKeyPair>>,
// Options
#[pytraverse(skip)]
options: PyRwLock<i32>,
// ALPN protocols
#[pytraverse(skip)]
alpn_protocols: PyRwLock<Vec<Vec<u8>>>,
// TLS 1.3 features
#[pytraverse(skip)]
post_handshake_auth: PyRwLock<bool>,
#[pytraverse(skip)]
num_tickets: PyRwLock<i32>,
// Protocol version limits
#[pytraverse(skip)]
minimum_version: PyRwLock<i32>,
#[pytraverse(skip)]
maximum_version: PyRwLock<i32>,
// SNI callback for server-side (contains PyObjectRef - needs GC tracking)
sni_callback: PyRwLock<Option<PyObjectRef>>,
// Message callback for debugging (contains PyObjectRef - needs GC tracking)
msg_callback: PyRwLock<Option<PyObjectRef>>,
keylog_filename: PyRwLock<Option<PyObjectRef>>,
#[pytraverse(skip)]
key_log: Arc<super::keylog::KeyLog>,
// ECDH curve name for key exchange
#[pytraverse(skip)]
ecdh_curve: PyRwLock<Option<String>>,
// Certificate statistics for cert_store_stats()
#[pytraverse(skip)]
ca_cert_count: PyRwLock<usize>, // Number of CA certificates
#[pytraverse(skip)]
x509_cert_count: PyRwLock<usize>, // Total number of certificates
// Session management
#[pytraverse(skip)]
client_session_cache: SessionCache,
// Rustls server session store for server-side session resumption
#[pytraverse(skip)]
rustls_server_session_store: Arc<rustls::server::ServerSessionMemoryCache>,
// Shared ticketer for TLS 1.2 session tickets
#[pytraverse(skip)]
server_ticketer: Arc<dyn rustls::server::ProducesTickets>,
// Server-side session statistics
#[pytraverse(skip)]
accept_count: AtomicUsize, // Total number of accepts
#[pytraverse(skip)]
session_hits: AtomicUsize, // Number of session reuses
// Cipher suite selection
/// Selected cipher suites (None = use all rustls defaults)
#[pytraverse(skip)]
selected_ciphers: PyRwLock<Option<Vec<rustls::SupportedCipherSuite>>>,
/// Key exchange groups a SUITEB* cipher string pinned (RFC 6460)
#[pytraverse(skip)]
suite_b_kx_groups: PyRwLock<Option<Vec<&'static dyn SupportedKxGroup>>>,
}
#[derive(FromArgs)]
struct WrapSocketArgs {
sock: PyObjectRef,
server_side: bool,
#[pyarg(any, optional)]
server_hostname: Option<PyUtf8StrRef>,
#[pyarg(named, optional)]
owner: Option<PyObjectRef>,
#[pyarg(named, optional)]
session: Option<PyObjectRef>,
}
#[derive(FromArgs)]
struct WrapBioArgs {
incoming: PyRef<PyMemoryBIO>,
outgoing: PyRef<PyMemoryBIO>,
server_side: bool,
#[pyarg(any, optional)]
server_hostname: Option<PyUtf8StrRef>,
#[pyarg(named, optional)]
owner: Option<PyObjectRef>,
#[pyarg(named, optional)]
session: Option<PyObjectRef>,
}
#[derive(FromArgs)]
struct LoadVerifyLocationsArgs {
#[pyarg(any, optional, error_msg = "path should be a str or bytes")]
cafile: Option<Either<PyStrRef, ArgBytesLike>>,
#[pyarg(any, optional, error_msg = "path should be a str or bytes")]
capath: Option<Either<PyStrRef, ArgBytesLike>>,
#[pyarg(any, optional, error_msg = "cadata should be a str or bytes")]
cadata: Option<Either<PyStrRef, ArgBytesLike>>,
}
#[derive(FromArgs)]
struct LoadCertChainArgs {
#[pyarg(any, error_msg = "path should be a str or bytes")]
certfile: Either<PyStrRef, ArgBytesLike>,
#[pyarg(any, optional, error_msg = "path should be a str or bytes")]
keyfile: Option<Either<PyStrRef, ArgBytesLike>>,
#[pyarg(any, optional)]
password: Option<PyObjectRef>,
}
#[derive(FromArgs)]
struct GetCertArgs {
#[pyarg(positional, default)]
der: bool,
}
#[derive(FromArgs)]
struct GetCaCertsArgs {
#[pyarg(any, default)]
binary_form: bool,
}
#[pyclass(with(Constructor, Representable), flags(BASETYPE))]
impl PySSLContext {
fn warn_deprecated_tls_version(version: i32, vm: &VirtualMachine) -> PyResult<()> {
let version_name = match version {
PROTO_SSLv3 => Some("SSLv3"),
PROTO_TLSv1 => Some("TLSv1"),
PROTO_TLSv1_1 => Some("TLSv1_1"),
_ => None,
};
if let Some(version_name) = version_name {
_warnings::warn(
vm.ctx.exceptions.deprecation_warning,
format!("ssl.TLSVersion.{version_name} is deprecated"),
2,
vm,
)?;
}
Ok(())
}
// Helper method to convert DER certificate bytes to Python dict
fn cert_der_to_dict(&self, vm: &VirtualMachine, cert_der: &[u8]) -> PyResult<PyObjectRef> {
cert::cert_der_to_dict_helper(vm, cert_der)
}
fn add_verify_dir(&self, directory: String) {
let mut capath_state = self.capath_state.write();
if capath_state
.directories
.iter()
.any(|known| known == &directory)
{
return;
}
capath_state.directories.push(directory);
capath_state.cache = None;
drop(capath_state);
*self.server_config.write() = None;
}
fn capath_certificates(&self) -> Arc<Vec<Vec<u8>>> {
let directories = self.capath_state.read().directories.clone();
if directories.is_empty() {
return Arc::new(Vec::new());
}
let stamps = directories
.iter()
.map(|directory| {
let modified = rustpython_host_env::fs::metadata(directory)
.and_then(|metadata| metadata.modified())
.ok();
(directory.clone(), modified)
})
.collect::<Vec<_>>();
if let Some((cached_stamps, certificates)) = self.capath_state.read().cache.as_ref()
&& cached_stamps == &stamps
{
return certificates.clone();
}
let mut store = RootCertStore::empty();
let mut certificates = Vec::new();
let mut loader = cert::CertLoader::new(&mut store, &mut certificates);
for directory in &directories {
let _ = loader.load_from_dir(directory);
}
let certificates = Arc::new(certificates);
let mut capath_state = self.capath_state.write();
if capath_state.directories == directories {
capath_state.cache = Some((stamps, certificates.clone()));
}
certificates
}
fn verification_roots(&self) -> (RootCertStore, Vec<Vec<u8>>) {
let mut root_store = self.root_certs.read().clone();
let mut ca_certs_der = self.ca_certs_der.read().clone();
for certificate in self.capath_certificates().iter() {
let _ = root_store.add(certificate.clone().into());
if !ca_certs_der.iter().any(|known| known == certificate) {
ca_certs_der.push(certificate.clone());
}
}
(root_store, ca_certs_der)
}
#[pygetset]
fn check_hostname(zelf: &Py<Self>) -> bool {
*zelf.check_hostname.read()
}
#[pygetset(setter)]
fn set_check_hostname(zelf: &Py<Self>, value: bool) {
*zelf.check_hostname.write() = value;
// When check_hostname is enabled, ensure verify_mode is at least CERT_REQUIRED
if value {
let current_verify_mode = *zelf.verify_mode.read();
if current_verify_mode == CERT_NONE {
*zelf.verify_mode.write() = CERT_REQUIRED;
}
}
}
#[pygetset]
fn _host_flags(zelf: &Py<Self>) -> i32 {
*zelf.host_flags.read()
}
#[pygetset(setter)]
fn set__host_flags(zelf: &Py<Self>, value: i32) {
*zelf.host_flags.write() = value;
}
#[pygetset]
fn verify_mode(zelf: &Py<Self>) -> i32 {
*zelf.verify_mode.read()
}
#[pygetset(setter)]
fn set_verify_mode(zelf: &Py<Self>, mode: i32, vm: &VirtualMachine) -> PyResult<()> {
if !(CERT_NONE..=CERT_REQUIRED).contains(&mode) {
return Err(vm.new_value_error("invalid verify mode"));
}
// Cannot set CERT_NONE when check_hostname is enabled
if mode == CERT_NONE && *zelf.check_hostname.read() {
return Err(vm.new_value_error(
"Cannot set verify_mode to CERT_NONE when check_hostname is enabled",
));
}
*zelf.verify_mode.write() = mode;
Ok(())
}
#[pygetset]
fn protocol(zelf: &Py<Self>) -> i32 {
zelf.protocol
}
#[pygetset]
fn verify_flags(zelf: &Py<Self>) -> i32 {
*zelf.verify_flags.read()
}
#[pygetset(setter)]
fn set_verify_flags(zelf: &Py<Self>, value: i32) {
*zelf.verify_flags.write() = value;
}
#[pygetset]
fn post_handshake_auth(zelf: &Py<Self>) -> bool {
*zelf.post_handshake_auth.read()
}
#[pygetset(setter)]
fn set_post_handshake_auth(zelf: &Py<Self>, value: bool) {
*zelf.post_handshake_auth.write() = value;
}
#[pygetset]
fn num_tickets(zelf: &Py<Self>) -> i32 {
*zelf.num_tickets.read()
}
#[pygetset(setter)]
fn set_num_tickets(zelf: &Py<Self>, value: i32, vm: &VirtualMachine) -> PyResult<()> {
if value < 0 {
return Err(vm.new_value_error("num_tickets must be a non-negative integer"));
}
if zelf.protocol != PROTOCOL_TLS_SERVER {
return Err(
vm.new_value_error("num_tickets can only be set on server-side contexts")
);
}
*zelf.num_tickets.write() = value;
Ok(())
}
#[pygetset]
fn options(zelf: &Py<Self>) -> i32 {
*zelf.options.read()
}
#[pygetset(setter)]
fn set_options(zelf: &Py<Self>, value: i32, vm: &VirtualMachine) -> PyResult<()> {
// Validate that the value is non-negative
if value < 0 {
return Err(vm.new_value_error("options must be non-negative"));
}
// Deprecated SSL/TLS protocol version options
let opt_no = OP_NO_SSLv2
| OP_NO_SSLv3
| OP_NO_TLSv1
| OP_NO_TLSv1_1
| OP_NO_TLSv1_2
| OP_NO_TLSv1_3;
// Get current options and calculate newly set bits
let old_opts = *zelf.options.read();
let set = !old_opts & value; // Bits being newly set
// Warn if any deprecated options are being newly set
if (set & opt_no) != 0 {
_warnings::warn(
vm.ctx.exceptions.deprecation_warning,
"ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are deprecated".to_owned(),
2, // stack_level = 2
vm,
)?;
}
*zelf.options.write() = value;
Ok(())
}
#[pygetset]
fn minimum_version(zelf: &Py<Self>) -> i32 {
let v = *zelf.minimum_version.read();
// return MINIMUM_SUPPORTED if value is 0
if v == 0 { PROTO_MINIMUM_SUPPORTED } else { v }
}
#[pygetset(setter)]
fn set_minimum_version(zelf: &Py<Self>, value: i32, vm: &VirtualMachine) -> PyResult<()> {
// Validate that the value is a valid TLS version constant
// Valid values: 0 (default), -2 (MINIMUM_SUPPORTED), -1 (MAXIMUM_SUPPORTED),
// or 0x0300-0x0304 (SSLv3-TLSv1.3)
if value != 0
&& value != -2
&& value != -1
&& !(PROTO_SSLv3..=PROTO_TLSv1_3).contains(&value)
{
return Err(vm.new_value_error(format!("invalid protocol version: {value}")));
}
Self::warn_deprecated_tls_version(value, vm)?;
// Convert special values to rustls actual supported versions
// MINIMUM_SUPPORTED (-2) -> 0 (auto-negotiate)
// MAXIMUM_SUPPORTED (-1) -> MAXIMUM_VERSION (TLSv1.3)
let normalized_value = match value {
PROTO_MINIMUM_SUPPORTED => 0, // Auto-negotiate
PROTO_MAXIMUM_SUPPORTED => MAXIMUM_VERSION, // TLSv1.3
_ => value,
};
*zelf.minimum_version.write() = normalized_value;
Ok(())
}
#[pygetset]
fn maximum_version(zelf: &Py<Self>) -> i32 {
let v = *zelf.maximum_version.read();
// return MAXIMUM_SUPPORTED if value is 0
if v == 0 { PROTO_MAXIMUM_SUPPORTED } else { v }
}
#[pygetset(setter)]
fn set_maximum_version(zelf: &Py<Self>, value: i32, vm: &VirtualMachine) -> PyResult<()> {
// Validate that the value is a valid TLS version constant
// Valid values: 0 (default), -2 (MINIMUM_SUPPORTED), -1 (MAXIMUM_SUPPORTED),
// or 0x0300-0x0304 (SSLv3-TLSv1.3)
if value != 0
&& value != -2
&& value != -1
&& !(PROTO_SSLv3..=PROTO_TLSv1_3).contains(&value)
{
return Err(vm.new_value_error(format!("invalid protocol version: {value}")));
}
Self::warn_deprecated_tls_version(value, vm)?;
// Convert special values to rustls actual supported versions
// MAXIMUM_SUPPORTED (-1) -> 0 (auto-negotiate)
// MINIMUM_SUPPORTED (-2) -> MINIMUM_VERSION (TLSv1.2)
let normalized_value = match value {
PROTO_MAXIMUM_SUPPORTED => 0, // Auto-negotiate
PROTO_MINIMUM_SUPPORTED => MINIMUM_VERSION, // TLSv1.2
_ => value,
};
*zelf.maximum_version.write() = normalized_value;
Ok(())
}
#[pymethod]
fn load_cert_chain(
zelf: &Py<Self>,
args: LoadCertChainArgs,
vm: &VirtualMachine,
) -> PyResult<()> {
let crypto_ext = CryptoExt::get_ext();
// Parse certfile argument (str or bytes) to path
let cert_path = Self::parse_path_arg(&args.certfile, vm)?;
// Parse keyfile argument (default to certfile if not provided)
let key_path = match args.keyfile {
Some(ref k) => Self::parse_path_arg(k, vm)?,
None => cert_path.clone(),
};
// Parse password argument (str, bytes-like, or callable)
// Callable passwords are NOT invoked immediately (lazy evaluation)
let (password_str, password_callable) =
Self::parse_password_argument(args.password.as_ref(), vm)?;
// Validate immediate password length (limit: PEM_BUFSIZE = 1024 bytes)
if let Some(ref pwd) = password_str
&& pwd.len() > PEM_BUFSIZE
{
return Err(vm.new_value_error(format!(
"password cannot be longer than {PEM_BUFSIZE} bytes",
)));
}
// First attempt: Load with immediate password (or None if callable)
let mut result =
cert::load_cert_chain_from_file(&cert_path, &key_path, password_str.as_deref());
// If failed and callable exists, invoke it and retry
// This implements lazy evaluation: callable only invoked if password is actually needed
if result.is_err()
&& let Some(callable) = password_callable
{
// Invoke callable - exceptions propagate naturally
let pwd_result = callable.call((), vm)?;
// Convert callable result to string
let password_from_callable =
if let Ok(pwd_str) = PyUtf8StrRef::try_from_object(vm, pwd_result.clone()) {
pwd_str.as_str().to_owned()
} else if pwd_result.check_buffer() {
let pwd_bytes_like = ArgBytesLike::try_from_object(vm, pwd_result)?;
String::from_utf8(pwd_bytes_like.borrow_buf().to_vec()).map_err(|_| {
vm.new_type_error("password callback returned invalid UTF-8 bytes")
})?
} else {
return Err(
vm.new_type_error("password callback must return a string or bytes")
);
};
// Validate callable password length
if password_from_callable.len() > PEM_BUFSIZE {
return Err(vm.new_value_error(format!(
"password cannot be longer than {PEM_BUFSIZE} bytes",
)));
}
// Retry with callable password
result = cert::load_cert_chain_from_file(
&cert_path,
&key_path,
Some(&password_from_callable),
);
}
// Process result
let (certs, key) = result.map_err(|e| {
// Try to downcast to io::Error to preserve errno information
if let Ok(io_err) = e.downcast::<std::io::Error>() {
match io_err.kind() {
// File access errors (NotFound, PermissionDenied) - preserve errno
std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied => {
io_err.into_pyexception(vm)
}
// Other io::Error types
std::io::ErrorKind::Other => {
let msg = io_err.to_string();
if msg.contains("Failed to decrypt") || msg.contains("wrong password") {
// Wrong password error
vm.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
msg,
)
.upcast()
} else {
// [SSL] PEM lib
super::compat::SslError::create_ssl_error_with_reason(
vm,
Some("SSL"),
"",
"PEM lib",
)
}
}
// PEM parsing errors - [SSL] PEM lib
_ => super::compat::SslError::create_ssl_error_with_reason(
vm,
Some("SSL"),
"",
"PEM lib",
),
}
} else {
// Unknown error type - [SSL] PEM lib
super::compat::SslError::create_ssl_error_with_reason(
vm,
Some("SSL"),
"",
"PEM lib",
)
}
})?;
// Validate certificate and key match
cert::validate_cert_key_match(&certs, &key).map_err(|e| {
let msg = if e.contains("key values mismatch") {
"[SSL: KEY_VALUES_MISMATCH] key values mismatch".to_owned()
} else {
e
};
vm.new_os_subtype_error(PySSLError::class(&vm.ctx).to_owned(), Some(0), msg)
.upcast()
})?;
// Auto-build certificate chain: if only leaf cert is in file, try to add CA certs
// This matches OpenSSL behavior where it automatically includes intermediate/CA certs
let mut full_chain = certs.clone();
if full_chain.len() == 1 {
// Only have leaf cert, try to build chain from CA certs
let ca_certs_der = zelf.ca_certs_der.read();
if !ca_certs_der.is_empty() {
// Use build_verified_chain to construct full chain
let chain_result = cert::build_verified_chain(&full_chain, &ca_certs_der);
if chain_result.len() > 1 {
// Successfully built a longer chain
full_chain = chain_result.into_iter().map(CertificateDer::from).collect();
}
}
}
// Additional validation: Create CertifiedKey to ensure rustls accepts it
let signing_key = crypto_ext.any_supported_key(&key).map_err(|_| {
vm.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"[SSL: KEY_VALUES_MISMATCH] key values mismatch",
)
.upcast()
})?;
let certified_key = CertifiedKey::new(full_chain.clone(), signing_key);
if certified_key.keys_match().is_err() {
return Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"[SSL: KEY_VALUES_MISMATCH] key values mismatch",
)
.upcast());
}
// Add cert/key pair to collection (OpenSSL allows multiple cert/key pairs)
// Store both CertifiedKey (for server) and PrivateKeyDer (for client mTLS)
let cert_der = &full_chain[0];
let mut cert_keys = zelf.cert_keys.write();
// Remove any existing cert/key pair with the same certificate
// (This allows updating cert/key pair without duplicating)
cert_keys.retain(|(existing, _)| &existing.cert[0] != cert_der);
// Add new cert/key pair as tuple
cert_keys.push((Arc::new(certified_key), key));
Ok(())
}
#[pymethod]
fn load_verify_locations(
zelf: &Py<Self>,
args: LoadVerifyLocationsArgs,
vm: &VirtualMachine,
) -> PyResult<()> {
// Check that at least one argument is provided
let has_cafile = args.cafile.is_some();
let has_capath = args.capath.is_some();
let has_cadata = args.cadata.is_some();
if !has_cafile && !has_capath && !has_cadata {
return Err(vm.new_type_error("cafile, capath and cadata cannot be all omitted"));
}
// Parse arguments BEFORE acquiring locks to reduce lock scope
let cafile_path = if let Some(ref cafile_obj) = args.cafile {
Some(Self::parse_path_arg(cafile_obj, vm)?)
} else {
None
};
let capath_dir = if let Some(ref capath_obj) = args.capath {
Some(Self::parse_path_arg(capath_obj, vm)?)
} else {
None
};
let cadata_parsed = if let Some(ref cadata_obj) = args.cadata {
let is_string = matches!(cadata_obj, Either::A(_));
let data_vec = zelf.parse_cadata_arg(cadata_obj, vm)?;
Some((data_vec, is_string))
} else {
None
};
// Check for CRL before acquiring main locks
let (crl_opt, cafile_is_crl) = if let Some(ref path) = cafile_path {
let crl = zelf.load_crl_from_file(path, vm)?;
let is_crl = crl.is_some();
(crl, is_crl)
} else {
(None, false)
};
// If it's a CRL, just add it (separate lock, no conflict with root_store)
if let Some(crl) = crl_opt {
zelf.crls.write().push(crl);
}
// Now acquire write locks for certificate loading
let mut root_store = zelf.root_certs.write();
let mut ca_certs_der = zelf.ca_certs_der.write();
// Load from file (if not CRL)
if let Some(ref path) = cafile_path
&& !cafile_is_crl
{
// Not a CRL, load as certificate
let stats =
zelf.load_certs_from_file_helper(&mut root_store, &mut ca_certs_der, path, vm)?;
zelf.update_cert_stats(stats);
}
// Load from bytes or str
if let Some((ref data_vec, is_string)) = cadata_parsed {
let stats = zelf.load_certs_from_bytes_helper(
&mut root_store,
&mut ca_certs_der,
data_vec,
is_string, // PEM only for strings
vm,
)?;
zelf.update_cert_stats(stats);
}
drop(root_store);
drop(ca_certs_der);
if let Some(dir_path) = capath_dir {
zelf.add_verify_dir(dir_path);
}
*zelf.server_config.write() = None;
Ok(())
}
/// Helper: Get path from Python's os.environ
fn get_env_path(
environ: &PyObject,
var_name: &str,
vm: &VirtualMachine,
) -> PyResult<String> {
let path_obj = environ.get_item(var_name, vm)?;
path_obj.try_into_value(vm)
}
/// Helper: Try to load certificates from Python's os.environ variables
///
/// Returns true if certificates were successfully loaded from
/// `SSL_CERT_FILE`. `SSL_CERT_DIR` is an independent source and its
/// certificates remain hidden from store statistics until used.
///
/// We use Python's os.environ instead of Rust's std::env
/// because Python code can modify os.environ at runtime (e.g.,
/// `os.environ['SSL_CERT_FILE'] = '/path'`), but the native certificate
/// loader uses std::env which only sees the process environment.
fn try_load_from_python_environ(
&self,
store: &mut rustls::RootCertStore,
vm: &VirtualMachine,
) -> PyResult<bool> {
let os_module = vm.import("os", 0)?;
let environ = os_module.get_attr("environ", vm)?;
let mut loaded_certs = Vec::new();
let mut loaded_file = false;
if let Ok(cert_file) = Self::get_env_path(&environ, "SSL_CERT_FILE", vm)
&& rustpython_host_env::fs::exists(&cert_file)
{
let mut loader = cert::CertLoader::new(store, &mut loaded_certs);
if let Ok(stats) = loader.load_from_file(&cert_file) {
self.update_cert_stats(stats);
loaded_file = true;
}
}
if let Ok(cert_dir) = Self::get_env_path(&environ, "SSL_CERT_DIR", vm)
&& rustpython_host_env::fs::is_dir(&cert_dir)
{
self.add_verify_dir(cert_dir);
}
Ok(loaded_file)
}
/// Helper: Load system certificates using rustls-native-certs
///
/// This uses platform-specific methods:
/// - Linux: host CA file/directory paths
/// - macOS: Keychain API
/// - Windows: System certificate store (ROOT + CA stores)
fn load_system_certificates(
&self,
store: &mut rustls::RootCertStore,
vm: &VirtualMachine,
) -> PyResult<()> {
#[cfg(windows)]
{
let store_names = ["ROOT", "CA"];
for store_name in store_names {
let certs = rustpython_host_env::cert_store::enum_certificates(store_name);
for cert_ctx in certs.entries {
let cert = rustls::pki_types::CertificateDer::from(cert_ctx.der.to_vec());
let is_ca = cert::is_ca_certificate(cert.as_ref());
if store.add(cert).is_ok() {
*self.x509_cert_count.write() += 1;
if is_ca {
*self.ca_cert_count.write() += 1;
}
}
}
}
if *self.x509_cert_count.read() == 0 {
return Err(vm.new_os_error("Failed to load certificates from Windows store"));
}
Ok(())
}
#[cfg(not(windows))]
{
let result = rustpython_host_env::native_certs::load();
// Load successfully found certificates
for cert in result.certs {
let is_ca = cert::is_ca_certificate(&cert);
if store.add(cert.into()).is_ok() {
*self.x509_cert_count.write() += 1;
if is_ca {
*self.ca_cert_count.write() += 1;
}
}
}
// If there were errors but some certs loaded, just continue
// If NO certs loaded and there were errors, report the first error
if *self.x509_cert_count.read() == 0 && !result.errors.is_empty() {
return Err(vm.new_os_error(format!(
"Failed to load native certificates: {}",
result.errors[0]
)));
}
Ok(())
}
}
#[pymethod]
fn load_default_certs(
zelf: &Py<Self>,
_purpose: OptionalArg<i32>,
vm: &VirtualMachine,
) -> PyResult<()> {
let mut store = zelf.root_certs.write();
#[cfg(windows)]
{
// Windows: Load system certificates first, then additionally load from env
// see: test_load_default_certs_env_windows
let _ = zelf.load_system_certificates(&mut store, vm);
let _ = zelf.try_load_from_python_environ(&mut store, vm)?;
}
#[cfg(not(windows))]
{
// Non-Windows: Try env vars first; only fallback to system certs if not set
// see: test_load_default_certs_env
let loaded = zelf.try_load_from_python_environ(&mut store, vm)?;
if !loaded {
let _ = zelf.load_system_certificates(&mut store, vm);
}
}
// If no certificates were loaded from system, fallback to webpki-roots (Mozilla CA bundle)
// This ensures we always have some trusted root certificates even if system cert loading fails
if *zelf.x509_cert_count.read() == 0 {
use webpki_roots;
// webpki_roots provides TLS_SERVER_ROOTS as &[TrustAnchor]
// We can use extend() to add them to the RootCertStore
let webpki_count = webpki_roots::TLS_SERVER_ROOTS.len();
store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
*zelf.x509_cert_count.write() += webpki_count;
*zelf.ca_cert_count.write() += webpki_count;
}
drop(store);
*zelf.server_config.write() = None;
Ok(())
}
#[pymethod]
fn set_alpn_protocols(
zelf: &Py<Self>,
protocols: PyListRef,
vm: &VirtualMachine,
) -> PyResult<()> {
let mut alpn_list = Vec::new();
for item in protocols.borrow_vec().iter() {
let bytes = ArgBytesLike::try_from_object(vm, item.clone())?;
alpn_list.push(bytes.borrow_buf().to_vec());
}
*zelf.alpn_protocols.write() = alpn_list;
Ok(())
}
#[pymethod]
fn _set_alpn_protocols(
zelf: &Py<Self>,
protos: ArgBytesLike,
vm: &VirtualMachine,
) -> PyResult<()> {
let bytes = protos.borrow_buf();
let alpn_list = parse_length_prefixed_alpn(&bytes, vm)?;
*zelf.alpn_protocols.write() = alpn_list;
Ok(())
}
#[pymethod]
fn set_ciphers(
zelf: &Py<Self>,
cipherlist: PyUtf8StrRef,
vm: &VirtualMachine,
) -> PyResult<()> {
// `SSL_CTX_set_cipher_list` reports one failure for a string it
// cannot read and for a readable one that selects nothing, and the
// TLS 1.3 suites are not among what it can select -- they have
// their own setter -- so a string naming only those selects
// nothing either.
let (mut selected_ciphers, suite_b_kx_groups) =
cipher::CipherList::parse_to_rustls(cipherlist.as_str())
.ok()
.filter(|(suites, _)| suites.iter().any(|s| s.tls13().is_none()))
.ok_or_else(|| {
vm.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"No cipher can be selected.".to_owned(),
)
.upcast()
})?;
// TLS 1.3 has a separate OpenSSL setter. Discard whatever this
// cipher string happened to match there, then restore exactly the
// provider defaults in their preference order.
selected_ciphers = cipher::restore_default_tls13(
selected_ciphers,
CryptoExt::get_ext().default_ciphers_or_provider(),
);
*zelf.selected_ciphers.write() = Some(selected_ciphers);
*zelf.suite_b_kx_groups.write() = suite_b_kx_groups;
*zelf.server_config.write() = None;
Ok(())
}
#[pymethod]
fn get_ciphers(zelf: &Py<Self>, vm: &VirtualMachine) -> PyListRef {
// What the last `set_ciphers` selected, or the provider defaults
// when no cipher string was given.
let selected = zelf.selected_ciphers.read().clone();
let suites = selected
.unwrap_or_else(|| CryptoExt::get_ext().default_ciphers_or_provider().to_vec());
let cipher_list = suites
.iter()
.map(|suite| {
let cipher = cipher::describe(suite);
let dict = vm.ctx.new_dict();
let items: [(&str, PyObjectRef); 6] = [
("id", vm.ctx.new_int(cipher.id).into()),
("name", vm.ctx.new_str(cipher.name).into()),
("protocol", vm.ctx.new_str(cipher.protocol).into()),
("strength_bits", vm.ctx.new_int(cipher.bits).into()),
("alg_bits", vm.ctx.new_int(cipher.bits).into()),
("description", vm.ctx.new_str(cipher.description).into()),
];
for (key, value) in items {
dict.set_item(key, value, vm).unwrap();
}
dict.into()
})
.collect::<Vec<_>>();
PyListRef::from(vm.ctx.new_list(cipher_list))
}
#[pymethod]
fn set_default_verify_paths(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
// Just call load_default_certs
Self::load_default_certs(zelf, OptionalArg::Missing, vm)
}
#[pymethod]
fn cert_store_stats(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
// Use the certificate counters that are updated in load_verify_locations
let x509_count = *zelf.x509_cert_count.read() as i32;
let ca_count = *zelf.ca_cert_count.read() as i32;
let dict = vm.ctx.new_dict();
dict.set_item("x509", vm.ctx.new_int(x509_count).into(), vm)?;
dict.set_item("crl", vm.ctx.new_int(0).into(), vm)?; // CRL not supported
dict.set_item("x509_ca", vm.ctx.new_int(ca_count).into(), vm)?;
Ok(dict.into())
}
#[pymethod]
fn session_stats(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
// Return session statistics
// NOTE: This is a partial implementation - rustls doesn't expose all OpenSSL stats
let dict = vm.ctx.new_dict();
// Number of sessions currently in the cache
let session_count = zelf.client_session_cache.read().len() as i32;
dict.set_item("number", vm.ctx.new_int(session_count).into(), vm)?;
// Client-side statistics (not tracked separately in this implementation)
dict.set_item("connect", vm.ctx.new_int(0).into(), vm)?;
dict.set_item("connect_good", vm.ctx.new_int(0).into(), vm)?;
dict.set_item("connect_renegotiate", vm.ctx.new_int(0).into(), vm)?; // rustls doesn't support renegotiation
// Server-side statistics
let accept_count = zelf.accept_count.load(Ordering::SeqCst) as i32;
dict.set_item("accept", vm.ctx.new_int(accept_count).into(), vm)?;
dict.set_item("accept_good", vm.ctx.new_int(accept_count).into(), vm)?; // Assume all accepts are good
dict.set_item("accept_renegotiate", vm.ctx.new_int(0).into(), vm)?; // rustls doesn't support renegotiation
// Session reuse statistics
let hits = zelf.session_hits.load(Ordering::SeqCst) as i32;
dict.set_item("hits", vm.ctx.new_int(hits).into(), vm)?;
// Misses, timeouts, and cache_full are not tracked in this implementation
dict.set_item("misses", vm.ctx.new_int(0).into(), vm)?;
dict.set_item("timeouts", vm.ctx.new_int(0).into(), vm)?;
dict.set_item("cache_full", vm.ctx.new_int(0).into(), vm)?;
Ok(dict.into())
}
#[pygetset]
fn sni_callback(zelf: &Py<Self>) -> Option<PyObjectRef> {
zelf.sni_callback.read().clone()
}
#[pygetset(setter)]
fn set_sni_callback(
zelf: &Py<Self>,
callback: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
// Validate callback is callable or None
if let Some(ref cb) = callback
&& !cb.is(vm.ctx.types.none_type)
&& !cb.is_callable()
{
return Err(vm.new_type_error("sni_callback must be callable or None"));
}
*zelf.sni_callback.write() = callback;
Ok(())
}
#[pymethod]
fn set_servername_callback(
zelf: &Py<Self>,
callback: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
// Alias for set_sni_callback
Self::set_sni_callback(zelf, callback, vm)
}
#[pygetset]
fn security_level(_zelf: &Py<Self>) -> i32 {
// rustls uses a fixed security level
// Return 2 which is a reasonable default (equivalent to OpenSSL 1.1.0+ level 2)
2
}
#[pygetset]
fn _msg_callback(zelf: &Py<Self>) -> Option<PyObjectRef> {
zelf.msg_callback.read().clone()
}
#[pygetset]
fn keylog_filename(zelf: &Py<Self>) -> Option<PyObjectRef> {
zelf.keylog_filename.read().clone()
}
#[pygetset(setter)]
fn set_keylog_filename(
zelf: &Py<Self>,
value: PySetterValue,
vm: &VirtualMachine,
) -> PyResult<()> {
let PySetterValue::Assign(value) = value else {
return Err(vm.new_attribute_error("attribute 'keylog_filename' cannot be deleted"));
};
// CPython disables the old destination even if path conversion or
// opening the replacement fails. Retain the original Python object
// (including PathLike and str subclasses) for the getter and GC.
let old_filename = zelf.keylog_filename.write().take();
zelf.key_log
.0
.set_path(None, super::keylog::HEADER)
.map_err(|e| e.into_pyexception(vm))?;
drop(old_filename);
if vm.is_none(&value) {
return Ok(());
}
let path = FsPath::try_from_object(vm, value.clone())?.to_path_buf(vm)?;
zelf.key_log
.0
.set_path(Some(&path), super::keylog::HEADER)
.map_err(|e| {
let exc = e.into_pyexception(vm);
let _ = exc.as_object().set_attr("filename", value.clone(), vm);
exc
})?;
let old_filename = zelf.keylog_filename.write().replace(value);
drop(old_filename);
Ok(())
}
#[pygetset(setter)]
fn set__msg_callback(
zelf: &Py<Self>,
callback: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
// Validate callback is callable or None
if let Some(ref cb) = callback
&& !cb.is(vm.ctx.types.none_type)
&& !cb.is_callable()
{
return Err(vm.new_type_error("msg_callback must be callable or None"));
}
*zelf.msg_callback.write() = callback;
Ok(())
}
#[pymethod]
fn get_ca_certs(
zelf: &Py<Self>,
args: GetCaCertsArgs,
vm: &VirtualMachine,
) -> PyResult<PyListRef> {
let binary_form = args.binary_form;
let ca_certs_der = zelf.ca_certs_der.read();
let mut certs = Vec::new();
for cert_der in ca_certs_der.iter() {
// Parse certificate to check if it's a CA and get info
match x509_parser::parse_x509_certificate(cert_der) {
Ok((_, cert)) => {
// Check if this is a CA certificate (BasicConstraints: CA=TRUE)
let is_ca = if let Ok(Some(bc_ext)) = cert.basic_constraints() {
bc_ext.value.ca
} else {
false
};
// Only include CA certificates
if !is_ca {
continue;
}
if binary_form {
// Return DER-encoded certificate as bytes
certs.push(vm.ctx.new_bytes(cert_der.clone()).into());
} else {
// Return certificate as dict (use helper from _test_decode_cert)
let dict = zelf.cert_der_to_dict(vm, cert_der)?;
certs.push(dict);
}
}
Err(_) => {
// Skip invalid certificates
continue;
}
}
}
Ok(PyListRef::from(vm.ctx.new_list(certs)))
}
#[pymethod]
fn load_dh_params(
_zelf: &Py<Self>,
path: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
// Validate filepath is not None
if vm.is_none(&path) {
return Err(vm.new_type_error("DH params filepath cannot be None"));
}
// Validate filepath is str or bytes
let path_str = if let Ok(s) = PyUtf8StrRef::try_from_object(vm, path.clone()) {
s.as_str().to_owned()
} else if path.check_buffer() {
let b = ArgBytesLike::try_from_object(vm, path)?;
String::from_utf8(b.borrow_buf().to_vec())
.map_err(|_| vm.new_value_error("Invalid path encoding"))?
} else {
return Err(vm.new_type_error("DH params filepath must be str or bytes"));
};
// Check if file exists
if !rustpython_host_env::fs::exists(&path_str) {
// Create FileNotFoundError with errno=ENOENT (2)
let exc = vm.new_os_subtype_error(
vm.ctx.exceptions.file_not_found_error.to_owned(),
Some(2), // errno = ENOENT (2)
"No such file or directory",
);
// Set filename attribute
let _ = exc
.as_object()
.set_attr("filename", vm.ctx.new_str(path_str), vm);
return Err(exc.upcast());
}
// Validate that the file contains DH parameters
// Read the file and check for DH PARAMETERS header
let contents = rustpython_host_env::fs::read_to_string(&path_str)
.map_err(|e| vm.new_os_error(e.to_string()))?;
if !contents.contains("BEGIN DH PARAMETERS")
&& !contents.contains("BEGIN X9.42 DH PARAMETERS")
{
// File exists but doesn't contain DH parameters - raise SSLError
// [PEM: NO_START_LINE] no start line
return Err(super::compat::SslError::create_ssl_error_with_reason(
vm,
Some("PEM"),
"NO_START_LINE",
"[PEM: NO_START_LINE] no start line",
));
}
// rustls doesn't use DH parameters (it uses ECDHE for key exchange)
// This is a no-op for compatibility with OpenSSL-based code
Ok(())
}
#[pymethod]
fn set_ecdh_curve(zelf: &Py<Self>, name: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
// Validate name is not None
if vm.is_none(&name) {
return Err(vm.new_type_error("ECDH curve name cannot be None"));
}
// Validate name is str or bytes
let curve_name = if let Ok(s) = PyUtf8StrRef::try_from_object(vm, name.clone()) {
s.as_str().to_owned()
} else if name.check_buffer() {
let b = ArgBytesLike::try_from_object(vm, name)?;
String::from_utf8(b.borrow_buf().to_vec())
.map_err(|_| vm.new_value_error("Invalid curve name encoding"))?
} else {
return Err(vm.new_type_error("ECDH curve name must be str or bytes"));
};
curve_name_to_kx_group(&curve_name).map_err(|error| vm.new_value_error(error))?;
// Store the curve name to be used during handshake
// This will limit the key exchange groups offered/accepted
*zelf.ecdh_curve.write() = Some(curve_name);
Ok(())
}
#[pymethod]
fn _wrap_socket(
zelf: PyRef<Self>,
args: WrapSocketArgs,
vm: &VirtualMachine,
) -> PyResult<PyRef<PySSLSocket>> {
let socket_mod = vm.import("socket", 0)?;
let socket_class = socket_mod.get_attr("socket", vm)?;
// Convert server_hostname to Option<String>
// Handle both missing argument and None value
let hostname = match args.server_hostname {
Some(hostname_str) => {
let hostname = hostname_str.as_str();
validate_hostname(hostname, vm)?;
Some(hostname.to_string())
}
None => None,
};
// Validate socket type and context protocol
if args.server_side && zelf.protocol == PROTOCOL_TLS_CLIENT {
return Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"Cannot create a server socket with a PROTOCOL_TLS_CLIENT context",
)
.upcast());
}
if !args.server_side && zelf.protocol == PROTOCOL_TLS_SERVER {
return Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"Cannot create a client socket with a PROTOCOL_TLS_SERVER context",
)
.upcast());
}
// Create _SSLSocket instance
let ssl_socket = PySSLSocket {
io: SocketOrBio::Socket {
sock: args.sock.clone(),
send: socket_class.get_attr("send", vm)?,
recv: socket_class.get_attr("recv", vm)?,
},
record_cursor: PyMutex::new(RecordCursor::default()),
key_log: Arc::new(super::keylog::ConnectionKeyLog::new(zelf.key_log.clone())),
context: PyRwLock::new(zelf),
server_side: args.server_side,
server_hostname: PyRwLock::new(hostname),
connection: PyMutex::new(None),
state: PyMutex::new(TlsState::new(args.server_side)),
session_was_reused: PyMutex::new(false),
owner: PyRwLock::new(args.owner.map(|o| o.downgrade(None, vm)).transpose()?),
session: PyRwLock::new(None),
client_config: PyRwLock::new(None),
chain_builder: PyRwLock::new(None),
verified_chain: PyRwLock::new(None),
client_session_store: PyRwLock::new(None),
pending_tls_output: PyMutex::new(Vec::new()),
msg_state: PyMutex::new(super::msg::MsgState::default()),
pending_msg_exc: PyMutex::new(None),
deferred_cert_error: Arc::new(ParkingRwLock::new(None)),
};
// Create PyRef with correct type
let ssl_socket_ref = ssl_socket
.into_ref_with_type(vm, vm.class("_ssl", "_SSLSocket"))
.map_err(|_| vm.new_type_error("Failed to create SSLSocket"))?;
if let Some(session) = args.session
&& !vm.is_none(&session)
{
PySSLSocket::set_session(&ssl_socket_ref, session, vm)?;
}
Ok(ssl_socket_ref)
}
#[pymethod]
fn _wrap_bio(
zelf: PyRef<Self>,
args: WrapBioArgs,
vm: &VirtualMachine,
) -> PyResult<PyRef<PySSLSocket>> {
// Convert server_hostname to Option<String>
// Handle both missing argument and None value
let hostname = match args.server_hostname {
Some(hostname_str) => {
let hostname = hostname_str.as_str();
validate_hostname(hostname, vm)?;
Some(hostname.to_string())
}
None => None,
};
let server_side = args.server_side;
// Validate socket type and context protocol
if server_side && zelf.protocol == PROTOCOL_TLS_CLIENT {
return Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"Cannot create a server socket with a PROTOCOL_TLS_CLIENT context",
)
.upcast());
}
if !server_side && zelf.protocol == PROTOCOL_TLS_SERVER {
return Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"Cannot create a client socket with a PROTOCOL_TLS_SERVER context",
)
.upcast());
}
// Create _SSLSocket instance with BIO mode
let ssl_socket = PySSLSocket {
io: SocketOrBio::Bio {
incoming: args.incoming,
outgoing: args.outgoing,
},
record_cursor: PyMutex::new(RecordCursor::default()),
key_log: Arc::new(super::keylog::ConnectionKeyLog::new(zelf.key_log.clone())),
context: PyRwLock::new(zelf),
server_side,
server_hostname: PyRwLock::new(hostname),
connection: PyMutex::new(None),
state: PyMutex::new(TlsState::new(server_side)),
session_was_reused: PyMutex::new(false),
owner: PyRwLock::new(args.owner.map(|o| o.downgrade(None, vm)).transpose()?),
session: PyRwLock::new(None),
client_config: PyRwLock::new(None),
chain_builder: PyRwLock::new(None),
verified_chain: PyRwLock::new(None),
client_session_store: PyRwLock::new(None),
pending_tls_output: PyMutex::new(Vec::new()),
msg_state: PyMutex::new(super::msg::MsgState::default()),
pending_msg_exc: PyMutex::new(None),
deferred_cert_error: Arc::new(ParkingRwLock::new(None)),
};
let ssl_socket_ref = ssl_socket
.into_ref_with_type(vm, vm.class("_ssl", "_SSLSocket"))
.map_err(|_| vm.new_type_error("Failed to create SSLSocket"))?;
if let Some(session) = args.session
&& !vm.is_none(&session)
{
PySSLSocket::set_session(&ssl_socket_ref, session, vm)?;
}
Ok(ssl_socket_ref)
}
// Helper functions (private):
/// Parse path argument (str or bytes) to string
fn parse_path_arg(
arg: &Either<PyStrRef, ArgBytesLike>,
vm: &VirtualMachine,
) -> PyResult<String> {
match arg {
Either::A(s) => Ok(s.clone().try_into_utf8(vm)?.as_str().to_owned()),
Either::B(b) => String::from_utf8(b.borrow_buf().to_vec())
.map_err(|_| vm.new_value_error("path contains invalid UTF-8")),
}
}
/// Parse password argument (str, bytes-like, or callable)
///
/// Returns (immediate_password, callable) where:
/// - immediate_password: Some(string) if password is str/bytes, None if callable
/// - callable: Some(PyObjectRef) if password is callable, None otherwise
fn parse_password_argument(
password: Option<&PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<(Option<String>, Option<PyObjectRef>)> {
match password {
Some(p) => {
if vm.is_none(p) {
return Ok((None, None));
}
// Try string
if let Ok(pwd_str) = PyUtf8StrRef::try_from_object(vm, p.clone()) {
Ok((Some(pwd_str.as_str().to_owned()), None))
}
// Try bytes-like
else if p.check_buffer() {
let pwd_bytes_like = ArgBytesLike::try_from_object(vm, p.clone())?;
let pwd = String::from_utf8(pwd_bytes_like.borrow_buf().to_vec())
.map_err(|_| vm.new_type_error("password bytes must be valid UTF-8"))?;
Ok((Some(pwd), None))
}
// Try callable
else if p.is_callable() {
Ok((None, Some(p.clone())))
} else {
Err(vm.new_type_error("password should be a string or callable"))
}
}
_ => Ok((None, None)),
}
}
/// Helper: Load certificates from file into existing store
fn load_certs_from_file_helper(
&self,
root_store: &mut RootCertStore,
ca_certs_der: &mut Vec<Vec<u8>>,
path: &str,
vm: &VirtualMachine,
) -> PyResult<cert::CertStats> {
let mut loader = cert::CertLoader::new(root_store, ca_certs_der);
loader.load_from_file(path).map_err(|e| {
// Preserve errno for file access errors (NotFound, PermissionDenied)
match e.kind() {
std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied => {
e.into_pyexception(vm)
}
// PEM parsing errors
_ => super::compat::SslError::create_ssl_error_with_reason(
vm,
Some("X509"),
"",
"PEM lib",
),
}
})
}
/// Helper: Load certificates from bytes into existing store
fn load_certs_from_bytes_helper(
&self,
root_store: &mut RootCertStore,
ca_certs_der: &mut Vec<Vec<u8>>,
data: &[u8],
pem_only: bool,
vm: &VirtualMachine,
) -> PyResult<cert::CertStats> {
let mut loader = cert::CertLoader::new(root_store, ca_certs_der);
// treat_all_as_ca=true: CPython counts all certificates loaded via cadata as CA certs
// regardless of their Basic Constraints extension
// pem_only=true for string input
loader
.load_from_bytes_ex(data, true, pem_only)
.map_err(|e| {
// Preserve specific error messages from cert.rs
let err_msg = e.to_string();
if err_msg.contains("no start line") {
vm.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"no start line: cadata does not contain a certificate",
)
.upcast()
} else if err_msg.contains("not enough data") {
vm.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"not enough data: cadata does not contain a certificate",
)
.upcast()
} else {
vm.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
err_msg,
)
.upcast()
}
})
}
/// Helper: Try to parse data as CRL (PEM or DER format)
fn try_parse_crl(
&self,
data: &[u8],
) -> Result<CertificateRevocationListDer<'static>, String> {
// Try PEM format first
let mut cursor = std::io::Cursor::new(data);
let mut crl_iter = rustls_pemfile::crls(&mut cursor);
if let Some(Ok(crl)) = crl_iter.next() {
return Ok(crl);
}
// Try DER format
// Basic validation: CRL should start with SEQUENCE tag (0x30)
if !data.is_empty() && data[0] == 0x30 {
return Ok(CertificateRevocationListDer::from(data.to_vec()));
}
Err("Not a valid CRL file".to_string())
}
/// Helper: Load CRL from file
fn load_crl_from_file(
&self,
path: &str,
vm: &VirtualMachine,
) -> PyResult<Option<CertificateRevocationListDer<'static>>> {
let data = rustpython_host_env::fs::read(path).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied => {
e.into_pyexception(vm)
}
_ => vm.new_os_error(e.to_string()),
})?;
match self.try_parse_crl(&data) {
Ok(crl) => Ok(Some(crl)),
Err(_) => Ok(None), // Not a CRL file, might be a cert file
}
}
/// Helper: Parse cadata argument (str or bytes)
fn parse_cadata_arg(
&self,
arg: &Either<PyStrRef, ArgBytesLike>,
vm: &VirtualMachine,
) -> PyResult<Vec<u8>> {
match arg {
Either::A(s) => Ok(s.clone().try_into_utf8(vm)?.as_str().as_bytes().to_vec()),
Either::B(b) => Ok(b.borrow_buf().to_vec()),
}
}
/// Helper: Update certificate statistics
fn update_cert_stats(&self, stats: cert::CertStats) {
*self.x509_cert_count.write() += stats.total_certs;
*self.ca_cert_count.write() += stats.ca_certs;
}
}
impl Representable for PySSLContext {
#[inline]
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!("<SSLContext(protocol={})>", zelf.protocol))
}
}
impl Constructor for PySSLContext {
type Args = (i32,);
fn py_new(
_cls: &Py<PyType>,
(protocol,): Self::Args,
vm: &VirtualMachine,
) -> PyResult<Self> {
let crypto_ext = CryptoExt::get_ext();
let deprecated_protocol = match protocol {
PROTOCOL_TLS => Some("PROTOCOL_TLS"),
PROTOCOL_TLSv1_2 => Some("PROTOCOL_TLSv1_2"),
PROTOCOL_TLS_CLIENT | PROTOCOL_TLS_SERVER | PROTOCOL_TLSv1_3 => None,
PROTOCOL_TLSv1 | PROTOCOL_TLSv1_1 => {
return Err(vm.new_value_error(
"TLS 1.0 and 1.1 are not supported by rustls for security reasons",
));
}
_ => {
return Err(vm.new_value_error(format!("invalid protocol version: {protocol}")));
}
};
if let Some(protocol_name) = deprecated_protocol {
_warnings::warn(
vm.ctx.exceptions.deprecation_warning,
format!("ssl.{protocol_name} is deprecated"),
2,
vm,
)?;
}
// Set default options
// OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_COMPRESSION |
// OP_CIPHER_SERVER_PREFERENCE | OP_SINGLE_DH_USE | OP_SINGLE_ECDH_USE |
// OP_ENABLE_MIDDLEBOX_COMPAT
let default_options = OP_ALL
| OP_NO_SSLv2
| OP_NO_SSLv3
| OP_NO_COMPRESSION
| OP_CIPHER_SERVER_PREFERENCE
| OP_SINGLE_DH_USE
| OP_SINGLE_ECDH_USE
| OP_ENABLE_MIDDLEBOX_COMPAT;
// Set default verify_mode based on protocol
// PROTOCOL_TLS_CLIENT defaults to CERT_REQUIRED
// PROTOCOL_TLS_SERVER defaults to CERT_NONE
let default_verify_mode = if protocol == PROTOCOL_TLS_CLIENT {
CERT_REQUIRED
} else {
CERT_NONE
};
// Set default verify_flags based on protocol
// Both PROTOCOL_TLS_CLIENT and PROTOCOL_TLS_SERVER only set VERIFY_X509_TRUSTED_FIRST
// Note: VERIFY_X509_PARTIAL_CHAIN and VERIFY_X509_STRICT are NOT set here
// - they're only added by create_default_context() in Python's ssl.py
let default_verify_flags = VERIFY_DEFAULT | VERIFY_X509_TRUSTED_FIRST;
// Set minimum and maximum protocol versions based on protocol constant
// specific protocol versions fix both min and max
let (min_version, max_version) = match protocol {
PROTOCOL_TLSv1_2 => (PROTO_TLSv1_2, PROTO_TLSv1_2), // Only TLS 1.2
PROTOCOL_TLSv1_3 => (PROTO_TLSv1_3, PROTO_TLSv1_3), // Only TLS 1.3
_ => (PROTO_MINIMUM_SUPPORTED, PROTO_MAXIMUM_SUPPORTED), // Auto-negotiate
};
// Session metadata is scoped to the SSLContext. Each per-connection
// rustls session store records into this shared cache.
let shared_session_cache = Arc::new(ParkingRwLock::new(HashMap::new()));
Ok(Self {
context_identity: Arc::new(()),
protocol,
check_hostname: PyRwLock::new(protocol == PROTOCOL_TLS_CLIENT),
host_flags: PyRwLock::new(0),
verify_mode: PyRwLock::new(default_verify_mode),
verify_flags: PyRwLock::new(default_verify_flags),
server_config: PyRwLock::new(None),
root_certs: PyRwLock::new(RootCertStore::empty()),
ca_certs_der: PyRwLock::new(Vec::new()),
capath_state: PyRwLock::new(CapathState::default()),
crls: PyRwLock::new(Vec::new()),
cert_keys: PyRwLock::new(Vec::new()),
options: PyRwLock::new(default_options),
alpn_protocols: PyRwLock::new(Vec::new()),
post_handshake_auth: PyRwLock::new(false),
num_tickets: PyRwLock::new(2), // TLS 1.3 default
minimum_version: PyRwLock::new(min_version),
maximum_version: PyRwLock::new(max_version),
sni_callback: PyRwLock::new(None),
msg_callback: PyRwLock::new(None),
keylog_filename: PyRwLock::new(None),
key_log: Arc::new(super::keylog::KeyLog::default()),
ecdh_curve: PyRwLock::new(None),
ca_cert_count: PyRwLock::new(0),
x509_cert_count: PyRwLock::new(0),
// Use the shared cache created above
client_session_cache: shared_session_cache,
rustls_server_session_store: rustls::server::ServerSessionMemoryCache::new(
SSL_SESSION_CACHE_SIZE,
),
server_ticketer: (crypto_ext.ticketer)()
.expect("Failed to create shared ticketer for TLS 1.2 session resumption"),
accept_count: AtomicUsize::new(0),
session_hits: AtomicUsize::new(0),
selected_ciphers: PyRwLock::new(None),
suite_b_kx_groups: PyRwLock::new(None),
})
}
}
#[derive(Debug)]
enum SocketOrBio {
Socket {
sock: PyObjectRef,
send: PyObjectRef,
recv: PyObjectRef,
},
Bio {
incoming: PyRef<PyMemoryBIO>,
outgoing: PyRef<PyMemoryBIO>,
},
}
unsafe impl crate::vm::object::Traverse for SocketOrBio {
fn traverse(&self, tracer: &mut crate::vm::object::TraverseFn<'_>) {
match self {
Self::Socket { sock, send, recv } => {
sock.traverse(tracer);
send.traverse(tracer);
recv.traverse(tracer);
}
Self::Bio { incoming, outgoing } => {
incoming.traverse(tracer);
outgoing.traverse(tracer);
}
}
}
}
impl SocketOrBio {
fn socket_object(&self, vm: &VirtualMachine) -> PyObjectRef {
match self {
Self::Socket { sock, .. } => sock.clone(),
Self::Bio { .. } => vm.ctx.none(),
}
}
fn incoming(&self) -> Option<PyRef<PyMemoryBIO>> {
match self {
Self::Bio { incoming, .. } => Some(incoming.clone()),
_ => None,
}
}
fn recv(&self, size: usize, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
match self {
Self::Socket { sock, recv, .. } => recv.call((sock.clone(), size), vm),
Self::Bio { incoming, .. } => {
incoming.as_object().get_attr("read", vm)?.call((size,), vm)
}
}
}
fn send(&self, data: &[u8], vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let bytes = vm.ctx.new_bytes(data.to_vec());
match self {
Self::Socket { sock, send, .. } => send.call((sock.clone(), bytes), vm),
Self::Bio { outgoing, .. } => outgoing
.as_object()
.get_attr("write", vm)?
.call((bytes,), vm),
}
}
}
// SSLSocket - represents a TLS-wrapped socket
#[pyattr]
#[pyclass(name = "_SSLSocket", module = "_ssl", traverse)]
#[derive(Debug, PyPayload)]
pub(crate) struct PySSLSocket {
io: SocketOrBio,
#[pytraverse(skip)]
record_cursor: PyMutex<RecordCursor>,
// SSL context
context: PyRwLock<PyRef<PySSLContext>>,
#[pytraverse(skip)]
key_log: Arc<super::keylog::ConnectionKeyLog>,
// Server-side or client-side
#[pytraverse(skip)]
server_side: bool,
// Server hostname for SNI
#[pytraverse(skip)]
server_hostname: PyRwLock<Option<String>>,
// TLS connection state
#[pytraverse(skip)]
connection: PyMutex<Option<TlsConnection>>,
// Includes the saved exception while a rejected handshake sends its alert.
state: PyMutex<TlsState>,
// Session was reused (for session resumption tracking)
#[pytraverse(skip)]
session_was_reused: PyMutex<bool>,
// Owner (SSLSocket instance that owns this _SSLSocket)
owner: PyRwLock<Option<PyRef<PyWeak>>>,
// Session for resumption
session: PyRwLock<Option<PyObjectRef>>,
// Client configuration used by this connection. Retained so the resulting
// SSLSession can reuse the same verifier and client credentials.
#[pytraverse(skip)]
client_config: PyRwLock<Option<Arc<rustls::ClientConfig>>>,
#[pytraverse(skip)]
chain_builder: PyRwLock<Option<Arc<VerifiedChainBuilder>>>,
#[pytraverse(skip)]
verified_chain: PyRwLock<Option<Vec<Vec<u8>>>>,
// Per-connection store containing the session selected by this connection.
#[pytraverse(skip)]
client_session_store: PyRwLock<Option<Arc<CapturingClientSessionStore>>>,
// Pending TLS output buffer for non-blocking sockets
// Stores unsent TLS bytes when sock_send() would block
// This prevents data loss when write_tls() drains rustls' internal buffer
// but the socket cannot accept all the data immediately
#[pytraverse(skip)]
pub(crate) pending_tls_output: PyMutex<Vec<u8>>,
#[pytraverse(skip)]
msg_state: PyMutex<super::msg::MsgState>,
pending_msg_exc: PyMutex<Option<PyBaseExceptionRef>>,
// Deferred client certificate verification error (for TLS 1.3)
// Stores error message if client cert verification failed during handshake
// Error is raised on first I/O operation after handshake
// Using Arc to share with the certificate verifier
#[pytraverse(skip)]
deferred_cert_error: Arc<ParkingRwLock<Option<String>>>,
}
#[pyclass(with(Constructor, Representable), flags(BASETYPE))]
impl PySSLSocket {
// Check if this is BIO mode
pub(crate) fn is_bio_mode(&self) -> bool {
matches!(self.io, SocketOrBio::Bio { .. })
}
// Get incoming BIO reference (for EOF checking)
pub(crate) fn incoming_bio(&self) -> Option<PyObjectRef> {
self.io.incoming().map(|bio| bio.into())
}
pub(crate) fn transport_eof(&self) -> bool {
self.io.incoming().is_none_or(|bio| PyMemoryBIO::eof(&bio))
}
/// rustls connection lock. Hold only around rustls operations, never
/// across socket or MemoryBIO I/O.
pub(crate) fn connection(&self) -> &PyMutex<Option<TlsConnection>> {
&self.connection
}
pub(crate) fn write_buffered_len(&self) -> usize {
self.connection
.lock()
.as_ref()
.map_or(0, TlsConnection::write_buffered_len)
}
pub(crate) fn set_write_buffered_len(&self, n: usize) {
if let Some(conn) = self.connection.lock().as_mut() {
conn.set_write_buffered_len(n);
}
}
pub(crate) fn observe_tls(&self, write: bool, bytes: &[u8], vm: &VirtualMachine) {
if bytes.is_empty() {
return;
}
let events = self.msg_state.lock().observe(write, bytes);
if events.is_empty() {
return;
}
let callback = self.context.read().msg_callback.read().clone();
let Some(callback) = callback else {
return;
};
let conn = self
.owner
.read()
.as_ref()
.and_then(|owner| owner.upgrade())
.unwrap_or_else(|| vm.ctx.none());
for event in events {
let result = callback.call(
(
conn.clone(),
vm.ctx.new_str(if write { "write" } else { "read" }),
vm.ctx.new_int(event.version),
vm.ctx.new_int(event.content_type),
vm.ctx.new_int(event.msg_type),
vm.ctx.new_bytes(event.data),
),
vm,
);
if let Err(exc) = result {
let mut pending = self.pending_msg_exc.lock();
if pending.is_none() {
*pending = Some(exc);
}
}
}
}
pub(crate) fn take_msg_exc(&self) -> Option<PyBaseExceptionRef> {
self.pending_msg_exc.lock().take()
}
// Check for deferred certificate verification errors (TLS 1.3)
// If an error exists, raise it and clear it from storage
fn check_deferred_cert_error(&self, vm: &VirtualMachine) -> PyResult<()> {
let error_opt = self.deferred_cert_error.read().clone();
if let Some(error_msg) = error_opt {
// Clear the error so it's only raised once
*self.deferred_cert_error.write() = None;
// Raise OSError with the stored error message
return Err(vm.new_os_error(error_msg));
}
Ok(())
}
// Get socket timeout as Duration
pub(crate) fn get_socket_timeout(&self, vm: &VirtualMachine) -> PyResult<Option<Duration>> {
if self.is_bio_mode() {
return Ok(None);
}
// Get timeout from socket
let timeout_obj = self
.io
.socket_object(vm)
.get_attr("gettimeout", vm)?
.call((), vm)?;
// timeout can be None (blocking), 0.0 (non-blocking), or positive float
if vm.is_none(&timeout_obj) {
// None means blocking forever
Ok(None)
} else {
let timeout_float: f64 = timeout_obj.try_into_value(vm)?;
if timeout_float <= 0.0 {
// 0 means non-blocking
Ok(Some(Duration::from_secs(0)))
} else {
// Positive timeout
Ok(Some(Duration::from_secs_f64(timeout_float)))
}
}
}
// Create and store a session object after successful handshake
fn create_session_after_handshake(&self, was_resumed: bool, vm: &VirtualMachine) {
// Only create session for client-side connections
if self.server_side {
return;
}
// Get server hostname
let server_name = self.server_hostname.read().clone();
let previous_session = self.session.read().clone();
// Try to get session data from context's session cache
// IMPORTANT: Acquire and release locks quickly to avoid deadlock
let (context_identity, session_cache_arc) = {
let context = self.context.read();
(
context.context_identity.clone(),
context.client_session_cache.clone(),
)
};
let cached_session_data = if let Some(ref name) = server_name {
let key = name.as_bytes().to_vec();
// Clone the data we need while holding the lock, then immediately release
let session_data_opt = {
let cache_guard = session_cache_arc.read();
cache_guard.get(&key).cloned() // Clone Arc<PyMutex<SessionData>>
}; // Lock released here
if let Some(session_data_arc) = session_data_opt {
session_data_arc.lock().clone()
} else {
SessionData::new(name, 7200)
}
} else {
SessionData::new("", 7200)
};
let session_data = if was_resumed {
previous_session
.as_ref()
.and_then(|session| session.downcast_ref::<PySSLSession>())
.map_or(cached_session_data, |session| SessionData {
server_name: server_name.clone().unwrap_or_default(),
session_id: session.session_id.clone(),
creation_time: session.creation_time,
lifetime: session.lifetime,
})
} else {
cached_session_data
};
let rustls_server_name = server_name.and_then(|name| ServerName::try_from(name).ok());
let protocol_version = self
.connection
.lock()
.as_ref()
.and_then(|connection| connection.protocol_version());
let session_kind = match protocol_version {
Some(rustls::ProtocolVersion::TLSv1_2) => ClientSessionKind::Tls12,
Some(rustls::ProtocolVersion::TLSv1_3) => ClientSessionKind::Tls13,
_ => return,
};
let Some(client_config) = self.client_config.write().take() else {
return;
};
let Some(session_store) = self.client_session_store.write().take() else {
return;
};
let session = PySSLSession {
context_identity,
client_config,
chain_builder: self
.chain_builder
.read()
.clone()
.expect("connection configured"),
session_store,
server_name: rustls_server_name,
kind: session_kind,
session_id: session_data.session_id,
creation_time: session_data.creation_time,
lifetime: session_data.lifetime,
has_ticket: true,
};
let py_session = session.into_pyobject(vm);
*self.session.write() = Some(py_session);
}
/// Retain the verified path and publish its selected capath anchor.
fn record_verified_chain(&self, was_resumed: bool) {
let Some(builder) = self.chain_builder.read().clone() else {
return;
};
// Like SSL_get0_verified_chain, resumption has no newly verified
// path. The peer certificate remains available separately. If the
// peer declined resumption, build the full handshake's path below.
if was_resumed {
*self.verified_chain.write() = None;
return;
}
let chain = self.connection.lock().as_ref().and_then(|conn| {
builder.build(
conn.peer_certificates()?,
rustls::pki_types::UnixTime::now(),
)
});
*self.verified_chain.write() = chain;
let Some(anchor) = self
.verified_chain
.read()
.as_ref()
.and_then(|chain| chain.last())
.cloned()
else {
return;
};
let context = self.context.read();
let mut root_certs = context.root_certs.write();
let mut ca_certs_der = context.ca_certs_der.write();
if !ca_certs_der.contains(&anchor) && builder.root_der.contains(&anchor) {
let is_ca = cert::is_ca_certificate(&anchor);
ca_certs_der.push(anchor.clone());
let _ = root_certs.add(anchor.into());
*context.x509_cert_count.write() += 1;
if is_ca {
*context.ca_cert_count.write() += 1;
}
}
}
fn complete_handshake(&self, vm: &VirtualMachine) {
*self.state.lock() = TlsState::Connected;
// Check if session was resumed - get value and release lock immediately
let was_resumed = self
.connection
.lock()
.as_ref()
.is_some_and(|conn| conn.handshake_kind() == Some(HandshakeKind::Resumed));
*self.session_was_reused.lock() = was_resumed;
// Update context session statistics if server-side
if self.server_side {
let context = self.context.read();
// Increment accept count for every successful server handshake
context.accept_count.fetch_add(1, Ordering::SeqCst);
// Increment hits count if session was resumed
if was_resumed {
context.session_hits.fetch_add(1, Ordering::SeqCst);
}
}
self.record_verified_chain(was_resumed);
self.create_session_after_handshake(was_resumed, vm);
}
// Internal implementation with timeout control
pub(crate) fn sock_wait_for_io_impl(
&self,
wait_kind: SockWaitKind,
vm: &VirtualMachine,
) -> PyResult<bool> {
if self.is_bio_mode() {
// BIO mode doesn't use select
return Ok(false);
}
#[cfg(target_arch = "wasm32")]
{
let _ = (wait_kind, vm);
return Ok(false);
}
#[cfg(not(target_arch = "wasm32"))]
{
// Get timeout
let timeout = self.get_socket_timeout(vm)?;
// Check for non-blocking mode (timeout = 0)
if let Some(t) = timeout
&& t.is_zero()
{
// Non-blocking mode - don't use select
return Ok(false);
}
// Use select with the effective timeout
let py_socket: PyRef<PySocket> = self.io.socket_object(vm).try_into_value(vm)?;
let socket = py_socket
.sock_snapshot()
.map_err(|e| vm.new_os_error(format!("Failed to get socket: {e}")))?;
sock_wait(&socket, wait_kind, timeout, vm)
}
}
// Internal implementation with explicit timeout override
pub(crate) fn sock_wait_for_io_with_timeout(
&self,
wait_kind: SockWaitKind,
timeout: Option<core::time::Duration>,
vm: &VirtualMachine,
) -> PyResult<bool> {
if self.is_bio_mode() {
// BIO mode doesn't use select
return Ok(false);
}
#[cfg(target_arch = "wasm32")]
{
let _ = (wait_kind, timeout, vm);
return Ok(false);
}
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(t) = timeout
&& t.is_zero()
{
// Non-blocking mode - don't use select
return Ok(false);
}
let py_socket: PyRef<PySocket> = self.io.socket_object(vm).try_into_value(vm)?;
let socket = py_socket
.sock_snapshot()
.map_err(|e| vm.new_os_error(format!("Failed to get socket: {e}")))?;
sock_wait(&socket, wait_kind, timeout, vm).map_err(|e| e.into_pyexception(vm))
}
}
fn handshake_completed(&self) -> bool {
matches!(
*self.state.lock(),
TlsState::Connected | TlsState::ShuttingDown | TlsState::ShutDown
)
}
fn reject_connection(
&self,
error: PyBaseExceptionRef,
bytes: Vec<u8>,
vm: &VirtualMachine,
) {
self.observe_tls(true, &bytes, vm);
self.pending_tls_output.lock().extend_from_slice(&bytes);
*self.state.lock() = TlsState::SendingAlert { error };
}
/// Receive ClientHello and select the context before rustls can generate
/// ServerHello. Keep protocol progress across non-blocking retries.
fn accept_client_hello(&self, vm: &VirtualMachine) -> PyResult<Option<Accepted>> {
loop {
// Never hold the state lock across Python callbacks or I/O.
// Reentrant handshake calls see an in-progress operation.
let state = core::mem::replace(&mut *self.state.lock(), TlsState::InProgress);
match state {
TlsState::WaitingForClientHello(mut acceptor) => {
match acceptor.accept() {
Ok(Some(accepted)) => {
let name = accepted.client_hello().server_name().map(str::to_owned);
if let Err((description, error)) =
self.invoke_sni_callback(name.as_deref(), vm)
{
self.reject_connection(
error,
super::handshake::sni_alert(description),
vm,
);
continue;
}
return Ok(Some(accepted));
}
Err((error, mut alert)) => {
let mut bytes = Vec::new();
// Vec writes cannot fail.
let _ = alert.write_all(&mut bytes);
let error = if matches!(error, rustls::Error::InvalidMessage(_)) {
SslError::PreauthData
} else {
SslError::from_rustls(error)
};
self.reject_connection(error.into_py_err(vm), bytes, vm);
continue;
}
Ok(None) => {}
}
let read = (|| {
if self.sock_wait_for_io_impl(SockWaitKind::Read, vm)? {
return Err(timeout_error_msg(
vm,
"The handshake operation timed out".to_owned(),
)
.upcast());
}
let bytes = self.sock_recv_at_most_one_tls_record(vm).map_err(|e| {
if is_blocking_io_error(&e, vm) {
create_ssl_want_read_error(vm).upcast()
} else {
e
}
})?;
if bytes.as_bytes().is_empty() {
return Err(
if self.is_bio_mode()
&& !self
.io
.incoming()
.as_ref()
.is_some_and(|bio| PyMemoryBIO::eof(bio))
{
create_ssl_want_read_error(vm).upcast()
} else {
SslError::Eof.into_py_err(vm)
},
);
}
self.observe_tls(false, bytes.as_bytes(), vm);
super::handshake::feed_acceptor(&mut acceptor, bytes.as_bytes())
.map_err(|e| e.into_pyexception(vm))?;
Ok(())
})();
*self.state.lock() = TlsState::WaitingForClientHello(acceptor);
read?;
}
TlsState::SendingAlert { error } => {
let result = self.flush_pending_tls_output(vm, None);
*self.state.lock() = TlsState::SendingAlert {
error: error.clone(),
};
result?;
return Err(error);
}
state @ (TlsState::Handshaking
| TlsState::Connected
| TlsState::ShuttingDown
| TlsState::ShutDown) => {
*self.state.lock() = state;
return Ok(None);
}
TlsState::InProgress => {
return Err(vm.new_value_error("handshake already in progress"));
}
}
}
}
/// Invoke SNI without any connection or state locks held. The alert is
/// returned separately from the local exception so the peer gets the
/// correct wire error before this operation reports failure.
fn invoke_sni_callback(
&self,
sni_name: Option<&str>,
vm: &VirtualMachine,
) -> Result<(), (u8, PyBaseExceptionRef)> {
let callback = self.context.read().sni_callback.read().clone();
let Some(callback) = callback else {
return Ok(());
};
let failed = || {
SslError::create_ssl_error_with_reason(
vm,
Some("SSL"),
"CALLBACK_FAILED",
"[SSL: CALLBACK_FAILED] callback failed",
)
};
let ssl_sock = self
.owner
.read()
.as_ref()
.and_then(|owner| owner.upgrade())
.ok_or_else(|| {
(
80,
SslError::create_ssl_error_with_reason(
vm,
Some("SSL"),
"PARSE_TLSEXT",
"[SSL: PARSE_TLSEXT] SNI callback owner is no longer available",
),
)
})?;
let server_name: PyObjectRef =
sni_name.map_or_else(|| vm.ctx.none(), |name| vm.ctx.new_str(name).into());
let context: PyObjectRef = self.context.read().clone().into();
let result = callback
.call((ssl_sock, server_name, context), vm)
.map_err(|exc| {
vm.run_unraisable(exc, Some("in ssl servername callback".to_owned()), callback);
(40, failed())
})?;
if vm.is_none(&result) {
return Ok(());
}
match result.try_to_value::<i32>(vm) {
Ok(alert) => Err((alert as u8, failed())),
Err(exc) => {
vm.run_unraisable(exc, None, result);
Err((80, failed()))
}
}
}
// Transport dispatch is shared by handshake, application data, alerts
// and shutdown, bypassing SSLSocket overrides that would reenter TLS.
pub(crate) fn sock_recv(&self, size: usize, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
self.io.recv(size, vm)
}
// Helper to receive data for at most one TLS record.
// May return incomplete data but never returns more when completes a
// previously incomplete TLS record.
pub(crate) fn sock_recv_at_most_one_tls_record(
&self,
vm: &VirtualMachine,
) -> PyResult<PyBytesRef> {
let obj_to_bytes = |bytes_obj| {
PyBytesRef::try_from_object(vm, bytes_obj)
.map_err(|_| vm.new_os_error("Expected bytes from recv"))
};
let (mut collected, remaining) = if self.record_cursor.lock().in_header() {
let want = self.record_cursor.lock().want();
let bytes = obj_to_bytes(self.sock_recv(want, vm)?)?;
self.record_cursor.lock().consume(bytes.as_bytes());
if self.record_cursor.lock().in_header() {
return Ok(bytes);
}
let remaining = self.record_cursor.lock().want();
if remaining == 0 {
return Ok(bytes);
}
(Some(bytes.as_bytes().to_vec()), remaining)
} else {
(None, self.record_cursor.lock().want())
};
let bytes = match self.sock_recv(remaining, vm) {
Ok(bytes) => obj_to_bytes(bytes)?,
Err(error) => {
// Header bytes already consumed must reach the TLS parser,
// even if the body is not yet available on a nonblocking socket.
if (is_blocking_io_error(&error, vm)
|| error.fast_isinstance(vm.ctx.exceptions.timeout_error))
&& let Some(header) = collected
{
return Ok(vm.ctx.new_bytes(header));
}
return Err(error);
}
};
self.record_cursor.lock().consume(bytes.as_bytes());
if let Some(collected) = collected.as_mut() {
collected.extend_from_slice(bytes.as_bytes());
}
Ok(collected.map_or(bytes, |bytes| vm.ctx.new_bytes(bytes)))
}
pub(crate) fn sock_send(&self, data: &[u8], vm: &VirtualMachine) -> PyResult<PyObjectRef> {
self.io.send(data, vm)
}
/// Resume pending output identically for socket and MemoryBIO transports.
pub(crate) fn flush_pending_tls_output(
&self,
vm: &VirtualMachine,
deadline: Option<std::time::Instant>,
) -> PyResult<()> {
let mut pending = self.pending_tls_output.lock();
while !pending.is_empty() {
let timeout = if let Some(deadline) = deadline {
Some(
deadline
.checked_duration_since(std::time::Instant::now())
.ok_or_else(|| {
timeout_error_msg(vm, "The write operation timed out".to_owned())
.upcast()
})?,
)
} else {
self.get_socket_timeout(vm)?
};
if self.sock_wait_for_io_with_timeout(SockWaitKind::Write, timeout, vm)? {
return Err(
timeout_error_msg(vm, "The write operation timed out".to_owned()).upcast(),
);
}
let result = self.sock_send(&pending, vm).map_err(|e| {
if is_blocking_io_error(&e, vm) {
create_ssl_want_write_error(vm).upcast()
} else {
e
}
})?;
let count = result.try_to_value::<usize>(vm)?;
if count == 0 {
return Err(create_ssl_want_write_error(vm).upcast());
}
pending.drain(..count);
}
Ok(())
}
/// Helper: Prepare TLS versions from context settings
fn prepare_tls_versions(&self) -> &'static [&'static rustls::SupportedProtocolVersion] {
let ctx = self.context.read();
let min_ver = *ctx.minimum_version.read();
let max_ver = *ctx.maximum_version.read();
let options = *ctx.options.read();
rustpython_host_env::ssl::rustls_versions(min_ver, max_ver, options)
}
/// Helper: Prepare KX groups (ECDH curve) from context settings
fn prepare_kx_groups(
&self,
vm: &VirtualMachine,
) -> PyResult<Option<Vec<&'static dyn SupportedKxGroup>>> {
let ctx = self.context.read();
let ecdh_curve = ctx.ecdh_curve.read().clone();
let suite_b_kx_groups = ctx.suite_b_kx_groups.read().clone();
drop(ctx);
if let Some(ref curve_name) = ecdh_curve {
match curve_name_to_kx_group(curve_name) {
Ok(groups) => Ok(Some(groups)),
Err(e) => Err(vm.new_value_error(format!("Failed to set ECDH curve: {e}"))),
}
} else {
// A SUITEB* cipher string pins its own groups, and nothing
// else asked for a curve.
Ok(suite_b_kx_groups)
}
}
/// Helper: Prepare all common protocol settings (versions, KX groups, ciphers, ALPN)
fn prepare_protocol_settings(&self, vm: &VirtualMachine) -> PyResult<ProtocolSettings> {
let ctx = self.context.read();
let versions = self.prepare_tls_versions();
let kx_groups = self.prepare_kx_groups(vm)?;
let cipher_suites = ctx.selected_ciphers.read().clone();
let alpn_protocols = ctx.alpn_protocols.read().clone();
Ok(ProtocolSettings {
versions,
kx_groups,
cipher_suites,
alpn_protocols,
})
}
/// Initialize server-side TLS connection with configuration
///
/// This method handles all server-side setup including:
/// - Certificate and key validation
/// - Client authentication configuration
/// - SNI (Server Name Indication) setup
/// - ALPN protocol negotiation
/// - Session resumption configuration
///
/// Continue the accepted ClientHello using the context selected by SNI.
fn initialize_server_connection(
&self,
conn_guard: &mut Option<TlsConnection>,
accepted: Accepted,
vm: &VirtualMachine,
) -> PyResult<()> {
let ctx = self.context.read();
let cert_keys = ctx.cert_keys.read();
if cert_keys.is_empty() {
return Err(vm.new_value_error(
"Server-side connection requires certificate and key (use load_cert_chain)",
));
}
// Clone cert_keys for use in config
// PrivateKeyDer doesn't implement Clone, use clone_key()
let cert_keys_clone: Vec<CertKeyPair> = cert_keys
.iter()
.map(|(ck, pk)| (ck.clone(), pk.clone_key()))
.collect();
drop(cert_keys);
// Prepare common protocol settings (TLS versions, ECDH curve, cipher suites, ALPN)
let protocol_settings = self.prepare_protocol_settings(vm)?;
let min_ver = *ctx.minimum_version.read();
// Check if client certificate verification is required
let verify_mode = *ctx.verify_mode.read();
let (root_store, ca_certs_der) = ctx.verification_roots();
let pha_enabled = *ctx.post_handshake_auth.read();
// Check if TLS 1.3 is being used
let is_tls13 = min_ver >= PROTO_TLSv1_3;
// For TLS 1.3: always use deferred validation for client certificates
// For TLS 1.2: use immediate validation during handshake
let use_deferred_validation = is_tls13
&& !pha_enabled
&& (verify_mode == CERT_REQUIRED || verify_mode == CERT_OPTIONAL);
// For TLS 1.3 + PHA: if PHA is enabled, don't request cert in initial handshake
// The certificate will be requested later via verify_client_post_handshake()
let request_initial_cert = if pha_enabled {
// PHA enabled: don't request cert initially (will use PHA later)
false
} else if verify_mode == CERT_REQUIRED || verify_mode == CERT_OPTIONAL {
// PHA not enabled or TLS 1.2: request cert in initial handshake
true
} else {
// CERT_NONE
false
};
// Certificate selection uses the actual ClientHello after SNI has
// selected the context, including multi-certificate configurations.
let cert_keys_only = cert_keys_clone.iter().map(|(ck, _)| ck.clone()).collect();
let cert_resolver: Option<Arc<dyn ResolvesServerCert>> =
Some(Arc::new(MultiCertResolver::new(cert_keys_only)));
// Extract cert_chain and private_key from first cert_key
//
// Note: Since we always use cert_resolver now, these values won't actually be used
// by create_server_config. But we still need to provide them for the API signature.
let (first_cert_key, _) = &cert_keys_clone[0];
let certs_clone = first_cert_key.cert.clone();
// Provide a dummy key since cert_resolver will handle cert selection
let key_clone = PrivateKeyDer::Pkcs8(Vec::new().into());
// Get shared server session storage and ticketer from context
let server_session_storage = ctx.rustls_server_session_store.clone();
let server_ticketer = ctx.server_ticketer.clone();
// Build server config using compat helper
let config_options = ServerConfigOptions {
protocol_settings,
ca_certs_der,
cert_chain: certs_clone,
private_key: key_clone,
root_store: if request_initial_cert {
Some(root_store)
} else {
None
},
request_client_cert: request_initial_cert,
use_deferred_validation,
cert_resolver,
deferred_cert_error: if use_deferred_validation {
Some(self.deferred_cert_error.clone())
} else {
None
},
session_storage: Some(server_session_storage),
ticketer: Some(server_ticketer),
};
// A capath may gain hashed entries between connections, so only
// cache configurations whose trust store is context-owned.
// A deferred verifier owns this connection's error slot, so it
// must never be reused by another connection.
let cache_server_config =
!use_deferred_validation && ctx.capath_state.read().directories.is_empty();
let cached_config_arc = if cache_server_config {
ctx.server_config.read().clone()
} else {
None
};
drop(ctx);
let (mut config_arc, chain_builder) = if let Some(cached) = cached_config_arc {
cached
} else {
let config =
create_server_config(config_options).map_err(|e| vm.new_value_error(e))?;
if cache_server_config {
let ctx = self.context.read();
*ctx.server_config.write() = Some(config.clone());
}
config
};
*self.chain_builder.write() = Some(chain_builder);
// The cache contains only context-owned configuration, never a
// particular connection's mutable keylog routing.
Arc::make_mut(&mut config_arc).key_log = self.key_log.clone();
match accepted.into_connection(config_arc) {
Ok(mut conn) => {
conn.set_buffer_limit(TLS_IO_BUFFER_LIMIT);
*conn_guard = Some(TlsConnection::new(Connection::Server(conn)));
*self.state.lock() = TlsState::Handshaking;
}
Err((error, mut alert)) => {
let mut bytes = Vec::new();
alert
.write_all(&mut bytes)
.map_err(|e| e.into_pyexception(vm))?;
self.reject_connection(SslError::from_rustls(error).into_py_err(vm), bytes, vm);
self.accept_client_hello(vm)?;
}
}
Ok(())
}
#[pymethod]
fn do_handshake(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
// Check if handshake already done
if zelf.handshake_completed() {
return Ok(());
}
let accepted = zelf.accept_client_hello(vm)?;
let mut conn_guard = zelf.connection.lock();
// Initialize connection if not already done
if conn_guard.is_none() {
if zelf.server_side {
if let Err(error) = zelf.initialize_server_connection(
&mut conn_guard,
accepted
.ok_or_else(|| vm.new_value_error("TLS connection is not available"))?,
vm,
) {
drop(conn_guard);
if matches!(*zelf.state.lock(), TlsState::SendingAlert { .. }) {
return Err(error);
}
zelf.reject_connection(error, super::handshake::sni_alert(40), vm);
return zelf.accept_client_hello(vm).map(|_| ());
}
} else {
// Client-side connection
let ctx = zelf.context.read();
// Prepare common protocol settings (TLS versions, ECDH curve, cipher suites, ALPN)
let protocol_settings = zelf.prepare_protocol_settings(vm)?;
// Clone values we need before building config
let verify_mode = *ctx.verify_mode.read();
let (root_store_clone, ca_certs_der_clone) = ctx.verification_roots();
// For client mTLS: extract cert_chain and private_key from first cert_key (if any)
// Now we store both CertifiedKey and PrivateKeyDer as tuple
let cert_keys_guard = ctx.cert_keys.read();
let (cert_chain_clone, private_key_opt) = if !cert_keys_guard.is_empty() {
let (first_cert_key, private_key) = &cert_keys_guard[0];
let certs = first_cert_key.cert.clone();
(certs, Some(private_key.clone_key()))
} else {
(Vec::new(), None)
};
drop(cert_keys_guard);
let check_hostname = *ctx.check_hostname.read();
let check_common_name =
*ctx.host_flags.read() & HOSTFLAG_NEVER_CHECK_SUBJECT == 0;
let verify_flags = *ctx.verify_flags.read();
let context_identity = ctx.context_identity.clone();
let session_cache = ctx.client_session_cache.clone();
// Get CRLs for revocation checking
let crls_clone = ctx.crls.read().clone();
// Drop ctx early to avoid borrow conflicts
drop(ctx);
// Parse server name for SNI
// Convert to ServerName
use rustls::pki_types::ServerName;
let hostname_opt = zelf.server_hostname.read().clone();
let server_name = if let Some(ref hostname) = hostname_opt {
// Use the provided hostname for SNI
ServerName::try_from(hostname.clone()).map_err(|e| {
vm.new_value_error(format!("Invalid server hostname: {e:?}"))
})?
} else {
// When server_hostname=None, use an IP address to suppress SNI
// no hostname = no SNI extension
ServerName::IpAddress(
core::net::IpAddr::V4(core::net::Ipv4Addr::LOCALHOST).into(),
)
};
let explicit_session = zelf.session.read().clone();
let session_store = Arc::new(CapturingClientSessionStore::new(session_cache));
let (mut config, chain_builder) = if let Some(session) = explicit_session {
let session = session
.downcast_ref::<PySSLSession>()
.ok_or_else(|| vm.new_type_error("Value is not a SSLSession."))?;
if !Arc::ptr_eq(&session.context_identity, &context_identity) {
return Err(
vm.new_value_error("Session refers to a different SSLContext.")
);
}
if session.server_name.as_ref() == Some(&server_name) {
session.session_store.transfer_session(
&session_store,
&server_name,
session.kind,
);
}
let mut config = (*session.client_config).clone();
config.resumption =
rustls::client::Resumption::store(session_store.clone());
(Arc::new(config), session.chain_builder.clone())
} else {
let config_options = ClientConfigOptions {
protocol_settings,
root_store: Some(root_store_clone),
ca_certs_der: ca_certs_der_clone,
cert_chain: if !cert_chain_clone.is_empty() {
Some(cert_chain_clone)
} else {
None
},
private_key: private_key_opt,
verify_server_cert: verify_mode != CERT_NONE,
check_hostname,
check_common_name,
verify_flags,
session_store: Some(session_store.clone()),
crls: crls_clone,
};
create_client_config(config_options).map_err(|e| vm.new_value_error(e))?
};
Arc::make_mut(&mut config).key_log = zelf.key_log.clone();
*zelf.chain_builder.write() = Some(chain_builder);
*zelf.client_config.write() = Some(config.clone());
*zelf.client_session_store.write() = Some(session_store);
let mut conn = ClientConnection::new(config, server_name).map_err(|e| {
vm.new_value_error(format!("Failed to create client connection: {e}"))
})?;
conn.set_buffer_limit(TLS_IO_BUFFER_LIMIT);
*conn_guard = Some(TlsConnection::new(Connection::Client(conn)));
}
}
drop(conn_guard);
// Perform the actual handshake by exchanging data with the socket/BIO
let handshake_result = ssl_do_handshake(zelf, vm);
if let Err(error @ (SslError::Rustls(_) | SslError::PreauthData)) = handshake_result {
// rustls queued the fatal alert while processing the failing
// record. Retain it and the original error across output retries.
let bytes = zelf
.connection
.lock()
.as_mut()
.and_then(|conn| conn.drain_tls().ok())
.unwrap_or_default();
zelf.reject_connection(error.into_py_err(vm), bytes, vm);
return zelf.accept_client_hello(vm).map(|_| ());
}
handshake_result.map_err(|e| e.into_py_err(vm))?;
if let Some(exc) = zelf.take_msg_exc() {
return Err(exc);
}
zelf.complete_handshake(vm);
Ok(())
}
#[pymethod]
fn read(
zelf: &Py<Self>,
len: OptionalArg<isize>,
buffer: OptionalArg<ArgMemoryBuffer>,
vm: &VirtualMachine,
) -> PyResult {
// Convert len to usize, defaulting to 1024 if not provided
// -1 means read all available data (treat as large buffer size)
let len_val = len.unwrap_or(PEM_BUFSIZE as isize);
let mut len = if len_val == -1 {
// -1 is only valid when a buffer is provided
match &buffer {
OptionalArg::Present(buf_arg) => buf_arg.len(),
OptionalArg::Missing => {
return Err(vm.new_value_error("negative read length"));
}
}
} else if len_val < 0 {
return Err(vm.new_value_error("negative read length"));
} else {
len_val as usize
};
// if buffer is provided, limit len to buffer size
if let OptionalArg::Present(buf_arg) = &buffer {
let buf_len = buf_arg.len();
if len_val <= 0 || len > buf_len {
len = buf_len;
}
}
// return empty bytes immediately for len=0
if len == 0 {
return match buffer {
OptionalArg::Present(_) => Ok(vm.ctx.new_int(0).into()),
OptionalArg::Missing => Ok(vm.ctx.new_bytes(vec![]).into()),
};
}
// Ensure handshake is done - if not, complete it first
// This matches OpenSSL behavior where SSL_read() auto-completes handshake
if !zelf.handshake_completed() {
Self::do_handshake(zelf, vm)?;
}
// Check if connection has been shut down
// Only block after shutdown is COMPLETED, not during shutdown process
if matches!(*zelf.state.lock(), TlsState::ShutDown) {
return Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"cannot read after shutdown",
)
.upcast());
}
// Helper function to handle return value based on buffer presence
let return_data = |data: Vec<u8>,
buffer_arg: &OptionalArg<ArgMemoryBuffer>,
vm: &VirtualMachine|
-> PyResult<PyObjectRef> {
match buffer_arg {
OptionalArg::Present(buf_arg) => {
// Write into buffer and return number of bytes written
let n = data.len();
if n > 0 {
let mut buf = buf_arg.borrow_buf_mut();
let buf_slice = &mut *buf;
let copy_len = n.min(buf_slice.len());
buf_slice[..copy_len].copy_from_slice(&data[..copy_len]);
}
Ok(vm.ctx.new_int(n).into())
}
OptionalArg::Missing => {
// Return bytes object
Ok(vm.ctx.new_bytes(data).into())
}
}
};
// Use compat layer for unified read logic with proper EOF handling
// This matches SSL_read_ex() approach
let mut buf = vm.new_zeroed_bytes(len)?;
let read_result = crate::ssl::compat::ssl_read(zelf, &mut buf, vm);
match read_result {
Ok(n) => {
// Check for deferred certificate verification errors (TLS 1.3)
// Must be checked AFTER ssl_read, as the error is set during I/O
zelf.check_deferred_cert_error(vm)?;
if let Some(exc) = zelf.take_msg_exc() {
return Err(exc);
}
buf.truncate(n);
return_data(buf, &buffer, vm)
}
Err(error) if error.is_eof() => {
// If plaintext is still buffered, return it before EOF.
let pending = {
let mut conn_guard = zelf.connection.lock();
let conn = match conn_guard.as_mut() {
Some(conn) => conn,
None => return Err(create_ssl_eof_error(vm).upcast()),
};
conn.pending_plaintext()
};
if pending > 0 {
let mut buf = vec![0u8; pending.min(len)];
let read_retry = crate::ssl::compat::ssl_read(zelf, &mut buf, vm);
if let Ok(n) = read_retry {
buf.truncate(n);
return return_data(buf, &buffer, vm);
}
}
// EOF occurred in violation of protocol (unexpected closure)
Err(create_ssl_eof_error(vm).upcast())
}
Err(error) if error.is_zero_return() => {
// If plaintext is still buffered, return it before clean EOF.
let pending = {
let mut conn_guard = zelf.connection.lock();
let conn = match conn_guard.as_mut() {
Some(conn) => conn,
None => return Err(create_ssl_zero_return_error(vm).upcast()),
};
conn.pending_plaintext()
};
if pending > 0 {
let mut buf = vec![0u8; pending.min(len)];
let read_retry = crate::ssl::compat::ssl_read(zelf, &mut buf, vm);
if let Ok(n) = read_retry {
buf.truncate(n);
return return_data(buf, &buffer, vm);
}
}
// Clean closure via close_notify from peer.
// If we already sent close_notify (unwrap was called),
// raise SSLZeroReturnError (bidirectional shutdown).
// Otherwise return empty bytes, which callers (asyncore,
// asyncio sslproto) interpret as EOF.
if matches!(
*zelf.state.lock(),
TlsState::ShuttingDown | TlsState::ShutDown
) {
Err(create_ssl_zero_return_error(vm).upcast())
} else {
return_data(vec![], &buffer, vm)
}
}
Err(crate::ssl::compat::SslError::WantRead) => {
// Non-blocking mode: would block
Err(create_ssl_want_read_error(vm).upcast())
}
Err(crate::ssl::compat::SslError::WantWrite) => {
// Non-blocking mode: would block on write
Err(create_ssl_want_write_error(vm).upcast())
}
Err(crate::ssl::compat::SslError::Timeout(msg)) => {
Err(timeout_error_msg(vm, msg).upcast())
}
Err(crate::ssl::compat::SslError::Py(e)) => {
// Python exception - pass through
Err(e)
}
Err(e) => {
// Other SSL errors
Err(e.into_py_err(vm))
}
}
}
#[pymethod]
fn pending(zelf: &Py<Self>) -> usize {
// Returns the number of already decrypted bytes available for read
// This is critical for asyncore's readable() method which checks socket.pending() > 0
let mut conn_guard = zelf.connection.lock();
let conn = match conn_guard.as_mut() {
Some(c) => c,
None => return 0, // No connection established yet
};
conn.pending_plaintext()
}
#[pymethod]
fn write(zelf: &Py<Self>, b: ArgBytesLike, vm: &VirtualMachine) -> PyResult<usize> {
let data_bytes = b.borrow_buf();
let data_len = data_bytes.len();
if data_len == 0 {
return Ok(0);
}
// Ensure handshake is done (SSL_write auto-completes handshake)
if !zelf.handshake_completed() {
Self::do_handshake(zelf, vm)?;
}
// Application data cannot follow our close_notify.
if matches!(
*zelf.state.lock(),
TlsState::ShuttingDown | TlsState::ShutDown
) {
return Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"cannot write after shutdown",
)
.upcast());
}
// Call ssl_write (matches CPython's SSL_write_ex loop)
let result = crate::ssl::compat::ssl_write(zelf, data_bytes.as_ref(), vm);
match result {
Ok(n) => {
zelf.check_deferred_cert_error(vm)?;
if let Some(exc) = zelf.take_msg_exc() {
return Err(exc);
}
Ok(n)
}
Err(crate::ssl::compat::SslError::WantRead) => {
Err(create_ssl_want_read_error(vm).upcast())
}
Err(crate::ssl::compat::SslError::WantWrite) => {
Err(create_ssl_want_write_error(vm).upcast())
}
Err(crate::ssl::compat::SslError::Timeout(msg)) => {
Err(timeout_error_msg(vm, msg).upcast())
}
Err(e) => Err(e.into_py_err(vm)),
}
}
#[pymethod]
fn getpeercert(
zelf: &Py<Self>,
args: GetCertArgs,
vm: &VirtualMachine,
) -> PyResult<Option<PyObjectRef>> {
let binary = args.der;
// Check if handshake is complete
if !zelf.handshake_completed() {
return Err(vm.new_value_error("handshake not done yet"));
}
// Extract DER bytes from connection, releasing lock quickly
let der_bytes = {
let conn_guard = zelf.connection.lock();
let conn = conn_guard
.as_ref()
.ok_or_else(|| vm.new_value_error("No TLS connection established"))?;
let Some(peer_certificates) = conn.peer_certificates() else {
return Ok(None);
};
let cert = peer_certificates
.first()
.ok_or_else(|| vm.new_value_error("No peer certificate available"))?;
cert.as_ref().to_vec()
};
if binary {
// Return DER-encoded certificate as bytes
return Ok(Some(vm.ctx.new_bytes(der_bytes).into()));
}
// Dictionary mode: check verify_mode
let verify_mode = *zelf.context.read().verify_mode.read();
if verify_mode == CERT_NONE {
// Return empty dict when CERT_NONE
return Ok(Some(vm.ctx.new_dict().into()));
}
cert::cert_der_to_dict_helper(vm, &der_bytes).map(Some)
}
#[pymethod]
fn cipher(zelf: &Py<Self>) -> Option<(String, String, i32)> {
// Extract cipher suite, releasing lock quickly
let suite = {
let conn_guard = zelf.connection.lock();
conn_guard.as_ref()?.negotiated_cipher_suite()?
};
// Extract cipher information outside the lock
let cipher = cipher::describe(&suite);
// Note: returns a 3-tuple (name, protocol_version, bits)
// The 'description' field is part of get_ciphers() output, not cipher()
Some((
cipher.name.to_owned(),
cipher.protocol.to_owned(),
cipher.bits.into(),
))
}
#[pymethod]
fn version(zelf: &Py<Self>) -> Option<String> {
// Extract cipher suite, releasing lock quickly
let suite = {
let conn_guard = zelf.connection.lock();
conn_guard.as_ref()?.negotiated_cipher_suite()?
};
// Convert to string outside the lock
let version_str = match suite.version().version {
rustls::ProtocolVersion::TLSv1_2 => "TLSv1.2",
rustls::ProtocolVersion::TLSv1_3 => "TLSv1.3",
_ => "Unknown",
};
Some(version_str.to_string())
}
#[pymethod]
fn selected_alpn_protocol(zelf: &Py<Self>) -> Option<String> {
let conn_guard = zelf.connection.lock();
let conn = conn_guard.as_ref()?;
let alpn_bytes = conn.alpn_protocol()?;
// Null byte protocol (vec![0u8]) means no actual ALPN match (fallback protocol)
if alpn_bytes.is_empty() || alpn_bytes == [0u8] {
return None;
}
// Convert bytes to string
String::from_utf8(alpn_bytes.to_vec()).ok()
}
#[pymethod]
fn selected_npn_protocol(_zelf: &Py<Self>) -> Option<String> {
// NPN (Next Protocol Negotiation) is the predecessor to ALPN
// It was deprecated in favor of ALPN (RFC 7301)
// Rustls doesn't support NPN, only ALPN
// Return None to indicate NPN is not supported
None
}
#[pygetset]
fn owner(zelf: &Py<Self>) -> Option<PyObjectRef> {
zelf.owner.read().as_ref().and_then(|owner| owner.upgrade())
}
#[pygetset(setter)]
fn set_owner(zelf: &Py<Self>, owner: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
*zelf.owner.write() = Some(owner.downgrade(None, vm)?);
Ok(())
}
#[pygetset]
fn server_side(zelf: &Py<Self>) -> bool {
zelf.server_side
}
#[pygetset]
fn context(zelf: &Py<Self>) -> PyRef<PySSLContext> {
zelf.context.read().clone()
}
#[pygetset(setter)]
fn set_context(zelf: &Py<Self>, value: PyRef<PySSLContext>, _vm: &VirtualMachine) {
zelf.key_log.set_sink(value.key_log.clone());
// Update context reference immediately
// SSL_set_SSL_CTX allows context changes at any time,
// even after handshake completion
*zelf.context.write() = value;
}
#[pygetset]
fn server_hostname(zelf: &Py<Self>) -> Option<String> {
zelf.server_hostname.read().clone()
}
#[pygetset(setter)]
fn set_server_hostname(
zelf: &Py<Self>,
value: Option<PyUtf8StrRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
// Check if handshake is already done
if zelf.handshake_completed() {
return Err(
vm.new_value_error("Cannot set server_hostname on socket after handshake")
);
}
// Validate hostname
let hostname_string = value
.map(|s| {
validate_hostname(s.as_str(), vm)?;
Ok::<String, _>(s.as_str().to_owned())
})
.transpose()?;
*zelf.server_hostname.write() = hostname_string;
Ok(())
}
#[pygetset]
fn session(zelf: &Py<Self>, vm: &VirtualMachine) -> PyObjectRef {
// Return the stored session object if any
let sess = zelf.session.read().clone();
sess.unwrap_or_else(|| vm.ctx.none())
}
#[pygetset(setter)]
fn set_session(zelf: &Py<Self>, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let session = value
.downcast_ref::<PySSLSession>()
.ok_or_else(|| vm.new_type_error("Value is not a SSLSession."))?;
if !Arc::ptr_eq(
&session.context_identity,
&zelf.context.read().context_identity,
) {
return Err(vm.new_value_error("Session refers to a different SSLContext."));
}
// Check if this is a client socket
if zelf.server_side {
return Err(vm.new_value_error("Cannot set session for server-side SSLSocket"));
}
// Check if handshake is already done
if zelf.handshake_completed() {
return Err(vm.new_value_error("Cannot set session after handshake."));
}
// Store the session for potential use during handshake
*zelf.session.write() = Some(value);
Ok(())
}
#[pygetset]
fn session_reused(zelf: &Py<Self>) -> bool {
// Return the tracked session reuse status
*zelf.session_was_reused.lock()
}
#[pymethod]
fn compression(_zelf: &Py<Self>) -> Option<&'static str> {
// rustls doesn't support compression
None
}
#[pymethod]
fn get_unverified_chain(
zelf: &Py<Self>,
vm: &VirtualMachine,
) -> PyResult<Option<PyListRef>> {
// Get peer certificates from the connection
let conn_guard = zelf.connection.lock();
let conn = conn_guard
.as_ref()
.ok_or_else(|| vm.new_value_error("Handshake not completed"))?;
let certs = conn.peer_certificates();
let Some(certs) = certs else {
return Ok(None);
};
// Convert to list of Certificate objects
let cert_list: Vec<PyObjectRef> = certs
.iter()
.map(|cert_der| {
let cert_bytes = cert_der.as_ref().to_vec();
PySSLCertificate {
der_bytes: cert_bytes,
}
.into_ref(&vm.ctx)
.into()
})
.collect();
Ok(Some(vm.ctx.new_list(cert_list)))
}
#[pymethod]
fn get_verified_chain(zelf: &Py<Self>, vm: &VirtualMachine) -> Option<PyListRef> {
let chain_der = zelf.verified_chain.read().clone()?;
// Convert DER chain to Python list of Certificate objects
let cert_list: Vec<PyObjectRef> = chain_der
.into_iter()
.map(|der_bytes| PySSLCertificate { der_bytes }.into_ref(&vm.ctx).into())
.collect();
Some(vm.ctx.new_list(cert_list))
}
#[pymethod]
fn shutdown(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
// A failed shutdown may still owe the peer a fatal alert. Resume
// that output on unwrap retries before reporting the saved error.
if matches!(*zelf.state.lock(), TlsState::SendingAlert { .. })
&& !zelf.pending_tls_output.lock().is_empty()
{
return zelf
.accept_client_hello(vm)
.map(|_| zelf.io.socket_object(vm));
}
if !zelf.handshake_completed() {
return Err(SslError::create_ssl_error_with_reason(
vm,
Some("SSL"),
"SHUTDOWN_WHILE_IN_INIT",
"[SSL: SHUTDOWN_WHILE_IN_INIT] shutdown while in init",
));
}
if matches!(*zelf.state.lock(), TlsState::ShutDown) {
return Ok(zelf.io.socket_object(vm));
}
let timeout = zelf.get_socket_timeout(vm)?;
let deadline = timeout
.filter(|timeout| !timeout.is_zero())
.map(|timeout| std::time::Instant::now() + timeout);
{
let mut conn_guard = zelf.connection.lock();
let conn = conn_guard
.as_mut()
.ok_or_else(|| vm.new_value_error("Connection not established"))?;
if matches!(*zelf.state.lock(), TlsState::Connected) {
// rustls queues close_notify after previously buffered data.
// Record this before any fallible write so retries never queue
// another alert, even if the transport cannot accept output.
conn.send_close_notify();
*zelf.state.lock() = TlsState::ShuttingDown;
}
}
let result = (|| loop {
let bytes = {
let mut conn_guard = zelf.connection.lock();
let conn = conn_guard
.as_mut()
.ok_or_else(|| vm.new_value_error("Connection not established"))?;
conn.drain_tls()
.map_err(|e| SslError::from(e).into_py_err(vm))?
};
super::compat::send_all_bytes(zelf, bytes, vm, deadline)
.map_err(|e| e.into_py_err(vm))?;
let io_state = {
let mut conn_guard = zelf.connection.lock();
let conn = conn_guard
.as_mut()
.ok_or_else(|| vm.new_value_error("Connection not established"))?;
conn.process_packets()
.map_err(|e| SslError::from(e).into_py_err(vm))?
};
if io_state.plaintext_bytes_to_read() != 0 {
return Err(SslError::create_ssl_error_with_reason(
vm,
Some("SSL"),
"APPLICATION_DATA_AFTER_CLOSE_NOTIFY",
"[SSL: APPLICATION_DATA_AFTER_CLOSE_NOTIFY] application data after close notify",
));
}
if io_state.peer_has_closed() {
*zelf.state.lock() = TlsState::ShutDown;
return Ok(zelf.io.socket_object(vm));
}
let remaining = match deadline {
Some(deadline) => Some(
deadline
.checked_duration_since(std::time::Instant::now())
.ok_or_else(|| {
timeout_error_msg(vm, "The read operation timed out".to_owned())
.upcast()
})?,
),
None => timeout,
};
if zelf.sock_wait_for_io_with_timeout(SockWaitKind::Read, remaining, vm)? {
return Err(
timeout_error_msg(vm, "The read operation timed out".to_owned()).upcast(),
);
}
// Stop at each TLS record boundary, leaving an unencrypted
// trailer after close_notify in the socket or incoming BIO.
let data = super::compat::recv_at_most_one_tls_record(zelf, vm)
.map_err(|e| e.into_py_err(vm))?;
let mut conn_guard = zelf.connection.lock();
let conn = conn_guard
.as_mut()
.ok_or_else(|| vm.new_value_error("Connection not established"))?;
super::compat::ssl_read_tls_records(conn, data, zelf.is_bio_mode(), vm)
.map_err(|e| e.into_py_err(vm))?;
})();
if let Err(error) = &result
&& error.fast_isinstance(PySSLError::class(&vm.ctx))
&& !error.fast_isinstance(PySSLWantReadError::class(&vm.ctx))
&& !error.fast_isinstance(PySSLWantWriteError::class(&vm.ctx))
{
// A protocol failure cannot resume as a normal shutdown. Keep
// any fatal alert rustls queued and preserve the original error.
let bytes = zelf
.connection
.lock()
.as_mut()
.and_then(|conn| conn.drain_tls().ok())
.unwrap_or_default();
zelf.reject_connection(error.clone(), bytes, vm);
return zelf
.accept_client_hello(vm)
.map(|_| zelf.io.socket_object(vm));
}
result
}
#[pymethod]
fn shared_ciphers(zelf: &Py<Self>, vm: &VirtualMachine) -> Option<PyListRef> {
// Return None for client-side sockets
if !zelf.server_side {
return None;
}
// Check if handshake completed
if !zelf.handshake_completed() {
return None;
}
// Get negotiated cipher suite from rustls
let conn_guard = zelf.connection.lock();
let conn = conn_guard.as_ref()?;
let suite = conn.negotiated_cipher_suite()?;
let cipher = cipher::describe(&suite);
// Return as list with single tuple (name, version, bits)
let tuple = vm.ctx.new_tuple(vec![
vm.ctx.new_str(cipher.name).into(),
vm.ctx.new_str(cipher.protocol).into(),
vm.ctx.new_int(cipher.bits).into(),
]);
Some(vm.ctx.new_list(vec![tuple.into()]))
}
#[pymethod]
fn verify_client_post_handshake(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
// TLS 1.3 post-handshake authentication
// This is only valid for server-side TLS 1.3 connections
// Check if this is a server-side socket
if !zelf.server_side {
return Err(vm.new_value_error(
"Cannot perform post-handshake authentication on client-side socket",
));
}
// Check if handshake has been completed
if !zelf.handshake_completed() {
return Err(vm.new_value_error(
"Handshake must be completed before post-handshake authentication",
));
}
// Check connection exists and protocol version
let conn_guard = zelf.connection.lock();
if let Some(conn) = conn_guard.as_ref() {
let version = match conn.inner() {
Connection::Client(_) => {
return Err(vm.new_value_error(
"Post-handshake authentication requires server socket",
));
}
Connection::Server(server) => server.protocol_version(),
};
// Post-handshake auth is only available in TLS 1.3
if version != Some(rustls::ProtocolVersion::TLSv1_3) {
// Get SSLError class from ssl module (not _ssl)
// ssl.py imports _ssl.SSLError as ssl.SSLError
let ssl_mod = vm.import("ssl", 0)?;
let ssl_error_class = ssl_mod.get_attr("SSLError", vm)?;
// Create SSLError instance with message containing WRONG_SSL_VERSION
let msg = "[SSL: WRONG_SSL_VERSION] wrong ssl version";
let args = vm.ctx.new_tuple(vec![vm.ctx.new_str(msg).into()]);
let exc = ssl_error_class.call((args,), vm)?;
return Err(exc
.downcast()
.map_err(|_| vm.new_type_error("Failed to create SSLError"))?);
}
} else {
return Err(vm.new_value_error("No SSL connection established"));
}
// rustls doesn't provide an API for post-handshake authentication.
// The rustls TLS library does not support requesting client certificates
// after the initial handshake is completed.
// Raise SSLError instead of NotImplementedError for compatibility
Err(vm
.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
"Post-handshake authentication is not supported by the rustls backend. \
The rustls TLS library does not provide an API to request client certificates \
after the initial handshake. Consider requesting the client certificate \
during the initial handshake by setting the appropriate verify_mode before \
calling do_handshake().",
)
.upcast())
}
#[pymethod]
fn get_channel_binding(
zelf: &Py<Self>,
args: ChannelBindingArgs,
vm: &VirtualMachine,
) -> PyResult<Option<PyBytesRef>> {
let cb_type_str = args.cb_type.as_str();
if cb_type_str != "tls-unique" {
return Err(super::msg::unknown_binding_type_error(cb_type_str, vm));
}
if !zelf.handshake_completed() {
return Ok(None);
}
let master_secret = zelf.key_log.master_secret();
let transcript = zelf.msg_state.lock().transcript().to_vec();
let session_reused = *zelf.session_was_reused.lock();
let suite = {
let conn_guard = zelf.connection.lock();
conn_guard
.as_ref()
.and_then(|conn| conn.negotiated_cipher_suite())
};
let Some(master_secret) = master_secret else {
return Ok(None);
};
let Some(suite) = suite else {
return Ok(None);
};
Ok(super::msg::tls12_unique(
suite,
&master_secret,
&transcript,
zelf.server_side,
session_reused,
)
.map(|bytes| vm.ctx.new_bytes(bytes)))
}
}
impl Representable for PySSLSocket {
#[inline]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok("<SSLSocket>".to_owned())
}
}
impl Constructor for PySSLSocket {
type Args = ();
fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error(
"Cannot directly instantiate SSLSocket, use SSLContext.wrap_socket()",
))
}
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
unimplemented!("use slot_new")
}
}
// Clean up SSL socket resources on drop
impl Drop for PySSLSocket {
fn drop(&mut self) {
// Only clear connection state.
// Do NOT clear pending_tls_output - it may contain data that hasn't
// been flushed to the socket yet. SSLSocket._real_close() in Python
// doesn't call shutdown(), so when the socket is closed, pending TLS
// data would be lost if we clear it here.
// All fields (Vec, primitives) are automatically freed when the
// struct is dropped, so explicit clearing is unnecessary.
let _ = self.connection.lock().take();
}
}
// MemoryBIO - provides in-memory buffer for SSL/TLS I/O
#[pyattr]
#[pyclass(name = "MemoryBIO", module = "_ssl")]
#[derive(Debug, PyPayload)]
struct PyMemoryBIO {
inner: PyMutex<rustpython_host_env::ssl::MemoryBio>,
}
#[pyclass(with(Constructor), flags(BASETYPE))]
impl PyMemoryBIO {
#[pymethod]
fn read(zelf: &Py<Self>, args: MemoryBioReadArgs, vm: &VirtualMachine) -> PyBytesRef {
let mut bio = zelf.inner.lock();
let read_len = if args.size >= 0 {
args.size as usize
} else {
bio.pending()
};
vm.ctx.new_bytes(bio.read(read_len))
}
#[pymethod]
fn write(zelf: &Py<Self>, b: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
// Check if it's a memoryview and if it's contiguous
if let Ok(mem_view) = b.get_attr("c_contiguous", vm) {
// It's a memoryview, check if contiguous
let is_contiguous: bool = mem_view.try_to_bool(vm)?;
if !is_contiguous {
return Err(vm.new_buffer_error("non-contiguous buffer is not supported"));
}
}
// Convert to bytes-like object
let bytes_like = ArgBytesLike::try_from_object(vm, b)?;
let data = bytes_like.borrow_buf();
zelf.inner.lock().write(&data).map_err(|err| {
vm.new_os_subtype_error(
PySSLError::class(&vm.ctx).to_owned(),
None,
err.to_string(),
)
.upcast()
})
}
#[pymethod]
fn write_eof(zelf: &Py<Self>, _vm: &VirtualMachine) {
zelf.inner.lock().write_eof();
}
#[pygetset]
fn pending(zelf: &Py<Self>) -> i32 {
zelf.inner.lock().pending() as i32
}
#[pygetset]
fn eof(zelf: &Py<Self>) -> bool {
zelf.inner.lock().eof()
}
}
impl Representable for PyMemoryBIO {
#[inline]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok("<MemoryBIO>".to_owned())
}
}
impl Constructor for PyMemoryBIO {
type Args = ();
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
Ok(Self {
inner: PyMutex::new(rustpython_host_env::ssl::MemoryBio::new()),
})
}
}
// SSLSession - represents a cached SSL session
// NOTE: This is an EMULATION - actual session data is managed by Rustls internally
#[pyattr]
#[pyclass(name = "SSLSession", module = "_ssl", unhashable = true)]
#[derive(Debug, PyPayload)]
struct PySSLSession {
context_identity: Arc<()>,
client_config: Arc<rustls::ClientConfig>,
chain_builder: Arc<VerifiedChainBuilder>,
session_store: Arc<CapturingClientSessionStore>,
server_name: Option<ServerName<'static>>,
kind: ClientSessionKind,
// Session ID - synthetic ID generated from metadata (NOT actual TLS session ID)
session_id: Vec<u8>,
// Session metadata
creation_time: std::time::SystemTime,
// Lifetime in seconds (default 7200 = 2 hours)
lifetime: u64,
has_ticket: bool,
}
#[pyclass(flags(BASETYPE), with(Comparable))]
impl PySSLSession {
#[pygetset]
fn time(zelf: &Py<Self>) -> i64 {
// Return session creation time as Unix timestamp
zelf.creation_time
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
#[pygetset]
fn timeout(zelf: &Py<Self>) -> i64 {
// Return session timeout/lifetime in seconds
zelf.lifetime as i64
}
#[pygetset]
fn ticket_lifetime_hint(zelf: &Py<Self>) -> i64 {
// Return ticket lifetime hint (same as timeout for rustls)
zelf.lifetime as i64
}
#[pygetset]
fn id(zelf: &Py<Self>, vm: &VirtualMachine) -> PyBytesRef {
vm.ctx.new_bytes(zelf.session_id.clone())
}
#[pygetset]
fn has_ticket(zelf: &Py<Self>) -> bool {
zelf.has_ticket
}
}
impl Comparable for PySSLSession {
fn cmp(
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
_vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
op.eq_only(|| {
if let Some(other_session) = other.downcast_ref::<Self>() {
Ok((zelf.session_id == other_session.session_id).into())
} else {
Ok(PyComparisonValue::NotImplemented)
}
})
}
}
impl Representable for PySSLSession {
#[inline]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok("<SSLSession>".to_owned())
}
}
// Helper functions
// OID module already imported at top of _ssl module
#[derive(FromArgs)]
struct ChannelBindingArgs {
#[pyarg(any, default = "tls-unique")]
cb_type: PyUtf8StrRef,
}
#[derive(FromArgs)]
struct MemoryBioReadArgs {
#[pyarg(positional, default = -1)]
size: i32,
}
#[derive(FromArgs)]
struct Txt2ObjArgs {
txt: PyUtf8StrRef,
#[pyarg(any, default)]
name: bool,
}
#[pyfunction]
fn txt2obj(args: Txt2ObjArgs, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let txt = args.txt.as_str();
let name = args.name;
// If name=False (default), only accept OID strings
// If name=True, accept both names and OID strings
let entry = if txt.chars().next().is_some_and(|c| c.is_ascii_digit()) {
// Looks like an OID string (starts with digit)
oid::find_by_oid_string(txt)
} else if name {
// name=True: allow shortname/longname lookup
oid::find_by_name(txt)
} else {
// name=False: only OID strings allowed, not names
None
};
let entry = entry.ok_or_else(|| vm.new_value_error(format!("unknown object '{txt}'")))?;
// Return tuple: (nid, shortname, longname, oid)
Ok(vm
.new_tuple((
vm.ctx.new_int(entry.nid),
vm.ctx.new_str(entry.short_name),
vm.ctx.new_str(entry.long_name),
// OpenSSL names some objects without giving them an OID, and
// `nid2obj` reports the fourth field as None for those.
entry
.oid_string()
.map_or_else(|| vm.ctx.none(), |oid| vm.ctx.new_str(oid).into()),
))
.into())
}
#[pyfunction]
fn nid2obj(nid: i32, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let entry = oid::find_by_nid(nid)
.ok_or_else(|| vm.new_value_error(format!("unknown NID {nid}")))?;
// Return tuple: (nid, shortname, longname, oid)
Ok(vm
.new_tuple((
vm.ctx.new_int(entry.nid),
vm.ctx.new_str(entry.short_name),
vm.ctx.new_str(entry.long_name),
// OpenSSL names some objects without giving them an OID, and
// `nid2obj` reports the fourth field as None for those.
entry
.oid_string()
.map_or_else(|| vm.ctx.none(), |oid| vm.ctx.new_str(oid).into()),
))
.into())
}
#[pyfunction]
fn get_default_verify_paths(vm: &VirtualMachine) -> PyObjectRef {
// Lib/ssl.py expects: (openssl_cafile_env, openssl_cafile, openssl_capath_env, openssl_capath)
let (default_cafile, default_capath) =
rustpython_host_env::native_certs::default_verify_paths();
let tuple = vm.ctx.new_tuple(vec![
vm.ctx.new_str("SSL_CERT_FILE").into(), // openssl_cafile_env
vm.ctx.new_str(default_cafile).into(), // openssl_cafile
vm.ctx.new_str("SSL_CERT_DIR").into(), // openssl_capath_env
vm.ctx.new_str(default_capath).into(), // openssl_capath
]);
tuple.into()
}
#[pyfunction]
fn RAND_status() -> i32 {
1 // The configured rustls provider supplies cryptographic randomness.
}
#[pyfunction]
fn RAND_add(_string: PyObjectRef, _entropy: f64) {
// No-op: the configured rustls provider handles its own entropy.
// Accept any type (str, bytes, bytearray)
}
#[pyfunction]
fn RAND_bytes(n: i32, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
// Validate n is not negative
if n < 0 {
return Err(vm.new_value_error("num must be positive"));
}
let mut buf = vm.new_zeroed_bytes(n as usize)?;
CryptoExt::get_provider()
.secure_random
.fill(&mut buf)
.map_err(|_| vm.new_os_error("Failed to generate random bytes"))?;
Ok(PyBytesRef::from(vm.ctx.new_bytes(buf)))
}
#[pyfunction]
fn RAND_pseudo_bytes(n: i32, vm: &VirtualMachine) -> PyResult<(PyBytesRef, bool)> {
// Rustls providers expose cryptographically strong random bytes.
let bytes = RAND_bytes(n, vm)?;
Ok((bytes, true))
}
// Test helper to decode a certificate from a file path
//
// This is a simplified wrapper around cert_der_to_dict_helper that handles
// file reading and PEM/DER auto-detection. Used by test suite.
#[pyfunction]
fn _test_decode_cert(path: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
// Read certificate file
let path_str = path.as_str();
let cert_data = rustpython_host_env::fs::read(path_str).map_err(|e| {
vm.new_os_error(format!("Failed to read certificate file {path_str}: {e}"))
})?;
// Auto-detect PEM vs DER format
let cert_der = if cert_data
.windows(27)
.any(|w| w == b"-----BEGIN CERTIFICATE-----")
{
// Parse PEM format
let mut cursor = std::io::Cursor::new(&cert_data);
rustls_pemfile::certs(&mut cursor)
.find_map(|r| r.ok())
.ok_or_else(|| vm.new_value_error("No valid certificate found in PEM file"))?
.to_vec()
} else {
// Assume DER format
cert_data
};
// Reuse the comprehensive helper function
cert::cert_der_to_dict_helper(vm, &cert_der)
}
#[pyfunction]
fn DER_cert_to_PEM_cert(der_cert: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let der_bytes = der_cert.borrow_buf();
let bytes_slice: &[u8] = der_bytes.as_ref();
// Use pem-rfc7468 for RFC 7468 compliant PEM encoding
let pem_str = encode_string("CERTIFICATE", LineEnding::LF, bytes_slice)
.map_err(|e| vm.new_value_error(format!("PEM encoding failed: {e}")))?;
Ok(vm.ctx.new_str(pem_str))
}
#[pyfunction]
fn PEM_cert_to_DER_cert(pem_cert: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
// Parse PEM format
let mut cursor = std::io::Cursor::new(pem_cert.as_bytes());
let mut certs = rustls_pemfile::certs(&mut cursor);
if let Some(Ok(cert)) = certs.next() {
Ok(vm.ctx.new_bytes(cert.to_vec()))
} else {
Err(vm.new_value_error("Failed to parse PEM certificate"))
}
}
// Windows-specific certificate store enumeration functions
#[cfg(windows)]
#[pyfunction]
fn enum_certificates(
store_name: PyUtf8StrRef,
vm: &VirtualMachine,
) -> PyResult<Vec<PyObjectRef>> {
let store_name_str = store_name.as_str();
let certs = rustpython_host_env::cert_store::enum_certificates(store_name_str);
if !certs.had_open_store {
return Err(vm.new_os_error(format!(
"failed to open certificate store {store_name_str:?}"
)));
}
let certs = certs.entries.into_iter().map(|c| {
let cert = vm.ctx.new_bytes(c.der);
let enc_type = match c.encoding {
rustpython_host_env::cert_store::EncodingType::X509Asn => vm.new_pyobj("x509_asn"),
rustpython_host_env::cert_store::EncodingType::Pkcs7Asn => {
vm.new_pyobj("pkcs_7_asn")
}
rustpython_host_env::cert_store::EncodingType::Other(other) => vm.new_pyobj(other),
};
let usage: PyObjectRef = match c.valid_uses {
Ok(rustpython_host_env::cert_store::CertificateUses::All) => {
vm.ctx.new_bool(true).into()
}
Ok(rustpython_host_env::cert_store::CertificateUses::Oids(oids)) => {
match crate::builtins::PyFrozenSet::from_iter(
vm,
oids.into_iter().map(|oid| vm.ctx.new_str(oid).into()),
) {
Ok(set) => set.into_ref(&vm.ctx).into(),
Err(_) => vm.ctx.new_bool(true).into(),
}
}
Err(_) => vm.ctx.new_bool(true).into(),
};
Ok(vm.new_tuple((cert, enc_type, usage)).into())
});
certs.collect::<PyResult<Vec<_>>>()
}
#[cfg(windows)]
#[pyfunction]
fn enum_crls(store_name: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
let store_name_str = store_name.as_str();
let crls = rustpython_host_env::cert_store::enum_crls(store_name_str).map_err(|_| {
vm.new_os_error(format!(
"failed to open certificate store {store_name_str:?}"
))
})?;
Ok(crls
.into_iter()
.map(|crl| {
let enc_type = match crl.encoding {
rustpython_host_env::cert_store::EncodingType::X509Asn => {
vm.new_pyobj("x509_asn")
}
rustpython_host_env::cert_store::EncodingType::Pkcs7Asn => {
vm.new_pyobj("pkcs_7_asn")
}
rustpython_host_env::cert_store::EncodingType::Other(other) => {
vm.new_pyobj(other)
}
};
vm.new_tuple((vm.ctx.new_bytes(crl.der), enc_type)).into()
})
.collect())
}
// Certificate type for SSL module (pure Rust implementation)
#[pyattr]
#[pyclass(module = "_ssl", name = "Certificate")]
#[derive(Debug, PyPayload)]
pub(super) struct PySSLCertificate {
// Store the raw DER bytes
der_bytes: Vec<u8>,
}
impl PySSLCertificate {
fn parse(&self) -> Result<x509_parser::certificate::X509Certificate<'_>, String> {
match x509_parser::parse_x509_certificate(&self.der_bytes) {
Ok((_, cert)) => Ok(cert),
Err(e) => Err(format!("Failed to parse certificate: {e}")),
}
}
}
#[pyclass(
flags(IMMUTABLETYPE, DISALLOW_INSTANTIATION),
with(Comparable, Hashable, Representable)
)]
impl PySSLCertificate {
#[pymethod]
fn public_bytes(
zelf: &Py<Self>,
format: OptionalArg<i32>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
let format = format.unwrap_or(ENCODING_PEM);
match format {
x if x == ENCODING_DER => {
// Return DER bytes directly
Ok(vm.ctx.new_bytes(zelf.der_bytes.clone()).into())
}
x if x == ENCODING_PEM => {
// Convert DER to PEM using RFC 7468 compliant encoding
let pem_str = encode_string("CERTIFICATE", LineEnding::LF, &zelf.der_bytes)
.map_err(|e| vm.new_value_error(format!("PEM encoding failed: {e}")))?;
Ok(vm.ctx.new_str(pem_str).into())
}
_ => Err(vm.new_value_error("Unsupported format")),
}
}
#[pymethod]
fn get_info(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult {
cert::cert_der_to_dict_helper(vm, &zelf.der_bytes)
}
}
// Implement Comparable trait for PySSLCertificate
impl Comparable for PySSLCertificate {
fn cmp(
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
_vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
op.eq_only(|| {
if let Some(other_cert) = other.downcast_ref::<Self>() {
Ok((zelf.der_bytes == other_cert.der_bytes).into())
} else {
Ok(PyComparisonValue::NotImplemented)
}
})
}
}
// Implement Hashable trait for PySSLCertificate
impl Hashable for PySSLCertificate {
fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyHash> {
let mut hasher = DefaultHasher::new();
zelf.der_bytes.hash(&mut hasher);
Ok(hasher.finish() as PyHash)
}
}
// Implement Representable trait for PySSLCertificate
impl Representable for PySSLCertificate {
#[inline]
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
// Try to parse and show subject
match zelf.parse() {
Ok(cert) => {
let subject = cert.subject();
// Get CN if available
let cn = subject
.iter_common_name()
.next()
.and_then(|attr| attr.as_str().ok())
.unwrap_or("Unknown");
Ok(format!("<Certificate(subject=CN={cn})>"))
}
Err(_) => Ok("<Certificate(invalid)>".to_owned()),
}
}
}
}