(self)
| 4471 | @requires_tls_version('TLSv1_2') |
| 4472 | @unittest.skipUnless(ssl.HAS_PSK, 'TLS-PSK disabled on this OpenSSL build') |
| 4473 | def test_psk(self): |
| 4474 | psk = bytes.fromhex('deadbeef') |
| 4475 | |
| 4476 | client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 4477 | client_context.check_hostname = False |
| 4478 | client_context.verify_mode = ssl.CERT_NONE |
| 4479 | client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4480 | client_context.set_ciphers('PSK') |
| 4481 | client_context.set_psk_client_callback(lambda hint: (None, psk)) |
| 4482 | |
| 4483 | server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 4484 | server_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4485 | server_context.set_ciphers('PSK') |
| 4486 | server_context.set_psk_server_callback(lambda identity: psk) |
| 4487 | |
| 4488 | # correct PSK should connect |
| 4489 | server = ThreadedEchoServer(context=server_context) |
| 4490 | with server: |
| 4491 | with client_context.wrap_socket(socket.socket()) as s: |
| 4492 | s.connect((HOST, server.port)) |
| 4493 | |
| 4494 | # incorrect PSK should fail |
| 4495 | incorrect_psk = bytes.fromhex('cafebabe') |
| 4496 | client_context.set_psk_client_callback(lambda hint: (None, incorrect_psk)) |
| 4497 | server = ThreadedEchoServer(context=server_context) |
| 4498 | with server: |
| 4499 | with client_context.wrap_socket(socket.socket()) as s: |
| 4500 | with self.assertRaises(ssl.SSLError): |
| 4501 | s.connect((HOST, server.port)) |
| 4502 | |
| 4503 | # identity_hint and client_identity should be sent to the other side |
| 4504 | identity_hint = 'identity-hint' |
| 4505 | client_identity = 'client-identity' |
| 4506 | |
| 4507 | def client_callback(hint): |
| 4508 | self.assertEqual(hint, identity_hint) |
| 4509 | return client_identity, psk |
| 4510 | |
| 4511 | def server_callback(identity): |
| 4512 | self.assertEqual(identity, client_identity) |
| 4513 | return psk |
| 4514 | |
| 4515 | client_context.set_psk_client_callback(client_callback) |
| 4516 | server_context.set_psk_server_callback(server_callback, identity_hint) |
| 4517 | server = ThreadedEchoServer(context=server_context) |
| 4518 | with server: |
| 4519 | with client_context.wrap_socket(socket.socket()) as s: |
| 4520 | s.connect((HOST, server.port)) |
| 4521 | |
| 4522 | # adding client callback to server or vice versa raises an exception |
| 4523 | with self.assertRaisesRegex(ssl.SSLError, 'Cannot add PSK server callback'): |
| 4524 | client_context.set_psk_server_callback(server_callback, identity_hint) |
| 4525 | with self.assertRaisesRegex(ssl.SSLError, 'Cannot add PSK client callback'): |
| 4526 | server_context.set_psk_client_callback(client_callback) |
| 4527 | |
| 4528 | # test with UTF-8 identities |
| 4529 | identity_hint = '身份暗示' # Translation: "Identity hint" |
| 4530 | client_identity = '客户身份' # Translation: "Customer identity" |
nothing calls this directly
no test coverage detected