| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
import base64 |
| 36 |
import hashlib |
| 37 |
import logging |
| 38 |
import re |
| 39 |
import sys |
| 40 |
import time |
| 41 |
import binascii |
| 42 |
|
| 43 |
|
| 44 |
USE_ASYNC = True |
| 45 |
|
| 46 |
|
| 47 |
try: |
| 48 |
import authres |
| 49 |
except ImportError: |
| 50 |
pass |
| 51 |
|
| 52 |
|
| 53 |
try: |
| 54 |
import nacl.signing |
| 55 |
import nacl.encoding |
| 56 |
except ImportError: |
| 57 |
pass |
| 58 |
|
| 59 |
from dkim.canonicalization import ( |
| 60 |
CanonicalizationPolicy, |
| 61 |
InvalidCanonicalizationPolicyError, |
| 62 |
) |
| 63 |
from dkim.canonicalization import Relaxed as RelaxedCanonicalization |
| 64 |
|
| 65 |
from dkim.crypto import ( |
| 66 |
DigestTooLargeError, |
| 67 |
HASH_ALGORITHMS, |
| 68 |
ARC_HASH_ALGORITHMS, |
| 69 |
parse_pem_private_key, |
| 70 |
parse_public_key, |
| 71 |
RSASSA_PKCS1_v1_5_sign, |
| 72 |
RSASSA_PKCS1_v1_5_verify, |
| 73 |
UnparsableKeyError, |
| 74 |
) |
| 75 |
try: |
| 76 |
from dkim.dnsplug import get_txt |
| 77 |
except ImportError: |
| 78 |
if USE_ASYNC: |
| 79 |
try: |
| 80 |
import aiodns |
| 81 |
from dkim.asyncsupport import get_txt_async as get_txt |
| 82 |
except: |
| 83 |
|
| 84 |
def get_txt(s,timeout=5): |
| 85 |
raise RuntimeError("DKIM.verify requires DNS or dnspython module") |
| 86 |
else: |
| 87 |
raise RuntimeError("DKIM.verify requires DNS or dnspython module") |
| 88 |
|
| 89 |
from dkim.util import ( |
| 90 |
get_default_logger, |
| 91 |
InvalidTagValueList, |
| 92 |
parse_tag_value, |
| 93 |
) |
| 94 |
|
| 95 |
__all__ = [ |
| 96 |
"DKIMException", |
| 97 |
"InternalError", |
| 98 |
"KeyFormatError", |
| 99 |
"MessageFormatError", |
| 100 |
"ParameterError", |
| 101 |
"ValidationError", |
| 102 |
"AuthresNotFoundError", |
| 103 |
"NaClNotFoundError", |
| 104 |
"DnsTimeoutError", |
| 105 |
"USE_ASYNC", |
| 106 |
"CV_Pass", |
| 107 |
"CV_Fail", |
| 108 |
"CV_None", |
| 109 |
"Relaxed", |
| 110 |
"Simple", |
| 111 |
"DKIM", |
| 112 |
"ARC", |
| 113 |
"sign", |
| 114 |
"verify", |
| 115 |
"dkim_sign", |
| 116 |
"dkim_verify", |
| 117 |
"arc_sign", |
| 118 |
"arc_verify", |
| 119 |
] |
| 120 |
|
| 121 |
Relaxed = b'relaxed' |
| 122 |
Simple = b'simple' |
| 123 |
|
| 124 |
|
| 125 |
CV_Pass = b'pass' |
| 126 |
CV_Fail = b'fail' |
| 127 |
CV_None = b'none' |
| 128 |
|
| 129 |
|
| 130 |
class HashThrough(object): |
| 131 |
def __init__(self, hasher, debug=False): |
| 132 |
self.data = [] |
| 133 |
self.hasher = hasher |
| 134 |
self.name = hasher.name |
| 135 |
self.debug = debug |
| 136 |
|
| 137 |
def update(self, data): |
| 138 |
if self.debug: |
| 139 |
self.data.append(data) |
| 140 |
return self.hasher.update(data) |
| 141 |
|
| 142 |
def digest(self): |
| 143 |
return self.hasher.digest() |
| 144 |
|
| 145 |
def hexdigest(self): |
| 146 |
return self.hasher.hexdigest() |
| 147 |
|
| 148 |
def hashed(self): |
| 149 |
return b''.join(self.data) |
| 150 |
|
| 151 |
|
| 152 |
def bitsize(x): |
| 153 |
"""Return size of long in bits.""" |
| 154 |
return len(bin(x)) - 2 |
| 155 |
|
| 156 |
|
| 157 |
class DKIMException(Exception): |
| 158 |
"""Base class for DKIM errors.""" |
| 159 |
pass |
| 160 |
|
| 161 |
|
| 162 |
class InternalError(DKIMException): |
| 163 |
"""Internal error in dkim module. Should never happen.""" |
| 164 |
pass |
| 165 |
|
| 166 |
|
| 167 |
class KeyFormatError(DKIMException): |
| 168 |
"""Key format error while parsing an RSA public or private key.""" |
| 169 |
pass |
| 170 |
|
| 171 |
|
| 172 |
class MessageFormatError(DKIMException): |
| 173 |
"""RFC822 message format error.""" |
| 174 |
pass |
| 175 |
|
| 176 |
|
| 177 |
class ParameterError(DKIMException): |
| 178 |
"""Input parameter error.""" |
| 179 |
pass |
| 180 |
|
| 181 |
|
| 182 |
class ValidationError(DKIMException): |
| 183 |
"""Validation error.""" |
| 184 |
pass |
| 185 |
|
| 186 |
|
| 187 |
class AuthresNotFoundError(DKIMException): |
| 188 |
""" Authres Package not installed, needed for ARC """ |
| 189 |
pass |
| 190 |
|
| 191 |
|
| 192 |
class NaClNotFoundError(DKIMException): |
| 193 |
""" Nacl package not installed, needed for ed25119 signatures """ |
| 194 |
pass |
| 195 |
|
| 196 |
class UnknownKeyTypeError(DKIMException): |
| 197 |
""" Key type (k tag) is not known (rsa/ed25519) """ |
| 198 |
|
| 199 |
class DnsTimeoutError(DKIMException): |
| 200 |
""" DNS query for public key timed out """ |
| 201 |
|
| 202 |
|
| 203 |
def select_headers(headers, include_headers): |
| 204 |
"""Select message header fields to be signed/verified. |
| 205 |
|
| 206 |
>>> h = [('from','biz'),('foo','bar'),('from','baz'),('subject','boring')] |
| 207 |
>>> i = ['from','subject','to','from'] |
| 208 |
>>> select_headers(h,i) |
| 209 |
[('from', 'baz'), ('subject', 'boring'), ('from', 'biz')] |
| 210 |
>>> h = [('From','biz'),('Foo','bar'),('Subject','Boring')] |
| 211 |
>>> i = ['from','subject','to','from'] |
| 212 |
>>> select_headers(h,i) |
| 213 |
[('From', 'biz'), ('Subject', 'Boring')] |
| 214 |
""" |
| 215 |
sign_headers = [] |
| 216 |
lastindex = {} |
| 217 |
for h in include_headers: |
| 218 |
assert h == h.lower() |
| 219 |
i = lastindex.get(h, len(headers)) |
| 220 |
while i > 0: |
| 221 |
i -= 1 |
| 222 |
if h == headers[i][0].lower(): |
| 223 |
sign_headers.append(headers[i]) |
| 224 |
break |
| 225 |
lastindex[h] = i |
| 226 |
return sign_headers |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
FWS = br'(?:(?:\s*\r?\n)?\s+)?' |
| 231 |
RE_BTAG = re.compile(br'([;\s]b'+FWS+br'=)(?:'+FWS+br'[a-zA-Z0-9+/=])*(?:\r?\n\Z)?') |
| 232 |
|
| 233 |
|
| 234 |
def hash_headers(hasher, canonicalize_headers, headers, include_headers, |
| 235 |
sigheader, sig): |
| 236 |
"""Update hash for signed message header fields.""" |
| 237 |
sign_headers = select_headers(headers,include_headers) |
| 238 |
|
| 239 |
|
| 240 |
cheaders = canonicalize_headers.canonicalize_headers( |
| 241 |
[(sigheader[0], RE_BTAG.sub(b'\\1',sigheader[1]))]) |
| 242 |
|
| 243 |
|
| 244 |
for x,y in sign_headers + [(x, y.rstrip()) for x,y in cheaders]: |
| 245 |
hasher.update(x) |
| 246 |
hasher.update(b":") |
| 247 |
hasher.update(y) |
| 248 |
return sign_headers |
| 249 |
|
| 250 |
|
| 251 |
def hash_headers_ed25519(pk, canonicalize_headers, headers, include_headers, |
| 252 |
sigheader, sig): |
| 253 |
"""Update hash for signed message header fields.""" |
| 254 |
hash_header = '' |
| 255 |
sign_headers = select_headers(headers,include_headers) |
| 256 |
|
| 257 |
|
| 258 |
cheaders = canonicalize_headers.canonicalize_headers( |
| 259 |
[(sigheader[0], RE_BTAG.sub(b'\\1',sigheader[1]))]) |
| 260 |
|
| 261 |
|
| 262 |
for x,y in sign_headers + [(x, y.rstrip()) for x,y in cheaders]: |
| 263 |
hash_header += x + y |
| 264 |
return sign_headers, hash_header |
| 265 |
|
| 266 |
|
| 267 |
def validate_signature_fields(sig, mandatory_fields=[b'v', b'a', b'b', b'bh', b'd', b'h', b's'], arc=False): |
| 268 |
"""Validate DKIM or ARC Signature fields. |
| 269 |
Basic checks for presence and correct formatting of mandatory fields. |
| 270 |
Raises a ValidationError if checks fail, otherwise returns None. |
| 271 |
@param sig: A dict mapping field keys to values. |
| 272 |
@param mandatory_fields: A list of non-optional fields |
| 273 |
@param arc: flag to differentiate between dkim & arc |
| 274 |
""" |
| 275 |
if arc: |
| 276 |
hashes = ARC_HASH_ALGORITHMS |
| 277 |
else: |
| 278 |
hashes = HASH_ALGORITHMS |
| 279 |
for field in mandatory_fields: |
| 280 |
if field not in sig: |
| 281 |
raise ValidationError("missing %s=" % field) |
| 282 |
|
| 283 |
if b'a' in sig and not sig[b'a'] in hashes: |
| 284 |
raise ValidationError("unknown signature algorithm: %s" % sig[b'a']) |
| 285 |
|
| 286 |
if b'b' in sig: |
| 287 |
if re.match(br"[\s0-9A-Za-z+/]+[\s=]*$", sig[b'b']) is None: |
| 288 |
raise ValidationError("b= value is not valid base64 (%s)" % sig[b'b']) |
| 289 |
if len(re.sub(br"\s+", b"", sig[b'b'])) % 4 != 0: |
| 290 |
raise ValidationError("b= value is not valid base64 (%s)" % sig[b'b']) |
| 291 |
|
| 292 |
if b'bh' in sig: |
| 293 |
if re.match(br"[\s0-9A-Za-z+/]+[\s=]*$", sig[b'b']) is None: |
| 294 |
raise ValidationError("bh= value is not valid base64 (%s)" % sig[b'bh']) |
| 295 |
if len(re.sub(br"\s+", b"", sig[b'bh'])) % 4 != 0: |
| 296 |
raise ValidationError("bh= value is not valid base64 (%s)" % sig[b'bh']) |
| 297 |
|
| 298 |
if b'cv' in sig and sig[b'cv'] not in (CV_Pass, CV_Fail, CV_None): |
| 299 |
raise ValidationError("cv= value is not valid (%s)" % sig[b'cv']) |
| 300 |
|
| 301 |
|
| 302 |
try: |
| 303 |
str(sig[b'd'], 'ascii') |
| 304 |
|
| 305 |
if re.findall(rb"[\(\)<>\[\]:;@\\,]", sig[b'd']): |
| 306 |
raise ValidationError("d= value is not valid (%s)" % sig[b'd']) |
| 307 |
except UnicodeDecodeError as e: |
| 308 |
|
| 309 |
pass |
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
if not arc and b'i' in sig and ( |
| 314 |
not sig[b'i'].lower().endswith(sig[b'd'].lower()) or |
| 315 |
sig[b'i'][-len(sig[b'd'])-1] not in ('@', '.', 64, 46)): |
| 316 |
raise ValidationError( |
| 317 |
"i= domain is not a subdomain of d= (i=%s d=%s)" % |
| 318 |
(sig[b'i'], sig[b'd'])) |
| 319 |
if b'l' in sig and re.match(br"\d{,76}$", sig[b'l']) is None: |
| 320 |
raise ValidationError( |
| 321 |
"l= value is not a decimal integer (%s)" % sig[b'l']) |
| 322 |
if b'q' in sig and sig[b'q'] != b"dns/txt": |
| 323 |
raise ValidationError("q= value is not dns/txt (%s)" % sig[b'q']) |
| 324 |
|
| 325 |
if b't' in sig: |
| 326 |
if re.match(br"\d+$", sig[b't']) is None: |
| 327 |
raise ValidationError( |
| 328 |
"t= value is not a decimal integer (%s)" % sig[b't']) |
| 329 |
now = int(time.time()) |
| 330 |
slop = 36000 |
| 331 |
t_sign = int(sig[b't']) |
| 332 |
if t_sign > now + slop: |
| 333 |
raise ValidationError("t= value is in the future (%s)" % sig[b't']) |
| 334 |
else: |
| 335 |
t_sign = None |
| 336 |
|
| 337 |
if b'v' in sig and sig[b'v'] != b"1": |
| 338 |
raise ValidationError("v= value is not 1 (%s)" % sig[b'v']) |
| 339 |
|
| 340 |
if b'x' in sig: |
| 341 |
if re.match(br"\d+$", sig[b'x']) is None: |
| 342 |
raise ValidationError( |
| 343 |
"x= value is not a decimal integer (%s)" % sig[b'x']) |
| 344 |
x_sign = int(sig[b'x']) |
| 345 |
now = int(time.time()) |
| 346 |
slop = 36000 |
| 347 |
if x_sign < now - slop: |
| 348 |
raise ValidationError( |
| 349 |
"x= value is past (%s)" % sig[b'x']) |
| 350 |
if t_sign and x_sign < t_sign: |
| 351 |
raise ValidationError( |
| 352 |
"x= value is less than t= value (x=%s t=%s)" % |
| 353 |
(sig[b'x'], sig[b't'])) |
| 354 |
|
| 355 |
|
| 356 |
def rfc822_parse(message): |
| 357 |
"""Parse a message in RFC822 format. |
| 358 |
|
| 359 |
@param message: The message in RFC822 format. Either CRLF or LF is an accepted line separator. |
| 360 |
@return: Returns a tuple of (headers, body) where headers is a list of (name, value) pairs. |
| 361 |
The body is a CRLF-separated string. |
| 362 |
""" |
| 363 |
headers = [] |
| 364 |
lines = re.split(b"\r?\n", message) |
| 365 |
i = 0 |
| 366 |
while i < len(lines): |
| 367 |
if len(lines[i]) == 0: |
| 368 |
|
| 369 |
i += 1 |
| 370 |
break |
| 371 |
if lines[i][0] in ("\x09", "\x20", 0x09, 0x20): |
| 372 |
headers[-1][1] += lines[i]+b"\r\n" |
| 373 |
else: |
| 374 |
m = re.match(br"([\x21-\x7e]+?):", lines[i]) |
| 375 |
if m is not None: |
| 376 |
headers.append([m.group(1), lines[i][m.end(0):]+b"\r\n"]) |
| 377 |
elif lines[i].startswith(b"From "): |
| 378 |
pass |
| 379 |
else: |
| 380 |
raise MessageFormatError("Unexpected characters in RFC822 header: %s" % lines[i]) |
| 381 |
i += 1 |
| 382 |
return (headers, b"\r\n".join(lines[i:])) |
| 383 |
|
| 384 |
|
| 385 |
def text(s): |
| 386 |
"""Normalize bytes/str to str for python 2/3 compatible doctests. |
| 387 |
>>> text(b'foo') |
| 388 |
'foo' |
| 389 |
>>> text(u'foo') |
| 390 |
'foo' |
| 391 |
>>> text('foo') |
| 392 |
'foo' |
| 393 |
""" |
| 394 |
if type(s) is str: return s |
| 395 |
s = s.decode('ascii') |
| 396 |
if type(s) is str: return s |
| 397 |
return s.encode('ascii') |
| 398 |
|
| 399 |
|
| 400 |
def fold(header, namelen=0, linesep=b'\r\n'): |
| 401 |
"""Fold a header line into multiple crlf-separated lines of text at column |
| 402 |
72. The crlf does not count for line length. |
| 403 |
|
| 404 |
>>> text(fold(b'foo')) |
| 405 |
'foo' |
| 406 |
>>> text(fold(b'foo '+b'foo'*24).splitlines()[0]) |
| 407 |
'foo ' |
| 408 |
>>> text(fold(b'foo'*25).splitlines()[-1]) |
| 409 |
' foo' |
| 410 |
>>> len(fold(b'foo'*25).splitlines()[0]) |
| 411 |
72 |
| 412 |
>>> text(fold(b'x')) |
| 413 |
'x' |
| 414 |
>>> text(fold(b'xyz'*24)) |
| 415 |
'xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyz' |
| 416 |
>>> len(fold(b'xyz'*48)) |
| 417 |
150 |
| 418 |
""" |
| 419 |
|
| 420 |
|
| 421 |
maxleng = 72 - namelen |
| 422 |
if len(header) <= maxleng: |
| 423 |
return header |
| 424 |
if len(header) - header.rfind(b"\r\n") == 2 and len(header) <= maxleng +2: |
| 425 |
return header |
| 426 |
i = header.rfind(b"\r\n ") |
| 427 |
if i == -1: |
| 428 |
pre = b"" |
| 429 |
else: |
| 430 |
i += 3 |
| 431 |
pre = header[:i] |
| 432 |
header = header[i:] |
| 433 |
while len(header) > maxleng: |
| 434 |
i = header[:maxleng].rfind(b" ") |
| 435 |
if i == -1: |
| 436 |
j = maxleng |
| 437 |
pre += header[:j] + linesep + b" " |
| 438 |
else: |
| 439 |
j = i + 1 |
| 440 |
pre += header[:i] + linesep + b" " |
| 441 |
header = header[j:] |
| 442 |
maxleng = 71 |
| 443 |
if len(header) > 2: |
| 444 |
return pre + header |
| 445 |
else: |
| 446 |
if pre[0] == b' ': |
| 447 |
return pre[:-1] |
| 448 |
else: |
| 449 |
return pre + header |
| 450 |
|
| 451 |
|
| 452 |
def evaluate_pk(name, s): |
| 453 |
if not s: |
| 454 |
raise KeyFormatError("missing public key: %s"%name) |
| 455 |
try: |
| 456 |
if type(s) is str: |
| 457 |
s = s.encode('ascii') |
| 458 |
pub = parse_tag_value(s) |
| 459 |
except InvalidTagValueList as e: |
| 460 |
raise KeyFormatError(e) |
| 461 |
try: |
| 462 |
if pub[b'v'] != b'DKIM1': |
| 463 |
raise KeyFormatError("bad version") |
| 464 |
except KeyError as e: |
| 465 |
|
| 466 |
pass |
| 467 |
try: |
| 468 |
if pub[b'k'] == b'ed25519': |
| 469 |
try: |
| 470 |
pk = nacl.signing.VerifyKey(pub[b'p'], encoder=nacl.encoding.Base64Encoder) |
| 471 |
except NameError: |
| 472 |
raise NaClNotFoundError('pynacl module required for ed25519 signing, see README.md') |
| 473 |
except nacl.exceptions.ValueError as e: |
| 474 |
raise KeyFormatError("could not parse ed25519 public key (%s): %s" % (pub[b'p'],e)) |
| 475 |
keysize = 256 |
| 476 |
ktag = b'ed25519' |
| 477 |
except KeyError: |
| 478 |
pub[b'k'] = b'rsa' |
| 479 |
if pub[b'k'] == b'rsa': |
| 480 |
try: |
| 481 |
pk = parse_public_key(base64.b64decode(pub[b'p'])) |
| 482 |
keysize = bitsize(pk['modulus']) |
| 483 |
except KeyError: |
| 484 |
raise KeyFormatError("incomplete RSA public key: %s" % s) |
| 485 |
except (TypeError,UnparsableKeyError) as e: |
| 486 |
raise KeyFormatError("could not parse RSA public key (%s): %s" % (pub[b'p'],e)) |
| 487 |
ktag = b'rsa' |
| 488 |
if pub[b'k'] != b'rsa' and pub[b'k'] != b'ed25519': |
| 489 |
raise KeyFormatError('unknown algorithm in k= tag: {0}'.format(pub[b'k'])) |
| 490 |
seqtlsrpt = False |
| 491 |
try: |
| 492 |
|
| 493 |
if pub[b's'] != b'*' and pub[b's'] != b'email' and pub[b's'] != b'tlsrpt': |
| 494 |
pk = None |
| 495 |
keysize = None |
| 496 |
ktag = None |
| 497 |
raise KeyFormatError('unknown service type in s= tag: {0}'.format(pub[b's'])) |
| 498 |
elif pub[b's'] == b'tlsrpt': |
| 499 |
seqtlsrpt = True |
| 500 |
except: |
| 501 |
|
| 502 |
pass |
| 503 |
return pk, keysize, ktag, seqtlsrpt |
| 504 |
|
| 505 |
|
| 506 |
def load_pk_from_dns(name, dnsfunc=get_txt, timeout=5): |
| 507 |
s = dnsfunc(name, timeout=timeout) |
| 508 |
pk, keysize, ktag, seqtlsrpt = evaluate_pk(name, s) |
| 509 |
return pk, keysize, ktag, seqtlsrpt |
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
class DomainSigner(object): |
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
def __init__(self,message=None,logger=None,signature_algorithm=b'rsa-sha256', |
| 528 |
minkey=1024, linesep=b'\r\n', debug_content=False, timeout=5, |
| 529 |
tlsrpt=False): |
| 530 |
self.set_message(message) |
| 531 |
if logger is None: |
| 532 |
logger = get_default_logger() |
| 533 |
self.logger = logger |
| 534 |
self.debug_content = debug_content and logger.isEnabledFor(logging.DEBUG) |
| 535 |
if signature_algorithm not in HASH_ALGORITHMS: |
| 536 |
raise ParameterError( |
| 537 |
"Unsupported signature algorithm: "+signature_algorithm) |
| 538 |
self.signature_algorithm = signature_algorithm |
| 539 |
|
| 540 |
self.should_sign = set(DKIM.SHOULD) |
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
self.should_not_sign = set(DKIM.SHOULD_NOT) |
| 546 |
|
| 547 |
self.frozen_sign = set(DKIM.FROZEN) |
| 548 |
|
| 549 |
|
| 550 |
self.minkey = minkey |
| 551 |
|
| 552 |
self.linesep = linesep |
| 553 |
self.timeout = timeout |
| 554 |
self.tlsrpt = tlsrpt |
| 555 |
|
| 556 |
self.seqtlsrpt = False |
| 557 |
|
| 558 |
|
| 559 |
|
| 560 |
|
| 561 |
|
| 562 |
|
| 563 |
FROZEN = (b'from',) |
| 564 |
|
| 565 |
|
| 566 |
|
| 567 |
SHOULD = ( |
| 568 |
b'from', b'sender', b'reply-to', b'subject', b'date', b'message-id', b'to', b'cc', |
| 569 |
b'mime-version', b'content-type', b'content-transfer-encoding', |
| 570 |
b'content-id', b'content-description', b'resent-date', b'resent-from', |
| 571 |
b'resent-sender', b'resent-to', b'resent-cc', b'resent-message-id', |
| 572 |
b'in-reply-to', b'references', b'list-id', b'list-help', b'list-unsubscribe', |
| 573 |
b'list-subscribe', b'list-post', b'list-owner', b'list-archive' |
| 574 |
) |
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
SHOULD_NOT = ( |
| 579 |
b'return-path',b'received',b'comments',b'keywords',b'bcc',b'resent-bcc', |
| 580 |
b'dkim-signature' |
| 581 |
) |
| 582 |
|
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
RFC5322_SINGLETON = (b'date',b'from',b'sender',b'reply-to',b'to',b'cc',b'bcc', |
| 593 |
b'message-id',b'in-reply-to',b'references') |
| 594 |
|
| 595 |
def add_frozen(self,s): |
| 596 |
""" Add headers not in should_not_sign to frozen_sign. |
| 597 |
@param s: list of headers to add to frozen_sign |
| 598 |
@since: 0.5 |
| 599 |
|
| 600 |
>>> dkim = DKIM() |
| 601 |
>>> dkim.add_frozen(DKIM.RFC5322_SINGLETON) |
| 602 |
>>> [text(x) for x in sorted(dkim.frozen_sign)] |
| 603 |
['cc', 'date', 'from', 'in-reply-to', 'message-id', 'references', 'reply-to', 'sender', 'to'] |
| 604 |
>>> dkim2 = DKIM() |
| 605 |
>>> dkim2.add_frozen((b'date',b'subject')) |
| 606 |
>>> [text(x) for x in sorted(dkim2.frozen_sign)] |
| 607 |
['date', 'from', 'subject'] |
| 608 |
""" |
| 609 |
self.frozen_sign.update(x.lower() for x in s |
| 610 |
if x.lower() not in self.should_not_sign) |
| 611 |
|
| 612 |
|
| 613 |
def add_should_not(self,s): |
| 614 |
""" Add headers not in should_not_sign to frozen_sign. |
| 615 |
@param s: list of headers to add to frozen_sign |
| 616 |
@since: 0.9 |
| 617 |
|
| 618 |
>>> dkim = DKIM() |
| 619 |
>>> dkim.add_should_not(DKIM.RFC5322_SINGLETON) |
| 620 |
>>> [text(x) for x in sorted(dkim.should_not_sign)] |
| 621 |
['bcc', 'cc', 'comments', 'date', 'dkim-signature', 'in-reply-to', 'keywords', 'message-id', 'received', 'references', 'reply-to', 'resent-bcc', 'return-path', 'sender', 'to'] |
| 622 |
""" |
| 623 |
self.should_not_sign.update(x.lower() for x in s |
| 624 |
if x.lower() not in self.frozen_sign) |
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
def set_message(self,message): |
| 632 |
if message: |
| 633 |
self.headers, self.body = rfc822_parse(message) |
| 634 |
else: |
| 635 |
self.headers, self.body = [],'' |
| 636 |
|
| 637 |
self.domain = None |
| 638 |
|
| 639 |
self.selector = 'default' |
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
self.signature_fields = {} |
| 644 |
|
| 645 |
|
| 646 |
|
| 647 |
self.signed_headers = [] |
| 648 |
|
| 649 |
self.keysize = 0 |
| 650 |
|
| 651 |
def default_sign_headers(self): |
| 652 |
"""Return the default list of headers to sign: those in should_sign or |
| 653 |
frozen_sign, with those in frozen_sign signed an extra time to prevent |
| 654 |
additions. |
| 655 |
@since: 0.5""" |
| 656 |
hset = self.should_sign | self.frozen_sign |
| 657 |
include_headers = [ x for x,y in self.headers |
| 658 |
if x.lower() in hset ] |
| 659 |
return include_headers + [ x for x in include_headers |
| 660 |
if x.lower() in self.frozen_sign] |
| 661 |
|
| 662 |
def all_sign_headers(self): |
| 663 |
"""Return header list of all existing headers not in should_not_sign. |
| 664 |
@since: 0.5""" |
| 665 |
return [x for x,y in self.headers if x.lower() not in self.should_not_sign] |
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
def gen_header(self, fields, include_headers, canon_policy, header_name, pk, standardize=False): |
| 676 |
if standardize: |
| 677 |
lower = [(x,y.lower().replace(b' ', b'')) for (x,y) in fields if x != b'bh'] |
| 678 |
reg = [(x,y.replace(b' ', b'')) for (x,y) in fields if x == b'bh'] |
| 679 |
fields = lower + reg |
| 680 |
fields = sorted(fields, key=(lambda x: x[0])) |
| 681 |
|
| 682 |
header_value = b"; ".join(b"=".join(x) for x in fields) |
| 683 |
if not standardize: |
| 684 |
header_value = fold(header_value, namelen=len(header_name), linesep=b'\r\n') |
| 685 |
header_value = RE_BTAG.sub(b'\\1',header_value) |
| 686 |
header = (header_name, b' ' + header_value) |
| 687 |
h = HashThrough(self.hasher(), self.debug_content) |
| 688 |
sig = dict(fields) |
| 689 |
|
| 690 |
headers = canon_policy.canonicalize_headers(self.headers) |
| 691 |
self.signed_headers = hash_headers( |
| 692 |
h, canon_policy, headers, include_headers, header, sig) |
| 693 |
if self.debug_content: |
| 694 |
self.logger.debug("sign %s headers: %r" % (header_name, h.hashed())) |
| 695 |
|
| 696 |
if self.signature_algorithm == b'rsa-sha256' or self.signature_algorithm == b'rsa-sha1': |
| 697 |
try: |
| 698 |
sig2 = RSASSA_PKCS1_v1_5_sign(h, pk) |
| 699 |
except DigestTooLargeError: |
| 700 |
raise ParameterError("digest too large for modulus") |
| 701 |
elif self.signature_algorithm == b'ed25519-sha256': |
| 702 |
sigobj = pk.sign(h.digest()) |
| 703 |
sig2 = sigobj.signature |
| 704 |
|
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
idx = [i for i in range(len(fields)) if fields[i][0] == b'b'][0] |
| 710 |
fields[idx] = (b'b', base64.b64encode(bytes(sig2))) |
| 711 |
header_value = b"; ".join(b"=".join(x) for x in fields) + self.linesep |
| 712 |
|
| 713 |
if not standardize: |
| 714 |
header_value = fold(header_value, namelen=len(header_name), linesep=self.linesep) |
| 715 |
|
| 716 |
return header_value |
| 717 |
|
| 718 |
def verify_sig_process(self, sig, include_headers, sig_header, dnsfunc): |
| 719 |
"""Non-async sensitive verify_sig elements. Separated to avoid async code |
| 720 |
duplication.""" |
| 721 |
|
| 722 |
if self.tlsrpt == 'strict' and not self.seqtlsrpt: |
| 723 |
raise ValidationError("Message is tlsrpt and Service Type is not tlsrpt") |
| 724 |
|
| 725 |
if not self.tlsrpt and self.seqtlsrpt: |
| 726 |
raise ValidationError("Message is not tlsrpt and Service Type is tlsrpt") |
| 727 |
|
| 728 |
try: |
| 729 |
canon_policy = CanonicalizationPolicy.from_c_value(sig.get(b'c', b'simple/simple')) |
| 730 |
except InvalidCanonicalizationPolicyError as e: |
| 731 |
raise MessageFormatError("invalid c= value: %s" % e.args[0]) |
| 732 |
|
| 733 |
hasher = HASH_ALGORITHMS[sig[b'a']] |
| 734 |
|
| 735 |
|
| 736 |
if b'bh' in sig: |
| 737 |
h = HashThrough(hasher(), self.debug_content) |
| 738 |
|
| 739 |
body = canon_policy.canonicalize_body(self.body) |
| 740 |
if b'l' in sig and not self.tlsrpt: |
| 741 |
body = body[:int(sig[b'l'])] |
| 742 |
h.update(body) |
| 743 |
if self.debug_content: |
| 744 |
self.logger.debug("body hashed: %r" % h.hashed()) |
| 745 |
bodyhash = h.digest() |
| 746 |
|
| 747 |
self.logger.debug("bh: %s" % base64.b64encode(bodyhash)) |
| 748 |
try: |
| 749 |
bh = base64.b64decode(re.sub(br"\s+", b"", sig[b'bh'])) |
| 750 |
except TypeError as e: |
| 751 |
raise MessageFormatError(str(e)) |
| 752 |
if bodyhash != bh: |
| 753 |
raise ValidationError( |
| 754 |
"body hash mismatch (got %s, expected %s)" % |
| 755 |
(base64.b64encode(bodyhash), sig[b'bh'])) |
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
if b'from' in include_headers: |
| 762 |
include_headers.append(b'from') |
| 763 |
h = HashThrough(hasher(), self.debug_content) |
| 764 |
|
| 765 |
headers = canon_policy.canonicalize_headers(self.headers) |
| 766 |
self.signed_headers = hash_headers( |
| 767 |
h, canon_policy, headers, include_headers, sig_header, sig) |
| 768 |
if self.debug_content: |
| 769 |
self.logger.debug("signed for %s: %r" % (sig_header[0], h.hashed())) |
| 770 |
signature = base64.b64decode(re.sub(br"\s+", b"", sig[b'b'])) |
| 771 |
if self.ktag == b'rsa': |
| 772 |
try: |
| 773 |
res = RSASSA_PKCS1_v1_5_verify(h, signature, self.pk) |
| 774 |
self.logger.debug("%s valid: %s" % (sig_header[0], res)) |
| 775 |
if res and self.keysize < self.minkey: |
| 776 |
raise KeyFormatError("public key too small: %d" % self.keysize) |
| 777 |
return res |
| 778 |
except (TypeError,DigestTooLargeError) as e: |
| 779 |
raise KeyFormatError("digest too large for modulus: %s"%e) |
| 780 |
elif self.ktag == b'ed25519': |
| 781 |
try: |
| 782 |
self.pk.verify(h.digest(), signature) |
| 783 |
self.logger.debug("%s valid" % (sig_header[0])) |
| 784 |
return True |
| 785 |
except (nacl.exceptions.BadSignatureError) as e: |
| 786 |
return False |
| 787 |
else: |
| 788 |
raise UnknownKeyTypeError(self.ktag) |
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
def verify_sig(self, sig, include_headers, sig_header, dnsfunc): |
| 797 |
name = sig[b's'] + b"._domainkey." + sig[b'd'] + b"." |
| 798 |
try: |
| 799 |
self.pk, self.keysize, self.ktag, self.seqtlsrpt = load_pk_from_dns(name, |
| 800 |
dnsfunc, timeout=self.timeout) |
| 801 |
except KeyFormatError as e: |
| 802 |
self.logger.error("%s" % e) |
| 803 |
return False |
| 804 |
except binascii.Error as e: |
| 805 |
self.logger.error('KeyFormatError: {0}'.format(e)) |
| 806 |
return False |
| 807 |
except DnsTimeoutError as e: |
| 808 |
self.logger.error('DnsTimeoutError: Domain: {0} Selector: {1} Error message: {2}'.format( |
| 809 |
sig[b'd'], sig[b's'], e)) |
| 810 |
return False |
| 811 |
return self.verify_sig_process(sig, include_headers, sig_header, dnsfunc) |
| 812 |
|
| 813 |
|
| 814 |
|
| 815 |
class DKIM(DomainSigner): |
| 816 |
|
| 817 |
|
| 818 |
|
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
|
| 829 |
|
| 830 |
|
| 831 |
|
| 832 |
|
| 833 |
|
| 834 |
|
| 835 |
|
| 836 |
|
| 837 |
|
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
|
| 842 |
|
| 843 |
|
| 844 |
|
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
|
| 849 |
|
| 850 |
|
| 851 |
def sign(self, selector, domain, privkey, signature_algorithm=None, identity=None, |
| 852 |
canonicalize=(b'relaxed',b'simple'), include_headers=None, length=False): |
| 853 |
if signature_algorithm: |
| 854 |
self.signature_algorithm = signature_algorithm |
| 855 |
if self.signature_algorithm == b'rsa-sha256' or self.signature_algorithm == b'rsa-sha1': |
| 856 |
try: |
| 857 |
pk = parse_pem_private_key(privkey) |
| 858 |
except UnparsableKeyError as e: |
| 859 |
raise KeyFormatError(str(e)) |
| 860 |
elif self.signature_algorithm == b'ed25519-sha256': |
| 861 |
try: |
| 862 |
pk = nacl.signing.SigningKey(privkey, encoder=nacl.encoding.Base64Encoder) |
| 863 |
except NameError: |
| 864 |
raise NaClNotFoundError('pynacl module required for ed25519 signing, see README.md') |
| 865 |
except nacl.exceptions.ValueError: |
| 866 |
raise KeyFormatError('invalid ed25519 private key or format') |
| 867 |
|
| 868 |
if identity is not None and not identity.endswith(domain): |
| 869 |
raise ParameterError("identity must end with domain") |
| 870 |
|
| 871 |
canon_policy = CanonicalizationPolicy.from_c_value(b'/'.join(canonicalize)) |
| 872 |
|
| 873 |
if include_headers is None: |
| 874 |
include_headers = self.default_sign_headers() |
| 875 |
try: |
| 876 |
include_headers = [bytes(x, 'utf-8') for x in include_headers] |
| 877 |
except TypeError: |
| 878 |
|
| 879 |
|
| 880 |
pass |
| 881 |
|
| 882 |
include_headers = tuple([x.lower() for x in include_headers]) |
| 883 |
|
| 884 |
self.include_headers = include_headers |
| 885 |
|
| 886 |
if self.tlsrpt: |
| 887 |
|
| 888 |
length = False |
| 889 |
|
| 890 |
|
| 891 |
if b'from' not in include_headers: |
| 892 |
raise ParameterError("The From header field MUST be signed") |
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
for x in set(include_headers).intersection(self.should_not_sign): |
| 897 |
raise ParameterError("The %s header field SHOULD NOT be signed"%x) |
| 898 |
|
| 899 |
body = canon_policy.canonicalize_body(self.body) |
| 900 |
|
| 901 |
self.hasher = HASH_ALGORITHMS[self.signature_algorithm] |
| 902 |
h = self.hasher() |
| 903 |
h.update(body) |
| 904 |
bodyhash = base64.b64encode(h.digest()) |
| 905 |
|
| 906 |
sigfields = [x for x in [ |
| 907 |
(b'v', b"1"), |
| 908 |
(b'a', self.signature_algorithm), |
| 909 |
(b'c', canon_policy.to_c_value()), |
| 910 |
(b'd', domain), |
| 911 |
(b'i', identity or b"@"+domain), |
| 912 |
length and (b'l', str(len(body)).encode('ascii')), |
| 913 |
(b'q', b"dns/txt"), |
| 914 |
(b's', selector), |
| 915 |
(b't', str(int(time.time())).encode('ascii')), |
| 916 |
(b'h', b" : ".join(include_headers)), |
| 917 |
(b'bh', bodyhash), |
| 918 |
|
| 919 |
|
| 920 |
(b'b', b'0'*60), |
| 921 |
] if x] |
| 922 |
|
| 923 |
res = self.gen_header(sigfields, include_headers, canon_policy, |
| 924 |
b"DKIM-Signature", pk) |
| 925 |
|
| 926 |
self.domain = domain |
| 927 |
self.selector = selector |
| 928 |
self.signature_fields = dict(sigfields) |
| 929 |
return b'DKIM-Signature: ' + res |
| 930 |
|
| 931 |
|
| 932 |
|
| 933 |
def present(self): |
| 934 |
return (len([(x,y) for x,y in self.headers if x.lower() == b"dkim-signature"]) > 0) |
| 935 |
|
| 936 |
def verify_headerprep(self, idx=0): |
| 937 |
"""Non-DNS verify parts to minimize asyncio code duplication.""" |
| 938 |
|
| 939 |
sigheaders = [(x,y) for x,y in self.headers if x.lower() == b"dkim-signature"] |
| 940 |
if len(sigheaders) <= idx: |
| 941 |
return False |
| 942 |
|
| 943 |
|
| 944 |
try: |
| 945 |
sig = parse_tag_value(sigheaders[idx][1]) |
| 946 |
self.signature_fields = sig |
| 947 |
except InvalidTagValueList as e: |
| 948 |
raise MessageFormatError(e) |
| 949 |
|
| 950 |
self.logger.debug("sig: %r" % sig) |
| 951 |
|
| 952 |
validate_signature_fields(sig) |
| 953 |
self.domain = sig[b'd'] |
| 954 |
self.selector = sig[b's'] |
| 955 |
|
| 956 |
include_headers = [x.lower() for x in re.split(br"\s*:\s*", sig[b'h'])] |
| 957 |
self.include_headers = tuple(include_headers) |
| 958 |
return sig, include_headers, sigheaders |
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
def verify(self,idx=0,dnsfunc=get_txt): |
| 969 |
prep = self.verify_headerprep(idx) |
| 970 |
if prep: |
| 971 |
sig, include_headers, sigheaders = prep |
| 972 |
return self.verify_sig(sig, include_headers, sigheaders[idx], dnsfunc) |
| 973 |
return False |
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
class ARC(DomainSigner): |
| 978 |
|
| 979 |
ARC_HEADERS = (b'arc-seal', b'arc-message-signature', b'arc-authentication-results') |
| 980 |
|
| 981 |
|
| 982 |
INSTANCE_RE = re.compile(br'[\s;]?i\s*=\s*(\d+)', re.MULTILINE | re.IGNORECASE) |
| 983 |
|
| 984 |
def sorted_arc_headers(self): |
| 985 |
headers = [] |
| 986 |
|
| 987 |
relaxed_headers = RelaxedCanonicalization.canonicalize_headers(self.headers) |
| 988 |
for x,y in relaxed_headers: |
| 989 |
if x.lower() in ARC.ARC_HEADERS: |
| 990 |
m = ARC.INSTANCE_RE.search(y) |
| 991 |
if m is not None: |
| 992 |
try: |
| 993 |
i = int(m.group(1)) |
| 994 |
headers.append((i, (x, y))) |
| 995 |
except ValueError: |
| 996 |
self.logger.debug("invalid instance number %s: '%s: %s'" % (m.group(1), x, y)) |
| 997 |
else: |
| 998 |
self.logger.debug("not instance number: '%s: %s'" % (x, y)) |
| 999 |
|
| 1000 |
if len(headers) == 0: |
| 1001 |
return 0, [] |
| 1002 |
|
| 1003 |
def arc_header_key(a): |
| 1004 |
return [a[0], a[1][0].lower(), a[1][1].lower()] |
| 1005 |
|
| 1006 |
headers = sorted(headers, key=arc_header_key) |
| 1007 |
headers.reverse() |
| 1008 |
return headers[0][0], headers |
| 1009 |
|
| 1010 |
|
| 1011 |
|
| 1012 |
|
| 1013 |
|
| 1014 |
|
| 1015 |
|
| 1016 |
|
| 1017 |
|
| 1018 |
|
| 1019 |
|
| 1020 |
|
| 1021 |
|
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
|
| 1026 |
|
| 1027 |
|
| 1028 |
|
| 1029 |
|
| 1030 |
|
| 1031 |
|
| 1032 |
|
| 1033 |
|
| 1034 |
|
| 1035 |
|
| 1036 |
|
| 1037 |
def sign(self, selector, domain, privkey, srv_id, include_headers=None, |
| 1038 |
timestamp=None, standardize=False): |
| 1039 |
|
| 1040 |
INSTANCE_LIMIT = 50 |
| 1041 |
self.add_should_not(('Authentication-Results',)) |
| 1042 |
|
| 1043 |
try: |
| 1044 |
authres.AuthenticationResultsHeader |
| 1045 |
except: |
| 1046 |
self.logger.debug("authres package not installed") |
| 1047 |
raise authres.AuthresNotFoundError |
| 1048 |
|
| 1049 |
try: |
| 1050 |
pk = parse_pem_private_key(privkey) |
| 1051 |
except UnparsableKeyError as e: |
| 1052 |
raise KeyFormatError(str(e)) |
| 1053 |
|
| 1054 |
|
| 1055 |
ar_headers = [res.strip() for [ar, res] in self.headers if ar == b'Authentication-Results'] |
| 1056 |
|
| 1057 |
parsed_ar_headers = [] |
| 1058 |
for res in ar_headers: |
| 1059 |
try: |
| 1060 |
|
| 1061 |
parsed_ar_headers.append(authres.AuthenticationResultsHeader.parse('Authentication-Results: ' + res.decode('utf-8'))) |
| 1062 |
except authres.core.SyntaxError: |
| 1063 |
|
| 1064 |
pass |
| 1065 |
auth_headers = [header for header in parsed_ar_headers if header.authserv_id == srv_id.decode('utf-8')] |
| 1066 |
|
| 1067 |
if len(auth_headers) == 0: |
| 1068 |
self.logger.debug("no AR headers found, chain terminated") |
| 1069 |
return [] |
| 1070 |
|
| 1071 |
|
| 1072 |
results = [res for header in auth_headers for res in header.results] |
| 1073 |
auth_results = srv_id + b''.join(b';' + self.linesep + b' ' + str(res).encode('utf-8') for res in results) |
| 1074 |
|
| 1075 |
|
| 1076 |
arc_results = [res for res in results if res.method == 'arc'] |
| 1077 |
if len(arc_results) == 0: |
| 1078 |
chain_validation_status = CV_None |
| 1079 |
elif len(arc_results) != 1: |
| 1080 |
self.logger.debug("multiple AR arc stamps found, failing chain") |
| 1081 |
chain_validation_status = CV_Fail |
| 1082 |
else: |
| 1083 |
chain_validation_status = arc_results[0].result.lower().encode('utf-8') |
| 1084 |
|
| 1085 |
|
| 1086 |
if include_headers is None: |
| 1087 |
include_headers = self.default_sign_headers() |
| 1088 |
|
| 1089 |
include_headers = tuple([x.lower() for x in include_headers]) |
| 1090 |
|
| 1091 |
|
| 1092 |
self.include_headers = include_headers |
| 1093 |
|
| 1094 |
|
| 1095 |
if b'from' not in include_headers: |
| 1096 |
raise ParameterError("The From header field MUST be signed") |
| 1097 |
|
| 1098 |
|
| 1099 |
|
| 1100 |
for x in set(include_headers).intersection(self.should_not_sign): |
| 1101 |
raise ParameterError("The %s header field SHOULD NOT be signed"%x) |
| 1102 |
|
| 1103 |
max_instance, arc_headers_w_instance = self.sorted_arc_headers() |
| 1104 |
instance = 1 |
| 1105 |
if len(arc_headers_w_instance) != 0: |
| 1106 |
instance = max_instance + 1 |
| 1107 |
if instance > INSTANCE_LIMIT: |
| 1108 |
raise ParameterError("Maximum instance tag value exceeded") |
| 1109 |
|
| 1110 |
if instance == 1 and chain_validation_status != CV_None: |
| 1111 |
raise ParameterError("No existing chain found on message, cv should be none") |
| 1112 |
elif instance != 1 and chain_validation_status == CV_None: |
| 1113 |
self.logger.debug("no previous AR arc results found and instance > 1, chain terminated") |
| 1114 |
return [] |
| 1115 |
|
| 1116 |
new_arc_set = [] |
| 1117 |
if chain_validation_status != CV_Fail: |
| 1118 |
arc_headers = [y for x,y in arc_headers_w_instance] |
| 1119 |
else: |
| 1120 |
arc_headers = [] |
| 1121 |
|
| 1122 |
|
| 1123 |
aar_value = ("i=%d; " % instance).encode('utf-8') + auth_results.rstrip() + self.linesep |
| 1124 |
canon_policy = CanonicalizationPolicy.from_c_value(b'relaxed/relaxed') |
| 1125 |
new_arc_set.append(b"ARC-Authentication-Results: " + aar_value) |
| 1126 |
arc_headers.insert(0, (b"ARC-Authentication-Results", aar_value)) |
| 1127 |
self.headers = canon_policy.canonicalize_headers(arc_headers[:1]) + self.headers |
| 1128 |
|
| 1129 |
|
| 1130 |
self.hasher = HASH_ALGORITHMS[self.signature_algorithm] |
| 1131 |
h = HashThrough(self.hasher(), self.debug_content) |
| 1132 |
h.update(canon_policy.canonicalize_body(self.body)) |
| 1133 |
if self.debug_content: |
| 1134 |
self.logger.debug("sign ams body hashed: %r" % h.hashed()) |
| 1135 |
bodyhash = base64.b64encode(h.digest()) |
| 1136 |
|
| 1137 |
|
| 1138 |
timestamp = str(timestamp or int(time.time())).encode('ascii') |
| 1139 |
ams_fields = [x for x in [ |
| 1140 |
(b'i', str(instance).encode('ascii')), |
| 1141 |
(b'a', self.signature_algorithm), |
| 1142 |
(b'c', b'relaxed/relaxed'), |
| 1143 |
(b'd', domain), |
| 1144 |
(b's', selector), |
| 1145 |
(b't', timestamp), |
| 1146 |
(b'h', b" : ".join(include_headers)), |
| 1147 |
(b'bh', bodyhash), |
| 1148 |
|
| 1149 |
|
| 1150 |
(b'b', b'0'*60), |
| 1151 |
] if x] |
| 1152 |
|
| 1153 |
res = self.gen_header(ams_fields, include_headers, canon_policy, |
| 1154 |
b"ARC-Message-Signature", pk, standardize) |
| 1155 |
|
| 1156 |
new_arc_set.append(b"ARC-Message-Signature: " + res) |
| 1157 |
arc_headers.insert(0, (b"ARC-Message-Signature", res)) |
| 1158 |
self.headers = canon_policy.canonicalize_headers(arc_headers[:1]) + self.headers |
| 1159 |
|
| 1160 |
|
| 1161 |
as_fields = [x for x in [ |
| 1162 |
(b'i', str(instance).encode('ascii')), |
| 1163 |
(b'cv', chain_validation_status), |
| 1164 |
(b'a', self.signature_algorithm), |
| 1165 |
(b'd', domain), |
| 1166 |
(b's', selector), |
| 1167 |
(b't', timestamp), |
| 1168 |
|
| 1169 |
|
| 1170 |
(b'b', b'0'*60), |
| 1171 |
] if x] |
| 1172 |
|
| 1173 |
as_include_headers = [x[0].lower() for x in arc_headers] |
| 1174 |
as_include_headers.reverse() |
| 1175 |
|
| 1176 |
|
| 1177 |
|
| 1178 |
if chain_validation_status == CV_Fail: |
| 1179 |
self.headers.reverse() |
| 1180 |
if b'h' in as_fields: |
| 1181 |
raise ValidationError("h= tag not permitted in ARC-Seal header field") |
| 1182 |
res = self.gen_header(as_fields, as_include_headers, canon_policy, |
| 1183 |
b"ARC-Seal", pk, standardize) |
| 1184 |
|
| 1185 |
new_arc_set.append(b"ARC-Seal: " + res) |
| 1186 |
arc_headers.insert(0, (b"ARC-Seal", res)) |
| 1187 |
self.headers = canon_policy.canonicalize_headers(arc_headers[:1]) + self.headers |
| 1188 |
|
| 1189 |
new_arc_set.reverse() |
| 1190 |
|
| 1191 |
return new_arc_set |
| 1192 |
|
| 1193 |
|
| 1194 |
|
| 1195 |
|
| 1196 |
|
| 1197 |
|
| 1198 |
|
| 1199 |
|
| 1200 |
|
| 1201 |
|
| 1202 |
|
| 1203 |
def verify(self,dnsfunc=get_txt): |
| 1204 |
result_data = [] |
| 1205 |
max_instance, arc_headers_w_instance = self.sorted_arc_headers() |
| 1206 |
if max_instance == 0: |
| 1207 |
return CV_None, result_data, "Message is not ARC signed" |
| 1208 |
for instance in range(max_instance, 0, -1): |
| 1209 |
try: |
| 1210 |
result = self.verify_instance(arc_headers_w_instance, instance, dnsfunc=dnsfunc) |
| 1211 |
result_data.append(result) |
| 1212 |
except DKIMException as e: |
| 1213 |
self.logger.error("%s" % e) |
| 1214 |
return CV_Fail, result_data, "%s" % e |
| 1215 |
|
| 1216 |
|
| 1217 |
if not result_data[0]['ams-valid']: |
| 1218 |
return CV_Fail, result_data, "Most recent ARC-Message-Signature did not validate" |
| 1219 |
for result in result_data: |
| 1220 |
if result['cv'] == CV_Fail: |
| 1221 |
return None, result_data, "ARC-Seal[%d] reported failure, the chain is terminated" % result['instance'] |
| 1222 |
elif not result['as-valid']: |
| 1223 |
return CV_Fail, result_data, "ARC-Seal[%d] did not validate" % result['instance'] |
| 1224 |
elif (result['instance'] == 1) and (result['cv'] != CV_None): |
| 1225 |
return CV_Fail, result_data, "ARC-Seal[%d] reported invalid status %s" % (result['instance'], result['cv']) |
| 1226 |
elif (result['instance'] != 1) and (result['cv'] == CV_None): |
| 1227 |
return CV_Fail, result_data, "ARC-Seal[%d] reported invalid status %s" % (result['instance'], result['cv']) |
| 1228 |
return CV_Pass, result_data, "success" |
| 1229 |
|
| 1230 |
|
| 1231 |
|
| 1232 |
|
| 1233 |
|
| 1234 |
|
| 1235 |
|
| 1236 |
|
| 1237 |
|
| 1238 |
|
| 1239 |
|
| 1240 |
|
| 1241 |
def verify_instance(self,arc_headers_w_instance,instance,dnsfunc=get_txt): |
| 1242 |
if (instance == 0) or (len(arc_headers_w_instance) == 0): |
| 1243 |
raise ParameterError("request to verify instance %d not present" % (instance)) |
| 1244 |
|
| 1245 |
aar_value = None |
| 1246 |
ams_value = None |
| 1247 |
as_value = None |
| 1248 |
arc_headers = [] |
| 1249 |
output = { 'instance': instance } |
| 1250 |
|
| 1251 |
for i, arc_header in arc_headers_w_instance: |
| 1252 |
if i > instance: continue |
| 1253 |
arc_headers.append(arc_header) |
| 1254 |
if i == instance: |
| 1255 |
if arc_header[0].lower() == b"arc-authentication-results": |
| 1256 |
if aar_value is not None: |
| 1257 |
raise MessageFormatError("Duplicate ARC-Authentication-Results for instance %d" % instance) |
| 1258 |
aar_value = arc_header[1] |
| 1259 |
elif arc_header[0].lower() == b"arc-message-signature": |
| 1260 |
if ams_value is not None: |
| 1261 |
raise MessageFormatError("Duplicate ARC-Message-Signature for instance %d" % instance) |
| 1262 |
ams_value = arc_header[1] |
| 1263 |
elif arc_header[0].lower() == b"arc-seal": |
| 1264 |
if as_value is not None: |
| 1265 |
raise MessageFormatError("Duplicate ARC-Seal for instance %d" % instance) |
| 1266 |
as_value = arc_header[1] |
| 1267 |
|
| 1268 |
if (aar_value is None) or (ams_value is None) or (as_value is None): |
| 1269 |
raise MessageFormatError("Incomplete ARC set for instance %d" % instance) |
| 1270 |
|
| 1271 |
output['aar-value'] = aar_value |
| 1272 |
|
| 1273 |
|
| 1274 |
try: |
| 1275 |
sig = parse_tag_value(ams_value) |
| 1276 |
except InvalidTagValueList as e: |
| 1277 |
raise MessageFormatError(e) |
| 1278 |
|
| 1279 |
self.logger.debug("ams sig[%d]: %r" % (instance, sig)) |
| 1280 |
|
| 1281 |
validate_signature_fields(sig, [b'i', b'a', b'b', b'bh', b'd', b'h', b's'], True) |
| 1282 |
output['ams-domain'] = sig[b'd'] |
| 1283 |
output['ams-selector'] = sig[b's'] |
| 1284 |
|
| 1285 |
include_headers = [x.lower() for x in re.split(br"\s*:\s*", sig[b'h'])] |
| 1286 |
if b'arc-seal' in include_headers: |
| 1287 |
raise ParameterError("The Arc-Message-Signature MUST NOT sign ARC-Seal") |
| 1288 |
|
| 1289 |
ams_header = (b'ARC-Message-Signature', b' ' + ams_value) |
| 1290 |
|
| 1291 |
|
| 1292 |
|
| 1293 |
|
| 1294 |
|
| 1295 |
raw_ams_header = [ |
| 1296 |
(x, y) for (x, y) in self.headers if x.lower() == b'arc-message-signature' and b" i="+sig[b'i']+b";" in y.lower() |
| 1297 |
][0] |
| 1298 |
|
| 1299 |
|
| 1300 |
if b'c' not in sig: |
| 1301 |
sig[b'c'] = b'relaxed/relaxed' |
| 1302 |
try: |
| 1303 |
ams_valid = self.verify_sig(sig, include_headers, raw_ams_header, dnsfunc) |
| 1304 |
except DKIMException as e: |
| 1305 |
self.logger.error("%s" % e) |
| 1306 |
ams_valid = False |
| 1307 |
|
| 1308 |
output['ams-valid'] = ams_valid |
| 1309 |
self.logger.debug("ams valid: %r" % ams_valid) |
| 1310 |
|
| 1311 |
|
| 1312 |
try: |
| 1313 |
sig = parse_tag_value(as_value) |
| 1314 |
except InvalidTagValueList as e: |
| 1315 |
raise MessageFormatError(e) |
| 1316 |
|
| 1317 |
self.logger.debug("as sig[%d]: %r" % (instance, sig)) |
| 1318 |
|
| 1319 |
validate_signature_fields(sig, [b'i', b'a', b'b', b'cv', b'd', b's'], True) |
| 1320 |
if b'h' in sig: |
| 1321 |
raise ValidationError("h= tag not permitted in ARC-Seal header field") |
| 1322 |
|
| 1323 |
output['as-domain'] = sig[b'd'] |
| 1324 |
output['as-selector'] = sig[b's'] |
| 1325 |
output['cv'] = sig[b'cv'] |
| 1326 |
|
| 1327 |
as_include_headers = [x[0].lower() for x in arc_headers] |
| 1328 |
as_include_headers.reverse() |
| 1329 |
as_header = (b'ARC-Seal', b' ' + as_value) |
| 1330 |
|
| 1331 |
if b'c' not in sig: |
| 1332 |
sig[b'c'] = b'relaxed/relaxed' |
| 1333 |
try: |
| 1334 |
as_valid = self.verify_sig(sig, as_include_headers[:-1], as_header, dnsfunc) |
| 1335 |
except DKIMException as e: |
| 1336 |
self.logger.error("%s" % e) |
| 1337 |
as_valid = False |
| 1338 |
|
| 1339 |
output['as-valid'] = as_valid |
| 1340 |
self.logger.debug("as valid: %r" % as_valid) |
| 1341 |
return output |
| 1342 |
|
| 1343 |
|
| 1344 |
def sign(message, selector, domain, privkey, identity=None, |
| 1345 |
canonicalize=(b'relaxed', b'simple'), |
| 1346 |
signature_algorithm=b'rsa-sha256', |
| 1347 |
include_headers=None, length=False, logger=None, |
| 1348 |
linesep=b'\r\n', tlsrpt=False): |
| 1349 |
|
| 1350 |
"""Sign an RFC822 message and return the DKIM-Signature header line. |
| 1351 |
@param message: an RFC822 formatted message (with either \\n or \\r\\n line endings) |
| 1352 |
@param selector: the DKIM selector value for the signature |
| 1353 |
@param domain: the DKIM domain value for the signature |
| 1354 |
@param privkey: a PKCS#1 private key in base64-encoded text form |
| 1355 |
@param identity: the DKIM identity value for the signature (default "@"+domain) |
| 1356 |
@param canonicalize: the canonicalization algorithms to use (default (Simple, Simple)) |
| 1357 |
@param signature_algorithm: the signing algorithm to use when signing |
| 1358 |
@param include_headers: a list of strings indicating which headers are to be signed (default all headers not listed as SHOULD NOT sign) |
| 1359 |
@param length: true if the l= tag should be included to indicate body length (default False) |
| 1360 |
@param logger: a logger to which debug info will be written (default None) |
| 1361 |
@param linesep: use this line seperator for folding the headers |
| 1362 |
@param tlsrpt: message is an RFC 8460 TLS report (default False) |
| 1363 |
False: Not a tlsrpt, True: Is a tlsrpt, 'strict': tlsrpt, invalid if |
| 1364 |
service type is missing. For signing, if True, length is never used. |
| 1365 |
@return: DKIM-Signature header field terminated by \\r\\n |
| 1366 |
@raise DKIMException: when the message, include_headers, or key are badly formed. |
| 1367 |
""" |
| 1368 |
|
| 1369 |
d = DKIM(message,logger=logger,signature_algorithm=signature_algorithm,linesep=linesep,tlsrpt=tlsrpt) |
| 1370 |
return d.sign(selector, domain, privkey, identity=identity, canonicalize=canonicalize, include_headers=include_headers, length=length) |
| 1371 |
|
| 1372 |
|
| 1373 |
def verify(message, logger=None, dnsfunc=get_txt, minkey=1024, |
| 1374 |
timeout=5, tlsrpt=False): |
| 1375 |
"""Verify the first (topmost) DKIM signature on an RFC822 formatted message. |
| 1376 |
@param message: an RFC822 formatted message (with either \\n or \\r\\n line endings) |
| 1377 |
@param logger: a logger to which debug info will be written (default None) |
| 1378 |
@param timeout: number of seconds for DNS lookup timeout (default = 5) |
| 1379 |
@param tlsrpt: message is an RFC 8460 TLS report (default False) |
| 1380 |
False: Not a tlsrpt, True: Is a tlsrpt, 'strict': tlsrpt, invalid if |
| 1381 |
service type is missing. For signing, if True, length is never used. |
| 1382 |
@return: True if signature verifies or False otherwise |
| 1383 |
""" |
| 1384 |
|
| 1385 |
d = DKIM(message,logger=logger,minkey=minkey,timeout=timeout,tlsrpt=tlsrpt) |
| 1386 |
try: |
| 1387 |
return d.verify(dnsfunc=dnsfunc) |
| 1388 |
except DKIMException as x: |
| 1389 |
if logger is not None: |
| 1390 |
logger.error("%s" % x) |
| 1391 |
return False |
| 1392 |
|
| 1393 |
|
| 1394 |
|
| 1395 |
if sys.version_info >= (3, 5) and USE_ASYNC: |
| 1396 |
try: |
| 1397 |
import aiodns |
| 1398 |
from dkim.asyncsupport import verify_async |
| 1399 |
dkim_verify_async = verify_async |
| 1400 |
except ImportError: |
| 1401 |
|
| 1402 |
pass |
| 1403 |
|
| 1404 |
|
| 1405 |
|
| 1406 |
dkim_sign = sign |
| 1407 |
dkim_verify = verify |
| 1408 |
|
| 1409 |
|
| 1410 |
def arc_sign(message, selector, domain, privkey, |
| 1411 |
srv_id, signature_algorithm=b'rsa-sha256', |
| 1412 |
include_headers=None, timestamp=None, |
| 1413 |
logger=None, standardize=False, linesep=b'\r\n'): |
| 1414 |
|
| 1415 |
"""Sign an RFC822 message and return the ARC set header lines for the next instance |
| 1416 |
@param message: an RFC822 formatted message (with either \\n or \\r\\n line endings) |
| 1417 |
@param selector: the DKIM selector value for the signature |
| 1418 |
@param domain: the DKIM domain value for the signature |
| 1419 |
@param privkey: a PKCS#1 private key in base64-encoded text form |
| 1420 |
@param srv_id: the authserv_id used to identify the ADMD's AR headers and to use for ARC authserv_id |
| 1421 |
@param signature_algorithm: the signing algorithm to use when signing |
| 1422 |
@param include_headers: a list of strings indicating which headers are to be signed (default all headers not listed as SHOULD NOT sign) |
| 1423 |
@param timestamp: the time in integer seconds when the message is sealed (default is int(time.time) based on platform, can be string or int) |
| 1424 |
@param logger: a logger to which debug info will be written (default None) |
| 1425 |
@param linesep: use this line seperator for folding the headers |
| 1426 |
@return: A list containing the ARC set of header fields for the next instance |
| 1427 |
@raise DKIMException: when the message, include_headers, or key are badly formed. |
| 1428 |
""" |
| 1429 |
|
| 1430 |
a = ARC(message,logger=logger,signature_algorithm=b'rsa-sha256',linesep=linesep) |
| 1431 |
if not include_headers: |
| 1432 |
include_headers = a.default_sign_headers() |
| 1433 |
return a.sign(selector, domain, privkey, srv_id, include_headers=include_headers, |
| 1434 |
timestamp=timestamp, standardize=standardize) |
| 1435 |
|
| 1436 |
|
| 1437 |
def arc_verify(message, logger=None, dnsfunc=get_txt, minkey=1024, timeout=5): |
| 1438 |
|
| 1439 |
"""Verify the ARC chain on an RFC822 formatted message. |
| 1440 |
@param message: an RFC822 formatted message (with either \\n or \\r\\n line endings) |
| 1441 |
@param logger: a logger to which debug info will be written (default None) |
| 1442 |
@param dnsfunc: an optional function to lookup TXT resource records |
| 1443 |
@param minkey: the minimum key size to accept |
| 1444 |
@param timeout: number of seconds for DNS lookup timeout (default = 5) |
| 1445 |
@return: three-tuple of (CV Result (CV_Pass, CV_Fail or CV_None), list of |
| 1446 |
result dictionaries, result reason) |
| 1447 |
""" |
| 1448 |
a = ARC(message,logger=logger,minkey=minkey,timeout=5) |
| 1449 |
try: |
| 1450 |
return a.verify(dnsfunc=dnsfunc) |
| 1451 |
except DKIMException as x: |
| 1452 |
if logger is not None: |
| 1453 |
logger.error("%s" % x) |
| 1454 |
return CV_Fail, [], "%s" % x |