| 1 |
""" |
| 2 |
I/O library for `awscrt`. |
| 3 |
|
| 4 |
All networking in `awscrt` is asynchronous. |
| 5 |
Long-running event-loop threads are used for concurrency. |
| 6 |
""" |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
import _awscrt |
| 12 |
from awscrt import NativeResource |
| 13 |
from enum import IntEnum |
| 14 |
import threading |
| 15 |
from typing import Union |
| 16 |
|
| 17 |
|
| 18 |
class _CertificateSource(IntEnum): |
| 19 |
"""Certificate source types for mTLS authentication. |
| 20 |
|
| 21 |
Used by TlsContextOptions to track which factory method created the |
| 22 |
TLS configuration. The metrics reads this and encodes it as |
| 23 |
feature ID "I" in the metrics string. |
| 24 |
""" |
| 25 |
CERTIFICATE_FILES = 0 |
| 26 |
PKCS11 = 1 |
| 27 |
WINDOWS_CERT_STORE = 2 |
| 28 |
|
| 29 |
PKCS12_FILE = 4 |
| 30 |
|
| 31 |
|
| 32 |
class LogLevel(IntEnum): |
| 33 |
NoLogs = 0 |
| 34 |
Fatal = 1 |
| 35 |
Error = 2 |
| 36 |
Warn = 3 |
| 37 |
Info = 4 |
| 38 |
Debug = 5 |
| 39 |
Trace = 6 |
| 40 |
|
| 41 |
|
| 42 |
def init_logging(log_level, file_name): |
| 43 |
"""Initialize logging in `awscrt`. |
| 44 |
|
| 45 |
Args: |
| 46 |
log_level (LogLevel): Display messages of this importance and higher. |
| 47 |
file_name (str): Logging destination. To write to stdout or stderr pass |
| 48 |
'stdout' or 'stderr' as strings. Otherwise, a file path is assumed. |
| 49 |
""" |
| 50 |
assert log_level is not None |
| 51 |
assert file_name is not None |
| 52 |
|
| 53 |
_awscrt.init_logging(log_level, file_name) |
| 54 |
|
| 55 |
|
| 56 |
def set_log_level(log_level): |
| 57 |
"""Change the log level of `awscrt`. init_logging() must have been called |
| 58 |
before using this function or else an exception will be raised. |
| 59 |
|
| 60 |
Args: |
| 61 |
log_level (LogLevel): Display messages of this importance and higher. |
| 62 |
""" |
| 63 |
assert log_level is not None |
| 64 |
|
| 65 |
_awscrt.set_log_level(log_level) |
| 66 |
|
| 67 |
|
| 68 |
class EventLoopGroup(NativeResource): |
| 69 |
"""A collection of event-loops. |
| 70 |
|
| 71 |
An event-loop is a thread for doing async work, such as I/O. Classes that |
| 72 |
need to do async work will ask the EventLoopGroup for an event-loop to use. |
| 73 |
|
| 74 |
Args: |
| 75 |
num_threads (Optional[int]): Maximum number of event-loops to create. |
| 76 |
If unspecified, one is created for each processor on the machine. |
| 77 |
|
| 78 |
cpu_group (Optional[int]): Optional processor group to which all |
| 79 |
threads will be pinned. Useful for systems with non-uniform |
| 80 |
memory access (NUMA) nodes. If specified, the number of threads |
| 81 |
will be capped at the number of processors in the group. |
| 82 |
|
| 83 |
Attributes: |
| 84 |
shutdown_event (threading.Event): Signals when EventLoopGroup's threads |
| 85 |
have all finished shutting down. Shutdown begins when the |
| 86 |
EventLoopGroup object is destroyed. |
| 87 |
""" |
| 88 |
|
| 89 |
_static_event_loop_group = None |
| 90 |
_static_event_loop_group_lock = threading.Lock() |
| 91 |
__slots__ = ('shutdown_event') |
| 92 |
|
| 93 |
def __init__(self, num_threads=None, cpu_group=None): |
| 94 |
super().__init__() |
| 95 |
|
| 96 |
if num_threads is None: |
| 97 |
|
| 98 |
num_threads = 0 |
| 99 |
|
| 100 |
if cpu_group is None: |
| 101 |
is_pinned = False |
| 102 |
cpu_group = 0 |
| 103 |
else: |
| 104 |
is_pinned = True |
| 105 |
|
| 106 |
shutdown_event = threading.Event() |
| 107 |
|
| 108 |
def on_shutdown(): |
| 109 |
shutdown_event.set() |
| 110 |
|
| 111 |
self.shutdown_event = shutdown_event |
| 112 |
self._binding = _awscrt.event_loop_group_new(num_threads, is_pinned, cpu_group, on_shutdown) |
| 113 |
|
| 114 |
@staticmethod |
| 115 |
def get_or_create_static_default(): |
| 116 |
with EventLoopGroup._static_event_loop_group_lock: |
| 117 |
if EventLoopGroup._static_event_loop_group is None: |
| 118 |
EventLoopGroup._static_event_loop_group = EventLoopGroup() |
| 119 |
return EventLoopGroup._static_event_loop_group |
| 120 |
|
| 121 |
@staticmethod |
| 122 |
def release_static_default(): |
| 123 |
with EventLoopGroup._static_event_loop_group_lock: |
| 124 |
EventLoopGroup._static_event_loop_group = None |
| 125 |
|
| 126 |
|
| 127 |
class HostResolverBase(NativeResource): |
| 128 |
"""DNS host resolver.""" |
| 129 |
__slots__ = () |
| 130 |
|
| 131 |
|
| 132 |
class DefaultHostResolver(HostResolverBase): |
| 133 |
"""Default DNS host resolver. |
| 134 |
|
| 135 |
Args: |
| 136 |
event_loop_group (EventLoopGroup): EventLoopGroup to use. |
| 137 |
max_hosts(int): Max host names to cache. |
| 138 |
""" |
| 139 |
|
| 140 |
_static_host_resolver = None |
| 141 |
_static_host_resolver_lock = threading.Lock() |
| 142 |
__slots__ = () |
| 143 |
|
| 144 |
def __init__(self, event_loop_group, max_hosts=16): |
| 145 |
assert isinstance(event_loop_group, EventLoopGroup) |
| 146 |
|
| 147 |
super().__init__() |
| 148 |
self._binding = _awscrt.host_resolver_new_default(max_hosts, event_loop_group) |
| 149 |
|
| 150 |
@staticmethod |
| 151 |
def get_or_create_static_default(): |
| 152 |
with DefaultHostResolver._static_host_resolver_lock: |
| 153 |
if DefaultHostResolver._static_host_resolver is None: |
| 154 |
DefaultHostResolver._static_host_resolver = DefaultHostResolver( |
| 155 |
EventLoopGroup.get_or_create_static_default()) |
| 156 |
return DefaultHostResolver._static_host_resolver |
| 157 |
|
| 158 |
@staticmethod |
| 159 |
def release_static_default(): |
| 160 |
with DefaultHostResolver._static_host_resolver_lock: |
| 161 |
DefaultHostResolver._static_host_resolver = None |
| 162 |
|
| 163 |
|
| 164 |
class ClientBootstrap(NativeResource): |
| 165 |
"""Handles creation and setup of client socket connections. |
| 166 |
|
| 167 |
Args: |
| 168 |
event_loop_group (EventLoopGroup): EventLoopGroup to use. |
| 169 |
host_resolver (HostResolverBase): DNS host resolver to use. |
| 170 |
|
| 171 |
Attributes: |
| 172 |
shutdown_event (threading.Event): Signals when the ClientBootstrap's |
| 173 |
internal resources finish shutting down. |
| 174 |
Shutdown begins when the ClientBootstrap object is destroyed. |
| 175 |
""" |
| 176 |
|
| 177 |
_static_client_bootstrap = None |
| 178 |
_static_client_bootstrap_lock = threading.Lock() |
| 179 |
__slots__ = ('shutdown_event') |
| 180 |
|
| 181 |
def __init__(self, event_loop_group, host_resolver): |
| 182 |
assert isinstance(event_loop_group, EventLoopGroup) |
| 183 |
assert isinstance(host_resolver, HostResolverBase) |
| 184 |
|
| 185 |
super().__init__() |
| 186 |
|
| 187 |
shutdown_event = threading.Event() |
| 188 |
|
| 189 |
def on_shutdown(): |
| 190 |
shutdown_event.set() |
| 191 |
|
| 192 |
self.shutdown_event = shutdown_event |
| 193 |
self._binding = _awscrt.client_bootstrap_new(event_loop_group, host_resolver, on_shutdown) |
| 194 |
|
| 195 |
@staticmethod |
| 196 |
def get_or_create_static_default(): |
| 197 |
with ClientBootstrap._static_client_bootstrap_lock: |
| 198 |
if ClientBootstrap._static_client_bootstrap is None: |
| 199 |
ClientBootstrap._static_client_bootstrap = ClientBootstrap( |
| 200 |
EventLoopGroup.get_or_create_static_default(), |
| 201 |
DefaultHostResolver.get_or_create_static_default()) |
| 202 |
return ClientBootstrap._static_client_bootstrap |
| 203 |
|
| 204 |
@staticmethod |
| 205 |
def release_static_default(): |
| 206 |
with ClientBootstrap._static_client_bootstrap_lock: |
| 207 |
ClientBootstrap._static_client_bootstrap = None |
| 208 |
|
| 209 |
|
| 210 |
def _read_binary_file(filepath): |
| 211 |
with open(filepath, mode='rb') as fh: |
| 212 |
contents = fh.read() |
| 213 |
return contents |
| 214 |
|
| 215 |
|
| 216 |
class SocketDomain(IntEnum): |
| 217 |
IPv4 = 0 |
| 218 |
IPv6 = 1 |
| 219 |
Local = 2 |
| 220 |
|
| 221 |
|
| 222 |
class SocketType(IntEnum): |
| 223 |
Stream = 0 |
| 224 |
"""A streaming socket sends reliable messages over a two-way connection. |
| 225 |
This means TCP when used with `SocketDomain.IPv4/6`, |
| 226 |
and Unix domain sockets when used with `SocketDomain.Local`""" |
| 227 |
|
| 228 |
DGram = 1 |
| 229 |
"""A datagram socket is connectionless and sends unreliable messages. |
| 230 |
This means UDP when used with `SocketDomain.IPv4/6`. |
| 231 |
`SocketDomain.Local` is not compatible with `DGram` """ |
| 232 |
|
| 233 |
|
| 234 |
class SocketOptions: |
| 235 |
"""Socket options. |
| 236 |
|
| 237 |
Attributes: |
| 238 |
domain (SocketDomain): Socket domain. |
| 239 |
type (SocketType): Socket type. |
| 240 |
connect_timeout_ms (int): Connection timeout, in milliseconds. |
| 241 |
keep_alive (bool): If set True, periodically transmit keepalive messages |
| 242 |
for detecting a disconnected peer. |
| 243 |
keep_alive_timeout_secs (int): Duration, in seconds, between keepalive |
| 244 |
transmissions in idle condition. If 0, then a default value is used. |
| 245 |
keep_alive_interval_secs (int): Duration, in seconds, between keepalive |
| 246 |
retransmissions, if acknowledgement of previous keepalive transmission |
| 247 |
is not received. If 0, then a default value is used. |
| 248 |
keep_alive_max_probes (int): If set, sets the number of keepalive probes |
| 249 |
allowed to fail before a connection is considered lost. |
| 250 |
""" |
| 251 |
|
| 252 |
__slots__ = ( |
| 253 |
'domain', 'type', 'connect_timeout_ms', 'keep_alive', |
| 254 |
'keep_alive_timeout_secs', 'keep_alive_interval_secs', 'keep_alive_max_probes' |
| 255 |
) |
| 256 |
|
| 257 |
def __init__(self): |
| 258 |
for slot in self.__slots__: |
| 259 |
setattr(self, slot, None) |
| 260 |
|
| 261 |
self.domain = SocketDomain.IPv6 |
| 262 |
self.type = SocketType.Stream |
| 263 |
self.connect_timeout_ms = 5000 |
| 264 |
self.keep_alive = False |
| 265 |
self.keep_alive_interval_secs = 0 |
| 266 |
self.keep_alive_timeout_secs = 0 |
| 267 |
self.keep_alive_max_probes = 0 |
| 268 |
|
| 269 |
|
| 270 |
class TlsVersion(IntEnum): |
| 271 |
SSLv3 = 0 |
| 272 |
TLSv1 = 1 |
| 273 |
TLSv1_1 = 2 |
| 274 |
TLSv1_2 = 3 |
| 275 |
TLSv1_3 = 4 |
| 276 |
DEFAULT = 128 |
| 277 |
|
| 278 |
|
| 279 |
class TlsCipherPref(IntEnum): |
| 280 |
"""TLS Cipher Preference. |
| 281 |
|
| 282 |
Each TlsCipherPref represents an ordered list of TLS Ciphers to use when negotiating a TLS Connection. At |
| 283 |
present, the ability to configure arbitrary orderings of TLS Ciphers is not allowed, and only a curated list of |
| 284 |
vetted TlsCipherPref's are exposed.""" |
| 285 |
|
| 286 |
DEFAULT = 0 |
| 287 |
"""The underlying platform's default TLS Cipher Preference ordering. This is usually the best option, as it will be |
| 288 |
automatically updated as the underlying OS or platform changes, and will always be supported on all platforms.""" |
| 289 |
|
| 290 |
PQ_TLSv1_0_2021_05 = 6 |
| 291 |
"""A TLS Cipher Preference ordering that supports TLS 1.0 through TLS 1.3, and has Kyber Round 3 as its highest |
| 292 |
priority post-quantum key exchange algorithm. PQ algorithms in this preference list will always be used in hybrid |
| 293 |
mode, and will be combined with a classical ECDHE key exchange that is performed in addition to the PQ key |
| 294 |
exchange. This preference makes a best-effort to negotiate a PQ algorithm, but if the peer does not support any |
| 295 |
PQ algorithms the TLS connection will fall back to a single classical algorithm for key exchange (such as ECDHE |
| 296 |
or RSA). |
| 297 |
|
| 298 |
NIST has announced that they plan to eventually standardize Kyber. However, the NIST standardization process might |
| 299 |
introduce minor changes that could cause the final Kyber standard to differ from the Kyber Round 3 implementation |
| 300 |
available in this preference list.""" |
| 301 |
|
| 302 |
PQ_DEFAULT = 8 |
| 303 |
"""Recommended default policy with post-quantum algorithm support. This policy may change over time.""" |
| 304 |
|
| 305 |
TLSv1_2_2025_07 = 9 |
| 306 |
"""A TLS Cipher Preference requiring TLS 1.2+ with FIPS compliance and perfect forward secrecy. This security policy |
| 307 |
is based on the AWS-CRT-SDK-TLSv1.2-2023 s2n TLS policy with enhanced security restrictions. It supports AES-GCM and |
| 308 |
ECDHE cipher suites with ECDSA and RSA-PSS signature schemes, and uses NIST P-256 and P-384 curves only.""" |
| 309 |
|
| 310 |
def is_supported(self): |
| 311 |
"""Return whether this Cipher Preference is available in the underlying platform's TLS implementation""" |
| 312 |
return _awscrt.is_tls_cipher_supported(self.value) |
| 313 |
|
| 314 |
|
| 315 |
class TlsContextOptions: |
| 316 |
"""Options to create a TLS context. |
| 317 |
|
| 318 |
The static `TlsContextOptions.create_X()` methods provide common TLS configurations. |
| 319 |
A default-initialized TlsContextOptions has `verify_peer` set True. |
| 320 |
|
| 321 |
Attributes: |
| 322 |
min_tls_ver (TlsVersion): Minimum TLS version to use. |
| 323 |
System defaults are used by default. |
| 324 |
cipher_pref (TlsCipherPref): The TLS Cipher Preference to use. System defaults are used by default. |
| 325 |
verify_peer (bool): Whether to validate the peer's x.509 certificate. |
| 326 |
no_certificate_revocation (bool): Set to true to disable certificate revocation checking during TLS negotiation. |
| 327 |
On Windows (SChannel), this prevents the TLS handshake from making outbound network calls |
| 328 |
to CRL/OCSP revocation endpoints, which can block for minutes when the endpoints are unreachable |
| 329 |
(e.g., in private subnets without internet access). |
| 330 |
On Linux (s2n), this disables validation of OCSP stapled responses provided by the server. |
| 331 |
On Apple platforms, this is a no-op as revocation checking is not enabled by default. |
| 332 |
alpn_list (Optional[List[str]]): If set, names to use in Application Layer |
| 333 |
Protocol Negotiation (ALPN). ALPN is not supported on all systems, |
| 334 |
see :meth:`is_alpn_available()`. This can be customized per connection, |
| 335 |
via :meth:`TlsConnectionOptions.set_alpn_list()`. |
| 336 |
""" |
| 337 |
__slots__ = ( |
| 338 |
'min_tls_ver', |
| 339 |
'ca_dirpath', |
| 340 |
'ca_buffer', |
| 341 |
'cipher_pref', |
| 342 |
'alpn_list', |
| 343 |
'certificate_buffer', |
| 344 |
'private_key_buffer', |
| 345 |
'pkcs12_filepath', |
| 346 |
'pkcs12_password', |
| 347 |
'verify_peer', |
| 348 |
'no_certificate_revocation', |
| 349 |
'_pkcs11_lib', |
| 350 |
'_pkcs11_user_pin', |
| 351 |
'_pkcs11_slot_id', |
| 352 |
'_pkcs11_token_label', |
| 353 |
'_pkcs11_private_key_label', |
| 354 |
'_pkcs11_cert_file_path', |
| 355 |
'_pkcs11_cert_file_contents', |
| 356 |
'_windows_cert_store_path', |
| 357 |
'_certificate_source', |
| 358 |
) |
| 359 |
|
| 360 |
def __init__(self): |
| 361 |
|
| 362 |
for slot in self.__slots__: |
| 363 |
setattr(self, slot, None) |
| 364 |
|
| 365 |
self.min_tls_ver = TlsVersion.DEFAULT |
| 366 |
self.cipher_pref = TlsCipherPref.DEFAULT |
| 367 |
self.verify_peer = True |
| 368 |
self.no_certificate_revocation = False |
| 369 |
|
| 370 |
@staticmethod |
| 371 |
def create_client_with_mtls_from_path(cert_filepath, pk_filepath): |
| 372 |
""" |
| 373 |
Create options configured for use with mutual TLS in client mode. |
| 374 |
|
| 375 |
Both files are treated as PKCS #7 PEM armored. |
| 376 |
They are loaded from disk and stored in buffers internally. |
| 377 |
|
| 378 |
Args: |
| 379 |
cert_filepath (str): Path to certificate file. |
| 380 |
pk_filepath (str): Path to private key file. |
| 381 |
|
| 382 |
Returns: |
| 383 |
TlsContextOptions: |
| 384 |
""" |
| 385 |
|
| 386 |
assert isinstance(cert_filepath, str) |
| 387 |
assert isinstance(pk_filepath, str) |
| 388 |
|
| 389 |
cert_buffer = _read_binary_file(cert_filepath) |
| 390 |
key_buffer = _read_binary_file(pk_filepath) |
| 391 |
|
| 392 |
return TlsContextOptions.create_client_with_mtls(cert_buffer, key_buffer) |
| 393 |
|
| 394 |
@staticmethod |
| 395 |
def create_client_with_mtls(cert_buffer, key_buffer): |
| 396 |
""" |
| 397 |
Create options configured for use with mutual TLS in client mode. |
| 398 |
|
| 399 |
Both buffers are treated as PKCS #7 PEM armored. |
| 400 |
|
| 401 |
Args: |
| 402 |
cert_buffer (bytes): Certificate contents |
| 403 |
key_buffer (bytes): Private key contents. |
| 404 |
|
| 405 |
Returns: |
| 406 |
TlsContextOptions: |
| 407 |
""" |
| 408 |
assert isinstance(cert_buffer, bytes) |
| 409 |
assert isinstance(key_buffer, bytes) |
| 410 |
|
| 411 |
opt = TlsContextOptions() |
| 412 |
opt.certificate_buffer = cert_buffer |
| 413 |
opt.private_key_buffer = key_buffer |
| 414 |
opt._certificate_source = _CertificateSource.CERTIFICATE_FILES |
| 415 |
|
| 416 |
return opt |
| 417 |
|
| 418 |
@staticmethod |
| 419 |
def create_client_with_mtls_pkcs11(*, |
| 420 |
pkcs11_lib: 'Pkcs11Lib', |
| 421 |
user_pin: Union[str, None], |
| 422 |
slot_id: int = None, |
| 423 |
token_label: str = None, |
| 424 |
private_key_label: str = None, |
| 425 |
cert_file_path: str = None, |
| 426 |
cert_file_contents=None): |
| 427 |
""" |
| 428 |
Create options configured for use with mutual TLS in client mode, |
| 429 |
using a PKCS#11 library for private key operations. |
| 430 |
|
| 431 |
NOTE: This configuration only works on Unix devices. |
| 432 |
|
| 433 |
Keyword Args: |
| 434 |
pkcs11_lib (Pkcs11Lib): Use this PKCS#11 library |
| 435 |
|
| 436 |
user_pin (str): User PIN, for logging into the PKCS#11 token. |
| 437 |
Pass `None` to log into a token with a "protected authentication path". |
| 438 |
|
| 439 |
slot_id (Optional[int]): ID of slot containing PKCS#11 token. |
| 440 |
If not specified, the token will be chosen based on other criteria (such as token label). |
| 441 |
|
| 442 |
token_label (Optional[str]): Label of the PKCS#11 token to use. |
| 443 |
If not specified, the token will be chosen based on other criteria (such as slot ID). |
| 444 |
|
| 445 |
private_key_label (Optional[str]): Label of private key object on PKCS#11 token. |
| 446 |
If not specified, the key will be chosen based on other criteria |
| 447 |
(such as being the only available private key on the token). |
| 448 |
|
| 449 |
cert_file_path (Optional[str]): Use this X.509 certificate (path to file on disk). |
| 450 |
The certificate must be PEM-formatted. The certificate may be |
| 451 |
specified by other means instead (ex: `cert_file_contents`) |
| 452 |
|
| 453 |
cert_file_contents (Optional[Union[str, bytes, bytearray]]): |
| 454 |
Use this X.509 certificate (contents in memory). |
| 455 |
The certificate must be PEM-formatted. The certificate may be |
| 456 |
specified by other means instead (ex: `cert_file_path`) |
| 457 |
""" |
| 458 |
|
| 459 |
assert isinstance(pkcs11_lib, Pkcs11Lib) |
| 460 |
assert isinstance(user_pin, str) or user_pin is None |
| 461 |
assert isinstance(slot_id, int) or slot_id is None |
| 462 |
assert isinstance(token_label, str) or token_label is None |
| 463 |
assert isinstance(private_key_label, str) or private_key_label is None |
| 464 |
assert isinstance(cert_file_path, str) or cert_file_path is None |
| 465 |
|
| 466 |
|
| 467 |
opt = TlsContextOptions() |
| 468 |
opt._pkcs11_lib = pkcs11_lib |
| 469 |
opt._pkcs11_user_pin = user_pin |
| 470 |
opt._pkcs11_slot_id = slot_id |
| 471 |
opt._pkcs11_token_label = token_label |
| 472 |
opt._pkcs11_private_key_label = private_key_label |
| 473 |
opt._pkcs11_cert_file_path = cert_file_path |
| 474 |
opt._pkcs11_cert_file_contents = cert_file_contents |
| 475 |
opt._certificate_source = _CertificateSource.PKCS11 |
| 476 |
return opt |
| 477 |
|
| 478 |
@staticmethod |
| 479 |
def create_client_with_mtls_pkcs12(pkcs12_filepath, pkcs12_password): |
| 480 |
""" |
| 481 |
Create options configured for use with mutual TLS in client mode. |
| 482 |
|
| 483 |
NOTE: This configuration only works on Apple devices. |
| 484 |
|
| 485 |
Args: |
| 486 |
pkcs12_filepath (str): Path to PKCS #12 file. |
| 487 |
The file is loaded from disk and stored internally. |
| 488 |
pkcs12_password (str): Password to PKCS #12 file. |
| 489 |
|
| 490 |
Returns: |
| 491 |
TlsContextOptions: |
| 492 |
""" |
| 493 |
|
| 494 |
assert isinstance(pkcs12_filepath, str) |
| 495 |
assert isinstance(pkcs12_password, str) |
| 496 |
|
| 497 |
opt = TlsContextOptions() |
| 498 |
opt.pkcs12_filepath = pkcs12_filepath |
| 499 |
opt.pkcs12_password = pkcs12_password |
| 500 |
opt._certificate_source = _CertificateSource.PKCS12_FILE |
| 501 |
return opt |
| 502 |
|
| 503 |
@staticmethod |
| 504 |
def create_client_with_mtls_windows_cert_store_path(cert_path): |
| 505 |
""" |
| 506 |
Create options configured for use with mutual TLS in client mode, |
| 507 |
using a certificate in a Windows certificate store. |
| 508 |
|
| 509 |
NOTE: This configuration only works on Windows devices. |
| 510 |
|
| 511 |
Args: |
| 512 |
cert_path (str): Path to certificate in a Windows certificate store. |
| 513 |
The path must use backslashes and end with the certificate's thumbprint. |
| 514 |
Example: ``CurrentUser\\MY\\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6`` |
| 515 |
|
| 516 |
Returns: |
| 517 |
TlsContextOptions |
| 518 |
""" |
| 519 |
assert isinstance(cert_path, str) |
| 520 |
opt = TlsContextOptions() |
| 521 |
opt._windows_cert_store_path = cert_path |
| 522 |
opt._certificate_source = _CertificateSource.WINDOWS_CERT_STORE |
| 523 |
return opt |
| 524 |
|
| 525 |
@staticmethod |
| 526 |
def create_server_from_path(cert_filepath, pk_filepath): |
| 527 |
""" |
| 528 |
Create options configured for use in server mode. |
| 529 |
|
| 530 |
Both files are treated as PKCS #7 PEM armored. |
| 531 |
They are loaded from disk and stored in buffers internally. |
| 532 |
|
| 533 |
Args: |
| 534 |
cert_filepath (str): Path to certificate file. |
| 535 |
pk_filepath (str): Path to private key file. |
| 536 |
|
| 537 |
Returns: |
| 538 |
TlsContextOptions: |
| 539 |
""" |
| 540 |
|
| 541 |
assert isinstance(cert_filepath, str) |
| 542 |
assert isinstance(pk_filepath, str) |
| 543 |
|
| 544 |
cert_buffer = _read_binary_file(cert_filepath) |
| 545 |
key_buffer = _read_binary_file(pk_filepath) |
| 546 |
|
| 547 |
return TlsContextOptions.create_server(cert_buffer, key_buffer) |
| 548 |
|
| 549 |
@staticmethod |
| 550 |
def create_server(cert_buffer, key_buffer): |
| 551 |
""" |
| 552 |
Create options configured for use in server mode. |
| 553 |
|
| 554 |
Both buffers are treated as PKCS #7 PEM armored. |
| 555 |
|
| 556 |
Args: |
| 557 |
cert_buffer (bytes): Certificate contents. |
| 558 |
key_buffer (bytes): Private key contents. |
| 559 |
|
| 560 |
Returns: |
| 561 |
TlsContextOptions: |
| 562 |
""" |
| 563 |
assert isinstance(cert_buffer, bytes) |
| 564 |
assert isinstance(key_buffer, bytes) |
| 565 |
|
| 566 |
opt = TlsContextOptions() |
| 567 |
opt.certificate_buffer = cert_buffer |
| 568 |
opt.private_key_buffer = key_buffer |
| 569 |
opt.verify_peer = False |
| 570 |
return opt |
| 571 |
|
| 572 |
@staticmethod |
| 573 |
def create_server_pkcs12(pkcs12_filepath, pkcs12_password): |
| 574 |
""" |
| 575 |
Create options configured for use in server mode. |
| 576 |
|
| 577 |
NOTE: This configuration only works on Apple devices. |
| 578 |
|
| 579 |
Args: |
| 580 |
pkcs12_filepath (str): Path to PKCS #12 file. |
| 581 |
pkcs12_password (str): Password to PKCS #12 file. |
| 582 |
|
| 583 |
Returns: |
| 584 |
TlsContextOptions: |
| 585 |
""" |
| 586 |
|
| 587 |
assert isinstance(pkcs12_filepath, str) |
| 588 |
assert isinstance(pkcs12_password, str) |
| 589 |
|
| 590 |
opt = TlsContextOptions() |
| 591 |
opt.pkcs12_filepath = pkcs12_filepath |
| 592 |
opt.pkcs12_password = pkcs12_password |
| 593 |
opt.verify_peer = False |
| 594 |
return opt |
| 595 |
|
| 596 |
def override_default_trust_store_from_path(self, ca_dirpath=None, ca_filepath=None): |
| 597 |
"""Override default trust store. |
| 598 |
|
| 599 |
Args: |
| 600 |
ca_dirpath (Optional[str]): Path to directory containing |
| 601 |
trusted certificates, which will overrides the default trust store. |
| 602 |
Only supported on Unix. |
| 603 |
ca_filepath(Optional[str]): Path to file containing PEM armored chain |
| 604 |
of trusted CA certificates. |
| 605 |
""" |
| 606 |
|
| 607 |
assert isinstance(ca_dirpath, str) or ca_dirpath is None |
| 608 |
assert isinstance(ca_filepath, str) or ca_filepath is None |
| 609 |
|
| 610 |
if ca_filepath: |
| 611 |
ca_buffer = _read_binary_file(ca_filepath) |
| 612 |
self.override_default_trust_store(ca_buffer) |
| 613 |
|
| 614 |
self.ca_dirpath = ca_dirpath |
| 615 |
|
| 616 |
def override_default_trust_store(self, rootca_buffer): |
| 617 |
"""Override default trust store. |
| 618 |
|
| 619 |
Args: |
| 620 |
rootca_buffer (bytes): PEM armored chain of trusted CA certificates. |
| 621 |
""" |
| 622 |
assert isinstance(rootca_buffer, bytes) |
| 623 |
|
| 624 |
self.ca_buffer = rootca_buffer |
| 625 |
|
| 626 |
|
| 627 |
class ClientTlsContext(NativeResource): |
| 628 |
"""Client TLS context. |
| 629 |
|
| 630 |
A context is expensive, but can be used for the lifetime of the application |
| 631 |
by all outgoing connections that wish to use the same TLS configuration. |
| 632 |
|
| 633 |
Args: |
| 634 |
options (TlsContextOptions): Configuration options. |
| 635 |
""" |
| 636 |
__slots__ = ('_min_tls_ver', '_cipher_pref', '_certificate_source') |
| 637 |
|
| 638 |
def __init__(self, options): |
| 639 |
assert isinstance(options, TlsContextOptions) |
| 640 |
|
| 641 |
super().__init__() |
| 642 |
|
| 643 |
self._min_tls_ver = options.min_tls_ver |
| 644 |
self._cipher_pref = options.cipher_pref |
| 645 |
self._certificate_source = options._certificate_source |
| 646 |
|
| 647 |
self._binding = _awscrt.client_tls_ctx_new( |
| 648 |
options.min_tls_ver.value, |
| 649 |
options.cipher_pref.value, |
| 650 |
options.ca_dirpath, |
| 651 |
options.ca_buffer, |
| 652 |
_alpn_list_to_str(options.alpn_list), |
| 653 |
options.certificate_buffer, |
| 654 |
options.private_key_buffer, |
| 655 |
options.pkcs12_filepath, |
| 656 |
options.pkcs12_password, |
| 657 |
options.verify_peer, |
| 658 |
options.no_certificate_revocation, |
| 659 |
options._pkcs11_lib, |
| 660 |
options._pkcs11_user_pin, |
| 661 |
options._pkcs11_slot_id, |
| 662 |
options._pkcs11_token_label, |
| 663 |
options._pkcs11_private_key_label, |
| 664 |
options._pkcs11_cert_file_path, |
| 665 |
options._pkcs11_cert_file_contents, |
| 666 |
options._windows_cert_store_path, |
| 667 |
) |
| 668 |
|
| 669 |
def new_connection_options(self): |
| 670 |
"""Create a :class:`TlsConnectionOptions` that makes use of this TLS context. |
| 671 |
|
| 672 |
Returns: |
| 673 |
TlsConnectionOptions: |
| 674 |
""" |
| 675 |
return TlsConnectionOptions(self) |
| 676 |
|
| 677 |
|
| 678 |
class TlsConnectionOptions(NativeResource): |
| 679 |
"""Connection-specific TLS options. |
| 680 |
|
| 681 |
Note that, while a TLS context is an expensive object, a :class:`TlsConnectionOptions` is cheap. |
| 682 |
|
| 683 |
Args: |
| 684 |
tls_ctx (ClientTlsContext): TLS context. A context can be shared by many connections. |
| 685 |
|
| 686 |
Attributes: |
| 687 |
tls_ctx (ClientTlsContext): TLS context. |
| 688 |
""" |
| 689 |
__slots__ = ('tls_ctx') |
| 690 |
|
| 691 |
def __init__(self, tls_ctx): |
| 692 |
assert isinstance(tls_ctx, ClientTlsContext) |
| 693 |
|
| 694 |
super().__init__() |
| 695 |
self.tls_ctx = tls_ctx |
| 696 |
self._binding = _awscrt.tls_connections_options_new_from_ctx(tls_ctx) |
| 697 |
|
| 698 |
def set_alpn_list(self, alpn_list): |
| 699 |
"""Set names to use in Application Layer Protocol Negotiation (ALPN). |
| 700 |
|
| 701 |
This overrides any ALPN list on the TLS context, see :attr:`TlsContextOptions.alpn_list`. |
| 702 |
ALPN is not supported on all systems, see :meth:`is_alpn_available()`. |
| 703 |
|
| 704 |
Args: |
| 705 |
alpn_list (List[str]): List of protocol names. |
| 706 |
""" |
| 707 |
_awscrt.tls_connection_options_set_alpn_list(self, _alpn_list_to_str(alpn_list)) |
| 708 |
|
| 709 |
def set_server_name(self, server_name): |
| 710 |
"""Set server name. |
| 711 |
|
| 712 |
Sets name for TLS Server Name Indication (SNI). |
| 713 |
Name is also used for x.509 validation. |
| 714 |
|
| 715 |
Args: |
| 716 |
server_name (str): Server name. |
| 717 |
""" |
| 718 |
_awscrt.tls_connection_options_set_server_name(self, server_name) |
| 719 |
|
| 720 |
|
| 721 |
def _alpn_list_to_str(alpn_list): |
| 722 |
""" |
| 723 |
Transform ['h2', 'http/1.1'] -> "h2;http/1.1" |
| 724 |
None is returned if list is None or empty |
| 725 |
""" |
| 726 |
if alpn_list: |
| 727 |
assert not isinstance(alpn_list, str) |
| 728 |
return ';'.join(alpn_list) |
| 729 |
return None |
| 730 |
|
| 731 |
|
| 732 |
def is_alpn_available(): |
| 733 |
"""Returns True if Application Layer Protocol Negotiation (ALPN) |
| 734 |
is supported on this system.""" |
| 735 |
return _awscrt.is_alpn_available() |
| 736 |
|
| 737 |
|
| 738 |
class InputStream(NativeResource): |
| 739 |
"""InputStream allows `awscrt` native code to read from Python binary I/O classes. |
| 740 |
|
| 741 |
Args: |
| 742 |
stream (io.IOBase): Python binary I/O stream to wrap. |
| 743 |
""" |
| 744 |
__slots__ = ('_stream') |
| 745 |
|
| 746 |
|
| 747 |
def __init__(self, stream): |
| 748 |
|
| 749 |
|
| 750 |
if not callable(getattr(stream, 'read', None)): |
| 751 |
raise TypeError('I/O stream type expected') |
| 752 |
assert not isinstance(stream, InputStream) |
| 753 |
|
| 754 |
super().__init__() |
| 755 |
self._stream = stream |
| 756 |
self._binding = _awscrt.input_stream_new(self) |
| 757 |
|
| 758 |
def _read_into_memoryview(self, m): |
| 759 |
|
| 760 |
|
| 761 |
try: |
| 762 |
|
| 763 |
if hasattr(self._stream, 'readinto1'): |
| 764 |
return self._stream.readinto1(m) |
| 765 |
if hasattr(self._stream, 'readinto'): |
| 766 |
return self._stream.readinto(m) |
| 767 |
|
| 768 |
if hasattr(self._stream, 'read1'): |
| 769 |
data = self._stream.read1(len(m)) |
| 770 |
else: |
| 771 |
data = self._stream.read(len(m)) |
| 772 |
n = len(data) |
| 773 |
m[:n] = data |
| 774 |
return n |
| 775 |
except BlockingIOError: |
| 776 |
return None |
| 777 |
|
| 778 |
def _seek(self, offset, whence): |
| 779 |
return self._stream.seek(offset, whence) |
| 780 |
|
| 781 |
@classmethod |
| 782 |
def wrap(cls, stream, allow_none=False): |
| 783 |
""" |
| 784 |
Given some stream type, returns an :class:`InputStream`. |
| 785 |
|
| 786 |
Args: |
| 787 |
stream (Union[io.IOBase, InputStream, None]): Binary I/O stream to wrap. |
| 788 |
allow_none (bool): Whether to allow `stream` to be None. |
| 789 |
If False (default), and `stream` is None, an exception is raised. |
| 790 |
|
| 791 |
Returns: |
| 792 |
Union[InputStream, None]: If `stream` is already an :class:`InputStream`, it is returned. |
| 793 |
Otherwise, an :class:`InputStream` which wraps the `stream` is returned. |
| 794 |
If `allow_none` is True, and `stream` is None, then None is returned. |
| 795 |
""" |
| 796 |
if stream is None and allow_none: |
| 797 |
return None |
| 798 |
if isinstance(stream, InputStream): |
| 799 |
return stream |
| 800 |
return cls(stream) |
| 801 |
|
| 802 |
|
| 803 |
class Pkcs11Lib(NativeResource): |
| 804 |
""" |
| 805 |
Handle to a loaded PKCS#11 library. |
| 806 |
|
| 807 |
For most use cases, a single instance of :class:`Pkcs11Lib` should be used for the |
| 808 |
lifetime of your application. |
| 809 |
|
| 810 |
Keyword Args: |
| 811 |
file (str): Path to PKCS#11 library. |
| 812 |
behavior (Optional[InitializeFinalizeBehavior]): |
| 813 |
Specifies how `C_Initialize()` and `C_Finalize()` will be called |
| 814 |
on the PKCS#11 library (default is :attr:`InitializeFinalizeBehavior.DEFAULT`) |
| 815 |
""" |
| 816 |
|
| 817 |
class InitializeFinalizeBehavior(IntEnum): |
| 818 |
""" |
| 819 |
An enumeration. |
| 820 |
|
| 821 |
Controls how `C_Initialize()` and `C_Finalize()` are called on the PKCS#11 library. |
| 822 |
""" |
| 823 |
|
| 824 |
DEFAULT = 0 |
| 825 |
""" |
| 826 |
Relaxed behavior that accommodates most use cases. |
| 827 |
|
| 828 |
`C_Initialize()` is called on creation, and "already-initialized" |
| 829 |
errors are ignored. `C_Finalize()` is never called, just in case |
| 830 |
another part of your application is still using the PKCS#11 library. |
| 831 |
""" |
| 832 |
|
| 833 |
OMIT = 1 |
| 834 |
""" |
| 835 |
Skip calling `C_Initialize()` and `C_Finalize()`. |
| 836 |
|
| 837 |
Use this if your application has already initialized the PKCS#11 library, and |
| 838 |
you do not want `C_Initialize()` called again. |
| 839 |
""" |
| 840 |
|
| 841 |
STRICT = 2 |
| 842 |
""" |
| 843 |
`C_Initialize()` is called on creation and `C_Finalize()` is |
| 844 |
called on cleanup. |
| 845 |
|
| 846 |
If `C_Initialize()` reports that's it's already initialized, this is |
| 847 |
treated as an error. Use this if you need perfect cleanup (ex: running |
| 848 |
valgrind with --leak-check). |
| 849 |
""" |
| 850 |
|
| 851 |
def __init__(self, *, file: str, behavior: InitializeFinalizeBehavior = None): |
| 852 |
super().__init__() |
| 853 |
if behavior is None: |
| 854 |
behavior = Pkcs11Lib.InitializeFinalizeBehavior.DEFAULT |
| 855 |
|
| 856 |
self._binding = _awscrt.pkcs11_lib_new(file, behavior) |