2022-11-06 12:48:04 -08:00
|
|
|
import base64
|
2022-11-06 20:30:07 -08:00
|
|
|
import json
|
2023-01-11 10:00:18 -08:00
|
|
|
from typing import Literal, TypedDict, cast
|
2022-11-06 20:30:07 -08:00
|
|
|
from urllib.parse import urlparse
|
2022-11-06 12:48:04 -08:00
|
|
|
|
2022-11-06 20:30:07 -08:00
|
|
|
import httpx
|
2022-11-20 17:42:39 -08:00
|
|
|
from cryptography.exceptions import InvalidSignature
|
2022-11-20 17:29:19 -08:00
|
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
2022-11-20 17:42:39 -08:00
|
|
|
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
2022-12-04 08:32:25 -08:00
|
|
|
from django.conf import settings
|
2022-11-06 12:48:04 -08:00
|
|
|
from django.http import HttpRequest
|
2022-11-12 14:10:15 -08:00
|
|
|
from django.utils import timezone
|
|
|
|
from django.utils.http import http_date, parse_http_date
|
2022-12-04 08:32:25 -08:00
|
|
|
from httpx._types import TimeoutTypes
|
2023-01-19 12:14:55 -08:00
|
|
|
from idna.core import InvalidCodepoint
|
2022-11-12 14:10:15 -08:00
|
|
|
from pyld import jsonld
|
2022-11-06 20:30:07 -08:00
|
|
|
|
2022-11-12 20:14:21 -08:00
|
|
|
from core.ld import format_ld_date
|
2022-11-12 14:10:15 -08:00
|
|
|
|
|
|
|
|
|
|
|
class VerificationError(BaseException):
|
|
|
|
"""
|
|
|
|
There was an error with verifying the signature
|
|
|
|
"""
|
|
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class VerificationFormatError(VerificationError):
|
|
|
|
"""
|
|
|
|
There was an error with the format of the signature (not if it is valid)
|
|
|
|
"""
|
|
|
|
|
|
|
|
pass
|
2022-11-06 12:48:04 -08:00
|
|
|
|
|
|
|
|
2022-11-20 17:29:19 -08:00
|
|
|
class RsaKeys:
|
|
|
|
@classmethod
|
2022-12-05 09:38:37 -08:00
|
|
|
def generate_keypair(cls) -> tuple[str, str]:
|
2022-11-20 17:29:19 -08:00
|
|
|
"""
|
|
|
|
Generates a new RSA keypair
|
|
|
|
"""
|
|
|
|
private_key = rsa.generate_private_key(
|
|
|
|
public_exponent=65537,
|
|
|
|
key_size=2048,
|
|
|
|
)
|
|
|
|
private_key_serialized = private_key.private_bytes(
|
|
|
|
encoding=serialization.Encoding.PEM,
|
|
|
|
format=serialization.PrivateFormat.PKCS8,
|
|
|
|
encryption_algorithm=serialization.NoEncryption(),
|
|
|
|
).decode("ascii")
|
|
|
|
public_key_serialized = (
|
|
|
|
private_key.public_key()
|
|
|
|
.public_bytes(
|
|
|
|
encoding=serialization.Encoding.PEM,
|
|
|
|
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
|
|
)
|
|
|
|
.decode("ascii")
|
|
|
|
)
|
|
|
|
return private_key_serialized, public_key_serialized
|
|
|
|
|
|
|
|
|
2022-11-06 12:48:04 -08:00
|
|
|
class HttpSignature:
|
|
|
|
"""
|
|
|
|
Allows for calculation and verification of HTTP signatures
|
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def calculate_digest(cls, data, algorithm="sha-256") -> str:
|
|
|
|
"""
|
|
|
|
Calculates the digest header value for a given HTTP body
|
|
|
|
"""
|
|
|
|
if algorithm == "sha-256":
|
|
|
|
digest = hashes.Hash(hashes.SHA256())
|
|
|
|
digest.update(data)
|
|
|
|
return "SHA-256=" + base64.b64encode(digest.finalize()).decode("ascii")
|
|
|
|
else:
|
|
|
|
raise ValueError(f"Unknown digest algorithm {algorithm}")
|
|
|
|
|
|
|
|
@classmethod
|
2022-12-05 09:38:37 -08:00
|
|
|
def headers_from_request(cls, request: HttpRequest, header_names: list[str]) -> str:
|
2022-11-06 12:48:04 -08:00
|
|
|
"""
|
2022-11-06 20:30:07 -08:00
|
|
|
Creates the to-be-signed header payload from a Django request
|
|
|
|
"""
|
2022-11-06 12:48:04 -08:00
|
|
|
headers = {}
|
|
|
|
for header_name in header_names:
|
|
|
|
if header_name == "(request-target)":
|
2022-12-17 11:00:47 -08:00
|
|
|
value = f"{request.method.lower()} {request.path}"
|
2022-11-06 12:48:04 -08:00
|
|
|
elif header_name == "content-type":
|
|
|
|
value = request.META["CONTENT_TYPE"]
|
2022-12-18 15:12:57 -08:00
|
|
|
elif header_name == "content-length":
|
|
|
|
value = request.META["CONTENT_LENGTH"]
|
2022-11-06 12:48:04 -08:00
|
|
|
else:
|
2022-11-16 20:12:28 -08:00
|
|
|
value = request.META["HTTP_%s" % header_name.upper().replace("-", "_")]
|
2022-11-06 12:48:04 -08:00
|
|
|
headers[header_name] = value
|
|
|
|
return "\n".join(f"{name.lower()}: {value}" for name, value in headers.items())
|
|
|
|
|
|
|
|
@classmethod
|
2022-11-12 14:10:15 -08:00
|
|
|
def parse_signature(cls, signature: str) -> "HttpSignatureDetails":
|
2022-11-06 13:14:08 -08:00
|
|
|
bits = {}
|
2022-11-06 12:48:04 -08:00
|
|
|
for item in signature.split(","):
|
|
|
|
name, value = item.split("=", 1)
|
|
|
|
value = value.strip('"')
|
2022-11-06 13:14:08 -08:00
|
|
|
bits[name.lower()] = value
|
2022-11-12 14:10:15 -08:00
|
|
|
signature_details: HttpSignatureDetails = {
|
2022-11-06 13:14:08 -08:00
|
|
|
"headers": bits["headers"].split(),
|
|
|
|
"signature": base64.b64decode(bits["signature"]),
|
|
|
|
"algorithm": bits["algorithm"],
|
|
|
|
"keyid": bits["keyid"],
|
|
|
|
}
|
2022-11-06 12:48:04 -08:00
|
|
|
return signature_details
|
2022-11-06 13:14:08 -08:00
|
|
|
|
2022-11-06 20:30:07 -08:00
|
|
|
@classmethod
|
2022-11-12 14:10:15 -08:00
|
|
|
def compile_signature(cls, details: "HttpSignatureDetails") -> str:
|
2022-11-06 20:30:07 -08:00
|
|
|
value = f'keyId="{details["keyid"]}",headers="'
|
|
|
|
value += " ".join(h.lower() for h in details["headers"])
|
|
|
|
value += '",signature="'
|
|
|
|
value += base64.b64encode(details["signature"]).decode("ascii")
|
|
|
|
value += f'",algorithm="{details["algorithm"]}"'
|
|
|
|
return value
|
|
|
|
|
2022-11-12 14:10:15 -08:00
|
|
|
@classmethod
|
|
|
|
def verify_signature(
|
|
|
|
cls,
|
|
|
|
signature: bytes,
|
|
|
|
cleartext: str,
|
|
|
|
public_key: str,
|
|
|
|
):
|
2023-01-11 10:00:18 -08:00
|
|
|
public_key_instance: rsa.RSAPublicKey = cast(
|
|
|
|
rsa.RSAPublicKey,
|
|
|
|
serialization.load_pem_public_key(public_key.encode("ascii")),
|
2022-11-12 14:10:15 -08:00
|
|
|
)
|
|
|
|
try:
|
2022-11-20 17:42:39 -08:00
|
|
|
public_key_instance.verify(
|
|
|
|
signature,
|
|
|
|
cleartext.encode("ascii"),
|
|
|
|
padding.PKCS1v15(),
|
|
|
|
hashes.SHA256(),
|
|
|
|
)
|
|
|
|
except InvalidSignature:
|
2022-11-12 14:10:15 -08:00
|
|
|
raise VerificationError("Signature mismatch")
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def verify_request(cls, request, public_key, skip_date=False):
|
|
|
|
"""
|
|
|
|
Verifies that the request has a valid signature for its body
|
|
|
|
"""
|
|
|
|
# Verify body digest
|
2022-12-05 13:44:50 -08:00
|
|
|
if "digest" in request.headers:
|
2022-11-12 14:10:15 -08:00
|
|
|
expected_digest = HttpSignature.calculate_digest(request.body)
|
2022-12-05 13:44:50 -08:00
|
|
|
if request.headers["digest"] != expected_digest:
|
2022-11-12 14:10:15 -08:00
|
|
|
raise VerificationFormatError("Digest is incorrect")
|
|
|
|
# Verify date header
|
2022-12-05 13:44:50 -08:00
|
|
|
if "date" in request.headers and not skip_date:
|
|
|
|
header_date = parse_http_date(request.headers["date"])
|
2022-11-12 14:10:15 -08:00
|
|
|
if abs(timezone.now().timestamp() - header_date) > 60:
|
|
|
|
raise VerificationFormatError("Date is too far away")
|
|
|
|
# Get the signature details
|
2022-12-05 13:44:50 -08:00
|
|
|
if "signature" not in request.headers:
|
2022-11-12 14:10:15 -08:00
|
|
|
raise VerificationFormatError("No signature header present")
|
2022-12-05 13:44:50 -08:00
|
|
|
signature_details = cls.parse_signature(request.headers["signature"])
|
2022-11-12 14:10:15 -08:00
|
|
|
# Reject unknown algorithms
|
|
|
|
if signature_details["algorithm"] != "rsa-sha256":
|
|
|
|
raise VerificationFormatError("Unknown signature algorithm")
|
|
|
|
# Create the signature payload
|
|
|
|
headers_string = cls.headers_from_request(request, signature_details["headers"])
|
|
|
|
cls.verify_signature(
|
|
|
|
signature_details["signature"],
|
|
|
|
headers_string,
|
|
|
|
public_key,
|
|
|
|
)
|
|
|
|
|
2022-11-06 20:30:07 -08:00
|
|
|
@classmethod
|
|
|
|
async def signed_request(
|
2022-11-20 17:29:19 -08:00
|
|
|
cls,
|
2022-11-06 20:30:07 -08:00
|
|
|
uri: str,
|
2022-12-05 09:38:37 -08:00
|
|
|
body: dict | None,
|
2022-11-12 14:10:15 -08:00
|
|
|
private_key: str,
|
|
|
|
key_id: str,
|
2022-11-06 20:30:07 -08:00
|
|
|
content_type: str = "application/json",
|
2022-11-20 17:29:19 -08:00
|
|
|
method: Literal["get", "post"] = "post",
|
2022-12-04 08:32:25 -08:00
|
|
|
timeout: TimeoutTypes = settings.SETUP.REMOTE_TIMEOUT,
|
2022-11-06 20:30:07 -08:00
|
|
|
):
|
|
|
|
"""
|
|
|
|
Performs an async request to the given path, with a document, signed
|
|
|
|
as an identity.
|
|
|
|
"""
|
2022-12-20 05:21:36 -08:00
|
|
|
if "://" not in uri:
|
|
|
|
raise ValueError("URI does not contain a scheme")
|
2022-11-20 17:29:19 -08:00
|
|
|
# Create the core header field set
|
2022-11-06 20:30:07 -08:00
|
|
|
uri_parts = urlparse(uri)
|
|
|
|
date_string = http_date()
|
|
|
|
headers = {
|
|
|
|
"(request-target)": f"{method} {uri_parts.path}",
|
|
|
|
"Host": uri_parts.hostname,
|
|
|
|
"Date": date_string,
|
|
|
|
}
|
2022-11-20 17:29:19 -08:00
|
|
|
# If we have a body, add a digest and content type
|
|
|
|
if body is not None:
|
|
|
|
body_bytes = json.dumps(body).encode("utf8")
|
|
|
|
headers["Digest"] = cls.calculate_digest(body_bytes)
|
|
|
|
headers["Content-Type"] = content_type
|
|
|
|
else:
|
|
|
|
body_bytes = b""
|
|
|
|
# GET requests get implicit accept headers added
|
|
|
|
if method == "get":
|
2022-12-20 05:21:36 -08:00
|
|
|
headers["Accept"] = "application/ld+json"
|
2022-11-20 17:29:19 -08:00
|
|
|
# Sign the headers
|
2022-11-06 20:30:07 -08:00
|
|
|
signed_string = "\n".join(
|
|
|
|
f"{name.lower()}: {value}" for name, value in headers.items()
|
|
|
|
)
|
2023-01-11 10:00:18 -08:00
|
|
|
private_key_instance: rsa.RSAPrivateKey = cast(
|
|
|
|
rsa.RSAPrivateKey,
|
|
|
|
serialization.load_pem_private_key(
|
|
|
|
private_key.encode("ascii"),
|
|
|
|
password=None,
|
|
|
|
),
|
2022-11-12 14:10:15 -08:00
|
|
|
)
|
2022-11-20 17:42:39 -08:00
|
|
|
signature = private_key_instance.sign(
|
2022-11-12 14:10:15 -08:00
|
|
|
signed_string.encode("ascii"),
|
2022-11-20 17:42:39 -08:00
|
|
|
padding.PKCS1v15(),
|
|
|
|
hashes.SHA256(),
|
2022-11-12 14:10:15 -08:00
|
|
|
)
|
2022-11-20 17:29:19 -08:00
|
|
|
headers["Signature"] = cls.compile_signature(
|
2022-11-06 20:30:07 -08:00
|
|
|
{
|
2022-11-12 14:10:15 -08:00
|
|
|
"keyid": key_id,
|
2022-11-06 20:30:07 -08:00
|
|
|
"headers": list(headers.keys()),
|
2022-11-12 14:10:15 -08:00
|
|
|
"signature": signature,
|
2022-11-06 20:30:07 -08:00
|
|
|
"algorithm": "rsa-sha256",
|
|
|
|
}
|
|
|
|
)
|
2022-12-06 20:59:05 -08:00
|
|
|
|
|
|
|
# Announce ourselves with an agent similar to Mastodon
|
|
|
|
headers["User-Agent"] = settings.TAKAHE_USER_AGENT
|
|
|
|
|
2022-11-20 17:29:19 -08:00
|
|
|
# Send the request with all those headers except the pseudo one
|
2022-11-06 20:30:07 -08:00
|
|
|
del headers["(request-target)"]
|
2022-12-04 08:32:25 -08:00
|
|
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
2023-01-19 12:14:55 -08:00
|
|
|
try:
|
|
|
|
response = await client.request(
|
|
|
|
method,
|
|
|
|
uri,
|
|
|
|
headers=headers,
|
|
|
|
content=body_bytes,
|
|
|
|
follow_redirects=method == "get",
|
|
|
|
)
|
|
|
|
except InvalidCodepoint as ex:
|
|
|
|
# Convert to a more generic error we handle
|
|
|
|
raise httpx.HTTPError(f"InvalidCodepoint: {str(ex)}") from None
|
|
|
|
|
2022-12-16 19:14:02 -08:00
|
|
|
if (
|
|
|
|
method == "post"
|
|
|
|
and response.status_code >= 400
|
2022-12-16 19:14:44 -08:00
|
|
|
and response.status_code < 500
|
2022-12-16 19:14:02 -08:00
|
|
|
and response.status_code != 404
|
|
|
|
):
|
2022-11-10 22:42:43 -08:00
|
|
|
raise ValueError(
|
2022-12-29 09:35:14 -08:00
|
|
|
f"POST error to {uri}: {response.status_code} {response.content!r}"
|
2022-11-10 22:42:43 -08:00
|
|
|
)
|
|
|
|
return response
|
2022-11-06 20:30:07 -08:00
|
|
|
|
2022-11-06 13:14:08 -08:00
|
|
|
|
2022-11-12 14:10:15 -08:00
|
|
|
class HttpSignatureDetails(TypedDict):
|
2022-11-06 13:14:08 -08:00
|
|
|
algorithm: str
|
2022-12-05 09:38:37 -08:00
|
|
|
headers: list[str]
|
2022-11-06 13:14:08 -08:00
|
|
|
signature: bytes
|
|
|
|
keyid: str
|
2022-11-12 14:10:15 -08:00
|
|
|
|
|
|
|
|
|
|
|
class LDSignature:
|
|
|
|
"""
|
|
|
|
Creates and verifies signatures of JSON-LD documents
|
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
2022-12-05 09:38:37 -08:00
|
|
|
def verify_signature(cls, document: dict, public_key: str) -> None:
|
2022-11-12 14:10:15 -08:00
|
|
|
"""
|
|
|
|
Verifies a document
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
# Strip out the signature from the incoming document
|
|
|
|
signature = document.pop("signature")
|
|
|
|
# Create the options document
|
|
|
|
options = {
|
|
|
|
"@context": "https://w3id.org/identity/v1",
|
|
|
|
"creator": signature["creator"],
|
|
|
|
"created": signature["created"],
|
|
|
|
}
|
|
|
|
except KeyError:
|
|
|
|
raise VerificationFormatError("Invalid signature section")
|
|
|
|
if signature["type"].lower() != "rsasignature2017":
|
|
|
|
raise VerificationFormatError("Unknown signature type")
|
|
|
|
# Get the normalised hash of each document
|
|
|
|
final_hash = cls.normalized_hash(options) + cls.normalized_hash(document)
|
|
|
|
# Verify the signature
|
2023-01-11 10:00:18 -08:00
|
|
|
public_key_instance: rsa.RSAPublicKey = cast(
|
|
|
|
rsa.RSAPublicKey,
|
|
|
|
serialization.load_pem_public_key(public_key.encode("ascii")),
|
2022-11-12 14:10:15 -08:00
|
|
|
)
|
|
|
|
try:
|
2022-11-20 17:42:39 -08:00
|
|
|
public_key_instance.verify(
|
2022-11-12 14:10:15 -08:00
|
|
|
base64.b64decode(signature["signatureValue"]),
|
|
|
|
final_hash,
|
2022-11-20 17:42:39 -08:00
|
|
|
padding.PKCS1v15(),
|
|
|
|
hashes.SHA256(),
|
2022-11-12 14:10:15 -08:00
|
|
|
)
|
2022-11-20 17:42:39 -08:00
|
|
|
except InvalidSignature:
|
2022-11-12 14:10:15 -08:00
|
|
|
raise VerificationError("Signature mismatch")
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def create_signature(
|
2022-12-05 09:38:37 -08:00
|
|
|
cls, document: dict, private_key: str, key_id: str
|
|
|
|
) -> dict[str, str]:
|
2022-11-12 14:10:15 -08:00
|
|
|
"""
|
|
|
|
Creates the signature for a document
|
|
|
|
"""
|
|
|
|
# Create the options document
|
2022-12-05 09:38:37 -08:00
|
|
|
options: dict[str, str] = {
|
2022-11-12 14:10:15 -08:00
|
|
|
"@context": "https://w3id.org/identity/v1",
|
|
|
|
"creator": key_id,
|
2022-11-12 20:14:21 -08:00
|
|
|
"created": format_ld_date(timezone.now()),
|
2022-11-12 14:10:15 -08:00
|
|
|
}
|
|
|
|
# Get the normalised hash of each document
|
|
|
|
final_hash = cls.normalized_hash(options) + cls.normalized_hash(document)
|
|
|
|
# Create the signature
|
2023-01-11 10:00:18 -08:00
|
|
|
private_key_instance: rsa.RSAPrivateKey = cast(
|
|
|
|
rsa.RSAPrivateKey,
|
|
|
|
serialization.load_pem_private_key(
|
|
|
|
private_key.encode("ascii"),
|
|
|
|
password=None,
|
|
|
|
),
|
2022-11-20 17:42:39 -08:00
|
|
|
)
|
|
|
|
signature = base64.b64encode(
|
|
|
|
private_key_instance.sign(
|
|
|
|
final_hash,
|
|
|
|
padding.PKCS1v15(),
|
|
|
|
hashes.SHA256(),
|
|
|
|
)
|
2022-11-12 14:10:15 -08:00
|
|
|
)
|
|
|
|
# Add it to the options document along with other bits
|
|
|
|
options["signatureValue"] = signature.decode("ascii")
|
|
|
|
options["type"] = "RsaSignature2017"
|
|
|
|
return options
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def normalized_hash(cls, document) -> bytes:
|
|
|
|
"""
|
|
|
|
Takes a JSON-LD document and create a hash of its URDNA2015 form,
|
|
|
|
in the same way that Mastodon does internally.
|
|
|
|
|
|
|
|
Reference: https://socialhub.activitypub.rocks/t/making-sense-of-rsasignature2017/347
|
|
|
|
"""
|
|
|
|
norm_form = jsonld.normalize(
|
|
|
|
document,
|
|
|
|
{"algorithm": "URDNA2015", "format": "application/n-quads"},
|
|
|
|
)
|
|
|
|
digest = hashes.Hash(hashes.SHA256())
|
|
|
|
digest.update(norm_form.encode("utf8"))
|
|
|
|
return digest.finalize().hex().encode("ascii")
|