-
Notifications
You must be signed in to change notification settings - Fork 420
/
Copy pathtest_ssl.py
4713 lines (4015 loc) · 163 KB
/
test_ssl.py
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
# Copyright (C) Jean-Paul Calderone
# See LICENSE for details.
"""
Unit tests for :mod:`OpenSSL.SSL`.
"""
from __future__ import annotations
import datetime
import gc
import os
import pathlib
import select
import sys
import time
import typing
import uuid
from errno import (
EAFNOSUPPORT,
ECONNREFUSED,
EINPROGRESS,
EPIPE,
ESHUTDOWN,
EWOULDBLOCK,
)
from gc import collect, get_referrers
from os import makedirs
from socket import (
AF_INET,
AF_INET6,
MSG_PEEK,
SHUT_RDWR,
gaierror,
socket,
)
from sys import getfilesystemencoding, platform
from weakref import ref
import pytest
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, rsa
from cryptography.x509.oid import NameOID
from pretend import raiser
from OpenSSL import SSL
from OpenSSL._util import ffi as _ffi
from OpenSSL._util import lib as _lib
from OpenSSL.crypto import (
FILETYPE_PEM,
TYPE_RSA,
X509,
PKey,
X509Name,
X509Store,
dump_certificate,
dump_privatekey,
get_elliptic_curves,
load_certificate,
load_privatekey,
)
from OpenSSL.SSL import (
DTLS_METHOD,
MODE_RELEASE_BUFFERS,
NO_OVERLAPPING_PROTOCOLS,
OP_COOKIE_EXCHANGE,
OP_NO_COMPRESSION,
OP_NO_QUERY_MTU,
OP_NO_TICKET,
OP_SINGLE_DH_USE,
OPENSSL_VERSION_NUMBER,
RECEIVED_SHUTDOWN,
SENT_SHUTDOWN,
SESS_CACHE_BOTH,
SESS_CACHE_CLIENT,
SESS_CACHE_NO_AUTO_CLEAR,
SESS_CACHE_NO_INTERNAL,
SESS_CACHE_NO_INTERNAL_LOOKUP,
SESS_CACHE_NO_INTERNAL_STORE,
SESS_CACHE_OFF,
SESS_CACHE_SERVER,
SSL_CB_ACCEPT_EXIT,
SSL_CB_ACCEPT_LOOP,
SSL_CB_ALERT,
SSL_CB_CONNECT_EXIT,
SSL_CB_CONNECT_LOOP,
SSL_CB_EXIT,
SSL_CB_HANDSHAKE_DONE,
SSL_CB_HANDSHAKE_START,
SSL_CB_LOOP,
SSL_CB_READ,
SSL_CB_READ_ALERT,
SSL_CB_WRITE,
SSL_CB_WRITE_ALERT,
SSL_ST_ACCEPT,
SSL_ST_CONNECT,
SSL_ST_MASK,
SSLEAY_BUILT_ON,
SSLEAY_CFLAGS,
SSLEAY_DIR,
SSLEAY_PLATFORM,
SSLEAY_VERSION,
TLS1_2_VERSION,
TLS1_3_VERSION,
TLS_METHOD,
VERIFY_CLIENT_ONCE,
VERIFY_FAIL_IF_NO_PEER_CERT,
VERIFY_NONE,
VERIFY_PEER,
Connection,
Context,
Error,
OP_NO_SSLv2,
OP_NO_SSLv3,
Session,
SSLeay_version,
SSLv23_METHOD,
SysCallError,
TLSv1_1_METHOD,
TLSv1_2_METHOD,
TLSv1_METHOD,
WantReadError,
WantWriteError,
ZeroReturnError,
_make_requires,
_NoOverlappingProtocols,
)
from .test_crypto import (
client_cert_pem,
client_key_pem,
root_cert_pem,
root_key_pem,
server_cert_pem,
server_key_pem,
)
from .util import NON_ASCII, WARNING_TYPE_EXPECTED
# openssl dhparam 2048 -out dh-2048.pem
dhparam = """\
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEA2F5e976d/GjsaCdKv5RMWL/YV7fq1UUWpPAer5fDXflLMVUuYXxE
3m3ayZob9lbpgEU0jlPAsXHfQPGxpKmvhv+xV26V/DEoukED8JeZUY/z4pigoptl
+8+TYdNNE/rFSZQFXIp+v2D91IEgmHBnZlKFSbKR+p8i0KjExXGjU6ji3S5jkOku
ogikc7df1Ui0hWNJCmTjExq07aXghk97PsdFSxjdawuG3+vos5bnNoUwPLYlFc/z
ITYG0KXySiCLi4UDlXTZTz7u/+OYczPEgqa/JPUddbM/kfvaRAnjY38cfQ7qXf8Y
i5s5yYK7a/0eWxxRr2qraYaUj8RwDpH9CwIBAg==
-----END DH PARAMETERS-----
"""
def socket_any_family() -> socket:
try:
return socket(AF_INET)
except OSError as e:
if e.errno == EAFNOSUPPORT:
return socket(AF_INET6)
raise
def loopback_address(socket: socket) -> str:
if socket.family == AF_INET:
return "127.0.0.1"
else:
assert socket.family == AF_INET6
return "::1"
def verify_cb(
conn: Connection, cert: X509, errnum: int, depth: int, ok: int
) -> bool:
return bool(ok)
def socket_pair() -> tuple[socket, socket]:
"""
Establish and return a pair of network sockets connected to each other.
"""
# Connect a pair of sockets
port = socket_any_family()
port.bind(("", 0))
port.listen(1)
client = socket(port.family)
client.setblocking(False)
client.connect_ex((loopback_address(port), port.getsockname()[1]))
client.setblocking(True)
server = port.accept()[0]
port.close()
# Let's pass some unencrypted data to make sure our socket connection is
# fine. Just one byte, so we don't have to worry about buffers getting
# filled up or fragmentation.
server.send(b"x")
assert client.recv(1024) == b"x"
client.send(b"y")
assert server.recv(1024) == b"y"
# Most of our callers want non-blocking sockets, make it easy for them.
server.setblocking(False)
client.setblocking(False)
return (server, client)
def handshake(client: Connection, server: Connection) -> None:
conns = [client, server]
while conns:
for conn in conns:
try:
conn.do_handshake()
except WantReadError:
pass
else:
conns.remove(conn)
def _create_certificate_chain() -> list[tuple[PKey, X509]]:
"""
Construct and return a chain of certificates.
1. A new self-signed certificate authority certificate (cacert)
2. A new intermediate certificate signed by cacert (icert)
3. A new server certificate signed by icert (scert)
"""
not_before = datetime.datetime(2000, 1, 1, 0, 0, 0)
not_after = datetime.datetime.now() + datetime.timedelta(days=365)
# Step 1
cakey = rsa.generate_private_key(key_size=2048, public_exponent=65537)
casubject = x509.Name(
[x509.NameAttribute(x509.NameOID.COMMON_NAME, "Authority Certificate")]
)
cacert = (
x509.CertificateBuilder()
.subject_name(casubject)
.issuer_name(casubject)
.public_key(cakey.public_key())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(
x509.BasicConstraints(ca=True, path_length=None), critical=False
)
.serial_number(1)
.sign(cakey, hashes.SHA256())
)
# Step 2
ikey = rsa.generate_private_key(key_size=2048, public_exponent=65537)
icert = (
x509.CertificateBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(
x509.NameOID.COMMON_NAME, "Intermediate Certificate"
)
]
)
)
.issuer_name(cacert.subject)
.public_key(ikey.public_key())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(
x509.BasicConstraints(ca=True, path_length=None), critical=False
)
.serial_number(1)
.sign(cakey, hashes.SHA256())
)
# Step 3
skey = rsa.generate_private_key(key_size=2048, public_exponent=65537)
scert = (
x509.CertificateBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(
x509.NameOID.COMMON_NAME, "Server Certificate"
)
]
)
)
.issuer_name(icert.subject)
.public_key(skey.public_key())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(
x509.BasicConstraints(ca=False, path_length=None), critical=True
)
.serial_number(1)
.sign(ikey, hashes.SHA256())
)
return [
(PKey.from_cryptography_key(cakey), X509.from_cryptography(cacert)),
(PKey.from_cryptography_key(ikey), X509.from_cryptography(icert)),
(PKey.from_cryptography_key(skey), X509.from_cryptography(scert)),
]
def loopback_client_factory(
socket: socket, version: int = SSLv23_METHOD
) -> Connection:
client = Connection(Context(version), socket)
client.set_connect_state()
return client
def loopback_server_factory(
socket: socket | None, version: int = SSLv23_METHOD
) -> Connection:
ctx = Context(version)
ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
server = Connection(ctx, socket)
server.set_accept_state()
return server
def loopback(
server_factory: typing.Callable[[socket], Connection] | None = None,
client_factory: typing.Callable[[socket], Connection] | None = None,
) -> tuple[Connection, Connection]:
"""
Create a connected socket pair and force two connected SSL sockets
to talk to each other via memory BIOs.
"""
if server_factory is None:
server_factory = loopback_server_factory
if client_factory is None:
client_factory = loopback_client_factory
(server, client) = socket_pair()
tls_server = server_factory(server)
tls_client = client_factory(client)
handshake(tls_client, tls_server)
tls_server.setblocking(True)
tls_client.setblocking(True)
return tls_server, tls_client
def interact_in_memory(
client_conn: Connection, server_conn: Connection
) -> tuple[Connection, bytes] | None:
"""
Try to read application bytes from each of the two `Connection` objects.
Copy bytes back and forth between their send/receive buffers for as long
as there is anything to copy. When there is nothing more to copy,
return `None`. If one of them actually manages to deliver some application
bytes, return a two-tuple of the connection from which the bytes were read
and the bytes themselves.
"""
wrote = True
while wrote:
# Loop until neither side has anything to say
wrote = False
# Copy stuff from each side's send buffer to the other side's
# receive buffer.
for read, write in [
(client_conn, server_conn),
(server_conn, client_conn),
]:
# Give the side a chance to generate some more bytes, or succeed.
try:
data = read.recv(2**16)
except WantReadError:
# It didn't succeed, so we'll hope it generated some output.
pass
else:
# It did succeed, so we'll stop now and let the caller deal
# with it.
return (read, data)
while True:
# Keep copying as long as there's more stuff there.
try:
dirty = read.bio_read(4096)
except WantReadError:
# Okay, nothing more waiting to be sent. Stop
# processing this send buffer.
break
else:
# Keep track of the fact that someone generated some
# output.
wrote = True
write.bio_write(dirty)
return None
def handshake_in_memory(
client_conn: Connection, server_conn: Connection
) -> None:
"""
Perform the TLS handshake between two `Connection` instances connected to
each other via memory BIOs.
"""
client_conn.set_connect_state()
server_conn.set_accept_state()
for conn in [client_conn, server_conn]:
try:
conn.do_handshake()
except WantReadError:
pass
interact_in_memory(client_conn, server_conn)
class TestVersion:
"""
Tests for version information exposed by `OpenSSL.SSL.SSLeay_version` and
`OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
"""
def test_OPENSSL_VERSION_NUMBER(self) -> None:
"""
`OPENSSL_VERSION_NUMBER` is an integer with status in the low byte and
the patch, fix, minor, and major versions in the nibbles above that.
"""
assert isinstance(OPENSSL_VERSION_NUMBER, int)
def test_SSLeay_version(self) -> None:
"""
`SSLeay_version` takes a version type indicator and returns one of a
number of version strings based on that indicator.
"""
versions = {}
for t in [
SSLEAY_VERSION,
SSLEAY_CFLAGS,
SSLEAY_BUILT_ON,
SSLEAY_PLATFORM,
SSLEAY_DIR,
]:
version = SSLeay_version(t)
versions[version] = t
assert isinstance(version, bytes)
assert len(versions) == 5
@pytest.fixture
def ca_file(tmp_path: pathlib.Path) -> bytes:
"""
Create a valid PEM file with CA certificates and return the path.
"""
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = key.public_key()
builder = x509.CertificateBuilder()
builder = builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "pyopenssl.org")])
)
builder = builder.issuer_name(
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "pyopenssl.org")])
)
one_day = datetime.timedelta(1, 0, 0)
builder = builder.not_valid_before(datetime.datetime.today() - one_day)
builder = builder.not_valid_after(datetime.datetime.today() + one_day)
builder = builder.serial_number(int(uuid.uuid4()))
builder = builder.public_key(public_key)
builder = builder.add_extension(
x509.BasicConstraints(ca=True, path_length=None),
critical=True,
)
certificate = builder.sign(private_key=key, algorithm=hashes.SHA256())
ca_file = tmp_path / "test.pem"
ca_file.write_bytes(
certificate.public_bytes(
encoding=serialization.Encoding.PEM,
)
)
return str(ca_file).encode("ascii")
@pytest.fixture
def context() -> Context:
"""
A simple "best TLS you can get" context. TLS 1.2+ in any reasonable OpenSSL
"""
return Context(SSLv23_METHOD)
class TestContext:
"""
Unit tests for `OpenSSL.SSL.Context`.
"""
@pytest.mark.parametrize(
"cipher_string",
[b"hello world:AES128-SHA", "hello world:AES128-SHA"],
)
def test_set_cipher_list(
self, context: Context, cipher_string: bytes
) -> None:
"""
`Context.set_cipher_list` accepts both byte and unicode strings
for naming the ciphers which connections created with the context
object will be able to choose from.
"""
context.set_cipher_list(cipher_string)
conn = Connection(context, None)
assert "AES128-SHA" in conn.get_cipher_list()
def test_set_cipher_list_wrong_type(self, context: Context) -> None:
"""
`Context.set_cipher_list` raises `TypeError` when passed a non-string
argument.
"""
with pytest.raises(TypeError):
context.set_cipher_list(object()) # type: ignore[arg-type]
@pytest.mark.flaky(reruns=2)
def test_set_cipher_list_no_cipher_match(self, context: Context) -> None:
"""
`Context.set_cipher_list` raises `OpenSSL.SSL.Error` with a
`"no cipher match"` reason string regardless of the TLS
version.
"""
with pytest.raises(Error) as excinfo:
context.set_cipher_list(b"imaginary-cipher")
assert excinfo.value.args[0][0] in [
# 1.1.x
(
"SSL routines",
"SSL_CTX_set_cipher_list",
"no cipher match",
),
# 3.0.x
(
"SSL routines",
"",
"no cipher match",
),
]
def test_load_client_ca(self, context: Context, ca_file: bytes) -> None:
"""
`Context.load_client_ca` works as far as we can tell.
"""
context.load_client_ca(ca_file)
def test_load_client_ca_invalid(
self, context: Context, tmp_path: pathlib.Path
) -> None:
"""
`Context.load_client_ca` raises an Error if the ca file is invalid.
"""
ca_file = tmp_path / "test.pem"
ca_file.write_text("")
with pytest.raises(Error) as e:
context.load_client_ca(str(ca_file).encode("ascii"))
assert "PEM routines" == e.value.args[0][0][0]
def test_load_client_ca_unicode(
self, context: Context, ca_file: bytes
) -> None:
"""
Passing the path as unicode raises a warning but works.
"""
pytest.deprecated_call(context.load_client_ca, ca_file.decode("ascii"))
def test_set_session_id(self, context: Context) -> None:
"""
`Context.set_session_id` works as far as we can tell.
"""
context.set_session_id(b"abc")
def test_set_session_id_fail(self, context: Context) -> None:
"""
`Context.set_session_id` errors are propagated.
"""
with pytest.raises(Error) as e:
context.set_session_id(b"abc" * 1000)
assert e.value.args[0][0] in [
# 1.1.x
(
"SSL routines",
"SSL_CTX_set_session_id_context",
"ssl session id context too long",
),
# 3.0.x
(
"SSL routines",
"",
"ssl session id context too long",
),
]
def test_set_session_id_unicode(self, context: Context) -> None:
"""
`Context.set_session_id` raises a warning if a unicode string is
passed.
"""
pytest.deprecated_call(context.set_session_id, "abc")
def test_method(self) -> None:
"""
`Context` can be instantiated with one of `SSLv2_METHOD`,
`SSLv3_METHOD`, `SSLv23_METHOD`, `TLSv1_METHOD`, `TLSv1_1_METHOD`,
or `TLSv1_2_METHOD`.
"""
methods = [SSLv23_METHOD, TLSv1_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
for meth in methods:
Context(meth)
with pytest.raises(TypeError):
Context("") # type: ignore[arg-type]
with pytest.raises(ValueError):
Context(13)
def test_use_privatekey_file_missing(self, tmpfile: bytes) -> None:
"""
`Context.use_privatekey_file` raises `OpenSSL.SSL.Error` when passed
the name of a file which does not exist.
"""
ctx = Context(SSLv23_METHOD)
with pytest.raises(Error):
ctx.use_privatekey_file(tmpfile)
def _use_privatekey_file_test(
self, pemfile: bytes | str, filetype: int
) -> None:
"""
Verify that calling ``Context.use_privatekey_file`` with the given
arguments does not raise an exception.
"""
key = PKey()
key.generate_key(TYPE_RSA, 1024)
with open(pemfile, "w") as pem:
pem.write(dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
ctx = Context(SSLv23_METHOD)
ctx.use_privatekey_file(pemfile, filetype)
@pytest.mark.parametrize("filetype", [object(), "", None, 1.0])
def test_wrong_privatekey_file_wrong_args(
self, tmpfile: bytes, filetype: object
) -> None:
"""
`Context.use_privatekey_file` raises `TypeError` when called with
a `filetype` which is not a valid file encoding.
"""
ctx = Context(SSLv23_METHOD)
with pytest.raises(TypeError):
ctx.use_privatekey_file(tmpfile, filetype) # type: ignore[arg-type]
def test_use_privatekey_file_bytes(self, tmpfile: bytes) -> None:
"""
A private key can be specified from a file by passing a ``bytes``
instance giving the file name to ``Context.use_privatekey_file``.
"""
self._use_privatekey_file_test(
tmpfile + NON_ASCII.encode(getfilesystemencoding()),
FILETYPE_PEM,
)
def test_use_privatekey_file_unicode(self, tmpfile: bytes) -> None:
"""
A private key can be specified from a file by passing a ``unicode``
instance giving the file name to ``Context.use_privatekey_file``.
"""
self._use_privatekey_file_test(
tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
FILETYPE_PEM,
)
def test_use_certificate_file_wrong_args(self) -> None:
"""
`Context.use_certificate_file` raises `TypeError` if the first
argument is not a byte string or the second argument is not an integer.
"""
ctx = Context(SSLv23_METHOD)
with pytest.raises(TypeError):
ctx.use_certificate_file(object(), FILETYPE_PEM) # type: ignore[arg-type]
with pytest.raises(TypeError):
ctx.use_certificate_file(b"somefile", object()) # type: ignore[arg-type]
with pytest.raises(TypeError):
ctx.use_certificate_file(object(), FILETYPE_PEM) # type: ignore[arg-type]
def test_use_certificate_file_missing(self, tmpfile: bytes) -> None:
"""
`Context.use_certificate_file` raises `OpenSSL.SSL.Error` if passed
the name of a file which does not exist.
"""
ctx = Context(SSLv23_METHOD)
with pytest.raises(Error):
ctx.use_certificate_file(tmpfile)
def _use_certificate_file_test(
self, certificate_file: bytes | str
) -> None:
"""
Verify that calling ``Context.use_certificate_file`` with the given
filename doesn't raise an exception.
"""
# TODO
# Hard to assert anything. But we could set a privatekey then ask
# OpenSSL if the cert and key agree using check_privatekey. Then as
# long as check_privatekey works right we're good...
with open(certificate_file, "wb") as pem_file:
pem_file.write(root_cert_pem)
ctx = Context(SSLv23_METHOD)
ctx.use_certificate_file(certificate_file)
def test_use_certificate_file_bytes(self, tmpfile: bytes) -> None:
"""
`Context.use_certificate_file` sets the certificate (given as a
`bytes` filename) which will be used to identify connections created
using the context.
"""
filename = tmpfile + NON_ASCII.encode(getfilesystemencoding())
self._use_certificate_file_test(filename)
def test_use_certificate_file_unicode(self, tmpfile: bytes) -> None:
"""
`Context.use_certificate_file` sets the certificate (given as a
`bytes` filename) which will be used to identify connections created
using the context.
"""
filename = tmpfile.decode(getfilesystemencoding()) + NON_ASCII
self._use_certificate_file_test(filename)
def test_check_privatekey_valid(self) -> None:
"""
`Context.check_privatekey` returns `None` if the `Context` instance
has been configured to use a matched key and certificate pair.
"""
key = load_privatekey(FILETYPE_PEM, client_key_pem)
cert = load_certificate(FILETYPE_PEM, client_cert_pem)
context = Context(SSLv23_METHOD)
context.use_privatekey(key)
context.use_certificate(cert)
assert context.check_privatekey() is None # type: ignore[func-returns-value]
context = Context(SSLv23_METHOD)
cryptography_key = key.to_cryptography_key()
assert isinstance(cryptography_key, rsa.RSAPrivateKey)
context.use_privatekey(cryptography_key)
context.use_certificate(cert)
assert context.check_privatekey() is None # type: ignore[func-returns-value]
def test_check_privatekey_invalid(self) -> None:
"""
`Context.check_privatekey` raises `Error` if the `Context` instance
has been configured to use a key and certificate pair which don't
relate to each other.
"""
key = load_privatekey(FILETYPE_PEM, client_key_pem)
cert = load_certificate(FILETYPE_PEM, server_cert_pem)
context = Context(SSLv23_METHOD)
context.use_privatekey(key)
context.use_certificate(cert)
with pytest.raises(Error):
context.check_privatekey()
context = Context(SSLv23_METHOD)
cryptography_key = key.to_cryptography_key()
assert isinstance(cryptography_key, rsa.RSAPrivateKey)
context.use_privatekey(cryptography_key)
context.use_certificate(cert)
with pytest.raises(Error):
context.check_privatekey()
def test_app_data(self) -> None:
"""
`Context.set_app_data` stores an object for later retrieval
using `Context.get_app_data`.
"""
app_data = object()
context = Context(SSLv23_METHOD)
context.set_app_data(app_data)
assert context.get_app_data() is app_data
def test_set_options_wrong_args(self) -> None:
"""
`Context.set_options` raises `TypeError` if called with
a non-`int` argument.
"""
context = Context(SSLv23_METHOD)
with pytest.raises(TypeError):
context.set_options(None) # type: ignore[arg-type]
def test_set_options(self) -> None:
"""
`Context.set_options` returns the new options value.
"""
context = Context(SSLv23_METHOD)
options = context.set_options(OP_NO_SSLv2)
assert options & OP_NO_SSLv2 == OP_NO_SSLv2
def test_set_mode_wrong_args(self) -> None:
"""
`Context.set_mode` raises `TypeError` if called with
a non-`int` argument.
"""
context = Context(SSLv23_METHOD)
with pytest.raises(TypeError):
context.set_mode(None) # type: ignore[arg-type]
def test_set_mode(self) -> None:
"""
`Context.set_mode` accepts a mode bitvector and returns the
newly set mode.
"""
context = Context(SSLv23_METHOD)
assert MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS)
def test_set_timeout_wrong_args(self) -> None:
"""
`Context.set_timeout` raises `TypeError` if called with
a non-`int` argument.
"""
context = Context(SSLv23_METHOD)
with pytest.raises(TypeError):
context.set_timeout(None) # type: ignore[arg-type]
def test_timeout(self) -> None:
"""
`Context.set_timeout` sets the session timeout for all connections
created using the context object. `Context.get_timeout` retrieves
this value.
"""
context = Context(SSLv23_METHOD)
context.set_timeout(1234)
assert context.get_timeout() == 1234
def test_set_verify_depth_wrong_args(self) -> None:
"""
`Context.set_verify_depth` raises `TypeError` if called with a
non-`int` argument.
"""
context = Context(SSLv23_METHOD)
with pytest.raises(TypeError):
context.set_verify_depth(None) # type: ignore[arg-type]
def test_verify_depth(self) -> None:
"""
`Context.set_verify_depth` sets the number of certificates in
a chain to follow before giving up. The value can be retrieved with
`Context.get_verify_depth`.
"""
context = Context(SSLv23_METHOD)
context.set_verify_depth(11)
assert context.get_verify_depth() == 11
def _write_encrypted_pem(self, passphrase: bytes, tmpfile: bytes) -> bytes:
"""
Write a new private key out to a new file, encrypted using the given
passphrase. Return the path to the new file.
"""
key = PKey()
key.generate_key(TYPE_RSA, 1024)
pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
with open(tmpfile, "w") as fObj:
fObj.write(pem.decode("ascii"))
return tmpfile
def test_set_passwd_cb_wrong_args(self) -> None:
"""
`Context.set_passwd_cb` raises `TypeError` if called with a
non-callable first argument.
"""
context = Context(SSLv23_METHOD)
with pytest.raises(TypeError):
context.set_passwd_cb(None) # type: ignore[arg-type]
def test_set_passwd_cb(self, tmpfile: bytes) -> None:
"""
`Context.set_passwd_cb` accepts a callable which will be invoked when
a private key is loaded from an encrypted PEM.
"""
passphrase = b"foobar"
pemFile = self._write_encrypted_pem(passphrase, tmpfile)
calledWith = []
def passphraseCallback(
maxlen: int, verify: bool, extra: None
) -> bytes:
calledWith.append((maxlen, verify, extra))
return passphrase
context = Context(SSLv23_METHOD)
context.set_passwd_cb(passphraseCallback)
context.use_privatekey_file(pemFile)
assert len(calledWith) == 1
assert isinstance(calledWith[0][0], int)
assert isinstance(calledWith[0][1], int)
assert calledWith[0][2] is None
def test_passwd_callback_exception(self, tmpfile: bytes) -> None:
"""
`Context.use_privatekey_file` propagates any exception raised
by the passphrase callback.
"""
pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
def passphraseCallback(
maxlen: int, verify: bool, extra: None
) -> bytes:
raise RuntimeError("Sorry, I am a fail.")
context = Context(SSLv23_METHOD)
context.set_passwd_cb(passphraseCallback)
with pytest.raises(RuntimeError):
context.use_privatekey_file(pemFile)
def test_passwd_callback_false(self, tmpfile: bytes) -> None:
"""
`Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
passphrase callback returns a false value.
"""
pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
def passphraseCallback(
maxlen: int, verify: bool, extra: None
) -> bytes:
return b""
context = Context(SSLv23_METHOD)
context.set_passwd_cb(passphraseCallback)
with pytest.raises(Error):
context.use_privatekey_file(pemFile)
def test_passwd_callback_non_string(self, tmpfile: bytes) -> None:
"""
`Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
passphrase callback returns a true non-string value.
"""
pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
def passphraseCallback(maxlen: int, verify: bool, extra: None) -> int:
return 10
context = Context(SSLv23_METHOD)
context.set_passwd_cb(passphraseCallback) # type: ignore[arg-type]
# TODO: Surely this is the wrong error?
with pytest.raises(ValueError):
context.use_privatekey_file(pemFile)
def test_passwd_callback_too_long(self, tmpfile: bytes) -> None:
"""
If the passphrase returned by the passphrase callback returns a string
longer than the indicated maximum length, it is truncated.
"""
# A priori knowledge!
passphrase = b"x" * 1024
pemFile = self._write_encrypted_pem(passphrase, tmpfile)
def passphraseCallback(
maxlen: int, verify: bool, extra: None
) -> bytes:
assert maxlen == 1024
return passphrase + b"y"
context = Context(SSLv23_METHOD)
context.set_passwd_cb(passphraseCallback)
# This shall succeed because the truncated result is the correct
# passphrase.
context.use_privatekey_file(pemFile)
def test_set_info_callback(self) -> None:
"""
`Context.set_info_callback` accepts a callable which will be
invoked when certain information about an SSL connection is available.
"""
(server, client) = socket_pair()
clientSSL = Connection(Context(SSLv23_METHOD), client)
clientSSL.set_connect_state()
called = []
def info(conn: Connection, where: int, ret: int) -> None:
called.append((conn, where, ret))
context = Context(SSLv23_METHOD)
context.set_info_callback(info)
context.use_certificate(load_certificate(FILETYPE_PEM, root_cert_pem))
context.use_privatekey(load_privatekey(FILETYPE_PEM, root_key_pem))
serverSSL = Connection(context, server)
serverSSL.set_accept_state()
handshake(clientSSL, serverSSL)