]> git.donarmstrong.com Git - dak.git/blob - daklib/gpg.py
daklib/gpg.py: Ignore POLICY_URL keyword.
[dak.git] / daklib / gpg.py
1 """Utilities for signed files
2
3 @contact: Debian FTP Master <ftpmaster@debian.org>
4 @copyright: 2011  Ansgar Burchardt <ansgar@debian.org>
5 @license: GNU General Public License version 2 or later
6 """
7
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
22 import apt_pkg
23 import datetime
24 import errno
25 import fcntl
26 import os
27 import select
28
29 try:
30     _MAXFD = os.sysconf("SC_OPEN_MAX")
31 except:
32     _MAXFD = 256
33
34 class GpgException(Exception):
35     pass
36
37 class _Pipe(object):
38     """context manager for pipes
39
40     Note: When the pipe is closed by other means than the close_r and close_w
41     methods, you have to set self.r (self.w) to None.
42     """
43     def __enter__(self):
44         (self.r, self.w) = os.pipe()
45         return self
46     def __exit__(self, type, value, traceback):
47         self.close_w()
48         self.close_r()
49         return False
50     def close_r(self):
51         """close reading side of the pipe"""
52         if self.r:
53             os.close(self.r)
54             self.r = None
55     def close_w(self):
56         """close writing part of the pipe"""
57         if self.w:
58             os.close(self.w)
59             self.w = None
60
61 class SignedFile(object):
62     """handle files signed with PGP
63
64     The following attributes are available:
65       contents            - string with the content (after removing PGP armor)
66       valid               - Boolean indicating a valid signature was found
67       fingerprint         - fingerprint of the key used for signing
68       primary_fingerprint - fingerprint of the primary key associated to the key used for signing
69     """
70     def __init__(self, data, keyrings, require_signature=True, gpg="/usr/bin/gpg"):
71         """
72         @param data: string containing the message
73         @param keyrings: sequence of keyrings
74         @param require_signature: if True (the default), will raise an exception if no valid signature was found
75         @param gpg: location of the gpg binary
76         """
77         self.gpg = gpg
78         self.keyrings = keyrings
79
80         self.valid = False
81         self.expired = False
82         self.invalid = False
83         self.fingerprint = None
84         self.primary_fingerprint = None
85         self.signature_id = None
86
87         self._verify(data, require_signature)
88
89     def _verify(self, data, require_signature):
90         with _Pipe() as stdin:
91          with _Pipe() as contents:
92           with _Pipe() as status:
93            with _Pipe() as stderr:
94             pid = os.fork()
95             if pid == 0:
96                 self._exec_gpg(stdin.r, contents.w, stderr.w, status.w)
97             else:
98                 stdin.close_r()
99                 contents.close_w()
100                 stderr.close_w()
101                 status.close_w()
102
103                 read = self._do_io([contents.r, stderr.r, status.r], {stdin.w: data})
104                 stdin.w = None # was closed by _do_io
105
106                 (pid_, exit_code, usage_) = os.wait4(pid, 0)
107
108                 self.contents = read[contents.r]
109                 self.status   = read[status.r]
110                 self.stderr   = read[stderr.r]
111
112                 if self.status == "":
113                     raise GpgException("No status output from GPG. (GPG exited with status code %s)\n%s" % (exit_code, self.stderr))
114
115                 for line in self.status.splitlines():
116                     self._parse_status(line)
117
118                 if self.invalid:
119                     self.valid = False
120
121                 if require_signature and not self.valid:
122                     raise GpgException("No valid signature found. (GPG exited with status code %s)\n%s" % (exit_code, self.stderr))
123
124     def _do_io(self, read, write):
125         for fd in write.keys():
126             old = fcntl.fcntl(fd, fcntl.F_GETFL)
127             fcntl.fcntl(fd, fcntl.F_SETFL, old | os.O_NONBLOCK)
128
129         read_lines = dict( (fd, []) for fd in read )
130         write_pos = dict( (fd, 0) for fd in write )
131
132         read_set = list(read)
133         write_set = write.keys()
134         while len(read_set) > 0 or len(write_set) > 0:
135             r, w, x_ = select.select(read_set, write_set, ())
136             for fd in r:
137                 data = os.read(fd, 4096)
138                 if data == "":
139                     read_set.remove(fd)
140                 read_lines[fd].append(data)
141             for fd in w:
142                 data = write[fd][write_pos[fd]:]
143                 if data == "":
144                     os.close(fd)
145                     write_set.remove(fd)
146                 else:
147                     bytes_written = os.write(fd, data)
148                     write_pos[fd] += bytes_written
149
150         return dict( (fd, "".join(read_lines[fd])) for fd in read_lines.keys() )
151
152     def _parse_timestamp(self, timestamp, datestring=None):
153         """parse timestamp in GnuPG's format
154
155         @rtype:   L{datetime.datetime}
156         @returns: datetime object for the given timestamp
157         """
158         # The old implementation did only return the date. As we already
159         # used this for replay production, return the legacy value for
160         # old signatures.
161         if datestring is not None:
162             year, month, day = datestring.split('-')
163             date = datetime.date(int(year), int(month), int(day))
164             time = datetime.time(0, 0)
165             if date < datetime.date(2014, 8, 4):
166                 return datetime.datetime.combine(date, time)
167
168         if 'T' in timestamp:
169             raise Exception('No support for ISO 8601 timestamps.')
170         return datetime.datetime.utcfromtimestamp(long(timestamp))
171
172     def _parse_status(self, line):
173         fields = line.split()
174         if fields[0] != "[GNUPG:]":
175             raise GpgException("Unexpected output on status-fd: %s" % line)
176
177         # VALIDSIG    <fingerprint in hex> <sig_creation_date> <sig-timestamp>
178         #             <expire-timestamp> <sig-version> <reserved> <pubkey-algo>
179         #             <hash-algo> <sig-class> <primary-key-fpr>
180         if fields[1] == "VALIDSIG":
181             if self.fingerprint is not None:
182                 raise GpgException("More than one signature is not (yet) supported.")
183             self.valid = True
184             self.fingerprint = fields[2]
185             self.primary_fingerprint = fields[11]
186             self.signature_timestamp = self._parse_timestamp(fields[4], fields[3])
187
188         elif fields[1] == "BADARMOR":
189             raise GpgException("Bad armor.")
190
191         elif fields[1] == "NODATA":
192             raise GpgException("No data.")
193
194         elif fields[1] == "DECRYPTION_FAILED":
195             raise GpgException("Decryption failed.")
196
197         elif fields[1] == "ERROR":
198             raise GpgException("Other error: %s %s" % (fields[2], fields[3]))
199
200         elif fields[1] == "SIG_ID":
201             if self.signature_id is not None:
202                 raise GpgException("More than one signature id.")
203             self.signature_id = fields[2]
204
205         elif fields[1] in ('PLAINTEXT', 'GOODSIG', 'NOTATION_NAME', 'NOTATION_DATA', 'SIGEXPIRED', 'KEYEXPIRED', 'POLICY_URL'):
206             pass
207
208         elif fields[1] in ('EXPSIG', 'EXPKEYSIG'):
209             self.expired = True
210             self.invalid = True
211
212         elif fields[1] in ('REVKEYSIG', 'BADSIG', 'ERRSIG', 'KEYREVOKED', 'NO_PUBKEY'):
213             self.invalid = True
214
215         else:
216             raise GpgException("Keyword '{0}' from GnuPG was not expected.".format(fields[1]))
217
218     def _exec_gpg(self, stdin, stdout, stderr, statusfd):
219         try:
220             if stdin != 0:
221                 os.dup2(stdin, 0)
222             if stdout != 1:
223                 os.dup2(stdout, 1)
224             if stderr != 2:
225                 os.dup2(stderr, 2)
226             if statusfd != 3:
227                 os.dup2(statusfd, 3)
228             for fd in range(4):
229                 old = fcntl.fcntl(fd, fcntl.F_GETFD)
230                 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~fcntl.FD_CLOEXEC)
231             os.closerange(4, _MAXFD)
232
233             args = [self.gpg,
234                     "--status-fd=3",
235                     "--no-default-keyring",
236                     "--batch",
237                     "--no-tty",
238                     "--trust-model", "always",
239                     "--fixed-list-mode"]
240             for k in self.keyrings:
241                 args.append("--keyring=%s" % k)
242             args.extend(["--decrypt", "-"])
243
244             os.execvp(self.gpg, args)
245         finally:
246             os._exit(1)
247
248     def contents_sha1(self):
249         return apt_pkg.sha1sum(self.contents)
250
251 # vim: set sw=4 et: