gpg-interface: refactor the free-and-xmemdupz pattern
[git] / gpg-interface.c
1 #include "cache.h"
2 #include "config.h"
3 #include "run-command.h"
4 #include "strbuf.h"
5 #include "gpg-interface.h"
6 #include "sigchain.h"
7 #include "tempfile.h"
8
9 static char *configured_signing_key;
10 struct gpg_format {
11         const char *name;
12         const char *program;
13         const char **verify_args;
14         const char **sigs;
15 };
16
17 static const char *openpgp_verify_args[] = {
18         "--keyid-format=long",
19         NULL
20 };
21 static const char *openpgp_sigs[] = {
22         "-----BEGIN PGP SIGNATURE-----",
23         "-----BEGIN PGP MESSAGE-----",
24         NULL
25 };
26
27 static const char *x509_verify_args[] = {
28         NULL
29 };
30 static const char *x509_sigs[] = {
31         "-----BEGIN SIGNED MESSAGE-----",
32         NULL
33 };
34
35 static struct gpg_format gpg_format[] = {
36         { .name = "openpgp", .program = "gpg",
37           .verify_args = openpgp_verify_args,
38           .sigs = openpgp_sigs
39         },
40         { .name = "x509", .program = "gpgsm",
41           .verify_args = x509_verify_args,
42           .sigs = x509_sigs
43         },
44 };
45
46 static struct gpg_format *use_format = &gpg_format[0];
47
48 static struct gpg_format *get_format_by_name(const char *str)
49 {
50         int i;
51
52         for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
53                 if (!strcmp(gpg_format[i].name, str))
54                         return gpg_format + i;
55         return NULL;
56 }
57
58 static struct gpg_format *get_format_by_sig(const char *sig)
59 {
60         int i, j;
61
62         for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
63                 for (j = 0; gpg_format[i].sigs[j]; j++)
64                         if (starts_with(sig, gpg_format[i].sigs[j]))
65                                 return gpg_format + i;
66         return NULL;
67 }
68
69 void signature_check_clear(struct signature_check *sigc)
70 {
71         FREE_AND_NULL(sigc->payload);
72         FREE_AND_NULL(sigc->gpg_output);
73         FREE_AND_NULL(sigc->gpg_status);
74         FREE_AND_NULL(sigc->signer);
75         FREE_AND_NULL(sigc->key);
76         FREE_AND_NULL(sigc->fingerprint);
77         FREE_AND_NULL(sigc->primary_key_fingerprint);
78 }
79
80 /* An exclusive status -- only one of them can appear in output */
81 #define GPG_STATUS_EXCLUSIVE    (1<<0)
82 /* The status includes key identifier */
83 #define GPG_STATUS_KEYID        (1<<1)
84 /* The status includes user identifier */
85 #define GPG_STATUS_UID          (1<<2)
86 /* The status includes key fingerprints */
87 #define GPG_STATUS_FINGERPRINT  (1<<3)
88
89 /* Short-hand for standard exclusive *SIG status with keyid & UID */
90 #define GPG_STATUS_STDSIG       (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
91
92 static struct {
93         char result;
94         const char *check;
95         unsigned int flags;
96 } sigcheck_gpg_status[] = {
97         { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
98         { 'B', "BADSIG ", GPG_STATUS_STDSIG },
99         { 'U', "TRUST_NEVER", 0 },
100         { 'U', "TRUST_UNDEFINED", 0 },
101         { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
102         { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
103         { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
104         { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
105         { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
106 };
107
108 static void replace_cstring(char **field, const char *line, const char *next)
109 {
110         free(*field);
111
112         if (line && next)
113                 *field = xmemdupz(line, next - line);
114         else
115                 *field = NULL;
116 }
117
118 static void parse_gpg_output(struct signature_check *sigc)
119 {
120         const char *buf = sigc->gpg_status;
121         const char *line, *next;
122         int i, j;
123         int seen_exclusive_status = 0;
124
125         /* Iterate over all lines */
126         for (line = buf; *line; line = strchrnul(line+1, '\n')) {
127                 while (*line == '\n')
128                         line++;
129                 if (!*line)
130                         break;
131
132                 /* Skip lines that don't start with GNUPG status */
133                 if (!skip_prefix(line, "[GNUPG:] ", &line))
134                         continue;
135
136                 /* Iterate over all search strings */
137                 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
138                         if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
139                                 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
140                                         if (seen_exclusive_status++)
141                                                 goto found_duplicate_status;
142                                 }
143
144                                 if (sigcheck_gpg_status[i].result)
145                                         sigc->result = sigcheck_gpg_status[i].result;
146                                 /* Do we have key information? */
147                                 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
148                                         next = strchrnul(line, ' ');
149                                         replace_cstring(&sigc->key, line, next);
150                                         /* Do we have signer information? */
151                                         if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
152                                                 line = next + 1;
153                                                 next = strchrnul(line, '\n');
154                                                 replace_cstring(&sigc->signer, line, next);
155                                         }
156                                 }
157                                 /* Do we have fingerprint? */
158                                 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
159                                         next = strchrnul(line, ' ');
160                                         replace_cstring(&sigc->fingerprint, line, next);
161
162                                         /* Skip interim fields */
163                                         for (j = 9; j > 0; j--) {
164                                                 if (!*next)
165                                                         break;
166                                                 line = next + 1;
167                                                 next = strchrnul(line, ' ');
168                                         }
169
170                                         next = strchrnul(line, '\n');
171                                         free(sigc->primary_key_fingerprint);
172                                         replace_cstring(&sigc->primary_key_fingerprint,
173                                                         line, next);
174                                 }
175
176                                 break;
177                         }
178                 }
179         }
180         return;
181
182 found_duplicate_status:
183         /*
184          * GOODSIG, BADSIG etc. can occur only once for each signature.
185          * Therefore, if we had more than one then we're dealing with multiple
186          * signatures.  We don't support them currently, and they're rather
187          * hard to create, so something is likely fishy and we should reject
188          * them altogether.
189          */
190         sigc->result = 'E';
191         /* Clear partial data to avoid confusion */
192         FREE_AND_NULL(sigc->primary_key_fingerprint);
193         FREE_AND_NULL(sigc->fingerprint);
194         FREE_AND_NULL(sigc->signer);
195         FREE_AND_NULL(sigc->key);
196 }
197
198 int check_signature(const char *payload, size_t plen, const char *signature,
199         size_t slen, struct signature_check *sigc)
200 {
201         struct strbuf gpg_output = STRBUF_INIT;
202         struct strbuf gpg_status = STRBUF_INIT;
203         int status;
204
205         sigc->result = 'N';
206
207         status = verify_signed_buffer(payload, plen, signature, slen,
208                                       &gpg_output, &gpg_status);
209         if (status && !gpg_output.len)
210                 goto out;
211         sigc->payload = xmemdupz(payload, plen);
212         sigc->gpg_output = strbuf_detach(&gpg_output, NULL);
213         sigc->gpg_status = strbuf_detach(&gpg_status, NULL);
214         parse_gpg_output(sigc);
215         status |= sigc->result != 'G' && sigc->result != 'U';
216
217  out:
218         strbuf_release(&gpg_status);
219         strbuf_release(&gpg_output);
220
221         return !!status;
222 }
223
224 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
225 {
226         const char *output = flags & GPG_VERIFY_RAW ?
227                 sigc->gpg_status : sigc->gpg_output;
228
229         if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
230                 fputs(sigc->payload, stdout);
231
232         if (output)
233                 fputs(output, stderr);
234 }
235
236 size_t parse_signature(const char *buf, size_t size)
237 {
238         size_t len = 0;
239         size_t match = size;
240         while (len < size) {
241                 const char *eol;
242
243                 if (get_format_by_sig(buf + len))
244                         match = len;
245
246                 eol = memchr(buf + len, '\n', size - len);
247                 len += eol ? eol - (buf + len) + 1 : size - len;
248         }
249         return match;
250 }
251
252 void set_signing_key(const char *key)
253 {
254         free(configured_signing_key);
255         configured_signing_key = xstrdup(key);
256 }
257
258 int git_gpg_config(const char *var, const char *value, void *cb)
259 {
260         struct gpg_format *fmt = NULL;
261         char *fmtname = NULL;
262
263         if (!strcmp(var, "user.signingkey")) {
264                 if (!value)
265                         return config_error_nonbool(var);
266                 set_signing_key(value);
267                 return 0;
268         }
269
270         if (!strcmp(var, "gpg.format")) {
271                 if (!value)
272                         return config_error_nonbool(var);
273                 fmt = get_format_by_name(value);
274                 if (!fmt)
275                         return error("unsupported value for %s: %s",
276                                      var, value);
277                 use_format = fmt;
278                 return 0;
279         }
280
281         if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
282                 fmtname = "openpgp";
283
284         if (!strcmp(var, "gpg.x509.program"))
285                 fmtname = "x509";
286
287         if (fmtname) {
288                 fmt = get_format_by_name(fmtname);
289                 return git_config_string(&fmt->program, var, value);
290         }
291
292         return 0;
293 }
294
295 const char *get_signing_key(void)
296 {
297         if (configured_signing_key)
298                 return configured_signing_key;
299         return git_committer_info(IDENT_STRICT|IDENT_NO_DATE);
300 }
301
302 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
303 {
304         struct child_process gpg = CHILD_PROCESS_INIT;
305         int ret;
306         size_t i, j, bottom;
307         struct strbuf gpg_status = STRBUF_INIT;
308
309         argv_array_pushl(&gpg.args,
310                          use_format->program,
311                          "--status-fd=2",
312                          "-bsau", signing_key,
313                          NULL);
314
315         bottom = signature->len;
316
317         /*
318          * When the username signingkey is bad, program could be terminated
319          * because gpg exits without reading and then write gets SIGPIPE.
320          */
321         sigchain_push(SIGPIPE, SIG_IGN);
322         ret = pipe_command(&gpg, buffer->buf, buffer->len,
323                            signature, 1024, &gpg_status, 0);
324         sigchain_pop(SIGPIPE);
325
326         ret |= !strstr(gpg_status.buf, "\n[GNUPG:] SIG_CREATED ");
327         strbuf_release(&gpg_status);
328         if (ret)
329                 return error(_("gpg failed to sign the data"));
330
331         /* Strip CR from the line endings, in case we are on Windows. */
332         for (i = j = bottom; i < signature->len; i++)
333                 if (signature->buf[i] != '\r') {
334                         if (i != j)
335                                 signature->buf[j] = signature->buf[i];
336                         j++;
337                 }
338         strbuf_setlen(signature, j);
339
340         return 0;
341 }
342
343 int verify_signed_buffer(const char *payload, size_t payload_size,
344                          const char *signature, size_t signature_size,
345                          struct strbuf *gpg_output, struct strbuf *gpg_status)
346 {
347         struct child_process gpg = CHILD_PROCESS_INIT;
348         struct gpg_format *fmt;
349         struct tempfile *temp;
350         int ret;
351         struct strbuf buf = STRBUF_INIT;
352
353         temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
354         if (!temp)
355                 return error_errno(_("could not create temporary file"));
356         if (write_in_full(temp->fd, signature, signature_size) < 0 ||
357             close_tempfile_gently(temp) < 0) {
358                 error_errno(_("failed writing detached signature to '%s'"),
359                             temp->filename.buf);
360                 delete_tempfile(&temp);
361                 return -1;
362         }
363
364         fmt = get_format_by_sig(signature);
365         if (!fmt)
366                 BUG("bad signature '%s'", signature);
367
368         argv_array_push(&gpg.args, fmt->program);
369         argv_array_pushv(&gpg.args, fmt->verify_args);
370         argv_array_pushl(&gpg.args,
371                          "--status-fd=1",
372                          "--verify", temp->filename.buf, "-",
373                          NULL);
374
375         if (!gpg_status)
376                 gpg_status = &buf;
377
378         sigchain_push(SIGPIPE, SIG_IGN);
379         ret = pipe_command(&gpg, payload, payload_size,
380                            gpg_status, 0, gpg_output, 0);
381         sigchain_pop(SIGPIPE);
382
383         delete_tempfile(&temp);
384
385         ret |= !strstr(gpg_status->buf, "\n[GNUPG:] GOODSIG ");
386         strbuf_release(&buf); /* no matter it was used or not */
387
388         return ret;
389 }