carnelian 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.
- carnelian-0.1.0/LICENSE +21 -0
- carnelian-0.1.0/PKG-INFO +73 -0
- carnelian-0.1.0/README.md +45 -0
- carnelian-0.1.0/carnelian/__init__.py +6 -0
- carnelian-0.1.0/carnelian/cas.py +101 -0
- carnelian-0.1.0/carnelian/der.py +174 -0
- carnelian-0.1.0/carnelian/federation.py +213 -0
- carnelian-0.1.0/carnelian/fetching.py +83 -0
- carnelian-0.1.0/carnelian/jose.py +157 -0
- carnelian-0.1.0/carnelian/ldap.py +303 -0
- carnelian-0.1.0/carnelian/oidc.py +188 -0
- carnelian-0.1.0/carnelian/saml.py +249 -0
- carnelian-0.1.0/carnelian/scim.py +1286 -0
- carnelian-0.1.0/carnelian/signatures.py +225 -0
- carnelian-0.1.0/carnelian/version.py +2 -0
- carnelian-0.1.0/carnelian/xmlTree.py +233 -0
- carnelian-0.1.0/carnelian/xmldsig.py +142 -0
- carnelian-0.1.0/carnelian.egg-info/PKG-INFO +73 -0
- carnelian-0.1.0/carnelian.egg-info/SOURCES.txt +32 -0
- carnelian-0.1.0/carnelian.egg-info/dependency_links.txt +1 -0
- carnelian-0.1.0/carnelian.egg-info/requires.txt +6 -0
- carnelian-0.1.0/carnelian.egg-info/top_level.txt +1 -0
- carnelian-0.1.0/pyproject.toml +52 -0
- carnelian-0.1.0/setup.cfg +4 -0
- carnelian-0.1.0/tests/testCAS.py +156 -0
- carnelian-0.1.0/tests/testFederation.py +212 -0
- carnelian-0.1.0/tests/testJose.py +105 -0
- carnelian-0.1.0/tests/testLDAP.py +79 -0
- carnelian-0.1.0/tests/testOIDC.py +197 -0
- carnelian-0.1.0/tests/testSAML.py +206 -0
- carnelian-0.1.0/tests/testSCIM.py +496 -0
- carnelian-0.1.0/tests/testSignatures.py +121 -0
- carnelian-0.1.0/tests/testXML.py +77 -0
- carnelian-0.1.0/tests/testXMLDSig.py +98 -0
carnelian-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the Carnelian authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
carnelian-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: carnelian
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Sign-in for Python on the standard library alone: OpenID Connect, SAML 2.0, LDAP and SCIM 2.0.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Source, https://github.com/rbraunm/carnelian
|
|
7
|
+
Project-URL: Issues, https://github.com/rbraunm/carnelian/issues
|
|
8
|
+
Keywords: openid-connect,oidc,saml,saml2,ldap,active-directory,scim,sign-in,sso
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Topic :: Security
|
|
17
|
+
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
|
|
18
|
+
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP
|
|
19
|
+
Requires-Python: >=3.13
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
24
|
+
Requires-Dist: cryptography>=44; extra == "test"
|
|
25
|
+
Requires-Dist: lxml>=5; extra == "test"
|
|
26
|
+
Requires-Dist: signxml>=4; extra == "test"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# Carnelian
|
|
30
|
+
|
|
31
|
+
Sign-in for Python applications on the standard library alone:
|
|
32
|
+
|
|
33
|
+
- **OpenID Connect** relying party (discovery, the authorization-code flow with PKCE, ID
|
|
34
|
+
token checks);
|
|
35
|
+
- **SAML 2.0** service provider (requests, responses, XML signatures with exclusive
|
|
36
|
+
canonicalization, protection against signature wrapping);
|
|
37
|
+
- **Research and education federations** (InCommon, the national federations, eduGAIN):
|
|
38
|
+
institutions' signed metadata by the Metadata Query protocol, their scopes, scoped
|
|
39
|
+
identifiers (subject-id, pairwise-id, eduPersonPrincipalName), and the service provider's
|
|
40
|
+
own metadata to register;
|
|
41
|
+
- **CAS** client (Apereo CAS protocol 3.0), the sign-in many universities in France, Spain
|
|
42
|
+
and Latin America run;
|
|
43
|
+
- **LDAP** client for Active Directory and other directories (bind and search over TLS);
|
|
44
|
+
- **SCIM 2.0** service provider (users with the enterprise extension, groups, the full
|
|
45
|
+
filter grammar, PATCH, paging, attribute selection, discovery), behind the application's
|
|
46
|
+
own store and web server; checked against the RFC examples and Microsoft Entra ID's
|
|
47
|
+
documented requests.
|
|
48
|
+
|
|
49
|
+
No third-party packages, so nothing but its own MIT licence governs where it can be used.
|
|
50
|
+
Its cryptography only *verifies* signatures with public keys -- it never signs or decrypts
|
|
51
|
+
with a secret -- and it leaves TLS to Python's own `ssl` module.
|
|
52
|
+
|
|
53
|
+
Status: being built. It starts life as the sign-in layer of
|
|
54
|
+
[OpenFurrow](https://github.com/rbraunm/openfurrow) and is tested against real identity
|
|
55
|
+
providers.
|
|
56
|
+
|
|
57
|
+
## Install
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
python -m pip install carnelian
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Python 3.13 or newer; nothing else is installed with it.
|
|
64
|
+
|
|
65
|
+
## Releases
|
|
66
|
+
|
|
67
|
+
A release is a version tag `v<version>` on a commit of `main` whose `carnelian/version.py`
|
|
68
|
+
names that version; the `publish` workflow builds it and publishes it to PyPI by trusted
|
|
69
|
+
publishing, with no token stored anywhere.
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
|
|
73
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Carnelian
|
|
2
|
+
|
|
3
|
+
Sign-in for Python applications on the standard library alone:
|
|
4
|
+
|
|
5
|
+
- **OpenID Connect** relying party (discovery, the authorization-code flow with PKCE, ID
|
|
6
|
+
token checks);
|
|
7
|
+
- **SAML 2.0** service provider (requests, responses, XML signatures with exclusive
|
|
8
|
+
canonicalization, protection against signature wrapping);
|
|
9
|
+
- **Research and education federations** (InCommon, the national federations, eduGAIN):
|
|
10
|
+
institutions' signed metadata by the Metadata Query protocol, their scopes, scoped
|
|
11
|
+
identifiers (subject-id, pairwise-id, eduPersonPrincipalName), and the service provider's
|
|
12
|
+
own metadata to register;
|
|
13
|
+
- **CAS** client (Apereo CAS protocol 3.0), the sign-in many universities in France, Spain
|
|
14
|
+
and Latin America run;
|
|
15
|
+
- **LDAP** client for Active Directory and other directories (bind and search over TLS);
|
|
16
|
+
- **SCIM 2.0** service provider (users with the enterprise extension, groups, the full
|
|
17
|
+
filter grammar, PATCH, paging, attribute selection, discovery), behind the application's
|
|
18
|
+
own store and web server; checked against the RFC examples and Microsoft Entra ID's
|
|
19
|
+
documented requests.
|
|
20
|
+
|
|
21
|
+
No third-party packages, so nothing but its own MIT licence governs where it can be used.
|
|
22
|
+
Its cryptography only *verifies* signatures with public keys -- it never signs or decrypts
|
|
23
|
+
with a secret -- and it leaves TLS to Python's own `ssl` module.
|
|
24
|
+
|
|
25
|
+
Status: being built. It starts life as the sign-in layer of
|
|
26
|
+
[OpenFurrow](https://github.com/rbraunm/openfurrow) and is tested against real identity
|
|
27
|
+
providers.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
python -m pip install carnelian
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Python 3.13 or newer; nothing else is installed with it.
|
|
36
|
+
|
|
37
|
+
## Releases
|
|
38
|
+
|
|
39
|
+
A release is a version tag `v<version>` on a commit of `main` whose `carnelian/version.py`
|
|
40
|
+
names that version; the `publish` workflow builds it and publishes it to PyPI by trusted
|
|
41
|
+
publishing, with no token stored anywhere.
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""A CAS client (Apereo CAS protocol 3.0): the sign-in many universities run, in France, Spain and Latin America above all.
|
|
3
|
+
|
|
4
|
+
Sign-in has two halves, as for OpenID Connect: `beginSignIn` gives the CAS login address
|
|
5
|
+
and a Pending record to keep server-side; `finishSignIn` takes it and the query the browser
|
|
6
|
+
came back with. CAS has no state parameter, so the service address carries one: the ticket
|
|
7
|
+
is only accepted for the sign-in this browser started, and validated against exactly the
|
|
8
|
+
service address it was issued for. The ticket is checked by the CAS server itself
|
|
9
|
+
(`/p3/serviceValidate`, over HTTPS), which answers the user and the attributes it releases.
|
|
10
|
+
Proxy tickets and proxy-granting are not used.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hmac
|
|
16
|
+
import re
|
|
17
|
+
import secrets
|
|
18
|
+
import time
|
|
19
|
+
import urllib.parse
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
|
|
22
|
+
from carnelian.fetching import Fetcher
|
|
23
|
+
from carnelian.xmlTree import XMLRefused, parse
|
|
24
|
+
|
|
25
|
+
casNamespace = "http://www.yale.edu/tp/cas"
|
|
26
|
+
_ticketPattern = re.compile(r"^ST-[A-Za-z0-9.\-_]{1,256}$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class CASRefused(ValueError):
|
|
30
|
+
"""A CAS sign-in that did not complete, with why."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Pending:
|
|
35
|
+
state: str
|
|
36
|
+
startedAt: float
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class CASIdentity:
|
|
41
|
+
userName: str
|
|
42
|
+
attributes: dict[str, tuple[str, ...]] = field(repr=False)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CASServer:
|
|
46
|
+
"""One CAS server (its address ends in /cas or wherever /login lives) and this service's return address."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, serverURL: str, serviceURL: str, fetcher: Fetcher, pendingSeconds: int = 600, clock=time.time):
|
|
49
|
+
if not serverURL.startswith("https://") or serverURL.endswith("/"):
|
|
50
|
+
raise ValueError("serverURL must be an https address without a trailing slash")
|
|
51
|
+
if "?" in serviceURL or "#" in serviceURL:
|
|
52
|
+
raise ValueError("serviceURL carries no query or fragment of its own; the sign-in adds its state")
|
|
53
|
+
self.serverURL, self.serviceURL, self.fetcher = serverURL, serviceURL, fetcher
|
|
54
|
+
self.pendingSeconds, self.clock = pendingSeconds, clock
|
|
55
|
+
|
|
56
|
+
def _service(self, state: str) -> str:
|
|
57
|
+
return f"{self.serviceURL}?{urllib.parse.urlencode({'state': state})}"
|
|
58
|
+
|
|
59
|
+
def beginSignIn(self) -> tuple[str, Pending]:
|
|
60
|
+
pending = Pending(state=secrets.token_urlsafe(32), startedAt=self.clock())
|
|
61
|
+
return f"{self.serverURL}/login?{urllib.parse.urlencode({'service': self._service(pending.state)})}", pending
|
|
62
|
+
|
|
63
|
+
def finishSignIn(self, pending: Pending, query: dict[str, str]) -> CASIdentity:
|
|
64
|
+
if self.clock() - pending.startedAt > self.pendingSeconds:
|
|
65
|
+
raise CASRefused("the sign-in took too long; start again")
|
|
66
|
+
if not hmac.compare_digest(str(query.get("state", "")), pending.state):
|
|
67
|
+
raise CASRefused("the sign-in's state does not match")
|
|
68
|
+
ticket = query.get("ticket", "")
|
|
69
|
+
if not _ticketPattern.match(ticket):
|
|
70
|
+
raise CASRefused("the CAS server sent no service ticket")
|
|
71
|
+
address = f"{self.serverURL}/p3/serviceValidate?" + urllib.parse.urlencode(
|
|
72
|
+
{"service": self._service(pending.state), "ticket": ticket})
|
|
73
|
+
return self.read(self.fetcher.getBytes(address, "application/xml"))
|
|
74
|
+
|
|
75
|
+
def read(self, answer: bytes) -> CASIdentity:
|
|
76
|
+
"""The CAS server's validation answer: the user and the released attributes, or why it refused."""
|
|
77
|
+
try:
|
|
78
|
+
return self._read(parse(answer))
|
|
79
|
+
except XMLRefused as error:
|
|
80
|
+
raise CASRefused(f"the CAS server's answer is refused: {error}") from None
|
|
81
|
+
|
|
82
|
+
def _read(self, root) -> CASIdentity:
|
|
83
|
+
if not root.isA(casNamespace, "serviceResponse"):
|
|
84
|
+
raise CASRefused("the CAS server's answer is not a serviceResponse")
|
|
85
|
+
failure = root.only(casNamespace, "authenticationFailure", required=False)
|
|
86
|
+
if failure is not None:
|
|
87
|
+
raise CASRefused(f"the CAS server refused the ticket: {failure.attribute('code')} {failure.text.strip()}".rstrip())
|
|
88
|
+
success = root.only(casNamespace, "authenticationSuccess")
|
|
89
|
+
if success.childrenNamed(casNamespace, "proxies"):
|
|
90
|
+
raise CASRefused("the ticket came through a proxy, which is refused")
|
|
91
|
+
userName = success.only(casNamespace, "user").text.strip()
|
|
92
|
+
if not userName:
|
|
93
|
+
raise CASRefused("the CAS server named no user")
|
|
94
|
+
attributes: dict[str, tuple[str, ...]] = {}
|
|
95
|
+
released = success.only(casNamespace, "attributes", required=False)
|
|
96
|
+
if released is not None:
|
|
97
|
+
for attribute in released.elements():
|
|
98
|
+
if attribute.namespaceURI != casNamespace:
|
|
99
|
+
raise CASRefused(f"an attribute outside the CAS namespace: {attribute.localName}")
|
|
100
|
+
attributes[attribute.localName] = attributes.get(attribute.localName, ()) + (attribute.text.strip(),)
|
|
101
|
+
return CASIdentity(userName=userName, attributes=attributes)
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Just enough DER (X.690) to read public keys: SubjectPublicKeyInfo and X.509 certificates.
|
|
3
|
+
|
|
4
|
+
Strict DER only: definite, minimally encoded lengths, and nothing left over where a
|
|
5
|
+
structure ends. Keys are RSA or EC on P-256, P-384 and P-521 with uncompressed points.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
from carnelian.signatures import ECPublicKey, RSAPublicKey, curves
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DERError(ValueError):
|
|
18
|
+
"""Bytes that are not the strict DER expected here."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Element:
|
|
23
|
+
tag: int
|
|
24
|
+
content: bytes
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def readElement(data: bytes, offset: int = 0) -> tuple[Element, int]:
|
|
28
|
+
"""One TLV at `offset`; returns it and the offset just past it."""
|
|
29
|
+
if offset + 2 > len(data):
|
|
30
|
+
raise DERError("truncated DER element")
|
|
31
|
+
tag = data[offset]
|
|
32
|
+
if tag & 0x1F == 0x1F:
|
|
33
|
+
raise DERError("multi-byte DER tags are not used here")
|
|
34
|
+
first = data[offset + 1]
|
|
35
|
+
position = offset + 2
|
|
36
|
+
if first < 0x80:
|
|
37
|
+
length = first
|
|
38
|
+
else:
|
|
39
|
+
count = first & 0x7F
|
|
40
|
+
if count == 0:
|
|
41
|
+
raise DERError("indefinite lengths are not DER")
|
|
42
|
+
if count > 4 or position + count > len(data):
|
|
43
|
+
raise DERError("DER length out of range")
|
|
44
|
+
length = int.from_bytes(data[position:position + count], "big")
|
|
45
|
+
if length < 0x80 or data[position] == 0:
|
|
46
|
+
raise DERError("DER length is not minimally encoded")
|
|
47
|
+
position += count
|
|
48
|
+
end = position + length
|
|
49
|
+
if end > len(data):
|
|
50
|
+
raise DERError("truncated DER content")
|
|
51
|
+
return Element(tag, data[position:end]), end
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def readAll(data: bytes) -> list[Element]:
|
|
55
|
+
"""Every element of a constructed value's content, which must be used up exactly."""
|
|
56
|
+
elements, offset = [], 0
|
|
57
|
+
while offset < len(data):
|
|
58
|
+
element, offset = readElement(data, offset)
|
|
59
|
+
elements.append(element)
|
|
60
|
+
return elements
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def readOne(data: bytes) -> Element:
|
|
64
|
+
element, end = readElement(data)
|
|
65
|
+
if end != len(data):
|
|
66
|
+
raise DERError("bytes left after the DER value")
|
|
67
|
+
return element
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _expect(element: Element, tag: int, what: str) -> Element:
|
|
71
|
+
if element.tag != tag:
|
|
72
|
+
raise DERError(f"{what}: expected tag 0x{tag:02x}, got 0x{element.tag:02x}")
|
|
73
|
+
return element
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def readInteger(element: Element) -> int:
|
|
77
|
+
_expect(element, 0x02, "INTEGER")
|
|
78
|
+
content = element.content
|
|
79
|
+
if not content or (len(content) > 1 and ((content[0] == 0 and content[1] < 0x80) or (content[0] == 0xFF and content[1] >= 0x80))):
|
|
80
|
+
raise DERError("INTEGER is not minimally encoded")
|
|
81
|
+
return int.from_bytes(content, "big", signed=True)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def readOID(element: Element) -> str:
|
|
85
|
+
content = _expect(element, 0x06, "OBJECT IDENTIFIER").content
|
|
86
|
+
if not content:
|
|
87
|
+
raise DERError("empty OBJECT IDENTIFIER")
|
|
88
|
+
values, current = [], 0
|
|
89
|
+
for index, byte in enumerate(content):
|
|
90
|
+
if current == 0 and byte == 0x80:
|
|
91
|
+
raise DERError("OBJECT IDENTIFIER is not minimally encoded")
|
|
92
|
+
current = (current << 7) | (byte & 0x7F)
|
|
93
|
+
if not byte & 0x80:
|
|
94
|
+
values.append(current)
|
|
95
|
+
current = 0
|
|
96
|
+
elif index == len(content) - 1:
|
|
97
|
+
raise DERError("truncated OBJECT IDENTIFIER")
|
|
98
|
+
first = min(values[0] // 40, 2)
|
|
99
|
+
return ".".join(str(part) for part in [first, values[0] - 40 * first, *values[1:]])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def readBitString(element: Element) -> bytes:
|
|
103
|
+
content = _expect(element, 0x03, "BIT STRING").content
|
|
104
|
+
if not content or content[0] != 0:
|
|
105
|
+
raise DERError("a key's BIT STRING has whole bytes")
|
|
106
|
+
return content[1:]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
rsaEncryption = "1.2.840.113549.1.1.1"
|
|
110
|
+
ecPublicKey = "1.2.840.10045.2.1"
|
|
111
|
+
curveForOID = {"1.2.840.10045.3.1.7": "P-256", "1.3.132.0.34": "P-384", "1.3.132.0.35": "P-521"}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def publicKeyFromInfo(info: bytes) -> RSAPublicKey | ECPublicKey:
|
|
115
|
+
"""The key in a DER SubjectPublicKeyInfo."""
|
|
116
|
+
elements = readAll(_expect(readOne(info), 0x30, "SubjectPublicKeyInfo").content)
|
|
117
|
+
if len(elements) != 2:
|
|
118
|
+
raise DERError("a SubjectPublicKeyInfo has two parts")
|
|
119
|
+
parts = readAll(_expect(elements[0], 0x30, "AlgorithmIdentifier").content)
|
|
120
|
+
kind = readOID(parts[0])
|
|
121
|
+
keyBytes = readBitString(elements[1])
|
|
122
|
+
if kind == rsaEncryption:
|
|
123
|
+
numbers = readAll(_expect(readOne(keyBytes), 0x30, "RSAPublicKey").content)
|
|
124
|
+
if len(numbers) != 2:
|
|
125
|
+
raise DERError("an RSAPublicKey has two integers")
|
|
126
|
+
return RSAPublicKey(readInteger(numbers[0]), readInteger(numbers[1]))
|
|
127
|
+
if kind == ecPublicKey:
|
|
128
|
+
curveOID = readOID(parts[1])
|
|
129
|
+
if curveOID not in curveForOID:
|
|
130
|
+
raise DERError(f"EC curve {curveOID} is not supported")
|
|
131
|
+
curveName = curveForOID[curveOID]
|
|
132
|
+
size = curves[curveName].length
|
|
133
|
+
if len(keyBytes) != 1 + 2 * size or keyBytes[0] != 0x04:
|
|
134
|
+
raise DERError("an EC public point is uncompressed (0x04, then x and y)")
|
|
135
|
+
return ECPublicKey(curveName, int.from_bytes(keyBytes[1:1 + size], "big"), int.from_bytes(keyBytes[1 + size:], "big"))
|
|
136
|
+
raise DERError(f"public key algorithm {kind} is not supported")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def subjectPublicKeyInfo(certificate: bytes) -> bytes:
|
|
140
|
+
"""The SubjectPublicKeyInfo of a DER X.509 certificate, as DER."""
|
|
141
|
+
outer = readAll(_expect(readOne(certificate), 0x30, "Certificate").content)
|
|
142
|
+
if len(outer) != 3:
|
|
143
|
+
raise DERError("a Certificate has three parts")
|
|
144
|
+
fields = readAll(_expect(outer[0], 0x30, "TBSCertificate").content)
|
|
145
|
+
if fields and fields[0].tag == 0xA0:
|
|
146
|
+
fields = fields[1:]
|
|
147
|
+
if len(fields) < 6:
|
|
148
|
+
raise DERError("TBSCertificate is too short")
|
|
149
|
+
info = _expect(fields[5], 0x30, "SubjectPublicKeyInfo")
|
|
150
|
+
return bytes([0x30]) + _length(len(info.content)) + info.content
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _length(length: int) -> bytes:
|
|
154
|
+
if length < 0x80:
|
|
155
|
+
return bytes([length])
|
|
156
|
+
body = length.to_bytes((length.bit_length() + 7) // 8, "big")
|
|
157
|
+
return bytes([0x80 | len(body)]) + body
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
_pemBlock = re.compile(r"-----BEGIN ([A-Z ]+)-----\s*(.*?)\s*-----END \1-----", re.S)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def fromPEM(text: str, label: str) -> bytes:
|
|
164
|
+
"""The DER inside the one PEM block with this label."""
|
|
165
|
+
blocks = [(found, body) for found, body in _pemBlock.findall(text) if found == label]
|
|
166
|
+
if len(blocks) != 1:
|
|
167
|
+
raise DERError(f"expected one PEM block '{label}', found {len(blocks)}")
|
|
168
|
+
return base64.b64decode("".join(blocks[0][1].split()), validate=True)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def publicKeyFromCertificate(certificate: bytes | str) -> RSAPublicKey | ECPublicKey:
|
|
172
|
+
"""The key of an X.509 certificate given as DER bytes or PEM text."""
|
|
173
|
+
der = fromPEM(certificate, "CERTIFICATE") if isinstance(certificate, str) else certificate
|
|
174
|
+
return publicKeyFromInfo(subjectPublicKeyInfo(der))
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""SAML research and education federations: InCommon, the national federations and eduGAIN.
|
|
3
|
+
|
|
4
|
+
A federation vouches for its institutions by signing their metadata. Each institution's
|
|
5
|
+
metadata is fetched by the Metadata Query protocol (MDQ: one small signed document per
|
|
6
|
+
entity, as InCommon serves its own and eduGAIN's), its signature checked against the
|
|
7
|
+
federation's signing certificate, and its validUntil required and honoured. What is read:
|
|
8
|
+
the identity provider (its single sign-on address and signing keys), its display names, the
|
|
9
|
+
federation that registered it, its entity categories, and its scopes.
|
|
10
|
+
|
|
11
|
+
A federation's identity is a scoped identifier, `value@scope`: SAML's subject-id or
|
|
12
|
+
pairwise-id (the SAML V2.0 Subject Identifier Attributes profile) or eduPersonPrincipalName.
|
|
13
|
+
An institution may only vouch for identifiers in the scopes its federation registered for
|
|
14
|
+
it, so one university cannot sign in another's people; a scope written as a regular
|
|
15
|
+
expression is refused by name. The service provider's own metadata, which the federation
|
|
16
|
+
registers, is written by `serviceProviderMetadata`.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import re
|
|
22
|
+
import time
|
|
23
|
+
import urllib.parse
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
|
|
26
|
+
from carnelian.der import publicKeyFromCertificate
|
|
27
|
+
from carnelian.fetching import Fetcher
|
|
28
|
+
from carnelian.saml import IdentityProvider, SAMLIdentity, SAMLRefused, _attribute, _time, identityProviderFromDescriptor, metadataNamespace
|
|
29
|
+
from carnelian.xmldsig import SignatureRefused, verifyEnveloped
|
|
30
|
+
from carnelian.xmlTree import XMLRefused, parse
|
|
31
|
+
|
|
32
|
+
shibbolethMetadata = "urn:mace:shibboleth:metadata:1.0"
|
|
33
|
+
uiNamespace = "urn:oasis:names:tc:SAML:metadata:ui"
|
|
34
|
+
registrationNamespace = "urn:oasis:names:tc:SAML:metadata:rpi"
|
|
35
|
+
entityAttributeNamespace = "urn:oasis:names:tc:SAML:metadata:attribute"
|
|
36
|
+
assertionNamespace = "urn:oasis:names:tc:SAML:2.0:assertion"
|
|
37
|
+
entityCategory = "http://macedir.org/entity-category"
|
|
38
|
+
hideFromDiscovery = "http://refeds.org/category/hide-from-discovery"
|
|
39
|
+
researchAndScholarship = "http://refeds.org/category/research-and-scholarship"
|
|
40
|
+
metadataMediaType = "application/samlmetadata+xml"
|
|
41
|
+
|
|
42
|
+
subjectID = "urn:oasis:names:tc:SAML:attribute:subject-id"
|
|
43
|
+
pairwiseID = "urn:oasis:names:tc:SAML:attribute:pairwise-id"
|
|
44
|
+
eduPersonPrincipalName = "urn:oid:1.3.6.1.4.1.5923.1.1.1.6"
|
|
45
|
+
mail = "urn:oid:0.9.2342.19200300.100.1.3"
|
|
46
|
+
displayName = "urn:oid:2.16.840.1.113730.3.1.241"
|
|
47
|
+
givenName = "urn:oid:2.5.4.42"
|
|
48
|
+
surname = "urn:oid:2.5.4.4"
|
|
49
|
+
scopedIdentifiers = (subjectID, pairwiseID, eduPersonPrincipalName)
|
|
50
|
+
|
|
51
|
+
# The SAML V2.0 Subject Identifier Attributes profile, section 3.3.1 (and 3.4.1 for pairwise-id).
|
|
52
|
+
_subjectSyntax = re.compile(r"^[0-9A-Za-z][-=0-9A-Za-z]{0,126}@[0-9A-Za-z][-.0-9A-Za-z]{0,126}$")
|
|
53
|
+
_principalSyntax = re.compile(r"^[^@\s]+@[0-9A-Za-z][-.0-9A-Za-z]*$")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Institution:
|
|
58
|
+
entityID: str
|
|
59
|
+
displayNames: dict[str, str]
|
|
60
|
+
registrationAuthority: str | None
|
|
61
|
+
entityCategories: tuple[str, ...]
|
|
62
|
+
scopes: tuple[str, ...]
|
|
63
|
+
identityProvider: IdentityProvider
|
|
64
|
+
validUntil: float
|
|
65
|
+
|
|
66
|
+
def displayName(self, language: str) -> str:
|
|
67
|
+
"""The display name in a language, else in English, else the entity ID."""
|
|
68
|
+
base = language.split("-")[0].lower()
|
|
69
|
+
for wanted in (language.lower(), base, "en"):
|
|
70
|
+
for name, text in self.displayNames.items():
|
|
71
|
+
if name.lower() == wanted:
|
|
72
|
+
return text
|
|
73
|
+
return self.entityID
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def hiddenFromDiscovery(self) -> bool:
|
|
77
|
+
return hideFromDiscovery in self.entityCategories
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _institution(root, signedBy: str) -> Institution:
|
|
81
|
+
identityProvider = identityProviderFromDescriptor(root)
|
|
82
|
+
validUntil = _time(root.attribute("validUntil"), "the metadata's validUntil")
|
|
83
|
+
descriptor = root.only(metadataNamespace, "IDPSSODescriptor")
|
|
84
|
+
scopes, names = [], {}
|
|
85
|
+
extensions = descriptor.only(metadataNamespace, "Extensions", required=False)
|
|
86
|
+
if extensions is not None:
|
|
87
|
+
for scope in extensions.childrenNamed(shibbolethMetadata, "Scope"):
|
|
88
|
+
if scope.attribute("regexp") not in (None, "false", "0"):
|
|
89
|
+
raise SAMLRefused(f"{root.attribute('entityID')} has a scope written as a regular expression, which is refused")
|
|
90
|
+
if scope.text.strip().lower() not in scopes:
|
|
91
|
+
scopes.append(scope.text.strip().lower())
|
|
92
|
+
information = extensions.only(uiNamespace, "UIInfo", required=False)
|
|
93
|
+
if information is not None:
|
|
94
|
+
for name in information.childrenNamed(uiNamespace, "DisplayName"):
|
|
95
|
+
names[name.attribute("lang", "http://www.w3.org/XML/1998/namespace") or ""] = name.text.strip()
|
|
96
|
+
authority, categories = None, []
|
|
97
|
+
entityExtensions = root.only(metadataNamespace, "Extensions", required=False)
|
|
98
|
+
if entityExtensions is not None:
|
|
99
|
+
registration = entityExtensions.only(registrationNamespace, "RegistrationInfo", required=False)
|
|
100
|
+
authority = registration.attribute("registrationAuthority") if registration is not None else None
|
|
101
|
+
attributes = entityExtensions.only(entityAttributeNamespace, "EntityAttributes", required=False)
|
|
102
|
+
if attributes is not None:
|
|
103
|
+
for attribute in attributes.childrenNamed(assertionNamespace, "Attribute"):
|
|
104
|
+
if attribute.attribute("Name") == entityCategory:
|
|
105
|
+
categories += [value.text.strip() for value in attribute.childrenNamed(assertionNamespace, "AttributeValue")]
|
|
106
|
+
if not scopes:
|
|
107
|
+
raise SAMLRefused(f"{root.attribute('entityID')} has no scope in {signedBy}'s metadata, so it can vouch for no one")
|
|
108
|
+
return Institution(entityID=root.attribute("entityID"), displayNames=names, registrationAuthority=authority,
|
|
109
|
+
entityCategories=tuple(categories), scopes=tuple(scopes), identityProvider=identityProvider,
|
|
110
|
+
validUntil=validUntil)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Federation:
|
|
114
|
+
"""A federation's institutions, fetched one by one from its MDQ service and checked against its signing certificate."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, name: str, mdqURL: str, signingCertificate: str | bytes, fetcher: Fetcher,
|
|
117
|
+
maximumCacheSeconds: float = 6 * 3600, clock=time.time):
|
|
118
|
+
if not mdqURL.startswith("https://") or mdqURL.endswith("/"):
|
|
119
|
+
raise ValueError("mdqURL must be an https address without a trailing slash")
|
|
120
|
+
self.name, self.mdqURL, self.fetcher = name, mdqURL, fetcher
|
|
121
|
+
self.signingKey = publicKeyFromCertificate(signingCertificate)
|
|
122
|
+
self.maximumCacheSeconds, self.clock = maximumCacheSeconds, clock
|
|
123
|
+
self._cache: dict[str, tuple[float, Institution]] = {}
|
|
124
|
+
|
|
125
|
+
def institution(self, entityID: str) -> Institution:
|
|
126
|
+
now = self.clock()
|
|
127
|
+
cached = self._cache.get(entityID)
|
|
128
|
+
if cached is not None and cached[0] > now:
|
|
129
|
+
return cached[1]
|
|
130
|
+
address = f"{self.mdqURL}/entities/{urllib.parse.quote(entityID, safe='')}"
|
|
131
|
+
institution = self.read(self.fetcher.getBytes(address, metadataMediaType), entityID)
|
|
132
|
+
self._cache[entityID] = (min(institution.validUntil, now + self.maximumCacheSeconds), institution)
|
|
133
|
+
return institution
|
|
134
|
+
|
|
135
|
+
def read(self, metadata: bytes, entityID: str) -> Institution:
|
|
136
|
+
"""One entity's signed metadata, as the MDQ service answers it, checked."""
|
|
137
|
+
try:
|
|
138
|
+
root = parse(metadata)
|
|
139
|
+
if not root.isA(metadataNamespace, "EntityDescriptor"):
|
|
140
|
+
raise SAMLRefused(f"{self.name} did not answer with an EntityDescriptor")
|
|
141
|
+
if verifyEnveloped(root, [self.signingKey]) is not root:
|
|
142
|
+
raise SAMLRefused(f"{self.name}'s signature does not cover the whole EntityDescriptor")
|
|
143
|
+
except (XMLRefused, SignatureRefused) as error:
|
|
144
|
+
raise SAMLRefused(f"{self.name}'s metadata for {entityID} is refused: {error}") from None
|
|
145
|
+
if root.attribute("entityID") != entityID:
|
|
146
|
+
raise SAMLRefused(f"{self.name} answered for {root.attribute('entityID')!r}, not {entityID!r}")
|
|
147
|
+
institution = _institution(root, self.name)
|
|
148
|
+
if institution.validUntil <= self.clock():
|
|
149
|
+
raise SAMLRefused(f"{self.name}'s metadata for {entityID} expired")
|
|
150
|
+
return institution
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def scopedIdentifier(identity: SAMLIdentity, institution: Institution, attributeName: str) -> str:
|
|
154
|
+
"""The identity's scoped identifier, refused unless its scope is one the institution was registered for."""
|
|
155
|
+
if attributeName not in scopedIdentifiers:
|
|
156
|
+
raise ValueError(f"{attributeName} is not a scoped identifier attribute")
|
|
157
|
+
if identity.issuer != institution.entityID:
|
|
158
|
+
raise SAMLRefused(f"the identity was issued by {identity.issuer!r}, not {institution.entityID!r}")
|
|
159
|
+
values = identity.attributes.get(attributeName, ())
|
|
160
|
+
if len(values) != 1:
|
|
161
|
+
raise SAMLRefused(f"{institution.entityID} sent {len(values)} values of {attributeName}, not one")
|
|
162
|
+
value = values[0].strip()
|
|
163
|
+
syntax = _principalSyntax if attributeName == eduPersonPrincipalName else _subjectSyntax
|
|
164
|
+
if not syntax.match(value):
|
|
165
|
+
raise SAMLRefused(f"{institution.entityID} sent a {attributeName} that is not a scoped identifier")
|
|
166
|
+
scope = value.rpartition("@")[2].lower()
|
|
167
|
+
if scope not in institution.scopes:
|
|
168
|
+
raise SAMLRefused(f"{institution.entityID} may vouch for {', '.join(institution.scopes)}, not {scope}")
|
|
169
|
+
# The profile makes subject-id and pairwise-id case-insensitive; eduPersonPrincipalName keeps its case.
|
|
170
|
+
return value.lower() if attributeName != eduPersonPrincipalName else value
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def serviceProviderMetadata(entityID: str, assertionConsumerURL: str, displayNames: dict[str, str],
|
|
174
|
+
informationURL: str, privacyStatementURL: str, organizationName: str,
|
|
175
|
+
technicalContact: str, securityContact: str | None = None,
|
|
176
|
+
entityCategories: tuple[str, ...] = (researchAndScholarship,)) -> bytes:
|
|
177
|
+
"""The service provider's metadata for its federation to register: unsigned (the federation signs what it publishes)."""
|
|
178
|
+
for address in (assertionConsumerURL, informationURL, privacyStatementURL):
|
|
179
|
+
if not address.startswith("https://"):
|
|
180
|
+
raise ValueError(f"{address} must be an https address")
|
|
181
|
+
for contact in (technicalContact, securityContact):
|
|
182
|
+
if contact is not None and not re.match(r"^[^@\s]+@[^@\s]+$", contact):
|
|
183
|
+
raise ValueError(f"{contact} is not an e-mail address")
|
|
184
|
+
names = "".join(f'<mdui:DisplayName xml:lang="{_attribute(language)}">{_attribute(text)}</mdui:DisplayName>'
|
|
185
|
+
for language, text in sorted(displayNames.items()))
|
|
186
|
+
categories = "".join(f"<saml:AttributeValue>{_attribute(category)}</saml:AttributeValue>" for category in entityCategories)
|
|
187
|
+
security = ""
|
|
188
|
+
if securityContact is not None:
|
|
189
|
+
security = (f'<md:ContactPerson contactType="other" xmlns:remd="http://refeds.org/metadata" '
|
|
190
|
+
f'remd:contactType="http://refeds.org/metadata/contactType/security">'
|
|
191
|
+
f"<md:EmailAddress>mailto:{_attribute(securityContact)}</md:EmailAddress></md:ContactPerson>")
|
|
192
|
+
document = (
|
|
193
|
+
f'<md:EntityDescriptor xmlns:md="{metadataNamespace}" xmlns:saml="{assertionNamespace}" '
|
|
194
|
+
f'xmlns:mdui="{uiNamespace}" xmlns:mdattr="{entityAttributeNamespace}" entityID="{_attribute(entityID)}">'
|
|
195
|
+
+ (f'<md:Extensions><mdattr:EntityAttributes><saml:Attribute Name="{entityCategory}" '
|
|
196
|
+
f'NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">{categories}</saml:Attribute>'
|
|
197
|
+
f"</mdattr:EntityAttributes></md:Extensions>" if entityCategories else "")
|
|
198
|
+
+ '<md:SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol" '
|
|
199
|
+
'AuthnRequestsSigned="false" WantAssertionsSigned="true">'
|
|
200
|
+
f"<md:Extensions><mdui:UIInfo>{names}"
|
|
201
|
+
f'<mdui:InformationURL xml:lang="en">{_attribute(informationURL)}</mdui:InformationURL>'
|
|
202
|
+
f'<mdui:PrivacyStatementURL xml:lang="en">{_attribute(privacyStatementURL)}</mdui:PrivacyStatementURL>'
|
|
203
|
+
"</mdui:UIInfo></md:Extensions>"
|
|
204
|
+
f'<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" '
|
|
205
|
+
f'Location="{_attribute(assertionConsumerURL)}" index="0" isDefault="true"/>'
|
|
206
|
+
"</md:SPSSODescriptor>"
|
|
207
|
+
f'<md:Organization><md:OrganizationName xml:lang="en">{_attribute(organizationName)}</md:OrganizationName>'
|
|
208
|
+
f'<md:OrganizationDisplayName xml:lang="en">{_attribute(organizationName)}</md:OrganizationDisplayName>'
|
|
209
|
+
f'<md:OrganizationURL xml:lang="en">{_attribute(informationURL)}</md:OrganizationURL></md:Organization>'
|
|
210
|
+
f'<md:ContactPerson contactType="technical"><md:EmailAddress>mailto:{_attribute(technicalContact)}'
|
|
211
|
+
f"</md:EmailAddress></md:ContactPerson>{security}</md:EntityDescriptor>"
|
|
212
|
+
)
|
|
213
|
+
return document.encode("utf-8")
|