Merge branch 'ps/document-breaking-changes' into next
[git.git] / gpg-interface.c
blob5c824aeb257cb94ccb16297e17fa00df973fd36c
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"
16 static int git_gpg_config(const char *, const char *,
17 const struct config_context *, void *);
19 static void gpg_interface_lazy_init(void)
21 static int done;
23 if (done)
24 return;
25 done = 1;
26 git_config(git_gpg_config, NULL);
29 static char *configured_signing_key;
30 static char *ssh_default_key_command;
31 static char *ssh_allowed_signers;
32 static char *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, NULL);
592 strbuf_stripspace(&ssh_keygen_err, NULL);
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 const 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 return git_config_string(&ssh_default_key_command, var, value);
769 if (!strcmp(var, "gpg.ssh.allowedsignersfile"))
770 return git_config_pathname(&ssh_allowed_signers, var, value);
772 if (!strcmp(var, "gpg.ssh.revocationfile"))
773 return git_config_pathname(&ssh_revocation_file, var, value);
775 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
776 fmtname = "openpgp";
778 if (!strcmp(var, "gpg.x509.program"))
779 fmtname = "x509";
781 if (!strcmp(var, "gpg.ssh.program"))
782 fmtname = "ssh";
784 if (fmtname) {
785 fmt = get_format_by_name(fmtname);
786 return git_config_string((char **) &fmt->program, var, value);
789 return 0;
793 * Returns 1 if `string` contains a literal ssh key, 0 otherwise
794 * `key` will be set to the start of the actual key if a prefix is present.
796 static int is_literal_ssh_key(const char *string, const char **key)
798 if (skip_prefix(string, "key::", key))
799 return 1;
800 if (starts_with(string, "ssh-")) {
801 *key = string;
802 return 1;
804 return 0;
807 static char *get_ssh_key_fingerprint(const char *signing_key)
809 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
810 int ret = -1;
811 struct strbuf fingerprint_stdout = STRBUF_INIT;
812 struct strbuf **fingerprint;
813 char *fingerprint_ret;
814 const char *literal_key = NULL;
817 * With SSH Signing this can contain a filename or a public key
818 * For textual representation we usually want a fingerprint
820 if (is_literal_ssh_key(signing_key, &literal_key)) {
821 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
822 ret = pipe_command(&ssh_keygen, literal_key,
823 strlen(literal_key), &fingerprint_stdout, 0,
824 NULL, 0);
825 } else {
826 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
827 configured_signing_key, NULL);
828 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
829 NULL, 0);
832 if (!!ret)
833 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
834 signing_key);
836 fingerprint = strbuf_split_max(&fingerprint_stdout, ' ', 3);
837 if (!fingerprint[1])
838 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
839 signing_key);
841 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
842 strbuf_list_free(fingerprint);
843 strbuf_release(&fingerprint_stdout);
844 return fingerprint_ret;
847 /* Returns the first public key from an ssh-agent to use for signing */
848 static const char *get_default_ssh_signing_key(void)
850 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
851 int ret = -1;
852 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
853 struct strbuf **keys;
854 char *key_command = NULL;
855 const char **argv;
856 int n;
857 char *default_key = NULL;
858 const char *literal_key = NULL;
860 if (!ssh_default_key_command)
861 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
863 key_command = xstrdup(ssh_default_key_command);
864 n = split_cmdline(key_command, &argv);
866 if (n < 0)
867 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
868 split_cmdline_strerror(n));
870 strvec_pushv(&ssh_default_key.args, argv);
871 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
872 &key_stderr, 0);
874 if (!ret) {
875 keys = strbuf_split_max(&key_stdout, '\n', 2);
876 if (keys[0] && is_literal_ssh_key(keys[0]->buf, &literal_key)) {
878 * We only use `is_literal_ssh_key` here to check validity
879 * The prefix will be stripped when the key is used.
881 default_key = strbuf_detach(keys[0], NULL);
882 } else {
883 warning(_("gpg.ssh.defaultKeyCommand succeeded but returned no keys: %s %s"),
884 key_stderr.buf, key_stdout.buf);
887 strbuf_list_free(keys);
888 } else {
889 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
890 key_stderr.buf, key_stdout.buf);
893 free(key_command);
894 free(argv);
895 strbuf_release(&key_stdout);
897 return default_key;
900 static const char *get_ssh_key_id(void) {
901 return get_ssh_key_fingerprint(get_signing_key());
904 /* Returns a textual but unique representation of the signing key */
905 const char *get_signing_key_id(void)
907 gpg_interface_lazy_init();
909 if (use_format->get_key_id) {
910 return use_format->get_key_id();
913 /* GPG/GPGSM only store a key id on this variable */
914 return get_signing_key();
917 const char *get_signing_key(void)
919 gpg_interface_lazy_init();
921 if (configured_signing_key)
922 return configured_signing_key;
923 if (use_format->get_default_key) {
924 return use_format->get_default_key();
927 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
930 const char *gpg_trust_level_to_str(enum signature_trust_level level)
932 struct sigcheck_gpg_trust_level *trust;
934 if (level < 0 || level >= ARRAY_SIZE(sigcheck_gpg_trust_level))
935 BUG("invalid trust level requested %d", level);
937 trust = &sigcheck_gpg_trust_level[level];
938 if (trust->value != level)
939 BUG("sigcheck_gpg_trust_level[] unsorted");
941 return sigcheck_gpg_trust_level[level].display_key;
944 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
946 gpg_interface_lazy_init();
948 return use_format->sign_buffer(buffer, signature, signing_key);
952 * Strip CR from the line endings, in case we are on Windows.
953 * NEEDSWORK: make it trim only CRs before LFs and rename
955 static void remove_cr_after(struct strbuf *buffer, size_t offset)
957 size_t i, j;
959 for (i = j = offset; i < buffer->len; i++) {
960 if (buffer->buf[i] != '\r') {
961 if (i != j)
962 buffer->buf[j] = buffer->buf[i];
963 j++;
966 strbuf_setlen(buffer, j);
969 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
970 const char *signing_key)
972 struct child_process gpg = CHILD_PROCESS_INIT;
973 int ret;
974 size_t bottom;
975 const char *cp;
976 struct strbuf gpg_status = STRBUF_INIT;
978 strvec_pushl(&gpg.args,
979 use_format->program,
980 "--status-fd=2",
981 "-bsau", signing_key,
982 NULL);
984 bottom = signature->len;
987 * When the username signingkey is bad, program could be terminated
988 * because gpg exits without reading and then write gets SIGPIPE.
990 sigchain_push(SIGPIPE, SIG_IGN);
991 ret = pipe_command(&gpg, buffer->buf, buffer->len,
992 signature, 1024, &gpg_status, 0);
993 sigchain_pop(SIGPIPE);
995 for (cp = gpg_status.buf;
996 cp && (cp = strstr(cp, "[GNUPG:] SIG_CREATED "));
997 cp++) {
998 if (cp == gpg_status.buf || cp[-1] == '\n')
999 break; /* found */
1001 ret |= !cp;
1002 if (ret) {
1003 error(_("gpg failed to sign the data:\n%s"),
1004 gpg_status.len ? gpg_status.buf : "(no gpg output)");
1005 strbuf_release(&gpg_status);
1006 return -1;
1008 strbuf_release(&gpg_status);
1010 /* Strip CR from the line endings, in case we are on Windows. */
1011 remove_cr_after(signature, bottom);
1013 return 0;
1016 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
1017 const char *signing_key)
1019 struct child_process signer = CHILD_PROCESS_INIT;
1020 int ret = -1;
1021 size_t bottom, keylen;
1022 struct strbuf signer_stderr = STRBUF_INIT;
1023 struct tempfile *key_file = NULL, *buffer_file = NULL;
1024 char *ssh_signing_key_file = NULL;
1025 struct strbuf ssh_signature_filename = STRBUF_INIT;
1026 const char *literal_key = NULL;
1027 int literal_ssh_key = 0;
1029 if (!signing_key || signing_key[0] == '\0')
1030 return error(
1031 _("user.signingKey needs to be set for ssh signing"));
1033 if (is_literal_ssh_key(signing_key, &literal_key)) {
1034 /* A literal ssh key */
1035 literal_ssh_key = 1;
1036 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
1037 if (!key_file)
1038 return error_errno(
1039 _("could not create temporary file"));
1040 keylen = strlen(literal_key);
1041 if (write_in_full(key_file->fd, literal_key, keylen) < 0 ||
1042 close_tempfile_gently(key_file) < 0) {
1043 error_errno(_("failed writing ssh signing key to '%s'"),
1044 key_file->filename.buf);
1045 goto out;
1047 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
1048 } else {
1049 /* We assume a file */
1050 ssh_signing_key_file = interpolate_path(signing_key, 1);
1053 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
1054 if (!buffer_file) {
1055 error_errno(_("could not create temporary file"));
1056 goto out;
1059 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
1060 close_tempfile_gently(buffer_file) < 0) {
1061 error_errno(_("failed writing ssh signing key buffer to '%s'"),
1062 buffer_file->filename.buf);
1063 goto out;
1066 strvec_pushl(&signer.args, use_format->program,
1067 "-Y", "sign",
1068 "-n", "git",
1069 "-f", ssh_signing_key_file,
1070 NULL);
1071 if (literal_ssh_key)
1072 strvec_push(&signer.args, "-U");
1073 strvec_push(&signer.args, buffer_file->filename.buf);
1075 sigchain_push(SIGPIPE, SIG_IGN);
1076 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
1077 sigchain_pop(SIGPIPE);
1079 if (ret) {
1080 if (strstr(signer_stderr.buf, "usage:"))
1081 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
1083 ret = error("%s", signer_stderr.buf);
1084 goto out;
1087 bottom = signature->len;
1089 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
1090 strbuf_addstr(&ssh_signature_filename, ".sig");
1091 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
1092 ret = error_errno(
1093 _("failed reading ssh signing data buffer from '%s'"),
1094 ssh_signature_filename.buf);
1095 goto out;
1097 /* Strip CR from the line endings, in case we are on Windows. */
1098 remove_cr_after(signature, bottom);
1100 out:
1101 if (key_file)
1102 delete_tempfile(&key_file);
1103 if (buffer_file)
1104 delete_tempfile(&buffer_file);
1105 if (ssh_signature_filename.len)
1106 unlink_or_warn(ssh_signature_filename.buf);
1107 strbuf_release(&signer_stderr);
1108 strbuf_release(&ssh_signature_filename);
1109 FREE_AND_NULL(ssh_signing_key_file);
1110 return ret;