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