]> git.decadent.org.uk Git - dak.git/blob - daklib/gpg.py
Merge remote branch 'ansgar/signatures-2' into merge
[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 errno
23 import fcntl
24 import os
25 import select
26 import sys
27
28 try:
29     _MAXFD = os.sysconf("SC_OPEN_MAX")
30 except:
31     _MAXFD = 256
32
33 class GpgException(Exception):
34     pass
35
36 class _Pipe(object):
37     """context manager for pipes
38
39     Note: When the pipe is closed by other means than the close_r and close_w
40     methods, you have to set self.r (self.w) to None.
41     """
42     def __enter__(self):
43         (self.r, self.w) = os.pipe()
44         return self
45     def __exit__(self, type, value, traceback):
46         self.close_w()
47         self.close_r()
48         return False
49     def close_r(self):
50         """close reading side of the pipe"""
51         if self.r:
52             os.close(self.r)
53             self.r = None
54     def close_w(self):
55         """close writing part of the pipe"""
56         if self.w:
57             os.close(self.w)
58             self.w = None
59
60 class SignedFile(object):
61     """handle files signed with PGP
62
63     The following attributes are available:
64       contents            - string with the content (after removing PGP armor)
65       valid               - Boolean indicating a valid signature was found
66       fingerprint         - fingerprint of the key used for signing
67       primary_fingerprint - fingerprint of the primary key associated to the key used for signing
68     """
69     def __init__(self, data, keyrings, require_signature=True, gpg="/usr/bin/gpg"):
70         """
71         @param data: string containing the message
72         @param keyrings: seqeuence of keyrings
73         @param require_signature: if True (the default), will raise an exception if no valid signature was found
74         @param gpg: location of the gpg binary
75         """
76         self.gpg = gpg
77         self.keyrings = keyrings
78
79         self.valid = False
80         self.fingerprint = None
81         self.primary_fingerprint = None
82
83         self._verify(data, require_signature)
84
85     def _verify(self, data, require_signature):
86         with _Pipe() as stdin:
87          with _Pipe() as contents:
88           with _Pipe() as status:
89            with _Pipe() as stderr:
90             pid = os.fork()
91             if pid == 0:
92                 self._exec_gpg(stdin.r, contents.w, stderr.w, status.w)
93             else:
94                 stdin.close_r()
95                 contents.close_w()
96                 stderr.close_w()
97                 status.close_w()
98
99                 read = self._do_io([contents.r, stderr.r, status.r], {stdin.w: data})
100                 stdin.w = None # was closed by _do_io
101
102                 (pid_, exit_code, usage_) = os.wait4(pid, 0)
103
104                 self.contents = read[contents.r]
105                 self.status   = read[status.r]
106                 self.stderr   = read[stderr.r]
107
108                 if self.status == "":
109                     raise GpgException("No status output from GPG. (GPG exited with status code %s)\n%s" % (exit_code, self.stderr))
110
111                 for line in self.status.splitlines():
112                     self._parse_status(line)
113
114                 if require_signature and not self.valid:
115                     raise GpgException("No valid signature found. (GPG exited with status code %s)\n%s" % (exit_code, self.stderr))
116
117     def _do_io(self, read, write):
118         read_lines = dict( (fd, []) for fd in read )
119         write_pos = dict( (fd, 0) for fd in write )
120
121         read_set = list(read)
122         write_set = write.keys()
123         while len(read_set) > 0 or len(write_set) > 0:
124             r, w, x_ = select.select(read_set, write_set, ())
125             for fd in r:
126                 data = os.read(fd, 4096)
127                 if data == "":
128                     read_set.remove(fd)
129                 read_lines[fd].append(data)
130             for fd in w:
131                 data = write[fd][write_pos[fd]:]
132                 if data == "":
133                     os.close(fd)
134                     write_set.remove(fd)
135                 else:
136                     bytes_written = os.write(fd, data)
137                     write_pos[fd] += bytes_written
138
139         return dict( (fd, "".join(read_lines[fd])) for fd in read_lines.keys() )
140
141     def _parse_status(self, line):
142         fields = line.split()
143         if fields[0] != "[GNUPG:]":
144             raise GpgException("Unexpected output on status-fd: %s" % line)
145
146         # VALIDSIG    <fingerprint in hex> <sig_creation_date> <sig-timestamp>
147         #             <expire-timestamp> <sig-version> <reserved> <pubkey-algo>
148         #             <hash-algo> <sig-class> <primary-key-fpr>
149         if fields[1] == "VALIDSIG":
150             self.valid = True
151             self.fingerprint = fields[2]
152             self.primary_fingerprint = fields[11]
153
154         if fields[1] == "BADARMOR":
155             raise GpgException("Bad armor.")
156
157         if fields[1] == "NODATA":
158             raise GpgException("No data.")
159
160         if fields[1] == "DECRYPTION_FAILED":
161             raise GpgException("Decryption failed.")
162
163         if fields[1] == "ERROR":
164             raise GpgException("Other error: %s %s" % (fields[2], fields[3]))
165
166     def _exec_gpg(self, stdin, stdout, stderr, statusfd):
167         try:
168             if stdin != 0:
169                 os.dup2(stdin, 0)
170             if stdout != 1:
171                 os.dup2(stdout, 1)
172             if stderr != 2:
173                 os.dup2(stderr, 2)
174             if statusfd != 3:
175                 os.dup2(statusfd, 3)
176             for fd in range(4):
177                 old = fcntl.fcntl(fd, fcntl.F_GETFD)
178                 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~fcntl.FD_CLOEXEC)
179             os.closerange(4, _MAXFD)
180
181             args = [self.gpg, "--status-fd=3", "--no-default-keyring"]
182             for k in self.keyrings:
183                 args.append("--keyring=%s" % k)
184             args.extend(["--decrypt", "-"])
185
186             os.execvp(self.gpg, args)
187         finally:
188             sys.exit(1)
189
190 # vim: set sw=4 et: