]> khamidou — GitHub mirrors - flanker.git/commitdiff
Initial implementation of DKIM signatures
authorAlex Gaynor <alex.gaynor@gmail.com>
Tue, 8 Jul 2014 23:12:40 +0000 (16:12 -0700)
committerAlex Gaynor <alex.gaynor@gmail.com>
Tue, 8 Jul 2014 23:12:40 +0000 (16:12 -0700)
flanker/dkim.py
tests/dkim_test.py

index a29250ae3272440ece2e17ee56cc5f5112d5b152..a0bbd2d5356cd86336691573326c7c0e5d1ebff9 100644 (file)
@@ -1,16 +1,30 @@
 import base64
 import io
 import re
+import time
 
+from cryptography.hazmat.backends import default_backend
 from cryptography.hazmat.primitives import hashes
 from cryptography.hazmat.primitives.asymmetric import padding
 
 from flanker.mime.message.headers import parsing
 
 
+_BODY_LINES_RE = re.compile(r"\r?\n")
+
+
+class SimpleCanonicalization(object):
+    name = "simple"
+
+    def canonicalize_header(self, header, value):
+        return header, value
+
+    def canonicalize_body(self, body):
+        return body.rstrip() + "\r\n"
+
+
 class NoFWSCanonicalization(object):
     _header_fws_re = re.compile(r"[\x09\x20\x0D\x0A]+")
-    _body_lines_re = re.compile(r"\r?\n")
     _body_wsp_re = re.compile(r"[\x09\x20]+")
     _body_orphan_cr_re = re.compile(b"\r([^\n])")
 
@@ -18,7 +32,6 @@ class NoFWSCanonicalization(object):
         return header, self._header_fws_re.sub("", value) + "\r\n"
 
     def canonicalize_body(self, body):
-        body = self._body_lines_re.sub(b"\r\n", body)
         body = self._body_wsp_re.sub("", body)
         body = self._body_orphan_cr_re.sub("\1", body)
         body = body.rstrip()
@@ -54,7 +67,7 @@ class DomainKeySigner(object):
         self._signed_headers = None
 
     def sign(self, message):
-        message = io.BytesIO(message)
+        message = io.BytesIO(_BODY_LINES_RE.sub("\r\n", message))
         canonicalization = NoFWSCanonicalization()
         signer = self._key.signer(padding.PKCS1v15(), hashes.SHA1())
         h_field = []
@@ -85,16 +98,56 @@ class DomainKeySigner(object):
 
 
 class DKIMSigner(object):
-    def __init__(self, key, selector, domain, canonicalization,
+    def __init__(self, key, selector, domain,
+                 header_canonicalization=SimpleCanonicalization(),
+                 body_canonicalization=SimpleCanonicalization(),
                  signed_headers=None):
         self._key = key
         self._selector = selector
         self._domain = domain
-        self._canonicalization = canonicalization
+        self._header_canonicalization = header_canonicalization
+        self._body_canonicalization = body_canonicalization
         self._signed_headers = signed_headers
 
-    def sign(self, message):
-        raise NotImplementedError
+    def sign(self, message, current_time=None):
+        message = io.BytesIO(_BODY_LINES_RE.sub("\r\n", message))
+        signer = self._key.signer(padding.PKCS1v15(), hashes.SHA256())
+
+        h_field = []
+        for header_line in parsing.split(message):
+            header, value = header_line.split(b":", 1)
+            if self._signed_headers is None or header in self._signed_headers:
+                h_field.append(header)
+
+                header, value = self._header_canonicalization.canonicalize_header(
+                    header, value)
+                signer.update(header)
+                signer.update(b":")
+                signer.update(value)
+
+        h = hashes.Hash(hashes.SHA256(), backend=default_backend())
+        h.update(self._body_canonicalization.canonicalize_body(message.read()))
+        dkim_header_value = _fold(
+            b" a=rsa-sha256; v=1; "
+            b"c={header_canonicalization.name}/{body_canonicalization.name}; "
+            b"d={domain}; q=dns/txt; s={selector}; t={time}; h={headers}; "
+            b"bh={body_hash}; b=".format(
+                header_canonicalization=self._header_canonicalization,
+                body_canonicalization=self._body_canonicalization,
+                domain=self._domain,
+                selector=self._selector,
+                time=int(time.time()) if current_time is None else current_time,
+                headers=": ".join(h_field),
+                body_hash=base64.b64encode(h.finalize()),
+            )
+        )
+
+        dkim_header, dkim_header_value = self._header_canonicalization.canonicalize_header("DKIM-Signature", dkim_header_value)
+        signer.update(dkim_header)
+        signer.update(b":")
+        signer.update(dkim_header_value)
+        return b"DKIM-Signature:{dkim_header}{signature}\r\n".format(dkim_header=dkim_header_value, signature=_fold(base64.b64encode(signer.finalize())))
+
 
 
 class DKIMVerifier(object):
index 21e0edc888c9f55339bacd89e771197ad392f19e..53d33f1194afd64fc07573c97509395b60b25591 100644 (file)
@@ -47,3 +47,15 @@ def test_simple_domain_key_signature():
         b"i2SN1doNsdHigD7hnXwzoRVaZQ15zWNcQwaHriaTyijV+PUHEeU/EdNSakv\r\n XDoo"
         b"7lzEjzaYxBDx2PP25abuTSJF0=\r\n"
     )
+
+def test_simple_dkim_signature():
+    signer = dkim.DKIMSigner(DUMMY_RSA_KEY, "mx", "testing1")
+    sig = signer.sign(DUMMY_EMAIL, current_time=1404859754)
+    assert sig == (
+        b"DKIM-Signature: a=rsa-sha256; v=1; c=simple/simple; d=testing1; q=dn"
+        b"s/txt; s=mx;\r\n t=1404859754; h=From: To: Subject: Date: Message-ID"
+        b";\r\n bh=4bLNXImK9drULnmePzZNEBleUanJCX5PIsDIFoH4KTQ=; b=IrtWacnHcpq"
+        b"elwoPBxtI9RY0qJ9ABdltZRJcf5wXjXwA7sCbuxibMWk4m81m2zGqMOBsziIE\r\n 0j"
+        b"Jxf4OJGbWVXwSB2mNPfPyScpqJEL+z43vhx+/ZTWBWpj3TSAuHmOT4G7wrySLAZmfDcm"
+        b"je\r\n J00EP9NPpJOz2oUI8NJwozkUr6k=\r\n"
+    )