-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
signers.py
2384 lines (2052 loc) · 90.4 KB
/
signers.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import binascii
import hashlib
import logging
import uuid
from dataclasses import dataclass, field
from datetime import datetime
from io import BytesIO, BufferedIOBase
from typing import Optional, Set
import tzlocal
from asn1crypto import x509, cms, core, algos, keys, pdf as asn1_pdf
from asn1crypto.algos import SignedDigestAlgorithm
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric.ec import \
EllipticCurvePrivateKey, ECDSA
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from cryptography.hazmat.primitives.serialization import pkcs12
from pyhanko_certvalidator.errors import PathValidationError, PathBuildingError
from pyhanko_certvalidator import ValidationContext, CertificateValidator
from pyhanko.sign.ades.api import CAdESSignedAttrSpec
from pyhanko.pdf_utils import generic, misc
from pyhanko.pdf_utils.generic import pdf_name, pdf_date, pdf_string
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
from pyhanko.pdf_utils.layout import BoxConstraints
from pyhanko.pdf_utils.reader import PdfFileReader
from pyhanko.pdf_utils.writer import BasePdfFileWriter
from pyhanko.sign import general
from pyhanko.sign.fields import (
enumerate_sig_fields, _prepare_sig_field,
SigSeedValueSpec, SigSeedValFlags, SigSeedSubFilter, MDPPerm, FieldMDPSpec,
SigFieldSpec, SeedLockDocument, _ensure_sig_flags
)
from pyhanko.sign.timestamps import TimeStamper
from pyhanko.sign.general import (
simple_cms_attribute, CertificateStore,
SimpleCertificateStore, SigningError, optimal_pss_params,
load_certs_from_pemder, load_cert_from_pemder,
_process_pss_params, load_private_key_from_pemder,
_translate_pyca_cryptography_key_to_asn1,
_translate_pyca_cryptography_cert_to_asn1,
)
from pyhanko.stamp import (
TextStampStyle, TextStamp, STAMP_ART_CONTENT,
QRStampStyle, QRStamp,
)
__all__ = [
'PdfSignatureMetadata',
'Signer', 'SimpleSigner', 'PdfTimeStamper', 'PdfSigner',
'PdfCMSEmbedder', 'SigObjSetup', 'SigAppearanceSetup', 'SigMDPSetup',
'PdfByteRangeDigest', 'PdfSignedData',
'SignatureObject', 'DocumentTimestamp',
'SigIOSetup', 'sign_pdf', 'load_certs_from_pemder',
'DEFAULT_MD', 'DEFAULT_SIGNING_STAMP_STYLE', 'DEFAULT_SIG_SUBFILTER'
]
logger = logging.getLogger(__name__)
class SigByteRangeObject(generic.PdfObject):
def __init__(self):
self._filled = False
self._range_object_offset = None
self.first_region_len = 0
self.second_region_offset = 0
self.second_region_len = 0
def fill_offsets(self, stream, sig_start, sig_end, eof):
if self._filled:
raise ValueError('Offsets already filled') # pragma: nocover
if self._range_object_offset is None:
raise ValueError(
'Could not determine where to write /ByteRange value'
) # pragma: nocover
old_seek = stream.tell()
self.first_region_len = sig_start
self.second_region_offset = sig_end
self.second_region_len = eof - sig_end
# our ArrayObject is rigged to have fixed width
# so we can just write over it
stream.seek(self._range_object_offset)
self.write_to_stream(stream, None)
stream.seek(old_seek)
self._filled = True
def write_to_stream(self, stream, handler=None, container_ref=None):
if self._range_object_offset is None:
self._range_object_offset = stream.tell()
string_repr = "[ %08d %08d %08d %08d ]" % (
0, self.first_region_len,
self.second_region_offset, self.second_region_len,
)
stream.write(string_repr.encode('ascii'))
class DERPlaceholder(generic.PdfObject):
def __init__(self, bytes_reserved=None):
self._placeholder = True
self.value = b'0' * (bytes_reserved or 16 * 1024)
self._offsets = None
@property
def offsets(self):
if self._offsets is None:
raise ValueError('No offsets available') # pragma: nocover
return self._offsets
# always ignore encryption key, since this is a placeholder
def write_to_stream(self, stream, handler=None, container_ref=None):
start = stream.tell()
stream.write(b'<')
stream.write(self.value)
stream.write(b'>')
end = stream.tell()
if self._offsets is None:
self._offsets = start, end
DEFAULT_SIG_SUBFILTER = SigSeedSubFilter.ADOBE_PKCS7_DETACHED
class PdfByteRangeDigest(generic.DictionaryObject):
def __init__(self, data_key=pdf_name('/Contents'), *, bytes_reserved=None):
super().__init__()
if bytes_reserved is not None and bytes_reserved % 2 == 1:
raise ValueError('bytes_reserved must be even')
self.data_key = data_key
contents = DERPlaceholder(bytes_reserved=bytes_reserved)
self[data_key] = self.contents = contents
byte_range = SigByteRangeObject()
self[pdf_name('/ByteRange')] = self.byte_range = byte_range
def fill(self, writer: BasePdfFileWriter, md_algorithm,
in_place=False, output=None, chunk_size=4096):
"""
Generator coroutine that handles the document hash computation and
the actual filling of the placeholder data.
This is internal API; you should use use :class:`.PdfSigner`
wherever possible. If you *really* need fine-grained control,
use :class:`.PdfCMSEmbedder` instead.
"""
if in_place:
if not isinstance(writer, IncrementalPdfFileWriter):
raise TypeError(
"in_place is only meaningful for incremental writers."
) # pragma: nocover
output = writer.prev.stream
writer.write_in_place()
else:
output = misc.prepare_rw_output_stream(output)
writer.write(output)
# retcon time: write the proper values of the /ByteRange entry
# in the signature object
eof = output.tell()
sig_start, sig_end = self.contents.offsets
self.byte_range.fill_offsets(output, sig_start, sig_end, eof)
# compute the digests
md = getattr(hashlib, md_algorithm)()
# attempt to get a memoryview for automatic buffering
output_buffer = None
if isinstance(output, BytesIO):
output_buffer = output.getbuffer()
else:
try:
output_buffer = memoryview(output)
except (TypeError, IOError):
pass
if output_buffer is not None:
# these are memoryviews, so slices should not copy stuff around
md.update(output_buffer[:sig_start])
md.update(output_buffer[sig_end:eof])
output_buffer.release()
else:
temp_buffer = bytearray(chunk_size)
output.seek(0)
misc.chunked_digest(temp_buffer, output, md, max_read=sig_start)
output.seek(sig_end)
misc.chunked_digest(temp_buffer, output, md, max_read=eof-sig_end)
digest_value = md.digest()
cms_data = yield digest_value
if isinstance(cms_data, bytes):
der_bytes = cms_data
else:
der_bytes = cms_data.dump()
cms_hex = binascii.hexlify(der_bytes).upper()
# might as well compute this
bytes_reserved = sig_end - sig_start - 2
length = len(cms_hex)
if length > bytes_reserved:
raise SigningError(
f"Final CMS buffer larger than expected: "
f"allocated {bytes_reserved} bytes, but CMS required "
f"{length} bytes."
) # pragma: nocover
# +1 to skip the '<'
output.seek(sig_start + 1)
# NOTE: the PDF spec is not completely clear on this, but
# signature contents are NOT supposed to be encrypted.
# Perhaps this falls under the "strings in encrypted containers"
# denominator in § 7.6.1?
# Addition: the PDF 2.0 spec *does* spell out that this content
# is not to be encrypted.
output.write(cms_hex)
output.seek(0)
padding = bytes(bytes_reserved // 2 - len(der_bytes))
yield output, der_bytes + padding
class PdfSignedData(PdfByteRangeDigest):
"""
Generic class to model signature dictionaries in a PDF file.
See also :class:`.SignatureObject` and :class:`.DocumentTimestamp`.
:param obj_type:
The type of signature object.
:param subfilter:
See :class:`.SigSeedSubFilter`.
:param timestamp:
The timestamp to embed into the ``/M`` entry.
:param bytes_reserved:
The number of bytes to reserve for the signature.
Defaults to 16 KiB.
.. warning::
Since the CMS object is written to the output file as a hexadecimal
string, you should request **twice** the (estimated) number of bytes
in the DER-encoded version of the CMS object.
"""
def __init__(self, obj_type,
subfilter: SigSeedSubFilter = DEFAULT_SIG_SUBFILTER,
timestamp: datetime = None, bytes_reserved=None):
super().__init__(bytes_reserved=bytes_reserved)
self.update({
pdf_name('/Type'): obj_type,
pdf_name('/Filter'): pdf_name('/Adobe.PPKLite'),
pdf_name('/SubFilter'): subfilter.value,
})
if timestamp is not None:
self[pdf_name('/M')] = pdf_date(timestamp)
class SignatureObject(PdfSignedData):
"""
Class modelling a (placeholder for) a regular PDF signature.
:param timestamp:
The (optional) timestamp to embed into the ``/M`` entry.
:param subfilter:
See :class:`.SigSeedSubFilter`.
:param bytes_reserved:
The number of bytes to reserve for the signature.
Defaults to 16 KiB.
.. warning::
Since the CMS object is written to the output file as a hexadecimal
string, you should request **twice** the (estimated) number of bytes
in the DER-encoded version of the CMS object.
:param name:
Signer name. You probably want to leave this blank, viewers should
default to the signer's subject name.
:param location:
Optional signing location.
:param reason:
Optional signing reason. May be restricted by seed values.
"""
def __init__(self, timestamp: Optional[datetime] = None,
subfilter: SigSeedSubFilter = DEFAULT_SIG_SUBFILTER,
name=None, location=None, reason=None, bytes_reserved=None):
super().__init__(
obj_type=pdf_name('/Sig'), subfilter=subfilter,
timestamp=timestamp, bytes_reserved=bytes_reserved
)
if name:
self[pdf_name('/Name')] = pdf_string(name)
if location:
self[pdf_name('/Location')] = pdf_string(location)
if reason:
self[pdf_name('/Reason')] = pdf_string(reason)
class DocumentTimestamp(PdfSignedData):
"""
Class modelling a (placeholder for) a regular PDF signature.
:param bytes_reserved:
The number of bytes to reserve for the signature.
Defaults to 16 KiB.
.. warning::
Since the CMS object is written to the output file as a hexadecimal
string, you should request **twice** the (estimated) number of bytes
in the DER-encoded version of the CMS object.
"""
def __init__(self, bytes_reserved=None):
super().__init__(
obj_type=pdf_name('/DocTimeStamp'),
subfilter=SigSeedSubFilter.ETSI_RFC3161,
bytes_reserved=bytes_reserved
)
# use of Name/Location/Reason is discouraged in document timestamps by
# PAdES, so we don't set those
class Signer:
"""
Abstract signer object that is agnostic as to where the cryptographic
operations actually happen.
As of now, pyHanko provides two implementations:
* :class:`.SimpleSigner` implements the easy case where all the key material
can be loaded into memory.
* :class:`~.pkcs11.PKCS11Signer` implements a signer that is capable of
interfacing with a PKCS11 device (see also :class:`~.beid.BEIDSigner`).
"""
signing_cert: x509.Certificate
"""
The certificate that will be used to create the signature.
"""
cert_registry: CertificateStore
"""
Collection of certificates associated with this signer.
Note that this is simply a bookkeeping tool; in particular it doesn't care
about trust.
"""
signature_mechanism: SignedDigestAlgorithm = None
"""
The (cryptographic) signature mechanism to use.
"""
def __init__(self, prefer_pss=False):
self.prefer_pss = prefer_pss
# TODO I guess that in theory, passing digest_algorithm should never
# be necessary. Should review the ASN.1 syntax for certificates once more.
def get_signature_mechanism(self, digest_algorithm):
"""
Get the signature mechanism for this signer to use.
If :attr:`signature_mechanism` is set, it will be used.
Otherwise, this method will attempt to put together a default
based on mechanism used in the signer's certificate.
:param digest_algorithm:
Digest algorithm to use as part of the signature mechanism.
Only used if a signature mechanism object has to be put together
on-the-fly, and the digest algorithm could not be inferred from
the signer's certificate.
:return:
A :class:`.SignedDigestAlgorithm` object.
"""
if self.signature_mechanism is not None:
return self.signature_mechanism
if self.signing_cert is None:
raise SigningError(
"Could not set up a default signature mechanism."
) # pragma: nocover
# Grab the certificate's algorithm (but forget about the digest)
# and use that to set up the default.
# We'll specify the digest somewhere else.
algo = self.signing_cert.public_key.algorithm
params = None
if algo == 'ec':
mech = 'ecdsa'
elif algo == 'rsa':
if self.prefer_pss:
mech = 'rsassa_pss'
params = optimal_pss_params(
self.signing_cert, digest_algorithm
)
else:
mech = 'rsassa_pkcs1v15'
else: # pragma: nocover
raise SigningError(
f"Signature mechanism {algo} is unsupported."
)
sda_kwargs = {'algorithm': mech}
if params is not None:
sda_kwargs['parameters'] = params
return SignedDigestAlgorithm(sda_kwargs)
def sign_raw(self, data: bytes, digest_algorithm: str, dry_run=False) \
-> bytes:
"""
Compute the raw cryptographic signature of the data provided, hashed
using the digest algorithm provided.
:param data:
Data to sign.
:param digest_algorithm:
Digest algorithm to use.
.. warning::
If :attr:`signature_mechanism` also specifies a digest, they
should match.
:param dry_run:
Do not actually create a signature, but merely output placeholder
bytes that would suffice to contain an actual signature.
:return:
Signature bytes.
"""
raise NotImplementedError
@property
def subject_name(self):
"""
:return:
The subject's common name as a string, extracted from
:attr:`signing_cert`.
"""
name: x509.Name = self.signing_cert.subject
result = name.native['common_name']
try:
email = name.native['email_address']
result = '%s <%s>' % (result, email)
except KeyError:
pass
return result
@staticmethod
def format_revinfo(ocsp_responses: list = None, crls: list = None):
"""
Format Adobe-style revocation information for inclusion into a CMS
object.
:param ocsp_responses:
A list of OCSP responses to include.
:param crls:
A list of CRLs to include.
:return:
A CMS attribute containing the relevant data.
"""
revinfo_dict = {}
if ocsp_responses:
revinfo_dict['ocsp'] = ocsp_responses
if crls:
revinfo_dict['crl'] = crls
if revinfo_dict:
revinfo = asn1_pdf.RevocationInfoArchival(revinfo_dict)
return simple_cms_attribute(
'adobe_revocation_info_archival', revinfo
)
def signed_attrs(self, data_digest: bytes, digest_algorithm: str,
timestamp: datetime = None,
revocation_info=None, use_pades=False,
cades_meta: CAdESSignedAttrSpec=None,
timestamper=None, dry_run=False):
"""
.. versionchanged:: 0.4.0
Added positional ``digest_algorithm`` parameter _(breaking change)_.
.. versionchanged:: 0.5.0
Added ``dry_run``, ``timestamper`` and ``cades_meta`` parameters.
Format the signed attributes for a CMS signature.
:param data_digest:
Raw digest of the data to be signed.
:param digest_algorithm:
.. versionadded:: 0.4.0
Name of the digest algorithm used to compute the digest.
:param timestamp:
Current timestamp (ignored when ``use_pades`` is ``True``).
:param revocation_info:
Revocation information to embed; this should be the output
of a call to :meth:`.Signer.format_revinfo` or ``None``
(ignored when ``use_pades`` is ``True``).
:param use_pades:
Respect PAdES requirements.
:param dry_run:
.. versionadded:: 0.5.0
Flag indicating "dry run" mode. If ``True``, only the approximate
size of the output matters, so cryptographic
operations can be replaced by placeholders.
:param timestamper:
.. versionadded:: 0.5.0
Timestamper to use when creating timestamp tokens.
:param cades_meta:
.. versionadded:: 0.5.0
Specification for CAdES-specific attributes.
:return:
An :class:`.asn1crypto.cms.CMSAttributes` object.
"""
attrs = [
simple_cms_attribute('content_type', 'data'),
simple_cms_attribute('message_digest', data_digest),
# required by PAdES
simple_cms_attribute(
'signing_certificate',
general.as_signing_certificate(self.signing_cert)
)
]
# the following attributes are only meaningful in non-PAdES signatures
# (i.e. old school PKCS7 with Adobe-style revocation info)
if not use_pades:
if timestamp is not None:
# NOTE: PAdES actually forbids this!
st = simple_cms_attribute(
'signing_time',
cms.Time({'utc_time': core.UTCTime(timestamp)})
)
attrs.append(st)
# this is not allowed under PAdES, should use DSS instead
if revocation_info:
attrs.append(revocation_info)
# TODO not sure if PAdES allows this, need to check.
# It *should*, but perhaps the version of CMS it is based on is too
# old, or it might not allow undefined signed attributes.
# In the meantime, we only add this attribute to non-PAdES sigs
algid_protection = cms.CMSAlgorithmProtection({
'digest_algorithm': algos.DigestAlgorithm(
{'algorithm': digest_algorithm}
),
'signature_algorithm':
self.get_signature_mechanism(digest_algorithm)
})
attrs.append(
simple_cms_attribute(
'cms_algorithm_protection', algid_protection
)
)
# apply CAdES-specific attributes regardless of use_pades
if cades_meta is not None:
cades_attrs = cades_meta.extra_signed_attributes(
data_digest, digest_algorithm, timestamper=timestamper,
dry_run=dry_run
)
attrs.extend(cades_attrs)
return cms.CMSAttributes(attrs)
def unsigned_attrs(self, digest_algorithm, signature: bytes,
timestamper=None, dry_run=False) \
-> Optional[cms.CMSAttributes]:
"""
Compute the unsigned attributes to embed into the CMS object.
This function is called after signing the hash of the signed attributes
(see :meth:`signed_attrs`).
By default, this method only handles timestamp requests, but other
functionality may be added by subclasses
If this method returns ``None``, no unsigned attributes will be
embedded.
:param digest_algorithm:
Digest algorithm used to hash the signed attributes.
:param signature:
Signature of the signed attribute hash.
:param timestamper:
Timestamp supplier to use.
:param dry_run:
Flag indicating "dry run" mode. If ``True``, only the approximate
size of the output matters, so cryptographic
operations can be replaced by placeholders.
:return:
The unsigned attributes to add, or ``None``.
"""
if timestamper is not None:
# the timestamp server needs to cross-sign our signature
md = getattr(hashlib, digest_algorithm)()
md.update(signature)
if dry_run:
ts_token = timestamper.dummy_response(digest_algorithm)
else:
ts_token = timestamper.timestamp(
md.digest(), digest_algorithm
)
return cms.CMSAttributes(
[simple_cms_attribute('signature_time_stamp_token', ts_token)]
)
def signer_info(self, digest_algorithm: str, signed_attrs, signature):
"""
Format the ``SignerInfo`` entry for a CMS signature.
:param digest_algorithm:
Digest algorithm to use.
:param signed_attrs:
Signed attributes (see :meth:`signed_attrs`).
:param signature:
The raw signature to embed (see :meth:`sign_raw`).
:return:
An :class:`.asn1crypto.cms.SignerInfo` object.
"""
digest_algorithm_obj = algos.DigestAlgorithm(
{'algorithm': digest_algorithm}
)
signing_cert = self.signing_cert
# build the signer info object that goes into the PKCS7 signature
# (see RFC 2315 § 9.2)
sig_info = cms.SignerInfo({
'version': 'v1',
'sid': cms.SignerIdentifier({
'issuer_and_serial_number': cms.IssuerAndSerialNumber({
'issuer': signing_cert.issuer,
'serial_number': signing_cert.serial_number,
})
}),
'digest_algorithm': digest_algorithm_obj,
'signature_algorithm': self.get_signature_mechanism(
digest_algorithm
),
'signed_attrs': signed_attrs,
'signature': signature
})
return sig_info
def sign(self, data_digest: bytes, digest_algorithm: str,
timestamp: datetime = None, dry_run=False,
revocation_info=None, use_pades=False, timestamper=None,
cades_signed_attr_meta: CAdESSignedAttrSpec = None) \
-> cms.ContentInfo:
"""
Produce a detached CMS signature from a raw data digest.
:param data_digest:
Digest of the actual content being signed.
:param digest_algorithm:
Digest algorithm to use. This should be the same digest method
as the one used to hash the (external) content.
:param timestamp:
Current timestamp (ignored when ``use_pades`` is ``True``).
:param dry_run:
If ``True``, the actual signing step will be replaced with
a placeholder.
In a PDF signing context, this is necessary to estimate the size
of the signature container before computing the actual digest of
the document.
:param revocation_info:
Revocation information to embed; this should be the output
of a call to :meth:`.Signer.format_revinfo`
(ignored when ``use_pades`` is ``True``).
:param use_pades:
Respect PAdES requirements.
:param timestamper:
:class:`~.timestamps.TimeStamper` used to obtain a trusted timestamp
token that can be embedded into the signature container.
.. note::
If ``dry_run`` is true, the timestamper's
:meth:`~.timestamps.TimeStamper.dummy_response` method will be
called to obtain a placeholder token.
Note that with a standard :class:`~.timestamps.HTTPTimeStamper`,
this might still hit the timestamping server (in order to
produce a realistic size estimate), but the dummy response will
be cached.
:param cades_signed_attr_meta:
.. versionadded:: 0.5.0
Specification for CAdES-specific attributes.
:return:
An :class:`~.asn1crypto.cms.ContentInfo` object.
"""
digest_algorithm = digest_algorithm.lower()
# the piece of data we'll actually sign is a DER-encoded version of the
# signed attributes of our message
signed_attrs = self.signed_attrs(
data_digest, digest_algorithm, timestamp,
revocation_info=revocation_info, use_pades=use_pades,
timestamper=timestamper, cades_meta=cades_signed_attr_meta,
dry_run=dry_run
)
digest_algorithm_obj = algos.DigestAlgorithm(
{'algorithm': digest_algorithm}
)
implied_hash_algo = None
try:
if self.signature_mechanism is not None:
implied_hash_algo = self.signature_mechanism.hash_algo
except ValueError:
# this is OK, just use the specified message digest
pass
if implied_hash_algo is not None \
and implied_hash_algo != digest_algorithm:
raise SigningError(
f"Selected signature mechanism specifies message digest "
f"{implied_hash_algo}, but {digest_algorithm} "
f"was requested."
)
signature = self.sign_raw(
signed_attrs.dump(), digest_algorithm.lower(), dry_run
)
sig_info = self.signer_info(digest_algorithm, signed_attrs, signature)
unsigned_attrs = self.unsigned_attrs(
digest_algorithm, signature, timestamper=timestamper,
dry_run=dry_run
)
if unsigned_attrs is not None:
sig_info['unsigned_attrs'] = unsigned_attrs
# do not add the TS certs at this point
certs = set(self.cert_registry)
certs.add(self.signing_cert)
# this is the SignedData object for our message (see RFC 2315 § 9.1)
signed_data = {
'version': 'v1',
'digest_algorithms': cms.DigestAlgorithms((digest_algorithm_obj,)),
'encap_content_info': {'content_type': 'data'},
'certificates': certs,
'signer_infos': [sig_info]
}
# time to pack up
return cms.ContentInfo({
'content_type': cms.ContentType('signed_data'),
'content': cms.SignedData(signed_data)
})
# TODO I've encountered TSAs that will spew invalid timestamps when presented
# with a sha512 req (Adobe Reader agrees).
# Should get to the bottom of that. In the meantime, default to sha256
DEFAULT_MD = 'sha256'
"""
Default message digest algorithm used when computing digests for use in
signatures.
"""
DEFAULT_SIGNER_KEY_USAGE = {"non_repudiation"}
"""
Default key usage bits required for the signer's certificate.
"""
@dataclass(frozen=True)
class PdfSignatureMetadata:
"""
Specification for a PDF signature.
"""
field_name: str = None
"""
The name of the form field to contain the signature.
If there is only one available signature field, the name may be inferred.
"""
md_algorithm: str = None
"""
The name of the digest algorithm to use.
It should be supported by :mod:`hashlib`.
If ``None``, this will ordinarily default to the value of
:const:`.DEFAULT_MD`, unless a seed value dictionary and/or a prior
certification signature happen to be available.
"""
location: str = None
"""
Location of signing.
"""
reason: str = None
"""
Reason for signing (textual).
"""
name: str = None
"""
Name of the signer. This value is usually not necessary to set, since
it should appear on the signer's certificate, but there are cases
where it might be useful to specify it here (e.g. in situations where
signing is delegated to a trusted third party).
"""
certify: bool = False
"""
Sign with an author (certification) signature, as opposed to an approval
signature. A document can contain at most one such signature, and it must
be the first one.
"""
# TODO Does this restriction also apply to prior document timestamps?
subfilter: SigSeedSubFilter = None
"""
Signature subfilter to use.
This should be one of
:attr:`~.fields.SigSeedSubFilter.ADOBE_PKCS7_DETACHED` or
:attr:`~.fields.SigSeedSubFilter.PADES`.
If not specified, the value may be inferred from the signature field's
seed value dictionary. Failing that,
:attr:`~.fields.SigSeedSubFilter.ADOBE_PKCS7_DETACHED` is used as the
default value.
"""
embed_validation_info: bool = False
"""
Flag indicating whether validation info (OCSP responses and/or CRLs)
should be embedded or not. This is necessary to be able to validate
signatures long after they have been made.
This flag requires :attr:`validation_context` to be set.
The precise manner in which the validation info is embedded depends on
the (effective) value of :attr:`subfilter`:
* With :attr:`~.fields.SigSeedSubFilter.ADOBE_PKCS7_DETACHED`, the
validation information will be embedded inside the CMS object containing
the signature.
* With :attr:`~.fields.SigSeedSubFilter.PADES`, the validation information
will be embedded into the document security store (DSS).
"""
use_pades_lta: bool = False
"""
If ``True``, the signer will append an additional document timestamp after
writing the signature's validation information to the document security
store (DSS).
This flag is only meaningful if :attr:`subfilter` is
:attr:`~.fields.SigSeedSubFilter.PADES`.
The PAdES B-LTA profile solves the long-term validation problem by
adding a timestamp chain to the document after the regular signatures, which
is updated with new timestamps at regular intervals.
This provides an audit trail that ensures the long-term integrity of the
validation information in the DSS, since OCSP responses and CRLs also have
a finite lifetime.
See also :meth:`.PdfTimeStamper.update_archival_timestamp_chain`.
"""
timestamp_field_name: str = None
"""
Name of the timestamp field created when :attr:`use_pades_lta` is ``True``.
If not specified, a unique name will be generated using :mod:`uuid`.
"""
validation_context: ValidationContext = None
"""
The validation context to use when validating signatures.
If provided, the signer's certificate and any timestamp certificates
will be validated before signing.
This parameter is mandatory when :attr:`embed_validation_info` is ``True``.
"""
docmdp_permissions: MDPPerm = MDPPerm.FILL_FORMS
"""
Indicates the document modification policy that will be in force after
this signature is created. Only relevant for certification signatures
or signatures that apply locking.
.. warning::
For non-certification signatures, this is only explicitly allowed since
PDF 2.0 (ISO 32000-2), so older software may not respect this setting
on approval signatures.
"""
signer_key_usage: Set[str] = field(
default_factory=lambda: DEFAULT_SIGNER_KEY_USAGE
)
"""
Key usage extensions required for the signer's certificate.
Defaults to ``non_repudiation`` only, but sometimes ``digital_signature``
or a combination of both may be more appropriate.
See :class:`x509.KeyUsage` for a complete list.
Only relevant if a validation context is also provided.
"""
cades_signed_attr_spec: Optional[CAdESSignedAttrSpec] = None
"""
.. versionadded:: 0.5.0
Specification for CAdES-specific attributes.
"""
class SimpleSigner(Signer):
"""
Simple signer implementation where the key material is available in local
memory.
"""
signing_key: keys.PrivateKeyInfo
"""
Private key associated with the certificate in :attr:`signing_cert`.
"""
def __init__(self, signing_cert: x509.Certificate,
signing_key: keys.PrivateKeyInfo,
cert_registry: CertificateStore,
signature_mechanism: SignedDigestAlgorithm = None,
prefer_pss=False):
self.signing_cert = signing_cert
self.signing_key = signing_key
self.cert_registry = cert_registry
self.signature_mechanism = signature_mechanism
super().__init__(prefer_pss=prefer_pss)
def sign_raw(self, data: bytes, digest_algorithm: str, dry_run=False) \
-> bytes:
signature_mechanism = self.get_signature_mechanism(digest_algorithm)
mechanism = signature_mechanism.signature_algo
priv_key = serialization.load_der_private_key(
self.signing_key.dump(), password=None
)
if mechanism == 'rsassa_pkcs1v15':
padding = PKCS1v15()
hash_algo = getattr(hashes, digest_algorithm.upper())()
assert isinstance(priv_key, RSAPrivateKey)
return priv_key.sign(data, padding, hash_algo)
elif mechanism == 'rsassa_pss':
params = signature_mechanism['parameters']
padding, hash_algo = _process_pss_params(
params, digest_algorithm
)
assert isinstance(priv_key, RSAPrivateKey)
return priv_key.sign(data, padding, hash_algo)
elif mechanism == 'ecdsa':
hash_algo = getattr(hashes, digest_algorithm.upper())()
assert isinstance(priv_key, EllipticCurvePrivateKey)
return priv_key.sign(data, signature_algorithm=ECDSA(hash_algo))
else: # pragma: nocover
raise SigningError(
f"The signature mechanism {mechanism} "
"is unsupported by this signer."
)
@classmethod
def _load_ca_chain(cls, ca_chain_files=None):
try:
return set(load_certs_from_pemder(ca_chain_files))
except (IOError, ValueError) as e: # pragma: nocover
logger.error('Could not load CA chain', exc_info=e)
return None
@classmethod
def load_pkcs12(cls, pfx_file, ca_chain_files=None, passphrase=None,
signature_mechanism=None, prefer_pss=False):
"""
Load certificates and key material from a PCKS#12 archive
(usually ``.pfx`` or ``.p12`` files).
:param pfx_file:
Path to the PKCS#12 archive.
:param ca_chain_files:
Path to (PEM/DER) files containing other relevant certificates
not included in the PKCS#12 file.
:param passphrase:
Passphrase to decrypt the PKCS#12 archive, if required.
:param signature_mechanism: