hash-ll.h: split out of hash.h to remove dependency on repository.h
[alt-git.git] / gpg-interface.c
blob8615dcd4b4bb3b6b78f2d6c29f93f539a335f1d7
1 #include "git-compat-util.h"
2 #include "commit.h"
3 #include "config.h"
4 #include "gettext.h"
5 #include "run-command.h"
6 #include "strbuf.h"
7 #include "dir.h"
8 #include "ident.h"
9 #include "gpg-interface.h"
10 #include "path.h"
11 #include "sigchain.h"
12 #include "tempfile.h"
13 #include "alias.h"
14 #include "wrapper.h"
16 static int git_gpg_config(const char *, const char *, void *);
18 static void gpg_interface_lazy_init(void)
20 static int done;
22 if (done)
23 return;
24 done = 1;
25 git_config(git_gpg_config, NULL);
28 static char *configured_signing_key;
29 static const char *ssh_default_key_command, *ssh_allowed_signers, *ssh_revocation_file;
30 static enum signature_trust_level configured_min_trust_level = TRUST_UNDEFINED;
32 struct gpg_format {
33 const char *name;
34 const char *program;
35 const char **verify_args;
36 const char **sigs;
37 int (*verify_signed_buffer)(struct signature_check *sigc,
38 struct gpg_format *fmt,
39 const char *signature,
40 size_t signature_size);
41 int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
42 const char *signing_key);
43 const char *(*get_default_key)(void);
44 const char *(*get_key_id)(void);
47 static const char *openpgp_verify_args[] = {
48 "--keyid-format=long",
49 NULL
51 static const char *openpgp_sigs[] = {
52 "-----BEGIN PGP SIGNATURE-----",
53 "-----BEGIN PGP MESSAGE-----",
54 NULL
57 static const char *x509_verify_args[] = {
58 NULL
60 static const char *x509_sigs[] = {
61 "-----BEGIN SIGNED MESSAGE-----",
62 NULL
65 static const char *ssh_verify_args[] = { NULL };
66 static const char *ssh_sigs[] = {
67 "-----BEGIN SSH SIGNATURE-----",
68 NULL
71 static int verify_gpg_signed_buffer(struct signature_check *sigc,
72 struct gpg_format *fmt,
73 const char *signature,
74 size_t signature_size);
75 static int verify_ssh_signed_buffer(struct signature_check *sigc,
76 struct gpg_format *fmt,
77 const char *signature,
78 size_t signature_size);
79 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
80 const char *signing_key);
81 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
82 const char *signing_key);
84 static const char *get_default_ssh_signing_key(void);
86 static const char *get_ssh_key_id(void);
88 static struct gpg_format gpg_format[] = {
90 .name = "openpgp",
91 .program = "gpg",
92 .verify_args = openpgp_verify_args,
93 .sigs = openpgp_sigs,
94 .verify_signed_buffer = verify_gpg_signed_buffer,
95 .sign_buffer = sign_buffer_gpg,
96 .get_default_key = NULL,
97 .get_key_id = NULL,
100 .name = "x509",
101 .program = "gpgsm",
102 .verify_args = x509_verify_args,
103 .sigs = x509_sigs,
104 .verify_signed_buffer = verify_gpg_signed_buffer,
105 .sign_buffer = sign_buffer_gpg,
106 .get_default_key = NULL,
107 .get_key_id = NULL,
110 .name = "ssh",
111 .program = "ssh-keygen",
112 .verify_args = ssh_verify_args,
113 .sigs = ssh_sigs,
114 .verify_signed_buffer = verify_ssh_signed_buffer,
115 .sign_buffer = sign_buffer_ssh,
116 .get_default_key = get_default_ssh_signing_key,
117 .get_key_id = get_ssh_key_id,
121 static struct gpg_format *use_format = &gpg_format[0];
123 static struct gpg_format *get_format_by_name(const char *str)
125 int i;
127 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
128 if (!strcmp(gpg_format[i].name, str))
129 return gpg_format + i;
130 return NULL;
133 static struct gpg_format *get_format_by_sig(const char *sig)
135 int i, j;
137 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
138 for (j = 0; gpg_format[i].sigs[j]; j++)
139 if (starts_with(sig, gpg_format[i].sigs[j]))
140 return gpg_format + i;
141 return NULL;
144 void signature_check_clear(struct signature_check *sigc)
146 FREE_AND_NULL(sigc->payload);
147 FREE_AND_NULL(sigc->output);
148 FREE_AND_NULL(sigc->gpg_status);
149 FREE_AND_NULL(sigc->signer);
150 FREE_AND_NULL(sigc->key);
151 FREE_AND_NULL(sigc->fingerprint);
152 FREE_AND_NULL(sigc->primary_key_fingerprint);
155 /* An exclusive status -- only one of them can appear in output */
156 #define GPG_STATUS_EXCLUSIVE (1<<0)
157 /* The status includes key identifier */
158 #define GPG_STATUS_KEYID (1<<1)
159 /* The status includes user identifier */
160 #define GPG_STATUS_UID (1<<2)
161 /* The status includes key fingerprints */
162 #define GPG_STATUS_FINGERPRINT (1<<3)
163 /* The status includes trust level */
164 #define GPG_STATUS_TRUST_LEVEL (1<<4)
166 /* Short-hand for standard exclusive *SIG status with keyid & UID */
167 #define GPG_STATUS_STDSIG (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
169 static struct {
170 char result;
171 const char *check;
172 unsigned int flags;
173 } sigcheck_gpg_status[] = {
174 { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
175 { 'B', "BADSIG ", GPG_STATUS_STDSIG },
176 { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
177 { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
178 { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
179 { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
180 { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
181 { 0, "TRUST_", GPG_STATUS_TRUST_LEVEL },
184 /* Keep the order same as enum signature_trust_level */
185 static struct sigcheck_gpg_trust_level {
186 const char *key;
187 const char *display_key;
188 enum signature_trust_level value;
189 } sigcheck_gpg_trust_level[] = {
190 { "UNDEFINED", "undefined", TRUST_UNDEFINED },
191 { "NEVER", "never", TRUST_NEVER },
192 { "MARGINAL", "marginal", TRUST_MARGINAL },
193 { "FULLY", "fully", TRUST_FULLY },
194 { "ULTIMATE", "ultimate", TRUST_ULTIMATE },
197 static void replace_cstring(char **field, const char *line, const char *next)
199 free(*field);
201 if (line && next)
202 *field = xmemdupz(line, next - line);
203 else
204 *field = NULL;
207 static int parse_gpg_trust_level(const char *level,
208 enum signature_trust_level *res)
210 size_t i;
212 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_trust_level); i++) {
213 if (!strcmp(sigcheck_gpg_trust_level[i].key, level)) {
214 *res = sigcheck_gpg_trust_level[i].value;
215 return 0;
218 return 1;
221 static void parse_gpg_output(struct signature_check *sigc)
223 const char *buf = sigc->gpg_status;
224 const char *line, *next;
225 int i, j;
226 int seen_exclusive_status = 0;
228 /* Iterate over all lines */
229 for (line = buf; *line; line = strchrnul(line+1, '\n')) {
230 while (*line == '\n')
231 line++;
232 if (!*line)
233 break;
235 /* Skip lines that don't start with GNUPG status */
236 if (!skip_prefix(line, "[GNUPG:] ", &line))
237 continue;
239 /* Iterate over all search strings */
240 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
241 if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
243 * GOODSIG, BADSIG etc. can occur only once for
244 * each signature. Therefore, if we had more
245 * than one then we're dealing with multiple
246 * signatures. We don't support them
247 * currently, and they're rather hard to
248 * create, so something is likely fishy and we
249 * should reject them altogether.
251 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
252 if (seen_exclusive_status++)
253 goto error;
256 if (sigcheck_gpg_status[i].result)
257 sigc->result = sigcheck_gpg_status[i].result;
258 /* Do we have key information? */
259 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
260 next = strchrnul(line, ' ');
261 replace_cstring(&sigc->key, line, next);
262 /* Do we have signer information? */
263 if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
264 line = next + 1;
265 next = strchrnul(line, '\n');
266 replace_cstring(&sigc->signer, line, next);
270 /* Do we have trust level? */
271 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
273 * GPG v1 and v2 differs in how the
274 * TRUST_ lines are written. Some
275 * trust lines contain no additional
276 * space-separated information for v1.
278 size_t trust_size = strcspn(line, " \n");
279 char *trust = xmemdupz(line, trust_size);
281 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
282 free(trust);
283 goto error;
285 free(trust);
288 /* Do we have fingerprint? */
289 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
290 const char *limit;
291 char **field;
293 next = strchrnul(line, ' ');
294 replace_cstring(&sigc->fingerprint, line, next);
297 * Skip interim fields. The search is
298 * limited to the same line since only
299 * OpenPGP signatures has a field with
300 * the primary fingerprint.
302 limit = strchrnul(line, '\n');
303 for (j = 9; j > 0; j--) {
304 if (!*next || limit <= next)
305 break;
306 line = next + 1;
307 next = strchrnul(line, ' ');
310 field = &sigc->primary_key_fingerprint;
311 if (!j) {
312 next = strchrnul(line, '\n');
313 replace_cstring(field, line, next);
314 } else {
315 replace_cstring(field, NULL, NULL);
319 break;
323 return;
325 error:
326 sigc->result = 'E';
327 /* Clear partial data to avoid confusion */
328 FREE_AND_NULL(sigc->primary_key_fingerprint);
329 FREE_AND_NULL(sigc->fingerprint);
330 FREE_AND_NULL(sigc->signer);
331 FREE_AND_NULL(sigc->key);
334 static int verify_gpg_signed_buffer(struct signature_check *sigc,
335 struct gpg_format *fmt,
336 const char *signature,
337 size_t signature_size)
339 struct child_process gpg = CHILD_PROCESS_INIT;
340 struct tempfile *temp;
341 int ret;
342 struct strbuf gpg_stdout = STRBUF_INIT;
343 struct strbuf gpg_stderr = STRBUF_INIT;
345 temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
346 if (!temp)
347 return error_errno(_("could not create temporary file"));
348 if (write_in_full(temp->fd, signature, signature_size) < 0 ||
349 close_tempfile_gently(temp) < 0) {
350 error_errno(_("failed writing detached signature to '%s'"),
351 temp->filename.buf);
352 delete_tempfile(&temp);
353 return -1;
356 strvec_push(&gpg.args, fmt->program);
357 strvec_pushv(&gpg.args, fmt->verify_args);
358 strvec_pushl(&gpg.args,
359 "--status-fd=1",
360 "--verify", temp->filename.buf, "-",
361 NULL);
363 sigchain_push(SIGPIPE, SIG_IGN);
364 ret = pipe_command(&gpg, sigc->payload, sigc->payload_len, &gpg_stdout, 0,
365 &gpg_stderr, 0);
366 sigchain_pop(SIGPIPE);
368 delete_tempfile(&temp);
370 ret |= !strstr(gpg_stdout.buf, "\n[GNUPG:] GOODSIG ");
371 sigc->output = strbuf_detach(&gpg_stderr, NULL);
372 sigc->gpg_status = strbuf_detach(&gpg_stdout, NULL);
374 parse_gpg_output(sigc);
376 strbuf_release(&gpg_stdout);
377 strbuf_release(&gpg_stderr);
379 return ret;
382 static void parse_ssh_output(struct signature_check *sigc)
384 const char *line, *principal, *search;
385 char *to_free;
386 char *key = NULL;
389 * ssh-keygen output should be:
390 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
392 * or for valid but unknown keys:
393 * Good "git" signature with RSA key SHA256:FINGERPRINT
395 * Note that "PRINCIPAL" can contain whitespace, "RSA" and
396 * "SHA256" part could be a different token that names of
397 * the algorithms used, and "FINGERPRINT" is a hexadecimal
398 * string. By finding the last occurence of " with ", we can
399 * reliably parse out the PRINCIPAL.
401 sigc->result = 'B';
402 sigc->trust_level = TRUST_NEVER;
404 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
406 if (skip_prefix(line, "Good \"git\" signature for ", &line)) {
407 /* Search for the last "with" to get the full principal */
408 principal = line;
409 do {
410 search = strstr(line, " with ");
411 if (search)
412 line = search + 1;
413 } while (search != NULL);
414 if (line == principal)
415 goto cleanup;
417 /* Valid signature and known principal */
418 sigc->result = 'G';
419 sigc->trust_level = TRUST_FULLY;
420 sigc->signer = xmemdupz(principal, line - principal - 1);
421 } else if (skip_prefix(line, "Good \"git\" signature with ", &line)) {
422 /* Valid signature, but key unknown */
423 sigc->result = 'G';
424 sigc->trust_level = TRUST_UNDEFINED;
425 } else {
426 goto cleanup;
429 key = strstr(line, "key ");
430 if (key) {
431 sigc->fingerprint = xstrdup(strstr(line, "key ") + 4);
432 sigc->key = xstrdup(sigc->fingerprint);
433 } else {
435 * Output did not match what we expected
436 * Treat the signature as bad
438 sigc->result = 'B';
441 cleanup:
442 free(to_free);
445 static int verify_ssh_signed_buffer(struct signature_check *sigc,
446 struct gpg_format *fmt,
447 const char *signature,
448 size_t signature_size)
450 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
451 struct tempfile *buffer_file;
452 int ret = -1;
453 const char *line;
454 char *principal;
455 struct strbuf ssh_principals_out = STRBUF_INIT;
456 struct strbuf ssh_principals_err = STRBUF_INIT;
457 struct strbuf ssh_keygen_out = STRBUF_INIT;
458 struct strbuf ssh_keygen_err = STRBUF_INIT;
459 struct strbuf verify_time = STRBUF_INIT;
460 const struct date_mode verify_date_mode = {
461 .type = DATE_STRFTIME,
462 .strftime_fmt = "%Y%m%d%H%M%S",
463 /* SSH signing key validity has no timezone information - Use the local timezone */
464 .local = 1,
467 if (!ssh_allowed_signers) {
468 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
469 return -1;
472 buffer_file = mks_tempfile_t(".git_vtag_tmpXXXXXX");
473 if (!buffer_file)
474 return error_errno(_("could not create temporary file"));
475 if (write_in_full(buffer_file->fd, signature, signature_size) < 0 ||
476 close_tempfile_gently(buffer_file) < 0) {
477 error_errno(_("failed writing detached signature to '%s'"),
478 buffer_file->filename.buf);
479 delete_tempfile(&buffer_file);
480 return -1;
483 if (sigc->payload_timestamp)
484 strbuf_addf(&verify_time, "-Overify-time=%s",
485 show_date(sigc->payload_timestamp, 0, &verify_date_mode));
487 /* Find the principal from the signers */
488 strvec_pushl(&ssh_keygen.args, fmt->program,
489 "-Y", "find-principals",
490 "-f", ssh_allowed_signers,
491 "-s", buffer_file->filename.buf,
492 verify_time.buf,
493 NULL);
494 ret = pipe_command(&ssh_keygen, NULL, 0, &ssh_principals_out, 0,
495 &ssh_principals_err, 0);
496 if (ret && strstr(ssh_principals_err.buf, "usage:")) {
497 error(_("ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"));
498 goto out;
500 if (ret || !ssh_principals_out.len) {
502 * We did not find a matching principal in the allowedSigners
503 * Check without validation
505 child_process_init(&ssh_keygen);
506 strvec_pushl(&ssh_keygen.args, fmt->program,
507 "-Y", "check-novalidate",
508 "-n", "git",
509 "-s", buffer_file->filename.buf,
510 verify_time.buf,
511 NULL);
512 pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
513 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
516 * Fail on unknown keys
517 * we still call check-novalidate to display the signature info
519 ret = -1;
520 } else {
521 /* Check every principal we found (one per line) */
522 const char *next;
523 for (line = ssh_principals_out.buf;
524 *line;
525 line = next) {
526 const char *end_of_text;
528 next = end_of_text = strchrnul(line, '\n');
530 /* Did we find a LF, and did we have CR before it? */
531 if (*end_of_text &&
532 line < end_of_text &&
533 end_of_text[-1] == '\r')
534 end_of_text--;
536 /* Unless we hit NUL, skip over the LF we found */
537 if (*next)
538 next++;
540 /* Not all lines are data. Skip empty ones */
541 if (line == end_of_text)
542 continue;
544 /* We now know we have an non-empty line. Process it */
545 principal = xmemdupz(line, end_of_text - line);
547 child_process_init(&ssh_keygen);
548 strbuf_release(&ssh_keygen_out);
549 strbuf_release(&ssh_keygen_err);
550 strvec_push(&ssh_keygen.args, fmt->program);
552 * We found principals
553 * Try with each until we find a match
555 strvec_pushl(&ssh_keygen.args, "-Y", "verify",
556 "-n", "git",
557 "-f", ssh_allowed_signers,
558 "-I", principal,
559 "-s", buffer_file->filename.buf,
560 verify_time.buf,
561 NULL);
563 if (ssh_revocation_file) {
564 if (file_exists(ssh_revocation_file)) {
565 strvec_pushl(&ssh_keygen.args, "-r",
566 ssh_revocation_file, NULL);
567 } else {
568 warning(_("ssh signing revocation file configured but not found: %s"),
569 ssh_revocation_file);
573 sigchain_push(SIGPIPE, SIG_IGN);
574 ret = pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
575 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
576 sigchain_pop(SIGPIPE);
578 FREE_AND_NULL(principal);
580 if (!ret)
581 ret = !starts_with(ssh_keygen_out.buf, "Good");
583 if (!ret)
584 break;
588 strbuf_stripspace(&ssh_keygen_out, 0);
589 strbuf_stripspace(&ssh_keygen_err, 0);
590 /* Add stderr outputs to show the user actual ssh-keygen errors */
591 strbuf_add(&ssh_keygen_out, ssh_principals_err.buf, ssh_principals_err.len);
592 strbuf_add(&ssh_keygen_out, ssh_keygen_err.buf, ssh_keygen_err.len);
593 sigc->output = strbuf_detach(&ssh_keygen_out, NULL);
594 sigc->gpg_status = xstrdup(sigc->output);
596 parse_ssh_output(sigc);
598 out:
599 if (buffer_file)
600 delete_tempfile(&buffer_file);
601 strbuf_release(&ssh_principals_out);
602 strbuf_release(&ssh_principals_err);
603 strbuf_release(&ssh_keygen_out);
604 strbuf_release(&ssh_keygen_err);
605 strbuf_release(&verify_time);
607 return ret;
610 static int parse_payload_metadata(struct signature_check *sigc)
612 const char *ident_line = NULL;
613 size_t ident_len;
614 struct ident_split ident;
615 const char *signer_header;
617 switch (sigc->payload_type) {
618 case SIGNATURE_PAYLOAD_COMMIT:
619 signer_header = "committer";
620 break;
621 case SIGNATURE_PAYLOAD_TAG:
622 signer_header = "tagger";
623 break;
624 case SIGNATURE_PAYLOAD_UNDEFINED:
625 case SIGNATURE_PAYLOAD_PUSH_CERT:
626 /* Ignore payloads we don't want to parse */
627 return 0;
628 default:
629 BUG("invalid value for sigc->payload_type");
632 ident_line = find_commit_header(sigc->payload, signer_header, &ident_len);
633 if (!ident_line || !ident_len)
634 return 1;
636 if (split_ident_line(&ident, ident_line, ident_len))
637 return 1;
639 if (!sigc->payload_timestamp && ident.date_begin && ident.date_end)
640 sigc->payload_timestamp = parse_timestamp(ident.date_begin, NULL, 10);
642 return 0;
645 int check_signature(struct signature_check *sigc,
646 const char *signature, size_t slen)
648 struct gpg_format *fmt;
649 int status;
651 gpg_interface_lazy_init();
653 sigc->result = 'N';
654 sigc->trust_level = -1;
656 fmt = get_format_by_sig(signature);
657 if (!fmt)
658 die(_("bad/incompatible signature '%s'"), signature);
660 if (parse_payload_metadata(sigc))
661 return 1;
663 status = fmt->verify_signed_buffer(sigc, fmt, signature, slen);
665 if (status && !sigc->output)
666 return !!status;
668 status |= sigc->result != 'G';
669 status |= sigc->trust_level < configured_min_trust_level;
671 return !!status;
674 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
676 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
677 sigc->output;
679 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
680 fwrite(sigc->payload, 1, sigc->payload_len, stdout);
682 if (output)
683 fputs(output, stderr);
686 size_t parse_signed_buffer(const char *buf, size_t size)
688 size_t len = 0;
689 size_t match = size;
690 while (len < size) {
691 const char *eol;
693 if (get_format_by_sig(buf + len))
694 match = len;
696 eol = memchr(buf + len, '\n', size - len);
697 len += eol ? eol - (buf + len) + 1 : size - len;
699 return match;
702 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
704 size_t match = parse_signed_buffer(buf, size);
705 if (match != size) {
706 strbuf_add(payload, buf, match);
707 remove_signature(payload);
708 strbuf_add(signature, buf + match, size - match);
709 return 1;
711 return 0;
714 void set_signing_key(const char *key)
716 gpg_interface_lazy_init();
718 free(configured_signing_key);
719 configured_signing_key = xstrdup(key);
722 static int git_gpg_config(const char *var, const char *value, void *cb UNUSED)
724 struct gpg_format *fmt = NULL;
725 char *fmtname = NULL;
726 char *trust;
727 int ret;
729 if (!strcmp(var, "user.signingkey")) {
730 if (!value)
731 return config_error_nonbool(var);
732 set_signing_key(value);
733 return 0;
736 if (!strcmp(var, "gpg.format")) {
737 if (!value)
738 return config_error_nonbool(var);
739 fmt = get_format_by_name(value);
740 if (!fmt)
741 return error(_("invalid value for '%s': '%s'"),
742 var, value);
743 use_format = fmt;
744 return 0;
747 if (!strcmp(var, "gpg.mintrustlevel")) {
748 if (!value)
749 return config_error_nonbool(var);
751 trust = xstrdup_toupper(value);
752 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
753 free(trust);
755 if (ret)
756 return error(_("invalid value for '%s': '%s'"),
757 var, value);
758 return 0;
761 if (!strcmp(var, "gpg.ssh.defaultkeycommand")) {
762 if (!value)
763 return config_error_nonbool(var);
764 return git_config_string(&ssh_default_key_command, var, value);
767 if (!strcmp(var, "gpg.ssh.allowedsignersfile")) {
768 if (!value)
769 return config_error_nonbool(var);
770 return git_config_pathname(&ssh_allowed_signers, var, value);
773 if (!strcmp(var, "gpg.ssh.revocationfile")) {
774 if (!value)
775 return config_error_nonbool(var);
776 return git_config_pathname(&ssh_revocation_file, var, value);
779 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
780 fmtname = "openpgp";
782 if (!strcmp(var, "gpg.x509.program"))
783 fmtname = "x509";
785 if (!strcmp(var, "gpg.ssh.program"))
786 fmtname = "ssh";
788 if (fmtname) {
789 fmt = get_format_by_name(fmtname);
790 return git_config_string(&fmt->program, var, value);
793 return 0;
797 * Returns 1 if `string` contains a literal ssh key, 0 otherwise
798 * `key` will be set to the start of the actual key if a prefix is present.
800 static int is_literal_ssh_key(const char *string, const char **key)
802 if (skip_prefix(string, "key::", key))
803 return 1;
804 if (starts_with(string, "ssh-")) {
805 *key = string;
806 return 1;
808 return 0;
811 static char *get_ssh_key_fingerprint(const char *signing_key)
813 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
814 int ret = -1;
815 struct strbuf fingerprint_stdout = STRBUF_INIT;
816 struct strbuf **fingerprint;
817 char *fingerprint_ret;
818 const char *literal_key = NULL;
821 * With SSH Signing this can contain a filename or a public key
822 * For textual representation we usually want a fingerprint
824 if (is_literal_ssh_key(signing_key, &literal_key)) {
825 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
826 ret = pipe_command(&ssh_keygen, literal_key,
827 strlen(literal_key), &fingerprint_stdout, 0,
828 NULL, 0);
829 } else {
830 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
831 configured_signing_key, NULL);
832 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
833 NULL, 0);
836 if (!!ret)
837 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
838 signing_key);
840 fingerprint = strbuf_split_max(&fingerprint_stdout, ' ', 3);
841 if (!fingerprint[1])
842 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
843 signing_key);
845 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
846 strbuf_list_free(fingerprint);
847 strbuf_release(&fingerprint_stdout);
848 return fingerprint_ret;
851 /* Returns the first public key from an ssh-agent to use for signing */
852 static const char *get_default_ssh_signing_key(void)
854 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
855 int ret = -1;
856 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
857 struct strbuf **keys;
858 char *key_command = NULL;
859 const char **argv;
860 int n;
861 char *default_key = NULL;
862 const char *literal_key = NULL;
864 if (!ssh_default_key_command)
865 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
867 key_command = xstrdup(ssh_default_key_command);
868 n = split_cmdline(key_command, &argv);
870 if (n < 0)
871 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
872 split_cmdline_strerror(n));
874 strvec_pushv(&ssh_default_key.args, argv);
875 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
876 &key_stderr, 0);
878 if (!ret) {
879 keys = strbuf_split_max(&key_stdout, '\n', 2);
880 if (keys[0] && is_literal_ssh_key(keys[0]->buf, &literal_key)) {
882 * We only use `is_literal_ssh_key` here to check validity
883 * The prefix will be stripped when the key is used.
885 default_key = strbuf_detach(keys[0], NULL);
886 } else {
887 warning(_("gpg.ssh.defaultKeyCommand succeeded but returned no keys: %s %s"),
888 key_stderr.buf, key_stdout.buf);
891 strbuf_list_free(keys);
892 } else {
893 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
894 key_stderr.buf, key_stdout.buf);
897 free(key_command);
898 free(argv);
899 strbuf_release(&key_stdout);
901 return default_key;
904 static const char *get_ssh_key_id(void) {
905 return get_ssh_key_fingerprint(get_signing_key());
908 /* Returns a textual but unique representation of the signing key */
909 const char *get_signing_key_id(void)
911 gpg_interface_lazy_init();
913 if (use_format->get_key_id) {
914 return use_format->get_key_id();
917 /* GPG/GPGSM only store a key id on this variable */
918 return get_signing_key();
921 const char *get_signing_key(void)
923 gpg_interface_lazy_init();
925 if (configured_signing_key)
926 return configured_signing_key;
927 if (use_format->get_default_key) {
928 return use_format->get_default_key();
931 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
934 const char *gpg_trust_level_to_str(enum signature_trust_level level)
936 struct sigcheck_gpg_trust_level *trust;
938 if (level < 0 || level >= ARRAY_SIZE(sigcheck_gpg_trust_level))
939 BUG("invalid trust level requested %d", level);
941 trust = &sigcheck_gpg_trust_level[level];
942 if (trust->value != level)
943 BUG("sigcheck_gpg_trust_level[] unsorted");
945 return sigcheck_gpg_trust_level[level].display_key;
948 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
950 gpg_interface_lazy_init();
952 return use_format->sign_buffer(buffer, signature, signing_key);
956 * Strip CR from the line endings, in case we are on Windows.
957 * NEEDSWORK: make it trim only CRs before LFs and rename
959 static void remove_cr_after(struct strbuf *buffer, size_t offset)
961 size_t i, j;
963 for (i = j = offset; i < buffer->len; i++) {
964 if (buffer->buf[i] != '\r') {
965 if (i != j)
966 buffer->buf[j] = buffer->buf[i];
967 j++;
970 strbuf_setlen(buffer, j);
973 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
974 const char *signing_key)
976 struct child_process gpg = CHILD_PROCESS_INIT;
977 int ret;
978 size_t bottom;
979 const char *cp;
980 struct strbuf gpg_status = STRBUF_INIT;
982 strvec_pushl(&gpg.args,
983 use_format->program,
984 "--status-fd=2",
985 "-bsau", signing_key,
986 NULL);
988 bottom = signature->len;
991 * When the username signingkey is bad, program could be terminated
992 * because gpg exits without reading and then write gets SIGPIPE.
994 sigchain_push(SIGPIPE, SIG_IGN);
995 ret = pipe_command(&gpg, buffer->buf, buffer->len,
996 signature, 1024, &gpg_status, 0);
997 sigchain_pop(SIGPIPE);
999 for (cp = gpg_status.buf;
1000 cp && (cp = strstr(cp, "[GNUPG:] SIG_CREATED "));
1001 cp++) {
1002 if (cp == gpg_status.buf || cp[-1] == '\n')
1003 break; /* found */
1005 ret |= !cp;
1006 if (ret) {
1007 error(_("gpg failed to sign the data:\n%s"),
1008 gpg_status.len ? gpg_status.buf : "(no gpg output)");
1009 strbuf_release(&gpg_status);
1010 return -1;
1012 strbuf_release(&gpg_status);
1014 /* Strip CR from the line endings, in case we are on Windows. */
1015 remove_cr_after(signature, bottom);
1017 return 0;
1020 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
1021 const char *signing_key)
1023 struct child_process signer = CHILD_PROCESS_INIT;
1024 int ret = -1;
1025 size_t bottom, keylen;
1026 struct strbuf signer_stderr = STRBUF_INIT;
1027 struct tempfile *key_file = NULL, *buffer_file = NULL;
1028 char *ssh_signing_key_file = NULL;
1029 struct strbuf ssh_signature_filename = STRBUF_INIT;
1030 const char *literal_key = NULL;
1031 int literal_ssh_key = 0;
1033 if (!signing_key || signing_key[0] == '\0')
1034 return error(
1035 _("user.signingKey needs to be set for ssh signing"));
1037 if (is_literal_ssh_key(signing_key, &literal_key)) {
1038 /* A literal ssh key */
1039 literal_ssh_key = 1;
1040 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
1041 if (!key_file)
1042 return error_errno(
1043 _("could not create temporary file"));
1044 keylen = strlen(literal_key);
1045 if (write_in_full(key_file->fd, literal_key, keylen) < 0 ||
1046 close_tempfile_gently(key_file) < 0) {
1047 error_errno(_("failed writing ssh signing key to '%s'"),
1048 key_file->filename.buf);
1049 goto out;
1051 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
1052 } else {
1053 /* We assume a file */
1054 ssh_signing_key_file = interpolate_path(signing_key, 1);
1057 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
1058 if (!buffer_file) {
1059 error_errno(_("could not create temporary file"));
1060 goto out;
1063 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
1064 close_tempfile_gently(buffer_file) < 0) {
1065 error_errno(_("failed writing ssh signing key buffer to '%s'"),
1066 buffer_file->filename.buf);
1067 goto out;
1070 strvec_pushl(&signer.args, use_format->program,
1071 "-Y", "sign",
1072 "-n", "git",
1073 "-f", ssh_signing_key_file,
1074 NULL);
1075 if (literal_ssh_key)
1076 strvec_push(&signer.args, "-U");
1077 strvec_push(&signer.args, buffer_file->filename.buf);
1079 sigchain_push(SIGPIPE, SIG_IGN);
1080 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
1081 sigchain_pop(SIGPIPE);
1083 if (ret) {
1084 if (strstr(signer_stderr.buf, "usage:"))
1085 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
1087 error("%s", signer_stderr.buf);
1088 goto out;
1091 bottom = signature->len;
1093 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
1094 strbuf_addstr(&ssh_signature_filename, ".sig");
1095 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
1096 ret = error_errno(
1097 _("failed reading ssh signing data buffer from '%s'"),
1098 ssh_signature_filename.buf);
1099 goto out;
1101 /* Strip CR from the line endings, in case we are on Windows. */
1102 remove_cr_after(signature, bottom);
1104 out:
1105 if (key_file)
1106 delete_tempfile(&key_file);
1107 if (buffer_file)
1108 delete_tempfile(&buffer_file);
1109 if (ssh_signature_filename.len)
1110 unlink_or_warn(ssh_signature_filename.buf);
1111 strbuf_release(&signer_stderr);
1112 strbuf_release(&ssh_signature_filename);
1113 FREE_AND_NULL(ssh_signing_key_file);
1114 return ret;