/
packets.py
1625 lines (1252 loc) · 54.4 KB
/
packets.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
""" packet.py
"""
import abc
import binascii
import calendar
import copy
import hashlib
import os
import re
from datetime import datetime
import six
from cryptography.hazmat.primitives import constant_time
from cryptography.hazmat.primitives.asymmetric import padding
from .fields import DSAPriv, DSAPub, DSASignature
from .fields import ECDSAPub, ECDSAPriv, ECDSASignature
from .fields import ECDHPub, ECDHPriv, ECDHCipherText
from .fields import EdDSAPub, EdDSAPriv, EdDSASignature
from .fields import ElGCipherText, ElGPriv, ElGPub
from .fields import OpaquePubKey
from .fields import OpaquePrivKey
from .fields import OpaqueSignature
from .fields import RSACipherText, RSAPriv, RSAPub, RSASignature
from .fields import String2Key
from .fields import SubPackets
from .fields import UserAttributeSubPackets
from .types import Packet
from .types import Primary
from .types import Private
from .types import Public
from .types import Sub
from .types import VersionedPacket
from ..constants import CompressionAlgorithm
from ..constants import HashAlgorithm
from ..constants import PubKeyAlgorithm
from ..constants import SignatureType
from ..constants import SymmetricKeyAlgorithm
from ..constants import TrustFlags
from ..constants import TrustLevel
from ..decorators import sdproperty
from ..errors import PGPDecryptionError
from ..symenc import _decrypt
from ..symenc import _encrypt
from ..types import Fingerprint
__all__ = ['PKESessionKey',
'PKESessionKeyV3',
'Signature',
'SignatureV4',
'SKESessionKey',
'SKESessionKeyV4',
'OnePassSignature',
'OnePassSignatureV3',
'PrivKey',
'PubKey',
'PubKeyV4',
'PrivKeyV4',
'PrivSubKey',
'PrivSubKeyV4',
'CompressedData',
'SKEData',
'Marker',
'LiteralData',
'Trust',
'UserID',
'PubSubKey',
'PubSubKeyV4',
'UserAttribute',
'IntegrityProtectedSKEData',
'IntegrityProtectedSKEDataV1',
'MDC']
class PKESessionKey(VersionedPacket):
__typeid__ = 0x01
__ver__ = 0
@abc.abstractmethod
def decrypt_sk(self, pk):
raise NotImplementedError()
@abc.abstractmethod
def encrypt_sk(self, pk, symalg, symkey):
raise NotImplementedError()
class PKESessionKeyV3(PKESessionKey):
"""
5.1. Public-Key Encrypted Session Key Packets (Tag 1)
A Public-Key Encrypted Session Key packet holds the session key used
to encrypt a message. Zero or more Public-Key Encrypted Session Key
packets and/or Symmetric-Key Encrypted Session Key packets may
precede a Symmetrically Encrypted Data Packet, which holds an
encrypted message. The message is encrypted with the session key,
and the session key is itself encrypted and stored in the Encrypted
Session Key packet(s). The Symmetrically Encrypted Data Packet is
preceded by one Public-Key Encrypted Session Key packet for each
OpenPGP key to which the message is encrypted. The recipient of the
message finds a session key that is encrypted to their public key,
decrypts the session key, and then uses the session key to decrypt
the message.
The body of this packet consists of:
- A one-octet number giving the version number of the packet type.
The currently defined value for packet version is 3.
- An eight-octet number that gives the Key ID of the public key to
which the session key is encrypted. If the session key is
encrypted to a subkey, then the Key ID of this subkey is used
here instead of the Key ID of the primary key.
- A one-octet number giving the public-key algorithm used.
- A string of octets that is the encrypted session key. This
string takes up the remainder of the packet, and its contents are
dependent on the public-key algorithm used.
Algorithm Specific Fields for RSA encryption
- multiprecision integer (MPI) of RSA encrypted value m**e mod n.
Algorithm Specific Fields for Elgamal encryption:
- MPI of Elgamal (Diffie-Hellman) value g**k mod p.
- MPI of Elgamal (Diffie-Hellman) value m * y**k mod p.
The value "m" in the above formulas is derived from the session key
as follows. First, the session key is prefixed with a one-octet
algorithm identifier that specifies the symmetric encryption
algorithm used to encrypt the following Symmetrically Encrypted Data
Packet. Then a two-octet checksum is appended, which is equal to the
sum of the preceding session key octets, not including the algorithm
identifier, modulo 65536. This value is then encoded as described in
PKCS#1 block encoding EME-PKCS1-v1_5 in Section 7.2.1 of [RFC3447] to
form the "m" value used in the formulas above. See Section 13.1 of
this document for notes on OpenPGP's use of PKCS#1.
Note that when an implementation forms several PKESKs with one
session key, forming a message that can be decrypted by several keys,
the implementation MUST make a new PKCS#1 encoding for each key.
An implementation MAY accept or use a Key ID of zero as a "wild card"
or "speculative" Key ID. In this case, the receiving implementation
would try all available private keys, checking for a valid decrypted
session key. This format helps reduce traffic analysis of messages.
"""
__ver__ = 3
@sdproperty
def encrypter(self):
return self._encrypter
@encrypter.register(bytearray)
def encrypter_bin(self, val):
self._encrypter = binascii.hexlify(val).upper().decode('latin-1')
@sdproperty
def pkalg(self):
return self._pkalg
@pkalg.register(int)
@pkalg.register(PubKeyAlgorithm)
def pkalg_int(self, val):
self._pkalg = PubKeyAlgorithm(val)
_c = {PubKeyAlgorithm.RSAEncryptOrSign: RSACipherText,
PubKeyAlgorithm.RSAEncrypt: RSACipherText,
PubKeyAlgorithm.ElGamal: ElGCipherText,
PubKeyAlgorithm.FormerlyElGamalEncryptOrSign: ElGCipherText,
PubKeyAlgorithm.ECDH: ECDHCipherText}
ct = _c.get(self._pkalg, None)
self.ct = ct() if ct is not None else ct
def __init__(self):
super(PKESessionKeyV3, self).__init__()
self.encrypter = bytearray(8)
self.pkalg = 0
self.ct = None
def __bytearray__(self):
_bytes = bytearray()
_bytes += super(PKESessionKeyV3, self).__bytearray__()
_bytes += binascii.unhexlify(self.encrypter.encode())
_bytes += bytearray([self.pkalg])
_bytes += self.ct.__bytearray__() if self.ct is not None else b'\x00' * (self.header.length - 10)
return _bytes
def __copy__(self):
sk = self.__class__()
sk.header = copy.copy(self.header)
sk._encrypter = self._encrypter
sk.pkalg = self.pkalg
if self.ct is not None:
sk.ct = copy.copy(self.ct)
return sk
def decrypt_sk(self, pk):
if self.pkalg == PubKeyAlgorithm.RSAEncryptOrSign:
# pad up ct with null bytes if necessary
ct = self.ct.me_mod_n.to_mpibytes()[2:]
ct = b'\x00' * ((pk.keymaterial.__privkey__().key_size // 8) - len(ct)) + ct
decrypter = pk.keymaterial.__privkey__().decrypt
decargs = (ct, padding.PKCS1v15(),)
elif self.pkalg == PubKeyAlgorithm.ECDH:
decrypter = pk
decargs = ()
else:
raise NotImplementedError(self.pkalg)
m = bytearray(self.ct.decrypt(decrypter, *decargs))
"""
The value "m" in the above formulas is derived from the session key
as follows. First, the session key is prefixed with a one-octet
algorithm identifier that specifies the symmetric encryption
algorithm used to encrypt the following Symmetrically Encrypted Data
Packet. Then a two-octet checksum is appended, which is equal to the
sum of the preceding session key octets, not including the algorithm
identifier, modulo 65536. This value is then encoded as described in
PKCS#1 block encoding EME-PKCS1-v1_5 in Section 7.2.1 of [RFC3447] to
form the "m" value used in the formulas above. See Section 13.1 of
this document for notes on OpenPGP's use of PKCS#1.
"""
symalg = SymmetricKeyAlgorithm(m[0])
del m[0]
symkey = m[:symalg.key_size // 8]
del m[:symalg.key_size // 8]
checksum = self.bytes_to_int(m[:2])
del m[:2]
if not sum(symkey) % 65536 == checksum: # pragma: no cover
raise PGPDecryptionError("{:s} decryption failed".format(self.pkalg.name))
return (symalg, symkey)
def encrypt_sk(self, pk, symalg, symkey):
m = bytearray(self.int_to_bytes(symalg) + symkey)
m += self.int_to_bytes(sum(bytearray(symkey)) % 65536, 2)
if self.pkalg == PubKeyAlgorithm.RSAEncryptOrSign:
encrypter = pk.keymaterial.__pubkey__().encrypt
encargs = (bytes(m), padding.PKCS1v15(),)
elif self.pkalg == PubKeyAlgorithm.ECDH:
encrypter = pk
encargs = (bytes(m),)
else:
raise NotImplementedError(self.pkalg)
self.ct = self.ct.encrypt(encrypter, *encargs)
self.update_hlen()
def parse(self, packet):
super(PKESessionKeyV3, self).parse(packet)
self.encrypter = packet[:8]
del packet[:8]
self.pkalg = packet[0]
del packet[0]
if self.ct is not None:
self.ct.parse(packet)
else: # pragma: no cover
del packet[:(self.header.length - 18)]
class Signature(VersionedPacket):
__typeid__ = 0x02
__ver__ = 0
class SignatureV4(Signature):
"""
5.2.3. Version 4 Signature Packet Format
The body of a version 4 Signature packet contains:
- One-octet version number (4).
- One-octet signature type.
- One-octet public-key algorithm.
- One-octet hash algorithm.
- Two-octet scalar octet count for following hashed subpacket data.
Note that this is the length in octets of all of the hashed
subpackets; a pointer incremented by this number will skip over
the hashed subpackets.
- Hashed subpacket data set (zero or more subpackets).
- Two-octet scalar octet count for the following unhashed subpacket
data. Note that this is the length in octets of all of the
unhashed subpackets; a pointer incremented by this number will
skip over the unhashed subpackets.
- Unhashed subpacket data set (zero or more subpackets).
- Two-octet field holding the left 16 bits of the signed hash
value.
- One or more multiprecision integers comprising the signature.
This portion is algorithm specific, as described above.
The concatenation of the data being signed and the signature data
from the version number through the hashed subpacket data (inclusive)
is hashed. The resulting hash value is what is signed. The left 16
bits of the hash are included in the Signature packet to provide a
quick test to reject some invalid signatures.
There are two fields consisting of Signature subpackets. The first
field is hashed with the rest of the signature data, while the second
is unhashed. The second set of subpackets is not cryptographically
protected by the signature and should include only advisory
information.
The algorithms for converting the hash function result to a signature
are described in a section below.
"""
__ver__ = 4
@sdproperty
def sigtype(self):
return self._sigtype
@sigtype.register(int)
@sigtype.register(SignatureType)
def sigtype_int(self, val):
self._sigtype = SignatureType(val)
@sdproperty
def pubalg(self):
return self._pubalg
@pubalg.register(int)
@pubalg.register(PubKeyAlgorithm)
def pubalg_int(self, val):
self._pubalg = PubKeyAlgorithm(val)
sigs = {PubKeyAlgorithm.RSAEncryptOrSign: RSASignature,
PubKeyAlgorithm.RSAEncrypt: RSASignature,
PubKeyAlgorithm.RSASign: RSASignature,
PubKeyAlgorithm.DSA: DSASignature,
PubKeyAlgorithm.ECDSA: ECDSASignature,
PubKeyAlgorithm.EdDSA: EdDSASignature,}
self.signature = sigs.get(self.pubalg, OpaqueSignature)()
@sdproperty
def halg(self):
return self._halg
@halg.register(int)
@halg.register(HashAlgorithm)
def halg_int(self, val):
try:
self._halg = HashAlgorithm(val)
except ValueError: # pragma: no cover
self._halg = val
@property
def signature(self):
return self._signature
@signature.setter
def signature(self, val):
self._signature = val
@property
def signer(self):
return self.subpackets['Issuer'][-1].issuer
def __init__(self):
super(Signature, self).__init__()
self._sigtype = None
self._pubalg = None
self._halg = None
self.subpackets = SubPackets()
self.hash2 = bytearray(2)
self.signature = None
def __bytearray__(self):
_bytes = bytearray()
_bytes += super(Signature, self).__bytearray__()
_bytes += self.int_to_bytes(self.sigtype)
_bytes += self.int_to_bytes(self.pubalg)
_bytes += self.int_to_bytes(self.halg)
_bytes += self.subpackets.__bytearray__()
_bytes += self.hash2
_bytes += self.signature.__bytearray__()
return _bytes
def __copy__(self):
spkt = SignatureV4()
spkt.header = copy.copy(self.header)
spkt._sigtype = self._sigtype
spkt._pubalg = self._pubalg
spkt._halg = self._halg
spkt.subpackets = copy.copy(self.subpackets)
spkt.hash2 = copy.copy(self.hash2)
spkt.signature = copy.copy(self.signature)
return spkt
def update_hlen(self):
self.subpackets.update_hlen()
super(SignatureV4, self).update_hlen()
def parse(self, packet):
super(Signature, self).parse(packet)
self.sigtype = packet[0]
del packet[0]
self.pubalg = packet[0]
del packet[0]
self.halg = packet[0]
del packet[0]
self.subpackets.parse(packet)
self.hash2 = packet[:2]
del packet[:2]
self.signature.parse(packet)
class SKESessionKey(VersionedPacket):
__typeid__ = 0x03
__ver__ = 0
@abc.abstractmethod
def decrypt_sk(self, passphrase):
raise NotImplementedError()
@abc.abstractmethod
def encrypt_sk(self, passphrase, sk):
raise NotImplementedError()
class SKESessionKeyV4(SKESessionKey):
"""
5.3. Symmetric-Key Encrypted Session Key Packets (Tag 3)
The Symmetric-Key Encrypted Session Key packet holds the
symmetric-key encryption of a session key used to encrypt a message.
Zero or more Public-Key Encrypted Session Key packets and/or
Symmetric-Key Encrypted Session Key packets may precede a
Symmetrically Encrypted Data packet that holds an encrypted message.
The message is encrypted with a session key, and the session key is
itself encrypted and stored in the Encrypted Session Key packet or
the Symmetric-Key Encrypted Session Key packet.
If the Symmetrically Encrypted Data packet is preceded by one or
more Symmetric-Key Encrypted Session Key packets, each specifies a
passphrase that may be used to decrypt the message. This allows a
message to be encrypted to a number of public keys, and also to one
or more passphrases. This packet type is new and is not generated
by PGP 2.x or PGP 5.0.
The body of this packet consists of:
- A one-octet version number. The only currently defined version
is 4.
- A one-octet number describing the symmetric algorithm used.
- A string-to-key (S2K) specifier, length as defined above.
- Optionally, the encrypted session key itself, which is decrypted
with the string-to-key object.
If the encrypted session key is not present (which can be detected
on the basis of packet length and S2K specifier size), then the S2K
algorithm applied to the passphrase produces the session key for
decrypting the file, using the symmetric cipher algorithm from the
Symmetric-Key Encrypted Session Key packet.
If the encrypted session key is present, the result of applying the
S2K algorithm to the passphrase is used to decrypt just that
encrypted session key field, using CFB mode with an IV of all zeros.
The decryption result consists of a one-octet algorithm identifier
that specifies the symmetric-key encryption algorithm used to
encrypt the following Symmetrically Encrypted Data packet, followed
by the session key octets themselves.
Note: because an all-zero IV is used for this decryption, the S2K
specifier MUST use a salt value, either a Salted S2K or an
Iterated-Salted S2K. The salt value will ensure that the decryption
key is not repeated even if the passphrase is reused.
"""
__ver__ = 4
@property
def symalg(self):
return self.s2k.encalg
def __init__(self):
super(SKESessionKeyV4, self).__init__()
self.s2k = String2Key()
self.ct = bytearray()
def __bytearray__(self):
_bytes = bytearray()
_bytes += super(SKESessionKeyV4, self).__bytearray__()
_bytes += self.s2k.__bytearray__()[1:]
_bytes += self.ct
return _bytes
def __copy__(self):
sk = self.__class__()
sk.header = copy.copy(self.header)
sk.s2k = copy.copy(self.s2k)
sk.ct = self.ct[:]
return sk
def parse(self, packet):
super(SKESessionKeyV4, self).parse(packet)
# prepend a valid usage identifier so this parses correctly
packet.insert(0, 255)
self.s2k.parse(packet, iv=False)
ctend = self.header.length - len(self.s2k)
self.ct = packet[:ctend]
del packet[:ctend]
def decrypt_sk(self, passphrase):
# derive the first session key from our passphrase
sk = self.s2k.derive_key(passphrase)
del passphrase
# if there is no ciphertext, then the first session key is the session key being used
if len(self.ct) == 0:
return self.symalg, sk
# otherwise, we now need to decrypt the encrypted session key
m = bytearray(_decrypt(bytes(self.ct), sk, self.symalg))
del sk
symalg = SymmetricKeyAlgorithm(m[0])
del m[0]
return symalg, bytes(m)
def encrypt_sk(self, passphrase, sk):
# generate the salt and derive the key to encrypt sk with from it
self.s2k.salt = bytearray(os.urandom(8))
esk = self.s2k.derive_key(passphrase)
del passphrase
self.ct = _encrypt(self.int_to_bytes(self.symalg) + sk, esk, self.symalg)
# update header length and return sk
self.update_hlen()
class OnePassSignature(VersionedPacket):
__typeid__ = 0x04
__ver__ = 0
class OnePassSignatureV3(OnePassSignature):
"""
5.4. One-Pass Signature Packets (Tag 4)
The One-Pass Signature packet precedes the signed data and contains
enough information to allow the receiver to begin calculating any
hashes needed to verify the signature. It allows the Signature
packet to be placed at the end of the message, so that the signer
can compute the entire signed message in one pass.
A One-Pass Signature does not interoperate with PGP 2.6.x or
earlier.
The body of this packet consists of:
- A one-octet version number. The current version is 3.
- A one-octet signature type. Signature types are described in
Section 5.2.1.
- A one-octet number describing the hash algorithm used.
- A one-octet number describing the public-key algorithm used.
- An eight-octet number holding the Key ID of the signing key.
- A one-octet number holding a flag showing whether the signature
is nested. A zero value indicates that the next packet is
another One-Pass Signature packet that describes another
signature to be applied to the same message data.
Note that if a message contains more than one one-pass signature,
then the Signature packets bracket the message; that is, the first
Signature packet after the message corresponds to the last one-pass
packet and the final Signature packet corresponds to the first
one-pass packet.
"""
__ver__ = 3
@sdproperty
def sigtype(self):
return self._sigtype
@sigtype.register(int)
@sigtype.register(SignatureType)
def sigtype_int(self, val):
self._sigtype = SignatureType(val)
@sdproperty
def pubalg(self):
return self._pubalg
@pubalg.register(int)
@pubalg.register(PubKeyAlgorithm)
def pubalg_int(self, val):
self._pubalg = PubKeyAlgorithm(val)
if self._pubalg in [PubKeyAlgorithm.RSAEncryptOrSign, PubKeyAlgorithm.RSAEncrypt, PubKeyAlgorithm.RSASign]:
self.signature = RSASignature()
elif self._pubalg == PubKeyAlgorithm.DSA:
self.signature = DSASignature()
@sdproperty
def halg(self):
return self._halg
@halg.register(int)
@halg.register(HashAlgorithm)
def halg_int(self, val):
try:
self._halg = HashAlgorithm(val)
except ValueError: # pragma: no cover
self._halg = val
@sdproperty
def signer(self):
return self._signer
@signer.register(str)
@signer.register(six.text_type)
def signer_str(self, val):
self._signer = val
@signer.register(bytearray)
def signer_bin(self, val):
self._signer = binascii.hexlify(val).upper().decode('latin-1')
def __init__(self):
super(OnePassSignatureV3, self).__init__()
self._sigtype = None
self._halg = None
self._pubalg = None
self._signer = b'\x00' * 8
self.nested = False
def __bytearray__(self):
_bytes = bytearray()
_bytes += super(OnePassSignatureV3, self).__bytearray__()
_bytes += bytearray([self.sigtype])
_bytes += bytearray([self.halg])
_bytes += bytearray([self.pubalg])
_bytes += binascii.unhexlify(six.b(self.signer))
_bytes += bytearray([int(self.nested)])
return _bytes
def parse(self, packet):
super(OnePassSignatureV3, self).parse(packet)
self.sigtype = packet[0]
del packet[0]
self.halg = packet[0]
del packet[0]
self.pubalg = packet[0]
del packet[0]
self.signer = packet[:8]
del packet[:8]
self.nested = (packet[0] == 1)
del packet[0]
class PrivKey(VersionedPacket, Primary, Private):
__typeid__ = 0x05
__ver__ = 0
class PubKey(VersionedPacket, Primary, Public):
__typeid__ = 0x06
__ver__ = 0
@abc.abstractproperty
def fingerprint(self):
"""compute and return the fingerprint of the key"""
class PubKeyV4(PubKey):
__ver__ = 4
@sdproperty
def created(self):
return self._created
@created.register(datetime)
def created_datetime(self, val):
self._created = val
@created.register(int)
def created_int(self, val):
self.created = datetime.utcfromtimestamp(val)
@created.register(bytes)
@created.register(bytearray)
def created_bin(self, val):
self.created = self.bytes_to_int(val)
@sdproperty
def pkalg(self):
return self._pkalg
@pkalg.register(int)
@pkalg.register(PubKeyAlgorithm)
def pkalg_int(self, val):
self._pkalg = PubKeyAlgorithm(val)
_c = {
# True means public
(True, PubKeyAlgorithm.RSAEncryptOrSign): RSAPub,
(True, PubKeyAlgorithm.RSAEncrypt): RSAPub,
(True, PubKeyAlgorithm.RSASign): RSAPub,
(True, PubKeyAlgorithm.DSA): DSAPub,
(True, PubKeyAlgorithm.ElGamal): ElGPub,
(True, PubKeyAlgorithm.FormerlyElGamalEncryptOrSign): ElGPub,
(True, PubKeyAlgorithm.ECDSA): ECDSAPub,
(True, PubKeyAlgorithm.ECDH): ECDHPub,
(True, PubKeyAlgorithm.EdDSA): EdDSAPub,
# False means private
(False, PubKeyAlgorithm.RSAEncryptOrSign): RSAPriv,
(False, PubKeyAlgorithm.RSAEncrypt): RSAPriv,
(False, PubKeyAlgorithm.RSASign): RSAPriv,
(False, PubKeyAlgorithm.DSA): DSAPriv,
(False, PubKeyAlgorithm.ElGamal): ElGPriv,
(False, PubKeyAlgorithm.FormerlyElGamalEncryptOrSign): ElGPriv,
(False, PubKeyAlgorithm.ECDSA): ECDSAPriv,
(False, PubKeyAlgorithm.ECDH): ECDHPriv,
(False, PubKeyAlgorithm.EdDSA): EdDSAPriv,
}
k = (self.public, self.pkalg)
km = _c.get(k, None)
self.keymaterial = (km or (OpaquePubKey if self.public else OpaquePrivKey))()
# km = _c.get(k, None)
# self.keymaterial = km() if km is not None else km
@property
def public(self):
return isinstance(self, PubKey) and not isinstance(self, PrivKey)
@property
def fingerprint(self):
# A V4 fingerprint is the 160-bit SHA-1 hash of the octet 0x99, followed by the two-octet packet length,
# followed by the entire Public-Key packet starting with the version field. The Key ID is the
# low-order 64 bits of the fingerprint.
fp = hashlib.new('sha1')
plen = self.keymaterial.publen()
bcde_len = self.int_to_bytes(6 + plen, 2)
# a.1) 0x99 (1 octet)
# a.2) high-order length octet
# a.3) low-order length octet
fp.update(b'\x99' + bcde_len[:1] + bcde_len[-1:])
# b) version number = 4 (1 octet);
fp.update(b'\x04')
# c) timestamp of key creation (4 octets);
fp.update(self.int_to_bytes(calendar.timegm(self.created.timetuple()), 4))
# d) algorithm (1 octet): 17 = DSA (example);
fp.update(self.int_to_bytes(self.pkalg))
# e) Algorithm-specific fields.
fp.update(self.keymaterial.__bytearray__()[:plen])
# and return the digest
return Fingerprint(fp.hexdigest().upper())
def __init__(self):
super(PubKeyV4, self).__init__()
self.created = datetime.utcnow()
self.pkalg = 0
self.keymaterial = None
def __bytearray__(self):
_bytes = bytearray()
_bytes += super(PubKeyV4, self).__bytearray__()
_bytes += self.int_to_bytes(calendar.timegm(self.created.timetuple()), 4)
_bytes += self.int_to_bytes(self.pkalg)
_bytes += self.keymaterial.__bytearray__()
return _bytes
def __copy__(self):
pk = self.__class__()
pk.header = copy.copy(self.header)
pk.created = self.created
pk.pkalg = self.pkalg
pk.keymaterial = copy.copy(self.keymaterial)
return pk
def verify(self, subj, sigbytes, hash_alg):
return self.keymaterial.verify(subj, sigbytes, hash_alg)
def parse(self, packet):
super(PubKeyV4, self).parse(packet)
self.created = packet[:4]
del packet[:4]
self.pkalg = packet[0]
del packet[0]
# bound keymaterial to the remaining length of the packet
pend = self.header.length - 6
self.keymaterial.parse(packet[:pend])
del packet[:pend]
class PrivKeyV4(PrivKey, PubKeyV4):
__ver__ = 4
@classmethod
def new(cls, key_algorithm, key_size, created=None):
# build a key packet
pk = PrivKeyV4()
pk.pkalg = key_algorithm
if pk.keymaterial is None:
raise NotImplementedError(key_algorithm)
pk.keymaterial._generate(key_size)
if created is not None:
pk.created = created
pk.update_hlen()
return pk
def pubkey(self):
# return a copy of ourselves, but just the public half
pk = PubKeyV4() if not isinstance(self, PrivSubKeyV4) else PubSubKeyV4()
pk.created = self.created
pk.pkalg = self.pkalg
# copy over MPIs
for pm in self.keymaterial.__pubfields__:
setattr(pk.keymaterial, pm, copy.copy(getattr(self.keymaterial, pm)))
if self.pkalg in {PubKeyAlgorithm.ECDSA, PubKeyAlgorithm.EdDSA}:
pk.keymaterial.oid = self.keymaterial.oid
if self.pkalg == PubKeyAlgorithm.ECDH:
pk.keymaterial.oid = self.keymaterial.oid
pk.keymaterial.kdf = copy.copy(self.keymaterial.kdf)
pk.update_hlen()
return pk
@property
def protected(self):
return bool(self.keymaterial.s2k)
@property
def unlocked(self):
if self.protected:
return 0 not in list(self.keymaterial)
return True # pragma: no cover
def protect(self, passphrase, enc_alg, hash_alg):
self.keymaterial.encrypt_keyblob(passphrase, enc_alg, hash_alg)
del passphrase
self.update_hlen()
def unprotect(self, passphrase):
self.keymaterial.decrypt_keyblob(passphrase)
del passphrase
def sign(self, sigdata, hash_alg):
return self.keymaterial.sign(sigdata, hash_alg)
class PrivSubKey(VersionedPacket, Sub, Private):
__typeid__ = 0x07
__ver__ = 0
class PrivSubKeyV4(PrivSubKey, PrivKeyV4):
__ver__ = 4
class CompressedData(Packet):
"""
5.6. Compressed Data Packet (Tag 8)
The Compressed Data packet contains compressed data. Typically, this
packet is found as the contents of an encrypted packet, or following
a Signature or One-Pass Signature packet, and contains a literal data
packet.
The body of this packet consists of:
- One octet that gives the algorithm used to compress the packet.
- Compressed data, which makes up the remainder of the packet.
A Compressed Data Packet's body contains an block that compresses
some set of packets. See section "Packet Composition" for details on
how messages are formed.
ZIP-compressed packets are compressed with raw RFC 1951 [RFC1951]
DEFLATE blocks. Note that PGP V2.6 uses 13 bits of compression. If
an implementation uses more bits of compression, PGP V2.6 cannot
decompress it.
ZLIB-compressed packets are compressed with RFC 1950 [RFC1950] ZLIB-
style blocks.
BZip2-compressed packets are compressed using the BZip2 [BZ2]
algorithm.
"""
__typeid__ = 0x08
@sdproperty
def calg(self):
return self._calg
@calg.register(int)
@calg.register(CompressionAlgorithm)
def calg_int(self, val):
self._calg = CompressionAlgorithm(val)
def __init__(self):
super(CompressedData, self).__init__()
self._calg = None
self.packets = []
def __bytearray__(self):
_bytes = bytearray()
_bytes += super(CompressedData, self).__bytearray__()
_bytes += bytearray([self.calg])
_pb = bytearray()
for pkt in self.packets:
_pb += pkt.__bytearray__()
_bytes += self.calg.compress(bytes(_pb))
return _bytes
def parse(self, packet):
super(CompressedData, self).parse(packet)
self.calg = packet[0]
del packet[0]
cdata = bytearray(self.calg.decompress(packet[:self.header.length - 1]))
del packet[:self.header.length - 1]
while len(cdata) > 0:
self.packets.append(Packet(cdata))
class SKEData(Packet):
"""
5.7. Symmetrically Encrypted Data Packet (Tag 9)
The Symmetrically Encrypted Data packet contains data encrypted with