"""Offline checks for ADFSpoof's modern cryptography/signxml compatibility."""
def main():
import datetime
import hashlib
import hmac
import sys
sys.path.insert(0, sys.argv[1])
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import pkcs12
from lxml import etree
from signxml import XMLVerifier
from microsoft_kbkdf import KBKDFHMAC, Mode, CounterLocation
from SamlSigner import SAMLSigner
# Independent HMAC reference: Microsoft encodes the requested BYTE count,
# whereas standard SP800-108 encodes bits. Exercise multiple output blocks.
key, label, context, length = b"test-key", b"test-label", b"test-context", 48
for location in CounterLocation:
fixed = label + b"\0" + context + length.to_bytes(4, "big")
expected = b""
for counter in (1, 2):
count = counter.to_bytes(4, "big")
data = count + fixed if location == CounterLocation.BeforeFixed else fixed + count
expected += hmac.digest(key, data, hashlib.sha256)
kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, length, 4, 4,
location, label, context, None, default_backend())
assert kdf.derive(key) == expected[:length]
# Generate our own certificate and verify an actual SAML signature offline.
# Run from the build cwd, not the source directory: template lookup must work.
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
name = x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, "test.invalid")])
now = datetime.datetime.now(datetime.timezone.utc)
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
.public_key(private_key.public_key()).serial_number(1)
.not_valid_before(now - datetime.timedelta(days=1))
.not_valid_after(now + datetime.timedelta(days=1))
.sign(private_key, hashes.SHA256()))
pfx = pkcs12.serialize_key_and_certificates(
b"test", private_key, cert, None, serialization.NoEncryption())
signer = SAMLSigner(pfx, "saml2")
params = {
"ResponseID": "_response", "AssertionID": "_assertion",
"TokenCreated": now.isoformat(), "TokenExpires": (now + datetime.timedelta(hours=1)).isoformat(),
"SubjectConfirmationTime": (now + datetime.timedelta(hours=1)).isoformat(),
"AuthnInstant": now.isoformat(), "AdfsServer": "test.invalid",
"SamlEndpoint": "https://test.invalid/saml", "NameIDFormat": "test-format",
"NameID": "test-user", "RPIdentifier": "test-rp",
"Assertions": '<Attribute Name="test"><AttributeValue>value</AttributeValue></Attribute>',
}
signed = signer.sign_XML(params, "ID", "rsa-sha256", "sha256")
assert etree.fromstring(signed) is not None
verified = XMLVerifier().verify(signed, x509_cert=cert, id_attribute="ID")
assert verified.signed_xml.get("ID") == "_assertion"
print("ADFSpoof: Microsoft KDF and SAML signature verified")
if __name__ == "__main__":
main()