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
28 _MAXFD = os.sysconf("SC_OPEN_MAX")
32 class GpgException(Exception):
36 """context manager for pipes
38 Note: When the pipe is closed by other means than the close_r and close_w
39 methods, you have to set self.r (self.w) to None.
42 (self.r, self.w) = os.pipe()
44 def __exit__(self, type, value, traceback):
49 """close reading side of the pipe"""
54 """close writing part of the pipe"""
59 class SignedFile(object):
60 """handle files signed with PGP
62 The following attributes are available:
63 contents - string with the content (after removing PGP armor)
64 valid - Boolean indicating a valid signature was found
65 fingerprint - fingerprint of the key used for signing
66 primary_fingerprint - fingerprint of the primary key associated to the key used for signing
68 def __init__(self, data, keyrings, require_signature=True, gpg="/usr/bin/gpg"):
70 @param data: string containing the message
71 @param keyrings: seqeuence of keyrings
72 @param require_signature: if True (the default), will raise an exception if no valid signature was found
73 @param gpg: location of the gpg binary
76 self.keyrings = keyrings
79 self.fingerprint = None
80 self.primary_fingerprint = None
82 self._verify(data, require_signature)
84 def _verify(self, data, require_signature):
85 with _Pipe() as stdin:
86 with _Pipe() as contents:
87 with _Pipe() as status:
88 with _Pipe() as stderr:
91 self._exec_gpg(stdin.r, contents.w, stderr.w, status.w)
98 read = self._do_io([contents.r, stderr.r, status.r], {stdin.w: data})
99 stdin.w = None # was closed by _do_io
101 (pid_, exit_code, usage_) = os.wait4(pid, 0)
103 self.contents = read[contents.r]
104 self.status = read[status.r]
105 self.stderr = read[stderr.r]
107 if self.status == "":
108 raise GpgException("No status output from GPG. (GPG exited with status code %s)\n%s" % (exit_code, self.stderr))
110 for line in self.status.splitlines():
111 self._parse_status(line)
113 if require_signature and not self.valid:
114 raise GpgException("No valid signature found. (GPG exited with status code %s)\n%s" % (exit_code, self.stderr))
116 def _do_io(self, read, write):
117 for fd in write.keys():
118 old = fcntl.fcntl(fd, fcntl.F_GETFL)
119 fcntl.fcntl(fd, fcntl.F_SETFL, old | os.O_NONBLOCK)
121 read_lines = dict( (fd, []) for fd in read )
122 write_pos = dict( (fd, 0) for fd in write )
124 read_set = list(read)
125 write_set = write.keys()
126 while len(read_set) > 0 or len(write_set) > 0:
127 r, w, x_ = select.select(read_set, write_set, ())
129 data = os.read(fd, 4096)
132 read_lines[fd].append(data)
134 data = write[fd][write_pos[fd]:]
139 bytes_written = os.write(fd, data)
140 write_pos[fd] += bytes_written
142 return dict( (fd, "".join(read_lines[fd])) for fd in read_lines.keys() )
144 def _parse_status(self, line):
145 fields = line.split()
146 if fields[0] != "[GNUPG:]":
147 raise GpgException("Unexpected output on status-fd: %s" % line)
149 # VALIDSIG <fingerprint in hex> <sig_creation_date> <sig-timestamp>
150 # <expire-timestamp> <sig-version> <reserved> <pubkey-algo>
151 # <hash-algo> <sig-class> <primary-key-fpr>
152 if fields[1] == "VALIDSIG":
154 self.fingerprint = fields[2]
155 self.primary_fingerprint = fields[11]
157 if fields[1] == "BADARMOR":
158 raise GpgException("Bad armor.")
160 if fields[1] == "NODATA":
161 raise GpgException("No data.")
163 if fields[1] == "DECRYPTION_FAILED":
164 raise GpgException("Decryption failed.")
166 if fields[1] == "ERROR":
167 raise GpgException("Other error: %s %s" % (fields[2], fields[3]))
169 def _exec_gpg(self, stdin, stdout, stderr, statusfd):
180 old = fcntl.fcntl(fd, fcntl.F_GETFD)
181 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~fcntl.FD_CLOEXEC)
182 os.closerange(4, _MAXFD)
184 args = [self.gpg, "--status-fd=3", "--no-default-keyring"]
185 for k in self.keyrings:
186 args.append("--keyring=%s" % k)
187 args.extend(["--decrypt", "-"])
189 os.execvp(self.gpg, args)