microblog/app/ldsig.py

92 lines
2.7 KiB
Python
Raw Normal View History

2022-06-27 18:56:13 +00:00
import base64
import hashlib
import typing
from datetime import datetime
2022-06-28 07:58:33 +00:00
import pyld # type: ignore
2022-06-27 18:56:13 +00:00
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
2022-07-06 17:04:38 +00:00
from loguru import logger
2022-06-27 18:56:13 +00:00
from pyld import jsonld # type: ignore
2022-06-28 07:58:33 +00:00
from app import activitypub as ap
2022-07-05 18:47:00 +00:00
from app.database import AsyncSession
from app.httpsig import _get_public_key
2022-06-28 07:58:33 +00:00
2022-06-27 18:56:13 +00:00
if typing.TYPE_CHECKING:
from app.key import Key
2022-06-28 07:58:33 +00:00
requests_loader = pyld.documentloader.requests.requests_document_loader()
2022-06-27 18:56:13 +00:00
2022-06-28 07:58:33 +00:00
def _loader(url, options={}):
# See https://github.com/digitalbazaar/pyld/issues/133
options["headers"]["Accept"] = "application/ld+json"
return requests_loader(url, options)
2022-06-27 18:56:13 +00:00
2022-06-28 07:58:33 +00:00
pyld.jsonld.set_document_loader(_loader)
2022-06-27 18:56:13 +00:00
2022-06-28 07:58:33 +00:00
def _options_hash(doc: ap.RawObject) -> str:
2022-06-27 18:56:13 +00:00
doc = dict(doc["signature"])
for k in ["type", "id", "signatureValue"]:
if k in doc:
del doc[k]
2023-01-15 18:29:27 +00:00
doc["@context"] = "https://w3id.org/security/v1"
2022-06-27 18:56:13 +00:00
normalized = jsonld.normalize(
doc, {"algorithm": "URDNA2015", "format": "application/nquads"}
)
h = hashlib.new("sha256")
h.update(normalized.encode("utf-8"))
return h.hexdigest()
2022-06-28 07:58:33 +00:00
def _doc_hash(doc: ap.RawObject) -> str:
2022-06-27 18:56:13 +00:00
doc = dict(doc)
if "signature" in doc:
del doc["signature"]
normalized = jsonld.normalize(
doc, {"algorithm": "URDNA2015", "format": "application/nquads"}
)
h = hashlib.new("sha256")
h.update(normalized.encode("utf-8"))
return h.hexdigest()
2022-07-05 18:47:00 +00:00
async def verify_signature(
db_session: AsyncSession,
doc: ap.RawObject,
) -> bool:
if "signature" not in doc:
2022-07-06 17:04:38 +00:00
logger.warning("The object does contain a signature")
return False
2022-07-05 18:47:00 +00:00
key_id = doc["signature"]["creator"]
key = await _get_public_key(db_session, key_id)
2022-06-27 18:56:13 +00:00
to_be_signed = _options_hash(doc) + _doc_hash(doc)
signature = doc["signature"]["signatureValue"]
signer = PKCS1_v1_5.new(key.pubkey or key.privkey) # type: ignore
digest = SHA256.new()
digest.update(to_be_signed.encode("utf-8"))
return signer.verify(digest, base64.b64decode(signature)) # type: ignore
2022-06-28 07:58:33 +00:00
def generate_signature(doc: ap.RawObject, key: "Key") -> None:
2022-06-27 18:56:13 +00:00
options = {
"type": "RsaSignature2017",
"creator": doc["actor"] + "#main-key",
"created": datetime.utcnow().replace(microsecond=0).isoformat() + "Z",
}
doc["signature"] = options
to_be_signed = _options_hash(doc) + _doc_hash(doc)
if not key.privkey:
raise ValueError(f"missing privkey on key {key!r}")
signer = PKCS1_v1_5.new(key.privkey)
digest = SHA256.new()
digest.update(to_be_signed.encode("utf-8"))
sig = base64.b64encode(signer.sign(digest)) # type: ignore
options["signatureValue"] = sig.decode("utf-8")