1 """Utilities for signed files
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
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.
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.
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
30 _MAXFD = os.sysconf("SC_OPEN_MAX")
34 class GpgException(Exception):
38 """context manager for pipes
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.
44 (self.r, self.w) = os.pipe()
46 def __exit__(self, type, value, traceback):
51 """close reading side of the pipe"""
56 """close writing part of the pipe"""
61 class SignedFile(object):
62 """handle files signed with PGP
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
70 def __init__(self, data, keyrings, require_signature=True, gpg="/usr/bin/gpg"):
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
78 self.keyrings = keyrings
83 self.fingerprint = None
84 self.primary_fingerprint = None
85 self.signature_id = None
87 self._verify(data, require_signature)
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:
96 self._exec_gpg(stdin.r, contents.w, stderr.w, status.w)
103 read = self._do_io([contents.r, stderr.r, status.r], {stdin.w: data})
104 stdin.w = None # was closed by _do_io
106 (pid_, exit_code, usage_) = os.wait4(pid, 0)
108 self.contents = read[contents.r]
109 self.status = read[status.r]
110 self.stderr = read[stderr.r]
112 if self.status == "":
113 raise GpgException("No status output from GPG. (GPG exited with status code %s)\n%s" % (exit_code, self.stderr))
115 for line in self.status.splitlines():
116 self._parse_status(line)
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))
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)
129 read_lines = dict( (fd, []) for fd in read )
130 write_pos = dict( (fd, 0) for fd in write )
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, ())
137 data = os.read(fd, 4096)
140 read_lines[fd].append(data)
142 data = write[fd][write_pos[fd]:]
147 bytes_written = os.write(fd, data)
148 write_pos[fd] += bytes_written
150 return dict( (fd, "".join(read_lines[fd])) for fd in read_lines.keys() )
152 def _parse_date(self, value):
153 """parse date string in YYYY-MM-DD format
155 @rtype: L{datetime.datetime}
156 @returns: datetime objects for 0:00 on the given day
158 year, month, day = value.split('-')
159 date = datetime.date(int(year), int(month), int(day))
160 time = datetime.time(0, 0)
161 return datetime.datetime.combine(date, time)
163 def _parse_status(self, line):
164 fields = line.split()
165 if fields[0] != "[GNUPG:]":
166 raise GpgException("Unexpected output on status-fd: %s" % line)
168 # VALIDSIG <fingerprint in hex> <sig_creation_date> <sig-timestamp>
169 # <expire-timestamp> <sig-version> <reserved> <pubkey-algo>
170 # <hash-algo> <sig-class> <primary-key-fpr>
171 if fields[1] == "VALIDSIG":
172 if self.fingerprint is not None:
173 raise GpgException("More than one signature is not (yet) supported.")
175 self.fingerprint = fields[2]
176 self.primary_fingerprint = fields[11]
177 self.signature_timestamp = self._parse_date(fields[3])
179 elif fields[1] == "BADARMOR":
180 raise GpgException("Bad armor.")
182 elif fields[1] == "NODATA":
183 raise GpgException("No data.")
185 elif fields[1] == "DECRYPTION_FAILED":
186 raise GpgException("Decryption failed.")
188 elif fields[1] == "ERROR":
189 raise GpgException("Other error: %s %s" % (fields[2], fields[3]))
191 elif fields[1] == "SIG_ID":
192 if self.signature_id is not None:
193 raise GpgException("More than one signature id.")
194 self.signature_id = fields[2]
196 elif fields[1] in ('PLAINTEXT', 'GOODSIG'):
199 elif fields[1] in ('EXPSIG', 'EXPKEYSIG'):
203 elif fields[1] in ('REVKEYSIG', 'BADSIG', 'ERRSIG'):
207 raise GpgException("Keyword '{0}' from GnuPG was not expected.".format(fields[1]))
209 def _exec_gpg(self, stdin, stdout, stderr, statusfd):
220 old = fcntl.fcntl(fd, fcntl.F_GETFD)
221 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~fcntl.FD_CLOEXEC)
222 os.closerange(4, _MAXFD)
226 "--no-default-keyring",
229 "--trust-model", "always"]
230 for k in self.keyrings:
231 args.append("--keyring=%s" % k)
232 args.extend(["--decrypt", "-"])
234 os.execvp(self.gpg, args)
238 def contents_sha1(self):
239 return apt_pkg.sha1sum(self.contents)