Add PGPPacket._symmetric_key_algorithms
[gpg-migrate.git] / gpg-migrate.py
1 #!/usr/bin/python
2
3 import re as _re
4 import subprocess as _subprocess
5 import struct as _struct
6
7
8 def _get_stdout(args, stdin=None):
9     stdin_pipe = None
10     if stdin is not None:
11         stdin_pipe = _subprocess.PIPE
12     p = _subprocess.Popen(args, stdin=stdin_pipe, stdout=_subprocess.PIPE)
13     stdout, stderr = p.communicate(stdin)
14     status = p.wait()
15     if status != 0:
16         raise RuntimeError(status)
17     return stdout
18
19
20 class PGPPacket (dict):
21     # http://tools.ietf.org/search/rfc4880
22     _old_format_packet_length_type = {  # type: (bytes, struct type)
23         0: (1, 'B'),  # 1-byte unsigned integer
24         1: (2, 'H'),  # 2-byte unsigned integer
25         2: (4, 'I'),  # 4-byte unsigned integer
26         3: (None, None),
27         }
28
29     _packet_types = {
30         0: 'reserved',
31         1: 'public-key encrypted session key packet',
32         2: 'signature packet',
33         3: 'symmetric-key encrypted session key packet',
34         4: 'one-pass signature packet',
35         5: 'secret-key packet',
36         6: 'public-key packet',
37         7: 'secret-subkey packet',
38         8: 'compressed data packet',
39         9: 'symmetrically encrypted data packet',
40         10: 'marker packet',
41         11: 'literal data packet',
42         12: 'trust packet',
43         13: 'user id packet',
44         14: 'public-subkey packet',
45         17: 'user attribute packet',
46         18: 'sym. encrypted and integrity protected data packet',
47         19: 'modification detection code packet',
48         60: 'private',
49         61: 'private',
50         62: 'private',
51         63: 'private',
52         }
53
54     _public_key_algorithms = {
55         1: 'rsa (encrypt or sign)',
56         2: 'rsa encrypt-only',
57         3: 'rsa sign-only',
58         16: 'elgamal (encrypt-only)',
59         17: 'dsa (digital signature algorithm)',
60         18: 'reserved for elliptic curve',
61         19: 'reserved for ecdsa',
62         20: 'reserved (formerly elgamal encrypt or sign)',
63         21: 'reserved for diffie-hellman',
64         100: 'private',
65         101: 'private',
66         102: 'private',
67         103: 'private',
68         104: 'private',
69         105: 'private',
70         106: 'private',
71         107: 'private',
72         108: 'private',
73         109: 'private',
74         110: 'private',
75         }
76
77     _symmetric_key_algorithms = {
78         0: 'plaintext or unencrypted data',
79         1: 'idea',
80         2: 'tripledes',
81         3: 'cast5',
82         4: 'blowfish',
83         5: 'reserved',
84         6: 'reserved',
85         7: 'aes with 128-bit key',
86         8: 'aes with 192-bit key',
87         9: 'aes with 256-bit key',
88         10: 'twofish',
89         100: 'private',
90         101: 'private',
91         102: 'private',
92         103: 'private',
93         104: 'private',
94         105: 'private',
95         106: 'private',
96         107: 'private',
97         108: 'private',
98         109: 'private',
99         110: 'private',
100         }
101
102     _clean_type_regex = _re.compile('\W+')
103
104     def _clean_type(self):
105         return self._clean_type_regex.sub('_', self['type'])
106
107     def from_bytes(self, data):
108         offset = self._parse_header(data=data)
109         packet = data[offset:offset + self['length']]
110         if len(packet) < self['length']:
111             raise ValueError('packet too short ({} < {})'.format(
112                 len(packet), self['length']))
113         offset += self['length']
114         method_name = '_parse_{}'.format(self._clean_type())
115         method = getattr(self, method_name, None)
116         if not method:
117             raise NotImplementedError(
118                 'cannot parse packet type {!r}'.format(self['type']))
119         method(data=packet)
120         return offset
121
122     def _parse_header(self, data):
123         packet_tag = data[0]
124         offset = 1
125         always_one = packet_tag & 1 << 7
126         if not always_one:
127             raise ValueError('most significant packet tag bit not set')
128         self['new-format'] = packet_tag & 1 << 6
129         if self['new-format']:
130             type_code = packet_tag & 0b111111
131             raise NotImplementedError('new-format packet length')
132         else:
133             type_code = packet_tag >> 2 & 0b1111
134             self['length-type'] = packet_tag & 0b11
135             length_bytes, length_type = self._old_format_packet_length_type[
136                 self['length-type']]
137             if not length_bytes:
138                 raise NotImplementedError(
139                     'old-format packet of indeterminate length')
140             length_format = '>{}'.format(length_type)
141             length_data = data[offset: offset + length_bytes]
142             offset += length_bytes
143             self['length'] = _struct.unpack(length_format, length_data)[0]
144         self['type'] = self._packet_types[type_code]
145         return offset
146
147     def _parse_public_key_packet(self, data):
148         self._parse_generic_public_key_packet(data=data)
149
150     def _parse_public_subkey_packet(self, data):
151         self._parse_generic_public_key_packet(data=data)
152
153     def _parse_generic_public_key_packet(self, data):
154         self['key-version'] = data[0]
155         offset = 1
156         if self['key-version'] != 4:
157             raise NotImplementedError(
158                 'public (sub)key packet version {}'.format(
159                     self['key-version']))
160         length = 5
161         self['creation_time'], self['public-key-algorithm'] = _struct.unpack(
162             '>IB', data[offset: offset + length])
163         offset += length
164         self['key'] = data[offset:]
165
166     def to_bytes(self):
167         pass
168
169
170 def packets_from_bytes(data):
171     offset = 0
172     while offset < len(data):
173         packet = PGPPacket()
174         offset += packet.from_bytes(data=data[offset:])
175         yield packet
176
177
178 def migrate(old_key, new_key):
179     """Add the old key and sub-keys to the new key
180
181     For example, to upgrade your master key, while preserving old
182     signatures you'd made.  You will lose signature *on* your old key
183     though, since sub-keys can't be signed (I don't think).
184     """
185     old_key_export = _get_stdout(
186         ['gpg', '--export', old_key])
187     old_key_packets = list(
188         packets_from_bytes(data=old_key_export))
189     if old_key_packets[0]['type'] != 'public-key packet':
190         raise ValueError(
191             '{} does not start with a public-key packet'.format(
192                 old_key))
193     old_key_secret_export = _get_stdout(
194         ['gpg', '--export-secret-keys', old_key])
195     old_key_secret_packets = list(
196         packets_from_bytes(data=old_key_secret_export))
197
198     import pprint
199     pprint.pprint(old_key_packets)
200     pprint.pprint(old_key_secret_packets)
201
202
203 if __name__ == '__main__':
204     import sys as _sys
205
206     old_key, new_key = _sys.argv[1:3]
207     migrate(old_key=old_key, new_key=new_key)