Debian Codegraph @

tests/test_ssl.py

raw ◀ ▶
2 Debian patches touch this file
1 # Copyright (C) Jean-Paul Calderone
2 # See LICENSE for details.
3
4 """
5 Unit tests for :mod:`OpenSSL.SSL`.
6 """
7
8 from __future__ import annotations
9
10 import contextlib
11 import datetime
12 import gc
13 import os
14 import pathlib
15 import select
16 import sys
17 import time
18 import typing
19 import uuid
20 from errno import (
21 EAFNOSUPPORT,
22 ECONNREFUSED,
23 EINPROGRESS,
24 EPIPE,
25 ESHUTDOWN,
26 EWOULDBLOCK,
27 )
28 from gc import collect, get_referrers
29 from os import makedirs
30 from socket import (
31 AF_INET,
32 AF_INET6,
33 MSG_PEEK,
34 SHUT_RDWR,
35 SO_RCVBUF,
36 SO_SNDBUF,
37 SOL_SOCKET,
38 gaierror,
39 socket,
40 socketpair,
41 )
42 from sys import getfilesystemencoding, platform
43 from weakref import ref
44
45 import pytest
46 from cryptography import x509
47 from cryptography.hazmat.primitives import hashes, serialization
48 from cryptography.hazmat.primitives.asymmetric import ec, rsa
49 from cryptography.x509.oid import NameOID
50 from pretend import raiser
51
52 from OpenSSL import SSL
53 from OpenSSL._util import ffi as _ffi
54 from OpenSSL._util import lib as _lib
55 from OpenSSL.crypto import (
56 FILETYPE_PEM,
57 TYPE_RSA,
58 X509,
59 PKey,
60 X509Name,
61 X509Store,
62 dump_certificate,
63 dump_privatekey,
64 get_elliptic_curves,
65 load_certificate,
66 load_privatekey,
67 )
68 from OpenSSL.SSL import (
69 DTLS_METHOD,
70 NO_OVERLAPPING_PROTOCOLS,
71 OP_COOKIE_EXCHANGE,
72 OP_NO_COMPRESSION,
73 OP_NO_QUERY_MTU,
74 OP_NO_TICKET,
75 OP_SINGLE_DH_USE,
76 OPENSSL_VERSION_NUMBER,
77 RECEIVED_SHUTDOWN,
78 SENT_SHUTDOWN,
79 SESS_CACHE_BOTH,
80 SESS_CACHE_CLIENT,
81 SESS_CACHE_NO_AUTO_CLEAR,
82 SESS_CACHE_NO_INTERNAL,
83 SESS_CACHE_NO_INTERNAL_LOOKUP,
84 SESS_CACHE_NO_INTERNAL_STORE,
85 SESS_CACHE_OFF,
86 SESS_CACHE_SERVER,
87 SSL_CB_ACCEPT_EXIT,
88 SSL_CB_ACCEPT_LOOP,
89 SSL_CB_ALERT,
90 SSL_CB_CONNECT_EXIT,
91 SSL_CB_CONNECT_LOOP,
92 SSL_CB_EXIT,
93 SSL_CB_HANDSHAKE_DONE,
94 SSL_CB_HANDSHAKE_START,
95 SSL_CB_LOOP,
96 SSL_CB_READ,
97 SSL_CB_READ_ALERT,
98 SSL_CB_WRITE,
99 SSL_CB_WRITE_ALERT,
100 SSL_ST_ACCEPT,
101 SSL_ST_CONNECT,
102 SSL_ST_MASK,
103 SSLEAY_BUILT_ON,
104 SSLEAY_CFLAGS,
105 SSLEAY_DIR,
106 SSLEAY_PLATFORM,
107 SSLEAY_VERSION,
108 TLS1_2_VERSION,
109 TLS1_3_VERSION,
110 TLS_METHOD,
111 VERIFY_CLIENT_ONCE,
112 VERIFY_FAIL_IF_NO_PEER_CERT,
113 VERIFY_NONE,
114 VERIFY_PEER,
115 Connection,
116 Context,
117 Error,
118 OP_NO_SSLv2,
119 OP_NO_SSLv3,
120 Session,
121 SSLeay_version,
122 SSLv23_METHOD,
123 SysCallError,
124 TLSv1_1_METHOD,
125 TLSv1_2_METHOD,
126 TLSv1_METHOD,
127 WantReadError,
128 WantWriteError,
129 ZeroReturnError,
130 _make_requires,
131 _NoOverlappingProtocols,
132 )
133
134 from . import conftest
135 from .test_crypto import (
136 client_cert_pem,
137 client_key_pem,
138 root_cert_pem,
139 root_key_pem,
140 server_cert_pem,
141 server_key_pem,
142 )
143 from .util import NON_ASCII, WARNING_TYPE_EXPECTED
144
145 # openssl dhparam 2048 -out dh-2048.pem
146 dhparam = """\
147 -----BEGIN DH PARAMETERS-----
148 MIIBCAKCAQEA2F5e976d/GjsaCdKv5RMWL/YV7fq1UUWpPAer5fDXflLMVUuYXxE
149 3m3ayZob9lbpgEU0jlPAsXHfQPGxpKmvhv+xV26V/DEoukED8JeZUY/z4pigoptl
150 +8+TYdNNE/rFSZQFXIp+v2D91IEgmHBnZlKFSbKR+p8i0KjExXGjU6ji3S5jkOku
151 ogikc7df1Ui0hWNJCmTjExq07aXghk97PsdFSxjdawuG3+vos5bnNoUwPLYlFc/z
152 ITYG0KXySiCLi4UDlXTZTz7u/+OYczPEgqa/JPUddbM/kfvaRAnjY38cfQ7qXf8Y
153 i5s5yYK7a/0eWxxRr2qraYaUj8RwDpH9CwIBAg==
154 -----END DH PARAMETERS-----
155 """
156
157
158 def socket_any_family() -> socket:
159 try:
160 return socket(AF_INET)
161 except OSError as e:
162 if e.errno == EAFNOSUPPORT:
163 return socket(AF_INET6)
164 raise
165
166
167 def loopback_address(socket: socket) -> str:
168 if socket.family == AF_INET:
169 return "127.0.0.1"
170 else:
171 assert socket.family == AF_INET6
172 return "::1"
173
174
175 def verify_cb(
176 conn: Connection, cert: X509, errnum: int, depth: int, ok: int
177 ) -> bool:
178 return bool(ok)
179
180
181 def socket_pair() -> tuple[socket, socket]:
182 """
183 Establish and return a pair of network sockets connected to each other.
184 """
185 # Connect a pair of sockets
186 port = socket_any_family()
187 port.bind(("", 0))
188 port.listen(1)
189 client = socket(port.family)
190 client.setblocking(False)
191 client.connect_ex((loopback_address(port), port.getsockname()[1]))
192 client.setblocking(True)
193 server = port.accept()[0]
194
195 port.close()
196
197 # Let's pass some unencrypted data to make sure our socket connection is
198 # fine. Just one byte, so we don't have to worry about buffers getting
199 # filled up or fragmentation.
200 server.send(b"x")
201 assert client.recv(1024) == b"x"
202 client.send(b"y")
203 assert server.recv(1024) == b"y"
204
205 # Most of our callers want non-blocking sockets, make it easy for them.
206 server.setblocking(False)
207 client.setblocking(False)
208
209 return (server, client)
210
211
212 def handshake(client: Connection, server: Connection) -> None:
213 conns = [client, server]
214 while conns:
215 for conn in conns:
216 try:
217 conn.do_handshake()
218 except WantReadError:
219 pass
220 else:
221 conns.remove(conn)
222
223
224 def _create_certificate_chain() -> list[tuple[PKey, X509]]:
225 """
226 Construct and return a chain of certificates.
227
228 1. A new self-signed certificate authority certificate (cacert)
229 2. A new intermediate certificate signed by cacert (icert)
230 3. A new server certificate signed by icert (scert)
231 """
232 not_before = datetime.datetime(2000, 1, 1, 0, 0, 0)
233 not_after = datetime.datetime.now() + datetime.timedelta(days=365)
234
235 # Step 1
236 cakey = rsa.generate_private_key(key_size=2048, public_exponent=65537)
237 casubject = x509.Name(
238 [x509.NameAttribute(x509.NameOID.COMMON_NAME, "Authority Certificate")]
239 )
240 cacert = (
241 x509.CertificateBuilder()
242 .subject_name(casubject)
243 .issuer_name(casubject)
244 .public_key(cakey.public_key())
245 .not_valid_before(not_before)
246 .not_valid_after(not_after)
247 .add_extension(
248 x509.BasicConstraints(ca=True, path_length=None), critical=False
249 )
250 .serial_number(1)
251 .sign(cakey, hashes.SHA256())
252 )
253
254 # Step 2
255 ikey = rsa.generate_private_key(key_size=2048, public_exponent=65537)
256 icert = (
257 x509.CertificateBuilder()
258 .subject_name(
259 x509.Name(
260 [
261 x509.NameAttribute(
262 x509.NameOID.COMMON_NAME, "Intermediate Certificate"
263 )
264 ]
265 )
266 )
267 .issuer_name(cacert.subject)
268 .public_key(ikey.public_key())
269 .not_valid_before(not_before)
270 .not_valid_after(not_after)
271 .add_extension(
272 x509.BasicConstraints(ca=True, path_length=None), critical=False
273 )
274 .serial_number(1)
275 .sign(cakey, hashes.SHA256())
276 )
277
278 # Step 3
279 skey = rsa.generate_private_key(key_size=2048, public_exponent=65537)
280 scert = (
281 x509.CertificateBuilder()
282 .subject_name(
283 x509.Name(
284 [
285 x509.NameAttribute(
286 x509.NameOID.COMMON_NAME, "Server Certificate"
287 )
288 ]
289 )
290 )
291 .issuer_name(icert.subject)
292 .public_key(skey.public_key())
293 .not_valid_before(not_before)
294 .not_valid_after(not_after)
295 .add_extension(
296 x509.BasicConstraints(ca=False, path_length=None), critical=True
297 )
298 .serial_number(1)
299 .sign(ikey, hashes.SHA256())
300 )
301
302 return [
303 (PKey.from_cryptography_key(cakey), X509.from_cryptography(cacert)),
304 (PKey.from_cryptography_key(ikey), X509.from_cryptography(icert)),
305 (PKey.from_cryptography_key(skey), X509.from_cryptography(scert)),
306 ]
307
308
309 def loopback_client_factory(
310 socket: socket, version: int = SSLv23_METHOD
311 ) -> Connection:
312 client = Connection(Context(version), socket)
313 client.set_connect_state()
314 return client
315
316
317 def loopback_server_factory(
318 socket: socket | None, version: int = SSLv23_METHOD
319 ) -> Connection:
320 ctx = Context(version)
321 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
322 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
323 server = Connection(ctx, socket)
324 server.set_accept_state()
325 return server
326
327
328 def loopback(
329 server_factory: typing.Callable[[socket], Connection] | None = None,
330 client_factory: typing.Callable[[socket], Connection] | None = None,
331 ) -> tuple[Connection, Connection]:
332 """
333 Create a connected socket pair and force two connected SSL sockets
334 to talk to each other.
335 """
336 if server_factory is None:
337 server_factory = loopback_server_factory
338 if client_factory is None:
339 client_factory = loopback_client_factory
340
341 (server, client) = socket_pair()
342 tls_server = server_factory(server)
343 tls_client = client_factory(client)
344
345 handshake(tls_client, tls_server)
346
347 tls_server.setblocking(True)
348 tls_client.setblocking(True)
349 return tls_server, tls_client
350
351
352 def interact_in_memory(
353 client_conn: Connection, server_conn: Connection
354 ) -> tuple[Connection, bytes] | None:
355 """
356 Try to read application bytes from each of the two `Connection` objects.
357 Copy bytes back and forth between their send/receive buffers for as long
358 as there is anything to copy. When there is nothing more to copy,
359 return `None`. If one of them actually manages to deliver some application
360 bytes, return a two-tuple of the connection from which the bytes were read
361 and the bytes themselves.
362 """
363 wrote = True
364 while wrote:
365 # Loop until neither side has anything to say
366 wrote = False
367
368 # Copy stuff from each side's send buffer to the other side's
369 # receive buffer.
370 for read, write in [
371 (client_conn, server_conn),
372 (server_conn, client_conn),
373 ]:
374 # Give the side a chance to generate some more bytes, or succeed.
375 try:
376 data = read.recv(2**16)
377 except WantReadError:
378 # It didn't succeed, so we'll hope it generated some output.
379 pass
380 else:
381 # It did succeed, so we'll stop now and let the caller deal
382 # with it.
383 return (read, data)
384
385 while True:
386 # Keep copying as long as there's more stuff there.
387 try:
388 dirty = read.bio_read(4096)
389 except WantReadError:
390 # Okay, nothing more waiting to be sent. Stop
391 # processing this send buffer.
392 break
393 else:
394 # Keep track of the fact that someone generated some
395 # output.
396 wrote = True
397 write.bio_write(dirty)
398
399 return None
400
401
402 def handshake_in_memory(
403 client_conn: Connection, server_conn: Connection
404 ) -> None:
405 """
406 Perform the TLS handshake between two `Connection` instances connected to
407 each other via memory BIOs.
408 """
409 client_conn.set_connect_state()
410 server_conn.set_accept_state()
411
412 for conn in [client_conn, server_conn]:
413 try:
414 conn.do_handshake()
415 except WantReadError:
416 pass
417
418 interact_in_memory(client_conn, server_conn)
419
420
421 def get_ssl_error_reason(ssl_error: SSL.Error) -> str | None:
422 """
423 Extracts the reason string from the first error tuple in an SSL.Error.
424 Returns None if the expected error structure is not found.
425 """
426 if (
427 ssl_error.args
428 and isinstance(ssl_error.args, tuple)
429 and len(ssl_error.args) > 0
430 ):
431 error_details = ssl_error.args[0] # list of error tuples
432 if isinstance(error_details, list) and len(error_details) > 0:
433 first_error_tuple = error_details[0]
434 if (
435 isinstance(first_error_tuple, tuple)
436 and len(first_error_tuple) >= 3
437 ):
438 reason = first_error_tuple[2]
439 if isinstance(reason, str):
440 return reason
441 return None
442
443
444 def create_ssl_nonblocking_connection(
445 mode: int | None, request_send_buffer_size: int
446 ) -> tuple[Connection, Connection, int, int]:
447 """
448 Create a pair of sockets and set up an SSL connection between them.
449 mode: The mode to set if not None.
450 request_send_buffer_size: requested size of the send buffer
451 Returns the SSL Connection objects
452 and the actual send/receive buffer sizes.
453 """
454
455 client_socket, server_socket = socket_pair()
456
457 # Set up client context
458 client_ctx = Context(SSLv23_METHOD)
459
460 # SSL_MODE_ENABLE_PARTIAL_WRITE and
461 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER modes
462 # are set by default when ctx is initialized.
463 # Clear them if requested so tests can
464 # be run without them if so desired.
465 if mode is not None:
466 client_ctx.clear_mode(
467 _lib.SSL_MODE_ENABLE_PARTIAL_WRITE
468 | _lib.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
469 )
470 # Set the new mode to the requested value
471 client_ctx.set_mode(mode)
472
473 # create the SSL connections
474 client = Connection(client_ctx, client_socket)
475 server = loopback_server_factory(server_socket)
476
477 # Allow caller to request small buffer sizes so they can be easily filled.
478 # Note the OS may not respect the requested values.
479 # Make the receive buffer smaller than the send buffer.
480 requested_receive_buffer_size = request_send_buffer_size // 2
481 client_socket.setsockopt(SOL_SOCKET, SO_SNDBUF, request_send_buffer_size)
482 actual_sndbuf = client_socket.getsockopt(SOL_SOCKET, SO_SNDBUF)
483
484 server_socket.setsockopt(
485 SOL_SOCKET, SO_RCVBUF, requested_receive_buffer_size
486 )
487 actual_rcvbuf = server_socket.getsockopt(SOL_SOCKET, SO_RCVBUF)
488
489 # set the connection state
490 client.set_connect_state()
491 # loopback_server_factory already sets the accept state on the server
492
493 handshake(client, server)
494
495 return (
496 client,
497 server,
498 actual_sndbuf,
499 actual_rcvbuf,
500 )
501
502
503 class TestVersion:
504 """
505 Tests for version information exposed by `OpenSSL.SSL.SSLeay_version` and
506 `OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
507 """
508
509 def test_OPENSSL_VERSION_NUMBER(self) -> None:
510 """
511 `OPENSSL_VERSION_NUMBER` is an integer with status in the low byte and
512 the patch, fix, minor, and major versions in the nibbles above that.
513 """
514 assert isinstance(OPENSSL_VERSION_NUMBER, int)
515
516 def test_SSLeay_version(self) -> None:
517 """
518 `SSLeay_version` takes a version type indicator and returns one of a
519 number of version strings based on that indicator.
520 """
521 versions = {}
522 for t in [
523 SSLEAY_VERSION,
524 SSLEAY_CFLAGS,
525 SSLEAY_BUILT_ON,
526 SSLEAY_PLATFORM,
527 SSLEAY_DIR,
528 ]:
529 version = SSLeay_version(t)
530 versions[version] = t
531 assert isinstance(version, bytes)
532 assert len(versions) == 5
533
534
535 @pytest.fixture
536 def ca_file(tmp_path: pathlib.Path) -> bytes:
537 """
538 Create a valid PEM file with CA certificates and return the path.
539 """
540 key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
541 public_key = key.public_key()
542
543 builder = x509.CertificateBuilder()
544 builder = builder.subject_name(
545 x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "pyopenssl.org")])
546 )
547 builder = builder.issuer_name(
548 x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "pyopenssl.org")])
549 )
550 one_day = datetime.timedelta(1, 0, 0)
551 builder = builder.not_valid_before(datetime.datetime.today() - one_day)
552 builder = builder.not_valid_after(datetime.datetime.today() + one_day)
553 builder = builder.serial_number(int(uuid.uuid4()))
554 builder = builder.public_key(public_key)
555 builder = builder.add_extension(
556 x509.BasicConstraints(ca=True, path_length=None),
557 critical=True,
558 )
559
560 certificate = builder.sign(private_key=key, algorithm=hashes.SHA256())
561
562 ca_file = tmp_path / "test.pem"
563 ca_file.write_bytes(
564 certificate.public_bytes(
565 encoding=serialization.Encoding.PEM,
566 )
567 )
568
569 return str(ca_file).encode("ascii")
570
571
572 @pytest.fixture
573 def context() -> Context:
574 """
575 A simple "best TLS you can get" context. TLS 1.2+ in any reasonable OpenSSL
576 """
577 return Context(SSLv23_METHOD)
578
579
580 class TestContext:
581 """
582 Unit tests for `OpenSSL.SSL.Context`.
583 """
584
585 @pytest.mark.parametrize(
586 "cipher_string",
587 [b"hello world:AES128-SHA", "hello world:AES128-SHA"],
588 )
589 def test_set_cipher_list(
590 self, context: Context, cipher_string: bytes
591 ) -> None:
592 """
593 `Context.set_cipher_list` accepts both byte and unicode strings
594 for naming the ciphers which connections created with the context
595 object will be able to choose from.
596 """
597 context.set_cipher_list(cipher_string)
598 conn = Connection(context, None)
599
600 assert "AES128-SHA" in conn.get_cipher_list()
601
602 def test_set_tls13_ciphersuites(self, context: Context) -> None:
603 """
604 `Context.set_tls13_ciphersuites` accepts both byte and unicode strings
605 for naming the ciphers which connections created with the context
606 object will be able to choose from.
607 """
608 context.set_tls13_ciphersuites(b"TLS_AES_128_GCM_SHA256")
609 conn = Connection(context, None)
610
611 # OpenSSL has different APIs for *setting* TLS <=1.2 and >= 1.3
612 # but only one API for retrieving them
613 assert "TLS_AES_128_GCM_SHA256" in conn.get_cipher_list()
614 assert "TLS_AES_256_GCM_SHA384" not in conn.get_cipher_list()
615
616 def test_set_cipher_list_wrong_type(self, context: Context) -> None:
617 """
618 `Context.set_cipher_list` raises `TypeError` when passed a non-string
619 argument.
620 """
621 with pytest.raises(TypeError):
622 context.set_cipher_list(object()) # type: ignore[arg-type]
623
624 @pytest.mark.flaky(reruns=2)
625 def test_set_cipher_list_no_cipher_match(self, context: Context) -> None:
626 """
627 `Context.set_cipher_list` raises `OpenSSL.SSL.Error` with a
628 `"no cipher match"` reason string regardless of the TLS
629 version.
630 """
631 with pytest.raises(Error) as excinfo:
632 context.set_cipher_list(b"imaginary-cipher")
633 assert excinfo.value.args[0][0] in [
634 # 1.1.x
635 (
636 "SSL routines",
637 "SSL_CTX_set_cipher_list",
638 "no cipher match",
639 ),
640 # 3.0.x
641 (
642 "SSL routines",
643 "",
644 "no cipher match",
645 ),
646 # aws-lc
647 (
648 "SSL routines",
649 "OPENSSL_internal",
650 "NO_CIPHER_MATCH",
651 ),
652 ]
653
654 def test_load_client_ca(self, context: Context, ca_file: bytes) -> None:
655 """
656 `Context.load_client_ca` works as far as we can tell.
657 """
658 context.load_client_ca(ca_file)
659
660 def test_load_client_ca_invalid(
661 self, context: Context, tmp_path: pathlib.Path
662 ) -> None:
663 """
664 `Context.load_client_ca` raises an Error if the ca file is invalid.
665 """
666 ca_file = tmp_path / "test.pem"
667 ca_file.write_text("")
668
669 with pytest.raises(Error) as e:
670 context.load_client_ca(str(ca_file).encode("ascii"))
671
672 assert "PEM routines" == e.value.args[0][0][0]
673
674 def test_load_client_ca_unicode(
675 self, context: Context, ca_file: bytes
676 ) -> None:
677 """
678 Passing the path as unicode raises a warning but works.
679 """
680 with pytest.deprecated_call():
681 context.load_client_ca(ca_file.decode("ascii")) # type: ignore[arg-type]
682
683 def test_set_session_id(self, context: Context) -> None:
684 """
685 `Context.set_session_id` works as far as we can tell.
686 """
687 context.set_session_id(b"abc")
688
689 def test_set_session_id_fail(self, context: Context) -> None:
690 """
691 `Context.set_session_id` errors are propagated.
692 """
693 with pytest.raises(Error) as e:
694 context.set_session_id(b"abc" * 1000)
695
696 assert e.value.args[0][0] in [
697 # 1.1.x
698 (
699 "SSL routines",
700 "SSL_CTX_set_session_id_context",
701 "ssl session id context too long",
702 ),
703 # 3.0.x
704 (
705 "SSL routines",
706 "",
707 "ssl session id context too long",
708 ),
709 # aws-lc
710 (
711 "SSL routines",
712 "OPENSSL_internal",
713 "SSL_SESSION_ID_CONTEXT_TOO_LONG",
714 ),
715 ]
716
717 def test_set_session_id_unicode(self, context: Context) -> None:
718 """
719 `Context.set_session_id` raises a warning if a unicode string is
720 passed.
721 """
722 with pytest.deprecated_call():
723 context.set_session_id("abc") # type: ignore[arg-type]
724
725 def test_method(self) -> None:
726 """
727 `Context` can be instantiated with one of `SSLv2_METHOD`,
728 `SSLv3_METHOD`, `SSLv23_METHOD`, `TLSv1_METHOD`, `TLSv1_1_METHOD`,
729 or `TLSv1_2_METHOD`.
730 """
731 methods = [SSLv23_METHOD, TLSv1_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
732 for meth in methods:
733 Context(meth)
734
735 with pytest.raises(TypeError):
736 Context("") # type: ignore[arg-type]
737 with pytest.raises(ValueError):
738 Context(13)
739
740 def test_use_privatekey_file_missing(self, tmpfile: bytes) -> None:
741 """
742 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` when passed
743 the name of a file which does not exist.
744 """
745 ctx = Context(SSLv23_METHOD)
746 with pytest.raises(Error):
747 ctx.use_privatekey_file(tmpfile)
748
749 def _use_privatekey_file_test(
750 self, pemfile: bytes | str, filetype: int
751 ) -> None:
752 """
753 Verify that calling ``Context.use_privatekey_file`` with the given
754 arguments does not raise an exception.
755 """
756 key = PKey()
757 key.generate_key(TYPE_RSA, 1024)
758
759 with open(pemfile, "w") as pem:
760 pem.write(dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
761
762 ctx = Context(SSLv23_METHOD)
763 ctx.use_privatekey_file(pemfile, filetype)
764
765 @pytest.mark.parametrize("filetype", [object(), "", None, 1.0])
766 def test_wrong_privatekey_file_wrong_args(
767 self, tmpfile: bytes, filetype: object
768 ) -> None:
769 """
770 `Context.use_privatekey_file` raises `TypeError` when called with
771 a `filetype` which is not a valid file encoding.
772 """
773 ctx = Context(SSLv23_METHOD)
774 with pytest.raises(TypeError):
775 ctx.use_privatekey_file(tmpfile, filetype) # type: ignore[arg-type]
776
777 def test_use_privatekey_file_bytes(self, tmpfile: bytes) -> None:
778 """
779 A private key can be specified from a file by passing a ``bytes``
780 instance giving the file name to ``Context.use_privatekey_file``.
781 """
782 self._use_privatekey_file_test(
783 tmpfile + NON_ASCII.encode(getfilesystemencoding()),
784 FILETYPE_PEM,
785 )
786
787 def test_use_privatekey_file_unicode(self, tmpfile: bytes) -> None:
788 """
789 A private key can be specified from a file by passing a ``unicode``
790 instance giving the file name to ``Context.use_privatekey_file``.
791 """
792 self._use_privatekey_file_test(
793 tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
794 FILETYPE_PEM,
795 )
796
797 def test_use_certificate_file_wrong_args(self) -> None:
798 """
799 `Context.use_certificate_file` raises `TypeError` if the first
800 argument is not a byte string or the second argument is not an integer.
801 """
802 ctx = Context(SSLv23_METHOD)
803 with pytest.raises(TypeError):
804 ctx.use_certificate_file(object(), FILETYPE_PEM) # type: ignore[arg-type]
805 with pytest.raises(TypeError):
806 ctx.use_certificate_file(b"somefile", object()) # type: ignore[arg-type]
807 with pytest.raises(TypeError):
808 ctx.use_certificate_file(object(), FILETYPE_PEM) # type: ignore[arg-type]
809
810 def test_use_certificate_file_missing(self, tmpfile: bytes) -> None:
811 """
812 `Context.use_certificate_file` raises `OpenSSL.SSL.Error` if passed
813 the name of a file which does not exist.
814 """
815 ctx = Context(SSLv23_METHOD)
816 with pytest.raises(Error):
817 ctx.use_certificate_file(tmpfile)
818
819 def _use_certificate_file_test(
820 self, certificate_file: bytes | str
821 ) -> None:
822 """
823 Verify that calling ``Context.use_certificate_file`` with the given
824 filename doesn't raise an exception.
825 """
826 # TODO
827 # Hard to assert anything. But we could set a privatekey then ask
828 # OpenSSL if the cert and key agree using check_privatekey. Then as
829 # long as check_privatekey works right we're good...
830 with open(certificate_file, "wb") as pem_file:
831 pem_file.write(root_cert_pem)
832
833 ctx = Context(SSLv23_METHOD)
834 ctx.use_certificate_file(certificate_file)
835
836 def test_use_certificate_file_bytes(self, tmpfile: bytes) -> None:
837 """
838 `Context.use_certificate_file` sets the certificate (given as a
839 `bytes` filename) which will be used to identify connections created
840 using the context.
841 """
842 filename = tmpfile + NON_ASCII.encode(getfilesystemencoding())
843 self._use_certificate_file_test(filename)
844
845 def test_use_certificate_file_unicode(self, tmpfile: bytes) -> None:
846 """
847 `Context.use_certificate_file` sets the certificate (given as a
848 `bytes` filename) which will be used to identify connections created
849 using the context.
850 """
851 filename = tmpfile.decode(getfilesystemencoding()) + NON_ASCII
852 self._use_certificate_file_test(filename)
853
854 def test_check_privatekey_valid(self) -> None:
855 """
856 `Context.check_privatekey` returns `None` if the `Context` instance
857 has been configured to use a matched key and certificate pair.
858 """
859 key = load_privatekey(FILETYPE_PEM, client_key_pem)
860 cert = load_certificate(FILETYPE_PEM, client_cert_pem)
861 context = Context(SSLv23_METHOD)
862 context.use_privatekey(key)
863 context.use_certificate(cert)
864 assert context.check_privatekey() is None # type: ignore[func-returns-value]
865
866 context = Context(SSLv23_METHOD)
867 cryptography_key = key.to_cryptography_key()
868 assert isinstance(cryptography_key, rsa.RSAPrivateKey)
869 context.use_privatekey(cryptography_key)
870 context.use_certificate(cert)
871 assert context.check_privatekey() is None # type: ignore[func-returns-value]
872
873 def test_check_privatekey_invalid(self) -> None:
874 """
875 `Context.check_privatekey` raises `Error` if the `Context` instance
876 has been configured to use a key and certificate pair which don't
877 relate to each other.
878 """
879 key = load_privatekey(FILETYPE_PEM, client_key_pem)
880 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
881 context = Context(SSLv23_METHOD)
882 context.use_privatekey(key)
883 context.use_certificate(cert)
884 with pytest.raises(Error):
885 context.check_privatekey()
886
887 context = Context(SSLv23_METHOD)
888 cryptography_key = key.to_cryptography_key()
889 assert isinstance(cryptography_key, rsa.RSAPrivateKey)
890 context.use_privatekey(cryptography_key)
891 context.use_certificate(cert)
892 with pytest.raises(Error):
893 context.check_privatekey()
894
895 def test_app_data(self) -> None:
896 """
897 `Context.set_app_data` stores an object for later retrieval
898 using `Context.get_app_data`.
899 """
900 app_data = object()
901 context = Context(SSLv23_METHOD)
902 context.set_app_data(app_data)
903 assert context.get_app_data() is app_data
904
905 def test_set_options_wrong_args(self) -> None:
906 """
907 `Context.set_options` raises `TypeError` if called with
908 a non-`int` argument.
909 """
910 context = Context(SSLv23_METHOD)
911 with pytest.raises(TypeError):
912 context.set_options(None) # type: ignore[arg-type]
913
914 def test_set_options(self) -> None:
915 """
916 `Context.set_options` returns the new options value.
917 """
918 context = Context(SSLv23_METHOD)
919 options = context.set_options(OP_NO_SSLv2)
920 assert options & OP_NO_SSLv2 == OP_NO_SSLv2
921
922 def test_set_mode_wrong_args(self) -> None:
923 """
924 `Context.set_mode` raises `TypeError` if called with
925 a non-`int` argument.
926 """
927 context = Context(SSLv23_METHOD)
928 with pytest.raises(TypeError):
929 context.set_mode(None) # type: ignore[arg-type]
930
931 def test_set_mode(self) -> None:
932 """
933 `Context.set_mode` accepts a mode bitvector and returns the
934 newly set mode.
935 """
936 context = Context(SSLv23_METHOD)
937 mode = _lib.SSL_MODE_ENABLE_PARTIAL_WRITE
938 assert mode & context.set_mode(mode)
939
940 def test_set_timeout_wrong_args(self) -> None:
941 """
942 `Context.set_timeout` raises `TypeError` if called with
943 a non-`int` argument.
944 """
945 context = Context(SSLv23_METHOD)
946 with pytest.raises(TypeError):
947 context.set_timeout(None) # type: ignore[arg-type]
948
949 def test_timeout(self) -> None:
950 """
951 `Context.set_timeout` sets the session timeout for all connections
952 created using the context object. `Context.get_timeout` retrieves
953 this value.
954 """
955 context = Context(SSLv23_METHOD)
956 context.set_timeout(1234)
957 assert context.get_timeout() == 1234
958
959 def test_set_verify_depth_wrong_args(self) -> None:
960 """
961 `Context.set_verify_depth` raises `TypeError` if called with a
962 non-`int` argument.
963 """
964 context = Context(SSLv23_METHOD)
965 with pytest.raises(TypeError):
966 context.set_verify_depth(None) # type: ignore[arg-type]
967
968 def test_verify_depth(self) -> None:
969 """
970 `Context.set_verify_depth` sets the number of certificates in
971 a chain to follow before giving up. The value can be retrieved with
972 `Context.get_verify_depth`.
973 """
974 context = Context(SSLv23_METHOD)
975 context.set_verify_depth(11)
976 assert context.get_verify_depth() == 11
977
978 def _write_encrypted_pem(self, passphrase: bytes, tmpfile: bytes) -> bytes:
979 """
980 Write a new private key out to a new file, encrypted using the given
981 passphrase. Return the path to the new file.
982 """
983 key = PKey()
984 key.generate_key(TYPE_RSA, 1024)
985 pem = dump_privatekey(FILETYPE_PEM, key, "aes-256-cbc", passphrase)
986 with open(tmpfile, "w") as fObj:
987 fObj.write(pem.decode("ascii"))
988 return tmpfile
989
990 def test_set_passwd_cb_wrong_args(self) -> None:
991 """
992 `Context.set_passwd_cb` raises `TypeError` if called with a
993 non-callable first argument.
994 """
995 context = Context(SSLv23_METHOD)
996 with pytest.raises(TypeError):
997 context.set_passwd_cb(None) # type: ignore[arg-type]
998
999 def test_set_passwd_cb(self, tmpfile: bytes) -> None:
1000 """
1001 `Context.set_passwd_cb` accepts a callable which will be invoked when
1002 a private key is loaded from an encrypted PEM.
1003 """
1004 passphrase = b"foobar"
1005 pemFile = self._write_encrypted_pem(passphrase, tmpfile)
1006 calledWith = []
1007
1008 def passphraseCallback(
1009 maxlen: int, verify: bool, extra: None
1010 ) -> bytes:
1011 calledWith.append((maxlen, verify, extra))
1012 return passphrase
1013
1014 context = Context(SSLv23_METHOD)
1015 context.set_passwd_cb(passphraseCallback)
1016 context.use_privatekey_file(pemFile)
1017 assert len(calledWith) == 1
1018 assert isinstance(calledWith[0][0], int)
1019 assert isinstance(calledWith[0][1], int)
1020 assert calledWith[0][2] is None
1021
1022 def test_passwd_callback_exception(self, tmpfile: bytes) -> None:
1023 """
1024 `Context.use_privatekey_file` propagates any exception raised
1025 by the passphrase callback.
1026 """
1027 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
1028
1029 def passphraseCallback(
1030 maxlen: int, verify: bool, extra: None
1031 ) -> bytes:
1032 raise RuntimeError("Sorry, I am a fail.")
1033
1034 context = Context(SSLv23_METHOD)
1035 context.set_passwd_cb(passphraseCallback)
1036 with pytest.raises(RuntimeError):
1037 context.use_privatekey_file(pemFile)
1038
1039 def test_passwd_callback_false(self, tmpfile: bytes) -> None:
1040 """
1041 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
1042 passphrase callback returns a false value.
1043 """
1044 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
1045
1046 def passphraseCallback(
1047 maxlen: int, verify: bool, extra: None
1048 ) -> bytes:
1049 return b""
1050
1051 context = Context(SSLv23_METHOD)
1052 context.set_passwd_cb(passphraseCallback)
1053 with pytest.raises(Error):
1054 context.use_privatekey_file(pemFile)
1055
1056 def test_passwd_callback_non_string(self, tmpfile: bytes) -> None:
1057 """
1058 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
1059 passphrase callback returns a true non-string value.
1060 """
1061 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
1062
1063 def passphraseCallback(maxlen: int, verify: bool, extra: None) -> int:
1064 return 10
1065
1066 context = Context(SSLv23_METHOD)
1067 context.set_passwd_cb(passphraseCallback) # type: ignore[arg-type]
1068 # TODO: Surely this is the wrong error?
1069 with pytest.raises(ValueError):
1070 context.use_privatekey_file(pemFile)
1071
1072 def test_passwd_callback_too_long(self, tmpfile: bytes) -> None:
1073 """
1074 If the passphrase returned by the passphrase callback returns a string
1075 longer than the indicated maximum length, it is truncated.
1076 """
1077 # A priori knowledge!
1078 passphrase = b"x" * 1024
1079 pemFile = self._write_encrypted_pem(passphrase, tmpfile)
1080
1081 def passphraseCallback(
1082 maxlen: int, verify: bool, extra: None
1083 ) -> bytes:
1084 assert maxlen == 1024
1085 return passphrase + b"y"
1086
1087 context = Context(SSLv23_METHOD)
1088 context.set_passwd_cb(passphraseCallback)
1089 # This shall succeed because the truncated result is the correct
1090 # passphrase.
1091 context.use_privatekey_file(pemFile)
1092
1093 def test_set_info_callback(self) -> None:
1094 """
1095 `Context.set_info_callback` accepts a callable which will be
1096 invoked when certain information about an SSL connection is available.
1097 """
1098 (server, client) = socket_pair()
1099
1100 clientSSL = Connection(Context(SSLv23_METHOD), client)
1101 clientSSL.set_connect_state()
1102
1103 called = []
1104
1105 def info(conn: Connection, where: int, ret: int) -> None:
1106 called.append((conn, where, ret))
1107
1108 context = Context(SSLv23_METHOD)
1109 context.set_info_callback(info)
1110 context.use_certificate(load_certificate(FILETYPE_PEM, root_cert_pem))
1111 context.use_privatekey(load_privatekey(FILETYPE_PEM, root_key_pem))
1112
1113 serverSSL = Connection(context, server)
1114 serverSSL.set_accept_state()
1115
1116 handshake(clientSSL, serverSSL)
1117
1118 # The callback must always be called with a Connection instance as the
1119 # first argument. It would probably be better to split this into
1120 # separate tests for client and server side info callbacks so we could
1121 # assert it is called with the right Connection instance. It would
1122 # also be good to assert *something* about `where` and `ret`.
1123 notConnections = [
1124 conn
1125 for (conn, where, ret) in called
1126 if not isinstance(conn, Connection)
1127 ]
1128 assert [] == notConnections, (
1129 "Some info callback arguments were not Connection instances."
1130 )
1131
1132 @pytest.mark.skipif(
1133 not getattr(_lib, "Cryptography_HAS_KEYLOG", None),
1134 reason="SSL_CTX_set_keylog_callback unavailable",
1135 )
1136 def test_set_keylog_callback(self) -> None:
1137 """
1138 `Context.set_keylog_callback` accepts a callable which will be
1139 invoked when key material is generated or received.
1140 """
1141 called = []
1142
1143 def keylog(conn: Connection, line: bytes) -> None:
1144 called.append((conn, line))
1145
1146 server_context = Context(TLSv1_2_METHOD)
1147 server_context.set_keylog_callback(keylog)
1148 server_context.use_certificate(
1149 load_certificate(FILETYPE_PEM, root_cert_pem)
1150 )
1151 server_context.use_privatekey(
1152 load_privatekey(FILETYPE_PEM, root_key_pem)
1153 )
1154
1155 client_context = Context(SSLv23_METHOD)
1156
1157 self._handshake_test(server_context, client_context)
1158
1159 assert called
1160 assert all(isinstance(conn, Connection) for conn, line in called)
1161 assert all(b"CLIENT_RANDOM" in line for conn, line in called)
1162
1163 def test_set_proto_version(self) -> None:
1164 high_version = TLS1_3_VERSION
1165 low_version = TLS1_2_VERSION
1166
1167 server_context = Context(TLS_METHOD)
1168 server_context.use_certificate(
1169 load_certificate(FILETYPE_PEM, root_cert_pem)
1170 )
1171 server_context.use_privatekey(
1172 load_privatekey(FILETYPE_PEM, root_key_pem)
1173 )
1174 server_context.set_min_proto_version(high_version)
1175
1176 client_context = Context(TLS_METHOD)
1177 client_context.set_max_proto_version(low_version)
1178
1179 with pytest.raises(Error, match=r"(?i)unsupported.protocol"):
1180 self._handshake_test(server_context, client_context)
1181
1182 client_context = Context(TLS_METHOD)
1183 client_context.set_max_proto_version(0)
1184 self._handshake_test(server_context, client_context)
1185
1186 def _load_verify_locations_test(
1187 self, cafile: bytes | str | None, capath: bytes | str | None = None
1188 ) -> None:
1189 """
1190 Create a client context which will verify the peer certificate and call
1191 its `load_verify_locations` method with the given arguments.
1192 Then connect it to a server and ensure that the handshake succeeds.
1193 """
1194 (server, client) = socket_pair()
1195
1196 clientContext = Context(SSLv23_METHOD)
1197 clientContext.load_verify_locations(cafile, capath)
1198 # Require that the server certificate verify properly or the
1199 # connection will fail.
1200 clientContext.set_verify(
1201 VERIFY_PEER,
1202 lambda conn, cert, errno, depth, preverify_ok: bool(preverify_ok),
1203 )
1204
1205 clientSSL = Connection(clientContext, client)
1206 clientSSL.set_connect_state()
1207
1208 serverContext = Context(SSLv23_METHOD)
1209 serverContext.use_certificate(
1210 load_certificate(FILETYPE_PEM, root_cert_pem)
1211 )
1212 serverContext.use_privatekey(
1213 load_privatekey(FILETYPE_PEM, root_key_pem)
1214 )
1215
1216 serverSSL = Connection(serverContext, server)
1217 serverSSL.set_accept_state()
1218
1219 # Without load_verify_locations above, the handshake
1220 # will fail:
1221 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
1222 # 'certificate verify failed')]
1223 handshake(clientSSL, serverSSL)
1224
1225 cert = clientSSL.get_peer_certificate()
1226 assert cert is not None
1227 assert cert.get_subject().CN == "Testing Root CA"
1228
1229 cryptography_cert = clientSSL.get_peer_certificate(
1230 as_cryptography=True
1231 )
1232 assert cryptography_cert is not None
1233 assert (
1234 cryptography_cert.subject.rfc4514_string()
1235 == "CN=Testing Root CA,O=Testing,L=Chicago,ST=IL,C=US"
1236 )
1237
1238 def _load_verify_cafile(self, cafile: str | bytes) -> None:
1239 """
1240 Verify that if path to a file containing a certificate is passed to
1241 `Context.load_verify_locations` for the ``cafile`` parameter, that
1242 certificate is used as a trust root for the purposes of verifying
1243 connections created using that `Context`.
1244 """
1245 with open(cafile, "w") as fObj:
1246 fObj.write(root_cert_pem.decode("ascii"))
1247
1248 self._load_verify_locations_test(cafile)
1249
1250 def test_load_verify_bytes_cafile(self, tmpfile: bytes) -> None:
1251 """
1252 `Context.load_verify_locations` accepts a file name as a `bytes`
1253 instance and uses the certificates within for verification purposes.
1254 """
1255 cafile = tmpfile + NON_ASCII.encode(getfilesystemencoding())
1256 self._load_verify_cafile(cafile)
1257
1258 def test_load_verify_unicode_cafile(self, tmpfile: bytes) -> None:
1259 """
1260 `Context.load_verify_locations` accepts a file name as a `unicode`
1261 instance and uses the certificates within for verification purposes.
1262 """
1263 self._load_verify_cafile(
1264 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
1265 )
1266
1267 def test_load_verify_invalid_file(self, tmpfile: bytes) -> None:
1268 """
1269 `Context.load_verify_locations` raises `Error` when passed a
1270 non-existent cafile.
1271 """
1272 clientContext = Context(SSLv23_METHOD)
1273 with pytest.raises(Error):
1274 clientContext.load_verify_locations(tmpfile)
1275
1276 def _load_verify_directory_locations_capath(
1277 self, capath: str | bytes
1278 ) -> None:
1279 """
1280 Verify that if path to a directory containing certificate files is
1281 passed to ``Context.load_verify_locations`` for the ``capath``
1282 parameter, those certificates are used as trust roots for the purposes
1283 of verifying connections created using that ``Context``.
1284 """
1285 makedirs(capath)
1286 # Hash values computed manually with c_rehash to avoid depending on
1287 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
1288 # from OpenSSL 1.0.0.
1289 for name in [b"c7adac82.0", b"c3705638.0"]:
1290 cafile: str | bytes
1291 if isinstance(capath, str):
1292 cafile = os.path.join(capath, name.decode())
1293 else:
1294 cafile = os.path.join(capath, name)
1295 with open(cafile, "w") as fObj:
1296 fObj.write(root_cert_pem.decode("ascii"))
1297
1298 self._load_verify_locations_test(None, capath)
1299
1300 @pytest.mark.parametrize(
1301 "pathtype",
1302 [
1303 "ascii_path",
1304 pytest.param(
1305 "unicode_path",
1306 marks=pytest.mark.skipif(
1307 platform == "win32",
1308 reason="Unicode paths not supported on Windows",
1309 ),
1310 ),
1311 ],
1312 )
1313 @pytest.mark.parametrize("argtype", ["bytes_arg", "unicode_arg"])
1314 def test_load_verify_directory_capath(
1315 self, pathtype: str, argtype: str, tmpfile: bytes
1316 ) -> None:
1317 """
1318 `Context.load_verify_locations` accepts a directory name as a `bytes`
1319 instance and uses the certificates within for verification purposes.
1320 """
1321 if pathtype == "unicode_path":
1322 tmpfile += NON_ASCII.encode(getfilesystemencoding())
1323
1324 if argtype == "unicode_arg":
1325 self._load_verify_directory_locations_capath(
1326 tmpfile.decode(getfilesystemencoding())
1327 )
1328 else:
1329 self._load_verify_directory_locations_capath(tmpfile)
1330
1331 def test_load_verify_locations_wrong_args(self) -> None:
1332 """
1333 `Context.load_verify_locations` raises `TypeError` if with non-`str`
1334 arguments.
1335 """
1336 context = Context(SSLv23_METHOD)
1337 with pytest.raises(TypeError):
1338 context.load_verify_locations(object()) # type: ignore[arg-type]
1339 with pytest.raises(TypeError):
1340 context.load_verify_locations(object(), object()) # type: ignore[arg-type]
1341
1342 @pytest.mark.skipif(
1343 not platform.startswith("linux"),
1344 reason="Loading fallback paths is a linux-specific behavior to "
1345 "accommodate pyca/cryptography manylinux wheels",
1346 )
1347 def test_fallback_default_verify_paths(
1348 self, monkeypatch: pytest.MonkeyPatch
1349 ) -> None:
1350 """
1351 Test that we load certificates successfully on linux from the fallback
1352 path. To do this we set the _CRYPTOGRAPHY_MANYLINUX_CA_FILE and
1353 _CRYPTOGRAPHY_MANYLINUX_CA_DIR vars to be equal to whatever the
1354 current OpenSSL default is and we disable
1355 SSL_CTX_SET_default_verify_paths so that it can't find certs unless
1356 it loads via fallback.
1357 """
1358 context = Context(SSLv23_METHOD)
1359 monkeypatch.setattr(
1360 _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
1361 )
1362 monkeypatch.setattr(
1363 SSL,
1364 "_CRYPTOGRAPHY_MANYLINUX_CA_FILE",
1365 _ffi.string(_lib.X509_get_default_cert_file()),
1366 )
1367 monkeypatch.setattr(
1368 SSL,
1369 "_CRYPTOGRAPHY_MANYLINUX_CA_DIR",
1370 _ffi.string(_lib.X509_get_default_cert_dir()),
1371 )
1372 context.set_default_verify_paths()
1373 store = context.get_cert_store()
1374 assert store is not None
1375 sk_obj = _lib.X509_STORE_get0_objects(store._store)
1376 assert sk_obj != _ffi.NULL
1377 num = _lib.sk_X509_OBJECT_num(sk_obj)
1378 assert num != 0
1379
1380 def test_check_env_vars(self, monkeypatch: pytest.MonkeyPatch) -> None:
1381 """
1382 Test that we return True/False appropriately if the env vars are set.
1383 """
1384 context = Context(SSLv23_METHOD)
1385 dir_var = "CUSTOM_DIR_VAR"
1386 file_var = "CUSTOM_FILE_VAR"
1387 assert context._check_env_vars_set(dir_var, file_var) is False
1388 monkeypatch.setenv(dir_var, "value")
1389 monkeypatch.setenv(file_var, "value")
1390 assert context._check_env_vars_set(dir_var, file_var) is True
1391 assert context._check_env_vars_set(dir_var, file_var) is True
1392
1393 def test_verify_no_fallback_if_env_vars_set(
1394 self, monkeypatch: pytest.MonkeyPatch
1395 ) -> None:
1396 """
1397 Test that we don't use the fallback path if env vars are set.
1398 """
1399 context = Context(SSLv23_METHOD)
1400 monkeypatch.setattr(
1401 _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
1402 )
1403 monkeypatch.setenv("SSL_CERT_DIR", "value")
1404 monkeypatch.setenv("SSL_CERT_FILE", "value")
1405 context.set_default_verify_paths()
1406
1407 monkeypatch.setattr(
1408 context, "_fallback_default_verify_paths", raiser(SystemError)
1409 )
1410 context.set_default_verify_paths()
1411
1412 @pytest.mark.skipif(
•1413 platform == "win32",
1414 reason="set_default_verify_paths appears not to work on Windows. "
1415 "See LP#404343 and LP#404344.",
1416 )
1417 def test_set_default_verify_paths(self) -> None:
1418 """
1419 `Context.set_default_verify_paths` causes the platform-specific CA
1420 certificate locations to be used for verification purposes.
1421 """
1422 # Testing this requires a server with a certificate signed by one
1423 # of the CAs in the platform CA location. Getting one of those
1424 # costs money. Fortunately (or unfortunately, depending on your
1425 # perspective), it's easy to think of a public server on the
1426 # internet which has such a certificate. Connecting to the network
1427 # in a unit test is bad, but it's the only way I can think of to
1428 # really test this. -exarkun
1429 return
1430 context = Context(SSLv23_METHOD)
1431 context.set_default_verify_paths()
1432 context.set_verify(
1433 VERIFY_PEER,
1434 lambda conn, cert, errno, depth, preverify_ok: bool(preverify_ok),
1435 )
1436
1437 client = socket_any_family()
1438 try:
1439 client.connect(("encrypted.google.com", 443))
1440 except gaierror:
1441 pytest.skip("cannot connect to encrypted.google.com")
1442 clientSSL = Connection(context, client)
1443 clientSSL.set_connect_state()
1444 clientSSL.set_tlsext_host_name(b"encrypted.google.com")
1445 clientSSL.do_handshake()
1446 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
1447 assert clientSSL.recv(1024)
1448
1449 def test_fallback_path_is_not_file_or_dir(self) -> None:
1450 """
1451 Test that when passed empty arrays or paths that do not exist no
1452 errors are raised.
1453 """
1454 context = Context(SSLv23_METHOD)
1455 context._fallback_default_verify_paths([], [])
1456 context._fallback_default_verify_paths(["/not/a/file"], ["/not/a/dir"])
1457
1458 def test_add_extra_chain_cert_invalid_cert(self) -> None:
1459 """
1460 `Context.add_extra_chain_cert` raises `TypeError` if called with an
1461 object which is not an instance of `X509`.
1462 """
1463 context = Context(SSLv23_METHOD)
1464 with pytest.raises(TypeError):
1465 context.add_extra_chain_cert(object()) # type: ignore[arg-type]
1466
1467 def _handshake_test(
1468 self, serverContext: Context, clientContext: Context
1469 ) -> None:
1470 """
1471 Verify that a client and server created with the given contexts can
1472 successfully handshake and communicate.
1473 """
1474 serverSocket, clientSocket = socket_pair()
1475
1476 with serverSocket, clientSocket:
1477 server = Connection(serverContext, serverSocket)
1478 server.set_accept_state()
1479
1480 client = Connection(clientContext, clientSocket)
1481 client.set_connect_state()
1482
1483 # Make them talk to each other.
1484 for _ in range(3):
1485 for s in [client, server]:
1486 try:
1487 s.do_handshake()
1488 except WantReadError:
1489 select.select([client, server], [], [])
1490
1491 def test_set_verify_callback_connection_argument(self) -> None:
1492 """
1493 The first argument passed to the verify callback is the
1494 `Connection` instance for which verification is taking place.
1495 """
1496 serverContext = Context(SSLv23_METHOD)
1497 serverContext.use_privatekey(
1498 load_privatekey(FILETYPE_PEM, root_key_pem)
1499 )
1500 serverContext.use_certificate(
1501 load_certificate(FILETYPE_PEM, root_cert_pem)
1502 )
1503 serverConnection = Connection(serverContext, None)
1504
1505 class VerifyCallback:
1506 def callback(
1507 self,
1508 connection: Connection,
1509 cert: X509,
1510 err: int,
1511 depth: int,
1512 ok: int,
1513 ) -> bool:
1514 self.connection = connection
1515 return True
1516
1517 verify = VerifyCallback()
1518 clientContext = Context(SSLv23_METHOD)
1519 clientContext.set_verify(VERIFY_PEER, verify.callback)
1520 clientConnection = Connection(clientContext, None)
1521 clientConnection.set_connect_state()
1522
1523 handshake_in_memory(clientConnection, serverConnection)
1524
1525 assert verify.connection is clientConnection
1526
1527 def test_x509_in_verify_works(self) -> None:
1528 """
1529 We had a bug where the X509 cert instantiated in the callback wrapper
1530 didn't __init__ so it was missing objects needed when calling
1531 get_subject. This test sets up a handshake where we call get_subject
1532 on the cert provided to the verify callback.
1533 """
1534 serverContext = Context(SSLv23_METHOD)
1535 serverContext.use_privatekey(
1536 load_privatekey(FILETYPE_PEM, root_key_pem)
1537 )
1538 serverContext.use_certificate(
1539 load_certificate(FILETYPE_PEM, root_cert_pem)
1540 )
1541 serverConnection = Connection(serverContext, None)
1542
1543 def verify_cb_get_subject(
1544 conn: Connection, cert: X509, errnum: int, depth: int, ok: int
1545 ) -> bool:
1546 assert cert.get_subject()
1547 return True
1548
1549 clientContext = Context(SSLv23_METHOD)
1550 clientContext.set_verify(VERIFY_PEER, verify_cb_get_subject)
1551 clientConnection = Connection(clientContext, None)
1552 clientConnection.set_connect_state()
1553
1554 handshake_in_memory(clientConnection, serverConnection)
1555
1556 def test_set_verify_callback_exception(self) -> None:
1557 """
1558 If the verify callback passed to `Context.set_verify` raises an
1559 exception, verification fails and the exception is propagated to the
1560 caller of `Connection.do_handshake`.
1561 """
1562 serverContext = Context(TLSv1_2_METHOD)
1563 serverContext.use_privatekey(
1564 load_privatekey(FILETYPE_PEM, root_key_pem)
1565 )
1566 serverContext.use_certificate(
1567 load_certificate(FILETYPE_PEM, root_cert_pem)
1568 )
1569
1570 clientContext = Context(TLSv1_2_METHOD)
1571
1572 def verify_callback(
1573 conn: Connection, cert: X509, err: int, depth: int, ok: int
1574 ) -> bool:
1575 raise Exception("silly verify failure")
1576
1577 clientContext.set_verify(VERIFY_PEER, verify_callback)
1578
1579 with pytest.raises(Exception) as exc:
1580 self._handshake_test(serverContext, clientContext)
1581
1582 assert "silly verify failure" == str(exc.value)
1583
1584 def test_set_verify_callback_reference(self) -> None:
1585 """
1586 If the verify callback passed to `Context.set_verify` is set multiple
1587 times, the pointers to the old call functions should not be dangling
1588 and trigger a segfault.
1589 """
1590 serverContext = Context(TLSv1_2_METHOD)
1591 serverContext.use_privatekey(
1592 load_privatekey(FILETYPE_PEM, root_key_pem)
1593 )
1594 serverContext.use_certificate(
1595 load_certificate(FILETYPE_PEM, root_cert_pem)
1596 )
1597
1598 clients = []
1599
1600 for i in range(5):
1601
1602 def verify_callback(*args: object) -> bool:
1603 return True
1604
1605 # Create a fresh client context for each iteration since contexts
1606 # cannot be mutated after use
1607 clientContext = Context(TLSv1_2_METHOD)
1608 clientContext.set_verify(VERIFY_PEER, verify_callback)
1609
1610 serverSocket, clientSocket = socket_pair()
1611 client = Connection(clientContext, clientSocket)
1612
1613 clients.append((serverSocket, client))
1614
1615 gc.collect()
1616
1617 # Make them talk to each other.
1618 for serverSocket, client in clients:
1619 server = Connection(serverContext, serverSocket)
1620 server.set_accept_state()
1621 client.set_connect_state()
1622
1623 for _ in range(5):
1624 for s in [client, server]:
1625 try:
1626 s.do_handshake()
1627 except WantReadError:
1628 pass
1629
1630 @pytest.mark.parametrize("mode", [SSL.VERIFY_PEER, SSL.VERIFY_NONE])
1631 def test_set_verify_default_callback(self, mode: int) -> None:
1632 """
1633 If the verify callback is omitted, the preverify value is used.
1634 """
1635 serverContext = Context(TLSv1_2_METHOD)
1636 serverContext.use_privatekey(
1637 load_privatekey(FILETYPE_PEM, root_key_pem)
1638 )
1639 serverContext.use_certificate(
1640 load_certificate(FILETYPE_PEM, root_cert_pem)
1641 )
1642
1643 clientContext = Context(TLSv1_2_METHOD)
1644 clientContext.set_verify(mode, None)
1645
1646 if mode == SSL.VERIFY_PEER:
1647 with pytest.raises(Exception) as exc:
1648 self._handshake_test(serverContext, clientContext)
1649 assert "certificate verify failed" in str(
1650 exc.value
1651 ) or "CERTIFICATE_VERIFY_FAILED" in str(exc.value)
1652 else:
1653 self._handshake_test(serverContext, clientContext)
1654
1655 def test_add_extra_chain_cert(self, tmp_path: pathlib.Path) -> None:
1656 """
1657 `Context.add_extra_chain_cert` accepts an `X509`
1658 instance to add to the certificate chain.
1659
1660 See `_create_certificate_chain` for the details of the
1661 certificate chain tested.
1662
1663 The chain is tested by starting a server with scert and connecting
1664 to it with a client which trusts cacert and requires verification to
1665 succeed.
1666 """
1667 chain = _create_certificate_chain()
1668 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1669
1670 # Dump the CA certificate to a file because that's the only way to load
1671 # it as a trusted CA in the client context.
1672 for cert, name in [
1673 (cacert, "ca.pem"),
1674 (icert, "i.pem"),
1675 (scert, "s.pem"),
1676 ]:
1677 with (tmp_path / name).open("w") as f:
1678 f.write(dump_certificate(FILETYPE_PEM, cert).decode("ascii"))
1679
1680 for key, name in [(cakey, "ca.key"), (ikey, "i.key"), (skey, "s.key")]:
1681 with (tmp_path / name).open("w") as f:
1682 f.write(dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
1683
1684 # Create the server context
1685 serverContext = Context(SSLv23_METHOD)
1686 serverContext.use_privatekey(skey)
1687 serverContext.use_certificate(scert)
1688 # The client already has cacert, we only need to give them icert.
1689 serverContext.add_extra_chain_cert(icert)
1690
1691 # Create the client
1692 clientContext = Context(SSLv23_METHOD)
1693 clientContext.set_verify(
1694 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb
1695 )
1696 clientContext.load_verify_locations(str(tmp_path / "ca.pem"))
1697
1698 # Try it out.
1699 self._handshake_test(serverContext, clientContext)
1700
1701 def _use_certificate_chain_file_test(self, certdir: str | bytes) -> None:
1702 """
1703 Verify that `Context.use_certificate_chain_file` reads a
1704 certificate chain from a specified file.
1705
1706 The chain is tested by starting a server with scert and connecting to
1707 it with a client which trusts cacert and requires verification to
1708 succeed.
1709 """
1710 [(_, cacert), (_, icert), (skey, scert)] = _create_certificate_chain()
1711
1712 makedirs(certdir)
1713
1714 chainFile: str | bytes
1715 caFile: str | bytes
1716 if isinstance(certdir, str):
1717 chainFile = os.path.join(certdir, "chain.pem")
1718 caFile = os.path.join(certdir, "ca.pem")
1719 else:
1720 chainFile = os.path.join(certdir, b"chain.pem")
1721 caFile = os.path.join(certdir, b"ca.pem")
1722
1723 # Write out the chain file.
1724 with open(chainFile, "wb") as fObj:
1725 # Most specific to least general.
1726 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1727 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1728 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
1729
1730 with open(caFile, "w") as fObj:
1731 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode("ascii"))
1732
1733 serverContext = Context(SSLv23_METHOD)
1734 serverContext.use_certificate_chain_file(chainFile)
1735 serverContext.use_privatekey(skey)
1736
1737 clientContext = Context(SSLv23_METHOD)
1738 clientContext.set_verify(
1739 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb
1740 )
1741 clientContext.load_verify_locations(caFile)
1742
1743 self._handshake_test(serverContext, clientContext)
1744
1745 def test_use_certificate_chain_file_bytes(self, tmpfile: bytes) -> None:
1746 """
1747 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1748 an instance of ``bytes``) to specify additional certificates to use to
1749 construct and verify a trust chain.
1750 """
1751 self._use_certificate_chain_file_test(
1752 tmpfile + NON_ASCII.encode(getfilesystemencoding())
1753 )
1754
1755 def test_use_certificate_chain_file_unicode(self, tmpfile: bytes) -> None:
1756 """
1757 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1758 an instance of ``unicode``) to specify additional certificates to use
1759 to construct and verify a trust chain.
1760 """
1761 self._use_certificate_chain_file_test(
1762 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
1763 )
1764
1765 def test_use_certificate_chain_file_wrong_args(self) -> None:
1766 """
1767 `Context.use_certificate_chain_file` raises `TypeError` if passed a
1768 non-byte string single argument.
1769 """
1770 context = Context(SSLv23_METHOD)
1771 with pytest.raises(TypeError):
1772 context.use_certificate_chain_file(object()) # type: ignore[arg-type]
1773
1774 def test_use_certificate_chain_file_missing_file(
1775 self, tmpfile: bytes
1776 ) -> None:
1777 """
1778 `Context.use_certificate_chain_file` raises `OpenSSL.SSL.Error` when
1779 passed a bad chain file name (for example, the name of a file which
1780 does not exist).
1781 """
1782 context = Context(SSLv23_METHOD)
1783 with pytest.raises(Error):
1784 context.use_certificate_chain_file(tmpfile)
1785
1786 def test_set_verify_mode(self) -> None:
1787 """
1788 `Context.get_verify_mode` returns the verify mode flags previously
1789 passed to `Context.set_verify`.
1790 """
1791 context = Context(SSLv23_METHOD)
1792 assert context.get_verify_mode() == 0
1793 context.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE)
1794 assert context.get_verify_mode() == (VERIFY_PEER | VERIFY_CLIENT_ONCE)
1795
1796 @pytest.mark.parametrize("mode", [None, 1.0, object(), "mode"])
1797 def test_set_verify_wrong_mode_arg(self, mode: object) -> None:
1798 """
1799 `Context.set_verify` raises `TypeError` if the first argument is
1800 not an integer.
1801 """
1802 context = Context(SSLv23_METHOD)
1803 with pytest.raises(TypeError):
1804 context.set_verify(mode=mode) # type: ignore[arg-type]
1805
1806 @pytest.mark.parametrize("callback", [1.0, "mode", ("foo", "bar")])
1807 def test_set_verify_wrong_callable_arg(self, callback: object) -> None:
1808 """
1809 `Context.set_verify` raises `TypeError` if the second argument
1810 is not callable.
1811 """
1812 context = Context(SSLv23_METHOD)
1813 with pytest.raises(TypeError):
1814 context.set_verify(mode=VERIFY_PEER, callback=callback) # type: ignore[arg-type]
1815
1816 def test_load_tmp_dh_wrong_args(self) -> None:
1817 """
1818 `Context.load_tmp_dh` raises `TypeError` if called with a
1819 non-`str` argument.
1820 """
1821 context = Context(SSLv23_METHOD)
1822 with pytest.raises(TypeError):
1823 context.load_tmp_dh(object()) # type: ignore[arg-type]
1824
1825 def test_load_tmp_dh_missing_file(self) -> None:
1826 """
1827 `Context.load_tmp_dh` raises `OpenSSL.SSL.Error` if the
1828 specified file does not exist.
1829 """
1830 context = Context(SSLv23_METHOD)
1831 with pytest.raises(Error):
1832 context.load_tmp_dh(b"hello")
1833
1834 def _load_tmp_dh_test(self, dhfilename: bytes | str) -> None:
1835 """
1836 Verify that calling ``Context.load_tmp_dh`` with the given filename
1837 does not raise an exception.
1838 """
1839 context = Context(SSLv23_METHOD)
1840 with open(dhfilename, "w") as dhfile:
1841 dhfile.write(dhparam)
1842
1843 context.load_tmp_dh(dhfilename)
1844
1845 def test_load_tmp_dh_bytes(self, tmpfile: bytes) -> None:
1846 """
1847 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
1848 specified file (given as ``bytes``).
1849 """
1850 self._load_tmp_dh_test(
1851 tmpfile + NON_ASCII.encode(getfilesystemencoding()),
1852 )
1853
1854 def test_load_tmp_dh_unicode(self, tmpfile: bytes) -> None:
1855 """
1856 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
1857 specified file (given as ``unicode``).
1858 """
1859 self._load_tmp_dh_test(
1860 tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
1861 )
1862
1863 def test_set_tmp_ecdh(self) -> None:
1864 """
1865 `Context.set_tmp_ecdh` sets the elliptic curve for Diffie-Hellman to
1866 the specified curve.
1867 """
1868 context = Context(SSLv23_METHOD)
1869 for curve in get_elliptic_curves():
1870 if curve.name.startswith("Oakley-"):
1871 # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
1872 # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
1873 # error queue on OpenSSL 1.0.2.
1874 continue
1875 # The only easily "assertable" thing is that it does not raise an
1876 # exception.
1877 with pytest.deprecated_call():
1878 context.set_tmp_ecdh(curve)
1879
1880 awslc_unsupported_curves = {
1881 "BRAINPOOLP256R1",
1882 "BRAINPOOLP384R1",
1883 "BRAINPOOLP512R1",
1884 "SECP192R1",
1885 "SECT163K1",
1886 "SECT163R2",
1887 "SECT233K1",
1888 "SECT233R1",
1889 "SECT283K1",
1890 "SECT283R1",
1891 "SECT409K1",
1892 "SECT409R1",
1893 "SECT571K1",
1894 "SECT571R1",
1895 }
1896 for name in dir(ec.EllipticCurveOID):
1897 if name.startswith("_"):
1898 continue
1899 if conftest.is_awslc and name in awslc_unsupported_curves:
1900 continue
1901 oid = getattr(ec.EllipticCurveOID, name)
1902 cryptography_curve = ec.get_curve_for_oid(oid)
1903 context.set_tmp_ecdh(cryptography_curve())
1904
1905 def test_set_session_cache_mode_wrong_args(self) -> None:
1906 """
1907 `Context.set_session_cache_mode` raises `TypeError` if called with
1908 a non-integer argument.
1909 called with other than one integer argument.
1910 """
1911 context = Context(SSLv23_METHOD)
1912 with pytest.raises(TypeError):
1913 context.set_session_cache_mode(object()) # type: ignore[arg-type]
1914
1915 def test_session_cache_mode(self) -> None:
1916 """
1917 `Context.set_session_cache_mode` specifies how sessions are cached.
1918 The setting can be retrieved via `Context.get_session_cache_mode`.
1919 """
1920 context = Context(SSLv23_METHOD)
1921 context.set_session_cache_mode(SESS_CACHE_OFF)
1922 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
1923 assert SESS_CACHE_OFF == off
1924 assert SESS_CACHE_BOTH == context.get_session_cache_mode()
1925
1926 def test_get_cert_store(self) -> None:
1927 """
1928 `Context.get_cert_store` returns a `X509Store` instance.
1929 """
1930 context = Context(SSLv23_METHOD)
1931 store = context.get_cert_store()
1932 assert isinstance(store, X509Store)
1933
1934 def test_set_tlsext_use_srtp_not_bytes(self) -> None:
1935 """
1936 `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
1937
1938 It raises a TypeError if the list of profiles is not a byte string.
1939 """
1940 context = Context(SSLv23_METHOD)
1941 with pytest.raises(TypeError):
1942 context.set_tlsext_use_srtp("SRTP_AES128_CM_SHA1_80") # type: ignore[arg-type]
1943
1944 def test_set_tlsext_use_srtp_invalid_profile(self) -> None:
1945 """
1946 `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
1947
1948 It raises an Error if the call to OpenSSL fails.
1949 """
1950 context = Context(SSLv23_METHOD)
1951 with pytest.raises(Error):
1952 context.set_tlsext_use_srtp(b"SRTP_BOGUS")
1953
1954 def test_set_tlsext_use_srtp_valid(self) -> None:
1955 """
1956 `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
1957
1958 It does not return anything.
1959 """
1960 context = Context(SSLv23_METHOD)
1961 assert context.set_tlsext_use_srtp(b"SRTP_AES128_CM_SHA1_80") is None
1962
1963
1964 class TestServerNameCallback:
1965 """
1966 Tests for `Context.set_tlsext_servername_callback` and its
1967 interaction with `Connection`.
1968 """
1969
1970 def test_old_callback_forgotten(self) -> None:
1971 """
1972 If `Context.set_tlsext_servername_callback` is used to specify
1973 a new callback, the one it replaces is dereferenced.
1974 """
1975
1976 def callback(connection: Connection) -> None: # pragma: no cover
1977 pass
1978
1979 def replacement(connection: Connection) -> None: # pragma: no cover
1980 pass
1981
1982 context = Context(SSLv23_METHOD)
1983 context.set_tlsext_servername_callback(callback)
1984
1985 tracker = ref(callback)
1986 del callback
1987
1988 context.set_tlsext_servername_callback(replacement)
1989
1990 # One run of the garbage collector happens to work on CPython. PyPy
1991 # doesn't collect the underlying object until a second run for whatever
1992 # reason. That's fine, it still demonstrates our code has properly
1993 # dropped the reference.
1994 collect()
1995 collect()
1996
1997 callback_ref = tracker()
1998 if callback_ref is not None:
1999 referrers = get_referrers(callback_ref)
2000 assert len(referrers) == 1
2001
2002 def test_no_servername(self) -> None:
2003 """
2004 When a client specifies no server name, the callback passed to
2005 `Context.set_tlsext_servername_callback` is invoked and the
2006 result of `Connection.get_servername` is `None`.
2007 """
2008 args = []
2009
2010 def servername(conn: Connection) -> None:
2011 args.append((conn, conn.get_servername()))
2012
2013 context = Context(SSLv23_METHOD)
2014 context.set_tlsext_servername_callback(servername)
2015
2016 # Lose our reference to it. The Context is responsible for keeping it
2017 # alive now.
2018 del servername
2019 collect()
2020
2021 # Necessary to actually accept the connection
2022 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2023 context.use_certificate(
2024 load_certificate(FILETYPE_PEM, server_cert_pem)
2025 )
2026
2027 # Do a little connection to trigger the logic
2028 server = Connection(context, None)
2029 server.set_accept_state()
2030
2031 client = Connection(Context(SSLv23_METHOD), None)
2032 client.set_connect_state()
2033
2034 interact_in_memory(server, client)
2035
2036 assert args == [(server, None)]
2037
2038 def test_servername(self) -> None:
2039 """
2040 When a client specifies a server name in its hello message, the
2041 callback passed to `Contexts.set_tlsext_servername_callback` is
2042 invoked and the result of `Connection.get_servername` is that
2043 server name.
2044 """
2045 args = []
2046
2047 def servername(conn: Connection) -> None:
2048 args.append((conn, conn.get_servername()))
2049
2050 context = Context(SSLv23_METHOD)
2051 context.set_tlsext_servername_callback(servername)
2052
2053 # Necessary to actually accept the connection
2054 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2055 context.use_certificate(
2056 load_certificate(FILETYPE_PEM, server_cert_pem)
2057 )
2058
2059 # Do a little connection to trigger the logic
2060 server = Connection(context, None)
2061 server.set_accept_state()
2062
2063 client = Connection(Context(SSLv23_METHOD), None)
2064 client.set_connect_state()
2065 client.set_tlsext_host_name(b"foo1.example.com")
2066
2067 interact_in_memory(server, client)
2068
2069 assert args == [(server, b"foo1.example.com")]
2070
2071 def test_servername_callback_exception(
2072 self, monkeypatch: pytest.MonkeyPatch
2073 ) -> None:
2074 """
2075 When the callback passed to `Context.set_tlsext_servername_callback`
2076 raises an exception, ``sys.excepthook`` is called with the exception
2077 and the handshake fails with an ``Error``.
2078 """
2079 exc = TypeError("server name callback failed")
2080
2081 def servername(conn: Connection) -> None:
2082 raise exc
2083
2084 excepthook_calls: list[
2085 tuple[type[BaseException], BaseException, object]
2086 ] = []
2087
2088 def custom_excepthook(
2089 exc_type: type[BaseException],
2090 exc_value: BaseException,
2091 exc_tb: object,
2092 ) -> None:
2093 excepthook_calls.append((exc_type, exc_value, exc_tb))
2094
2095 context = Context(SSLv23_METHOD)
2096 context.set_tlsext_servername_callback(servername)
2097
2098 # Necessary to actually accept the connection
2099 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2100 context.use_certificate(
2101 load_certificate(FILETYPE_PEM, server_cert_pem)
2102 )
2103
2104 # Do a little connection to trigger the logic
2105 server = Connection(context, None)
2106 server.set_accept_state()
2107
2108 client = Connection(Context(SSLv23_METHOD), None)
2109 client.set_connect_state()
2110 client.set_tlsext_host_name(b"foo1.example.com")
2111
2112 monkeypatch.setattr(sys, "excepthook", custom_excepthook)
2113 with pytest.raises(Error):
2114 interact_in_memory(server, client)
2115
2116 assert len(excepthook_calls) == 1
2117 assert excepthook_calls[0][0] is TypeError
2118 assert excepthook_calls[0][1] is exc
2119 assert excepthook_calls[0][2] is not None
2120
2121
2122 class TestApplicationLayerProtoNegotiation:
2123 """
2124 Tests for ALPN in PyOpenSSL.
2125 """
2126
2127 def test_alpn_success(self) -> None:
2128 """
2129 Clients and servers that agree on the negotiated ALPN protocol can
2130 correct establish a connection, and the agreed protocol is reported
2131 by the connections.
2132 """
2133 select_args = []
2134
2135 def select(conn: Connection, options: list[bytes]) -> bytes:
2136 select_args.append((conn, options))
2137 return b"spdy/2"
2138
2139 client_context = Context(SSLv23_METHOD)
2140 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
2141
2142 server_context = Context(SSLv23_METHOD)
2143 server_context.set_alpn_select_callback(select)
2144
2145 # Necessary to actually accept the connection
2146 server_context.use_privatekey(
2147 load_privatekey(FILETYPE_PEM, server_key_pem)
2148 )
2149 server_context.use_certificate(
2150 load_certificate(FILETYPE_PEM, server_cert_pem)
2151 )
2152
2153 # Do a little connection to trigger the logic
2154 server = Connection(server_context, None)
2155 server.set_accept_state()
2156
2157 client = Connection(client_context, None)
2158 client.set_connect_state()
2159
2160 interact_in_memory(server, client)
2161
2162 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
2163
2164 assert server.get_alpn_proto_negotiated() == b"spdy/2"
2165 assert client.get_alpn_proto_negotiated() == b"spdy/2"
2166
2167 def test_alpn_call_failure(self) -> None:
2168 """
2169 SSL_CTX_set_alpn_protos does not like to be called with an empty
2170 protocols list. Ensure that we produce a user-visible error.
2171 """
2172 context = Context(SSLv23_METHOD)
2173 with pytest.raises(ValueError):
2174 context.set_alpn_protos([])
2175
2176 def test_alpn_set_on_connection(self) -> None:
2177 """
2178 The same as test_alpn_success, but setting the ALPN protocols on
2179 the connection rather than the context.
2180 """
2181 select_args = []
2182
2183 def select(conn: Connection, options: list[bytes]) -> bytes:
2184 select_args.append((conn, options))
2185 return b"spdy/2"
2186
2187 # Setup the client context but don't set any ALPN protocols.
2188 client_context = Context(SSLv23_METHOD)
2189
2190 server_context = Context(SSLv23_METHOD)
2191 server_context.set_alpn_select_callback(select)
2192
2193 # Necessary to actually accept the connection
2194 server_context.use_privatekey(
2195 load_privatekey(FILETYPE_PEM, server_key_pem)
2196 )
2197 server_context.use_certificate(
2198 load_certificate(FILETYPE_PEM, server_cert_pem)
2199 )
2200
2201 # Do a little connection to trigger the logic
2202 server = Connection(server_context, None)
2203 server.set_accept_state()
2204
2205 # Set the ALPN protocols on the client connection.
2206 client = Connection(client_context, None)
2207 client.set_alpn_protos([b"http/1.1", b"spdy/2"])
2208 client.set_connect_state()
2209
2210 interact_in_memory(server, client)
2211
2212 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
2213
2214 assert server.get_alpn_proto_negotiated() == b"spdy/2"
2215 assert client.get_alpn_proto_negotiated() == b"spdy/2"
2216
2217 def test_alpn_server_fail(self) -> None:
2218 """
2219 When clients and servers cannot agree on what protocol to use next
2220 the TLS connection does not get established.
2221 """
2222 select_args = []
2223
2224 def select(conn: Connection, options: list[bytes]) -> bytes:
2225 select_args.append((conn, options))
2226 return b""
2227
2228 client_context = Context(SSLv23_METHOD)
2229 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
2230
2231 server_context = Context(SSLv23_METHOD)
2232 server_context.set_alpn_select_callback(select)
2233
2234 # Necessary to actually accept the connection
2235 server_context.use_privatekey(
2236 load_privatekey(FILETYPE_PEM, server_key_pem)
2237 )
2238 server_context.use_certificate(
2239 load_certificate(FILETYPE_PEM, server_cert_pem)
2240 )
2241
2242 # Do a little connection to trigger the logic
2243 server = Connection(server_context, None)
2244 server.set_accept_state()
2245
2246 client = Connection(client_context, None)
2247 client.set_connect_state()
2248
2249 # If the client doesn't return anything, the connection will fail.
2250 with pytest.raises(Error):
2251 interact_in_memory(server, client)
2252
2253 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
2254
2255 def test_alpn_no_server_overlap(self) -> None:
2256 """
2257 A server can allow a TLS handshake to complete without
2258 agreeing to an application protocol by returning
2259 ``NO_OVERLAPPING_PROTOCOLS``.
2260 """
2261 refusal_args = []
2262
2263 def refusal(
2264 conn: Connection, options: list[bytes]
2265 ) -> _NoOverlappingProtocols:
2266 refusal_args.append((conn, options))
2267 return NO_OVERLAPPING_PROTOCOLS
2268
2269 client_context = Context(SSLv23_METHOD)
2270 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
2271
2272 server_context = Context(SSLv23_METHOD)
2273 server_context.set_alpn_select_callback(refusal)
2274
2275 # Necessary to actually accept the connection
2276 server_context.use_privatekey(
2277 load_privatekey(FILETYPE_PEM, server_key_pem)
2278 )
2279 server_context.use_certificate(
2280 load_certificate(FILETYPE_PEM, server_cert_pem)
2281 )
2282
2283 # Do a little connection to trigger the logic
2284 server = Connection(server_context, None)
2285 server.set_accept_state()
2286
2287 client = Connection(client_context, None)
2288 client.set_connect_state()
2289
2290 # Do the dance.
2291 interact_in_memory(server, client)
2292
2293 assert refusal_args == [(server, [b"http/1.1", b"spdy/2"])]
2294
2295 assert client.get_alpn_proto_negotiated() == b""
2296
2297 def test_alpn_select_cb_returns_invalid_value(self) -> None:
2298 """
2299 If the ALPN selection callback returns anything other than
2300 a bytestring or ``NO_OVERLAPPING_PROTOCOLS``, a
2301 :py:exc:`TypeError` is raised.
2302 """
2303 invalid_cb_args = []
2304
2305 def invalid_cb(conn: Connection, options: list[bytes]) -> str:
2306 invalid_cb_args.append((conn, options))
2307 return "can't return unicode"
2308
2309 client_context = Context(SSLv23_METHOD)
2310 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
2311
2312 server_context = Context(SSLv23_METHOD)
2313 server_context.set_alpn_select_callback(invalid_cb) # type: ignore[arg-type]
2314
2315 # Necessary to actually accept the connection
2316 server_context.use_privatekey(
2317 load_privatekey(FILETYPE_PEM, server_key_pem)
2318 )
2319 server_context.use_certificate(
2320 load_certificate(FILETYPE_PEM, server_cert_pem)
2321 )
2322
2323 # Do a little connection to trigger the logic
2324 server = Connection(server_context, None)
2325 server.set_accept_state()
2326
2327 client = Connection(client_context, None)
2328 client.set_connect_state()
2329
2330 # Do the dance.
2331 with pytest.raises(TypeError):
2332 interact_in_memory(server, client)
2333
2334 assert invalid_cb_args == [(server, [b"http/1.1", b"spdy/2"])]
2335
2336 assert client.get_alpn_proto_negotiated() == b""
2337
2338 def test_alpn_no_server(self) -> None:
2339 """
2340 When clients and servers cannot agree on what protocol to use next
2341 because the server doesn't offer ALPN, no protocol is negotiated.
2342 """
2343 client_context = Context(SSLv23_METHOD)
2344 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
2345
2346 server_context = Context(SSLv23_METHOD)
2347
2348 # Necessary to actually accept the connection
2349 server_context.use_privatekey(
2350 load_privatekey(FILETYPE_PEM, server_key_pem)
2351 )
2352 server_context.use_certificate(
2353 load_certificate(FILETYPE_PEM, server_cert_pem)
2354 )
2355
2356 # Do a little connection to trigger the logic
2357 server = Connection(server_context, None)
2358 server.set_accept_state()
2359
2360 client = Connection(client_context, None)
2361 client.set_connect_state()
2362
2363 # Do the dance.
2364 interact_in_memory(server, client)
2365
2366 assert client.get_alpn_proto_negotiated() == b""
2367
2368 def test_alpn_callback_exception(self) -> None:
2369 """
2370 We can handle exceptions in the ALPN select callback.
2371 """
2372 select_args = []
2373
2374 def select(conn: Connection, options: list[bytes]) -> bytes:
2375 select_args.append((conn, options))
2376 raise TypeError()
2377
2378 client_context = Context(SSLv23_METHOD)
2379 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
2380
2381 server_context = Context(SSLv23_METHOD)
2382 server_context.set_alpn_select_callback(select)
2383
2384 # Necessary to actually accept the connection
2385 server_context.use_privatekey(
2386 load_privatekey(FILETYPE_PEM, server_key_pem)
2387 )
2388 server_context.use_certificate(
2389 load_certificate(FILETYPE_PEM, server_cert_pem)
2390 )
2391
2392 # Do a little connection to trigger the logic
2393 server = Connection(server_context, None)
2394 server.set_accept_state()
2395
2396 client = Connection(client_context, None)
2397 client.set_connect_state()
2398
2399 with pytest.raises(TypeError):
2400 interact_in_memory(server, client)
2401 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
2402
2403
2404 class TestSession:
2405 """
2406 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
2407 """
2408
2409 def test_construction(self) -> None:
2410 """
2411 :py:class:`Session` can be constructed with no arguments, creating
2412 a new instance of that type.
2413 """
2414 new_session = Session()
2415 assert isinstance(new_session, Session)
2416
2417
2418 @pytest.fixture(params=["context", "connection"])
2419 def ctx_or_conn(request: pytest.FixtureRequest) -> Context | Connection:
2420 ctx = Context(SSLv23_METHOD)
2421 if request.param == "context":
2422 return ctx
2423 else:
2424 return Connection(ctx, None)
2425
2426
2427 class TestContextConnection:
2428 """
2429 Unit test for methods that are exposed both by Connection and Context
2430 objects.
2431 """
2432
2433 def test_use_privatekey(self, ctx_or_conn: Context | Connection) -> None:
2434 """
2435 `use_privatekey` takes an `OpenSSL.crypto.PKey` instance.
2436 """
2437 key = PKey()
2438 key.generate_key(TYPE_RSA, 1024)
2439
2440 ctx_or_conn.use_privatekey(key)
2441 with pytest.raises(TypeError):
2442 ctx_or_conn.use_privatekey("") # type: ignore[arg-type]
2443
2444 cryptography_key = key.to_cryptography_key()
2445 assert isinstance(cryptography_key, rsa.RSAPrivateKey)
2446 ctx_or_conn.use_privatekey(cryptography_key)
2447
2448 def test_use_privatekey_wrong_key(
2449 self, ctx_or_conn: Context | Connection
2450 ) -> None:
2451 """
2452 `use_privatekey` raises `OpenSSL.SSL.Error` when passed a
2453 `OpenSSL.crypto.PKey` instance which has not been initialized.
2454 """
2455 key = PKey()
2456 key.generate_key(TYPE_RSA, 1024)
2457 ctx_or_conn.use_certificate(
2458 load_certificate(FILETYPE_PEM, root_cert_pem)
2459 )
2460 with pytest.raises(Error):
2461 ctx_or_conn.use_privatekey(key)
2462
2463 def test_use_certificate(self, ctx_or_conn: Context | Connection) -> None:
2464 """
2465 `use_certificate` sets the certificate which will be
2466 used to identify connections created using the context.
2467 """
2468 # TODO
2469 # Hard to assert anything. But we could set a privatekey then ask
2470 # OpenSSL if the cert and key agree using check_privatekey. Then as
2471 # long as check_privatekey works right we're good...
2472 ctx_or_conn.use_certificate(
2473 load_certificate(FILETYPE_PEM, root_cert_pem)
2474 )
2475 ctx_or_conn.use_certificate(
2476 load_certificate(FILETYPE_PEM, root_cert_pem).to_cryptography()
2477 )
2478
2479 def test_use_certificate_wrong_args(
2480 self, ctx_or_conn: Context | Connection
2481 ) -> None:
2482 """
2483 `use_certificate_wrong_args` raises `TypeError` when not passed
2484 exactly one `OpenSSL.crypto.X509` instance as an argument.
2485 """
2486 with pytest.raises(TypeError):
2487 ctx_or_conn.use_certificate("hello, world") # type: ignore[arg-type]
2488
2489 def test_use_certificate_uninitialized(
2490 self, ctx_or_conn: Context | Connection
2491 ) -> None:
2492 """
2493 `use_certificate` raises `OpenSSL.SSL.Error` when passed a
2494 `OpenSSL.crypto.X509` instance which has not been initialized
2495 (ie, which does not actually have any certificate data).
2496 """
2497 with pytest.raises(Error):
2498 ctx_or_conn.use_certificate(X509())
2499
2500
2501 class TestConnection:
2502 """
2503 Unit tests for `OpenSSL.SSL.Connection`.
2504 """
2505
2506 # XXX get_peer_certificate -> None
2507 # XXX sock_shutdown
2508 # XXX master_key -> TypeError
2509 # XXX server_random -> TypeError
2510 # XXX connect -> TypeError
2511 # XXX connect_ex -> TypeError
2512 # XXX set_connect_state -> TypeError
2513 # XXX set_accept_state -> TypeError
2514 # XXX do_handshake -> TypeError
2515 # XXX bio_read -> TypeError
2516 # XXX recv -> TypeError
2517 # XXX send -> TypeError
2518 # XXX bio_write -> TypeError
2519
2520 @pytest.mark.parametrize("bad_context", [object(), "context", None, 1])
2521 def test_wrong_args(self, bad_context: object) -> None:
2522 """
2523 `Connection.__init__` raises `TypeError` if called with a non-`Context`
2524 instance argument.
2525 """
2526 with pytest.raises(TypeError):
2527 Connection(bad_context) # type: ignore[arg-type]
2528
2529 @pytest.mark.parametrize("bad_bio", [object(), None, 1, [1, 2, 3]])
2530 def test_bio_write_wrong_args(self, bad_bio: object) -> None:
2531 """
2532 `Connection.bio_write` raises `TypeError` if called with a non-bytes
2533 (or text) argument.
2534 """
2535 context = Context(SSLv23_METHOD)
2536 connection = Connection(context, None)
2537 with pytest.raises(TypeError):
2538 connection.bio_write(bad_bio) # type: ignore[arg-type]
2539
2540 def test_bio_write(self) -> None:
2541 """
2542 `Connection.bio_write` does not raise if called with bytes or
2543 bytearray, warns if called with text.
2544 """
2545 context = Context(SSLv23_METHOD)
2546 connection = Connection(context, None)
2547 connection.bio_write(b"xy")
2548 connection.bio_write(bytearray(b"za"))
2549 with pytest.warns(DeprecationWarning):
2550 connection.bio_write("deprecated") # type: ignore[arg-type]
2551
2552 def test_get_context(self) -> None:
2553 """
2554 `Connection.get_context` returns the `Context` instance used to
2555 construct the `Connection` instance.
2556 """
2557 context = Context(SSLv23_METHOD)
2558 connection = Connection(context, None)
2559 assert connection.get_context() is context
2560
2561 def test_set_context_wrong_args(self) -> None:
2562 """
2563 `Connection.set_context` raises `TypeError` if called with a
2564 non-`Context` instance argument.
2565 """
2566 ctx = Context(SSLv23_METHOD)
2567 connection = Connection(ctx, None)
2568 with pytest.raises(TypeError):
2569 connection.set_context(object()) # type: ignore[arg-type]
2570 with pytest.raises(TypeError):
2571 connection.set_context("hello") # type: ignore[arg-type]
2572 with pytest.raises(TypeError):
2573 connection.set_context(1) # type: ignore[arg-type]
2574 assert ctx is connection.get_context()
2575
2576 def test_set_options_wrong_args(self) -> None:
2577 """
2578 `Connection.set_options` raises `TypeError` if called with
2579 a non-`int` argument.
2580 """
2581 context = Context(SSLv23_METHOD)
2582 connection = Connection(context, None)
2583 with pytest.raises(TypeError):
2584 connection.set_options(None) # type: ignore[arg-type]
2585
2586 def test_set_options(self) -> None:
2587 """
2588 `Connection.set_options` returns the new options value.
2589 """
2590 context = Context(SSLv23_METHOD)
2591 connection = Connection(context, None)
2592 options = connection.set_options(OP_NO_SSLv2)
2593 assert options & OP_NO_SSLv2 == OP_NO_SSLv2
2594
2595 def test_set_context(self) -> None:
2596 """
2597 `Connection.set_context` specifies a new `Context` instance to be
2598 used for the connection.
2599 """
2600 original = Context(SSLv23_METHOD)
2601 replacement = Context(SSLv23_METHOD)
2602 connection = Connection(original, None)
2603 connection.set_context(replacement)
2604 assert replacement is connection.get_context()
2605 # Lose our references to the contexts, just in case the Connection
2606 # isn't properly managing its own contributions to their reference
2607 # counts.
2608 del original, replacement
2609 collect()
2610
2611 def test_set_tlsext_host_name_wrong_args(self) -> None:
2612 """
2613 If `Connection.set_tlsext_host_name` is called with a non-byte string
2614 argument or a byte string with an embedded NUL, `TypeError` is raised.
2615 """
2616 conn = Connection(Context(SSLv23_METHOD), None)
2617 with pytest.raises(TypeError):
2618 conn.set_tlsext_host_name(object()) # type: ignore[arg-type]
2619 with pytest.raises(TypeError):
2620 conn.set_tlsext_host_name(b"with\0null")
2621
2622 with pytest.raises(TypeError):
2623 conn.set_tlsext_host_name(b"example.com".decode("ascii")) # type: ignore[arg-type]
2624
2625 def test_pending(self) -> None:
2626 """
2627 `Connection.pending` returns the number of bytes available for
2628 immediate read.
2629 """
2630 connection = Connection(Context(SSLv23_METHOD), None)
2631 assert connection.pending() == 0
2632
2633 def test_peek(self) -> None:
2634 """
2635 `Connection.recv` peeks into the connection if `socket.MSG_PEEK` is
2636 passed.
2637 """
2638 server, client = loopback()
2639 server.send(b"xy")
2640 assert client.recv(2, MSG_PEEK) == b"xy"
2641 assert client.recv(2, MSG_PEEK) == b"xy"
2642 assert client.recv(2) == b"xy"
2643
2644 def test_connect_wrong_args(self) -> None:
2645 """
2646 `Connection.connect` raises `TypeError` if called with a non-address
2647 argument.
2648 """
2649 connection = Connection(Context(SSLv23_METHOD), socket_any_family())
2650 with pytest.raises(TypeError):
2651 connection.connect(None)
2652
2653 def test_connect_refused(self) -> None:
2654 """
2655 `Connection.connect` raises `socket.error` if the underlying socket
2656 connect method raises it.
2657 """
2658 client = socket_any_family()
2659 context = Context(SSLv23_METHOD)
2660 clientSSL = Connection(context, client)
2661 # pytest.raises here doesn't work because of a bug in py.test on Python
2662 # 2.6: https://github.com/pytest-dev/pytest/issues/988
2663 try:
2664 clientSSL.connect((loopback_address(client), 1))
2665 except OSError as e:
2666 exc = e
2667 assert exc.args[0] == ECONNREFUSED
2668
2669 def test_connect(self) -> None:
2670 """
2671 `Connection.connect` establishes a connection to the specified address.
2672 """
2673 port = socket_any_family()
2674 port.bind(("", 0))
2675 port.listen(3)
2676
2677 clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
2678 clientSSL.connect((loopback_address(port), port.getsockname()[1]))
2679 # XXX An assertion? Or something?
2680
2681 def test_connect_ex(self) -> None:
2682 """
2683 If there is a connection error, `Connection.connect_ex` returns the
2684 errno instead of raising an exception.
2685 """
2686 port = socket_any_family()
2687 port.bind(("", 0))
2688 port.listen(3)
2689
2690 clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
2691 clientSSL.setblocking(False)
2692 result = clientSSL.connect_ex(port.getsockname())
2693 expected = (EINPROGRESS, EWOULDBLOCK)
2694 assert result in expected
2695
2696 def test_accept(self) -> None:
2697 """
2698 `Connection.accept` accepts a pending connection attempt and returns a
2699 tuple of a new `Connection` (the accepted client) and the address the
2700 connection originated from.
2701 """
2702 ctx = Context(SSLv23_METHOD)
2703 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2704 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2705 port = socket_any_family()
2706 portSSL = Connection(ctx, port)
2707 portSSL.bind(("", 0))
2708 portSSL.listen(3)
2709
2710 clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
2711
2712 # Calling portSSL.getsockname() here to get the server IP address
2713 # sounds great, but frequently fails on Windows.
2714 clientSSL.connect((loopback_address(port), portSSL.getsockname()[1]))
2715
2716 serverSSL, address = portSSL.accept()
2717
2718 assert isinstance(serverSSL, Connection)
2719 assert serverSSL.get_context() is ctx
2720 assert address == clientSSL.getsockname()
2721
2722 def test_shutdown_wrong_args(self) -> None:
2723 """
2724 `Connection.set_shutdown` raises `TypeError` if called with arguments
2725 other than integers.
2726 """
2727 connection = Connection(Context(SSLv23_METHOD), None)
2728 with pytest.raises(TypeError):
2729 connection.set_shutdown(None) # type: ignore[arg-type]
2730
2731 def test_shutdown(self) -> None:
2732 """
2733 `Connection.shutdown` performs an SSL-level connection shutdown.
2734 """
2735 server, client = loopback()
2736 assert not server.shutdown()
2737 assert server.get_shutdown() == SENT_SHUTDOWN
2738 with pytest.raises(ZeroReturnError):
2739 client.recv(1024)
2740 assert client.get_shutdown() == RECEIVED_SHUTDOWN
2741 client.shutdown()
2742 assert client.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
2743 with pytest.raises(ZeroReturnError):
2744 server.recv(1024)
2745 assert server.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
2746
2747 def test_shutdown_closed(self) -> None:
2748 """
2749 If the underlying socket is closed, `Connection.shutdown` propagates
2750 the write error from the low level write call.
2751 """
2752 server, _ = loopback()
2753 server.sock_shutdown(2)
2754 with pytest.raises(SysCallError) as exc:
2755 server.shutdown()
2756 if platform == "win32":
2757 assert exc.value.args[0] == ESHUTDOWN
2758 else:
2759 assert exc.value.args[0] == EPIPE
2760
2761 def test_shutdown_truncated(self) -> None:
2762 """
2763 If the underlying connection is truncated, `Connection.shutdown`
2764 raises an `Error`.
2765 """
2766 server_ctx = Context(SSLv23_METHOD)
2767 client_ctx = Context(SSLv23_METHOD)
2768 server_ctx.use_privatekey(
2769 load_privatekey(FILETYPE_PEM, server_key_pem)
2770 )
2771 server_ctx.use_certificate(
2772 load_certificate(FILETYPE_PEM, server_cert_pem)
2773 )
2774 server = Connection(server_ctx, None)
2775 client = Connection(client_ctx, None)
2776 handshake_in_memory(client, server)
2777 assert not server.shutdown()
2778 with pytest.raises(WantReadError):
2779 server.shutdown()
2780 server.bio_shutdown()
2781 with pytest.raises(Error):
2782 server.shutdown()
2783
2784 def test_set_shutdown(self) -> None:
2785 """
2786 `Connection.set_shutdown` sets the state of the SSL connection
2787 shutdown process.
2788 """
2789 connection = Connection(Context(SSLv23_METHOD), socket_any_family())
2790 connection.set_shutdown(RECEIVED_SHUTDOWN)
2791 assert connection.get_shutdown() == RECEIVED_SHUTDOWN
2792
2793 def test_state_string(self) -> None:
2794 """
2795 `Connection.state_string` verbosely describes the current state of
2796 the `Connection`.
2797 """
2798 server, client = socket_pair()
2799 tls_server = loopback_server_factory(server)
2800 tls_client = loopback_client_factory(client)
2801
2802 assert tls_server.get_state_string() in [
2803 b"before/accept initialization",
2804 b"before SSL initialization",
2805 b"TLS server start_accept",
2806 ]
2807 assert tls_client.get_state_string() in [
2808 b"before/connect initialization",
2809 b"before SSL initialization",
2810 b"TLS client start_connect",
2811 ]
2812
2813 def test_app_data(self) -> None:
2814 """
2815 Any object can be set as app data by passing it to
2816 `Connection.set_app_data` and later retrieved with
2817 `Connection.get_app_data`.
2818 """
2819 conn = Connection(Context(SSLv23_METHOD), None)
2820 assert None is conn.get_app_data()
2821 app_data = object()
2822 conn.set_app_data(app_data)
2823 assert conn.get_app_data() is app_data
2824
2825 def test_makefile(self) -> None:
2826 """
2827 `Connection.makefile` is not implemented and calling that
2828 method raises `NotImplementedError`.
2829 """
2830 conn = Connection(Context(SSLv23_METHOD), None)
2831 with pytest.raises(NotImplementedError):
2832 conn.makefile()
2833
2834 def test_get_certificate(self) -> None:
2835 """
2836 `Connection.get_certificate` returns the local certificate.
2837 """
2838 [_, _, (_, scert)] = _create_certificate_chain()
2839
2840 context = Context(SSLv23_METHOD)
2841 context.use_certificate(scert)
2842 client = Connection(context, None)
2843 cert = client.get_certificate()
2844 assert cert is not None
2845 assert "Server Certificate" == cert.get_subject().CN
2846
2847 cryptography_cert = client.get_certificate(as_cryptography=True)
2848 assert cryptography_cert is not None
2849 assert (
2850 cryptography_cert.subject.rfc4514_string()
2851 == "CN=Server Certificate"
2852 )
2853
2854 def test_get_certificate_none(self) -> None:
2855 """
2856 `Connection.get_certificate` returns the local certificate.
2857
2858 If there is no certificate, it returns None.
2859 """
2860 context = Context(SSLv23_METHOD)
2861 client = Connection(context, None)
2862 cert = client.get_certificate()
2863 assert cert is None
2864
2865 def test_get_peer_cert_chain(self) -> None:
2866 """
2867 `Connection.get_peer_cert_chain` returns a list of certificates
2868 which the connected server returned for the certification verification.
2869 """
2870 [(_, cacert), (_, icert), (skey, scert)] = _create_certificate_chain()
2871
2872 serverContext = Context(SSLv23_METHOD)
2873 serverContext.use_privatekey(skey)
2874 serverContext.use_certificate(scert)
2875 serverContext.add_extra_chain_cert(icert)
2876 serverContext.add_extra_chain_cert(cacert.to_cryptography())
2877 server = Connection(serverContext, None)
2878 server.set_accept_state()
2879
2880 # Create the client
2881 clientContext = Context(SSLv23_METHOD)
2882 clientContext.set_verify(VERIFY_NONE, verify_cb)
2883 client = Connection(clientContext, None)
2884 client.set_connect_state()
2885
2886 interact_in_memory(client, server)
2887
2888 chain = client.get_peer_cert_chain()
2889 assert chain is not None
2890 assert len(chain) == 3
2891 assert "Server Certificate" == chain[0].get_subject().CN
2892 assert "Intermediate Certificate" == chain[1].get_subject().CN
2893 assert "Authority Certificate" == chain[2].get_subject().CN
2894
2895 cryptography_chain = client.get_peer_cert_chain(as_cryptography=True)
2896 assert cryptography_chain is not None
2897 assert len(cryptography_chain) == 3
2898 assert (
2899 cryptography_chain[0].subject.rfc4514_string()
2900 == "CN=Server Certificate"
2901 )
2902 assert (
2903 cryptography_chain[1].subject.rfc4514_string()
2904 == "CN=Intermediate Certificate"
2905 )
2906 assert (
2907 cryptography_chain[2].subject.rfc4514_string()
2908 == "CN=Authority Certificate"
2909 )
2910
2911 def test_get_peer_cert_chain_none(self) -> None:
2912 """
2913 `Connection.get_peer_cert_chain` returns `None` if the peer sends
2914 no certificate chain.
2915 """
2916 ctx = Context(SSLv23_METHOD)
2917 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2918 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2919 server = Connection(ctx, None)
2920 server.set_accept_state()
2921 client = Connection(Context(SSLv23_METHOD), None)
2922 client.set_connect_state()
2923 interact_in_memory(client, server)
2924 assert None is server.get_peer_cert_chain()
2925
2926 def test_get_verified_chain(self) -> None:
2927 """
2928 `Connection.get_verified_chain` returns a list of certificates
2929 which the connected server returned for the certification verification.
2930 """
2931 [(_, cacert), (_, icert), (skey, scert)] = _create_certificate_chain()
2932
2933 serverContext = Context(SSLv23_METHOD)
2934 serverContext.use_privatekey(skey)
2935 serverContext.use_certificate(scert)
2936 serverContext.add_extra_chain_cert(icert.to_cryptography())
2937 serverContext.add_extra_chain_cert(cacert)
2938 server = Connection(serverContext, None)
2939 server.set_accept_state()
2940
2941 # Create the client
2942 clientContext = Context(SSLv23_METHOD)
2943 # cacert is self-signed so the client must trust it for verification
2944 # to succeed.
2945 cert_store = clientContext.get_cert_store()
2946 assert cert_store is not None
2947 cert_store.add_cert(cacert)
2948 clientContext.set_verify(VERIFY_PEER, verify_cb)
2949 client = Connection(clientContext, None)
2950 client.set_connect_state()
2951
2952 interact_in_memory(client, server)
2953
2954 chain = client.get_verified_chain()
2955 assert chain is not None
2956 assert len(chain) == 3
2957 assert "Server Certificate" == chain[0].get_subject().CN
2958 assert "Intermediate Certificate" == chain[1].get_subject().CN
2959 assert "Authority Certificate" == chain[2].get_subject().CN
2960
2961 cryptography_chain = client.get_verified_chain(as_cryptography=True)
2962 assert cryptography_chain is not None
2963 assert len(cryptography_chain) == 3
2964 assert (
2965 cryptography_chain[0].subject.rfc4514_string()
2966 == "CN=Server Certificate"
2967 )
2968 assert (
2969 cryptography_chain[1].subject.rfc4514_string()
2970 == "CN=Intermediate Certificate"
2971 )
2972 assert (
2973 cryptography_chain[2].subject.rfc4514_string()
2974 == "CN=Authority Certificate"
2975 )
2976
2977 def test_get_verified_chain_none(self) -> None:
2978 """
2979 `Connection.get_verified_chain` returns `None` if the peer sends
2980 no certificate chain.
2981 """
2982 ctx = Context(SSLv23_METHOD)
2983 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2984 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2985 server = Connection(ctx, None)
2986 server.set_accept_state()
2987 client = Connection(Context(SSLv23_METHOD), None)
2988 client.set_connect_state()
2989 interact_in_memory(client, server)
2990 assert None is server.get_verified_chain()
2991
2992 def test_get_verified_chain_unconnected(self) -> None:
2993 """
2994 `Connection.get_verified_chain` returns `None` when used with an object
2995 which has not been connected.
2996 """
2997 ctx = Context(SSLv23_METHOD)
2998 server = Connection(ctx, None)
2999 assert None is server.get_verified_chain()
3000
3001 def test_set_verify_overrides_context(self) -> None:
3002 context = Context(SSLv23_METHOD)
3003 context.set_verify(VERIFY_PEER)
3004 conn = Connection(context, None)
3005 conn.set_verify(VERIFY_NONE)
3006
3007 assert context.get_verify_mode() == VERIFY_PEER
3008 assert conn.get_verify_mode() == VERIFY_NONE
3009
3010 with pytest.raises(TypeError):
3011 conn.set_verify(None) # type: ignore[arg-type]
3012
3013 with pytest.raises(TypeError):
3014 conn.set_verify(VERIFY_PEER, "not a callable") # type: ignore[arg-type]
3015
3016 def test_set_verify_callback_reference(self) -> None:
3017 """
3018 The callback for certificate verification should only be forgotten if
3019 the context and all connections created by it do not use it anymore.
3020 """
3021
3022 def callback(
3023 conn: Connection, cert: X509, errnum: int, depth: int, ok: int
3024 ) -> bool: # pragma: no cover
3025 return bool(ok)
3026
3027 tracker = ref(callback)
3028
3029 context = Context(SSLv23_METHOD)
3030 context.set_verify(VERIFY_PEER, callback)
3031 del callback
3032
3033 conn = Connection(context, None)
3034
3035 collect()
3036 collect()
3037 assert tracker()
3038
3039 # Setting a new callback on the connection should maintain the original
3040 # context callback reference
3041 conn.set_verify(
3042 VERIFY_PEER, lambda conn, cert, errnum, depth, ok: bool(ok)
3043 )
3044 collect()
3045 collect()
3046
3047 # The callback should still be referenced - check that it exists
3048 callback_ref = tracker()
3049 assert callback_ref is not None
3050
3051 def test_get_session_unconnected(self) -> None:
3052 """
3053 `Connection.get_session` returns `None` when used with an object
3054 which has not been connected.
3055 """
3056 ctx = Context(SSLv23_METHOD)
3057 server = Connection(ctx, None)
3058 session = server.get_session()
3059 assert None is session
3060
3061 def test_server_get_session(self) -> None:
3062 """
3063 On the server side of a connection, `Connection.get_session` returns a
3064 `Session` instance representing the SSL session for that connection.
3065 """
3066 server, _ = loopback()
3067 session = server.get_session()
3068 assert isinstance(session, Session)
3069
3070 def test_client_get_session(self) -> None:
3071 """
3072 On the client side of a connection, `Connection.get_session`
3073 returns a `Session` instance representing the SSL session for
3074 that connection.
3075 """
3076 _, client = loopback()
3077 session = client.get_session()
3078 assert isinstance(session, Session)
3079
3080 def test_set_session_wrong_args(self) -> None:
3081 """
3082 `Connection.set_session` raises `TypeError` if called with an object
3083 that is not an instance of `Session`.
3084 """
3085 ctx = Context(SSLv23_METHOD)
3086 connection = Connection(ctx, None)
3087 with pytest.raises(TypeError):
3088 connection.set_session(123) # type: ignore[arg-type]
3089 with pytest.raises(TypeError):
3090 connection.set_session("hello") # type: ignore[arg-type]
3091 with pytest.raises(TypeError):
3092 connection.set_session(object()) # type: ignore[arg-type]
3093
3094 def test_client_set_session(self) -> None:
3095 """
3096 `Connection.set_session`, when used prior to a connection being
3097 established, accepts a `Session` instance and causes an attempt to
3098 re-use the session it represents when the SSL handshake is performed.
3099 """
3100 key = load_privatekey(FILETYPE_PEM, server_key_pem)
3101 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
3102 ctx = Context(TLSv1_2_METHOD)
3103 ctx.use_privatekey(key)
3104 ctx.use_certificate(cert)
3105 ctx.set_session_id(b"unity-test")
3106
3107 def makeServer(socket: socket) -> Connection:
3108 server = Connection(ctx, socket)
3109 server.set_accept_state()
3110 return server
3111
3112 clientCtx = Context(SSLv23_METHOD)
3113
3114 def makeOriginalClient(socket: socket) -> Connection:
3115 client = Connection(clientCtx, socket)
3116 client.set_connect_state()
3117 return client
3118
3119 originalServer, originalClient = loopback(
3120 server_factory=makeServer, client_factory=makeOriginalClient
3121 )
3122 originalSession = originalClient.get_session()
3123 assert originalSession is not None
3124
3125 def makeClient(socket: socket) -> Connection:
3126 client = Connection(clientCtx, socket)
3127 client.set_connect_state()
3128 client.set_session(originalSession)
3129 return client
3130
3131 resumedServer, _ = loopback(
3132 server_factory=makeServer, client_factory=makeClient
3133 )
3134
3135 # This is a proxy: in general, we have no access to any unique
3136 # identifier for the session (new enough versions of OpenSSL expose
3137 # a hash which could be usable, but "new enough" is very, very new).
3138 # Instead, exploit the fact that the master key is re-used if the
3139 # session is re-used. As long as the master key for the two
3140 # connections is the same, the session was re-used!
3141 assert originalServer.master_key() == resumedServer.master_key()
3142
3143 def test_set_session_wrong_context(self) -> None:
3144 """
3145 If `Connection.set_session` is passed a `Session` instance that was
3146 created by a `Connection` using a different `Context` than the
3147 `Connection` is using, a `ValueError` is raised.
3148 """
3149 key = load_privatekey(FILETYPE_PEM, server_key_pem)
3150 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
3151 ctx = Context(TLSv1_2_METHOD)
3152 ctx.use_privatekey(key)
3153 ctx.use_certificate(cert)
3154 ctx.set_session_id(b"unity-test")
3155
3156 def makeServer(socket: socket) -> Connection:
3157 server = Connection(ctx, socket)
3158 server.set_accept_state()
3159 return server
3160
3161 _, originalClient = loopback(server_factory=makeServer)
3162 originalSession = originalClient.get_session()
3163 assert originalSession is not None
3164
3165 # Intentionally use a different Context here.
3166 client = Connection(Context(SSLv23_METHOD), None)
3167 client.set_connect_state()
3168 with pytest.raises(ValueError):
3169 client.set_session(originalSession)
3170
3171 def test_wantWriteError(self) -> None:
3172 """
3173 `Connection` methods which generate output raise
3174 `OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
3175 fail indicating a should-write state.
3176 """
3177 # Use Unix domain sockets rather than TCP loopback. On macOS,
3178 # TCP loopback aggressively auto-tunes buffer sizes and drains
3179 # the send buffer into the peer's receive buffer nearly
3180 # instantly, so the send buffer won't stay full long enough
3181 # for do_handshake() to observe it.
3182 client_socket, peer = socketpair()
3183 client_socket.setblocking(False)
3184 peer.setblocking(False)
3185 # Fill up the client's send buffer so Connection won't be able to write
3186 # anything. Start by sending larger chunks (Windows Socket I/O is slow)
3187 # and continue by writing a single byte at a time so we can be sure we
3188 # completely fill the buffer. Even though the socket API is allowed to
3189 # signal a short write via its return value it seems this doesn't
3190 # always happen on all platforms (FreeBSD and OS X particular) for the
3191 # very last bit of available buffer space.
3192 for msg in [b"x" * 65536, b"x"]:
3193 for i in range(1024 * 1024 * 64):
3194 try:
3195 client_socket.send(msg)
3196 except OSError as e:
3197 if e.errno == EWOULDBLOCK:
3198 break
3199 raise # pragma: no cover
3200 else: # pragma: no cover
3201 pytest.fail(
3202 "Failed to fill socket buffer, cannot test BIO want write"
3203 )
3204
3205 ctx = Context(SSLv23_METHOD)
3206 conn = Connection(ctx, client_socket)
3207 # Client's speak first, so make it an SSL client
3208 conn.set_connect_state()
3209 with pytest.raises(WantWriteError):
3210 conn.do_handshake()
3211
3212 # XXX want_read
3213
3214 def _attempt_want_write_error(
3215 self, client: Connection, buffer_size: int
3216 ) -> bytes:
3217 """
3218 Deliberately attempts to send application data
3219 over SSL to trigger WantWriteError. The send may need
3220 to be repeated many times depending on the socket and
3221 network buffer sizes allocated by the environment.
3222 Returns the message that triggered the error so that
3223 the buffer for the message is not immediately reclaimed.
3224 """
3225 initial_want_write_triggered = False
3226 max_num_of_attempts = 100000
3227
3228 for i in range(max_num_of_attempts):
3229 msg = b"Y" * buffer_size
3230 try:
3231 client.send(msg)
3232 except SSL.WantWriteError:
3233 initial_want_write_triggered = True
3234 break # Exit loop as desired error was triggered
3235
3236 assert initial_want_write_triggered, (
3237 f"Could not induce WantWriteError within {i + 1} attempts"
3238 )
3239 return msg
3240
3241 def _drain_server_buffers(self, server: Connection) -> None:
3242 """Reads from server SSL and raw sockets to drain any pending data."""
3243 total_ssl_read = 0
3244 consecutive_empty_ssl_reads = 0
3245
3246 while total_ssl_read < 1024 * 1024:
3247 try:
3248 data = server.recv(65536)
3249 # if serverbuffer is empty the call should
3250 # raise WantReadError not return None
3251 assert data is not None, "SSL peer closed or empty data"
3252 total_ssl_read += len(data)
3253 # Reset counter on successful read
3254 consecutive_empty_ssl_reads = 0
3255 except SSL.WantReadError:
3256 consecutive_empty_ssl_reads += 1
3257 if consecutive_empty_ssl_reads >= 10:
3258 # "No more SSL application data available after
3259 # consecutive_empty_ssl_readss
3260 return
3261 # Small delay to allow time for clearing buffers
3262 time.sleep(0.01)
3263
3264 def _perform_moving_buffer_test(
3265 self, client: Connection, buffer_size: int, want_bad_retry: bool
3266 ) -> bool:
3267 """
3268 Attempts a retry write with a moving buffer and checks for
3269 'bad write retry' error.
3270 Returns True if 'bad write retry' occurs, False otherwise.
3271 """
3272 # Attempt retry with different buffer but same size
3273 msg2 = b"Z" * buffer_size
3274 try:
3275 bytes_written = client.send(msg2)
3276 assert not want_bad_retry, (
3277 "_perform_moving_buffer_test() failed as retry succeeded "
3278 f"unexpectedly with {bytes_written} bytes written."
3279 )
3280 return False # Retry succeeded
3281 except SSL.Error as e:
3282 reason = get_ssl_error_reason(e)
3283 assert reason in (
3284 "bad write retry",
3285 "BAD_WRITE_RETRY",
3286 ), f"Retry failed with unexpected SSL error: {e!r}({reason})."
3287 return True # Bad write retry
3288
3289 def _shutdown_connections(
3290 self,
3291 client: Connection,
3292 server: Connection,
3293 ) -> None:
3294 """Helper to safely shut down SSL connections and close sockets."""
3295 if client:
3296 with contextlib.suppress(SSL.Error):
3297 # When closing connections in the test teardown stage,
3298 # we don't care about possible TLS-level problems as the test
3299 # was specifically emulating corner case situations
3300 # pre-shutdown. We just attempt releasing resources
3301 # if possible and disregard any possibly related
3302 # problems that may occur at this point.
3303 client.shutdown()
3304 if server:
3305 with contextlib.suppress(SSL.Error):
3306 server.shutdown()
3307
3308 @pytest.fixture
3309 def ssl_connection_setup(
3310 self, request: pytest.FixtureRequest
3311 ) -> typing.Generator[
3312 tuple[Connection, Connection, int, bool],
3313 None,
3314 None,
3315 ]:
3316 """
3317 Sets up a non-blocking SSL connection for testing
3318 bad_write_retry errors.
3319 Modeflag allows the caller to turn off
3320 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER which is normally
3321 on by default.
3322 """
3323 want_bad_retry = request.param.get("want_bad_retry")
3324 request_buffer_size = request.param.get("request_buffer_size")
3325 modeflag = request.param.get("modeflag")
3326
3327 client, server, sndbuf, rcvbuf = create_ssl_nonblocking_connection(
3328 modeflag, request_buffer_size
3329 )
3330 # Use a buffer size that is half the size
3331 # of the allocated socket buffers
3332 buffer_size = min(sndbuf, rcvbuf) // 2
3333
3334 # Yield the resources needed by the test
3335 yield (
3336 client,
3337 server,
3338 buffer_size,
3339 want_bad_retry,
3340 )
3341
3342 # Teardown: Clean up the connections after the test finishes
3343 self._shutdown_connections(client, server)
3344
3345 @pytest.mark.parametrize(
3346 "ssl_connection_setup",
3347 [
3348 {
3349 "request_buffer_size": 65536,
3350 "modeflag": _lib.SSL_MODE_ENABLE_PARTIAL_WRITE,
3351 "want_bad_retry": True,
3352 },
3353 {
3354 "request_buffer_size": 65536,
3355 "modeflag": None,
3356 "want_bad_retry": False,
3357 },
3358 ],
3359 indirect=True,
3360 )
3361 def test_moving_buffer_behavior(
3362 self,
3363 ssl_connection_setup: tuple[Connection, Connection, int, bool],
3364 ) -> None:
3365 """Tests for possible "bad write retry" errors over an SSL connection.
3366 If an SSL connection partially processes some data,
3367 and then hits an `OpenSSL.SSL.WantWriteError`,
3368 the connection may expect a retry. When PyOpenSSL creates
3369 a new connection object, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is
3370 applied by default. This mode allows for data to be sent from a
3371 different buffer location, something that may happen if Python moves a
3372 mutable object such as a bytearray as part of its memory management.
3373 If the mode is turned off, OpenSSL will reject the resend with
3374 "bad_write_retry" error.
3375 """
3376 (
3377 client,
3378 server,
3379 buffer_size,
3380 want_bad_retry,
3381 ) = ssl_connection_setup
3382
3383 _ = self._attempt_want_write_error(client, buffer_size)
3384 self._drain_server_buffers(server)
3385
3386 # Perform the test and get the result
3387 result = self._perform_moving_buffer_test(
3388 client, buffer_size, want_bad_retry
3389 )
3390
3391 # Assert that the result matches the expected outcome from the fixture
3392 assert result == want_bad_retry
3393
3394 def test_get_finished_before_connect(self) -> None:
3395 """
3396 `Connection.get_finished` returns `None` before TLS handshake
3397 is completed.
3398 """
3399 ctx = Context(SSLv23_METHOD)
3400 connection = Connection(ctx, None)
3401 assert connection.get_finished() is None
3402
3403 def test_get_peer_finished_before_connect(self) -> None:
3404 """
3405 `Connection.get_peer_finished` returns `None` before TLS handshake
3406 is completed.
3407 """
3408 ctx = Context(SSLv23_METHOD)
3409 connection = Connection(ctx, None)
3410 assert connection.get_peer_finished() is None
3411
3412 def test_get_finished(self) -> None:
3413 """
3414 `Connection.get_finished` method returns the TLS Finished message send
3415 from client, or server. Finished messages are send during
3416 TLS handshake.
3417 """
3418 server, _ = loopback()
3419
3420 finished = server.get_finished()
3421 assert finished is not None
3422 assert len(finished) > 0
3423
3424 def test_get_peer_finished(self) -> None:
3425 """
3426 `Connection.get_peer_finished` method returns the TLS Finished
3427 message received from client, or server. Finished messages are send
3428 during TLS handshake.
3429 """
3430 server, _ = loopback()
3431
3432 finished = server.get_peer_finished()
3433 assert finished is not None
3434 assert len(finished) > 0
3435
3436 def test_tls_finished_message_symmetry(self) -> None:
3437 """
3438 The TLS Finished message send by server must be the TLS Finished
3439 message received by client.
3440
3441 The TLS Finished message send by client must be the TLS Finished
3442 message received by server.
3443 """
3444 server, client = loopback()
3445
3446 assert server.get_finished() == client.get_peer_finished()
3447 assert client.get_finished() == server.get_peer_finished()
3448
3449 def test_get_cipher_name_before_connect(self) -> None:
3450 """
3451 `Connection.get_cipher_name` returns `None` if no connection
3452 has been established.
3453 """
3454 ctx = Context(SSLv23_METHOD)
3455 conn = Connection(ctx, None)
3456 assert conn.get_cipher_name() is None
3457
3458 def test_get_cipher_name(self) -> None:
3459 """
3460 `Connection.get_cipher_name` returns a `unicode` string giving the
3461 name of the currently used cipher.
3462 """
3463 server, client = loopback()
3464 server_cipher_name, client_cipher_name = (
3465 server.get_cipher_name(),
3466 client.get_cipher_name(),
3467 )
3468
3469 assert isinstance(server_cipher_name, str)
3470 assert isinstance(client_cipher_name, str)
3471
3472 assert server_cipher_name == client_cipher_name
3473
3474 def test_get_cipher_version_before_connect(self) -> None:
3475 """
3476 `Connection.get_cipher_version` returns `None` if no connection
3477 has been established.
3478 """
3479 ctx = Context(SSLv23_METHOD)
3480 conn = Connection(ctx, None)
3481 assert conn.get_cipher_version() is None
3482
3483 def test_get_cipher_version(self) -> None:
3484 """
3485 `Connection.get_cipher_version` returns a `unicode` string giving
3486 the protocol name of the currently used cipher.
3487 """
3488 server, client = loopback()
3489 server_cipher_version, client_cipher_version = (
3490 server.get_cipher_version(),
3491 client.get_cipher_version(),
3492 )
3493
3494 assert isinstance(server_cipher_version, str)
3495 assert isinstance(client_cipher_version, str)
3496
3497 assert server_cipher_version == client_cipher_version
3498
3499 def test_get_cipher_bits_before_connect(self) -> None:
3500 """
3501 `Connection.get_cipher_bits` returns `None` if no connection has
3502 been established.
3503 """
3504 ctx = Context(SSLv23_METHOD)
3505 conn = Connection(ctx, None)
3506 assert conn.get_cipher_bits() is None
3507
3508 def test_get_cipher_bits(self) -> None:
3509 """
3510 `Connection.get_cipher_bits` returns the number of secret bits
3511 of the currently used cipher.
3512 """
3513 server, client = loopback()
3514 server_cipher_bits, client_cipher_bits = (
3515 server.get_cipher_bits(),
3516 client.get_cipher_bits(),
3517 )
3518
3519 assert isinstance(server_cipher_bits, int)
3520 assert isinstance(client_cipher_bits, int)
3521
3522 assert server_cipher_bits == client_cipher_bits
3523
3524 def test_get_protocol_version_name(self) -> None:
3525 """
3526 `Connection.get_protocol_version_name()` returns a string giving the
3527 protocol version of the current connection.
3528 """
3529 server, client = loopback()
3530 client_protocol_version_name = client.get_protocol_version_name()
3531 server_protocol_version_name = server.get_protocol_version_name()
3532
3533 assert isinstance(server_protocol_version_name, str)
3534 assert isinstance(client_protocol_version_name, str)
3535
3536 assert server_protocol_version_name == client_protocol_version_name
3537
3538 def test_get_protocol_version(self) -> None:
3539 """
3540 `Connection.get_protocol_version()` returns an integer
3541 giving the protocol version of the current connection.
3542 """
3543 server, client = loopback()
3544 client_protocol_version = client.get_protocol_version()
3545 server_protocol_version = server.get_protocol_version()
3546
3547 assert isinstance(server_protocol_version, int)
3548 assert isinstance(client_protocol_version, int)
3549
3550 assert server_protocol_version == client_protocol_version
3551
3552 @pytest.mark.skipif(
3553 not getattr(_lib, "Cryptography_HAS_SSL_GET0_GROUP_NAME", None),
3554 reason="SSL_get0_group_name unavailable",
3555 )
3556 def test_get_group_name_before_connect(self) -> None:
3557 """
3558 `Connection.get_group_name()` returns `None` if no connection
3559 has been established.
3560 """
3561 ctx = Context(TLS_METHOD)
3562 conn = Connection(ctx, None)
3563 assert conn.get_group_name() is None
3564
3565 @pytest.mark.skipif(
3566 not getattr(_lib, "Cryptography_HAS_SSL_GET0_GROUP_NAME", None),
3567 reason="SSL_get0_group_name unavailable",
3568 )
3569 def test_group_name_null_case(
3570 self, monkeypatch: pytest.MonkeyPatch
3571 ) -> None:
3572 """
3573 `Connection.get_group_name()` returns `None` when SSL_get0_group_name
3574 returns NULL.
3575 """
3576 monkeypatch.setattr(_lib, "SSL_get0_group_name", lambda ssl: _ffi.NULL)
3577
3578 server, client = loopback()
3579 assert server.get_group_name() is None
3580 assert client.get_group_name() is None
3581
3582 @pytest.mark.skipif(
3583 not getattr(_lib, "Cryptography_HAS_SSL_GET0_GROUP_NAME", None),
3584 reason="SSL_get0_group_name unavailable",
3585 )
3586 def test_get_group_name(self) -> None:
3587 """
3588 `Connection.get_group_name()` returns a string giving the
3589 name of the connection's negotiated key exchange group.
3590 """
3591 server, client = loopback()
3592 server_group_name = server.get_group_name()
3593 client_group_name = client.get_group_name()
3594
3595 assert isinstance(server_group_name, str)
3596 assert isinstance(client_group_name, str)
3597
3598 assert server_group_name == client_group_name
3599
3600 def test_wantReadError(self) -> None:
3601 """
3602 `Connection.bio_read` raises `OpenSSL.SSL.WantReadError` if there are
3603 no bytes available to be read from the BIO.
3604 """
3605 ctx = Context(SSLv23_METHOD)
3606 conn = Connection(ctx, None)
3607 with pytest.raises(WantReadError):
3608 conn.bio_read(1024)
3609
3610 @pytest.mark.parametrize("bufsize", [1.0, None, object(), "bufsize"])
3611 def test_bio_read_wrong_args(self, bufsize: object) -> None:
3612 """
3613 `Connection.bio_read` raises `TypeError` if passed a non-integer
3614 argument.
3615 """
3616 ctx = Context(SSLv23_METHOD)
3617 conn = Connection(ctx, None)
3618 with pytest.raises(TypeError):
3619 conn.bio_read(bufsize) # type: ignore[arg-type]
3620
3621 def test_buffer_size(self) -> None:
3622 """
3623 `Connection.bio_read` accepts an integer giving the maximum number
3624 of bytes to read and return.
3625 """
3626 ctx = Context(SSLv23_METHOD)
3627 conn = Connection(ctx, None)
3628 conn.set_connect_state()
3629 try:
3630 conn.do_handshake()
3631 except WantReadError:
3632 pass
3633 data = conn.bio_read(2)
3634 assert 2 == len(data)
3635
3636 def test_connection_set_info_callback(self) -> None:
3637 (server_sock, client_sock) = socket_pair()
3638
3639 context = Context(SSLv23_METHOD)
3640 context.use_certificate(load_certificate(FILETYPE_PEM, root_cert_pem))
3641 context.use_privatekey(load_privatekey(FILETYPE_PEM, root_key_pem))
3642 server = Connection(context, server_sock)
3643 server.set_accept_state()
3644
3645 client = Connection(Context(SSLv23_METHOD), client_sock)
3646 client.set_connect_state()
3647
3648 called = []
3649
3650 def info(conn: Connection, where: int, ret: int) -> None:
3651 assert conn is client
3652 called.append(where)
3653
3654 client.set_info_callback(info)
3655
3656 handshake(client, server)
3657
3658 # Verify that the callback was actually called during handshake
3659 assert len(called) > 0
3660 assert SSL_CB_HANDSHAKE_START in called
3661 assert SSL_CB_HANDSHAKE_DONE in called
3662
3663
3664 class TestConnectionGetCipherList:
3665 """
3666 Tests for `Connection.get_cipher_list`.
3667 """
3668
3669 def test_result(self) -> None:
3670 """
3671 `Connection.get_cipher_list` returns a list of `bytes` giving the
3672 names of the ciphers which might be used.
3673 """
3674 connection = Connection(Context(SSLv23_METHOD), None)
3675 ciphers = connection.get_cipher_list()
3676 assert isinstance(ciphers, list)
3677 for cipher in ciphers:
3678 assert isinstance(cipher, str)
3679
3680
3681 class VeryLarge(bytes):
3682 """
3683 Mock object so that we don't have to allocate 2**31 bytes
3684 """
3685
3686 def __len__(self) -> int:
3687 return 2**31
3688
3689
3690 class TestConnectionSend:
3691 """
3692 Tests for `Connection.send`.
3693 """
3694
3695 def test_wrong_args(self) -> None:
3696 """
3697 When called with arguments other than string argument for its first
3698 parameter, `Connection.send` raises `TypeError`.
3699 """
3700 connection = Connection(Context(SSLv23_METHOD), None)
3701 with pytest.raises(TypeError):
3702 connection.send(object()) # type: ignore[arg-type]
3703 with pytest.raises(TypeError):
3704 connection.send([1, 2, 3]) # type: ignore[arg-type]
3705
3706 def test_short_bytes(self) -> None:
3707 """
3708 When passed a short byte string, `Connection.send` transmits all of it
3709 and returns the number of bytes sent.
3710 """
3711 server, client = loopback()
3712 count = server.send(b"xy")
3713 assert count == 2
3714 assert client.recv(2) == b"xy"
3715
3716 def test_text(self) -> None:
3717 """
3718 When passed a text, `Connection.send` transmits all of it and
3719 returns the number of bytes sent. It also raises a DeprecationWarning.
3720 """
3721 server, client = loopback()
3722 with pytest.warns(DeprecationWarning) as w:
3723 count = server.send(b"xy".decode("ascii")) # type: ignore[arg-type]
3724 assert (
3725 f"{WARNING_TYPE_EXPECTED} for buf is no longer accepted, "
3726 f"use bytes"
3727 ) == str(w[-1].message)
3728 assert count == 2
3729 assert client.recv(2) == b"xy"
3730
3731 def test_short_memoryview(self) -> None:
3732 """
3733 When passed a memoryview onto a small number of bytes,
3734 `Connection.send` transmits all of them and returns the number
3735 of bytes sent.
3736 """
3737 server, client = loopback()
3738 count = server.send(memoryview(b"xy"))
3739 assert count == 2
3740 assert client.recv(2) == b"xy"
3741
3742 def test_short_bytearray(self) -> None:
3743 """
3744 When passed a short bytearray, `Connection.send` transmits all of
3745 it and returns the number of bytes sent.
3746 """
3747 server, client = loopback()
3748 count = server.send(bytearray(b"xy"))
3749 assert count == 2
3750 assert client.recv(2) == b"xy"
3751
3752 @pytest.mark.skipif(
3753 sys.maxsize < 2**31,
3754 reason="sys.maxsize < 2**31 - test requires 64 bit",
3755 )
3756 def test_buf_too_large(self) -> None:
3757 """
3758 When passed a buffer containing >= 2**31 bytes,
3759 `Connection.send` bails out as SSL_write only
3760 accepts an int for the buffer length.
3761 """
3762 connection = Connection(Context(SSLv23_METHOD), None)
3763 with pytest.raises(ValueError) as exc_info:
3764 connection.send(VeryLarge())
3765 exc_info.match(r"Cannot send more than .+ bytes at once")
3766
3767
3768 def _make_memoryview(size: int) -> memoryview:
3769 """
3770 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
3771 size.
3772 """
3773 return memoryview(bytearray(size))
3774
3775
3776 class TestConnectionRecvInto:
3777 """
3778 Tests for `Connection.recv_into`.
3779 """
3780
3781 def _no_length_test(
3782 self, factory: typing.Callable[[int], typing.Any]
3783 ) -> None:
3784 """
3785 Assert that when the given buffer is passed to `Connection.recv_into`,
3786 whatever bytes are available to be received that fit into that buffer
3787 are written into that buffer.
3788 """
3789 output_buffer = factory(5)
3790
3791 server, client = loopback()
3792 server.send(b"xy")
3793
3794 assert client.recv_into(output_buffer) == 2
3795 assert output_buffer == bytearray(b"xy\x00\x00\x00")
3796
3797 def test_bytearray_no_length(self) -> None:
3798 """
3799 `Connection.recv_into` can be passed a `bytearray` instance and data
3800 in the receive buffer is written to it.
3801 """
3802 self._no_length_test(bytearray)
3803
3804 def _respects_length_test(
3805 self, factory: typing.Callable[[int], typing.Any]
3806 ) -> None:
3807 """
3808 Assert that when the given buffer is passed to `Connection.recv_into`
3809 along with a value for `nbytes` that is less than the size of that
3810 buffer, only `nbytes` bytes are written into the buffer.
3811 """
3812 output_buffer = factory(10)
3813
3814 server, client = loopback()
3815 server.send(b"abcdefghij")
3816
3817 assert client.recv_into(output_buffer, 5) == 5
3818 assert output_buffer == bytearray(b"abcde\x00\x00\x00\x00\x00")
3819
3820 def test_bytearray_respects_length(self) -> None:
3821 """
3822 When called with a `bytearray` instance, `Connection.recv_into`
3823 respects the `nbytes` parameter and doesn't copy in more than that
3824 number of bytes.
3825 """
3826 self._respects_length_test(bytearray)
3827
3828 def _doesnt_overfill_test(
3829 self, factory: typing.Callable[[int], typing.Any]
3830 ) -> None:
3831 """
3832 Assert that if there are more bytes available to be read from the
3833 receive buffer than would fit into the buffer passed to
3834 `Connection.recv_into`, only as many as fit are written into it.
3835 """
3836 output_buffer = factory(5)
3837
3838 server, client = loopback()
3839 server.send(b"abcdefghij")
3840
3841 assert client.recv_into(output_buffer) == 5
3842 assert output_buffer == bytearray(b"abcde")
3843 rest = client.recv(5)
3844 assert b"fghij" == rest
3845
3846 def test_bytearray_doesnt_overfill(self) -> None:
3847 """
3848 When called with a `bytearray` instance, `Connection.recv_into`
3849 respects the size of the array and doesn't write more bytes into it
3850 than will fit.
3851 """
3852 self._doesnt_overfill_test(bytearray)
3853
3854 def test_bytearray_really_doesnt_overfill(self) -> None:
3855 """
3856 When called with a `bytearray` instance and an `nbytes` value that is
3857 too large, `Connection.recv_into` respects the size of the array and
3858 not the `nbytes` value and doesn't write more bytes into the buffer
3859 than will fit.
3860 """
3861 self._doesnt_overfill_test(bytearray)
3862
3863 def test_peek(self) -> None:
3864 server, client = loopback()
3865 server.send(b"xy")
3866
3867 for _ in range(2):
3868 output_buffer = bytearray(5)
3869 assert client.recv_into(output_buffer, flags=MSG_PEEK) == 2
3870 assert output_buffer == bytearray(b"xy\x00\x00\x00")
3871
3872 def test_memoryview_no_length(self) -> None:
3873 """
3874 `Connection.recv_into` can be passed a `memoryview` instance and data
3875 in the receive buffer is written to it.
3876 """
3877 self._no_length_test(_make_memoryview)
3878
3879 def test_memoryview_respects_length(self) -> None:
3880 """
3881 When called with a `memoryview` instance, `Connection.recv_into`
3882 respects the ``nbytes`` parameter and doesn't copy more than that
3883 number of bytes in.
3884 """
3885 self._respects_length_test(_make_memoryview)
3886
3887 def test_memoryview_doesnt_overfill(self) -> None:
3888 """
3889 When called with a `memoryview` instance, `Connection.recv_into`
3890 respects the size of the array and doesn't write more bytes into it
3891 than will fit.
3892 """
3893 self._doesnt_overfill_test(_make_memoryview)
3894
3895 def test_memoryview_really_doesnt_overfill(self) -> None:
3896 """
3897 When called with a `memoryview` instance and an `nbytes` value that is
3898 too large, `Connection.recv_into` respects the size of the array and
3899 not the `nbytes` value and doesn't write more bytes into the buffer
3900 than will fit.
3901 """
3902 self._doesnt_overfill_test(_make_memoryview)
3903
3904
3905 class TestConnectionSendall:
3906 """
3907 Tests for `Connection.sendall`.
3908 """
3909
3910 def test_wrong_args(self) -> None:
3911 """
3912 When called with arguments other than a string argument for its first
3913 parameter, `Connection.sendall` raises `TypeError`.
3914 """
3915 connection = Connection(Context(SSLv23_METHOD), None)
3916 with pytest.raises(TypeError):
3917 connection.sendall(object()) # type: ignore[arg-type]
3918 with pytest.raises(TypeError):
3919 connection.sendall([1, 2, 3]) # type: ignore[arg-type]
3920
3921 def test_short(self) -> None:
3922 """
3923 `Connection.sendall` transmits all of the bytes in the string
3924 passed to it.
3925 """
3926 server, client = loopback()
3927 server.sendall(b"x")
3928 assert client.recv(1) == b"x"
3929
3930 def test_text(self) -> None:
3931 """
3932 `Connection.sendall` transmits all the content in the string passed
3933 to it, raising a DeprecationWarning in case of this being a text.
3934 """
3935 server, client = loopback()
3936 with pytest.warns(DeprecationWarning) as w:
3937 server.sendall(b"x".decode("ascii")) # type: ignore[arg-type]
3938 assert (
3939 f"{WARNING_TYPE_EXPECTED} for buf is no longer accepted, "
3940 f"use bytes"
3941 ) == str(w[-1].message)
3942 assert client.recv(1) == b"x"
3943
3944 def test_short_memoryview(self) -> None:
3945 """
3946 When passed a memoryview onto a small number of bytes,
3947 `Connection.sendall` transmits all of them.
3948 """
3949 server, client = loopback()
3950 server.sendall(memoryview(b"x"))
3951 assert client.recv(1) == b"x"
3952
3953 def test_long(self) -> None:
3954 """
3955 `Connection.sendall` transmits all the bytes in the string passed to it
3956 even if this requires multiple calls of an underlying write function.
3957 """
3958 server, client = loopback()
3959 # Should be enough, underlying SSL_write should only do 16k at a time.
3960 # On Windows, after 32k of bytes the write will block (forever
3961 # - because no one is yet reading).
3962 message = b"x" * (1024 * 32 - 1) + b"y"
3963 server.sendall(message)
3964 accum = []
3965 received = 0
3966 while received < len(message):
3967 data = client.recv(1024)
3968 accum.append(data)
3969 received += len(data)
3970 assert message == b"".join(accum)
3971
3972 def test_closed(self) -> None:
3973 """
3974 If the underlying socket is closed, `Connection.sendall` propagates the
3975 write error from the low level write call.
3976 """
3977 server, _ = loopback()
3978 server.sock_shutdown(2)
3979 with pytest.raises(SysCallError) as err:
3980 server.sendall(b"hello, world")
3981 if platform == "win32":
3982 assert err.value.args[0] == ESHUTDOWN
3983 else:
3984 assert err.value.args[0] == EPIPE
3985
3986
3987 class TestConnectionRenegotiate:
3988 """
3989 Tests for SSL renegotiation APIs.
3990 """
3991
3992 def test_total_renegotiations(self) -> None:
3993 """
3994 `Connection.total_renegotiations` returns `0` before any renegotiations
3995 have happened.
3996 """
3997 connection = Connection(Context(SSLv23_METHOD), None)
3998 assert connection.total_renegotiations() == 0
3999
4000 @pytest.mark.skipif(
4001 conftest.is_awslc,
4002 reason="aws-lc doesn't support renegotiation",
4003 )
4004 def test_renegotiate(self) -> None:
4005 """
4006 Go through a complete renegotiation cycle.
4007 """
4008 server, client = loopback(
4009 lambda s: loopback_server_factory(s, TLSv1_2_METHOD),
4010 lambda s: loopback_client_factory(s, TLSv1_2_METHOD),
4011 )
4012
4013 server.send(b"hello world")
4014
4015 assert b"hello world" == client.recv(len(b"hello world"))
4016
4017 assert 0 == server.total_renegotiations()
4018 assert False is server.renegotiate_pending()
4019
4020 assert True is server.renegotiate()
4021
4022 assert True is server.renegotiate_pending()
4023
4024 server.setblocking(False)
4025 client.setblocking(False)
4026
4027 client.do_handshake()
4028 server.do_handshake()
4029
4030 assert 1 == server.total_renegotiations()
4031 while False is server.renegotiate_pending():
4032 pass
4033
4034
4035 class TestError:
4036 """
4037 Unit tests for `OpenSSL.SSL.Error`.
4038 """
4039
4040 def test_type(self) -> None:
4041 """
4042 `Error` is an exception type.
4043 """
4044 assert issubclass(Error, Exception)
4045 assert Error.__name__ == "Error"
4046
4047
4048 class TestConstants:
4049 """
4050 Tests for the values of constants exposed in `OpenSSL.SSL`.
4051
4052 These are values defined by OpenSSL intended only to be used as flags to
4053 OpenSSL APIs. The only assertions it seems can be made about them is
4054 their values.
4055 """
4056
4057 @pytest.mark.skipif(
4058 OP_NO_QUERY_MTU is None,
4059 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old",
4060 )
4061 def test_op_no_query_mtu(self) -> None:
4062 """
4063 The value of `OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
4064 of `SSL_OP_NO_QUERY_MTU` defined by `openssl/ssl.h`.
4065 """
4066 assert OP_NO_QUERY_MTU == 0x1000
4067
4068 @pytest.mark.skipif(
4069 OP_COOKIE_EXCHANGE is None,
4070 reason="OP_COOKIE_EXCHANGE unavailable - "
4071 "OpenSSL version may be too old",
4072 )
4073 def test_op_cookie_exchange(self) -> None:
4074 """
4075 The value of `OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
4076 value of `SSL_OP_COOKIE_EXCHANGE` defined by `openssl/ssl.h`.
4077 """
4078 assert OP_COOKIE_EXCHANGE == 0x2000
4079
4080 @pytest.mark.skipif(
4081 OP_NO_TICKET is None,
4082 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old",
4083 )
4084 def test_op_no_ticket(self) -> None:
4085 """
4086 The value of `OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
4087 `SSL_OP_NO_TICKET` defined by `openssl/ssl.h`.
4088 """
4089 assert OP_NO_TICKET == 0x4000
4090
4091 @pytest.mark.skipif(
4092 OP_NO_COMPRESSION is None,
4093 reason=(
4094 "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
4095 ),
4096 )
4097 @pytest.mark.skipif(
4098 conftest.is_awslc,
4099 reason="aws-lc defines OP_NO_COMPRESSION as 0",
4100 )
4101 def test_op_no_compression(self) -> None:
4102 """
4103 The value of `OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
4104 value of `SSL_OP_NO_COMPRESSION` defined by `openssl/ssl.h`.
4105 """
4106 assert OP_NO_COMPRESSION == 0x20000
4107
4108 def test_sess_cache_off(self) -> None:
4109 """
4110 The value of `OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
4111 `SSL_SESS_CACHE_OFF` defined by `openssl/ssl.h`.
4112 """
4113 assert 0x0 == SESS_CACHE_OFF
4114
4115 def test_sess_cache_client(self) -> None:
4116 """
4117 The value of `OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
4118 `SSL_SESS_CACHE_CLIENT` defined by `openssl/ssl.h`.
4119 """
4120 assert 0x1 == SESS_CACHE_CLIENT
4121
4122 def test_sess_cache_server(self) -> None:
4123 """
4124 The value of `OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
4125 `SSL_SESS_CACHE_SERVER` defined by `openssl/ssl.h`.
4126 """
4127 assert 0x2 == SESS_CACHE_SERVER
4128
4129 def test_sess_cache_both(self) -> None:
4130 """
4131 The value of `OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
4132 `SSL_SESS_CACHE_BOTH` defined by `openssl/ssl.h`.
4133 """
4134 assert 0x3 == SESS_CACHE_BOTH
4135
4136 def test_sess_cache_no_auto_clear(self) -> None:
4137 """
4138 The value of `OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
4139 value of `SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
4140 `openssl/ssl.h`.
4141 """
4142 assert 0x80 == SESS_CACHE_NO_AUTO_CLEAR
4143
4144 def test_sess_cache_no_internal_lookup(self) -> None:
4145 """
4146 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
4147 the value of `SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
4148 `openssl/ssl.h`.
4149 """
4150 assert 0x100 == SESS_CACHE_NO_INTERNAL_LOOKUP
4151
4152 def test_sess_cache_no_internal_store(self) -> None:
4153 """
4154 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
4155 the value of `SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
4156 `openssl/ssl.h`.
4157 """
4158 assert 0x200 == SESS_CACHE_NO_INTERNAL_STORE
4159
4160 def test_sess_cache_no_internal(self) -> None:
4161 """
4162 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
4163 value of `SSL_SESS_CACHE_NO_INTERNAL` defined by
4164 `openssl/ssl.h`.
4165 """
4166 assert 0x300 == SESS_CACHE_NO_INTERNAL
4167
4168
4169 class TestMemoryBIO:
4170 """
4171 Tests for `OpenSSL.SSL.Connection` using a memory BIO.
4172 """
4173
4174 def _create_server_context(self) -> Context:
4175 """
4176 Create a configured server context with certificates and options.
4177 """
4178 server_ctx = Context(SSLv23_METHOD)
4179 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
4180 server_ctx.set_verify(
4181 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
4182 verify_cb,
4183 )
4184 server_store = server_ctx.get_cert_store()
4185 assert server_store is not None
4186 server_ctx.use_privatekey(
4187 load_privatekey(FILETYPE_PEM, server_key_pem)
4188 )
4189 server_ctx.use_certificate(
4190 load_certificate(FILETYPE_PEM, server_cert_pem)
4191 )
4192 server_ctx.check_privatekey()
4193 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
4194 return server_ctx
4195
4196 def _server(
4197 self, sock: socket | None, ctx: Context | None = None
4198 ) -> Connection:
4199 """
4200 Create a new server-side SSL `Connection` object wrapped around `sock`.
4201
4202 :param sock: The socket to wrap, or None for memory BIO.
4203 :param ctx: Optional pre-configured context. If None, creates a
4204 default server context.
4205 """
4206 if ctx is None:
4207 server_ctx = self._create_server_context()
4208 else:
4209 server_ctx = ctx
4210
4211 # Here the Connection is actually created. If None is passed as the
4212 # 2nd parameter, it indicates a memory BIO should be created.
4213 server_conn = Connection(server_ctx, sock)
4214 server_conn.set_accept_state()
4215 return server_conn
4216
4217 def _client(self, sock: socket | None) -> Connection:
4218 """
4219 Create a new client-side SSL `Connection` object wrapped around `sock`.
4220 """
4221 # Now create the client side Connection. Similar boilerplate to the
4222 # above.
4223 client_ctx = Context(SSLv23_METHOD)
4224 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
4225 client_ctx.set_verify(
4226 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
4227 verify_cb,
4228 )
4229 client_store = client_ctx.get_cert_store()
4230 assert client_store is not None
4231 client_ctx.use_privatekey(
4232 load_privatekey(FILETYPE_PEM, client_key_pem)
4233 )
4234 client_ctx.use_certificate(
4235 load_certificate(FILETYPE_PEM, client_cert_pem)
4236 )
4237 client_ctx.check_privatekey()
4238 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
4239 client_conn = Connection(client_ctx, sock)
4240 client_conn.set_connect_state()
4241 return client_conn
4242
4243 def test_memory_connect(self) -> None:
4244 """
4245 Two `Connection`s which use memory BIOs can be manually connected by
4246 reading from the output of each and writing those bytes to the input of
4247 the other and in this way establish a connection and exchange
4248 application-level bytes with each other.
4249 """
4250 server_conn = self._server(None)
4251 client_conn = self._client(None)
4252
4253 # There should be no key or nonces yet.
4254 assert server_conn.master_key() is None
4255 assert server_conn.client_random() is None
4256 assert server_conn.server_random() is None
4257
4258 # First, the handshake needs to happen. We'll deliver bytes back and
4259 # forth between the client and server until neither of them feels like
4260 # speaking any more.
4261 assert interact_in_memory(client_conn, server_conn) is None
4262
4263 # Now that the handshake is done, there should be a key and nonces.
4264 assert server_conn.master_key() is not None
4265 assert server_conn.client_random() is not None
4266 assert server_conn.server_random() is not None
4267 assert server_conn.client_random() == client_conn.client_random()
4268 assert server_conn.server_random() == client_conn.server_random()
4269 assert server_conn.client_random() != server_conn.server_random()
4270 assert client_conn.client_random() != client_conn.server_random()
4271
4272 # Export key material for other uses.
4273 cekm = client_conn.export_keying_material(b"LABEL", 32)
4274 sekm = server_conn.export_keying_material(b"LABEL", 32)
4275 assert cekm is not None
4276 assert sekm is not None
4277 assert cekm == sekm
4278 assert len(sekm) == 32
4279
4280 # Export key material for other uses with additional context.
4281 cekmc = client_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
4282 sekmc = server_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
4283 assert cekmc is not None
4284 assert sekmc is not None
4285 assert cekmc == sekmc
4286 assert cekmc != cekm
4287 assert sekmc != sekm
4288 # Export with alternate label
4289 cekmt = client_conn.export_keying_material(b"test", 32, b"CONTEXT")
4290 sekmt = server_conn.export_keying_material(b"test", 32, b"CONTEXT")
4291 assert cekmc != cekmt
4292 assert sekmc != sekmt
4293
4294 # Here are the bytes we'll try to send.
4295 important_message = b"One if by land, two if by sea."
4296
4297 server_conn.write(important_message)
4298 assert interact_in_memory(client_conn, server_conn) == (
4299 client_conn,
4300 important_message,
4301 )
4302
4303 client_conn.write(important_message[::-1])
4304 assert interact_in_memory(client_conn, server_conn) == (
4305 server_conn,
4306 important_message[::-1],
4307 )
4308
4309 def test_socket_connect(self) -> None:
4310 """
4311 Just like `test_memory_connect` but with an actual socket.
4312
4313 This is primarily to rule out the memory BIO code as the source of any
4314 problems encountered while passing data over a `Connection` (if
4315 this test fails, there must be a problem outside the memory BIO code,
4316 as no memory BIO is involved here). Even though this isn't a memory
4317 BIO test, it's convenient to have it here.
4318 """
4319 server_conn, client_conn = loopback()
4320
4321 important_message = b"Help me Obi Wan Kenobi, you're my only hope."
4322 client_conn.send(important_message)
4323 msg = server_conn.recv(1024)
4324 assert msg == important_message
4325
4326 # Again in the other direction, just for fun.
4327 important_message = important_message[::-1]
4328 server_conn.send(important_message)
4329 msg = client_conn.recv(1024)
4330 assert msg == important_message
4331
4332 def test_socket_overrides_memory(self) -> None:
4333 """
4334 Test that `OpenSSL.SSL.bio_read` and `OpenSSL.SSL.bio_write` don't
4335 work on `OpenSSL.SSL.Connection`() that use sockets.
4336 """
4337 context = Context(SSLv23_METHOD)
4338 client = socket_any_family()
4339 clientSSL = Connection(context, client)
4340 with pytest.raises(TypeError):
4341 clientSSL.bio_read(100)
4342 with pytest.raises(TypeError):
4343 clientSSL.bio_write(b"foo")
4344 with pytest.raises(TypeError):
4345 clientSSL.bio_shutdown()
4346
4347 def test_outgoing_overflow(self) -> None:
4348 """
4349 If more bytes than can be written to the memory BIO are passed to
4350 `Connection.send` at once, the number of bytes which were written is
4351 returned and that many bytes from the beginning of the input can be
4352 read from the other end of the connection.
4353 """
4354 server = self._server(None)
4355 client = self._client(None)
4356
4357 interact_in_memory(client, server)
4358
4359 size = 2**15
4360 sent = client.send(b"x" * size)
4361 # Sanity check. We're trying to test what happens when the entire
4362 # input can't be sent. If the entire input was sent, this test is
4363 # meaningless.
4364 assert sent < size
4365
4366 result = interact_in_memory(client, server)
4367 assert result is not None
4368 receiver, received = result
4369 assert receiver is server
4370
4371 # We can rely on all of these bytes being received at once because
4372 # loopback passes 2 ** 16 to recv - more than 2 ** 15.
4373 assert len(received) == sent
4374
4375 def test_shutdown(self) -> None:
4376 """
4377 `Connection.bio_shutdown` signals the end of the data stream
4378 from which the `Connection` reads.
4379 """
4380 server = self._server(None)
4381 server.bio_shutdown()
4382 with pytest.raises(Error) as err:
4383 server.recv(1024)
4384 # We don't want WantReadError or ZeroReturnError or anything - it's a
4385 # handshake failure.
4386 assert type(err.value) in [Error, SysCallError]
4387
4388 def test_unexpected_EOF(self) -> None:
4389 """
4390 If the connection is lost before an orderly SSL shutdown occurs,
4391 `OpenSSL.SSL.SysCallError` is raised with a message of
4392 "Unexpected EOF" (or WSAECONNRESET on Windows).
4393 """
4394 server_conn, client_conn = loopback()
4395 client_conn.sock_shutdown(SHUT_RDWR)
4396 with pytest.raises(SysCallError) as err:
4397 server_conn.recv(1024)
4398 if platform == "win32":
4399 assert err.value.args == (10054, "WSAECONNRESET")
4400 else:
4401 assert err.value.args in [
4402 (-1, "Unexpected EOF"),
4403 (54, "ECONNRESET"),
4404 ]
4405
4406 def _check_client_ca_list(
4407 self, func: typing.Callable[[Context], list[X509Name]]
4408 ) -> None:
4409 """
4410 Verify the return value of the `get_client_ca_list` method for
4411 server and client connections.
4412
4413 :param func: A function which will be called with the server context
4414 before the client and server are connected to each other. This
4415 function should specify a list of CAs for the server to send to the
4416 client and return that same list. The list will be used to verify
4417 that `get_client_ca_list` returns the proper value at
4418 various times.
4419 """
4420 # Create a server context and configure it before creating connections
4421 server_ctx = self._create_server_context()
4422
4423 # Configure the CA list before creating connections
4424 expected = func(server_ctx)
4425
4426 # Now create connections with the configured context
4427 server = self._server(None, server_ctx)
4428 client = self._client(None)
4429
4430 assert client.get_client_ca_list() == []
4431 assert server.get_client_ca_list() == expected
4432 interact_in_memory(client, server)
4433 assert client.get_client_ca_list() == expected
4434 assert server.get_client_ca_list() == expected
4435
4436 def test_set_client_ca_list_errors(self) -> None:
4437 """
4438 `Context.set_client_ca_list` raises a `TypeError` if called with a
4439 non-list or a list that contains objects other than X509Names.
4440 """
4441 ctx = Context(SSLv23_METHOD)
4442 with pytest.raises(TypeError):
4443 ctx.set_client_ca_list("spam") # type: ignore[arg-type]
4444 with pytest.raises(TypeError):
4445 ctx.set_client_ca_list(["spam"]) # type: ignore[list-item]
4446
4447 def test_set_empty_ca_list(self) -> None:
4448 """
4449 If passed an empty list, `Context.set_client_ca_list` configures the
4450 context to send no CA names to the client and, on both the server and
4451 client sides, `Connection.get_client_ca_list` returns an empty list
4452 after the connection is set up.
4453 """
4454
4455 def no_ca(ctx: Context) -> list[X509Name]:
4456 ctx.set_client_ca_list([])
4457 return []
4458
4459 self._check_client_ca_list(no_ca)
4460
4461 def test_set_one_ca_list(self) -> None:
4462 """
4463 If passed a list containing a single X509Name,
4464 `Context.set_client_ca_list` configures the context to send
4465 that CA name to the client and, on both the server and client sides,
4466 `Connection.get_client_ca_list` returns a list containing that
4467 X509Name after the connection is set up.
4468 """
4469 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4470 cadesc = cacert.get_subject()
4471
4472 def single_ca(ctx: Context) -> list[X509Name]:
4473 ctx.set_client_ca_list([cadesc])
4474 return [cadesc]
4475
4476 self._check_client_ca_list(single_ca)
4477
4478 def test_get_client_ca_list_as_cryptography(self) -> None:
4479 """
4480 `Connection.get_client_ca_list` returns a list of
4481 `cryptography.x509.Name` when called with ``as_cryptography=True``.
4482 """
4483 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4484 expected = [cacert.to_cryptography().subject]
4485
4486 server_ctx = self._create_server_context()
4487 server_ctx.set_client_ca_list([cacert.get_subject()])
4488
4489 server = self._server(None, server_ctx)
4490 client = self._client(None)
4491
4492 assert client.get_client_ca_list(as_cryptography=True) == []
4493 assert server.get_client_ca_list(as_cryptography=True) == expected
4494 interact_in_memory(client, server)
4495 assert client.get_client_ca_list(as_cryptography=True) == expected
4496 assert server.get_client_ca_list(as_cryptography=True) == expected
4497
4498 def test_set_multiple_ca_list(self) -> None:
4499 """
4500 If passed a list containing multiple X509Name objects,
4501 `Context.set_client_ca_list` configures the context to send
4502 those CA names to the client and, on both the server and client sides,
4503 `Connection.get_client_ca_list` returns a list containing those
4504 X509Names after the connection is set up.
4505 """
4506 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
4507 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
4508
4509 sedesc = secert.get_subject()
4510 cldesc = clcert.get_subject()
4511
4512 def multiple_ca(ctx: Context) -> list[X509Name]:
4513 L = [sedesc, cldesc]
4514 ctx.set_client_ca_list(L)
4515 return L
4516
4517 self._check_client_ca_list(multiple_ca)
4518
4519 def test_reset_ca_list(self) -> None:
4520 """
4521 If called multiple times, only the X509Names passed to the final call
4522 of `Context.set_client_ca_list` are used to configure the CA
4523 names sent to the client.
4524 """
4525 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4526 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
4527 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
4528
4529 cadesc = cacert.get_subject()
4530 sedesc = secert.get_subject()
4531 cldesc = clcert.get_subject()
4532
4533 def changed_ca(ctx: Context) -> list[X509Name]:
4534 ctx.set_client_ca_list([sedesc, cldesc])
4535 ctx.set_client_ca_list([cadesc])
4536 return [cadesc]
4537
4538 self._check_client_ca_list(changed_ca)
4539
4540 def test_mutated_ca_list(self) -> None:
4541 """
4542 If the list passed to `Context.set_client_ca_list` is mutated
4543 afterwards, this does not affect the list of CA names sent to the
4544 client.
4545 """
4546 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4547 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
4548
4549 cadesc = cacert.get_subject()
4550 sedesc = secert.get_subject()
4551
4552 def mutated_ca(ctx: Context) -> list[X509Name]:
4553 L = [cadesc]
4554 ctx.set_client_ca_list([cadesc])
4555 L.append(sedesc)
4556 return [cadesc]
4557
4558 self._check_client_ca_list(mutated_ca)
4559
4560 def test_add_client_ca_wrong_args(self) -> None:
4561 """
4562 `Context.add_client_ca` raises `TypeError` if called with
4563 a non-X509 object.
4564 """
4565 ctx = Context(SSLv23_METHOD)
4566 with pytest.raises(TypeError):
4567 ctx.add_client_ca("spam") # type: ignore[arg-type]
4568
4569 def test_one_add_client_ca(self) -> None:
4570 """
4571 A certificate's subject can be added as a CA to be sent to the client
4572 with `Context.add_client_ca`.
4573 """
4574 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4575 cadesc = cacert.get_subject()
4576
4577 def single_ca(ctx: Context) -> list[X509Name]:
4578 ctx.add_client_ca(cacert)
4579 return [cadesc]
4580
4581 self._check_client_ca_list(single_ca)
4582
4583 def test_multiple_add_client_ca(self) -> None:
4584 """
4585 Multiple CA names can be sent to the client by calling
4586 `Context.add_client_ca` with multiple X509 objects.
4587 """
4588 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4589 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
4590
4591 cadesc = cacert.get_subject()
4592 sedesc = secert.get_subject()
4593
4594 def multiple_ca(ctx: Context) -> list[X509Name]:
4595 ctx.add_client_ca(cacert)
4596 ctx.add_client_ca(secert.to_cryptography())
4597 return [cadesc, sedesc]
4598
4599 self._check_client_ca_list(multiple_ca)
4600
4601 def test_set_and_add_client_ca(self) -> None:
4602 """
4603 A call to `Context.set_client_ca_list` followed by a call to
4604 `Context.add_client_ca` results in using the CA names from the
4605 first call and the CA name from the second call.
4606 """
4607 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4608 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
4609 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
4610
4611 cadesc = cacert.get_subject()
4612 sedesc = secert.get_subject()
4613 cldesc = clcert.get_subject()
4614
4615 def mixed_set_add_ca(ctx: Context) -> list[X509Name]:
4616 ctx.set_client_ca_list([cadesc, sedesc])
4617 ctx.add_client_ca(clcert)
4618 return [cadesc, sedesc, cldesc]
4619
4620 self._check_client_ca_list(mixed_set_add_ca)
•4621
4622 def test_set_after_add_client_ca(self) -> None:
4623 """
4624 A call to `Context.set_client_ca_list` after a call to
4625 `Context.add_client_ca` replaces the CA name specified by the
4626 former call with the names specified by the latter call.
4627 """
4628 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
4629 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
4630 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
4631
4632 cadesc = cacert.get_subject()
4633 sedesc = secert.get_subject()
4634
4635 def set_replaces_add_ca(ctx: Context) -> list[X509Name]:
4636 ctx.add_client_ca(clcert.to_cryptography())
4637 ctx.set_client_ca_list([cadesc])
4638 ctx.add_client_ca(secert)
4639 return [cadesc, sedesc]
4640
4641 self._check_client_ca_list(set_replaces_add_ca)
4642
4643
4644 class TestInfoConstants:
4645 """
4646 Tests for assorted constants exposed for use in info callbacks.
4647 """
4648
4649 def test_integers(self) -> None:
4650 """
4651 All of the info constants are integers.
4652
4653 This is a very weak test. It would be nice to have one that actually
4654 verifies that as certain info events happen, the value passed to the
4655 info callback matches up with the constant exposed by OpenSSL.SSL.
4656 """
4657 for const in [
4658 SSL_ST_CONNECT,
4659 SSL_ST_ACCEPT,
4660 SSL_ST_MASK,
4661 SSL_CB_LOOP,
4662 SSL_CB_EXIT,
4663 SSL_CB_READ,
4664 SSL_CB_WRITE,
4665 SSL_CB_ALERT,
4666 SSL_CB_READ_ALERT,
4667 SSL_CB_WRITE_ALERT,
4668 SSL_CB_ACCEPT_LOOP,
4669 SSL_CB_ACCEPT_EXIT,
4670 SSL_CB_CONNECT_LOOP,
4671 SSL_CB_CONNECT_EXIT,
4672 SSL_CB_HANDSHAKE_START,
4673 SSL_CB_HANDSHAKE_DONE,
4674 ]:
4675 assert isinstance(const, int)
4676
4677
4678 class TestRequires:
4679 """
4680 Tests for the decorator factory used to conditionally raise
4681 NotImplementedError when older OpenSSLs are used.
4682 """
4683
4684 def test_available(self) -> None:
4685 """
4686 When the OpenSSL functionality is available the decorated functions
4687 work appropriately.
4688 """
4689 feature_guard = _make_requires(True, "Error text")
4690 results = []
4691
4692 @feature_guard
4693 def inner() -> bool:
4694 results.append(True)
4695 return True
4696
4697 assert inner() is True
4698 assert [True] == results
4699
4700 def test_unavailable(self) -> None:
4701 """
4702 When the OpenSSL functionality is not available the decorated function
4703 does not execute and NotImplementedError is raised.
4704 """
4705 feature_guard = _make_requires(False, "Error text")
4706
4707 @feature_guard
4708 def inner() -> None: # pragma: nocover
4709 pytest.fail("Should not be called")
4710
4711 with pytest.raises(NotImplementedError) as e:
4712 inner()
4713
4714 assert "Error text" in str(e.value)
4715
4716
4717 T = typing.TypeVar("T")
4718
4719
4720 class TestOCSP:
4721 """
4722 Tests for PyOpenSSL's OCSP stapling support.
4723 """
4724
4725 # Minimal valid DER-encoded OCSPResponse with status "unauthorized"
4726 # (SEQUENCE { ENUMERATED 6 }). Required by OpenSSL 4.0+, which parses
4727 # the bytes via d2i_OCSP_RESPONSE before stapling and silently drops
4728 # unparseable input.
4729 sample_ocsp_data = b"\x30\x03\x0a\x01\x06"
4730
4731 def _client_connection(
4732 self,
4733 callback: typing.Callable[[Connection, bytes, T | None], bool],
4734 data: T | None,
4735 request_ocsp: bool = True,
4736 ) -> Connection:
4737 """
4738 Builds a client connection suitable for using OCSP.
4739
4740 :param callback: The callback to register for OCSP.
4741 :param data: The opaque data object that will be handed to the
4742 OCSP callback.
4743 :param request_ocsp: Whether the client will actually ask for OCSP
4744 stapling. Useful for testing only.
4745 """
4746 ctx = Context(SSLv23_METHOD)
4747 ctx.set_ocsp_client_callback(callback, data)
4748 client = Connection(ctx)
4749
4750 if request_ocsp:
4751 client.request_ocsp()
4752
4753 client.set_connect_state()
4754 return client
4755
4756 def _server_connection(
4757 self,
4758 callback: typing.Callable[[Connection, T | None], bytes],
4759 data: T | None,
4760 ) -> Connection:
4761 """
4762 Builds a server connection suitable for using OCSP.
4763
4764 :param callback: The callback to register for OCSP.
4765 :param data: The opaque data object that will be handed to the
4766 OCSP callback.
4767 """
4768 ctx = Context(SSLv23_METHOD)
4769 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
4770 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
4771 ctx.set_ocsp_server_callback(callback, data)
4772 server = Connection(ctx)
4773 server.set_accept_state()
4774 return server
4775
4776 def test_callbacks_arent_called_by_default(self) -> None:
4777 """
4778 If both the client and the server have registered OCSP callbacks, but
4779 the client does not send the OCSP request, neither callback gets
4780 called.
4781 """
4782
4783 def ocsp_callback(*args: object) -> typing.NoReturn: # pragma: nocover
4784 pytest.fail("Should not be called")
4785
4786 client = self._client_connection(
4787 callback=ocsp_callback, data=None, request_ocsp=False
4788 )
4789 server = self._server_connection(callback=ocsp_callback, data=None)
4790 handshake_in_memory(client, server)
4791
4792 def test_client_negotiates_without_server(self) -> None:
4793 """
4794 If the client wants to do OCSP but the server does not, the handshake
4795 succeeds, and the client callback fires with an empty byte string.
4796 """
4797 called = []
4798
4799 def ocsp_callback(
4800 conn: Connection, ocsp_data: bytes, ignored: None
4801 ) -> bool:
4802 called.append(ocsp_data)
4803 return True
4804
4805 client = self._client_connection(callback=ocsp_callback, data=None)
4806 server = loopback_server_factory(socket=None)
4807 handshake_in_memory(client, server)
4808
4809 assert len(called) == 1
4810 assert called[0] == b""
4811
4812 @pytest.mark.skip(reason="OCSP data must not be a string")
4813 def test_client_receives_servers_data(self) -> None:
4814 """
4815 The data the server sends in its callback is received by the client.
4816 """
4817 calls = []
4818
4819 def server_callback(*args: object, **kwargs: object) -> bytes:
4820 return self.sample_ocsp_data
4821
4822 def client_callback(
4823 conn: Connection, ocsp_data: bytes, ignored: None
4824 ) -> bool:
4825 calls.append(ocsp_data)
4826 return True
4827
4828 client = self._client_connection(callback=client_callback, data=None)
4829 server = self._server_connection(callback=server_callback, data=None)
4830 handshake_in_memory(client, server)
4831
4832 assert len(calls) == 1
4833 assert calls[0] == self.sample_ocsp_data
4834
4835 def test_callbacks_are_invoked_with_connections(self) -> None:
4836 """
4837 The first arguments to both callbacks are their respective connections.
4838 """
4839 client_calls = []
4840 server_calls = []
4841
4842 def client_callback(
4843 conn: Connection, *args: object, **kwargs: object
4844 ) -> bool:
4845 client_calls.append(conn)
4846 return True
4847
4848 def server_callback(
4849 conn: Connection, *args: object, **kwargs: object
4850 ) -> bytes:
4851 server_calls.append(conn)
4852 return self.sample_ocsp_data
4853
4854 client = self._client_connection(callback=client_callback, data=None)
4855 server = self._server_connection(callback=server_callback, data=None)
4856 handshake_in_memory(client, server)
4857
4858 assert len(client_calls) == 1
4859 assert len(server_calls) == 1
4860 assert client_calls[0] is client
4861 assert server_calls[0] is server
4862
4863 def test_opaque_data_is_passed_through(self) -> None:
4864 """
4865 Both callbacks receive an opaque, user-provided piece of data in their
4866 callbacks as the final argument.
4867 """
4868 calls = []
4869
4870 def server_callback(*args: object) -> bytes:
4871 calls.append(args)
4872 return self.sample_ocsp_data
4873
4874 def client_callback(*args: object) -> bool:
4875 calls.append(args)
4876 return True
4877
4878 sentinel = object()
4879
4880 client = self._client_connection(
4881 callback=client_callback, data=sentinel
4882 )
4883 server = self._server_connection(
4884 callback=server_callback, data=sentinel
4885 )
4886 handshake_in_memory(client, server)
4887
4888 assert len(calls) == 2
4889 assert calls[0][-1] is sentinel
4890 assert calls[1][-1] is sentinel
4891
4892 def test_server_returns_empty_string(self) -> None:
4893 """
4894 If the server returns an empty bytestring from its callback, the
4895 client callback is called with the empty bytestring.
4896 """
4897 client_calls = []
4898
4899 def server_callback(*args: object) -> bytes:
4900 return b""
4901
4902 def client_callback(
4903 conn: Connection, ocsp_data: bytes, ignored: None
4904 ) -> bool:
4905 client_calls.append(ocsp_data)
4906 return True
4907
4908 client = self._client_connection(callback=client_callback, data=None)
4909 server = self._server_connection(callback=server_callback, data=None)
4910 handshake_in_memory(client, server)
4911
4912 assert len(client_calls) == 1
4913 assert client_calls[0] == b""
4914
4915 def test_client_returns_false_terminates_handshake(self) -> None:
4916 """
4917 If the client returns False from its callback, the handshake fails.
4918 """
4919
4920 def server_callback(*args: object) -> bytes:
4921 return self.sample_ocsp_data
4922
4923 def client_callback(*args: object) -> bool:
4924 return False
4925
4926 client = self._client_connection(callback=client_callback, data=None)
4927 server = self._server_connection(callback=server_callback, data=None)
4928
4929 with pytest.raises(Error):
4930 handshake_in_memory(client, server)
4931
4932 def test_exceptions_in_client_bubble_up(self) -> None:
4933 """
4934 The callbacks thrown in the client callback bubble up to the caller.
4935 """
4936
4937 class SentinelException(Exception):
4938 pass
4939
4940 def server_callback(*args: object) -> bytes:
4941 return self.sample_ocsp_data
4942
4943 def client_callback(*args: object) -> typing.NoReturn:
4944 raise SentinelException()
4945
4946 client = self._client_connection(callback=client_callback, data=None)
4947 server = self._server_connection(callback=server_callback, data=None)
4948
4949 with pytest.raises(SentinelException):
4950 handshake_in_memory(client, server)
4951
4952 def test_exceptions_in_server_bubble_up(self) -> None:
4953 """
4954 The callbacks thrown in the server callback bubble up to the caller.
4955 """
4956
4957 class SentinelException(Exception):
4958 pass
4959
4960 def server_callback(*args: object) -> typing.NoReturn:
4961 raise SentinelException()
4962
4963 def client_callback(
4964 *args: object,
4965 ) -> typing.NoReturn: # pragma: nocover
4966 pytest.fail("Should not be called")
4967
4968 client = self._client_connection(callback=client_callback, data=None)
4969 server = self._server_connection(callback=server_callback, data=None)
4970
4971 with pytest.raises(SentinelException):
4972 handshake_in_memory(client, server)
4973
4974 def test_server_must_return_bytes(self) -> None:
4975 """
4976 The server callback must return a bytestring, or a TypeError is thrown.
4977 """
4978
4979 def server_callback(*args: object) -> str:
4980 return self.sample_ocsp_data.decode("ascii")
4981
4982 def client_callback(
4983 *args: object,
4984 ) -> typing.NoReturn: # pragma: nocover
4985 pytest.fail("Should not be called")
4986
4987 client = self._client_connection(callback=client_callback, data=None)
4988 server = self._server_connection(callback=server_callback, data=None) # type: ignore[arg-type]
4989
4990 with pytest.raises(TypeError):
4991 handshake_in_memory(client, server)
4992
4993
4994 class TestDTLS:
4995 # The way you would expect DTLSv1_listen to work is:
4996 #
4997 # - it reads packets in a loop
4998 # - when it finds a valid ClientHello, it returns
4999 # - now the handshake can proceed
5000 #
5001 # However, on older versions of OpenSSL, it did something "cleverer". The
5002 # way it worked is:
5003 #
5004 # - it "peeks" into the BIO to see the next packet without consuming it
5005 # - if *not* a valid ClientHello, then it reads the packet to consume it
5006 # and loops around
5007 # - if it *is* a valid ClientHello, it *leaves the packet in the BIO*, and
5008 # returns
5009 # - then the handshake finds the ClientHello in the BIO and reads it a
5010 # second time.
5011 #
5012 # I'm not sure exactly when this switched over. The OpenSSL v1.1.1 in
5013 # Ubuntu 18.04 has the old behavior. The OpenSSL v1.1.1 in Ubuntu 20.04 has
5014 # the new behavior. There doesn't seem to be any mention of this change in
5015 # the OpenSSL v1.1.1 changelog, but presumably it changed in some point
5016 # release or another. Presumably in 2025 or so there will be only new
5017 # OpenSSLs around we can delete this whole comment and the weird
5018 # workaround. If anyone is still using this library by then, which seems
5019 # both depressing and inevitable.
5020 #
5021 # Anyway, why do we care? The reason is that the old strategy has a
5022 # problem: the "peek" operation is only defined on "DGRAM BIOs", which are
5023 # a special type of object that is different from the more familiar "socket
5024 # BIOs" and "memory BIOs". If you *don't* have a DGRAM BIO, and you try to
5025 # peek into the BIO... then it silently degrades to a full-fledged "read"
5026 # operation that consumes the packet. Which is a problem if your algorithm
5027 # depends on leaving the packet in the BIO to be read again later.
5028 #
5029 # So on old OpenSSL, we have a problem:
5030 #
5031 # - we can't use a DGRAM BIO, because cryptography/pyopenssl don't wrap the
5032 # relevant APIs, nor should they.
5033 #
5034 # - if we use a socket BIO, then the first time DTLSv1_listen sees an
5035 # invalid packet (like for example... the challenge packet that *every
5036 # DTLS handshake starts with before the real ClientHello!*), it tries to
5037 # first "peek" it, and then "read" it. But since the first "peek"
5038 # consumes the packet, the second "read" ends up hanging or consuming
5039 # some unrelated packet, which is undesirable. So you can't even get to
5040 # the handshake stage successfully.
5041 #
5042 # - if we use a memory BIO, then DTLSv1_listen works OK on invalid packets
5043 # -- first the "peek" consumes them, and then it tries to "read" again to
5044 # consume them, which fails immediately, and OpenSSL ignores the failure.
5045 # So it works by accident. BUT, when we get a valid ClientHello, we have
5046 # a problem: DTLSv1_listen tries to "peek" it and then leave it in the
5047 # read BIO for do_handshake to consume. But instead "peek" consumes the
5048 # packet, so it's not there where do_handshake is expecting it, and the
5049 # handshake fails.
5050 #
5051 # Fortunately (if that's the word), we can work around the memory BIO
5052 # problem. (Which is good, because in real life probably all our users will
5053 # be using memory BIOs.) All we have to do is to save the valid ClientHello
5054 # before calling DTLSv1_listen, and then after it returns we push *a second
5055 # copy of it* of the packet memory BIO before calling do_handshake. This
5056 # fakes out OpenSSL and makes it think the "peek" operation worked
5057 # correctly, and we can go on with our lives.
5058 #
5059 # In fact, we push the second copy of the ClientHello unconditionally. On
5060 # new versions of OpenSSL, this is unnecessary, but harmless, because the
5061 # DTLS state machine treats it like a network hiccup that duplicated a
5062 # packet, which DTLS is robust against.
5063
5064 # Arbitrary number larger than any conceivable handshake volley.
5065 LARGE_BUFFER = 65536
5066
5067 def _test_handshake_and_data(self, srtp_profile: bytes | None) -> None:
5068 s_ctx = Context(DTLS_METHOD)
5069
5070 def generate_cookie(ssl: Connection) -> bytes:
5071 return b"xyzzy"
5072
5073 def verify_cookie(ssl: Connection, cookie: bytes) -> bool:
5074 return cookie == b"xyzzy"
5075
5076 s_ctx.set_cookie_generate_callback(generate_cookie)
5077 s_ctx.set_cookie_verify_callback(verify_cookie)
5078 s_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
5079 s_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
5080 s_ctx.set_options(OP_NO_QUERY_MTU)
5081 if srtp_profile is not None:
5082 s_ctx.set_tlsext_use_srtp(srtp_profile)
5083 s = Connection(s_ctx)
5084 s.set_accept_state()
5085
5086 c_ctx = Context(DTLS_METHOD)
5087 c_ctx.set_options(OP_NO_QUERY_MTU)
5088 if srtp_profile is not None:
5089 c_ctx.set_tlsext_use_srtp(srtp_profile)
5090 c = Connection(c_ctx)
5091 c.set_connect_state()
5092
5093 # These are mandatory, because openssl can't guess the MTU for a memory
5094 # bio and will produce a mysterious error if you make it try.
5095 c.set_ciphertext_mtu(1500)
5096 s.set_ciphertext_mtu(1500)
5097
5098 latest_client_hello = None
5099
5100 def pump_membio(
5101 label: str, source: Connection, sink: Connection
5102 ) -> bool:
5103 try:
5104 chunk = source.bio_read(self.LARGE_BUFFER)
5105 except WantReadError:
5106 return False
5107 # I'm not sure this check is needed, but I'm not sure it's *not*
5108 # needed either:
5109 if not chunk: # pragma: no cover
5110 return False
5111 # Gross hack: if this is a ClientHello, save it so we can find it
5112 # later. See giant comment above.
5113 try:
5114 # if ContentType == handshake and HandshakeType ==
5115 # client_hello:
5116 if chunk[0] == 22 and chunk[13] == 1:
5117 nonlocal latest_client_hello
5118 latest_client_hello = chunk
5119 except IndexError: # pragma: no cover
5120 pass
5121 print(f"{label}: {chunk.hex()}")
5122 sink.bio_write(chunk)
5123 return True
5124
5125 def pump() -> None:
5126 # Raises if there was no data to pump, to avoid infinite loops if
5127 # we aren't making progress.
5128 assert pump_membio("s -> c", s, c) or pump_membio("c -> s", c, s)
5129
5130 c_handshaking = True
5131 s_listening = True
5132 s_handshaking = False
5133 first = True
5134 while c_handshaking or s_listening or s_handshaking:
5135 if not first:
5136 pump()
5137 first = False
5138
5139 if c_handshaking:
5140 try:
5141 c.do_handshake()
5142 except WantReadError:
5143 pass
5144 else:
5145 c_handshaking = False
5146
5147 if s_listening:
5148 try:
5149 s.DTLSv1_listen()
5150 except WantReadError:
5151 pass
5152 else:
5153 s_listening = False
5154 s_handshaking = True
5155 # Write the duplicate ClientHello. See giant comment above.
5156 assert latest_client_hello is not None
5157 s.bio_write(latest_client_hello)
5158
5159 if s_handshaking:
5160 try:
5161 s.do_handshake()
5162 except WantReadError:
5163 pass
5164 else:
5165 s_handshaking = False
5166
5167 s.write(b"hello")
5168 pump()
5169 assert c.read(100) == b"hello"
5170 c.write(b"goodbye")
5171 pump()
5172 assert s.read(100) == b"goodbye"
5173
5174 # Check whether SRTP was negotiated
5175 if srtp_profile is not None:
5176 assert s.get_selected_srtp_profile() == srtp_profile
5177 assert c.get_selected_srtp_profile() == srtp_profile
5178 else:
5179 assert s.get_selected_srtp_profile() == b""
5180 assert c.get_selected_srtp_profile() == b""
5181
5182 # Check that the MTU set/query functions are doing *something*
5183 c.set_ciphertext_mtu(1000)
5184 assert 500 < c.get_cleartext_mtu() < 1000
5185 c.set_ciphertext_mtu(500)
5186 assert 0 < c.get_cleartext_mtu() < 500
5187
5188 @pytest.mark.skipif(
5189 OP_COOKIE_EXCHANGE is None,
5190 reason="DTLS cookie exchange not supported",
5191 )
5192 def test_it_works_at_all(self) -> None:
5193 self._test_handshake_and_data(srtp_profile=None)
5194
5195 @pytest.mark.skipif(
5196 OP_COOKIE_EXCHANGE is None,
5197 reason="DTLS cookie exchange not supported",
5198 )
5199 def test_it_works_with_srtp(self) -> None:
5200 self._test_handshake_and_data(srtp_profile=b"SRTP_AES128_CM_SHA1_80")
5201
5202 @pytest.mark.skipif(
5203 OP_COOKIE_EXCHANGE is None,
5204 reason="DTLS cookie exchange not supported",
5205 )
5206 def test_cookie_generate_too_long(self) -> None:
5207 s_ctx = Context(DTLS_METHOD)
5208
5209 def generate_cookie(ssl: Connection) -> bytes:
5210 return b"\x00" * 256
5211
5212 def verify_cookie(ssl: Connection, cookie: bytes) -> bool:
5213 return True
5214
5215 s_ctx.set_cookie_generate_callback(generate_cookie)
5216 s_ctx.set_cookie_verify_callback(verify_cookie)
5217 s_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
5218 s_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
5219 s_ctx.set_options(OP_NO_QUERY_MTU)
5220 s = Connection(s_ctx)
5221 s.set_accept_state()
5222
5223 c_ctx = Context(DTLS_METHOD)
5224 c_ctx.set_options(OP_NO_QUERY_MTU)
5225 c = Connection(c_ctx)
5226 c.set_connect_state()
5227
5228 c.set_ciphertext_mtu(1500)
5229 s.set_ciphertext_mtu(1500)
5230
5231 # Client sends ClientHello
5232 try:
5233 c.do_handshake()
5234 except SSL.WantReadError:
5235 pass
5236 chunk = c.bio_read(self.LARGE_BUFFER)
5237 s.bio_write(chunk)
5238
5239 # Server tries DTLSv1_listen, which triggers cookie generation.
5240 # The oversized cookie should raise ValueError.
5241 with pytest.raises(ValueError, match="Cookie too long"):
5242 s.DTLSv1_listen()
5243
5244 def test_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None:
5245 c_ctx = Context(DTLS_METHOD)
5246 c = Connection(c_ctx)
5247
5248 # No timeout before the handshake starts.
5249 assert c.DTLSv1_get_timeout() is None
5250 assert c.DTLSv1_handle_timeout() is False
5251
5252 # Start handshake and check there is data to send.
5253 c.set_connect_state()
5254 try:
5255 c.do_handshake()
5256 except SSL.WantReadError:
5257 pass
5258 assert c.bio_read(self.LARGE_BUFFER)
5259
5260 # There should now be an active timeout.
5261 seconds = c.DTLSv1_get_timeout()
5262 assert seconds is not None
5263
5264 # Handle the timeout and check there is data to send.
5265 time.sleep(seconds)
5266 assert c.DTLSv1_handle_timeout() is True
5267 assert c.bio_read(self.LARGE_BUFFER)
5268
5269 # After the maximum number of allowed timeouts is reached,
5270 # DTLSv1_handle_timeout will return -1.
5271 #
5272 # Testing this directly is prohibitively time consuming as the timeout
5273 # duration is doubled on each retry, so the best we can do is to mock
5274 # this condition.
5275 monkeypatch.setattr(_lib, "DTLSv1_handle_timeout", lambda x: -1)
5276
5277 with pytest.raises(Error):
5278 c.DTLSv1_handle_timeout()