-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
pubkey.py
1514 lines (1338 loc) · 51.4 KB
/
pubkey.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 abc
import enum
import logging
import re
import secrets
import struct
from dataclasses import dataclass
from hashlib import sha1, sha256
from typing import Dict, List, Optional, Set, Tuple, Union
from asn1crypto import algos, cms, core, x509
from asn1crypto.algos import RSAESOAEPParams
from asn1crypto.cms import KeyEncryptionAlgorithm, KeyEncryptionAlgorithmId
from asn1crypto.keys import PrivateKeyInfo, PublicKeyAlgorithm, PublicKeyInfo
from cryptography.hazmat.primitives import hashes, keywrap, serialization
from cryptography.hazmat.primitives.asymmetric.ec import (
ECDH,
EllipticCurvePrivateKey,
EllipticCurvePublicKey,
)
from cryptography.hazmat.primitives.asymmetric.ec import (
generate_private_key as generate_ec_private_key,
)
from cryptography.hazmat.primitives.asymmetric.padding import (
MGF1,
OAEP,
AsymmetricPadding,
PKCS1v15,
)
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPrivateKey,
RSAPublicKey,
)
from cryptography.hazmat.primitives.asymmetric.x448 import (
X448PrivateKey,
X448PublicKey,
)
from cryptography.hazmat.primitives.asymmetric.x25519 import (
X25519PrivateKey,
X25519PublicKey,
)
from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
from cryptography.hazmat.primitives.serialization import pkcs12
from .. import generic, misc
from ._util import aes_cbc_decrypt, aes_cbc_encrypt, as_signed, rc4_encrypt
from .api import (
ALL_PERMS,
AuthResult,
AuthStatus,
CryptFilter,
CryptFilterBuilder,
CryptFilterConfiguration,
IdentityCryptFilter,
SecurityHandler,
SecurityHandlerVersion,
build_crypt_filter,
)
from .cred_ser import SerialisableCredential, SerialisedCredential
from .filter_mixins import AESCryptFilterMixin, RC4CryptFilterMixin
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class RecipientEncryptionPolicy:
ignore_key_usage: bool = False
"""
Ignore key usage bits in the recipient's certificate.
"""
prefer_oaep: bool = False
"""
For RSA recipients, encrypt with RSAES-OAEP.
.. warning::
This is not widely supported.
"""
class PubKeyCryptFilter(CryptFilter, abc.ABC):
"""
Crypt filter for use with public key security handler.
These are a little more independent than their counterparts for
the standard security handlers, since different crypt filters
can cater to different sets of recipients.
:param recipients:
List of CMS objects encoding recipient information for this crypt
filters.
:param acts_as_default:
Indicates whether this filter is intended to be used in
``/StrF`` or ``/StmF``.
:param encrypt_metadata:
Whether this crypt filter should encrypt document-level metadata.
.. warning::
See :class:`.SecurityHandler` for some background on the
way pyHanko interprets this value.
"""
_handler: Optional['PubKeySecurityHandler'] = None
def __init__(
self,
*,
recipients=None,
acts_as_default=False,
encrypt_metadata=True,
**kwargs,
):
self.recipients = recipients
self.acts_as_default = acts_as_default
self.encrypt_metadata = encrypt_metadata
self._pubkey_auth_failed = False
self._shared_key = self._recp_key_seed = None
super().__init__(**kwargs)
@property
def _auth_failed(self) -> bool:
return self._pubkey_auth_failed
def _set_security_handler(self, handler):
if not isinstance(handler, PubKeySecurityHandler):
raise TypeError # pragma: nocover
super()._set_security_handler(handler)
self._shared_key = self._recp_key_seed = None
def add_recipients(
self,
certs: List[x509.Certificate],
policy: RecipientEncryptionPolicy,
perms=ALL_PERMS,
):
"""
Add recipients to this crypt filter.
This always adds one full CMS object to the Recipients array
:param certs:
A list of recipient certificates.
:param policy:
Encryption policy choices for the chosen set of recipients.
:param perms:
The permission bits to assign to the listed recipients.
"""
if not self.acts_as_default and self.recipients:
raise misc.PdfError(
"A non-default crypt filter cannot have multiple sets of "
"recipients."
)
if self.recipients is None:
# assume that this is a freshly created pubkey crypt filter,
# so set up the shared seed
self._recp_key_seed = secrets.token_bytes(20)
self.recipients = []
if self._shared_key is not None or self._recp_key_seed is None:
raise misc.PdfError(
"Adding recipients after deriving the shared key or "
"before authenticating is not possible."
)
new_cms = construct_recipient_cms(
certs,
self._recp_key_seed,
as_signed(perms),
policy=policy,
include_permissions=self.acts_as_default,
)
self.recipients.append(new_cms)
def authenticate(self, credential) -> AuthResult:
"""
Authenticate to this crypt filter in particular.
If used in ``/StmF`` or ``/StrF``, you don't need to worry about
calling this method directly.
:param credential:
The :class:`.EnvelopeKeyDecrypter` to authenticate with.
:return:
An :class:`AuthResult` object indicating the level of access
obtained.
"""
for recp in self.recipients:
seed, perms = read_seed_from_recipient_cms(recp, credential)
if seed is not None:
self._recp_key_seed = seed
return AuthResult(AuthStatus.USER, perms)
return AuthResult(AuthStatus.FAILED)
def derive_shared_encryption_key(self) -> bytes:
assert self._handler is not None
if self._recp_key_seed is None:
raise misc.PdfError("No seed available; authenticate first.")
if self._handler.version >= SecurityHandlerVersion.AES256:
md = sha256()
else:
md = sha1()
md.update(self._recp_key_seed)
for recp in self.recipients:
md.update(recp.dump())
if not self.encrypt_metadata and self.acts_as_default:
md.update(b'\xff\xff\xff\xff')
return md.digest()[: self.keylen]
def as_pdf_object(self):
result = super().as_pdf_object()
result['/Length'] = generic.NumberObject(self.keylen * 8)
recipients = generic.ArrayObject(
generic.ByteStringObject(recp.dump()) for recp in self.recipients
)
if self.acts_as_default:
result['/Recipients'] = recipients
else:
# non-default crypt filters can only have one recipient object
result['/Recipients'] = recipients[0]
result['/EncryptMetadata'] = generic.BooleanObject(
self.encrypt_metadata
)
return result
class PubKeyAESCryptFilter(PubKeyCryptFilter, AESCryptFilterMixin):
"""
AES crypt filter for public key security handlers.
"""
pass
class PubKeyRC4CryptFilter(PubKeyCryptFilter, RC4CryptFilterMixin):
"""
RC4 crypt filter for public key security handlers.
"""
pass
"""
Default name to use for the default crypt filter in the standard security
handler.
"""
DEFAULT_CRYPT_FILTER = generic.NameObject('/DefaultCryptFilter')
"""
Default name to use for the default crypt filter in public key security
handlers.
"""
DEF_EMBEDDED_FILE = generic.NameObject('/DefEmbeddedFile')
"""
Default name to use for the EFF crypt filter in public key security
handlers for documents where only embedded files are encrypted.
"""
"""
Name of the identity crypt filter.
"""
def _pubkey_rc4_config(keylen, recipients=None, encrypt_metadata=True):
return CryptFilterConfiguration(
{
DEFAULT_CRYPT_FILTER: PubKeyRC4CryptFilter(
keylen=keylen,
acts_as_default=True,
recipients=recipients,
encrypt_metadata=encrypt_metadata,
)
},
default_stream_filter=DEFAULT_CRYPT_FILTER,
default_string_filter=DEFAULT_CRYPT_FILTER,
)
def _pubkey_aes_config(keylen, recipients=None, encrypt_metadata=True):
return CryptFilterConfiguration(
{
DEFAULT_CRYPT_FILTER: PubKeyAESCryptFilter(
keylen=keylen,
acts_as_default=True,
recipients=recipients,
encrypt_metadata=encrypt_metadata,
)
},
default_stream_filter=DEFAULT_CRYPT_FILTER,
default_string_filter=DEFAULT_CRYPT_FILTER,
)
"""
Type alias for a callable that produces a crypt filter from a dictionary.
"""
@enum.unique
class PubKeyAdbeSubFilter(enum.Enum):
"""
Enum describing the different subfilters that can be used for public key
encryption in the PDF specification.
"""
S3 = generic.NameObject('/adbe.pkcs7.s3')
S4 = generic.NameObject('/adbe.pkcs7.s4')
S5 = generic.NameObject('/adbe.pkcs7.s5')
def construct_envelope_content(
seed: bytes, perms: int, include_permissions=True
):
assert len(seed) == 20
return seed + (struct.pack('<i', perms) if include_permissions else b'')
def _rsaes_pkcs1v15_recipient(
pub_key_info: PublicKeyInfo,
rid: cms.RecipientIdentifier,
envelope_key: bytes,
):
padding = PKCS1v15()
algo = cms.KeyEncryptionAlgorithm(
{'algorithm': cms.KeyEncryptionAlgorithmId('rsaes_pkcs1v15')}
)
pub_key = serialization.load_der_public_key(pub_key_info.dump())
assert isinstance(pub_key, RSAPublicKey)
encrypted_data = pub_key.encrypt(envelope_key, padding=padding)
return _format_ktri(rid=rid, algo=algo, encrypted_data=encrypted_data)
def _rsaes_oaep_recipient(
pub_key_info: PublicKeyInfo,
rid: cms.RecipientIdentifier,
envelope_key: bytes,
):
# recycle these routines
from pyhanko.sign.general import get_pyca_cryptography_hash
from pyhanko.sign.signers.pdf_cms import select_suitable_signing_md
digest_function_name = select_suitable_signing_md(pub_key_info)
digest_spec = get_pyca_cryptography_hash(digest_function_name)
algo = cms.KeyEncryptionAlgorithm(
{
'algorithm': cms.KeyEncryptionAlgorithmId('rsaes_oaep'),
'parameters': RSAESOAEPParams(
{
'hash_algorithm': {'algorithm': digest_function_name},
'mask_gen_algorithm': {
'algorithm': 'mgf1',
'parameters': {'algorithm': digest_function_name},
},
}
),
}
)
padding = OAEP(mgf=MGF1(digest_spec), algorithm=digest_spec, label=None)
pub_key = serialization.load_der_public_key(pub_key_info.dump())
assert isinstance(pub_key, RSAPublicKey)
encrypted_data = pub_key.encrypt(envelope_key, padding=padding)
return _format_ktri(rid=rid, algo=algo, encrypted_data=encrypted_data)
def _format_ktri(
rid: cms.RecipientIdentifier,
algo: cms.KeyEncryptionAlgorithm,
encrypted_data: bytes,
):
return cms.RecipientInfo(
{
'ktri': cms.KeyTransRecipientInfo(
{
'version': 0,
'rid': rid,
'key_encryption_algorithm': algo,
'encrypted_key': encrypted_data,
}
)
}
)
def _choose_ecdh_settings(
pub_key_info: PublicKeyInfo,
) -> Tuple[
hashes.HashAlgorithm, KeyEncryptionAlgorithmId, KeyEncryptionAlgorithmId
]:
algo_name = pub_key_info.algorithm
if algo_name == 'ec':
approx_sec_level = pub_key_info.bit_size // 2
elif algo_name == 'x25519':
approx_sec_level = 128
else:
approx_sec_level = 256
# All of these are dhSinglePass-stdDH-sha*kdf
if approx_sec_level <= 128:
return (
hashes.SHA256(),
KeyEncryptionAlgorithmId('aes128_wrap'),
KeyEncryptionAlgorithmId('1.3.132.1.11.1'),
)
elif approx_sec_level <= 192:
return (
hashes.SHA384(),
KeyEncryptionAlgorithmId('aes192_wrap'),
KeyEncryptionAlgorithmId('1.3.132.1.11.2'),
)
else:
return (
hashes.SHA512(),
KeyEncryptionAlgorithmId('aes256_wrap'),
KeyEncryptionAlgorithmId('1.3.132.1.11.3'),
)
def _ecdh_recipient(
pub_key_info: PublicKeyInfo,
rid: cms.KeyAgreementRecipientIdentifier,
envelope_key: bytes,
):
# static-ephemeral ECDH (standard) with X9.63 key derivation
digest_spec, key_wrap_algo_id, key_exch_algo_id = _choose_ecdh_settings(
pub_key_info
)
key_wrap_algo = KeyEncryptionAlgorithm({'algorithm': key_wrap_algo_id})
pub_key = serialization.load_der_public_key(pub_key_info.dump())
originator_key: Union[
X25519PrivateKey, X448PrivateKey, EllipticCurvePrivateKey
]
if isinstance(pub_key, EllipticCurvePublicKey):
originator_key = generate_ec_private_key(pub_key.curve)
ecdh_value = originator_key.exchange(ECDH(), pub_key)
elif isinstance(pub_key, X25519PublicKey):
originator_key = X25519PrivateKey.generate()
ecdh_value = originator_key.exchange(pub_key)
elif isinstance(pub_key, X448PublicKey):
originator_key = X448PrivateKey.generate()
ecdh_value = originator_key.exchange(pub_key)
else:
raise NotImplementedError
originator_key_info = PublicKeyInfo.load(
originator_key.public_key().public_bytes(
serialization.Encoding.DER,
serialization.PublicFormat.SubjectPublicKeyInfo,
)
)
ukm = secrets.token_bytes(16)
kdf = _kdf_for_exchange(
kdf_digest=digest_spec,
key_wrap_algo=key_wrap_algo,
user_keying_material=ukm,
)
kek = kdf.derive(ecdh_value)
encrypted_data = keywrap.aes_key_wrap(
wrapping_key=kek, key_to_wrap=envelope_key
)
return _format_kari(
rid=rid,
originator_key=originator_key_info,
algo=cms.KeyEncryptionAlgorithm(
{
'algorithm': key_exch_algo_id,
'parameters': key_wrap_algo,
}
),
ukm=ukm,
encrypted_data=encrypted_data,
)
def _format_kari(
rid: cms.KeyAgreementRecipientIdentifier,
originator_key: PublicKeyInfo,
algo: cms.KeyEncryptionAlgorithm,
ukm: bytes,
encrypted_data: bytes,
):
return cms.RecipientInfo(
name='kari',
value=cms.KeyAgreeRecipientInfo(
{
'version': 3,
'originator': cms.OriginatorIdentifierOrKey(
name='originator_key', value=originator_key
),
'ukm': ukm,
'key_encryption_algorithm': algo,
'recipient_encrypted_keys': [
cms.RecipientEncryptedKey(
{'rid': rid, 'encrypted_key': encrypted_data}
)
],
}
),
)
def _recipient_info(
envelope_key: bytes,
cert: x509.Certificate,
policy: RecipientEncryptionPolicy,
):
pub_key_info = cert.public_key
pubkey_algo_info: PublicKeyAlgorithm = pub_key_info['algorithm']
algorithm_name = pubkey_algo_info['algorithm'].native
assert len(envelope_key) == 32
if not policy.ignore_key_usage:
# TODO for ECC: reject ECDSA-only keys
key_usage = cert.key_usage_value
if key_usage is None or 'key_encipherment' not in key_usage.native:
raise misc.PdfWriteError(
f"Certificate for subject {cert.subject.human_friendly} does "
f"not have the 'key_encipherment' key usage bit set."
)
# TODO support subjectKeyIdentifier here (requiring version 2)
iss_serial_rid = cms.IssuerAndSerialNumber(
{'issuer': cert.issuer, 'serial_number': cert.serial_number}
)
if algorithm_name == 'rsa':
rid = cms.RecipientIdentifier(
{'issuer_and_serial_number': iss_serial_rid}
)
if policy.prefer_oaep:
return _rsaes_pkcs1v15_recipient(pub_key_info, rid, envelope_key)
else:
return _rsaes_oaep_recipient(pub_key_info, rid, envelope_key)
elif algorithm_name in ('ec', 'x25519', 'x448'):
ka_rid = cms.KeyAgreementRecipientIdentifier(
{'issuer_and_serial_number': iss_serial_rid}
)
return _ecdh_recipient(pub_key_info, ka_rid, envelope_key)
else:
raise NotImplementedError(
f"Cannot encrypt for key type '{algorithm_name}'"
)
def construct_recipient_cms(
certificates: List[x509.Certificate],
seed: bytes,
perms: int,
policy: RecipientEncryptionPolicy,
include_permissions=True,
) -> cms.ContentInfo:
# The content of the generated ContentInfo object
# is an object of type EnvelopedData, containing a 20 byte seed (+ perms).
#
# This seed is shared among all recipients (including those occurring in
# other CMS objects, if relevant), and is the only secret part of the
# key derivation procedure used to obtain the file encryption key.
#
# The envelope content is then encrypted using an envelope key,
# which is in turn encrypted using the public key of each recipient and
# stored in a RecipientInfo object (more precisely, a
# KeyTransRecipientInfo object). PyHanko always uses AES-256 to encrypt
# the envelope content, even if the chosen PDF encryption is weaker.
#
# The RecipientInfo objects, algorithm specification and envelope content
# are then bundled into an EnvelopedData object.
envelope_content = construct_envelope_content(
seed, perms, include_permissions=include_permissions
)
# 256-bit key used to encrypt the envelope
envelope_key = secrets.token_bytes(32)
# encrypt the envelope content with the envelope key
iv, encrypted_envelope_content = aes_cbc_encrypt(
envelope_key, envelope_content, iv=None
)
# encrypt the envelope key for each recipient
rec_infos = [
_recipient_info(envelope_key, cert, policy=policy)
for cert in certificates
]
algo = cms.EncryptionAlgorithm(
{
'algorithm': algos.EncryptionAlgorithmId('aes256_cbc'),
'parameters': iv,
}
)
encrypted_content_info = cms.EncryptedContentInfo(
{
'content_type': cms.ContentType('data'),
'content_encryption_algorithm': algo,
'encrypted_content': encrypted_envelope_content,
}
)
# version 0 because no originatorInfo, no attribute certs
# and all recipientinfo structures have version 0 (and aren't pwri)
enveloped_data = cms.EnvelopedData(
{
'version': 0,
'recipient_infos': rec_infos,
'encrypted_content_info': encrypted_content_info,
}
)
# finally, package up the whole thing into a ContentInfo object
return cms.ContentInfo(
{
'content_type': cms.ContentType('enveloped_data'),
'content': enveloped_data,
}
)
class InappropriateCredentialError(TypeError):
pass
# TODO implement a PKCS#11 version of this interface
class EnvelopeKeyDecrypter:
"""
General credential class for use with public key security handlers.
This allows the key decryption process to happen offline, e.g. on a smart
card.
"""
@property
def cert(self) -> x509.Certificate:
"""
:return:
Return the recipient's certificate
"""
raise NotImplementedError
def decrypt(
self, encrypted_key: bytes, algo_params: cms.KeyEncryptionAlgorithm
) -> bytes:
"""
Invoke the actual key decryption algorithm.
Used with key transport.
:param encrypted_key:
Payload to decrypt.
:param algo_params:
Specification of the encryption algorithm as a CMS object.
:raises InappropriateCredentialError:
if the credential cannot be used for key transport.
:return:
The decrypted payload.
"""
raise NotImplementedError
def decrypt_with_exchange(
self,
encrypted_key: bytes,
algo_params: cms.KeyEncryptionAlgorithm,
originator_identifier: cms.OriginatorIdentifierOrKey,
user_keying_material: bytes,
) -> bytes:
"""
Decrypt an envelope key using a key derived from a key exchange.
:param encrypted_key:
Payload to decrypt.
:param algo_params:
Specification of the encryption algorithm as a CMS object.
:param originator_identifier:
Information about the originator necessary to complete the key
exchange.
:param user_keying_material:
The user keying material that will be used in the key derivation.
:return:
The decrypted payload.
"""
raise NotImplementedError
class _PrivKeyAndCert(core.Sequence):
_fields = [('key', PrivateKeyInfo), ('cert', x509.Certificate)]
class ECCCMSSharedInfo(core.Sequence):
_fields = [
('key_info', KeyEncryptionAlgorithm),
(
'entityUInfo',
core.OctetString,
{'explicit': 0, 'optional': True},
),
('suppPubInfo', core.OctetString, {'explicit': 2}),
]
AES_WRAP_PATTERN = re.compile(r'aes(\d+)_wrap(_pad)?')
def _kdf_for_exchange(
*,
kdf_digest: hashes.HashAlgorithm,
key_wrap_algo: cms.KeyEncryptionAlgorithm,
user_keying_material: Optional[bytes],
) -> KeyDerivationFunction:
key_wrap_algo_id: str = key_wrap_algo['algorithm'].native
wrap_match = AES_WRAP_PATTERN.fullmatch(key_wrap_algo_id)
if not wrap_match:
raise NotImplementedError(
f"{key_wrap_algo_id} is not a supported key wrapping algorithm"
)
kek_bit_len = int(wrap_match.group(1))
return X963KDF(
algorithm=kdf_digest,
length=kek_bit_len // 8,
sharedinfo=ECCCMSSharedInfo(
{
'key_info': key_wrap_algo,
'entityUInfo': user_keying_material,
'suppPubInfo': struct.pack('>I', kek_bit_len),
}
).dump(),
)
class SimpleEnvelopeKeyDecrypter(EnvelopeKeyDecrypter, SerialisableCredential):
"""
Implementation of :class:`.EnvelopeKeyDecrypter` where the private key
is an RSA or ECC key residing in memory.
:param cert:
The recipient's certificate.
:param private_key:
The recipient's private key.
"""
dhsinglepass_stddh_arc_pattern = re.compile(r'1\.3\.132\.1\.11\.(\d+)')
@classmethod
def get_name(cls) -> str:
return 'raw_privkey'
def _ser_value(self) -> bytes:
values = {'key': self.private_key, 'cert': self.cert}
return _PrivKeyAndCert(values).dump()
@classmethod
def _deser_value(cls, data: bytes):
try:
decoded = _PrivKeyAndCert.load(data)
key = decoded['key']
cert = decoded['cert']
except ValueError as e:
raise misc.PdfReadError(
"Failed to decode serialised pubkey credential"
) from e
return SimpleEnvelopeKeyDecrypter(cert=cert, private_key=key)
def __init__(self, cert: x509.Certificate, private_key: PrivateKeyInfo):
self.private_key: PrivateKeyInfo = private_key
self._cert = cert
@property
def cert(self) -> x509.Certificate:
return self._cert
@staticmethod
def load(key_file, cert_file, key_passphrase=None):
"""
Load a key decrypter using key material from files on disk.
:param key_file:
File containing the recipient's private key.
:param cert_file:
File containing the recipient's certificate.
:param key_passphrase:
Passphrase for the key file, if applicable.
:return:
An instance of :class:`.SimpleEnvelopeKeyDecrypter`.
"""
from ...keys import load_private_key_from_pemder
try:
private_key = load_private_key_from_pemder(
key_file, passphrase=key_passphrase
)
from ...keys import load_cert_from_pemder
cert = load_cert_from_pemder(cert_file)
except (IOError, ValueError, TypeError) as e: # pragma: nocover
logger.error('Could not load cryptographic material', exc_info=e)
return None
return SimpleEnvelopeKeyDecrypter(cert=cert, private_key=private_key)
@classmethod
def load_pkcs12(cls, pfx_file, passphrase=None):
"""
Load a key decrypter using key material from a PKCS#12 file on disk.
:param pfx_file:
Path to the PKCS#12 file containing the key material.
:param passphrase:
Passphrase for the private key, if applicable.
:return:
An instance of :class:`.SimpleEnvelopeKeyDecrypter`.
"""
try:
with open(pfx_file, 'rb') as f:
pfx_bytes = f.read()
(private_key, cert, other_certs) = pkcs12.load_key_and_certificates(
pfx_bytes, passphrase
)
from ...keys import (
_translate_pyca_cryptography_cert_to_asn1,
_translate_pyca_cryptography_key_to_asn1,
)
cert = _translate_pyca_cryptography_cert_to_asn1(cert)
private_key = _translate_pyca_cryptography_key_to_asn1(private_key)
except (IOError, ValueError, TypeError) as e: # pragma: nocover
logger.error(f'Could not open PKCS#12 file {pfx_file}.', exc_info=e)
return None
return SimpleEnvelopeKeyDecrypter(cert=cert, private_key=private_key)
def decrypt(
self, encrypted_key: bytes, algo_params: cms.KeyEncryptionAlgorithm
) -> bytes:
"""
Decrypt the payload using RSA with PKCS#1 v1.5 padding or OAEP.
Other schemes are not (currently) supported by this implementation.
:param encrypted_key:
Payload to decrypt.
:param algo_params:
Specification of the encryption algorithm as a CMS object.
Must use ``rsaes_pkcs1v15`` or ``rsaes_oaep``.
:return:
The decrypted payload.
"""
algo_name = algo_params['algorithm'].native
padding: AsymmetricPadding
if algo_name == 'rsaes_pkcs1v15':
padding = PKCS1v15()
elif algo_name == 'rsaes_oaep':
from pyhanko.sign.general import get_pyca_cryptography_hash
oaep_params: RSAESOAEPParams = algo_params['parameters']
mgf = oaep_params['mask_gen_algorithm']
mgf_name = mgf['algorithm'].native
if mgf_name != 'mgf1':
raise NotImplementedError(
f"Only MGF1 is implemented, but got '{mgf_name}'"
)
padding = OAEP(
mgf=MGF1(
algorithm=get_pyca_cryptography_hash(
mgf['parameters']['algorithm'].native
)
),
algorithm=get_pyca_cryptography_hash(
oaep_params['hash_algorithm']['algorithm'].native
),
label=None,
)
else:
raise NotImplementedError(
f"Only 'rsaes_pkcs1v15' and 'rsaes_oaep' are supported for "
f"envelope decryption, not '{algo_name}'."
)
priv_key = serialization.load_der_private_key(
self.private_key.dump(), password=None
)
if not isinstance(priv_key, RSAPrivateKey):
raise InappropriateCredentialError(
"The loaded key does not seem to be an RSA private key"
)
return priv_key.decrypt(encrypted_key, padding=padding)
def decrypt_with_exchange(
self,
encrypted_key: bytes,
algo_params: cms.KeyEncryptionAlgorithm,
originator_identifier: cms.OriginatorIdentifierOrKey,
user_keying_material: Optional[bytes],
) -> bytes:
"""
Decrypt the payload using a key agreed via ephemeral-static
standard (non-cofactor) ECDH with X9.63 key derivation.
Other schemes aer not supported at this time.
:param encrypted_key:
Payload to decrypt.
:param algo_params:
Specification of the encryption algorithm as a CMS object.
:param originator_identifier:
The originator info, which must be an EC key.
:param user_keying_material:
The user keying material that will be used in the key derivation.
:return:
The decrypted payload.
"""
# TODO get the relevant OIDs added to asn1crypto
oid = algo_params['algorithm']
match = self.dhsinglepass_stddh_arc_pattern.fullmatch(oid.dotted)
kdf_digest: Optional[hashes.HashAlgorithm] = None
if match:
kdf_digest = {
'0': hashes.SHA224(),
'1': hashes.SHA256(),
'2': hashes.SHA384(),
'3': hashes.SHA512(),
}.get(match.group(1), None)
if not kdf_digest:
raise NotImplementedError(
"Only dhSinglePass-stdDH algorithms from SEC 1 / RFC 5753 are "
"supported."
)
key_wrap_algo = cms.KeyEncryptionAlgorithm.load(
algo_params['parameters'].dump()
)
key_wrap_algo_id: str = key_wrap_algo['algorithm'].native
if not AES_WRAP_PATTERN.fullmatch(key_wrap_algo_id):
raise NotImplementedError(
f"{key_wrap_algo_id} is not a supported key wrapping algorithm"
)
unwrap_key = (
keywrap.aes_key_unwrap_with_padding
if key_wrap_algo_id.endswith('_pad')
else keywrap.aes_key_unwrap
)
kdf = _kdf_for_exchange(
kdf_digest=kdf_digest,
key_wrap_algo=key_wrap_algo,
user_keying_material=user_keying_material,
)
if originator_identifier.name != 'originator_key':
raise NotImplementedError("Only originator_key is supported")
originator_pub_key_info: PublicKeyInfo = (
originator_identifier.chosen.untag()
)
originator_pub_key = serialization.load_der_public_key(
originator_pub_key_info.dump()
)
priv_key = serialization.load_der_private_key(
self.private_key.dump(), password=None
)
mismatch_msg = (
"Originator's public key is not compatible "
"with selected private key"
)
if isinstance(priv_key, EllipticCurvePrivateKey):
# we could rely on pyca/cryptography to perform this check for us,
# but then mypy complains
if (
not isinstance(originator_pub_key, EllipticCurvePublicKey)
or originator_pub_key.curve.name != priv_key.curve.name
):
raise ValueError(mismatch_msg)
ecdh_value = priv_key.exchange(ECDH(), originator_pub_key)
elif isinstance(priv_key, X25519PrivateKey):
if not isinstance(originator_pub_key, X25519PublicKey):
raise ValueError(mismatch_msg)
ecdh_value = priv_key.exchange(originator_pub_key)
elif isinstance(priv_key, X448PrivateKey):
if not isinstance(originator_pub_key, X448PublicKey):
raise ValueError(mismatch_msg)
ecdh_value = priv_key.exchange(originator_pub_key)
else:
raise InappropriateCredentialError(
"The loaded key does not seem to be an EC private key"
)
derived_kek = kdf.derive(ecdh_value)
return unwrap_key(wrapping_key=derived_kek, wrapped_key=encrypted_key)
SerialisableCredential.register(SimpleEnvelopeKeyDecrypter)
def read_envelope_key(
ed: cms.EnvelopedData, decrypter: EnvelopeKeyDecrypter
) -> Optional[bytes]:
rec_info: cms.RecipientInfo
for rec_info in ed['recipient_infos']:
if rec_info.name == 'ktri':
ktri = rec_info.chosen
issuer_and_serial = ktri['rid'].chosen
if not isinstance(issuer_and_serial, cms.IssuerAndSerialNumber):
raise NotImplementedError(
"Recipient identifier must be of type IssuerAndSerialNumber."