ssh signing: retrieve a default key from ssh-agent
[alt-git.git] / gpg-interface.c
blob3a0cca1b1d21093406efdb0153b20dc87e7f27d2
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 #include "alias.h"
11 static char *configured_signing_key;
12 static const char *ssh_default_key_command;
13 static enum signature_trust_level configured_min_trust_level = TRUST_UNDEFINED;
15 struct gpg_format {
16 const char *name;
17 const char *program;
18 const char **verify_args;
19 const char **sigs;
20 int (*verify_signed_buffer)(struct signature_check *sigc,
21 struct gpg_format *fmt, const char *payload,
22 size_t payload_size, const char *signature,
23 size_t signature_size);
24 int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
25 const char *signing_key);
26 const char *(*get_default_key)(void);
29 static const char *openpgp_verify_args[] = {
30 "--keyid-format=long",
31 NULL
33 static const char *openpgp_sigs[] = {
34 "-----BEGIN PGP SIGNATURE-----",
35 "-----BEGIN PGP MESSAGE-----",
36 NULL
39 static const char *x509_verify_args[] = {
40 NULL
42 static const char *x509_sigs[] = {
43 "-----BEGIN SIGNED MESSAGE-----",
44 NULL
47 static const char *ssh_verify_args[] = { NULL };
48 static const char *ssh_sigs[] = {
49 "-----BEGIN SSH SIGNATURE-----",
50 NULL
53 static int verify_gpg_signed_buffer(struct signature_check *sigc,
54 struct gpg_format *fmt, const char *payload,
55 size_t payload_size, const char *signature,
56 size_t signature_size);
57 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
58 const char *signing_key);
59 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
60 const char *signing_key);
62 static const char *get_default_ssh_signing_key(void);
64 static struct gpg_format gpg_format[] = {
66 .name = "openpgp",
67 .program = "gpg",
68 .verify_args = openpgp_verify_args,
69 .sigs = openpgp_sigs,
70 .verify_signed_buffer = verify_gpg_signed_buffer,
71 .sign_buffer = sign_buffer_gpg,
72 .get_default_key = NULL,
75 .name = "x509",
76 .program = "gpgsm",
77 .verify_args = x509_verify_args,
78 .sigs = x509_sigs,
79 .verify_signed_buffer = verify_gpg_signed_buffer,
80 .sign_buffer = sign_buffer_gpg,
81 .get_default_key = NULL,
84 .name = "ssh",
85 .program = "ssh-keygen",
86 .verify_args = ssh_verify_args,
87 .sigs = ssh_sigs,
88 .verify_signed_buffer = NULL, /* TODO */
89 .sign_buffer = sign_buffer_ssh,
90 .get_default_key = get_default_ssh_signing_key,
94 static struct gpg_format *use_format = &gpg_format[0];
96 static struct gpg_format *get_format_by_name(const char *str)
98 int i;
100 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
101 if (!strcmp(gpg_format[i].name, str))
102 return gpg_format + i;
103 return NULL;
106 static struct gpg_format *get_format_by_sig(const char *sig)
108 int i, j;
110 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
111 for (j = 0; gpg_format[i].sigs[j]; j++)
112 if (starts_with(sig, gpg_format[i].sigs[j]))
113 return gpg_format + i;
114 return NULL;
117 void signature_check_clear(struct signature_check *sigc)
119 FREE_AND_NULL(sigc->payload);
120 FREE_AND_NULL(sigc->output);
121 FREE_AND_NULL(sigc->gpg_status);
122 FREE_AND_NULL(sigc->signer);
123 FREE_AND_NULL(sigc->key);
124 FREE_AND_NULL(sigc->fingerprint);
125 FREE_AND_NULL(sigc->primary_key_fingerprint);
128 /* An exclusive status -- only one of them can appear in output */
129 #define GPG_STATUS_EXCLUSIVE (1<<0)
130 /* The status includes key identifier */
131 #define GPG_STATUS_KEYID (1<<1)
132 /* The status includes user identifier */
133 #define GPG_STATUS_UID (1<<2)
134 /* The status includes key fingerprints */
135 #define GPG_STATUS_FINGERPRINT (1<<3)
136 /* The status includes trust level */
137 #define GPG_STATUS_TRUST_LEVEL (1<<4)
139 /* Short-hand for standard exclusive *SIG status with keyid & UID */
140 #define GPG_STATUS_STDSIG (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
142 static struct {
143 char result;
144 const char *check;
145 unsigned int flags;
146 } sigcheck_gpg_status[] = {
147 { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
148 { 'B', "BADSIG ", GPG_STATUS_STDSIG },
149 { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
150 { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
151 { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
152 { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
153 { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
154 { 0, "TRUST_", GPG_STATUS_TRUST_LEVEL },
157 static struct {
158 const char *key;
159 enum signature_trust_level value;
160 } sigcheck_gpg_trust_level[] = {
161 { "UNDEFINED", TRUST_UNDEFINED },
162 { "NEVER", TRUST_NEVER },
163 { "MARGINAL", TRUST_MARGINAL },
164 { "FULLY", TRUST_FULLY },
165 { "ULTIMATE", TRUST_ULTIMATE },
168 static void replace_cstring(char **field, const char *line, const char *next)
170 free(*field);
172 if (line && next)
173 *field = xmemdupz(line, next - line);
174 else
175 *field = NULL;
178 static int parse_gpg_trust_level(const char *level,
179 enum signature_trust_level *res)
181 size_t i;
183 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_trust_level); i++) {
184 if (!strcmp(sigcheck_gpg_trust_level[i].key, level)) {
185 *res = sigcheck_gpg_trust_level[i].value;
186 return 0;
189 return 1;
192 static void parse_gpg_output(struct signature_check *sigc)
194 const char *buf = sigc->gpg_status;
195 const char *line, *next;
196 int i, j;
197 int seen_exclusive_status = 0;
199 /* Iterate over all lines */
200 for (line = buf; *line; line = strchrnul(line+1, '\n')) {
201 while (*line == '\n')
202 line++;
203 if (!*line)
204 break;
206 /* Skip lines that don't start with GNUPG status */
207 if (!skip_prefix(line, "[GNUPG:] ", &line))
208 continue;
210 /* Iterate over all search strings */
211 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
212 if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
214 * GOODSIG, BADSIG etc. can occur only once for
215 * each signature. Therefore, if we had more
216 * than one then we're dealing with multiple
217 * signatures. We don't support them
218 * currently, and they're rather hard to
219 * create, so something is likely fishy and we
220 * should reject them altogether.
222 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
223 if (seen_exclusive_status++)
224 goto error;
227 if (sigcheck_gpg_status[i].result)
228 sigc->result = sigcheck_gpg_status[i].result;
229 /* Do we have key information? */
230 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
231 next = strchrnul(line, ' ');
232 replace_cstring(&sigc->key, line, next);
233 /* Do we have signer information? */
234 if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
235 line = next + 1;
236 next = strchrnul(line, '\n');
237 replace_cstring(&sigc->signer, line, next);
241 /* Do we have trust level? */
242 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
244 * GPG v1 and v2 differs in how the
245 * TRUST_ lines are written. Some
246 * trust lines contain no additional
247 * space-separated information for v1.
249 size_t trust_size = strcspn(line, " \n");
250 char *trust = xmemdupz(line, trust_size);
252 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
253 free(trust);
254 goto error;
256 free(trust);
259 /* Do we have fingerprint? */
260 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
261 const char *limit;
262 char **field;
264 next = strchrnul(line, ' ');
265 replace_cstring(&sigc->fingerprint, line, next);
268 * Skip interim fields. The search is
269 * limited to the same line since only
270 * OpenPGP signatures has a field with
271 * the primary fingerprint.
273 limit = strchrnul(line, '\n');
274 for (j = 9; j > 0; j--) {
275 if (!*next || limit <= next)
276 break;
277 line = next + 1;
278 next = strchrnul(line, ' ');
281 field = &sigc->primary_key_fingerprint;
282 if (!j) {
283 next = strchrnul(line, '\n');
284 replace_cstring(field, line, next);
285 } else {
286 replace_cstring(field, NULL, NULL);
290 break;
294 return;
296 error:
297 sigc->result = 'E';
298 /* Clear partial data to avoid confusion */
299 FREE_AND_NULL(sigc->primary_key_fingerprint);
300 FREE_AND_NULL(sigc->fingerprint);
301 FREE_AND_NULL(sigc->signer);
302 FREE_AND_NULL(sigc->key);
305 static int verify_gpg_signed_buffer(struct signature_check *sigc,
306 struct gpg_format *fmt, const char *payload,
307 size_t payload_size, const char *signature,
308 size_t signature_size)
310 struct child_process gpg = CHILD_PROCESS_INIT;
311 struct tempfile *temp;
312 int ret;
313 struct strbuf gpg_stdout = STRBUF_INIT;
314 struct strbuf gpg_stderr = STRBUF_INIT;
316 temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
317 if (!temp)
318 return error_errno(_("could not create temporary file"));
319 if (write_in_full(temp->fd, signature, signature_size) < 0 ||
320 close_tempfile_gently(temp) < 0) {
321 error_errno(_("failed writing detached signature to '%s'"),
322 temp->filename.buf);
323 delete_tempfile(&temp);
324 return -1;
327 strvec_push(&gpg.args, fmt->program);
328 strvec_pushv(&gpg.args, fmt->verify_args);
329 strvec_pushl(&gpg.args,
330 "--status-fd=1",
331 "--verify", temp->filename.buf, "-",
332 NULL);
334 sigchain_push(SIGPIPE, SIG_IGN);
335 ret = pipe_command(&gpg, payload, payload_size, &gpg_stdout, 0,
336 &gpg_stderr, 0);
337 sigchain_pop(SIGPIPE);
339 delete_tempfile(&temp);
341 ret |= !strstr(gpg_stdout.buf, "\n[GNUPG:] GOODSIG ");
342 sigc->payload = xmemdupz(payload, payload_size);
343 sigc->output = strbuf_detach(&gpg_stderr, NULL);
344 sigc->gpg_status = strbuf_detach(&gpg_stdout, NULL);
346 parse_gpg_output(sigc);
348 strbuf_release(&gpg_stdout);
349 strbuf_release(&gpg_stderr);
351 return ret;
354 int check_signature(const char *payload, size_t plen, const char *signature,
355 size_t slen, struct signature_check *sigc)
357 struct gpg_format *fmt;
358 int status;
360 sigc->result = 'N';
361 sigc->trust_level = -1;
363 fmt = get_format_by_sig(signature);
364 if (!fmt)
365 die(_("bad/incompatible signature '%s'"), signature);
367 status = fmt->verify_signed_buffer(sigc, fmt, payload, plen, signature,
368 slen);
370 if (status && !sigc->output)
371 return !!status;
373 status |= sigc->result != 'G';
374 status |= sigc->trust_level < configured_min_trust_level;
376 return !!status;
379 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
381 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
382 sigc->output;
384 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
385 fputs(sigc->payload, stdout);
387 if (output)
388 fputs(output, stderr);
391 size_t parse_signed_buffer(const char *buf, size_t size)
393 size_t len = 0;
394 size_t match = size;
395 while (len < size) {
396 const char *eol;
398 if (get_format_by_sig(buf + len))
399 match = len;
401 eol = memchr(buf + len, '\n', size - len);
402 len += eol ? eol - (buf + len) + 1 : size - len;
404 return match;
407 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
409 size_t match = parse_signed_buffer(buf, size);
410 if (match != size) {
411 strbuf_add(payload, buf, match);
412 remove_signature(payload);
413 strbuf_add(signature, buf + match, size - match);
414 return 1;
416 return 0;
419 void set_signing_key(const char *key)
421 free(configured_signing_key);
422 configured_signing_key = xstrdup(key);
425 int git_gpg_config(const char *var, const char *value, void *cb)
427 struct gpg_format *fmt = NULL;
428 char *fmtname = NULL;
429 char *trust;
430 int ret;
432 if (!strcmp(var, "user.signingkey")) {
433 if (!value)
434 return config_error_nonbool(var);
435 set_signing_key(value);
436 return 0;
439 if (!strcmp(var, "gpg.format")) {
440 if (!value)
441 return config_error_nonbool(var);
442 fmt = get_format_by_name(value);
443 if (!fmt)
444 return error("unsupported value for %s: %s",
445 var, value);
446 use_format = fmt;
447 return 0;
450 if (!strcmp(var, "gpg.mintrustlevel")) {
451 if (!value)
452 return config_error_nonbool(var);
454 trust = xstrdup_toupper(value);
455 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
456 free(trust);
458 if (ret)
459 return error("unsupported value for %s: %s", var,
460 value);
461 return 0;
464 if (!strcmp(var, "gpg.ssh.defaultkeycommand")) {
465 if (!value)
466 return config_error_nonbool(var);
467 return git_config_string(&ssh_default_key_command, var, value);
470 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
471 fmtname = "openpgp";
473 if (!strcmp(var, "gpg.x509.program"))
474 fmtname = "x509";
476 if (!strcmp(var, "gpg.ssh.program"))
477 fmtname = "ssh";
479 if (fmtname) {
480 fmt = get_format_by_name(fmtname);
481 return git_config_string(&fmt->program, var, value);
484 return 0;
487 /* Returns the first public key from an ssh-agent to use for signing */
488 static const char *get_default_ssh_signing_key(void)
490 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
491 int ret = -1;
492 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
493 struct strbuf **keys;
494 char *key_command = NULL;
495 const char **argv;
496 int n;
497 char *default_key = NULL;
499 if (!ssh_default_key_command)
500 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
502 key_command = xstrdup(ssh_default_key_command);
503 n = split_cmdline(key_command, &argv);
505 if (n < 0)
506 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
507 split_cmdline_strerror(n));
509 strvec_pushv(&ssh_default_key.args, argv);
510 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
511 &key_stderr, 0);
513 if (!ret) {
514 keys = strbuf_split_max(&key_stdout, '\n', 2);
515 if (keys[0] && starts_with(keys[0]->buf, "ssh-")) {
516 default_key = strbuf_detach(keys[0], NULL);
517 } else {
518 warning(_("gpg.ssh.defaultKeycommand succeeded but returned no keys: %s %s"),
519 key_stderr.buf, key_stdout.buf);
522 strbuf_list_free(keys);
523 } else {
524 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
525 key_stderr.buf, key_stdout.buf);
528 free(key_command);
529 free(argv);
530 strbuf_release(&key_stdout);
532 return default_key;
535 const char *get_signing_key(void)
537 if (configured_signing_key)
538 return configured_signing_key;
539 if (use_format->get_default_key) {
540 return use_format->get_default_key();
543 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
546 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
548 return use_format->sign_buffer(buffer, signature, signing_key);
552 * Strip CR from the line endings, in case we are on Windows.
553 * NEEDSWORK: make it trim only CRs before LFs and rename
555 static void remove_cr_after(struct strbuf *buffer, size_t offset)
557 size_t i, j;
559 for (i = j = offset; i < buffer->len; i++) {
560 if (buffer->buf[i] != '\r') {
561 if (i != j)
562 buffer->buf[j] = buffer->buf[i];
563 j++;
566 strbuf_setlen(buffer, j);
569 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
570 const char *signing_key)
572 struct child_process gpg = CHILD_PROCESS_INIT;
573 int ret;
574 size_t bottom;
575 struct strbuf gpg_status = STRBUF_INIT;
577 strvec_pushl(&gpg.args,
578 use_format->program,
579 "--status-fd=2",
580 "-bsau", signing_key,
581 NULL);
583 bottom = signature->len;
586 * When the username signingkey is bad, program could be terminated
587 * because gpg exits without reading and then write gets SIGPIPE.
589 sigchain_push(SIGPIPE, SIG_IGN);
590 ret = pipe_command(&gpg, buffer->buf, buffer->len,
591 signature, 1024, &gpg_status, 0);
592 sigchain_pop(SIGPIPE);
594 ret |= !strstr(gpg_status.buf, "\n[GNUPG:] SIG_CREATED ");
595 strbuf_release(&gpg_status);
596 if (ret)
597 return error(_("gpg failed to sign the data"));
599 /* Strip CR from the line endings, in case we are on Windows. */
600 remove_cr_after(signature, bottom);
602 return 0;
605 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
606 const char *signing_key)
608 struct child_process signer = CHILD_PROCESS_INIT;
609 int ret = -1;
610 size_t bottom, keylen;
611 struct strbuf signer_stderr = STRBUF_INIT;
612 struct tempfile *key_file = NULL, *buffer_file = NULL;
613 char *ssh_signing_key_file = NULL;
614 struct strbuf ssh_signature_filename = STRBUF_INIT;
616 if (!signing_key || signing_key[0] == '\0')
617 return error(
618 _("user.signingkey needs to be set for ssh signing"));
620 if (starts_with(signing_key, "ssh-")) {
621 /* A literal ssh key */
622 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
623 if (!key_file)
624 return error_errno(
625 _("could not create temporary file"));
626 keylen = strlen(signing_key);
627 if (write_in_full(key_file->fd, signing_key, keylen) < 0 ||
628 close_tempfile_gently(key_file) < 0) {
629 error_errno(_("failed writing ssh signing key to '%s'"),
630 key_file->filename.buf);
631 goto out;
633 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
634 } else {
635 /* We assume a file */
636 ssh_signing_key_file = expand_user_path(signing_key, 1);
639 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
640 if (!buffer_file) {
641 error_errno(_("could not create temporary file"));
642 goto out;
645 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
646 close_tempfile_gently(buffer_file) < 0) {
647 error_errno(_("failed writing ssh signing key buffer to '%s'"),
648 buffer_file->filename.buf);
649 goto out;
652 strvec_pushl(&signer.args, use_format->program,
653 "-Y", "sign",
654 "-n", "git",
655 "-f", ssh_signing_key_file,
656 buffer_file->filename.buf,
657 NULL);
659 sigchain_push(SIGPIPE, SIG_IGN);
660 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
661 sigchain_pop(SIGPIPE);
663 if (ret) {
664 if (strstr(signer_stderr.buf, "usage:"))
665 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
667 error("%s", signer_stderr.buf);
668 goto out;
671 bottom = signature->len;
673 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
674 strbuf_addstr(&ssh_signature_filename, ".sig");
675 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
676 error_errno(
677 _("failed reading ssh signing data buffer from '%s'"),
678 ssh_signature_filename.buf);
680 unlink_or_warn(ssh_signature_filename.buf);
682 /* Strip CR from the line endings, in case we are on Windows. */
683 remove_cr_after(signature, bottom);
685 out:
686 if (key_file)
687 delete_tempfile(&key_file);
688 if (buffer_file)
689 delete_tempfile(&buffer_file);
690 strbuf_release(&signer_stderr);
691 strbuf_release(&ssh_signature_filename);
692 FREE_AND_NULL(ssh_signing_key_file);
693 return ret;