forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_ssl.cs
More file actions
1246 lines (1053 loc) · 51.1 KB
/
_ssl.cs
File metadata and controls
1246 lines (1053 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_FULL_NET
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("_ssl", typeof(IronPython.Modules.PythonSsl))]
namespace IronPython.Modules {
internal class Asn1Object {
public Asn1Object(string shortName, string longName, int nid, byte[] oid) {
ShortName = shortName;
LongName = longName;
NID = nid;
OID = oid;
OIDString = string.Join(".", OID);
}
public string ShortName {
get; set;
}
public string LongName {
get; set;
}
public int NID {
get; set;
}
public byte[] OID {
get; set;
}
public string OIDString {
get;
}
public PythonTuple ToTuple() {
return PythonTuple.MakeTuple(NID, ShortName, LongName, OIDString);
}
}
public static class PythonSsl {
public const string __doc__ = "Implementation module for SSL socket operations. See the socket module\nfor documentation.";
public const int OPENSSL_VERSION_NUMBER = 9437184;
public static readonly PythonTuple OPENSSL_VERSION_INFO = PythonTuple.MakeTuple(0, 0, 0, 0, 0);
public static readonly object _OPENSSL_API_VERSION = OPENSSL_VERSION_INFO;
public const string OPENSSL_VERSION = "OpenSSL 0.0.0 (.NET SSL)";
private static readonly List<Asn1Object> _asn1Objects = new List<Asn1Object>();
static PythonSsl() {
_asn1Objects.AddRange(new Asn1Object[] {
new Asn1Object("serverAuth", "TLS Web Server Authentication", 129, new byte[] { 1, 3, 6, 1 ,5, 5, 7, 3, 1 }),
new Asn1Object("clientAuth", "TLS Web Client Authentication", 130, new byte[] { 1, 3, 6, 1 ,5, 5, 7, 3, 2 }),
});
}
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
var sslError = context.EnsureModuleException("SSLError", PythonSocket.error, dict, "SSLError", "ssl");
context.EnsureModuleException("SSLZeroReturnError", sslError, dict, "SSLZeroReturnError", "ssl");
context.EnsureModuleException("SSLWantWriteError", sslError, dict, "SSLWantWriteError", "ssl");
context.EnsureModuleException("SSLSyscallError", sslError, dict, "SSLSyscallError", "ssl");
context.EnsureModuleException("SSLEOFError", sslError, dict, "SSLEOFError", "ssl");
context.EnsureModuleException("SSLWantReadError", sslError, dict, "SSLWantReadError", "ssl");
}
#region Stubs for RAND functions
// The RAND_ functions are effectively no-ops, as the BCL draws on system sources
// for cryptographically-strong randomness and doesn't need (or accept) user input
public static void RAND_add(object buf, double entropy) {
if (!(buf is string) && !(buf is IBufferProtocol)) {
throw PythonOps.TypeError($"'{PythonOps.GetPythonTypeName(buf)}' does not support the buffer interface");
}
}
public static int RAND_status() => 1; // always ready
public static object RAND_bytes(int num) => PythonNT.urandom(num);
public static object RAND_pseudo_bytes(int num) => PythonTuple.MakeTuple(PythonNT.urandom(num), true);
#endregion
[PythonType]
public class _SSLContext {
internal readonly X509Certificate2Collection _cert_store = new X509Certificate2Collection();
internal string _cafile;
internal X509Certificate2 _cert;
private int _verify_mode = SSL_VERIFY_NONE;
public _SSLContext(CodeContext context, int protocol) {
if (protocol != PROTOCOL_SSLv2 && protocol != PROTOCOL_SSLv23 && protocol != PROTOCOL_SSLv3 &&
protocol != PROTOCOL_TLSv1 && protocol != PROTOCOL_TLSv1_1 && protocol != PROTOCOL_TLSv1_2) {
throw PythonOps.ValueError("invalid protocol version");
}
this.protocol = protocol;
if (protocol != PROTOCOL_SSLv2)
options |= OP_NO_SSLv2;
if (protocol != PROTOCOL_SSLv3)
options |= OP_NO_SSLv3;
verify_mode = SSL_VERIFY_NONE;
check_hostname = false;
}
public void set_ciphers(CodeContext context, string ciphers) {
// TODO
}
public void _set_alpn_protocols(CodeContext context, IBufferProtocol protos) {
// TODO
}
public void _set_npn_protocols(CodeContext context, IBufferProtocol protos) {
// TODO
}
public int options {
get; set;
}
public int verify_mode {
get {
return _verify_mode;
}
set {
if (_verify_mode != CERT_NONE && _verify_mode != CERT_OPTIONAL && _verify_mode != CERT_REQUIRED) {
throw PythonOps.ValueError("invalid value for verify_mode");
}
// TODO: change this in 3.7
if (check_hostname && value == CERT_NONE) {
throw PythonOps.ValueError("Cannot set verify_mode to CERT_NONE when check_hostname is enabled.");
}
_verify_mode = value;
}
}
public int protocol {
get; set;
}
private bool _check_hostname;
public bool check_hostname {
get => _check_hostname;
set {
// TODO: change this in 3.7
if (value && _verify_mode != CERT_OPTIONAL && _verify_mode != CERT_REQUIRED) {
throw PythonOps.ValueError("check_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED");
}
_check_hostname = value;
}
}
public void set_default_verify_paths(CodeContext context) {
}
public void set_ecdh_curve(CodeContext context, [NotNone] string curve) {
if (curve != "prime256v1")
throw PythonOps.ValueError($"unknown elliptic curve name {PythonOps.Repr(context, curve)}");
}
public void set_ecdh_curve(CodeContext context, [NotNone] Bytes curve) {
if (curve.MakeString() != "prime256v1")
throw PythonOps.ValueError($"unknown elliptic curve name {PythonOps.Repr(context, curve)}");
}
public void load_cert_chain(CodeContext context, string certfile, string keyfile = null, object password = null) {
if (keyfile is not null) throw new NotImplementedException(nameof(keyfile));
if (password is not null) throw new NotImplementedException(nameof(password));
#if NET
_cert = X509Certificate2.CreateFromPemFile(certfile, keyfile);
#else
_cert = ReadCertificate(context, certfile, readKey: true);
#endif
}
public PythonList get_ca_certs(CodeContext context, bool binary_form = false) {
if (binary_form) throw new NotImplementedException(nameof(binary_form));
return new PythonList(_cert_store.Cast<X509Certificate2>().Select(c => CertificateToPython(context, c)));
}
public void load_verify_locations(CodeContext context, object cafile = null, string capath = null, object cadata = null) {
if (cafile == null && capath == null && cadata == null) {
throw PythonOps.TypeError("cafile, capath and cadata cannot be all omitted");
}
if (cafile is not null) {
if (cafile is string s) {
_cafile = s;
} else if (cafile is Bytes b) {
_cafile = b.MakeString();
} else {
throw PythonOps.TypeError("cafile should be a valid filesystem path");
}
#if NET
_cert_store.ImportFromPemFile(_cafile);
#else
_cert_store.Add(ReadCertificate(context, _cafile));
#endif
}
if (capath != null) {
// TODO
}
if (cadata is not null) {
if (cadata is string s) {
if (!StringOps.TryEncodeAscii(s, out Bytes ascii))
throw PythonOps.ValueError("cadata should be an ASCII string or a bytes-like object");
#if NET
_cert_store.ImportFromPem(s);
#else
string line;
var lines = new List<string>();
using var stream = new MemoryStream(ascii.UnsafeByteArray);
using var sr = new StreamReader(stream);
while ((line = sr.ReadLine()) != null)
lines.Add(line);
_cert_store.Add(ReadCertificate(context, string.Empty, lines.ToArray()));
#endif
} else if (cadata is IBufferProtocol cabuf) {
using IPythonBuffer buf = cabuf.GetBuffer();
var contents = buf.AsReadOnlySpan();
while (contents.Length > 0) {
#if NET
var cert = new X509Certificate2(contents);
#else
var cert = new X509Certificate2(contents.ToArray());
#endif
_cert_store.Add(cert);
contents = contents.Slice(cert.GetRawCertData().Length);
}
} else {
throw PythonOps.ValueError("cadata should be an ASCII string or a bytes-like object");
}
}
}
public object _wrap_socket(CodeContext context, PythonSocket.socket sock, bool server_side, string server_hostname = null) {
return new _SSLSocket(context, this, sock, server_side, server_hostname);
}
}
[PythonType]
public class _SSLSocket {
private SslStream _sslStream;
private readonly PythonSocket.socket _socket;
private readonly X509Certificate2Collection _certCollection;
private readonly int _certsMode;
private readonly bool _validate, _serverSide;
private readonly CodeContext _context;
private readonly RemoteCertificateValidationCallback _callback;
private Exception _validationFailure;
public _SSLContext context { get; }
public object owner { get; set; } // TODO
public string server_hostname { get; }
public string version() => ProtocolToPython();
internal _SSLSocket(CodeContext context, _SSLContext sslcontext, PythonSocket.socket sock, bool server_side, string server_hostname) {
if (sock == null) {
throw PythonOps.TypeError("expected socket object, got None");
}
this.context = sslcontext;
_serverSide = server_side;
this.server_hostname = server_hostname;
_certsMode = sslcontext.verify_mode;
bool validate;
RemoteCertificateValidationCallback callback;
switch (_certsMode) {
case PythonSsl.CERT_NONE:
validate = false;
callback = CertValidationCallback;
break;
case PythonSsl.CERT_OPTIONAL:
validate = true;
callback = CertValidationCallbackOptional;
break;
case PythonSsl.CERT_REQUIRED:
validate = true;
callback = CertValidationCallbackRequired;
break;
default:
throw new InvalidOperationException(String.Format("bad certs_mode: {0}", _certsMode));
}
_callback = callback;
if (sslcontext._cert_store != null) {
_certCollection = sslcontext._cert_store;
}
_socket = sock;
EnsureSslStream(false);
_validate = validate;
_context = context;
}
private void EnsureSslStream(bool throwWhenNotConnected) {
if (_sslStream == null && _socket._socket.Connected) {
if (_serverSide) {
_sslStream = new SslStream(
new NetworkStream(_socket._socket, false),
true,
_callback
);
} else {
_sslStream = new SslStream(
new NetworkStream(_socket._socket, false),
true,
_callback,
CertSelectLocal
);
}
}
if (throwWhenNotConnected && _sslStream == null) {
throw PythonExceptions.CreateThrowable(PythonSocket.error, 10057, "A request to send or receive data was disallowed because the socket is not connected.");
}
}
internal bool CertValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
return true;
}
internal bool CertValidationCallbackOptional(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
if (!_serverSide) {
if (certificate != null && sslPolicyErrors != SslPolicyErrors.None) {
ValidateCertificate(certificate, chain, sslPolicyErrors);
}
}
return true;
}
internal X509Certificate CertSelectLocal(object sender, string targetHost, X509CertificateCollection collection, X509Certificate remoteCertificate, string[] acceptableIssuers) {
if (acceptableIssuers != null && acceptableIssuers.Length > 0 && collection != null && collection.Count > 0) {
// Use the first certificate that is from an acceptable issuer.
foreach (X509Certificate certificate in collection) {
string issuer = certificate.Issuer;
if (Array.IndexOf(acceptableIssuers, issuer) != -1)
return certificate;
}
}
if (collection != null && collection.Count > 0) {
return collection[0];
}
return null;
}
internal bool CertValidationCallbackRequired(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
if (!_serverSide) {
// client check
if (certificate == null) {
ValidationError(SslPolicyErrors.None);
} else if (sslPolicyErrors != SslPolicyErrors.None) {
ValidateCertificate(certificate, chain, sslPolicyErrors);
}
}
return true;
}
private void ValidateCertificate(X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
Debug.Assert(chain.ChainStatus.Length > 0);
foreach (var elem in chain.ChainStatus) {
if (elem.Status == X509ChainStatusFlags.UntrustedRoot) {
bool isOk = false;
foreach (var cert in _certCollection) {
if (certificate.Issuer == cert.Subject) {
isOk = true;
}
}
if (isOk) {
continue;
}
}
ValidationError(sslPolicyErrors);
break;
}
}
private void ValidationError(object reason) {
_validationFailure = PythonExceptions.CreateThrowable(PythonSsl.SSLError(_context), "errors while validating certificate chain: ", reason.ToString());
}
public void do_handshake() {
try {
// make sure the remote side hasn't shutdown before authenticating so we don't
// hang if we're in blocking mode.
#pragma warning disable 219 // unused variable
int available = _socket._socket.Available;
#pragma warning restore 219
} catch (SocketException) {
throw PythonExceptions.CreateThrowable(PythonExceptions.OSError, "socket closed before handshake");
}
EnsureSslStream(true);
var enabledSslProtocols = GetProtocolType(context.protocol, context.options);
try {
if (_serverSide) {
var _cert = context._cert;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
_cert = new X509Certificate2(_cert.Export(X509ContentType.Pkcs12));
}
_sslStream.AuthenticateAsServer(_cert, _certsMode == PythonSsl.CERT_REQUIRED, enabledSslProtocols, false);
} else {
_sslStream.AuthenticateAsClient(server_hostname ?? _socket._hostName ?? string.Empty, context._cert_store, enabledSslProtocols, false);
}
} catch (AuthenticationException e) {
((IDisposable)_socket._socket).Dispose();
throw PythonExceptions.CreateThrowable(PythonSsl.SSLError(_context), "errors while performing handshake: ", e.ToString());
}
if (_validationFailure != null) {
throw _validationFailure;
}
}
public PythonSocket.socket shutdown() {
_sslStream.Dispose();
return _socket;
}
/* supported communication based upon what the client & server specify
* as per the CPython docs:
* client / server SSLv2 SSLv3 SSLv23 TLSv1 TLSv1.1 TLSv1.2
SSLv2 yes no yes no no no
SSLv3 no yes yes no no no
SSLv23 no yes yes yes yes yes
TLSv1 no no yes yes no no
TLSv1.1 no no yes no yes no
TLSv1.2 no no yes no no yes
*/
#pragma warning disable CA5397 // Do not use deprecated SslProtocols values
#pragma warning disable CS0618 // Type or member is obsolete
#pragma warning disable SYSLIB0039 // Type or member is obsolete
private static SslProtocols GetProtocolType(int protocol, int options) {
SslProtocols result = SslProtocols.None;
switch (protocol) {
case PythonSsl.PROTOCOL_SSLv2:
result = SslProtocols.Ssl2;
break;
case PythonSsl.PROTOCOL_SSLv3:
result = SslProtocols.Ssl3;
break;
case PythonSsl.PROTOCOL_SSLv23:
result = SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
break;
case PythonSsl.PROTOCOL_TLSv1:
result = SslProtocols.Tls;
break;
case PythonSsl.PROTOCOL_TLSv1_1:
result = SslProtocols.Tls11;
break;
case PythonSsl.PROTOCOL_TLSv1_2:
result = SslProtocols.Tls12;
break;
default:
throw new InvalidOperationException("bad ssl protocol type: " + protocol);
}
// Filter out requested protocol exclusions:
result &= (options & PythonSsl.OP_NO_SSLv3) != 0 ? ~SslProtocols.Ssl3 : ~SslProtocols.None;
result &= (options & PythonSsl.OP_NO_SSLv2) != 0 ? ~SslProtocols.Ssl2 : ~SslProtocols.None;
result &= (options & PythonSsl.OP_NO_TLSv1) != 0 ? ~SslProtocols.Tls : ~SslProtocols.None;
result &= (options & PythonSsl.OP_NO_TLSv1_1) != 0 ? ~SslProtocols.Tls11 : ~SslProtocols.None;
result &= (options & PythonSsl.OP_NO_TLSv1_2) != 0 ? ~SslProtocols.Tls12 : ~SslProtocols.None;
return result;
}
#pragma warning restore SYSLIB0039 // Type or member is obsolete
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning restore CA5397 // Do not use deprecated SslProtocols values
public PythonTuple cipher() {
if (_sslStream != null && _sslStream.IsAuthenticated) {
return PythonTuple.MakeTuple(
_sslStream.CipherAlgorithm.ToString(),
ProtocolToPython(),
_sslStream.CipherStrength
);
}
return null;
}
public object compression() => null; // TODO
#pragma warning disable CA5397 // Do not use deprecated SslProtocols values
#pragma warning disable CS0618 // Type or member is obsolete
#pragma warning disable SYSLIB0039 // Type or member is obsolete
private string ProtocolToPython() {
switch (_sslStream.SslProtocol) {
case SslProtocols.Ssl2: return "SSLv2";
case SslProtocols.Ssl3: return "TLSv1/SSLv3";
case SslProtocols.Tls: return "TLSv1";
default: return _sslStream.SslProtocol.ToString();
}
}
#pragma warning restore SYSLIB0039 // Type or member is obsolete
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning restore CA5397 // Do not use deprecated SslProtocols values
public object peer_certificate(bool binary_form) {
var peerCert = _sslStream?.RemoteCertificate;
if (peerCert != null) {
if (binary_form) {
return Bytes.Make(peerCert.GetRawCertData());
} else if (_validate) {
return CertificateToPython(_context, peerCert);
}
}
return null;
}
public int pending() {
return _socket._socket.Available;
}
[Documentation("issuer() -> issuer_certificate\n\n"
+ "Returns a string that describes the issuer of the server's certificate. Only useful for debugging purposes."
)]
public string issuer() {
if (_sslStream != null && _sslStream.IsAuthenticated) {
X509Certificate remoteCertificate = _sslStream.RemoteCertificate;
if (remoteCertificate != null) {
return remoteCertificate.Issuer;
} else {
return String.Empty;
}
}
return String.Empty;
}
[Documentation(@"read(size, [buffer])
Read up to size bytes from the SSL socket.")]
public object read(CodeContext/*!*/ context, int size, ByteArray buffer = null) {
EnsureSslStream(true);
try {
byte[] buf = new byte[2048];
MemoryStream result = new MemoryStream(size);
while (true) {
int readLength = (size < buf.Length) ? size : buf.Length;
int bytes = _sslStream.Read(buf, 0, readLength);
if (bytes > 0) {
result.Write(buf, 0, bytes);
size -= bytes;
}
if (bytes == 0 || size == 0 || bytes < readLength) {
var res = result.ToArray();
if (buffer == null)
return Bytes.Make(res);
// TODO: get rid of the MemoryStream and write directly to the buffer
buffer[new Slice(0, res.Length)] = res;
return res.Length;
}
}
} catch (Exception e) {
throw PythonSocket.MakeException(context, e);
}
}
[Documentation("server() -> server_certificate\n\n"
+ "Returns a string that describes the server's certificate. Only useful for debugging purposes."
)]
public string server() {
if (_sslStream != null && _sslStream.IsAuthenticated) {
X509Certificate remoteCertificate = _sslStream.RemoteCertificate;
if (remoteCertificate != null) {
return remoteCertificate.Subject;
}
}
return String.Empty;
}
[Documentation(@"Writes the bytes-like object b into the SSL object.
Returns the number of bytes written.")]
public int write(CodeContext/*!*/ context, IBufferProtocol data) {
EnsureSslStream(true);
using var buffer = data.GetBuffer();
try {
#if NETCOREAPP
var bytes = buffer.AsReadOnlySpan();
_sslStream.Write(bytes);
return bytes.Length;
#else
var bytes = buffer.AsUnsafeArray() ?? buffer.ToArray();
_sslStream.Write(bytes);
return bytes.Length;
#endif
} catch (Exception e) {
throw PythonSocket.MakeException(context, e);
}
}
}
#nullable enable
[PythonType]
public class MemoryBIO {
private bool _write_eof;
public bool eof { get; private set; }
public int pending { get; private set; }
private Bytes? buf;
private Queue<Bytes> queue = new Queue<Bytes>();
public MemoryBIO() { }
public Bytes read(int size = -1) {
if (size == 0 || eof) {
return Bytes.Empty;
}
if (size == -1 || size > pending) {
size = pending;
}
byte[] res = new byte[size];
var resSpan = res.AsSpan();
if (buf is not null) {
var span = buf.AsSpan();
var length = resSpan.Length;
if (length < span.Length) {
buf = Bytes.Make(span.Slice(length).ToArray());
span = span.Slice(0, length);
} else {
buf = null;
}
span.CopyTo(resSpan);
resSpan = resSpan.Slice(span.Length);
}
while (resSpan.Length > 0) {
Debug.Assert(buf is null && queue.Count > 0);
var span = queue.Dequeue().AsSpan();
var length = resSpan.Length;
if (length < span.Length) {
buf = Bytes.Make(span.Slice(length).ToArray());
span = span.Slice(0, length);
}
span.CopyTo(resSpan);
resSpan = resSpan.Slice(span.Length);
}
pending -= size;
if (_write_eof && pending == 0) eof = true;
return Bytes.Make(res);
}
public int write(CodeContext context, [NotNone] IBufferProtocol b) {
if (_write_eof) throw PythonExceptions.CreateThrowable(SSLError(context), "cannot write() after write_eof()");
if (b is not Bytes bytes) {
using var buffer = b.GetBuffer();
bytes = Bytes.Make(buffer.ToArray());
}
if (bytes.Count == 0) return 0;
queue.Enqueue(bytes);
pending += bytes.Count;
return bytes.Count;
}
public void write_eof() {
_write_eof = true;
if (pending == 0) eof = true;
}
}
#nullable restore
public static object txt2obj(CodeContext context, string txt, bool name = false) {
Asn1Object obj = null;
if (name) {
obj = _asn1Objects.Where(x => txt == x.OIDString || txt == x.ShortName || txt == x.LongName).FirstOrDefault();
} else {
obj = _asn1Objects.Where(x => txt == x.OIDString).FirstOrDefault();
}
if (obj == null) {
throw PythonOps.ValueError("unknown object '{0}'", txt);
}
return obj.ToTuple();
}
public static object nid2obj(CodeContext context, int nid) {
if (nid < 0) {
throw PythonOps.ValueError("NID must be positive");
}
var obj = _asn1Objects.Where(x => x.NID == nid).FirstOrDefault();
if (obj == null) {
throw PythonOps.ValueError("unknown NID {0}", nid);
}
return obj.ToTuple();
}
public static PythonList enum_certificates(string store_name) {
X509Store store = null;
try {
store = new X509Store(store_name, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var result = new PythonList();
foreach (var cert in store.Certificates) {
string format = cert.GetFormat();
switch (format) {
case "X509":
format = "x509_asn";
break;
default:
format = "unknown";
break;
}
var set = new SetCollection();
bool found = false;
foreach (var ext in cert.Extensions) {
var keyUsage = ext as X509EnhancedKeyUsageExtension;
if (keyUsage != null) {
foreach (var oid in keyUsage.EnhancedKeyUsages) {
set.add(oid.Value);
}
found = true;
break;
}
}
result.Add(PythonTuple.MakeTuple(new Bytes(cert.RawData.ToList()), format, found ? set : ScriptingRuntimeHelpers.True));
}
return result;
} catch {
} finally {
store?.Close();
}
return new PythonList();
}
public static PythonList enum_crls(string store_name) {
X509Store store = null;
try {
store = new X509Store(store_name, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var result = new PythonList();
foreach (var cert in store.Certificates) {
string format = cert.GetFormat();
}
} catch {
} finally {
store?.Close();
}
return new PythonList();
}
internal static PythonType SSLError(CodeContext/*!*/ context) {
return (PythonType)context.LanguageContext.GetModuleState("SSLError");
}
public static PythonDictionary _test_decode_cert(CodeContext context, string path) {
var cert = ReadCertificate(context, path);
return CertificateToPython(context, cert);
}
private static PythonDictionary CertificateToPython(CodeContext context, X509Certificate cert) {
if (cert is X509Certificate2 cert2)
return CertificateToPython(context, cert2);
return CertificateToPython(context, new X509Certificate2(cert.GetRawCertData()));
}
private static PythonDictionary CertificateToPython(CodeContext context, X509Certificate2 cert) {
var dict = new CommonDictionaryStorage();
dict.AddNoLock("notAfter", ToPythonDateFormat(cert.NotAfter));
dict.AddNoLock("subject", IssuerToPython(context, cert.Subject));
dict.AddNoLock("notBefore", ToPythonDateFormat(cert.NotBefore));
dict.AddNoLock("serialNumber", SerialNumberToPython(cert));
dict.AddNoLock("version", cert.Version);
dict.AddNoLock("issuer", IssuerToPython(context, cert.Issuer));
AddSubjectAltNames(dict, cert);
return new PythonDictionary(dict);
string ToPythonDateFormat(DateTime date) {
var dateStr = date.ToUniversalTime().ToString("MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture) + " GMT";
if (dateStr[4] == '0')
dateStr = dateStr.Substring(0, 4) + " " + dateStr.Substring(5); // CPython uses leading space
return dateStr;
}
}
private static void AddSubjectAltNames(CommonDictionaryStorage dict, X509Certificate2 cert2) {
foreach (var extension in cert2.Extensions) {
if (extension.Oid.Value != "2.5.29.17") { // Subject Alternative Name
continue;
}
var altNames = new List<object>();
var sr = new StringReader(extension.Format(true));
// The string generated by format varies depending on the platform, for example:
// - On Windows, one entry per line:
// DNS Name=www.python.org
// DNS Name=pypi.python.org
// - On Mac/Linux (.NET Core), multiple entries on a single line:
// DNS:www.python.org, DNS:pypi.python.org
string line;
while (null != (line = sr.ReadLine())) {
line = line.Trim();
// On Linux and Mac (.NET Core), Format produces a string matching the OpenSSL format which may contain multiple entries:
foreach (var val in line.Split(',')) {
var keyValue = val.Split(new char[] { ':', '=' });
// On Windows, Format produces different results based on the locale so we can't check for a specific key
if (keyValue[0].Contains("DNS") && keyValue.Length == 2) {
altNames.Add(PythonTuple.MakeTuple("DNS", keyValue[1]));
}
}
}
dict.AddNoLock("subjectAltName", PythonTuple.MakeTuple(altNames.ToArray()));
break;
}
}
private static string SerialNumberToPython(X509Certificate2 cert) {
var res = cert.SerialNumber;
for (int i = 0; i < res.Length; i++) {
if (res[i] != '0') {
return res.Substring(i);
}
}
return res;
}
// yields parts out of issuer or subject string
// Respects quoted comma e.g: CN=*.c.ssl.fastly.net, O="Fastly, Inc.", L=San Francisco, S=California, C=US
// Quote characters are removed
private static IEnumerable<string> IssuerParts(string issuer) {
var inQuote = false;
var token = new StringBuilder();
foreach (var c in issuer) {
if (inQuote) {
if (c == '"') {
inQuote = false;
} else {
token.Append(c);
}
} else {
if (c == '"') {
inQuote = true;
} else if (c == ',') {
yield return token.ToString().Trim();
token.Length = 0;
} else {
token.Append(c);
}
}
}
if (token.Length > 0)
yield return token.ToString().Trim();
}
private static PythonTuple IssuerToPython(CodeContext context, string issuer) {
var collector = new List<object>();
foreach (var part in IssuerParts(issuer)) {
var field = IssuerFieldToPython(context, part);
if (field != null) {
collector.Add(PythonTuple.MakeTuple(new object[] { field }));
}
}
return PythonTuple.MakeTuple(collector.ToReverseArray()); // CPython reverses the fields
}
private static PythonTuple IssuerFieldToPython(CodeContext context, string p) {
if (p.StartsWith("CN=", StringComparison.Ordinal)) {
return PythonTuple.MakeTuple("commonName", p.Substring(3));
} else if (p.StartsWith("OU=", StringComparison.Ordinal)) {
return PythonTuple.MakeTuple("organizationalUnitName", p.Substring(3));
} else if (p.StartsWith("O=", StringComparison.Ordinal)) {
return PythonTuple.MakeTuple("organizationName", p.Substring(2));
} else if (p.StartsWith("L=", StringComparison.Ordinal)) {
return PythonTuple.MakeTuple("localityName", p.Substring(2));
} else if (p.StartsWith("S=", StringComparison.Ordinal)) {
return PythonTuple.MakeTuple("stateOrProvinceName", p.Substring(2));
} else if (p.StartsWith("C=", StringComparison.Ordinal)) {
return PythonTuple.MakeTuple("countryName", p.Substring(2));
} else if (p.StartsWith("E=", StringComparison.Ordinal)) {
return PythonTuple.MakeTuple("email", p.Substring(2));
}
// Ignore unknown fields
return null;
}
private static X509Certificate2 ReadCertificate(CodeContext context, string filename, bool readKey = false) {
#if NET
if (readKey) {
return X509Certificate2.CreateFromPemFile(filename);
}
#endif
string[] lines;
try {
lines = File.ReadAllLines(filename);
} catch (IOException) {
throw PythonExceptions.CreateThrowable(SSLError(context), "Can't open file ", filename);
}
return ReadCertificate(context, filename, lines, readKey);
}
private static X509Certificate2 ReadCertificate(CodeContext context, string filename, string[] lines, bool readKey = false) {
X509Certificate2 cert = null;
RSACryptoServiceProvider key = null;
try {
for (int i = 0; i < lines.Length; i++) {
if (lines[i] == "-----BEGIN CERTIFICATE-----") {
var certStr = ReadToEnd(lines, ref i, "-----END CERTIFICATE-----");
try {
cert = new X509Certificate2(Convert.FromBase64String(certStr.ToString()));
} catch (Exception e) {
throw ErrorDecoding(context, filename, e);
}
if (!readKey) return cert;
} else if (lines[i] == "-----BEGIN RSA PRIVATE KEY-----") {
var keyStr = ReadToEnd(lines, ref i, "-----END RSA PRIVATE KEY-----");
if (readKey) {
try {
var keyBytes = Convert.FromBase64String(keyStr.ToString());
key = ParsePkcs1DerEncodedPrivateKey(context, filename, keyBytes);
} catch (Exception e) {
throw ErrorDecoding(context, filename, e);
}
}
} else if (lines[i] == "-----BEGIN PRIVATE KEY-----") {
var keyStr = ReadToEnd(lines, ref i, "-----END PRIVATE KEY-----");
if (readKey) {
try {
var keyBytes = Convert.FromBase64String(keyStr.ToString());