Merge branch 'vd/adjust-mfow-doc-to-updated-headers'
[git/debian.git] / gpg-interface.c
blobf7c1d385c1f6ec068da2886395aba78d8d8a8e5b
1 #include "git-compat-util.h"
2 #include "commit.h"
3 #include "config.h"
4 #include "date.h"
5 #include "gettext.h"
6 #include "run-command.h"
7 #include "strbuf.h"
8 #include "dir.h"
9 #include "ident.h"
10 #include "gpg-interface.h"
11 #include "path.h"
12 #include "sigchain.h"
13 #include "tempfile.h"
14 #include "alias.h"
15 #include "wrapper.h"
16 #include "environment.h"
18 static int git_gpg_config(const char *, const char *,
19 const struct config_context *, void *);
21 static void gpg_interface_lazy_init(void)
23 static int done;
25 if (done)
26 return;
27 done = 1;
28 git_config(git_gpg_config, NULL);
31 static char *configured_signing_key;
32 static const char *ssh_default_key_command, *ssh_allowed_signers, *ssh_revocation_file;
33 static enum signature_trust_level configured_min_trust_level = TRUST_UNDEFINED;
35 struct gpg_format {
36 const char *name;
37 const char *program;
38 const char **verify_args;
39 const char **sigs;
40 int (*verify_signed_buffer)(struct signature_check *sigc,
41 struct gpg_format *fmt,
42 const char *signature,
43 size_t signature_size);
44 int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
45 const char *signing_key);
46 const char *(*get_default_key)(void);
47 const char *(*get_key_id)(void);
50 static const char *openpgp_verify_args[] = {
51 "--keyid-format=long",
52 NULL
54 static const char *openpgp_sigs[] = {
55 "-----BEGIN PGP SIGNATURE-----",
56 "-----BEGIN PGP MESSAGE-----",
57 NULL
60 static const char *x509_verify_args[] = {
61 NULL
63 static const char *x509_sigs[] = {
64 "-----BEGIN SIGNED MESSAGE-----",
65 NULL
68 static const char *ssh_verify_args[] = { NULL };
69 static const char *ssh_sigs[] = {
70 "-----BEGIN SSH SIGNATURE-----",
71 NULL
74 static int verify_gpg_signed_buffer(struct signature_check *sigc,
75 struct gpg_format *fmt,
76 const char *signature,
77 size_t signature_size);
78 static int verify_ssh_signed_buffer(struct signature_check *sigc,
79 struct gpg_format *fmt,
80 const char *signature,
81 size_t signature_size);
82 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
83 const char *signing_key);
84 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
85 const char *signing_key);
87 static const char *get_default_ssh_signing_key(void);
89 static const char *get_ssh_key_id(void);
91 static struct gpg_format gpg_format[] = {
93 .name = "openpgp",
94 .program = "gpg",
95 .verify_args = openpgp_verify_args,
96 .sigs = openpgp_sigs,
97 .verify_signed_buffer = verify_gpg_signed_buffer,
98 .sign_buffer = sign_buffer_gpg,
99 .get_default_key = NULL,
100 .get_key_id = NULL,
103 .name = "x509",
104 .program = "gpgsm",
105 .verify_args = x509_verify_args,
106 .sigs = x509_sigs,
107 .verify_signed_buffer = verify_gpg_signed_buffer,
108 .sign_buffer = sign_buffer_gpg,
109 .get_default_key = NULL,
110 .get_key_id = NULL,
113 .name = "ssh",
114 .program = "ssh-keygen",
115 .verify_args = ssh_verify_args,
116 .sigs = ssh_sigs,
117 .verify_signed_buffer = verify_ssh_signed_buffer,
118 .sign_buffer = sign_buffer_ssh,
119 .get_default_key = get_default_ssh_signing_key,
120 .get_key_id = get_ssh_key_id,
124 static struct gpg_format *use_format = &gpg_format[0];
126 static struct gpg_format *get_format_by_name(const char *str)
128 int i;
130 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
131 if (!strcmp(gpg_format[i].name, str))
132 return gpg_format + i;
133 return NULL;
136 static struct gpg_format *get_format_by_sig(const char *sig)
138 int i, j;
140 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
141 for (j = 0; gpg_format[i].sigs[j]; j++)
142 if (starts_with(sig, gpg_format[i].sigs[j]))
143 return gpg_format + i;
144 return NULL;
147 void signature_check_clear(struct signature_check *sigc)
149 FREE_AND_NULL(sigc->payload);
150 FREE_AND_NULL(sigc->output);
151 FREE_AND_NULL(sigc->gpg_status);
152 FREE_AND_NULL(sigc->signer);
153 FREE_AND_NULL(sigc->key);
154 FREE_AND_NULL(sigc->fingerprint);
155 FREE_AND_NULL(sigc->primary_key_fingerprint);
158 /* An exclusive status -- only one of them can appear in output */
159 #define GPG_STATUS_EXCLUSIVE (1<<0)
160 /* The status includes key identifier */
161 #define GPG_STATUS_KEYID (1<<1)
162 /* The status includes user identifier */
163 #define GPG_STATUS_UID (1<<2)
164 /* The status includes key fingerprints */
165 #define GPG_STATUS_FINGERPRINT (1<<3)
166 /* The status includes trust level */
167 #define GPG_STATUS_TRUST_LEVEL (1<<4)
169 /* Short-hand for standard exclusive *SIG status with keyid & UID */
170 #define GPG_STATUS_STDSIG (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
172 static struct {
173 char result;
174 const char *check;
175 unsigned int flags;
176 } sigcheck_gpg_status[] = {
177 { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
178 { 'B', "BADSIG ", GPG_STATUS_STDSIG },
179 { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
180 { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
181 { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
182 { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
183 { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
184 { 0, "TRUST_", GPG_STATUS_TRUST_LEVEL },
187 /* Keep the order same as enum signature_trust_level */
188 static struct sigcheck_gpg_trust_level {
189 const char *key;
190 const char *display_key;
191 enum signature_trust_level value;
192 } sigcheck_gpg_trust_level[] = {
193 { "UNDEFINED", "undefined", TRUST_UNDEFINED },
194 { "NEVER", "never", TRUST_NEVER },
195 { "MARGINAL", "marginal", TRUST_MARGINAL },
196 { "FULLY", "fully", TRUST_FULLY },
197 { "ULTIMATE", "ultimate", TRUST_ULTIMATE },
200 static void replace_cstring(char **field, const char *line, const char *next)
202 free(*field);
204 if (line && next)
205 *field = xmemdupz(line, next - line);
206 else
207 *field = NULL;
210 static int parse_gpg_trust_level(const char *level,
211 enum signature_trust_level *res)
213 size_t i;
215 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_trust_level); i++) {
216 if (!strcmp(sigcheck_gpg_trust_level[i].key, level)) {
217 *res = sigcheck_gpg_trust_level[i].value;
218 return 0;
221 return 1;
224 static void parse_gpg_output(struct signature_check *sigc)
226 const char *buf = sigc->gpg_status;
227 const char *line, *next;
228 int i, j;
229 int seen_exclusive_status = 0;
231 /* Iterate over all lines */
232 for (line = buf; *line; line = strchrnul(line+1, '\n')) {
233 while (*line == '\n')
234 line++;
235 if (!*line)
236 break;
238 /* Skip lines that don't start with GNUPG status */
239 if (!skip_prefix(line, "[GNUPG:] ", &line))
240 continue;
242 /* Iterate over all search strings */
243 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
244 if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
246 * GOODSIG, BADSIG etc. can occur only once for
247 * each signature. Therefore, if we had more
248 * than one then we're dealing with multiple
249 * signatures. We don't support them
250 * currently, and they're rather hard to
251 * create, so something is likely fishy and we
252 * should reject them altogether.
254 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
255 if (seen_exclusive_status++)
256 goto error;
259 if (sigcheck_gpg_status[i].result)
260 sigc->result = sigcheck_gpg_status[i].result;
261 /* Do we have key information? */
262 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
263 next = strchrnul(line, ' ');
264 replace_cstring(&sigc->key, line, next);
265 /* Do we have signer information? */
266 if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
267 line = next + 1;
268 next = strchrnul(line, '\n');
269 replace_cstring(&sigc->signer, line, next);
273 /* Do we have trust level? */
274 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
276 * GPG v1 and v2 differs in how the
277 * TRUST_ lines are written. Some
278 * trust lines contain no additional
279 * space-separated information for v1.
281 size_t trust_size = strcspn(line, " \n");
282 char *trust = xmemdupz(line, trust_size);
284 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
285 free(trust);
286 goto error;
288 free(trust);
291 /* Do we have fingerprint? */
292 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
293 const char *limit;
294 char **field;
296 next = strchrnul(line, ' ');
297 replace_cstring(&sigc->fingerprint, line, next);
300 * Skip interim fields. The search is
301 * limited to the same line since only
302 * OpenPGP signatures has a field with
303 * the primary fingerprint.
305 limit = strchrnul(line, '\n');
306 for (j = 9; j > 0; j--) {
307 if (!*next || limit <= next)
308 break;
309 line = next + 1;
310 next = strchrnul(line, ' ');
313 field = &sigc->primary_key_fingerprint;
314 if (!j) {
315 next = strchrnul(line, '\n');
316 replace_cstring(field, line, next);
317 } else {
318 replace_cstring(field, NULL, NULL);
322 break;
326 return;
328 error:
329 sigc->result = 'E';
330 /* Clear partial data to avoid confusion */
331 FREE_AND_NULL(sigc->primary_key_fingerprint);
332 FREE_AND_NULL(sigc->fingerprint);
333 FREE_AND_NULL(sigc->signer);
334 FREE_AND_NULL(sigc->key);
337 static int verify_gpg_signed_buffer(struct signature_check *sigc,
338 struct gpg_format *fmt,
339 const char *signature,
340 size_t signature_size)
342 struct child_process gpg = CHILD_PROCESS_INIT;
343 struct tempfile *temp;
344 int ret;
345 struct strbuf gpg_stdout = STRBUF_INIT;
346 struct strbuf gpg_stderr = STRBUF_INIT;
348 temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
349 if (!temp)
350 return error_errno(_("could not create temporary file"));
351 if (write_in_full(temp->fd, signature, signature_size) < 0 ||
352 close_tempfile_gently(temp) < 0) {
353 error_errno(_("failed writing detached signature to '%s'"),
354 temp->filename.buf);
355 delete_tempfile(&temp);
356 return -1;
359 strvec_push(&gpg.args, fmt->program);
360 strvec_pushv(&gpg.args, fmt->verify_args);
361 strvec_pushl(&gpg.args,
362 "--status-fd=1",
363 "--verify", temp->filename.buf, "-",
364 NULL);
366 sigchain_push(SIGPIPE, SIG_IGN);
367 ret = pipe_command(&gpg, sigc->payload, sigc->payload_len, &gpg_stdout, 0,
368 &gpg_stderr, 0);
369 sigchain_pop(SIGPIPE);
371 delete_tempfile(&temp);
373 ret |= !strstr(gpg_stdout.buf, "\n[GNUPG:] GOODSIG ");
374 sigc->output = strbuf_detach(&gpg_stderr, NULL);
375 sigc->gpg_status = strbuf_detach(&gpg_stdout, NULL);
377 parse_gpg_output(sigc);
379 strbuf_release(&gpg_stdout);
380 strbuf_release(&gpg_stderr);
382 return ret;
385 static void parse_ssh_output(struct signature_check *sigc)
387 const char *line, *principal, *search;
388 char *to_free;
389 char *key = NULL;
392 * ssh-keygen output should be:
393 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
395 * or for valid but unknown keys:
396 * Good "git" signature with RSA key SHA256:FINGERPRINT
398 * Note that "PRINCIPAL" can contain whitespace, "RSA" and
399 * "SHA256" part could be a different token that names of
400 * the algorithms used, and "FINGERPRINT" is a hexadecimal
401 * string. By finding the last occurence of " with ", we can
402 * reliably parse out the PRINCIPAL.
404 sigc->result = 'B';
405 sigc->trust_level = TRUST_NEVER;
407 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
409 if (skip_prefix(line, "Good \"git\" signature for ", &line)) {
410 /* Search for the last "with" to get the full principal */
411 principal = line;
412 do {
413 search = strstr(line, " with ");
414 if (search)
415 line = search + 1;
416 } while (search != NULL);
417 if (line == principal)
418 goto cleanup;
420 /* Valid signature and known principal */
421 sigc->result = 'G';
422 sigc->trust_level = TRUST_FULLY;
423 sigc->signer = xmemdupz(principal, line - principal - 1);
424 } else if (skip_prefix(line, "Good \"git\" signature with ", &line)) {
425 /* Valid signature, but key unknown */
426 sigc->result = 'G';
427 sigc->trust_level = TRUST_UNDEFINED;
428 } else {
429 goto cleanup;
432 key = strstr(line, "key ");
433 if (key) {
434 sigc->fingerprint = xstrdup(strstr(line, "key ") + 4);
435 sigc->key = xstrdup(sigc->fingerprint);
436 } else {
438 * Output did not match what we expected
439 * Treat the signature as bad
441 sigc->result = 'B';
444 cleanup:
445 free(to_free);
448 static int verify_ssh_signed_buffer(struct signature_check *sigc,
449 struct gpg_format *fmt,
450 const char *signature,
451 size_t signature_size)
453 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
454 struct tempfile *buffer_file;
455 int ret = -1;
456 const char *line;
457 char *principal;
458 struct strbuf ssh_principals_out = STRBUF_INIT;
459 struct strbuf ssh_principals_err = STRBUF_INIT;
460 struct strbuf ssh_keygen_out = STRBUF_INIT;
461 struct strbuf ssh_keygen_err = STRBUF_INIT;
462 struct strbuf verify_time = STRBUF_INIT;
463 const struct date_mode verify_date_mode = {
464 .type = DATE_STRFTIME,
465 .strftime_fmt = "%Y%m%d%H%M%S",
466 /* SSH signing key validity has no timezone information - Use the local timezone */
467 .local = 1,
470 if (!ssh_allowed_signers) {
471 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
472 return -1;
475 buffer_file = mks_tempfile_t(".git_vtag_tmpXXXXXX");
476 if (!buffer_file)
477 return error_errno(_("could not create temporary file"));
478 if (write_in_full(buffer_file->fd, signature, signature_size) < 0 ||
479 close_tempfile_gently(buffer_file) < 0) {
480 error_errno(_("failed writing detached signature to '%s'"),
481 buffer_file->filename.buf);
482 delete_tempfile(&buffer_file);
483 return -1;
486 if (sigc->payload_timestamp)
487 strbuf_addf(&verify_time, "-Overify-time=%s",
488 show_date(sigc->payload_timestamp, 0, &verify_date_mode));
490 /* Find the principal from the signers */
491 strvec_pushl(&ssh_keygen.args, fmt->program,
492 "-Y", "find-principals",
493 "-f", ssh_allowed_signers,
494 "-s", buffer_file->filename.buf,
495 verify_time.buf,
496 NULL);
497 ret = pipe_command(&ssh_keygen, NULL, 0, &ssh_principals_out, 0,
498 &ssh_principals_err, 0);
499 if (ret && strstr(ssh_principals_err.buf, "usage:")) {
500 error(_("ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"));
501 goto out;
503 if (ret || !ssh_principals_out.len) {
505 * We did not find a matching principal in the allowedSigners
506 * Check without validation
508 child_process_init(&ssh_keygen);
509 strvec_pushl(&ssh_keygen.args, fmt->program,
510 "-Y", "check-novalidate",
511 "-n", "git",
512 "-s", buffer_file->filename.buf,
513 verify_time.buf,
514 NULL);
515 pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
516 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
519 * Fail on unknown keys
520 * we still call check-novalidate to display the signature info
522 ret = -1;
523 } else {
524 /* Check every principal we found (one per line) */
525 const char *next;
526 for (line = ssh_principals_out.buf;
527 *line;
528 line = next) {
529 const char *end_of_text;
531 next = end_of_text = strchrnul(line, '\n');
533 /* Did we find a LF, and did we have CR before it? */
534 if (*end_of_text &&
535 line < end_of_text &&
536 end_of_text[-1] == '\r')
537 end_of_text--;
539 /* Unless we hit NUL, skip over the LF we found */
540 if (*next)
541 next++;
543 /* Not all lines are data. Skip empty ones */
544 if (line == end_of_text)
545 continue;
547 /* We now know we have an non-empty line. Process it */
548 principal = xmemdupz(line, end_of_text - line);
550 child_process_init(&ssh_keygen);
551 strbuf_release(&ssh_keygen_out);
552 strbuf_release(&ssh_keygen_err);
553 strvec_push(&ssh_keygen.args, fmt->program);
555 * We found principals
556 * Try with each until we find a match
558 strvec_pushl(&ssh_keygen.args, "-Y", "verify",
559 "-n", "git",
560 "-f", ssh_allowed_signers,
561 "-I", principal,
562 "-s", buffer_file->filename.buf,
563 verify_time.buf,
564 NULL);
566 if (ssh_revocation_file) {
567 if (file_exists(ssh_revocation_file)) {
568 strvec_pushl(&ssh_keygen.args, "-r",
569 ssh_revocation_file, NULL);
570 } else {
571 warning(_("ssh signing revocation file configured but not found: %s"),
572 ssh_revocation_file);
576 sigchain_push(SIGPIPE, SIG_IGN);
577 ret = pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
578 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
579 sigchain_pop(SIGPIPE);
581 FREE_AND_NULL(principal);
583 if (!ret)
584 ret = !starts_with(ssh_keygen_out.buf, "Good");
586 if (!ret)
587 break;
591 strbuf_stripspace(&ssh_keygen_out, '\0');
592 strbuf_stripspace(&ssh_keygen_err, '\0');
593 /* Add stderr outputs to show the user actual ssh-keygen errors */
594 strbuf_add(&ssh_keygen_out, ssh_principals_err.buf, ssh_principals_err.len);
595 strbuf_add(&ssh_keygen_out, ssh_keygen_err.buf, ssh_keygen_err.len);
596 sigc->output = strbuf_detach(&ssh_keygen_out, NULL);
597 sigc->gpg_status = xstrdup(sigc->output);
599 parse_ssh_output(sigc);
601 out:
602 if (buffer_file)
603 delete_tempfile(&buffer_file);
604 strbuf_release(&ssh_principals_out);
605 strbuf_release(&ssh_principals_err);
606 strbuf_release(&ssh_keygen_out);
607 strbuf_release(&ssh_keygen_err);
608 strbuf_release(&verify_time);
610 return ret;
613 static int parse_payload_metadata(struct signature_check *sigc)
615 const char *ident_line = NULL;
616 size_t ident_len;
617 struct ident_split ident;
618 const char *signer_header;
620 switch (sigc->payload_type) {
621 case SIGNATURE_PAYLOAD_COMMIT:
622 signer_header = "committer";
623 break;
624 case SIGNATURE_PAYLOAD_TAG:
625 signer_header = "tagger";
626 break;
627 case SIGNATURE_PAYLOAD_UNDEFINED:
628 case SIGNATURE_PAYLOAD_PUSH_CERT:
629 /* Ignore payloads we don't want to parse */
630 return 0;
631 default:
632 BUG("invalid value for sigc->payload_type");
635 ident_line = find_commit_header(sigc->payload, signer_header, &ident_len);
636 if (!ident_line || !ident_len)
637 return 1;
639 if (split_ident_line(&ident, ident_line, ident_len))
640 return 1;
642 if (!sigc->payload_timestamp && ident.date_begin && ident.date_end)
643 sigc->payload_timestamp = parse_timestamp(ident.date_begin, NULL, 10);
645 return 0;
648 int check_signature(struct signature_check *sigc,
649 const char *signature, size_t slen)
651 struct gpg_format *fmt;
652 int status;
654 gpg_interface_lazy_init();
656 sigc->result = 'N';
657 sigc->trust_level = TRUST_UNDEFINED;
659 fmt = get_format_by_sig(signature);
660 if (!fmt)
661 die(_("bad/incompatible signature '%s'"), signature);
663 if (parse_payload_metadata(sigc))
664 return 1;
666 status = fmt->verify_signed_buffer(sigc, fmt, signature, slen);
668 if (status && !sigc->output)
669 return !!status;
671 status |= sigc->result != 'G';
672 status |= sigc->trust_level < configured_min_trust_level;
674 return !!status;
677 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
679 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
680 sigc->output;
682 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
683 fwrite(sigc->payload, 1, sigc->payload_len, stdout);
685 if (output)
686 fputs(output, stderr);
689 size_t parse_signed_buffer(const char *buf, size_t size)
691 size_t len = 0;
692 size_t match = size;
693 while (len < size) {
694 const char *eol;
696 if (get_format_by_sig(buf + len))
697 match = len;
699 eol = memchr(buf + len, '\n', size - len);
700 len += eol ? eol - (buf + len) + 1 : size - len;
702 return match;
705 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
707 size_t match = parse_signed_buffer(buf, size);
708 if (match != size) {
709 strbuf_add(payload, buf, match);
710 remove_signature(payload);
711 strbuf_add(signature, buf + match, size - match);
712 return 1;
714 return 0;
717 void set_signing_key(const char *key)
719 gpg_interface_lazy_init();
721 free(configured_signing_key);
722 configured_signing_key = xstrdup(key);
725 static int git_gpg_config(const char *var, const char *value,
726 const struct config_context *ctx UNUSED,
727 void *cb UNUSED)
729 struct gpg_format *fmt = NULL;
730 char *fmtname = NULL;
731 char *trust;
732 int ret;
734 if (!strcmp(var, "user.signingkey")) {
735 if (!value)
736 return config_error_nonbool(var);
737 set_signing_key(value);
738 return 0;
741 if (!strcmp(var, "gpg.format")) {
742 if (!value)
743 return config_error_nonbool(var);
744 fmt = get_format_by_name(value);
745 if (!fmt)
746 return error(_("invalid value for '%s': '%s'"),
747 var, value);
748 use_format = fmt;
749 return 0;
752 if (!strcmp(var, "gpg.mintrustlevel")) {
753 if (!value)
754 return config_error_nonbool(var);
756 trust = xstrdup_toupper(value);
757 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
758 free(trust);
760 if (ret)
761 return error(_("invalid value for '%s': '%s'"),
762 var, value);
763 return 0;
766 if (!strcmp(var, "gpg.ssh.defaultkeycommand")) {
767 if (!value)
768 return config_error_nonbool(var);
769 return git_config_string(&ssh_default_key_command, var, value);
772 if (!strcmp(var, "gpg.ssh.allowedsignersfile")) {
773 if (!value)
774 return config_error_nonbool(var);
775 return git_config_pathname(&ssh_allowed_signers, var, value);
778 if (!strcmp(var, "gpg.ssh.revocationfile")) {
779 if (!value)
780 return config_error_nonbool(var);
781 return git_config_pathname(&ssh_revocation_file, var, value);
784 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
785 fmtname = "openpgp";
787 if (!strcmp(var, "gpg.x509.program"))
788 fmtname = "x509";
790 if (!strcmp(var, "gpg.ssh.program"))
791 fmtname = "ssh";
793 if (fmtname) {
794 fmt = get_format_by_name(fmtname);
795 return git_config_string(&fmt->program, var, value);
798 return 0;
802 * Returns 1 if `string` contains a literal ssh key, 0 otherwise
803 * `key` will be set to the start of the actual key if a prefix is present.
805 static int is_literal_ssh_key(const char *string, const char **key)
807 if (skip_prefix(string, "key::", key))
808 return 1;
809 if (starts_with(string, "ssh-")) {
810 *key = string;
811 return 1;
813 return 0;
816 static char *get_ssh_key_fingerprint(const char *signing_key)
818 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
819 int ret = -1;
820 struct strbuf fingerprint_stdout = STRBUF_INIT;
821 struct strbuf **fingerprint;
822 char *fingerprint_ret;
823 const char *literal_key = NULL;
826 * With SSH Signing this can contain a filename or a public key
827 * For textual representation we usually want a fingerprint
829 if (is_literal_ssh_key(signing_key, &literal_key)) {
830 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
831 ret = pipe_command(&ssh_keygen, literal_key,
832 strlen(literal_key), &fingerprint_stdout, 0,
833 NULL, 0);
834 } else {
835 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
836 configured_signing_key, NULL);
837 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
838 NULL, 0);
841 if (!!ret)
842 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
843 signing_key);
845 fingerprint = strbuf_split_max(&fingerprint_stdout, ' ', 3);
846 if (!fingerprint[1])
847 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
848 signing_key);
850 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
851 strbuf_list_free(fingerprint);
852 strbuf_release(&fingerprint_stdout);
853 return fingerprint_ret;
856 /* Returns the first public key from an ssh-agent to use for signing */
857 static const char *get_default_ssh_signing_key(void)
859 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
860 int ret = -1;
861 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
862 struct strbuf **keys;
863 char *key_command = NULL;
864 const char **argv;
865 int n;
866 char *default_key = NULL;
867 const char *literal_key = NULL;
869 if (!ssh_default_key_command)
870 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
872 key_command = xstrdup(ssh_default_key_command);
873 n = split_cmdline(key_command, &argv);
875 if (n < 0)
876 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
877 split_cmdline_strerror(n));
879 strvec_pushv(&ssh_default_key.args, argv);
880 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
881 &key_stderr, 0);
883 if (!ret) {
884 keys = strbuf_split_max(&key_stdout, '\n', 2);
885 if (keys[0] && is_literal_ssh_key(keys[0]->buf, &literal_key)) {
887 * We only use `is_literal_ssh_key` here to check validity
888 * The prefix will be stripped when the key is used.
890 default_key = strbuf_detach(keys[0], NULL);
891 } else {
892 warning(_("gpg.ssh.defaultKeyCommand succeeded but returned no keys: %s %s"),
893 key_stderr.buf, key_stdout.buf);
896 strbuf_list_free(keys);
897 } else {
898 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
899 key_stderr.buf, key_stdout.buf);
902 free(key_command);
903 free(argv);
904 strbuf_release(&key_stdout);
906 return default_key;
909 static const char *get_ssh_key_id(void) {
910 return get_ssh_key_fingerprint(get_signing_key());
913 /* Returns a textual but unique representation of the signing key */
914 const char *get_signing_key_id(void)
916 gpg_interface_lazy_init();
918 if (use_format->get_key_id) {
919 return use_format->get_key_id();
922 /* GPG/GPGSM only store a key id on this variable */
923 return get_signing_key();
926 const char *get_signing_key(void)
928 gpg_interface_lazy_init();
930 if (configured_signing_key)
931 return configured_signing_key;
932 if (use_format->get_default_key) {
933 return use_format->get_default_key();
936 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
939 const char *gpg_trust_level_to_str(enum signature_trust_level level)
941 struct sigcheck_gpg_trust_level *trust;
943 if (level < 0 || level >= ARRAY_SIZE(sigcheck_gpg_trust_level))
944 BUG("invalid trust level requested %d", level);
946 trust = &sigcheck_gpg_trust_level[level];
947 if (trust->value != level)
948 BUG("sigcheck_gpg_trust_level[] unsorted");
950 return sigcheck_gpg_trust_level[level].display_key;
953 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
955 gpg_interface_lazy_init();
957 return use_format->sign_buffer(buffer, signature, signing_key);
961 * Strip CR from the line endings, in case we are on Windows.
962 * NEEDSWORK: make it trim only CRs before LFs and rename
964 static void remove_cr_after(struct strbuf *buffer, size_t offset)
966 size_t i, j;
968 for (i = j = offset; i < buffer->len; i++) {
969 if (buffer->buf[i] != '\r') {
970 if (i != j)
971 buffer->buf[j] = buffer->buf[i];
972 j++;
975 strbuf_setlen(buffer, j);
978 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
979 const char *signing_key)
981 struct child_process gpg = CHILD_PROCESS_INIT;
982 int ret;
983 size_t bottom;
984 const char *cp;
985 struct strbuf gpg_status = STRBUF_INIT;
987 strvec_pushl(&gpg.args,
988 use_format->program,
989 "--status-fd=2",
990 "-bsau", signing_key,
991 NULL);
993 bottom = signature->len;
996 * When the username signingkey is bad, program could be terminated
997 * because gpg exits without reading and then write gets SIGPIPE.
999 sigchain_push(SIGPIPE, SIG_IGN);
1000 ret = pipe_command(&gpg, buffer->buf, buffer->len,
1001 signature, 1024, &gpg_status, 0);
1002 sigchain_pop(SIGPIPE);
1004 for (cp = gpg_status.buf;
1005 cp && (cp = strstr(cp, "[GNUPG:] SIG_CREATED "));
1006 cp++) {
1007 if (cp == gpg_status.buf || cp[-1] == '\n')
1008 break; /* found */
1010 ret |= !cp;
1011 if (ret) {
1012 error(_("gpg failed to sign the data:\n%s"),
1013 gpg_status.len ? gpg_status.buf : "(no gpg output)");
1014 strbuf_release(&gpg_status);
1015 return -1;
1017 strbuf_release(&gpg_status);
1019 /* Strip CR from the line endings, in case we are on Windows. */
1020 remove_cr_after(signature, bottom);
1022 return 0;
1025 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
1026 const char *signing_key)
1028 struct child_process signer = CHILD_PROCESS_INIT;
1029 int ret = -1;
1030 size_t bottom, keylen;
1031 struct strbuf signer_stderr = STRBUF_INIT;
1032 struct tempfile *key_file = NULL, *buffer_file = NULL;
1033 char *ssh_signing_key_file = NULL;
1034 struct strbuf ssh_signature_filename = STRBUF_INIT;
1035 const char *literal_key = NULL;
1036 int literal_ssh_key = 0;
1038 if (!signing_key || signing_key[0] == '\0')
1039 return error(
1040 _("user.signingKey needs to be set for ssh signing"));
1042 if (is_literal_ssh_key(signing_key, &literal_key)) {
1043 /* A literal ssh key */
1044 literal_ssh_key = 1;
1045 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
1046 if (!key_file)
1047 return error_errno(
1048 _("could not create temporary file"));
1049 keylen = strlen(literal_key);
1050 if (write_in_full(key_file->fd, literal_key, keylen) < 0 ||
1051 close_tempfile_gently(key_file) < 0) {
1052 error_errno(_("failed writing ssh signing key to '%s'"),
1053 key_file->filename.buf);
1054 goto out;
1056 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
1057 } else {
1058 /* We assume a file */
1059 ssh_signing_key_file = interpolate_path(signing_key, 1);
1062 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
1063 if (!buffer_file) {
1064 error_errno(_("could not create temporary file"));
1065 goto out;
1068 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
1069 close_tempfile_gently(buffer_file) < 0) {
1070 error_errno(_("failed writing ssh signing key buffer to '%s'"),
1071 buffer_file->filename.buf);
1072 goto out;
1075 strvec_pushl(&signer.args, use_format->program,
1076 "-Y", "sign",
1077 "-n", "git",
1078 "-f", ssh_signing_key_file,
1079 NULL);
1080 if (literal_ssh_key)
1081 strvec_push(&signer.args, "-U");
1082 strvec_push(&signer.args, buffer_file->filename.buf);
1084 sigchain_push(SIGPIPE, SIG_IGN);
1085 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
1086 sigchain_pop(SIGPIPE);
1088 if (ret) {
1089 if (strstr(signer_stderr.buf, "usage:"))
1090 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
1092 error("%s", signer_stderr.buf);
1093 goto out;
1096 bottom = signature->len;
1098 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
1099 strbuf_addstr(&ssh_signature_filename, ".sig");
1100 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
1101 ret = error_errno(
1102 _("failed reading ssh signing data buffer from '%s'"),
1103 ssh_signature_filename.buf);
1104 goto out;
1106 /* Strip CR from the line endings, in case we are on Windows. */
1107 remove_cr_after(signature, bottom);
1109 out:
1110 if (key_file)
1111 delete_tempfile(&key_file);
1112 if (buffer_file)
1113 delete_tempfile(&buffer_file);
1114 if (ssh_signature_filename.len)
1115 unlink_or_warn(ssh_signature_filename.buf);
1116 strbuf_release(&signer_stderr);
1117 strbuf_release(&ssh_signature_filename);
1118 FREE_AND_NULL(ssh_signing_key_file);
1119 return ret;