spiffe-tls 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.1
2
+ Name: spiffe-tls
3
+ Version: 0.1.0
4
+ Summary: TLS Support using SPIFFE
5
+ License: Apache-2.0
6
+ Author: Max Lambrecht
7
+ Author-email: maxlambrecht@gmail.com
8
+ Requires-Python: >=3.9,<4.0
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: pyOpenSSL (>=24.0,<25.0)
16
+ Requires-Dist: spiffe (>=0.1.0,<0.2.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # `spiffe-tls` Module
20
+
21
+ This `py-spiffe` module provides TLS utilities that facilitate creating secure TLS connections leveraging SPIFFE IDs for
22
+ authentication. It wraps [pyOpenSSL](https://pypi.org/project/pyOpenSSL/), offering easy-to-use functions for setting up
23
+ TLS clients and servers with SPIFFE-based authentication using `X509Source` to manage and automatically update X.509
24
+ certificates and CA trusted bundles.
25
+
26
+ ## Key Features
27
+
28
+ - Establish TLS connections with SPIFFE ID validation.
29
+ - Support for Mutual TLS (MTLS) and TLS with server authorization.
30
+ - Extensible options for server and client configurations.
31
+
32
+ ## Quick Start
33
+
34
+ ### Server Setup
35
+
36
+ Use the `listen()` function to create a TLS server socket bound to a specified address, configured according to SPIFFE
37
+ X.509 SVIDs.
38
+
39
+ ```python
40
+ from spiffetls import listen, ListenOptions
41
+ from spiffe import SpiffeId, X509Source
42
+ from spiffetls.mode import ServerTlsMode
43
+ from spiffetls.tlsconfig.authorize import authorize_id
44
+
45
+ x509_source = X509Source()
46
+ options = ListenOptions(
47
+ tls_mode=ServerTlsMode.MTLS,
48
+ authorize_fn=authorize_id(SpiffeId("spiffe://example.org/client-service")),
49
+ )
50
+
51
+ listener = listen("localhost:8443", x509_source, options)
52
+ ```
53
+
54
+ ### Client Connection
55
+
56
+ Use the `dial()` function to establish a secure client connection to a TLS server.
57
+
58
+ ```python
59
+ from spiffetls import dial
60
+ from spiffe import SpiffeId, X509Source
61
+ from spiffetls.tlsconfig.authorize import authorize_id
62
+
63
+ x509_source = X509Source()
64
+
65
+ conn = dial(
66
+ "localhost:8443",
67
+ x509_source,
68
+ authorize_fn=authorize_id(SpiffeId("spiffe://example.org/client-service")),
69
+ )
70
+ ```
71
+
72
+ ### Authorization Functions
73
+
74
+ The module supports custom authorization functions for additional certificate validation:
75
+
76
+ - `authorize_any()`: Authorizes any valid SPIFFE ID.
77
+ - `authorize_id(expected_spiffe_id)`: Authorizes a specific SPIFFE ID.
78
+ - `authorize_one_of(allowed_ids)`: Authorizes any SPIFFE ID in a given set.
79
+ - `authorize_member_of(allowed_trust_domain)`: Authorizes any SPIFFE ID within a specific trust domain.
@@ -0,0 +1,61 @@
1
+ # `spiffe-tls` Module
2
+
3
+ This `py-spiffe` module provides TLS utilities that facilitate creating secure TLS connections leveraging SPIFFE IDs for
4
+ authentication. It wraps [pyOpenSSL](https://pypi.org/project/pyOpenSSL/), offering easy-to-use functions for setting up
5
+ TLS clients and servers with SPIFFE-based authentication using `X509Source` to manage and automatically update X.509
6
+ certificates and CA trusted bundles.
7
+
8
+ ## Key Features
9
+
10
+ - Establish TLS connections with SPIFFE ID validation.
11
+ - Support for Mutual TLS (MTLS) and TLS with server authorization.
12
+ - Extensible options for server and client configurations.
13
+
14
+ ## Quick Start
15
+
16
+ ### Server Setup
17
+
18
+ Use the `listen()` function to create a TLS server socket bound to a specified address, configured according to SPIFFE
19
+ X.509 SVIDs.
20
+
21
+ ```python
22
+ from spiffetls import listen, ListenOptions
23
+ from spiffe import SpiffeId, X509Source
24
+ from spiffetls.mode import ServerTlsMode
25
+ from spiffetls.tlsconfig.authorize import authorize_id
26
+
27
+ x509_source = X509Source()
28
+ options = ListenOptions(
29
+ tls_mode=ServerTlsMode.MTLS,
30
+ authorize_fn=authorize_id(SpiffeId("spiffe://example.org/client-service")),
31
+ )
32
+
33
+ listener = listen("localhost:8443", x509_source, options)
34
+ ```
35
+
36
+ ### Client Connection
37
+
38
+ Use the `dial()` function to establish a secure client connection to a TLS server.
39
+
40
+ ```python
41
+ from spiffetls import dial
42
+ from spiffe import SpiffeId, X509Source
43
+ from spiffetls.tlsconfig.authorize import authorize_id
44
+
45
+ x509_source = X509Source()
46
+
47
+ conn = dial(
48
+ "localhost:8443",
49
+ x509_source,
50
+ authorize_fn=authorize_id(SpiffeId("spiffe://example.org/client-service")),
51
+ )
52
+ ```
53
+
54
+ ### Authorization Functions
55
+
56
+ The module supports custom authorization functions for additional certificate validation:
57
+
58
+ - `authorize_any()`: Authorizes any valid SPIFFE ID.
59
+ - `authorize_id(expected_spiffe_id)`: Authorizes a specific SPIFFE ID.
60
+ - `authorize_one_of(allowed_ids)`: Authorizes any SPIFFE ID in a given set.
61
+ - `authorize_member_of(allowed_trust_domain)`: Authorizes any SPIFFE ID within a specific trust domain.
@@ -0,0 +1,49 @@
1
+ [tool.poetry]
2
+ name = "spiffe-tls"
3
+ version = "0.1.0"
4
+ description = "TLS Support using SPIFFE"
5
+ authors = ["Max Lambrecht <maxlambrecht@gmail.com>"]
6
+ readme = "README.md"
7
+ license = "Apache-2.0"
8
+
9
+ packages = [
10
+ { include = "spiffetls", from = "src" },
11
+ ]
12
+
13
+ [tool.poetry.dependencies]
14
+ python = "^3.9" # >= 3.9, < 4.0
15
+ spiffe = "~0.1.0"
16
+ pyOpenSSL = "^24.0"
17
+
18
+ [tool.poetry.dev-dependencies]
19
+ black = "^24.3"
20
+ mypy = "^1.9"
21
+ mypy-protobuf = "^3.0"
22
+ types-pyOpenSSL = "^24.0"
23
+ pytest = "^8.1"
24
+ pytest-mock = "^3.14"
25
+ pre-commit = "^3.7"
26
+ flake8 = "^7.0"
27
+ testutils = { path = "../testutils" }
28
+
29
+ [build-system]
30
+ requires = ["poetry-core>=1.9.0"]
31
+ build-backend = "poetry.core.masonry.api"
32
+
33
+ [tool.mypy]
34
+ ignore_missing_imports = true
35
+ files = ["src", "tests"]
36
+
37
+
38
+ [tool.black]
39
+ skip-string-normalization = true
40
+ target-version = ['py39']
41
+
42
+
43
+ [tool.pytest.ini_options]
44
+ addopts = [
45
+ "--doctest-modules",
46
+ ]
47
+ testpaths = [
48
+ "tests",
49
+ ]
@@ -0,0 +1,4 @@
1
+ from .listen import listen, ListenOptions # noqa: F401
2
+ from .mode import ServerTlsMode, ClientTlsMode # noqa: F401
3
+ from .dial import dial # noqa: F401
4
+ from .context import create_ssl_context # noqa: F401
@@ -0,0 +1,147 @@
1
+ """
2
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ not use this file except in compliance with the License. You may obtain
6
+ a copy of the License at
7
+
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ License for the specific language governing permissions and limitations
14
+ under the License.
15
+ """
16
+
17
+ import logging
18
+ from typing import Optional, Callable
19
+
20
+ from OpenSSL import SSL, crypto
21
+ from cryptography.hazmat.primitives import serialization
22
+
23
+ from spiffe import X509Source
24
+ from spiffetls.errors import SslContextError
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def create_ssl_context(
30
+ method: int,
31
+ x509_source: X509Source,
32
+ authorize_fn: Optional[Callable[[crypto.X509], bool]] = None,
33
+ verify_mode: int = SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
34
+ use_system_trusted_cas=False,
35
+ ) -> SSL.Context:
36
+ """Configures and returns an SSL context for secure connections.
37
+
38
+ This function abstracts the complexity of configuring SSL contexts with
39
+ certificates provided by a X509Source, including setting up custom
40
+ certificate verification if needed.
41
+
42
+ Args:
43
+ method: SSL method to use (e.g., SSL.TLS_SERVER_METHOD).
44
+ x509_source: Provides the certificates and private keys.
45
+ authorize_fn: Optional callback for additional cert verification.
46
+ verify_mode: Determines the SSL certificate verification strategy.
47
+ use_system_trusted_cas (bool): If True, the SSL context will include the system's trusted Certificate Authorities
48
+ in addition to any custom certificates. Default is False.
49
+ to any custom certificates. Default is False.
50
+
51
+ Returns:
52
+ Configured SSL.Context object.
53
+
54
+ Raises:
55
+ SslContextError: If SSL context configuration fails.
56
+ """
57
+ ssl_context = SSL.Context(method)
58
+
59
+ try:
60
+ _load_certificate_chain(ssl_context, x509_source)
61
+ _load_ca_bundles(ssl_context, x509_source)
62
+
63
+ def verify_callback(connection, x509, errno, depth, preverify_ok):
64
+ if not preverify_ok:
65
+ return False
66
+ if depth == 0 and authorize_fn:
67
+ # Perform custom verification at the leaf certificate
68
+ return authorize_fn(x509)
69
+
70
+ return preverify_ok
71
+
72
+ ssl_context.set_verify(verify_mode, verify_callback)
73
+ x509_source.subscribe_for_updates(
74
+ lambda: _on_source_update(ssl_context, x509_source)
75
+ )
76
+
77
+ if use_system_trusted_cas:
78
+ ssl_context.set_default_verify_paths()
79
+
80
+ except SSL.Error as err:
81
+ raise SslContextError("Error setting up certificates", err) from err
82
+ except Exception as err:
83
+ raise SslContextError("Unexpected error during SSL context setup", err) from err
84
+
85
+ return ssl_context
86
+
87
+
88
+ def _load_certificate_chain(ssl_context: SSL.Context, x509_source: X509Source):
89
+ """
90
+ Loads the certificate chain and private key into the SSL context.
91
+ """
92
+ try:
93
+ svid = x509_source.svid
94
+ encoding_type = serialization.Encoding.PEM
95
+ crypto_file_type = crypto.FILETYPE_PEM
96
+
97
+ # Load the leaf certificate
98
+ leaf_cert_pem = svid.leaf.public_bytes(encoding_type)
99
+ leaf_cert = crypto.load_certificate(crypto_file_type, leaf_cert_pem)
100
+ ssl_context.use_certificate(leaf_cert)
101
+
102
+ # Load the private key
103
+ private_key_pem = svid.private_key.private_bytes(
104
+ encoding=encoding_type,
105
+ format=serialization.PrivateFormat.PKCS8,
106
+ encryption_algorithm=serialization.NoEncryption(),
107
+ )
108
+ private_key = crypto.load_privatekey(crypto_file_type, private_key_pem)
109
+ ssl_context.use_privatekey(private_key)
110
+
111
+ # Ensure the private key and certificate match
112
+ ssl_context.check_privatekey()
113
+
114
+ # Load the rest of certificate chain
115
+ for cert_pem in svid.cert_chain[1:]:
116
+ cert = crypto.load_certificate(
117
+ crypto_file_type, cert_pem.public_bytes(encoding_type)
118
+ )
119
+ ssl_context.add_extra_chain_cert(cert)
120
+ except Exception as e:
121
+ raise Exception(f'Error loading certificates into SSL Context: {e}') from e
122
+
123
+
124
+ def _load_ca_bundles(ssl_context: SSL.Context, x509_source: X509Source):
125
+ """
126
+ Loads the trusted CA certificate bundles into the SSL context.
127
+ """
128
+ try:
129
+ # Load trusted CA certificates
130
+ for bundle in x509_source.bundles:
131
+ for ca_cert in bundle.x509_authorities:
132
+ ca_cert_pem = ca_cert.public_bytes(serialization.Encoding.PEM)
133
+ ca_cert_obj = crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert_pem)
134
+ ssl_context.get_cert_store().add_cert(ca_cert_obj)
135
+ except Exception as e:
136
+ raise Exception(
137
+ f'Error loading trusted CA certificates into SSL Context: {e}'
138
+ ) from e
139
+
140
+
141
+ def _on_source_update(ssl_context: SSL.Context, x509_source: X509Source):
142
+ """
143
+ Callback function to reload certificates.
144
+ """
145
+ _load_ca_bundles(ssl_context, x509_source)
146
+ _load_certificate_chain(ssl_context, x509_source)
147
+ logger.info("Certificates updated in SSL context.")
@@ -0,0 +1,84 @@
1
+ """
2
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ not use this file except in compliance with the License. You may obtain
6
+ a copy of the License at
7
+
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ License for the specific language governing permissions and limitations
14
+ under the License.
15
+ """
16
+
17
+ import logging
18
+ import socket
19
+ from typing import Optional, Callable
20
+
21
+ from OpenSSL import SSL, crypto
22
+
23
+ from spiffe import X509Source
24
+ from spiffetls.context import create_ssl_context
25
+ from spiffetls.errors import TLSConnectionError
26
+ from spiffetls.mode import ClientTlsMode
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ def dial(
32
+ address: str,
33
+ x509_source: X509Source,
34
+ tls_mode: ClientTlsMode = ClientTlsMode.TLS,
35
+ authorize_fn: Optional[Callable[[crypto.X509], bool]] = None,
36
+ ) -> SSL.Connection:
37
+ """
38
+ Establishes a secure TLS connection to a server at the specified address.
39
+
40
+ This function creates a client-side connection using certificates and keys provided by the X509Source.
41
+ It can optionally perform additional server certificate validations using the provided `authorize_fn`.
42
+
43
+ Args:
44
+ address (str): Target server address in 'host:port' format.
45
+ tls_mode(ClientTlsMode, optional): Client-side TLS mode. Defaults to ClientTlsMode.TLS.
46
+ x509_source (X509Source): Provides the client's X.509 certificates and keys.
47
+ authorize_fn (Callable[[crypto.X509], bool], optional): A callback for additional server
48
+ certificate validation. If not provided, standard certificate validation is performed.
49
+
50
+ Returns:
51
+ SSL.Connection: A secured connection to the server.
52
+
53
+ Raises:
54
+ Exception: If there's an error establishing the connection or configuring TLS context.
55
+ """
56
+
57
+ host, port = address.split(':')
58
+
59
+ # Configures SSL context for the client to verify the server's certificate.
60
+ # The client always attempts to verify the server's certificate to ensure a secure connection.
61
+ verify_mode = SSL.VERIFY_PEER
62
+ use_system_trusted_cas = True if tls_mode == ClientTlsMode.TLS_WEB else False
63
+
64
+ ssl_context = create_ssl_context(
65
+ SSL.TLS_CLIENT_METHOD,
66
+ x509_source,
67
+ authorize_fn,
68
+ verify_mode,
69
+ use_system_trusted_cas,
70
+ )
71
+
72
+ sock = socket.socket()
73
+ conn = SSL.Connection(ssl_context, sock)
74
+
75
+ try:
76
+ conn.connect((host, int(port)))
77
+ conn.do_handshake()
78
+ return conn
79
+ except SSL.Error as ssl_error:
80
+ raise TLSConnectionError(
81
+ "TLS connection failed", address=address, reason=str(ssl_error)
82
+ ) from ssl_error
83
+ except socket.error as sock_error:
84
+ raise ConnectionError(f"Socket connection failed: {sock_error}") from sock_error
@@ -0,0 +1,57 @@
1
+ """
2
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ not use this file except in compliance with the License. You may obtain
6
+ a copy of the License at
7
+
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ License for the specific language governing permissions and limitations
14
+ under the License.
15
+ """
16
+
17
+ from typing import Optional
18
+
19
+ from spiffe.errors import PySpiffeError
20
+
21
+
22
+ class SslContextError(PySpiffeError):
23
+ """
24
+ Represents errors that occur during SSL context configuration.
25
+
26
+ Attributes:
27
+ detail (str): Detailed error message.
28
+ cause (Exception, optional): The original exception that caused this error.
29
+ """
30
+
31
+ def __init__(self, detail: str, cause: Optional[Exception] = None) -> None:
32
+ message = f"SSL context configuration failed: {detail}"
33
+ if cause:
34
+ message += f". Cause: {cause}"
35
+ super().__init__(message)
36
+ self.cause = cause
37
+
38
+
39
+ class TLSConnectionError(PySpiffeError):
40
+ """Exception raised for errors during TLS connection setup."""
41
+
42
+ def __init__(self, message, **context):
43
+ super().__init__(message)
44
+ self.context = context
45
+
46
+
47
+ class ListenError(Exception):
48
+ """Exception raised when a listening socket cannot be created."""
49
+
50
+ def __init__(self, host, port, original_error):
51
+ self.host = host
52
+ self.port = port
53
+ self.original_error = original_error
54
+ message = (
55
+ f"Failed to create listening socket on {host}:{port}: {original_error}"
56
+ )
57
+ super().__init__(message)
@@ -0,0 +1,127 @@
1
+ """
2
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ not use this file except in compliance with the License. You may obtain
6
+ a copy of the License at
7
+
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ License for the specific language governing permissions and limitations
14
+ under the License.
15
+ """
16
+
17
+ import socket
18
+ import logging
19
+ from typing import Callable, Optional
20
+
21
+ from OpenSSL import SSL, crypto
22
+
23
+ from spiffe import X509Source
24
+ from spiffetls.context import create_ssl_context
25
+ from spiffetls.errors import ListenError
26
+ from spiffetls.mode import ServerTlsMode
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ class ListenOptions:
32
+ """
33
+ Configuration options for creating a TLS listening socket with the listen function.
34
+
35
+ Attributes:
36
+ tls_mode (ServerTlsMode): Serveer-side TLS mode. Defaults to ServerTlsMode.TLS.
37
+ authentication only, MTLS for mutual authentication, and MTLS_WEB for mutual authentication with system trusted CAs.
38
+ authorize_fn (Callable[[crypto.X509], bool], optional): Optional callback function for additional client
39
+ certificate verification.
40
+ backlog (int): Maximum number of queued connections. Default is 5.
41
+ socket_family (int): Socket family. Default is socket.AF_INET.
42
+ socket_type (int): Socket type. Default is socket.SOCK_STREAM.
43
+
44
+ This class allows for customization of the listening socket and SSL context behavior, including SSL mode, authorization function, and socket characteristics.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ tls_mode: ServerTlsMode = ServerTlsMode.MTLS,
50
+ authorize_fn: Optional[Callable[[crypto.X509], bool]] = None,
51
+ backlog: int = 5,
52
+ socket_family: int = socket.AF_INET,
53
+ socket_type: int = socket.SOCK_STREAM,
54
+ ):
55
+ self.tls_mode = tls_mode
56
+ self.authorize_fn = authorize_fn
57
+ self.backlog = backlog
58
+ self.socket_family = socket_family
59
+ self.socket_type = socket_type
60
+
61
+
62
+ def listen(
63
+ address: str, x509_source: X509Source, options: Optional[ListenOptions] = None
64
+ ) -> SSL.Connection:
65
+ """
66
+ Creates a TLS listening socket bound to the specified address.
67
+
68
+ Args:
69
+ address (str): The address to bind the server to, formatted as 'host:port'.
70
+ x509_source (X509Source): Source of X.509 certificates and private key for TLS configuration.
71
+ options (ListenOptions, optional): Optional configuration options for the server. Defaults to None.
72
+
73
+ Returns:
74
+ SSL.Connection: A configured SSL connection wrapped around a listening socket.
75
+
76
+ This function sets up a server socket to listen for incoming TLS connections based on the provided X.509 source.
77
+ """
78
+
79
+ if options is None:
80
+ options = ListenOptions()
81
+
82
+ host, port = _parse_address(address)
83
+
84
+ # For mTLS, require the client to present a certificate and fail if no certificate is presented.
85
+ # For TLS, verify the peer's certificate if presented but do not require a client certificate.
86
+ verify_mode = (
87
+ SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT
88
+ if options.tls_mode in (ServerTlsMode.MTLS, ServerTlsMode.MTLS_WEB)
89
+ else SSL.VERIFY_PEER
90
+ )
91
+ use_system_trusted_cas = (
92
+ True if options.tls_mode == ServerTlsMode.MTLS_WEB else False
93
+ )
94
+
95
+ ssl_context = create_ssl_context(
96
+ SSL.TLS_SERVER_METHOD,
97
+ x509_source,
98
+ options.authorize_fn,
99
+ verify_mode,
100
+ use_system_trusted_cas,
101
+ )
102
+
103
+ sock = None
104
+ try:
105
+ sock = socket.socket(options.socket_family, options.socket_type)
106
+ sock.bind((host, int(port)))
107
+ sock.listen(options.backlog)
108
+ except socket.error as err:
109
+ if sock:
110
+ sock.close()
111
+ raise ListenError(host, port, err) from err
112
+
113
+ ssl_connection = SSL.Connection(ssl_context, sock)
114
+ ssl_connection.set_accept_state()
115
+
116
+ return ssl_connection
117
+
118
+
119
+ def _parse_address(address):
120
+ try:
121
+ host, port_str = address.split(':')
122
+ port = int(port_str)
123
+ return host, port
124
+ except ValueError:
125
+ raise ValueError(
126
+ f"Invalid address format or port number: '{address}'. Format should be 'host:port'."
127
+ )
@@ -0,0 +1,59 @@
1
+ """
2
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ not use this file except in compliance with the License. You may obtain
6
+ a copy of the License at
7
+
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ License for the specific language governing permissions and limitations
14
+ under the License.
15
+ """
16
+
17
+ from enum import Enum, auto
18
+
19
+
20
+ class ServerTlsMode(Enum):
21
+ """
22
+ Represents the TLS modes that can be used for setting up TLS connections on the Server.
23
+
24
+ Modes:
25
+ TLS: The server doesn't require the client to present a TLS certificate. Use this mode for traditional TLS
26
+ where client authentication is not necessary. Suitable for public-facing services where client identity
27
+ verification is not required.
28
+
29
+ MTLS: The server requires client authentication using certificates provided by the SPIFFE Workload API. Use this
30
+ mode for mutual TLS (mTLS) where both server and client identities must be verified. Ideal for secure,
31
+ internal communication between services in a SPIFFE-enabled environment.
32
+
33
+ MTLS_WEB: Similar to MTLS, but the server also trusts certificates from the system's trust store. This mode
34
+ allows for mutual TLS authentication with clients that may use well-known CA certificates. It's useful
35
+ when you need to authenticate SPIFFE identities and also support clients with traditional web PKI
36
+ certificates.
37
+ """
38
+
39
+ TLS = auto()
40
+ MTLS = auto()
41
+ MTLS_WEB = auto()
42
+
43
+
44
+ class ClientTlsMode(Enum):
45
+ """
46
+ Represents the TLS modes that can be used for setting up TLS connections on the Client.
47
+
48
+ Modes:
49
+ TLS: The server is authenticated using a certificate provided by the SPIFFE Workload API. This mode ensures that
50
+ the client can securely communicate with a server that presents a SPIFFE identity.
51
+
52
+ TLS_WEB: The server is authenticated using certificates provided by the SPIFFE Workload API and also trusts
53
+ certificates from the system's trust store. This mode supports server authentication via both
54
+ SPIFFE IDs and traditional web PKI. It's suitable for clients that communicate with both SPIFFE-enabled
55
+ services and standard web services.
56
+ """
57
+
58
+ TLS = auto()
59
+ TLS_WEB = auto()
File without changes
@@ -0,0 +1,118 @@
1
+ """
2
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ not use this file except in compliance with the License. You may obtain
6
+ a copy of the License at
7
+
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ License for the specific language governing permissions and limitations
14
+ under the License.
15
+ """
16
+
17
+ import logging
18
+ from typing import Callable, Set
19
+
20
+ from OpenSSL import crypto
21
+
22
+ from spiffe import SpiffeId, TrustDomain
23
+ from spiffe.spiffe_id.spiffe_id import SCHEME_PREFIX
24
+ from spiffe.utils.errors import X509CertificateError
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def authorize_any() -> Callable[[crypto.X509], bool]:
30
+ """Authorizes any valid SPIFFE ID, rejects if no valid SPIFFE ID is present."""
31
+
32
+ def _authorize(cert: crypto.X509) -> bool:
33
+ try:
34
+ _spiffe_id_from_cert(cert)
35
+ return True
36
+ except X509CertificateError as e:
37
+ logger.error(
38
+ f'Failed to authorize certificate due to invalid SPIFFE ID: {e}'
39
+ )
40
+
41
+ return False
42
+
43
+ return _authorize
44
+
45
+
46
+ def authorize_id(expected_spiffe_id: SpiffeId) -> Callable[[crypto.X509], bool]:
47
+ """Authorizes a specific SPIFFE ID."""
48
+
49
+ def _authorize(cert: crypto.X509) -> bool:
50
+ try:
51
+ spiffe_id = _spiffe_id_from_cert(cert)
52
+ return spiffe_id == expected_spiffe_id
53
+ except X509CertificateError as e:
54
+ logger.error(f'Failed to extract SPIFFE ID from certificate: {e}')
55
+
56
+ return False
57
+
58
+ return _authorize
59
+
60
+
61
+ def authorize_one_of(allowed_ids: Set[SpiffeId]) -> Callable[[crypto.X509], bool]:
62
+ """Authorizes any SPIFFE ID in the given list of IDs."""
63
+
64
+ def _authorize(cert: crypto.X509) -> bool:
65
+ try:
66
+ spiffe_id = _spiffe_id_from_cert(cert)
67
+ if spiffe_id in allowed_ids:
68
+ return True
69
+ else:
70
+ logger.error(f"Unauthorized SPIFFE ID: {spiffe_id}")
71
+ except X509CertificateError as e:
72
+ logger.error(f"Failed to extract SPIFFE ID from certificate: {e}")
73
+
74
+ return False
75
+
76
+ return _authorize
77
+
78
+
79
+ def authorize_member_of(
80
+ allowed_trust_domain: TrustDomain,
81
+ ) -> Callable[[crypto.X509], bool]:
82
+ """Authorizes any SPIFFE ID in the given trust domain."""
83
+
84
+ def _authorize(cert: crypto.X509) -> bool:
85
+ try:
86
+ cert_spiffe_id = _spiffe_id_from_cert(cert)
87
+ return cert_spiffe_id.trust_domain == allowed_trust_domain
88
+ except X509CertificateError as e:
89
+ logger.error(f'Failed to extract SPIFFE ID from certificate: {e}')
90
+
91
+ return False
92
+
93
+ return _authorize
94
+
95
+
96
+ def _spiffe_id_from_cert(cert: crypto.X509) -> SpiffeId:
97
+ """Returns the SPIFFE ID from a pyOpenSSL certificate"""
98
+ for i in range(cert.get_extension_count()):
99
+ ext = cert.get_extension(i)
100
+ if "subjectAltName" in str(ext.get_short_name()):
101
+ sans = str(ext)
102
+ uris = [
103
+ uri.replace('URI:', '').strip()
104
+ for uri in sans.split(',')
105
+ if 'URI:' in uri
106
+ ]
107
+ spiffe_ids = [uri for uri in uris if uri.startswith(SCHEME_PREFIX)]
108
+
109
+ if spiffe_ids:
110
+ return SpiffeId(spiffe_ids[0])
111
+ else:
112
+ raise X509CertificateError(
113
+ 'Certificate does not contain a SPIFFE ID in the URI SAN'
114
+ )
115
+
116
+ raise X509CertificateError(
117
+ 'Certificate does not contain a Subject Alternative Name extension'
118
+ )