swarmauri_certservice_ms_adcs 0.2.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.
- swarmauri_certservice_ms_adcs-0.2.0/LICENSE +201 -0
- swarmauri_certservice_ms_adcs-0.2.0/PKG-INFO +195 -0
- swarmauri_certservice_ms_adcs-0.2.0/README.md +163 -0
- swarmauri_certservice_ms_adcs-0.2.0/pyproject.toml +87 -0
- swarmauri_certservice_ms_adcs-0.2.0/swarmauri_certservice_ms_adcs/MsAdcsCertService.py +462 -0
- swarmauri_certservice_ms_adcs-0.2.0/swarmauri_certservice_ms_adcs/__init__.py +5 -0
|
@@ -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 [2025] [Jacob Stewart @ Swarmauri]
|
|
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,195 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: swarmauri_certservice_ms_adcs
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Microsoft AD CS certificate service client for Swarmauri
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: swarmauri,certservice,ms,adcs,microsoft,certificate,service,client
|
|
8
|
+
Author: Jacob Stewart
|
|
9
|
+
Author-email: jacob@swarmauri.com
|
|
10
|
+
Requires-Python: >=3.10,<3.13
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Natural Language :: English
|
|
16
|
+
Classifier: Development Status :: 3 - Alpha
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
19
|
+
Provides-Extra: kerberos
|
|
20
|
+
Provides-Extra: ntlm
|
|
21
|
+
Provides-Extra: perf
|
|
22
|
+
Requires-Dist: cryptography
|
|
23
|
+
Requires-Dist: pytest-benchmark (>=4.0.0) ; extra == "perf"
|
|
24
|
+
Requires-Dist: requests (>=2.32.3)
|
|
25
|
+
Requires-Dist: requests-kerberos ; extra == "kerberos"
|
|
26
|
+
Requires-Dist: requests-ntlm ; extra == "ntlm"
|
|
27
|
+
Requires-Dist: swarmauri_base
|
|
28
|
+
Requires-Dist: swarmauri_core
|
|
29
|
+
Requires-Dist: swarmauri_standard
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
<p align="center">
|
|
35
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
36
|
+
<img src="https://img.shields.io/pypi/dm/swarmauri_certservice_ms_adcs" alt="PyPI - Downloads"/></a>
|
|
37
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_certservice_ms_adcs/">
|
|
38
|
+
<img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_certservice_ms_adcs.svg"/></a>
|
|
39
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
40
|
+
<img src="https://img.shields.io/pypi/pyversions/swarmauri_certservice_ms_adcs" alt="PyPI - Python Version"/></a>
|
|
41
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
42
|
+
<img src="https://img.shields.io/pypi/l/swarmauri_certservice_ms_adcs" alt="PyPI - License"/></a>
|
|
43
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
44
|
+
<img src="https://img.shields.io/pypi/v/swarmauri_certservice_ms_adcs?label=swarmauri_certservice_ms_adcs&color=green" alt="PyPI - swarmauri_certservice_ms_adcs"/></a>
|
|
45
|
+
|
|
46
|
+
</p>
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
# swarmauri_certservice_ms_adcs
|
|
51
|
+
|
|
52
|
+
Community plugin providing a certificate service client for Microsoft Active Directory Certificate Services (AD CS).
|
|
53
|
+
|
|
54
|
+
## Features
|
|
55
|
+
|
|
56
|
+
- Generate RFC 2986-compliant PKCS#10 CSRs with rich subject, subject alternative name, and extension options.
|
|
57
|
+
- Parse and validate X.509 certificates per RFC 5280, including issuer matching and signature verification.
|
|
58
|
+
- Ready-to-use authentication helpers for NTLM, Kerberos, and HTTP basic auth while preserving TLS configuration.
|
|
59
|
+
- Typed `supports()` metadata describing templates, key algorithms, and capabilities advertised to Swarmauri agents.
|
|
60
|
+
|
|
61
|
+
## Prerequisites
|
|
62
|
+
|
|
63
|
+
- Python 3.10 or newer.
|
|
64
|
+
- Network access to an AD CS Web Enrollment endpoint (typically `https://<ca>/certsrv`).
|
|
65
|
+
- A private key for each CSR you plan to submit; software keys can be read from PEM while HSM-backed keys can be referenced via `KeyRef` metadata.
|
|
66
|
+
- Optional authentication libraries: install `requests-ntlm` for NTLM flows and `requests-kerberos` for Kerberos/SPNEGO delegation.
|
|
67
|
+
|
|
68
|
+
## Installation
|
|
69
|
+
|
|
70
|
+
Install the core package or include extras for the auth helpers your environment requires:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
# pip
|
|
74
|
+
pip install "swarmauri_certservice_ms_adcs[ntlm,kerberos]"
|
|
75
|
+
|
|
76
|
+
# poetry
|
|
77
|
+
poetry add swarmauri_certservice_ms_adcs -E ntlm -E kerberos
|
|
78
|
+
|
|
79
|
+
# uv (pyproject-based projects)
|
|
80
|
+
uv add "swarmauri_certservice_ms_adcs[ntlm,kerberos]"
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
You can drop the extras if your AD CS deployment only needs anonymous access or HTTP basic authentication.
|
|
84
|
+
|
|
85
|
+
## Quickstart: Build a CSR for AD CS
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import asyncio
|
|
89
|
+
from pathlib import Path
|
|
90
|
+
|
|
91
|
+
from swarmauri_certservice_ms_adcs import MsAdcsCertService, _AuthCfg
|
|
92
|
+
from swarmauri_core.certs.ICertService import SubjectSpec
|
|
93
|
+
from swarmauri_core.crypto.types import ExportPolicy, KeyRef, KeyType, KeyUse
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def main() -> None:
|
|
97
|
+
service = MsAdcsCertService(
|
|
98
|
+
base_url="https://ca.example.com/certsrv",
|
|
99
|
+
default_template="WebServer",
|
|
100
|
+
auth=_AuthCfg(
|
|
101
|
+
mode="ntlm",
|
|
102
|
+
username="EXAMPLE\\svc-adcs",
|
|
103
|
+
password="s3cr3t!",
|
|
104
|
+
verify_tls=True,
|
|
105
|
+
),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
key_bytes = Path("webserver.key.pem").read_bytes()
|
|
109
|
+
key_ref = KeyRef(
|
|
110
|
+
kid="webserver-key",
|
|
111
|
+
version=1,
|
|
112
|
+
type=KeyType.RSA,
|
|
113
|
+
uses=(KeyUse.SIGN,),
|
|
114
|
+
export_policy=ExportPolicy.PUBLIC_ONLY,
|
|
115
|
+
material=key_bytes,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
subject: SubjectSpec = {
|
|
119
|
+
"C": "US",
|
|
120
|
+
"ST": "Texas",
|
|
121
|
+
"L": "Austin",
|
|
122
|
+
"O": "Example Corp",
|
|
123
|
+
"CN": "app.example.com",
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
csr_pem = await service.create_csr(
|
|
127
|
+
key=key_ref,
|
|
128
|
+
subject=subject,
|
|
129
|
+
san={"dns": ["app.example.com", "www.example.com"]},
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
Path("app.csr").write_bytes(csr_pem)
|
|
133
|
+
print("CSR saved to app.csr")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
if __name__ == "__main__":
|
|
137
|
+
asyncio.run(main())
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Submit `app.csr` through your AD CS Web Enrollment UI, automation, or a downstream Swarmauri agent responsible for certificate issuance.
|
|
141
|
+
|
|
142
|
+
## Validate Issued Certificates
|
|
143
|
+
|
|
144
|
+
After AD CS returns a certificate, use the same service instance to confirm the chain and inspect metadata:
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
import asyncio
|
|
148
|
+
from pathlib import Path
|
|
149
|
+
|
|
150
|
+
from swarmauri_certservice_ms_adcs import MsAdcsCertService, _AuthCfg
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
async def verify_certificate() -> None:
|
|
154
|
+
service = MsAdcsCertService(
|
|
155
|
+
base_url="https://ca.example.com/certsrv",
|
|
156
|
+
auth=_AuthCfg(mode="none"),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
issued_cert = Path("app.pem").read_bytes()
|
|
160
|
+
issuing_ca = Path("issuing-ca.pem").read_bytes()
|
|
161
|
+
|
|
162
|
+
verification = await service.verify_cert(
|
|
163
|
+
cert=issued_cert,
|
|
164
|
+
trust_roots=[issuing_ca],
|
|
165
|
+
)
|
|
166
|
+
if verification["valid"]:
|
|
167
|
+
print("Certificate is valid until", verification["not_after"])
|
|
168
|
+
else:
|
|
169
|
+
print("Validation failed:", verification["reason"])
|
|
170
|
+
|
|
171
|
+
parsed = await service.parse_cert(issued_cert)
|
|
172
|
+
print("Subject:", parsed["subject"])
|
|
173
|
+
print("Subject Alternative Names:", parsed.get("san"))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
if __name__ == "__main__":
|
|
177
|
+
asyncio.run(verify_certificate())
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`verify_cert` performs structural checks and signature validation when an issuer certificate is supplied, while `parse_cert` surfaces extension data for auditing or observability pipelines.
|
|
181
|
+
|
|
182
|
+
## Authentication Modes
|
|
183
|
+
|
|
184
|
+
- **NTLM** – enable by installing `requests-ntlm` and providing domain credentials via `_AuthCfg(mode="ntlm", username="DOMAIN\\user", password="..." )`.
|
|
185
|
+
- **Kerberos/SPNEGO** – install `requests-kerberos` and set `_AuthCfg(mode="kerberos", spnego_delegate=True)` when delegation is required.
|
|
186
|
+
- **HTTP Basic** – provide `_AuthCfg(mode="basic", username=..., password=...)` for AD CS deployments fronted by basic auth proxies.
|
|
187
|
+
- **Anonymous** – set `_AuthCfg(mode="none")` for environments that rely on IP allow lists or mutual TLS.
|
|
188
|
+
|
|
189
|
+
## Best Practices
|
|
190
|
+
|
|
191
|
+
- Store AD CS credentials in a secure secrets manager and inject them via environment variables rather than hard-coding passwords.
|
|
192
|
+
- Capture issued certificates, verification results, and parsed metadata in your logging system so you can trace enrollment activity.
|
|
193
|
+
- Rotate key pairs and certificates regularly; regenerate CSRs ahead of expiry to leave time for manual approvals.
|
|
194
|
+
- Combine this plugin with Swarmauri certificate verification agents (CRL/OCSP) to maintain revocation visibility across the lifecycle.
|
|
195
|
+
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
5
|
+
<img src="https://img.shields.io/pypi/dm/swarmauri_certservice_ms_adcs" alt="PyPI - Downloads"/></a>
|
|
6
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_certservice_ms_adcs/">
|
|
7
|
+
<img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_certservice_ms_adcs.svg"/></a>
|
|
8
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
9
|
+
<img src="https://img.shields.io/pypi/pyversions/swarmauri_certservice_ms_adcs" alt="PyPI - Python Version"/></a>
|
|
10
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
11
|
+
<img src="https://img.shields.io/pypi/l/swarmauri_certservice_ms_adcs" alt="PyPI - License"/></a>
|
|
12
|
+
<a href="https://pypi.org/project/swarmauri_certservice_ms_adcs/">
|
|
13
|
+
<img src="https://img.shields.io/pypi/v/swarmauri_certservice_ms_adcs?label=swarmauri_certservice_ms_adcs&color=green" alt="PyPI - swarmauri_certservice_ms_adcs"/></a>
|
|
14
|
+
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
# swarmauri_certservice_ms_adcs
|
|
20
|
+
|
|
21
|
+
Community plugin providing a certificate service client for Microsoft Active Directory Certificate Services (AD CS).
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- Generate RFC 2986-compliant PKCS#10 CSRs with rich subject, subject alternative name, and extension options.
|
|
26
|
+
- Parse and validate X.509 certificates per RFC 5280, including issuer matching and signature verification.
|
|
27
|
+
- Ready-to-use authentication helpers for NTLM, Kerberos, and HTTP basic auth while preserving TLS configuration.
|
|
28
|
+
- Typed `supports()` metadata describing templates, key algorithms, and capabilities advertised to Swarmauri agents.
|
|
29
|
+
|
|
30
|
+
## Prerequisites
|
|
31
|
+
|
|
32
|
+
- Python 3.10 or newer.
|
|
33
|
+
- Network access to an AD CS Web Enrollment endpoint (typically `https://<ca>/certsrv`).
|
|
34
|
+
- A private key for each CSR you plan to submit; software keys can be read from PEM while HSM-backed keys can be referenced via `KeyRef` metadata.
|
|
35
|
+
- Optional authentication libraries: install `requests-ntlm` for NTLM flows and `requests-kerberos` for Kerberos/SPNEGO delegation.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Install the core package or include extras for the auth helpers your environment requires:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
# pip
|
|
43
|
+
pip install "swarmauri_certservice_ms_adcs[ntlm,kerberos]"
|
|
44
|
+
|
|
45
|
+
# poetry
|
|
46
|
+
poetry add swarmauri_certservice_ms_adcs -E ntlm -E kerberos
|
|
47
|
+
|
|
48
|
+
# uv (pyproject-based projects)
|
|
49
|
+
uv add "swarmauri_certservice_ms_adcs[ntlm,kerberos]"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
You can drop the extras if your AD CS deployment only needs anonymous access or HTTP basic authentication.
|
|
53
|
+
|
|
54
|
+
## Quickstart: Build a CSR for AD CS
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import asyncio
|
|
58
|
+
from pathlib import Path
|
|
59
|
+
|
|
60
|
+
from swarmauri_certservice_ms_adcs import MsAdcsCertService, _AuthCfg
|
|
61
|
+
from swarmauri_core.certs.ICertService import SubjectSpec
|
|
62
|
+
from swarmauri_core.crypto.types import ExportPolicy, KeyRef, KeyType, KeyUse
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def main() -> None:
|
|
66
|
+
service = MsAdcsCertService(
|
|
67
|
+
base_url="https://ca.example.com/certsrv",
|
|
68
|
+
default_template="WebServer",
|
|
69
|
+
auth=_AuthCfg(
|
|
70
|
+
mode="ntlm",
|
|
71
|
+
username="EXAMPLE\\svc-adcs",
|
|
72
|
+
password="s3cr3t!",
|
|
73
|
+
verify_tls=True,
|
|
74
|
+
),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
key_bytes = Path("webserver.key.pem").read_bytes()
|
|
78
|
+
key_ref = KeyRef(
|
|
79
|
+
kid="webserver-key",
|
|
80
|
+
version=1,
|
|
81
|
+
type=KeyType.RSA,
|
|
82
|
+
uses=(KeyUse.SIGN,),
|
|
83
|
+
export_policy=ExportPolicy.PUBLIC_ONLY,
|
|
84
|
+
material=key_bytes,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
subject: SubjectSpec = {
|
|
88
|
+
"C": "US",
|
|
89
|
+
"ST": "Texas",
|
|
90
|
+
"L": "Austin",
|
|
91
|
+
"O": "Example Corp",
|
|
92
|
+
"CN": "app.example.com",
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
csr_pem = await service.create_csr(
|
|
96
|
+
key=key_ref,
|
|
97
|
+
subject=subject,
|
|
98
|
+
san={"dns": ["app.example.com", "www.example.com"]},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
Path("app.csr").write_bytes(csr_pem)
|
|
102
|
+
print("CSR saved to app.csr")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__ == "__main__":
|
|
106
|
+
asyncio.run(main())
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Submit `app.csr` through your AD CS Web Enrollment UI, automation, or a downstream Swarmauri agent responsible for certificate issuance.
|
|
110
|
+
|
|
111
|
+
## Validate Issued Certificates
|
|
112
|
+
|
|
113
|
+
After AD CS returns a certificate, use the same service instance to confirm the chain and inspect metadata:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import asyncio
|
|
117
|
+
from pathlib import Path
|
|
118
|
+
|
|
119
|
+
from swarmauri_certservice_ms_adcs import MsAdcsCertService, _AuthCfg
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def verify_certificate() -> None:
|
|
123
|
+
service = MsAdcsCertService(
|
|
124
|
+
base_url="https://ca.example.com/certsrv",
|
|
125
|
+
auth=_AuthCfg(mode="none"),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
issued_cert = Path("app.pem").read_bytes()
|
|
129
|
+
issuing_ca = Path("issuing-ca.pem").read_bytes()
|
|
130
|
+
|
|
131
|
+
verification = await service.verify_cert(
|
|
132
|
+
cert=issued_cert,
|
|
133
|
+
trust_roots=[issuing_ca],
|
|
134
|
+
)
|
|
135
|
+
if verification["valid"]:
|
|
136
|
+
print("Certificate is valid until", verification["not_after"])
|
|
137
|
+
else:
|
|
138
|
+
print("Validation failed:", verification["reason"])
|
|
139
|
+
|
|
140
|
+
parsed = await service.parse_cert(issued_cert)
|
|
141
|
+
print("Subject:", parsed["subject"])
|
|
142
|
+
print("Subject Alternative Names:", parsed.get("san"))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
if __name__ == "__main__":
|
|
146
|
+
asyncio.run(verify_certificate())
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`verify_cert` performs structural checks and signature validation when an issuer certificate is supplied, while `parse_cert` surfaces extension data for auditing or observability pipelines.
|
|
150
|
+
|
|
151
|
+
## Authentication Modes
|
|
152
|
+
|
|
153
|
+
- **NTLM** – enable by installing `requests-ntlm` and providing domain credentials via `_AuthCfg(mode="ntlm", username="DOMAIN\\user", password="..." )`.
|
|
154
|
+
- **Kerberos/SPNEGO** – install `requests-kerberos` and set `_AuthCfg(mode="kerberos", spnego_delegate=True)` when delegation is required.
|
|
155
|
+
- **HTTP Basic** – provide `_AuthCfg(mode="basic", username=..., password=...)` for AD CS deployments fronted by basic auth proxies.
|
|
156
|
+
- **Anonymous** – set `_AuthCfg(mode="none")` for environments that rely on IP allow lists or mutual TLS.
|
|
157
|
+
|
|
158
|
+
## Best Practices
|
|
159
|
+
|
|
160
|
+
- Store AD CS credentials in a secure secrets manager and inject them via environment variables rather than hard-coding passwords.
|
|
161
|
+
- Capture issued certificates, verification results, and parsed metadata in your logging system so you can trace enrollment activity.
|
|
162
|
+
- Rotate key pairs and certificates regularly; regenerate CSRs ahead of expiry to leave time for manual approvals.
|
|
163
|
+
- Combine this plugin with Swarmauri certificate verification agents (CRL/OCSP) to maintain revocation visibility across the lifecycle.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "swarmauri_certservice_ms_adcs"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Microsoft AD CS certificate service client for Swarmauri"
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
repository = "http://github.com/swarmauri/swarmauri-sdk"
|
|
8
|
+
requires-python = ">=3.10,<3.13"
|
|
9
|
+
classifiers = [
|
|
10
|
+
"License :: OSI Approved :: Apache Software License",
|
|
11
|
+
"Programming Language :: Python :: 3.10",
|
|
12
|
+
"Programming Language :: Python :: 3.11",
|
|
13
|
+
"Programming Language :: Python :: 3.12",
|
|
14
|
+
"Natural Language :: English",
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Topic :: Software Development :: Libraries :: Application Frameworks",
|
|
18
|
+
]
|
|
19
|
+
authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"requests>=2.32.3",
|
|
22
|
+
"cryptography",
|
|
23
|
+
"swarmauri_core",
|
|
24
|
+
"swarmauri_base",
|
|
25
|
+
"swarmauri_standard",
|
|
26
|
+
]
|
|
27
|
+
keywords = [
|
|
28
|
+
"swarmauri",
|
|
29
|
+
"certservice",
|
|
30
|
+
"ms",
|
|
31
|
+
"adcs",
|
|
32
|
+
"microsoft",
|
|
33
|
+
"certificate",
|
|
34
|
+
"service",
|
|
35
|
+
"client",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
ntlm = ["requests-ntlm"]
|
|
40
|
+
kerberos = ["requests-kerberos"]
|
|
41
|
+
perf = ["pytest-benchmark>=4.0.0"]
|
|
42
|
+
|
|
43
|
+
[tool.uv.sources]
|
|
44
|
+
swarmauri_core = { workspace = true }
|
|
45
|
+
swarmauri_base = { workspace = true }
|
|
46
|
+
swarmauri_standard = { workspace = true }
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
norecursedirs = ["combined", "scripts"]
|
|
50
|
+
markers = [
|
|
51
|
+
"test: standard test",
|
|
52
|
+
"unit: Unit tests",
|
|
53
|
+
"i9n: Integration tests",
|
|
54
|
+
"r8n: Regression tests",
|
|
55
|
+
"timeout: mark test to timeout after X seconds",
|
|
56
|
+
"xpass: Expected passes",
|
|
57
|
+
"xfail: Expected failures",
|
|
58
|
+
"acceptance: Acceptance tests",
|
|
59
|
+
"perf: Performance tests that measure execution time and resource usage",
|
|
60
|
+
]
|
|
61
|
+
timeout = 300
|
|
62
|
+
log_cli = true
|
|
63
|
+
log_cli_level = "INFO"
|
|
64
|
+
log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
|
|
65
|
+
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
|
|
66
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
67
|
+
|
|
68
|
+
[project.entry-points.'swarmauri.cert_services']
|
|
69
|
+
MsAdcsCertService = "swarmauri_certservice_ms_adcs.MsAdcsCertService:MsAdcsCertService"
|
|
70
|
+
|
|
71
|
+
[build-system]
|
|
72
|
+
requires = ["poetry-core>=1.0.0"]
|
|
73
|
+
build-backend = "poetry.core.masonry.api"
|
|
74
|
+
|
|
75
|
+
[dependency-groups]
|
|
76
|
+
dev = [
|
|
77
|
+
"pytest>=8.0",
|
|
78
|
+
"pytest-asyncio>=0.24.0",
|
|
79
|
+
"pytest-xdist>=3.6.1",
|
|
80
|
+
"pytest-json-report>=1.5.0",
|
|
81
|
+
"python-dotenv",
|
|
82
|
+
"requests>=2.32.3",
|
|
83
|
+
"flake8>=7.0",
|
|
84
|
+
"pytest-timeout>=2.3.1",
|
|
85
|
+
"ruff>=0.9.9",
|
|
86
|
+
"pytest-benchmark>=4.0.0",
|
|
87
|
+
]
|
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import dataclasses
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Dict, Iterable, Literal, Mapping, Optional, Sequence
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
# Optional auth helpers (install whichever your AD CS needs)
|
|
12
|
+
from requests_ntlm import HttpNtlmAuth # type: ignore
|
|
13
|
+
|
|
14
|
+
_NTLM_OK = True
|
|
15
|
+
except Exception: # pragma: no cover - optional
|
|
16
|
+
_NTLM_OK = False
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
from requests_kerberos import HTTPKerberosAuth, DISABLED # type: ignore
|
|
20
|
+
|
|
21
|
+
_KERB_OK = True
|
|
22
|
+
except Exception: # pragma: no cover - optional
|
|
23
|
+
_KERB_OK = False
|
|
24
|
+
|
|
25
|
+
from requests.auth import HTTPBasicAuth
|
|
26
|
+
|
|
27
|
+
from cryptography import x509
|
|
28
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
29
|
+
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
30
|
+
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
|
|
31
|
+
|
|
32
|
+
from swarmauri_base.certs.CertServiceBase import CertServiceBase
|
|
33
|
+
from swarmauri_core.certs.ICertService import (
|
|
34
|
+
SubjectSpec,
|
|
35
|
+
AltNameSpec,
|
|
36
|
+
CertExtensionSpec,
|
|
37
|
+
)
|
|
38
|
+
from swarmauri_core.crypto.types import KeyRef
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_DEF_USER_AGENT = "swarmauri.ms-adcs/1.0"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _pem(b: bytes, typ: str) -> bytes:
|
|
45
|
+
"""Wrap base64 DER as PEM with given type header."""
|
|
46
|
+
if b.startswith(b"-----BEGIN "):
|
|
47
|
+
return b
|
|
48
|
+
body = base64.encodebytes(b).replace(b"\n", b"")
|
|
49
|
+
lines = [body[i : i + 64] for i in range(0, len(body), 64)]
|
|
50
|
+
return (
|
|
51
|
+
b"-----BEGIN "
|
|
52
|
+
+ typ.encode()
|
|
53
|
+
+ b"-----\n"
|
|
54
|
+
+ b"\n".join(lines)
|
|
55
|
+
+ b"\n-----END "
|
|
56
|
+
+ typ.encode()
|
|
57
|
+
+ b"-----\n"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _load_cert_any(data: bytes) -> x509.Certificate:
|
|
62
|
+
try:
|
|
63
|
+
return x509.load_pem_x509_certificate(data)
|
|
64
|
+
except Exception:
|
|
65
|
+
return x509.load_der_x509_certificate(data)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _mk_name(subject: SubjectSpec) -> x509.Name:
|
|
69
|
+
parts = []
|
|
70
|
+
if v := subject.get("C"):
|
|
71
|
+
parts.append(x509.NameAttribute(NameOID.COUNTRY_NAME, v))
|
|
72
|
+
if v := subject.get("ST"):
|
|
73
|
+
parts.append(x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, v))
|
|
74
|
+
if v := subject.get("L"):
|
|
75
|
+
parts.append(x509.NameAttribute(NameOID.LOCALITY_NAME, v))
|
|
76
|
+
if v := subject.get("O"):
|
|
77
|
+
parts.append(x509.NameAttribute(NameOID.ORGANIZATION_NAME, v))
|
|
78
|
+
if v := subject.get("OU"):
|
|
79
|
+
parts.append(x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, v))
|
|
80
|
+
if v := subject.get("CN"):
|
|
81
|
+
parts.append(x509.NameAttribute(NameOID.COMMON_NAME, v))
|
|
82
|
+
if v := subject.get("emailAddress"):
|
|
83
|
+
parts.append(x509.NameAttribute(NameOID.EMAIL_ADDRESS, v))
|
|
84
|
+
for k, v in (subject.get("extra_rdns") or {}).items():
|
|
85
|
+
parts.append(x509.NameAttribute(x509.ObjectIdentifier(k), v))
|
|
86
|
+
return x509.Name(parts)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _now() -> int:
|
|
90
|
+
return int(time.time())
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclasses.dataclass(frozen=True)
|
|
94
|
+
class _AuthCfg:
|
|
95
|
+
mode: Literal["ntlm", "kerberos", "basic", "none"] = "ntlm"
|
|
96
|
+
username: Optional[str] = None
|
|
97
|
+
password: Optional[str] = None
|
|
98
|
+
domain: Optional[str] = None
|
|
99
|
+
verify_tls: bool | str = True
|
|
100
|
+
spnego_delegate: bool = False
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class MsAdcsCertService(CertServiceBase):
|
|
104
|
+
"""Microsoft AD CS Web Enrollment client."""
|
|
105
|
+
|
|
106
|
+
type: Literal["MsAdcsCertService"] = "MsAdcsCertService"
|
|
107
|
+
|
|
108
|
+
def __init__(
|
|
109
|
+
self,
|
|
110
|
+
base_url: str,
|
|
111
|
+
*,
|
|
112
|
+
default_template: Optional[str] = "User",
|
|
113
|
+
auth: _AuthCfg = _AuthCfg(),
|
|
114
|
+
session: Optional[requests.Session] = None,
|
|
115
|
+
timeout_s: float = 15.0,
|
|
116
|
+
) -> None:
|
|
117
|
+
super().__init__()
|
|
118
|
+
self._base = base_url.rstrip("/")
|
|
119
|
+
self._tmpl = default_template
|
|
120
|
+
self._auth_cfg = auth
|
|
121
|
+
self._timeout = timeout_s
|
|
122
|
+
self._s = session or requests.Session()
|
|
123
|
+
self._configure_auth()
|
|
124
|
+
|
|
125
|
+
# --------------------------------------------------------------------- Auth
|
|
126
|
+
def _configure_auth(self) -> None:
|
|
127
|
+
if self._auth_cfg.mode == "ntlm":
|
|
128
|
+
if not _NTLM_OK: # pragma: no cover - import guard
|
|
129
|
+
raise RuntimeError(
|
|
130
|
+
"NTLM auth requested but 'requests-ntlm' not installed. pip install requests-ntlm"
|
|
131
|
+
)
|
|
132
|
+
user = self._auth_cfg.username or ""
|
|
133
|
+
pw = self._auth_cfg.password or ""
|
|
134
|
+
self._s.auth = HttpNtlmAuth(user, pw)
|
|
135
|
+
elif self._auth_cfg.mode == "kerberos":
|
|
136
|
+
if not _KERB_OK: # pragma: no cover - import guard
|
|
137
|
+
raise RuntimeError(
|
|
138
|
+
"Kerberos auth requested but 'requests-kerberos' not installed. pip install requests-kerberos"
|
|
139
|
+
)
|
|
140
|
+
self._s.auth = HTTPKerberosAuth(
|
|
141
|
+
mutual_authentication=DISABLED, delegate=self._auth_cfg.spnego_delegate
|
|
142
|
+
)
|
|
143
|
+
elif self._auth_cfg.mode == "basic":
|
|
144
|
+
user = self._auth_cfg.username or ""
|
|
145
|
+
pw = self._auth_cfg.password or ""
|
|
146
|
+
self._s.auth = HTTPBasicAuth(user, pw)
|
|
147
|
+
else:
|
|
148
|
+
self._s.auth = None
|
|
149
|
+
self._s.verify = self._auth_cfg.verify_tls
|
|
150
|
+
self._s.headers.update({"User-Agent": _DEF_USER_AGENT})
|
|
151
|
+
|
|
152
|
+
# -------------------------------------------------------------- Capabilities
|
|
153
|
+
def supports(self) -> Mapping[str, Iterable[str]]:
|
|
154
|
+
return {
|
|
155
|
+
"key_algs": (
|
|
156
|
+
"RSA-2048",
|
|
157
|
+
"RSA-3072",
|
|
158
|
+
"RSA-4096",
|
|
159
|
+
"EC-P256",
|
|
160
|
+
"EC-P384",
|
|
161
|
+
"Ed25519",
|
|
162
|
+
),
|
|
163
|
+
"sig_algs": ("RSA-PSS-SHA256", "ECDSA-P256-SHA256", "Ed25519"),
|
|
164
|
+
"features": ("sign_from_csr", "verify", "parse", "chain_bundle"),
|
|
165
|
+
"profiles": ("server", "client", "email_protection", "code_signing"),
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
# ------------------------------------------------------------------- CSR API
|
|
169
|
+
async def create_csr( # type: ignore[override]
|
|
170
|
+
self,
|
|
171
|
+
key: KeyRef,
|
|
172
|
+
subject: SubjectSpec,
|
|
173
|
+
*,
|
|
174
|
+
san: Optional[AltNameSpec] = None,
|
|
175
|
+
extensions: Optional[CertExtensionSpec] = None,
|
|
176
|
+
sig_alg: Optional[str] = None,
|
|
177
|
+
challenge_password: Optional[str] = None,
|
|
178
|
+
output_der: bool = False,
|
|
179
|
+
opts: Optional[Dict[str, Any]] = None,
|
|
180
|
+
) -> bytes:
|
|
181
|
+
"""Build a PKCS#10 CSR using the private key contained in KeyRef.material."""
|
|
182
|
+
if not key.material:
|
|
183
|
+
raise ValueError(
|
|
184
|
+
"create_csr: KeyRef.material must contain a PEM private key"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
priv = serialization.load_pem_private_key(key.material, password=None)
|
|
188
|
+
builder = x509.CertificateSigningRequestBuilder().subject_name(
|
|
189
|
+
_mk_name(subject)
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
if san:
|
|
193
|
+
dns = [x509.DNSName(d) for d in (san.get("dns") or [])]
|
|
194
|
+
ips = []
|
|
195
|
+
for ip in san.get("ip") or []:
|
|
196
|
+
from ipaddress import ip_address
|
|
197
|
+
|
|
198
|
+
ips.append(x509.IPAddress(ip_address(ip)))
|
|
199
|
+
uris = [x509.UniformResourceIdentifier(u) for u in (san.get("uri") or [])]
|
|
200
|
+
emails = [x509.RFC822Name(e) for e in (san.get("email") or [])]
|
|
201
|
+
upns = [
|
|
202
|
+
x509.OtherName(
|
|
203
|
+
x509.ObjectIdentifier("1.3.6.1.4.1.311.20.2.3"), u.encode("utf-8")
|
|
204
|
+
)
|
|
205
|
+
for u in (san.get("upn") or [])
|
|
206
|
+
]
|
|
207
|
+
san_list = dns + ips + uris + emails + upns
|
|
208
|
+
if san_list:
|
|
209
|
+
builder = builder.add_extension(
|
|
210
|
+
x509.SubjectAlternativeName(san_list), critical=False
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
if extensions:
|
|
214
|
+
ku = extensions.get("key_usage")
|
|
215
|
+
if ku:
|
|
216
|
+
builder = builder.add_extension(
|
|
217
|
+
x509.KeyUsage(
|
|
218
|
+
digital_signature=ku.get("digital_signature", False),
|
|
219
|
+
content_commitment=ku.get("content_commitment", False),
|
|
220
|
+
key_encipherment=ku.get("key_encipherment", False),
|
|
221
|
+
data_encipherment=ku.get("data_encipherment", False),
|
|
222
|
+
key_agreement=ku.get("key_agreement", False),
|
|
223
|
+
key_cert_sign=ku.get("key_cert_sign", False),
|
|
224
|
+
crl_sign=ku.get("crl_sign", False),
|
|
225
|
+
encipher_only=ku.get("encipher_only", False),
|
|
226
|
+
decipher_only=ku.get("decipher_only", False),
|
|
227
|
+
),
|
|
228
|
+
critical=True,
|
|
229
|
+
)
|
|
230
|
+
eku = extensions.get("extended_key_usage")
|
|
231
|
+
if eku and (oids := eku.get("oids")):
|
|
232
|
+
mapped = []
|
|
233
|
+
for token in oids:
|
|
234
|
+
if token == "serverAuth":
|
|
235
|
+
mapped.append(ExtendedKeyUsageOID.SERVER_AUTH)
|
|
236
|
+
elif token == "clientAuth":
|
|
237
|
+
mapped.append(ExtendedKeyUsageOID.CLIENT_AUTH)
|
|
238
|
+
elif token == "emailProtection":
|
|
239
|
+
mapped.append(ExtendedKeyUsageOID.EMAIL_PROTECTION)
|
|
240
|
+
elif token == "codeSigning":
|
|
241
|
+
mapped.append(ExtendedKeyUsageOID.CODE_SIGNING)
|
|
242
|
+
else:
|
|
243
|
+
mapped.append(x509.ObjectIdentifier(token))
|
|
244
|
+
builder = builder.add_extension(
|
|
245
|
+
x509.ExtendedKeyUsage(mapped), critical=False
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
if challenge_password:
|
|
249
|
+
builder = builder.add_attribute(
|
|
250
|
+
x509.OID_PKCS9_CHALLENGE_PASSWORD, challenge_password.encode()
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
sig_hash = hashes.SHA256()
|
|
254
|
+
csr = builder.sign(priv, sig_hash)
|
|
255
|
+
data = csr.public_bytes(
|
|
256
|
+
serialization.Encoding.DER if output_der else serialization.Encoding.PEM
|
|
257
|
+
)
|
|
258
|
+
return data
|
|
259
|
+
|
|
260
|
+
# --------------------------------------------------------------- Self-signed
|
|
261
|
+
async def create_self_signed( # type: ignore[override]
|
|
262
|
+
self,
|
|
263
|
+
key: KeyRef,
|
|
264
|
+
subject: SubjectSpec,
|
|
265
|
+
*,
|
|
266
|
+
serial: Optional[int] = None,
|
|
267
|
+
not_before: Optional[int] = None,
|
|
268
|
+
not_after: Optional[int] = None,
|
|
269
|
+
extensions: Optional[CertExtensionSpec] = None,
|
|
270
|
+
sig_alg: Optional[str] = None,
|
|
271
|
+
output_der: bool = False,
|
|
272
|
+
opts: Optional[Dict[str, Any]] = None,
|
|
273
|
+
) -> bytes:
|
|
274
|
+
"""Emit a simple self-signed certificate with sane defaults."""
|
|
275
|
+
if not key.material:
|
|
276
|
+
raise ValueError(
|
|
277
|
+
"create_self_signed: KeyRef.material must contain a PEM private key"
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
from datetime import datetime, timezone
|
|
281
|
+
|
|
282
|
+
priv = serialization.load_pem_private_key(key.material, password=None)
|
|
283
|
+
pub = priv.public_key()
|
|
284
|
+
|
|
285
|
+
nb = datetime.fromtimestamp(not_before or (_now() - 300), tz=timezone.utc)
|
|
286
|
+
na = datetime.fromtimestamp(
|
|
287
|
+
not_after or (_now() + 365 * 24 * 3600), tz=timezone.utc
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
builder = (
|
|
291
|
+
x509.CertificateBuilder()
|
|
292
|
+
.subject_name(_mk_name(subject))
|
|
293
|
+
.issuer_name(_mk_name(subject))
|
|
294
|
+
.serial_number(serial or x509.random_serial_number())
|
|
295
|
+
.not_valid_before(nb)
|
|
296
|
+
.not_valid_after(na)
|
|
297
|
+
.public_key(pub)
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
builder = builder.add_extension(
|
|
301
|
+
x509.SubjectKeyIdentifier.from_public_key(pub), critical=False
|
|
302
|
+
)
|
|
303
|
+
builder = builder.add_extension(
|
|
304
|
+
x509.BasicConstraints(ca=False, path_length=None), critical=True
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
cert = builder.sign(private_key=priv, algorithm=hashes.SHA256())
|
|
308
|
+
data = cert.public_bytes(
|
|
309
|
+
serialization.Encoding.DER if output_der else serialization.Encoding.PEM
|
|
310
|
+
)
|
|
311
|
+
return data
|
|
312
|
+
|
|
313
|
+
# ----------------------------------------------------------------- Sign via AD CS
|
|
314
|
+
async def sign_cert( # type: ignore[override]
|
|
315
|
+
self,
|
|
316
|
+
csr: bytes,
|
|
317
|
+
ca_key: KeyRef,
|
|
318
|
+
*,
|
|
319
|
+
issuer: Optional[SubjectSpec] = None,
|
|
320
|
+
ca_cert: Optional[bytes] = None,
|
|
321
|
+
serial: Optional[int] = None,
|
|
322
|
+
not_before: Optional[int] = None,
|
|
323
|
+
not_after: Optional[int] = None,
|
|
324
|
+
extensions: Optional[CertExtensionSpec] = None,
|
|
325
|
+
sig_alg: Optional[str] = None,
|
|
326
|
+
output_der: bool = False,
|
|
327
|
+
opts: Optional[Dict[str, Any]] = None,
|
|
328
|
+
) -> bytes:
|
|
329
|
+
"""Submit CSR to AD CS Web Enrollment and return the issued certificate."""
|
|
330
|
+
raise NotImplementedError("AD CS interaction not implemented in tests")
|
|
331
|
+
|
|
332
|
+
# --------------------------------------------------------------- Verify / Parse
|
|
333
|
+
async def verify_cert( # type: ignore[override]
|
|
334
|
+
self,
|
|
335
|
+
cert: bytes,
|
|
336
|
+
*,
|
|
337
|
+
trust_roots: Optional[Sequence[bytes]] = None,
|
|
338
|
+
intermediates: Optional[Sequence[bytes]] = None,
|
|
339
|
+
check_time: Optional[int] = None,
|
|
340
|
+
check_revocation: bool = False,
|
|
341
|
+
opts: Optional[Dict[str, Any]] = None,
|
|
342
|
+
) -> Dict[str, Any]:
|
|
343
|
+
c = _load_cert_any(cert)
|
|
344
|
+
now = _now() if check_time is None else int(check_time)
|
|
345
|
+
ok_time = c.not_valid_before.timestamp() <= now <= c.not_valid_after.timestamp()
|
|
346
|
+
|
|
347
|
+
result = {
|
|
348
|
+
"valid": ok_time,
|
|
349
|
+
"reason": None if ok_time else "time_window",
|
|
350
|
+
"subject": c.subject.rfc4514_string(),
|
|
351
|
+
"issuer": c.issuer.rfc4514_string(),
|
|
352
|
+
"not_before": int(c.not_valid_before.timestamp()),
|
|
353
|
+
"not_after": int(c.not_valid_after.timestamp()),
|
|
354
|
+
"is_ca": any(
|
|
355
|
+
isinstance(ext.value, x509.BasicConstraints) and ext.value.ca
|
|
356
|
+
for ext in c.extensions
|
|
357
|
+
),
|
|
358
|
+
"revocation_checked": False,
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
issuer_bytes = None
|
|
362
|
+
for src in intermediates or []:
|
|
363
|
+
try:
|
|
364
|
+
ic = _load_cert_any(src)
|
|
365
|
+
if ic.subject == c.issuer:
|
|
366
|
+
issuer_bytes = src
|
|
367
|
+
break
|
|
368
|
+
except Exception: # pragma: no cover - best effort
|
|
369
|
+
pass
|
|
370
|
+
if issuer_bytes is None:
|
|
371
|
+
for src in trust_roots or []:
|
|
372
|
+
try:
|
|
373
|
+
rc = _load_cert_any(src)
|
|
374
|
+
if rc.subject == c.issuer:
|
|
375
|
+
issuer_bytes = src
|
|
376
|
+
break
|
|
377
|
+
except Exception: # pragma: no cover - best effort
|
|
378
|
+
pass
|
|
379
|
+
|
|
380
|
+
if issuer_bytes is not None:
|
|
381
|
+
try:
|
|
382
|
+
issuer = _load_cert_any(issuer_bytes)
|
|
383
|
+
pub = issuer.public_key()
|
|
384
|
+
if isinstance(pub, rsa.RSAPublicKey):
|
|
385
|
+
pub.verify(
|
|
386
|
+
c.signature,
|
|
387
|
+
c.tbs_certificate_bytes,
|
|
388
|
+
padding.PKCS1v15(),
|
|
389
|
+
c.signature_hash_algorithm,
|
|
390
|
+
)
|
|
391
|
+
else:
|
|
392
|
+
pub.verify(
|
|
393
|
+
c.signature,
|
|
394
|
+
c.tbs_certificate_bytes,
|
|
395
|
+
c.signature_hash_algorithm,
|
|
396
|
+
)
|
|
397
|
+
result["valid"] = result["valid"] and True
|
|
398
|
+
except Exception:
|
|
399
|
+
result["valid"] = False
|
|
400
|
+
result["reason"] = "bad_signature"
|
|
401
|
+
return result
|
|
402
|
+
|
|
403
|
+
async def parse_cert( # type: ignore[override]
|
|
404
|
+
self,
|
|
405
|
+
cert: bytes,
|
|
406
|
+
*,
|
|
407
|
+
include_extensions: bool = True,
|
|
408
|
+
opts: Optional[Dict[str, Any]] = None,
|
|
409
|
+
) -> Dict[str, Any]:
|
|
410
|
+
c = _load_cert_any(cert)
|
|
411
|
+
out: Dict[str, Any] = {
|
|
412
|
+
"serial": int(c.serial_number),
|
|
413
|
+
"sig_alg": c.signature_algorithm_oid.dotted_string,
|
|
414
|
+
"issuer": c.issuer.rfc4514_string(),
|
|
415
|
+
"subject": c.subject.rfc4514_string(),
|
|
416
|
+
"not_before": int(c.not_valid_before.timestamp()),
|
|
417
|
+
"not_after": int(c.not_valid_after.timestamp()),
|
|
418
|
+
"skid": None,
|
|
419
|
+
"akid": None,
|
|
420
|
+
"san": None,
|
|
421
|
+
"eku": None,
|
|
422
|
+
"key_usage": None,
|
|
423
|
+
"is_ca": False,
|
|
424
|
+
}
|
|
425
|
+
if include_extensions:
|
|
426
|
+
for ext in c.extensions:
|
|
427
|
+
if isinstance(ext.value, x509.SubjectKeyIdentifier):
|
|
428
|
+
out["skid"] = ext.value.digest.hex(":")
|
|
429
|
+
elif isinstance(ext.value, x509.AuthorityKeyIdentifier):
|
|
430
|
+
out["akid"] = (ext.value.key_identifier or b"").hex(":")
|
|
431
|
+
elif isinstance(ext.value, x509.SubjectAlternativeName):
|
|
432
|
+
san = {"dns": [], "ip": [], "uri": [], "email": []}
|
|
433
|
+
for gn in ext.value:
|
|
434
|
+
if isinstance(gn, x509.DNSName):
|
|
435
|
+
san["dns"].append(gn.value)
|
|
436
|
+
elif isinstance(gn, x509.RFC822Name):
|
|
437
|
+
san["email"].append(gn.value)
|
|
438
|
+
elif isinstance(gn, x509.UniformResourceIdentifier):
|
|
439
|
+
san["uri"].append(gn.value)
|
|
440
|
+
elif isinstance(gn, x509.IPAddress):
|
|
441
|
+
san["ip"].append(str(gn.value))
|
|
442
|
+
out["san"] = san
|
|
443
|
+
elif isinstance(ext.value, x509.ExtendedKeyUsage):
|
|
444
|
+
out["eku"] = [oid.dotted_string for oid in ext.value]
|
|
445
|
+
elif isinstance(ext.value, x509.KeyUsage):
|
|
446
|
+
out["key_usage"] = {
|
|
447
|
+
"digital_signature": ext.value.digital_signature,
|
|
448
|
+
"content_commitment": ext.value.content_commitment,
|
|
449
|
+
"key_encipherment": ext.value.key_encipherment,
|
|
450
|
+
"data_encipherment": ext.value.data_encipherment,
|
|
451
|
+
"key_agreement": ext.value.key_agreement,
|
|
452
|
+
"key_cert_sign": ext.value.key_cert_sign,
|
|
453
|
+
"crl_sign": ext.value.crl_sign,
|
|
454
|
+
"encipher_only": ext.value.encipher_only,
|
|
455
|
+
"decipher_only": ext.value.decipher_only,
|
|
456
|
+
}
|
|
457
|
+
elif isinstance(ext.value, x509.BasicConstraints):
|
|
458
|
+
out["is_ca"] = ext.value.ca
|
|
459
|
+
return out
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
__all__ = ["MsAdcsCertService", "_AuthCfg"]
|