rebase: deprecate --rebase-merges=""
[git/debian.git] / gpg-interface.c
blob855970bb939fb84c09d9b52c4afbc0b7689f9956
1 #include "cache.h"
2 #include "commit.h"
3 #include "config.h"
4 #include "run-command.h"
5 #include "strbuf.h"
6 #include "dir.h"
7 #include "ident.h"
8 #include "gpg-interface.h"
9 #include "sigchain.h"
10 #include "tempfile.h"
11 #include "alias.h"
13 static int git_gpg_config(const char *, const char *, void *);
15 static void gpg_interface_lazy_init(void)
17 static int done;
19 if (done)
20 return;
21 done = 1;
22 git_config(git_gpg_config, NULL);
25 static char *configured_signing_key;
26 static const char *ssh_default_key_command, *ssh_allowed_signers, *ssh_revocation_file;
27 static enum signature_trust_level configured_min_trust_level = TRUST_UNDEFINED;
29 struct gpg_format {
30 const char *name;
31 const char *program;
32 const char **verify_args;
33 const char **sigs;
34 int (*verify_signed_buffer)(struct signature_check *sigc,
35 struct gpg_format *fmt,
36 const char *signature,
37 size_t signature_size);
38 int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
39 const char *signing_key);
40 const char *(*get_default_key)(void);
41 const char *(*get_key_id)(void);
44 static const char *openpgp_verify_args[] = {
45 "--keyid-format=long",
46 NULL
48 static const char *openpgp_sigs[] = {
49 "-----BEGIN PGP SIGNATURE-----",
50 "-----BEGIN PGP MESSAGE-----",
51 NULL
54 static const char *x509_verify_args[] = {
55 NULL
57 static const char *x509_sigs[] = {
58 "-----BEGIN SIGNED MESSAGE-----",
59 NULL
62 static const char *ssh_verify_args[] = { NULL };
63 static const char *ssh_sigs[] = {
64 "-----BEGIN SSH SIGNATURE-----",
65 NULL
68 static int verify_gpg_signed_buffer(struct signature_check *sigc,
69 struct gpg_format *fmt,
70 const char *signature,
71 size_t signature_size);
72 static int verify_ssh_signed_buffer(struct signature_check *sigc,
73 struct gpg_format *fmt,
74 const char *signature,
75 size_t signature_size);
76 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
77 const char *signing_key);
78 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
79 const char *signing_key);
81 static const char *get_default_ssh_signing_key(void);
83 static const char *get_ssh_key_id(void);
85 static struct gpg_format gpg_format[] = {
87 .name = "openpgp",
88 .program = "gpg",
89 .verify_args = openpgp_verify_args,
90 .sigs = openpgp_sigs,
91 .verify_signed_buffer = verify_gpg_signed_buffer,
92 .sign_buffer = sign_buffer_gpg,
93 .get_default_key = NULL,
94 .get_key_id = NULL,
97 .name = "x509",
98 .program = "gpgsm",
99 .verify_args = x509_verify_args,
100 .sigs = x509_sigs,
101 .verify_signed_buffer = verify_gpg_signed_buffer,
102 .sign_buffer = sign_buffer_gpg,
103 .get_default_key = NULL,
104 .get_key_id = NULL,
107 .name = "ssh",
108 .program = "ssh-keygen",
109 .verify_args = ssh_verify_args,
110 .sigs = ssh_sigs,
111 .verify_signed_buffer = verify_ssh_signed_buffer,
112 .sign_buffer = sign_buffer_ssh,
113 .get_default_key = get_default_ssh_signing_key,
114 .get_key_id = get_ssh_key_id,
118 static struct gpg_format *use_format = &gpg_format[0];
120 static struct gpg_format *get_format_by_name(const char *str)
122 int i;
124 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
125 if (!strcmp(gpg_format[i].name, str))
126 return gpg_format + i;
127 return NULL;
130 static struct gpg_format *get_format_by_sig(const char *sig)
132 int i, j;
134 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
135 for (j = 0; gpg_format[i].sigs[j]; j++)
136 if (starts_with(sig, gpg_format[i].sigs[j]))
137 return gpg_format + i;
138 return NULL;
141 void signature_check_clear(struct signature_check *sigc)
143 FREE_AND_NULL(sigc->payload);
144 FREE_AND_NULL(sigc->output);
145 FREE_AND_NULL(sigc->gpg_status);
146 FREE_AND_NULL(sigc->signer);
147 FREE_AND_NULL(sigc->key);
148 FREE_AND_NULL(sigc->fingerprint);
149 FREE_AND_NULL(sigc->primary_key_fingerprint);
152 /* An exclusive status -- only one of them can appear in output */
153 #define GPG_STATUS_EXCLUSIVE (1<<0)
154 /* The status includes key identifier */
155 #define GPG_STATUS_KEYID (1<<1)
156 /* The status includes user identifier */
157 #define GPG_STATUS_UID (1<<2)
158 /* The status includes key fingerprints */
159 #define GPG_STATUS_FINGERPRINT (1<<3)
160 /* The status includes trust level */
161 #define GPG_STATUS_TRUST_LEVEL (1<<4)
163 /* Short-hand for standard exclusive *SIG status with keyid & UID */
164 #define GPG_STATUS_STDSIG (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
166 static struct {
167 char result;
168 const char *check;
169 unsigned int flags;
170 } sigcheck_gpg_status[] = {
171 { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
172 { 'B', "BADSIG ", GPG_STATUS_STDSIG },
173 { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
174 { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
175 { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
176 { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
177 { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
178 { 0, "TRUST_", GPG_STATUS_TRUST_LEVEL },
181 /* Keep the order same as enum signature_trust_level */
182 static struct sigcheck_gpg_trust_level {
183 const char *key;
184 const char *display_key;
185 enum signature_trust_level value;
186 } sigcheck_gpg_trust_level[] = {
187 { "UNDEFINED", "undefined", TRUST_UNDEFINED },
188 { "NEVER", "never", TRUST_NEVER },
189 { "MARGINAL", "marginal", TRUST_MARGINAL },
190 { "FULLY", "fully", TRUST_FULLY },
191 { "ULTIMATE", "ultimate", TRUST_ULTIMATE },
194 static void replace_cstring(char **field, const char *line, const char *next)
196 free(*field);
198 if (line && next)
199 *field = xmemdupz(line, next - line);
200 else
201 *field = NULL;
204 static int parse_gpg_trust_level(const char *level,
205 enum signature_trust_level *res)
207 size_t i;
209 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_trust_level); i++) {
210 if (!strcmp(sigcheck_gpg_trust_level[i].key, level)) {
211 *res = sigcheck_gpg_trust_level[i].value;
212 return 0;
215 return 1;
218 static void parse_gpg_output(struct signature_check *sigc)
220 const char *buf = sigc->gpg_status;
221 const char *line, *next;
222 int i, j;
223 int seen_exclusive_status = 0;
225 /* Iterate over all lines */
226 for (line = buf; *line; line = strchrnul(line+1, '\n')) {
227 while (*line == '\n')
228 line++;
229 if (!*line)
230 break;
232 /* Skip lines that don't start with GNUPG status */
233 if (!skip_prefix(line, "[GNUPG:] ", &line))
234 continue;
236 /* Iterate over all search strings */
237 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
238 if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
240 * GOODSIG, BADSIG etc. can occur only once for
241 * each signature. Therefore, if we had more
242 * than one then we're dealing with multiple
243 * signatures. We don't support them
244 * currently, and they're rather hard to
245 * create, so something is likely fishy and we
246 * should reject them altogether.
248 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
249 if (seen_exclusive_status++)
250 goto error;
253 if (sigcheck_gpg_status[i].result)
254 sigc->result = sigcheck_gpg_status[i].result;
255 /* Do we have key information? */
256 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
257 next = strchrnul(line, ' ');
258 replace_cstring(&sigc->key, line, next);
259 /* Do we have signer information? */
260 if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
261 line = next + 1;
262 next = strchrnul(line, '\n');
263 replace_cstring(&sigc->signer, line, next);
267 /* Do we have trust level? */
268 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
270 * GPG v1 and v2 differs in how the
271 * TRUST_ lines are written. Some
272 * trust lines contain no additional
273 * space-separated information for v1.
275 size_t trust_size = strcspn(line, " \n");
276 char *trust = xmemdupz(line, trust_size);
278 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
279 free(trust);
280 goto error;
282 free(trust);
285 /* Do we have fingerprint? */
286 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
287 const char *limit;
288 char **field;
290 next = strchrnul(line, ' ');
291 replace_cstring(&sigc->fingerprint, line, next);
294 * Skip interim fields. The search is
295 * limited to the same line since only
296 * OpenPGP signatures has a field with
297 * the primary fingerprint.
299 limit = strchrnul(line, '\n');
300 for (j = 9; j > 0; j--) {
301 if (!*next || limit <= next)
302 break;
303 line = next + 1;
304 next = strchrnul(line, ' ');
307 field = &sigc->primary_key_fingerprint;
308 if (!j) {
309 next = strchrnul(line, '\n');
310 replace_cstring(field, line, next);
311 } else {
312 replace_cstring(field, NULL, NULL);
316 break;
320 return;
322 error:
323 sigc->result = 'E';
324 /* Clear partial data to avoid confusion */
325 FREE_AND_NULL(sigc->primary_key_fingerprint);
326 FREE_AND_NULL(sigc->fingerprint);
327 FREE_AND_NULL(sigc->signer);
328 FREE_AND_NULL(sigc->key);
331 static int verify_gpg_signed_buffer(struct signature_check *sigc,
332 struct gpg_format *fmt,
333 const char *signature,
334 size_t signature_size)
336 struct child_process gpg = CHILD_PROCESS_INIT;
337 struct tempfile *temp;
338 int ret;
339 struct strbuf gpg_stdout = STRBUF_INIT;
340 struct strbuf gpg_stderr = STRBUF_INIT;
342 temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
343 if (!temp)
344 return error_errno(_("could not create temporary file"));
345 if (write_in_full(temp->fd, signature, signature_size) < 0 ||
346 close_tempfile_gently(temp) < 0) {
347 error_errno(_("failed writing detached signature to '%s'"),
348 temp->filename.buf);
349 delete_tempfile(&temp);
350 return -1;
353 strvec_push(&gpg.args, fmt->program);
354 strvec_pushv(&gpg.args, fmt->verify_args);
355 strvec_pushl(&gpg.args,
356 "--status-fd=1",
357 "--verify", temp->filename.buf, "-",
358 NULL);
360 sigchain_push(SIGPIPE, SIG_IGN);
361 ret = pipe_command(&gpg, sigc->payload, sigc->payload_len, &gpg_stdout, 0,
362 &gpg_stderr, 0);
363 sigchain_pop(SIGPIPE);
365 delete_tempfile(&temp);
367 ret |= !strstr(gpg_stdout.buf, "\n[GNUPG:] GOODSIG ");
368 sigc->output = strbuf_detach(&gpg_stderr, NULL);
369 sigc->gpg_status = strbuf_detach(&gpg_stdout, NULL);
371 parse_gpg_output(sigc);
373 strbuf_release(&gpg_stdout);
374 strbuf_release(&gpg_stderr);
376 return ret;
379 static void parse_ssh_output(struct signature_check *sigc)
381 const char *line, *principal, *search;
382 char *to_free;
383 char *key = NULL;
386 * ssh-keygen output should be:
387 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
389 * or for valid but unknown keys:
390 * Good "git" signature with RSA key SHA256:FINGERPRINT
392 * Note that "PRINCIPAL" can contain whitespace, "RSA" and
393 * "SHA256" part could be a different token that names of
394 * the algorithms used, and "FINGERPRINT" is a hexadecimal
395 * string. By finding the last occurence of " with ", we can
396 * reliably parse out the PRINCIPAL.
398 sigc->result = 'B';
399 sigc->trust_level = TRUST_NEVER;
401 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
403 if (skip_prefix(line, "Good \"git\" signature for ", &line)) {
404 /* Search for the last "with" to get the full principal */
405 principal = line;
406 do {
407 search = strstr(line, " with ");
408 if (search)
409 line = search + 1;
410 } while (search != NULL);
411 if (line == principal)
412 goto cleanup;
414 /* Valid signature and known principal */
415 sigc->result = 'G';
416 sigc->trust_level = TRUST_FULLY;
417 sigc->signer = xmemdupz(principal, line - principal - 1);
418 } else if (skip_prefix(line, "Good \"git\" signature with ", &line)) {
419 /* Valid signature, but key unknown */
420 sigc->result = 'G';
421 sigc->trust_level = TRUST_UNDEFINED;
422 } else {
423 goto cleanup;
426 key = strstr(line, "key ");
427 if (key) {
428 sigc->fingerprint = xstrdup(strstr(line, "key ") + 4);
429 sigc->key = xstrdup(sigc->fingerprint);
430 } else {
432 * Output did not match what we expected
433 * Treat the signature as bad
435 sigc->result = 'B';
438 cleanup:
439 free(to_free);
442 static int verify_ssh_signed_buffer(struct signature_check *sigc,
443 struct gpg_format *fmt,
444 const char *signature,
445 size_t signature_size)
447 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
448 struct tempfile *buffer_file;
449 int ret = -1;
450 const char *line;
451 char *principal;
452 struct strbuf ssh_principals_out = STRBUF_INIT;
453 struct strbuf ssh_principals_err = STRBUF_INIT;
454 struct strbuf ssh_keygen_out = STRBUF_INIT;
455 struct strbuf ssh_keygen_err = STRBUF_INIT;
456 struct strbuf verify_time = STRBUF_INIT;
457 const struct date_mode verify_date_mode = {
458 .type = DATE_STRFTIME,
459 .strftime_fmt = "%Y%m%d%H%M%S",
460 /* SSH signing key validity has no timezone information - Use the local timezone */
461 .local = 1,
464 if (!ssh_allowed_signers) {
465 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
466 return -1;
469 buffer_file = mks_tempfile_t(".git_vtag_tmpXXXXXX");
470 if (!buffer_file)
471 return error_errno(_("could not create temporary file"));
472 if (write_in_full(buffer_file->fd, signature, signature_size) < 0 ||
473 close_tempfile_gently(buffer_file) < 0) {
474 error_errno(_("failed writing detached signature to '%s'"),
475 buffer_file->filename.buf);
476 delete_tempfile(&buffer_file);
477 return -1;
480 if (sigc->payload_timestamp)
481 strbuf_addf(&verify_time, "-Overify-time=%s",
482 show_date(sigc->payload_timestamp, 0, &verify_date_mode));
484 /* Find the principal from the signers */
485 strvec_pushl(&ssh_keygen.args, fmt->program,
486 "-Y", "find-principals",
487 "-f", ssh_allowed_signers,
488 "-s", buffer_file->filename.buf,
489 verify_time.buf,
490 NULL);
491 ret = pipe_command(&ssh_keygen, NULL, 0, &ssh_principals_out, 0,
492 &ssh_principals_err, 0);
493 if (ret && strstr(ssh_principals_err.buf, "usage:")) {
494 error(_("ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"));
495 goto out;
497 if (ret || !ssh_principals_out.len) {
499 * We did not find a matching principal in the allowedSigners
500 * Check without validation
502 child_process_init(&ssh_keygen);
503 strvec_pushl(&ssh_keygen.args, fmt->program,
504 "-Y", "check-novalidate",
505 "-n", "git",
506 "-s", buffer_file->filename.buf,
507 verify_time.buf,
508 NULL);
509 pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
510 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
513 * Fail on unknown keys
514 * we still call check-novalidate to display the signature info
516 ret = -1;
517 } else {
518 /* Check every principal we found (one per line) */
519 const char *next;
520 for (line = ssh_principals_out.buf;
521 *line;
522 line = next) {
523 const char *end_of_text;
525 next = end_of_text = strchrnul(line, '\n');
527 /* Did we find a LF, and did we have CR before it? */
528 if (*end_of_text &&
529 line < end_of_text &&
530 end_of_text[-1] == '\r')
531 end_of_text--;
533 /* Unless we hit NUL, skip over the LF we found */
534 if (*next)
535 next++;
537 /* Not all lines are data. Skip empty ones */
538 if (line == end_of_text)
539 continue;
541 /* We now know we have an non-empty line. Process it */
542 principal = xmemdupz(line, end_of_text - line);
544 child_process_init(&ssh_keygen);
545 strbuf_release(&ssh_keygen_out);
546 strbuf_release(&ssh_keygen_err);
547 strvec_push(&ssh_keygen.args, fmt->program);
549 * We found principals
550 * Try with each until we find a match
552 strvec_pushl(&ssh_keygen.args, "-Y", "verify",
553 "-n", "git",
554 "-f", ssh_allowed_signers,
555 "-I", principal,
556 "-s", buffer_file->filename.buf,
557 verify_time.buf,
558 NULL);
560 if (ssh_revocation_file) {
561 if (file_exists(ssh_revocation_file)) {
562 strvec_pushl(&ssh_keygen.args, "-r",
563 ssh_revocation_file, NULL);
564 } else {
565 warning(_("ssh signing revocation file configured but not found: %s"),
566 ssh_revocation_file);
570 sigchain_push(SIGPIPE, SIG_IGN);
571 ret = pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
572 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
573 sigchain_pop(SIGPIPE);
575 FREE_AND_NULL(principal);
577 if (!ret)
578 ret = !starts_with(ssh_keygen_out.buf, "Good");
580 if (!ret)
581 break;
585 strbuf_stripspace(&ssh_keygen_out, 0);
586 strbuf_stripspace(&ssh_keygen_err, 0);
587 /* Add stderr outputs to show the user actual ssh-keygen errors */
588 strbuf_add(&ssh_keygen_out, ssh_principals_err.buf, ssh_principals_err.len);
589 strbuf_add(&ssh_keygen_out, ssh_keygen_err.buf, ssh_keygen_err.len);
590 sigc->output = strbuf_detach(&ssh_keygen_out, NULL);
591 sigc->gpg_status = xstrdup(sigc->output);
593 parse_ssh_output(sigc);
595 out:
596 if (buffer_file)
597 delete_tempfile(&buffer_file);
598 strbuf_release(&ssh_principals_out);
599 strbuf_release(&ssh_principals_err);
600 strbuf_release(&ssh_keygen_out);
601 strbuf_release(&ssh_keygen_err);
602 strbuf_release(&verify_time);
604 return ret;
607 static int parse_payload_metadata(struct signature_check *sigc)
609 const char *ident_line = NULL;
610 size_t ident_len;
611 struct ident_split ident;
612 const char *signer_header;
614 switch (sigc->payload_type) {
615 case SIGNATURE_PAYLOAD_COMMIT:
616 signer_header = "committer";
617 break;
618 case SIGNATURE_PAYLOAD_TAG:
619 signer_header = "tagger";
620 break;
621 case SIGNATURE_PAYLOAD_UNDEFINED:
622 case SIGNATURE_PAYLOAD_PUSH_CERT:
623 /* Ignore payloads we don't want to parse */
624 return 0;
625 default:
626 BUG("invalid value for sigc->payload_type");
629 ident_line = find_commit_header(sigc->payload, signer_header, &ident_len);
630 if (!ident_line || !ident_len)
631 return 1;
633 if (split_ident_line(&ident, ident_line, ident_len))
634 return 1;
636 if (!sigc->payload_timestamp && ident.date_begin && ident.date_end)
637 sigc->payload_timestamp = parse_timestamp(ident.date_begin, NULL, 10);
639 return 0;
642 int check_signature(struct signature_check *sigc,
643 const char *signature, size_t slen)
645 struct gpg_format *fmt;
646 int status;
648 gpg_interface_lazy_init();
650 sigc->result = 'N';
651 sigc->trust_level = -1;
653 fmt = get_format_by_sig(signature);
654 if (!fmt)
655 die(_("bad/incompatible signature '%s'"), signature);
657 if (parse_payload_metadata(sigc))
658 return 1;
660 status = fmt->verify_signed_buffer(sigc, fmt, signature, slen);
662 if (status && !sigc->output)
663 return !!status;
665 status |= sigc->result != 'G';
666 status |= sigc->trust_level < configured_min_trust_level;
668 return !!status;
671 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
673 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
674 sigc->output;
676 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
677 fwrite(sigc->payload, 1, sigc->payload_len, stdout);
679 if (output)
680 fputs(output, stderr);
683 size_t parse_signed_buffer(const char *buf, size_t size)
685 size_t len = 0;
686 size_t match = size;
687 while (len < size) {
688 const char *eol;
690 if (get_format_by_sig(buf + len))
691 match = len;
693 eol = memchr(buf + len, '\n', size - len);
694 len += eol ? eol - (buf + len) + 1 : size - len;
696 return match;
699 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
701 size_t match = parse_signed_buffer(buf, size);
702 if (match != size) {
703 strbuf_add(payload, buf, match);
704 remove_signature(payload);
705 strbuf_add(signature, buf + match, size - match);
706 return 1;
708 return 0;
711 void set_signing_key(const char *key)
713 gpg_interface_lazy_init();
715 free(configured_signing_key);
716 configured_signing_key = xstrdup(key);
719 static int git_gpg_config(const char *var, const char *value, void *cb UNUSED)
721 struct gpg_format *fmt = NULL;
722 char *fmtname = NULL;
723 char *trust;
724 int ret;
726 if (!strcmp(var, "user.signingkey")) {
727 if (!value)
728 return config_error_nonbool(var);
729 set_signing_key(value);
730 return 0;
733 if (!strcmp(var, "gpg.format")) {
734 if (!value)
735 return config_error_nonbool(var);
736 fmt = get_format_by_name(value);
737 if (!fmt)
738 return error(_("invalid value for '%s': '%s'"),
739 var, value);
740 use_format = fmt;
741 return 0;
744 if (!strcmp(var, "gpg.mintrustlevel")) {
745 if (!value)
746 return config_error_nonbool(var);
748 trust = xstrdup_toupper(value);
749 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
750 free(trust);
752 if (ret)
753 return error(_("invalid value for '%s': '%s'"),
754 var, value);
755 return 0;
758 if (!strcmp(var, "gpg.ssh.defaultkeycommand")) {
759 if (!value)
760 return config_error_nonbool(var);
761 return git_config_string(&ssh_default_key_command, var, value);
764 if (!strcmp(var, "gpg.ssh.allowedsignersfile")) {
765 if (!value)
766 return config_error_nonbool(var);
767 return git_config_pathname(&ssh_allowed_signers, var, value);
770 if (!strcmp(var, "gpg.ssh.revocationfile")) {
771 if (!value)
772 return config_error_nonbool(var);
773 return git_config_pathname(&ssh_revocation_file, var, value);
776 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
777 fmtname = "openpgp";
779 if (!strcmp(var, "gpg.x509.program"))
780 fmtname = "x509";
782 if (!strcmp(var, "gpg.ssh.program"))
783 fmtname = "ssh";
785 if (fmtname) {
786 fmt = get_format_by_name(fmtname);
787 return git_config_string(&fmt->program, var, value);
790 return 0;
794 * Returns 1 if `string` contains a literal ssh key, 0 otherwise
795 * `key` will be set to the start of the actual key if a prefix is present.
797 static int is_literal_ssh_key(const char *string, const char **key)
799 if (skip_prefix(string, "key::", key))
800 return 1;
801 if (starts_with(string, "ssh-")) {
802 *key = string;
803 return 1;
805 return 0;
808 static char *get_ssh_key_fingerprint(const char *signing_key)
810 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
811 int ret = -1;
812 struct strbuf fingerprint_stdout = STRBUF_INIT;
813 struct strbuf **fingerprint;
814 char *fingerprint_ret;
815 const char *literal_key = NULL;
818 * With SSH Signing this can contain a filename or a public key
819 * For textual representation we usually want a fingerprint
821 if (is_literal_ssh_key(signing_key, &literal_key)) {
822 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
823 ret = pipe_command(&ssh_keygen, literal_key,
824 strlen(literal_key), &fingerprint_stdout, 0,
825 NULL, 0);
826 } else {
827 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
828 configured_signing_key, NULL);
829 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
830 NULL, 0);
833 if (!!ret)
834 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
835 signing_key);
837 fingerprint = strbuf_split_max(&fingerprint_stdout, ' ', 3);
838 if (!fingerprint[1])
839 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
840 signing_key);
842 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
843 strbuf_list_free(fingerprint);
844 strbuf_release(&fingerprint_stdout);
845 return fingerprint_ret;
848 /* Returns the first public key from an ssh-agent to use for signing */
849 static const char *get_default_ssh_signing_key(void)
851 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
852 int ret = -1;
853 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
854 struct strbuf **keys;
855 char *key_command = NULL;
856 const char **argv;
857 int n;
858 char *default_key = NULL;
859 const char *literal_key = NULL;
861 if (!ssh_default_key_command)
862 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
864 key_command = xstrdup(ssh_default_key_command);
865 n = split_cmdline(key_command, &argv);
867 if (n < 0)
868 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
869 split_cmdline_strerror(n));
871 strvec_pushv(&ssh_default_key.args, argv);
872 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
873 &key_stderr, 0);
875 if (!ret) {
876 keys = strbuf_split_max(&key_stdout, '\n', 2);
877 if (keys[0] && is_literal_ssh_key(keys[0]->buf, &literal_key)) {
879 * We only use `is_literal_ssh_key` here to check validity
880 * The prefix will be stripped when the key is used.
882 default_key = strbuf_detach(keys[0], NULL);
883 } else {
884 warning(_("gpg.ssh.defaultKeyCommand succeeded but returned no keys: %s %s"),
885 key_stderr.buf, key_stdout.buf);
888 strbuf_list_free(keys);
889 } else {
890 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
891 key_stderr.buf, key_stdout.buf);
894 free(key_command);
895 free(argv);
896 strbuf_release(&key_stdout);
898 return default_key;
901 static const char *get_ssh_key_id(void) {
902 return get_ssh_key_fingerprint(get_signing_key());
905 /* Returns a textual but unique representation of the signing key */
906 const char *get_signing_key_id(void)
908 gpg_interface_lazy_init();
910 if (use_format->get_key_id) {
911 return use_format->get_key_id();
914 /* GPG/GPGSM only store a key id on this variable */
915 return get_signing_key();
918 const char *get_signing_key(void)
920 gpg_interface_lazy_init();
922 if (configured_signing_key)
923 return configured_signing_key;
924 if (use_format->get_default_key) {
925 return use_format->get_default_key();
928 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
931 const char *gpg_trust_level_to_str(enum signature_trust_level level)
933 struct sigcheck_gpg_trust_level *trust;
935 if (level < 0 || level >= ARRAY_SIZE(sigcheck_gpg_trust_level))
936 BUG("invalid trust level requested %d", level);
938 trust = &sigcheck_gpg_trust_level[level];
939 if (trust->value != level)
940 BUG("sigcheck_gpg_trust_level[] unsorted");
942 return sigcheck_gpg_trust_level[level].display_key;
945 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
947 gpg_interface_lazy_init();
949 return use_format->sign_buffer(buffer, signature, signing_key);
953 * Strip CR from the line endings, in case we are on Windows.
954 * NEEDSWORK: make it trim only CRs before LFs and rename
956 static void remove_cr_after(struct strbuf *buffer, size_t offset)
958 size_t i, j;
960 for (i = j = offset; i < buffer->len; i++) {
961 if (buffer->buf[i] != '\r') {
962 if (i != j)
963 buffer->buf[j] = buffer->buf[i];
964 j++;
967 strbuf_setlen(buffer, j);
970 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
971 const char *signing_key)
973 struct child_process gpg = CHILD_PROCESS_INIT;
974 int ret;
975 size_t bottom;
976 const char *cp;
977 struct strbuf gpg_status = STRBUF_INIT;
979 strvec_pushl(&gpg.args,
980 use_format->program,
981 "--status-fd=2",
982 "-bsau", signing_key,
983 NULL);
985 bottom = signature->len;
988 * When the username signingkey is bad, program could be terminated
989 * because gpg exits without reading and then write gets SIGPIPE.
991 sigchain_push(SIGPIPE, SIG_IGN);
992 ret = pipe_command(&gpg, buffer->buf, buffer->len,
993 signature, 1024, &gpg_status, 0);
994 sigchain_pop(SIGPIPE);
996 for (cp = gpg_status.buf;
997 cp && (cp = strstr(cp, "[GNUPG:] SIG_CREATED "));
998 cp++) {
999 if (cp == gpg_status.buf || cp[-1] == '\n')
1000 break; /* found */
1002 ret |= !cp;
1003 if (ret) {
1004 error(_("gpg failed to sign the data:\n%s"),
1005 gpg_status.len ? gpg_status.buf : "(no gpg output)");
1006 strbuf_release(&gpg_status);
1007 return -1;
1009 strbuf_release(&gpg_status);
1011 /* Strip CR from the line endings, in case we are on Windows. */
1012 remove_cr_after(signature, bottom);
1014 return 0;
1017 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
1018 const char *signing_key)
1020 struct child_process signer = CHILD_PROCESS_INIT;
1021 int ret = -1;
1022 size_t bottom, keylen;
1023 struct strbuf signer_stderr = STRBUF_INIT;
1024 struct tempfile *key_file = NULL, *buffer_file = NULL;
1025 char *ssh_signing_key_file = NULL;
1026 struct strbuf ssh_signature_filename = STRBUF_INIT;
1027 const char *literal_key = NULL;
1028 int literal_ssh_key = 0;
1030 if (!signing_key || signing_key[0] == '\0')
1031 return error(
1032 _("user.signingKey needs to be set for ssh signing"));
1034 if (is_literal_ssh_key(signing_key, &literal_key)) {
1035 /* A literal ssh key */
1036 literal_ssh_key = 1;
1037 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
1038 if (!key_file)
1039 return error_errno(
1040 _("could not create temporary file"));
1041 keylen = strlen(literal_key);
1042 if (write_in_full(key_file->fd, literal_key, keylen) < 0 ||
1043 close_tempfile_gently(key_file) < 0) {
1044 error_errno(_("failed writing ssh signing key to '%s'"),
1045 key_file->filename.buf);
1046 goto out;
1048 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
1049 } else {
1050 /* We assume a file */
1051 ssh_signing_key_file = expand_user_path(signing_key, 1);
1054 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
1055 if (!buffer_file) {
1056 error_errno(_("could not create temporary file"));
1057 goto out;
1060 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
1061 close_tempfile_gently(buffer_file) < 0) {
1062 error_errno(_("failed writing ssh signing key buffer to '%s'"),
1063 buffer_file->filename.buf);
1064 goto out;
1067 strvec_pushl(&signer.args, use_format->program,
1068 "-Y", "sign",
1069 "-n", "git",
1070 "-f", ssh_signing_key_file,
1071 NULL);
1072 if (literal_ssh_key)
1073 strvec_push(&signer.args, "-U");
1074 strvec_push(&signer.args, buffer_file->filename.buf);
1076 sigchain_push(SIGPIPE, SIG_IGN);
1077 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
1078 sigchain_pop(SIGPIPE);
1080 if (ret) {
1081 if (strstr(signer_stderr.buf, "usage:"))
1082 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
1084 error("%s", signer_stderr.buf);
1085 goto out;
1088 bottom = signature->len;
1090 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
1091 strbuf_addstr(&ssh_signature_filename, ".sig");
1092 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
1093 ret = error_errno(
1094 _("failed reading ssh signing data buffer from '%s'"),
1095 ssh_signature_filename.buf);
1096 goto out;
1098 /* Strip CR from the line endings, in case we are on Windows. */
1099 remove_cr_after(signature, bottom);
1101 out:
1102 if (key_file)
1103 delete_tempfile(&key_file);
1104 if (buffer_file)
1105 delete_tempfile(&buffer_file);
1106 if (ssh_signature_filename.len)
1107 unlink_or_warn(ssh_signature_filename.buf);
1108 strbuf_release(&signer_stderr);
1109 strbuf_release(&ssh_signature_filename);
1110 FREE_AND_NULL(ssh_signing_key_file);
1111 return ret;