scalar: implement the `clone` subcommand
[git/debian.git] / gpg-interface.c
blob3e7255a2a91103323232f55a6ae7770266595f9a
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 "gpg-interface.h"
8 #include "sigchain.h"
9 #include "tempfile.h"
10 #include "alias.h"
12 static char *configured_signing_key;
13 static const char *ssh_default_key_command, *ssh_allowed_signers, *ssh_revocation_file;
14 static enum signature_trust_level configured_min_trust_level = TRUST_UNDEFINED;
16 struct gpg_format {
17 const char *name;
18 const char *program;
19 const char **verify_args;
20 const char **sigs;
21 int (*verify_signed_buffer)(struct signature_check *sigc,
22 struct gpg_format *fmt, const char *payload,
23 size_t payload_size, const char *signature,
24 size_t signature_size);
25 int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
26 const char *signing_key);
27 const char *(*get_default_key)(void);
28 const char *(*get_key_id)(void);
31 static const char *openpgp_verify_args[] = {
32 "--keyid-format=long",
33 NULL
35 static const char *openpgp_sigs[] = {
36 "-----BEGIN PGP SIGNATURE-----",
37 "-----BEGIN PGP MESSAGE-----",
38 NULL
41 static const char *x509_verify_args[] = {
42 NULL
44 static const char *x509_sigs[] = {
45 "-----BEGIN SIGNED MESSAGE-----",
46 NULL
49 static const char *ssh_verify_args[] = { NULL };
50 static const char *ssh_sigs[] = {
51 "-----BEGIN SSH SIGNATURE-----",
52 NULL
55 static int verify_gpg_signed_buffer(struct signature_check *sigc,
56 struct gpg_format *fmt, const char *payload,
57 size_t payload_size, const char *signature,
58 size_t signature_size);
59 static int verify_ssh_signed_buffer(struct signature_check *sigc,
60 struct gpg_format *fmt, const char *payload,
61 size_t payload_size, const char *signature,
62 size_t signature_size);
63 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
64 const char *signing_key);
65 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
66 const char *signing_key);
68 static const char *get_default_ssh_signing_key(void);
70 static const char *get_ssh_key_id(void);
72 static struct gpg_format gpg_format[] = {
74 .name = "openpgp",
75 .program = "gpg",
76 .verify_args = openpgp_verify_args,
77 .sigs = openpgp_sigs,
78 .verify_signed_buffer = verify_gpg_signed_buffer,
79 .sign_buffer = sign_buffer_gpg,
80 .get_default_key = NULL,
81 .get_key_id = NULL,
84 .name = "x509",
85 .program = "gpgsm",
86 .verify_args = x509_verify_args,
87 .sigs = x509_sigs,
88 .verify_signed_buffer = verify_gpg_signed_buffer,
89 .sign_buffer = sign_buffer_gpg,
90 .get_default_key = NULL,
91 .get_key_id = NULL,
94 .name = "ssh",
95 .program = "ssh-keygen",
96 .verify_args = ssh_verify_args,
97 .sigs = ssh_sigs,
98 .verify_signed_buffer = verify_ssh_signed_buffer,
99 .sign_buffer = sign_buffer_ssh,
100 .get_default_key = get_default_ssh_signing_key,
101 .get_key_id = get_ssh_key_id,
105 static struct gpg_format *use_format = &gpg_format[0];
107 static struct gpg_format *get_format_by_name(const char *str)
109 int i;
111 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
112 if (!strcmp(gpg_format[i].name, str))
113 return gpg_format + i;
114 return NULL;
117 static struct gpg_format *get_format_by_sig(const char *sig)
119 int i, j;
121 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
122 for (j = 0; gpg_format[i].sigs[j]; j++)
123 if (starts_with(sig, gpg_format[i].sigs[j]))
124 return gpg_format + i;
125 return NULL;
128 void signature_check_clear(struct signature_check *sigc)
130 FREE_AND_NULL(sigc->payload);
131 FREE_AND_NULL(sigc->output);
132 FREE_AND_NULL(sigc->gpg_status);
133 FREE_AND_NULL(sigc->signer);
134 FREE_AND_NULL(sigc->key);
135 FREE_AND_NULL(sigc->fingerprint);
136 FREE_AND_NULL(sigc->primary_key_fingerprint);
139 /* An exclusive status -- only one of them can appear in output */
140 #define GPG_STATUS_EXCLUSIVE (1<<0)
141 /* The status includes key identifier */
142 #define GPG_STATUS_KEYID (1<<1)
143 /* The status includes user identifier */
144 #define GPG_STATUS_UID (1<<2)
145 /* The status includes key fingerprints */
146 #define GPG_STATUS_FINGERPRINT (1<<3)
147 /* The status includes trust level */
148 #define GPG_STATUS_TRUST_LEVEL (1<<4)
150 /* Short-hand for standard exclusive *SIG status with keyid & UID */
151 #define GPG_STATUS_STDSIG (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
153 static struct {
154 char result;
155 const char *check;
156 unsigned int flags;
157 } sigcheck_gpg_status[] = {
158 { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
159 { 'B', "BADSIG ", GPG_STATUS_STDSIG },
160 { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
161 { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
162 { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
163 { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
164 { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
165 { 0, "TRUST_", GPG_STATUS_TRUST_LEVEL },
168 static struct {
169 const char *key;
170 enum signature_trust_level value;
171 } sigcheck_gpg_trust_level[] = {
172 { "UNDEFINED", TRUST_UNDEFINED },
173 { "NEVER", TRUST_NEVER },
174 { "MARGINAL", TRUST_MARGINAL },
175 { "FULLY", TRUST_FULLY },
176 { "ULTIMATE", TRUST_ULTIMATE },
179 static void replace_cstring(char **field, const char *line, const char *next)
181 free(*field);
183 if (line && next)
184 *field = xmemdupz(line, next - line);
185 else
186 *field = NULL;
189 static int parse_gpg_trust_level(const char *level,
190 enum signature_trust_level *res)
192 size_t i;
194 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_trust_level); i++) {
195 if (!strcmp(sigcheck_gpg_trust_level[i].key, level)) {
196 *res = sigcheck_gpg_trust_level[i].value;
197 return 0;
200 return 1;
203 static void parse_gpg_output(struct signature_check *sigc)
205 const char *buf = sigc->gpg_status;
206 const char *line, *next;
207 int i, j;
208 int seen_exclusive_status = 0;
210 /* Iterate over all lines */
211 for (line = buf; *line; line = strchrnul(line+1, '\n')) {
212 while (*line == '\n')
213 line++;
214 if (!*line)
215 break;
217 /* Skip lines that don't start with GNUPG status */
218 if (!skip_prefix(line, "[GNUPG:] ", &line))
219 continue;
221 /* Iterate over all search strings */
222 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
223 if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
225 * GOODSIG, BADSIG etc. can occur only once for
226 * each signature. Therefore, if we had more
227 * than one then we're dealing with multiple
228 * signatures. We don't support them
229 * currently, and they're rather hard to
230 * create, so something is likely fishy and we
231 * should reject them altogether.
233 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
234 if (seen_exclusive_status++)
235 goto error;
238 if (sigcheck_gpg_status[i].result)
239 sigc->result = sigcheck_gpg_status[i].result;
240 /* Do we have key information? */
241 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
242 next = strchrnul(line, ' ');
243 replace_cstring(&sigc->key, line, next);
244 /* Do we have signer information? */
245 if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
246 line = next + 1;
247 next = strchrnul(line, '\n');
248 replace_cstring(&sigc->signer, line, next);
252 /* Do we have trust level? */
253 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
255 * GPG v1 and v2 differs in how the
256 * TRUST_ lines are written. Some
257 * trust lines contain no additional
258 * space-separated information for v1.
260 size_t trust_size = strcspn(line, " \n");
261 char *trust = xmemdupz(line, trust_size);
263 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
264 free(trust);
265 goto error;
267 free(trust);
270 /* Do we have fingerprint? */
271 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
272 const char *limit;
273 char **field;
275 next = strchrnul(line, ' ');
276 replace_cstring(&sigc->fingerprint, line, next);
279 * Skip interim fields. The search is
280 * limited to the same line since only
281 * OpenPGP signatures has a field with
282 * the primary fingerprint.
284 limit = strchrnul(line, '\n');
285 for (j = 9; j > 0; j--) {
286 if (!*next || limit <= next)
287 break;
288 line = next + 1;
289 next = strchrnul(line, ' ');
292 field = &sigc->primary_key_fingerprint;
293 if (!j) {
294 next = strchrnul(line, '\n');
295 replace_cstring(field, line, next);
296 } else {
297 replace_cstring(field, NULL, NULL);
301 break;
305 return;
307 error:
308 sigc->result = 'E';
309 /* Clear partial data to avoid confusion */
310 FREE_AND_NULL(sigc->primary_key_fingerprint);
311 FREE_AND_NULL(sigc->fingerprint);
312 FREE_AND_NULL(sigc->signer);
313 FREE_AND_NULL(sigc->key);
316 static int verify_gpg_signed_buffer(struct signature_check *sigc,
317 struct gpg_format *fmt, const char *payload,
318 size_t payload_size, const char *signature,
319 size_t signature_size)
321 struct child_process gpg = CHILD_PROCESS_INIT;
322 struct tempfile *temp;
323 int ret;
324 struct strbuf gpg_stdout = STRBUF_INIT;
325 struct strbuf gpg_stderr = STRBUF_INIT;
327 temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
328 if (!temp)
329 return error_errno(_("could not create temporary file"));
330 if (write_in_full(temp->fd, signature, signature_size) < 0 ||
331 close_tempfile_gently(temp) < 0) {
332 error_errno(_("failed writing detached signature to '%s'"),
333 temp->filename.buf);
334 delete_tempfile(&temp);
335 return -1;
338 strvec_push(&gpg.args, fmt->program);
339 strvec_pushv(&gpg.args, fmt->verify_args);
340 strvec_pushl(&gpg.args,
341 "--status-fd=1",
342 "--verify", temp->filename.buf, "-",
343 NULL);
345 sigchain_push(SIGPIPE, SIG_IGN);
346 ret = pipe_command(&gpg, payload, payload_size, &gpg_stdout, 0,
347 &gpg_stderr, 0);
348 sigchain_pop(SIGPIPE);
350 delete_tempfile(&temp);
352 ret |= !strstr(gpg_stdout.buf, "\n[GNUPG:] GOODSIG ");
353 sigc->payload = xmemdupz(payload, payload_size);
354 sigc->output = strbuf_detach(&gpg_stderr, NULL);
355 sigc->gpg_status = strbuf_detach(&gpg_stdout, NULL);
357 parse_gpg_output(sigc);
359 strbuf_release(&gpg_stdout);
360 strbuf_release(&gpg_stderr);
362 return ret;
365 static void parse_ssh_output(struct signature_check *sigc)
367 const char *line, *principal, *search;
368 char *to_free;
369 char *key = NULL;
372 * ssh-keygen output should be:
373 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
375 * or for valid but unknown keys:
376 * Good "git" signature with RSA key SHA256:FINGERPRINT
378 * Note that "PRINCIPAL" can contain whitespace, "RSA" and
379 * "SHA256" part could be a different token that names of
380 * the algorithms used, and "FINGERPRINT" is a hexadecimal
381 * string. By finding the last occurence of " with ", we can
382 * reliably parse out the PRINCIPAL.
384 sigc->result = 'B';
385 sigc->trust_level = TRUST_NEVER;
387 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
389 if (skip_prefix(line, "Good \"git\" signature for ", &line)) {
390 /* Search for the last "with" to get the full principal */
391 principal = line;
392 do {
393 search = strstr(line, " with ");
394 if (search)
395 line = search + 1;
396 } while (search != NULL);
397 if (line == principal)
398 goto cleanup;
400 /* Valid signature and known principal */
401 sigc->result = 'G';
402 sigc->trust_level = TRUST_FULLY;
403 sigc->signer = xmemdupz(principal, line - principal - 1);
404 } else if (skip_prefix(line, "Good \"git\" signature with ", &line)) {
405 /* Valid signature, but key unknown */
406 sigc->result = 'G';
407 sigc->trust_level = TRUST_UNDEFINED;
408 } else {
409 goto cleanup;
412 key = strstr(line, "key ");
413 if (key) {
414 sigc->fingerprint = xstrdup(strstr(line, "key ") + 4);
415 sigc->key = xstrdup(sigc->fingerprint);
416 } else {
418 * Output did not match what we expected
419 * Treat the signature as bad
421 sigc->result = 'B';
424 cleanup:
425 free(to_free);
428 static int verify_ssh_signed_buffer(struct signature_check *sigc,
429 struct gpg_format *fmt, const char *payload,
430 size_t payload_size, const char *signature,
431 size_t signature_size)
433 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
434 struct tempfile *buffer_file;
435 int ret = -1;
436 const char *line;
437 size_t trust_size;
438 char *principal;
439 struct strbuf ssh_principals_out = STRBUF_INIT;
440 struct strbuf ssh_principals_err = STRBUF_INIT;
441 struct strbuf ssh_keygen_out = STRBUF_INIT;
442 struct strbuf ssh_keygen_err = STRBUF_INIT;
444 if (!ssh_allowed_signers) {
445 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
446 return -1;
449 buffer_file = mks_tempfile_t(".git_vtag_tmpXXXXXX");
450 if (!buffer_file)
451 return error_errno(_("could not create temporary file"));
452 if (write_in_full(buffer_file->fd, signature, signature_size) < 0 ||
453 close_tempfile_gently(buffer_file) < 0) {
454 error_errno(_("failed writing detached signature to '%s'"),
455 buffer_file->filename.buf);
456 delete_tempfile(&buffer_file);
457 return -1;
460 /* Find the principal from the signers */
461 strvec_pushl(&ssh_keygen.args, fmt->program,
462 "-Y", "find-principals",
463 "-f", ssh_allowed_signers,
464 "-s", buffer_file->filename.buf,
465 NULL);
466 ret = pipe_command(&ssh_keygen, NULL, 0, &ssh_principals_out, 0,
467 &ssh_principals_err, 0);
468 if (ret && strstr(ssh_principals_err.buf, "usage:")) {
469 error(_("ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"));
470 goto out;
472 if (ret || !ssh_principals_out.len) {
474 * We did not find a matching principal in the allowedSigners
475 * Check without validation
477 child_process_init(&ssh_keygen);
478 strvec_pushl(&ssh_keygen.args, fmt->program,
479 "-Y", "check-novalidate",
480 "-n", "git",
481 "-s", buffer_file->filename.buf,
482 NULL);
483 pipe_command(&ssh_keygen, payload, payload_size,
484 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
487 * Fail on unknown keys
488 * we still call check-novalidate to display the signature info
490 ret = -1;
491 } else {
492 /* Check every principal we found (one per line) */
493 for (line = ssh_principals_out.buf; *line;
494 line = strchrnul(line + 1, '\n')) {
495 while (*line == '\n')
496 line++;
497 if (!*line)
498 break;
500 trust_size = strcspn(line, "\n");
501 principal = xmemdupz(line, trust_size);
503 child_process_init(&ssh_keygen);
504 strbuf_release(&ssh_keygen_out);
505 strbuf_release(&ssh_keygen_err);
506 strvec_push(&ssh_keygen.args, fmt->program);
508 * We found principals
509 * Try with each until we find a match
511 strvec_pushl(&ssh_keygen.args, "-Y", "verify",
512 "-n", "git",
513 "-f", ssh_allowed_signers,
514 "-I", principal,
515 "-s", buffer_file->filename.buf,
516 NULL);
518 if (ssh_revocation_file) {
519 if (file_exists(ssh_revocation_file)) {
520 strvec_pushl(&ssh_keygen.args, "-r",
521 ssh_revocation_file, NULL);
522 } else {
523 warning(_("ssh signing revocation file configured but not found: %s"),
524 ssh_revocation_file);
528 sigchain_push(SIGPIPE, SIG_IGN);
529 ret = pipe_command(&ssh_keygen, payload, payload_size,
530 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
531 sigchain_pop(SIGPIPE);
533 FREE_AND_NULL(principal);
535 if (!ret)
536 ret = !starts_with(ssh_keygen_out.buf, "Good");
538 if (!ret)
539 break;
543 sigc->payload = xmemdupz(payload, payload_size);
544 strbuf_stripspace(&ssh_keygen_out, 0);
545 strbuf_stripspace(&ssh_keygen_err, 0);
546 /* Add stderr outputs to show the user actual ssh-keygen errors */
547 strbuf_add(&ssh_keygen_out, ssh_principals_err.buf, ssh_principals_err.len);
548 strbuf_add(&ssh_keygen_out, ssh_keygen_err.buf, ssh_keygen_err.len);
549 sigc->output = strbuf_detach(&ssh_keygen_out, NULL);
550 sigc->gpg_status = xstrdup(sigc->output);
552 parse_ssh_output(sigc);
554 out:
555 if (buffer_file)
556 delete_tempfile(&buffer_file);
557 strbuf_release(&ssh_principals_out);
558 strbuf_release(&ssh_principals_err);
559 strbuf_release(&ssh_keygen_out);
560 strbuf_release(&ssh_keygen_err);
562 return ret;
565 int check_signature(const char *payload, size_t plen, const char *signature,
566 size_t slen, struct signature_check *sigc)
568 struct gpg_format *fmt;
569 int status;
571 sigc->result = 'N';
572 sigc->trust_level = -1;
574 fmt = get_format_by_sig(signature);
575 if (!fmt)
576 die(_("bad/incompatible signature '%s'"), signature);
578 status = fmt->verify_signed_buffer(sigc, fmt, payload, plen, signature,
579 slen);
581 if (status && !sigc->output)
582 return !!status;
584 status |= sigc->result != 'G';
585 status |= sigc->trust_level < configured_min_trust_level;
587 return !!status;
590 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
592 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
593 sigc->output;
595 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
596 fputs(sigc->payload, stdout);
598 if (output)
599 fputs(output, stderr);
602 size_t parse_signed_buffer(const char *buf, size_t size)
604 size_t len = 0;
605 size_t match = size;
606 while (len < size) {
607 const char *eol;
609 if (get_format_by_sig(buf + len))
610 match = len;
612 eol = memchr(buf + len, '\n', size - len);
613 len += eol ? eol - (buf + len) + 1 : size - len;
615 return match;
618 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
620 size_t match = parse_signed_buffer(buf, size);
621 if (match != size) {
622 strbuf_add(payload, buf, match);
623 remove_signature(payload);
624 strbuf_add(signature, buf + match, size - match);
625 return 1;
627 return 0;
630 void set_signing_key(const char *key)
632 free(configured_signing_key);
633 configured_signing_key = xstrdup(key);
636 int git_gpg_config(const char *var, const char *value, void *cb)
638 struct gpg_format *fmt = NULL;
639 char *fmtname = NULL;
640 char *trust;
641 int ret;
643 if (!strcmp(var, "user.signingkey")) {
644 if (!value)
645 return config_error_nonbool(var);
646 set_signing_key(value);
647 return 0;
650 if (!strcmp(var, "gpg.format")) {
651 if (!value)
652 return config_error_nonbool(var);
653 fmt = get_format_by_name(value);
654 if (!fmt)
655 return error("unsupported value for %s: %s",
656 var, value);
657 use_format = fmt;
658 return 0;
661 if (!strcmp(var, "gpg.mintrustlevel")) {
662 if (!value)
663 return config_error_nonbool(var);
665 trust = xstrdup_toupper(value);
666 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
667 free(trust);
669 if (ret)
670 return error("unsupported value for %s: %s", var,
671 value);
672 return 0;
675 if (!strcmp(var, "gpg.ssh.defaultkeycommand")) {
676 if (!value)
677 return config_error_nonbool(var);
678 return git_config_string(&ssh_default_key_command, var, value);
681 if (!strcmp(var, "gpg.ssh.allowedsignersfile")) {
682 if (!value)
683 return config_error_nonbool(var);
684 return git_config_pathname(&ssh_allowed_signers, var, value);
687 if (!strcmp(var, "gpg.ssh.revocationfile")) {
688 if (!value)
689 return config_error_nonbool(var);
690 return git_config_pathname(&ssh_revocation_file, var, value);
693 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
694 fmtname = "openpgp";
696 if (!strcmp(var, "gpg.x509.program"))
697 fmtname = "x509";
699 if (!strcmp(var, "gpg.ssh.program"))
700 fmtname = "ssh";
702 if (fmtname) {
703 fmt = get_format_by_name(fmtname);
704 return git_config_string(&fmt->program, var, value);
707 return 0;
710 static char *get_ssh_key_fingerprint(const char *signing_key)
712 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
713 int ret = -1;
714 struct strbuf fingerprint_stdout = STRBUF_INIT;
715 struct strbuf **fingerprint;
716 char *fingerprint_ret;
719 * With SSH Signing this can contain a filename or a public key
720 * For textual representation we usually want a fingerprint
722 if (starts_with(signing_key, "ssh-")) {
723 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
724 ret = pipe_command(&ssh_keygen, signing_key,
725 strlen(signing_key), &fingerprint_stdout, 0,
726 NULL, 0);
727 } else {
728 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
729 configured_signing_key, NULL);
730 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
731 NULL, 0);
734 if (!!ret)
735 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
736 signing_key);
738 fingerprint = strbuf_split_max(&fingerprint_stdout, ' ', 3);
739 if (!fingerprint[1])
740 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
741 signing_key);
743 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
744 strbuf_list_free(fingerprint);
745 strbuf_release(&fingerprint_stdout);
746 return fingerprint_ret;
749 /* Returns the first public key from an ssh-agent to use for signing */
750 static const char *get_default_ssh_signing_key(void)
752 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
753 int ret = -1;
754 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
755 struct strbuf **keys;
756 char *key_command = NULL;
757 const char **argv;
758 int n;
759 char *default_key = NULL;
761 if (!ssh_default_key_command)
762 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
764 key_command = xstrdup(ssh_default_key_command);
765 n = split_cmdline(key_command, &argv);
767 if (n < 0)
768 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
769 split_cmdline_strerror(n));
771 strvec_pushv(&ssh_default_key.args, argv);
772 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
773 &key_stderr, 0);
775 if (!ret) {
776 keys = strbuf_split_max(&key_stdout, '\n', 2);
777 if (keys[0] && starts_with(keys[0]->buf, "ssh-")) {
778 default_key = strbuf_detach(keys[0], NULL);
779 } else {
780 warning(_("gpg.ssh.defaultKeyCommand succeeded but returned no keys: %s %s"),
781 key_stderr.buf, key_stdout.buf);
784 strbuf_list_free(keys);
785 } else {
786 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
787 key_stderr.buf, key_stdout.buf);
790 free(key_command);
791 free(argv);
792 strbuf_release(&key_stdout);
794 return default_key;
797 static const char *get_ssh_key_id(void) {
798 return get_ssh_key_fingerprint(get_signing_key());
801 /* Returns a textual but unique representation of the signing key */
802 const char *get_signing_key_id(void)
804 if (use_format->get_key_id) {
805 return use_format->get_key_id();
808 /* GPG/GPGSM only store a key id on this variable */
809 return get_signing_key();
812 const char *get_signing_key(void)
814 if (configured_signing_key)
815 return configured_signing_key;
816 if (use_format->get_default_key) {
817 return use_format->get_default_key();
820 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
823 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
825 return use_format->sign_buffer(buffer, signature, signing_key);
829 * Strip CR from the line endings, in case we are on Windows.
830 * NEEDSWORK: make it trim only CRs before LFs and rename
832 static void remove_cr_after(struct strbuf *buffer, size_t offset)
834 size_t i, j;
836 for (i = j = offset; i < buffer->len; i++) {
837 if (buffer->buf[i] != '\r') {
838 if (i != j)
839 buffer->buf[j] = buffer->buf[i];
840 j++;
843 strbuf_setlen(buffer, j);
846 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
847 const char *signing_key)
849 struct child_process gpg = CHILD_PROCESS_INIT;
850 int ret;
851 size_t bottom;
852 struct strbuf gpg_status = STRBUF_INIT;
854 strvec_pushl(&gpg.args,
855 use_format->program,
856 "--status-fd=2",
857 "-bsau", signing_key,
858 NULL);
860 bottom = signature->len;
863 * When the username signingkey is bad, program could be terminated
864 * because gpg exits without reading and then write gets SIGPIPE.
866 sigchain_push(SIGPIPE, SIG_IGN);
867 ret = pipe_command(&gpg, buffer->buf, buffer->len,
868 signature, 1024, &gpg_status, 0);
869 sigchain_pop(SIGPIPE);
871 ret |= !strstr(gpg_status.buf, "\n[GNUPG:] SIG_CREATED ");
872 strbuf_release(&gpg_status);
873 if (ret)
874 return error(_("gpg failed to sign the data"));
876 /* Strip CR from the line endings, in case we are on Windows. */
877 remove_cr_after(signature, bottom);
879 return 0;
882 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
883 const char *signing_key)
885 struct child_process signer = CHILD_PROCESS_INIT;
886 int ret = -1;
887 size_t bottom, keylen;
888 struct strbuf signer_stderr = STRBUF_INIT;
889 struct tempfile *key_file = NULL, *buffer_file = NULL;
890 char *ssh_signing_key_file = NULL;
891 struct strbuf ssh_signature_filename = STRBUF_INIT;
893 if (!signing_key || signing_key[0] == '\0')
894 return error(
895 _("user.signingkey needs to be set for ssh signing"));
897 if (starts_with(signing_key, "ssh-")) {
898 /* A literal ssh key */
899 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
900 if (!key_file)
901 return error_errno(
902 _("could not create temporary file"));
903 keylen = strlen(signing_key);
904 if (write_in_full(key_file->fd, signing_key, keylen) < 0 ||
905 close_tempfile_gently(key_file) < 0) {
906 error_errno(_("failed writing ssh signing key to '%s'"),
907 key_file->filename.buf);
908 goto out;
910 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
911 } else {
912 /* We assume a file */
913 ssh_signing_key_file = expand_user_path(signing_key, 1);
916 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
917 if (!buffer_file) {
918 error_errno(_("could not create temporary file"));
919 goto out;
922 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
923 close_tempfile_gently(buffer_file) < 0) {
924 error_errno(_("failed writing ssh signing key buffer to '%s'"),
925 buffer_file->filename.buf);
926 goto out;
929 strvec_pushl(&signer.args, use_format->program,
930 "-Y", "sign",
931 "-n", "git",
932 "-f", ssh_signing_key_file,
933 buffer_file->filename.buf,
934 NULL);
936 sigchain_push(SIGPIPE, SIG_IGN);
937 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
938 sigchain_pop(SIGPIPE);
940 if (ret) {
941 if (strstr(signer_stderr.buf, "usage:"))
942 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
944 error("%s", signer_stderr.buf);
945 goto out;
948 bottom = signature->len;
950 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
951 strbuf_addstr(&ssh_signature_filename, ".sig");
952 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
953 error_errno(
954 _("failed reading ssh signing data buffer from '%s'"),
955 ssh_signature_filename.buf);
957 unlink_or_warn(ssh_signature_filename.buf);
959 /* Strip CR from the line endings, in case we are on Windows. */
960 remove_cr_after(signature, bottom);
962 out:
963 if (key_file)
964 delete_tempfile(&key_file);
965 if (buffer_file)
966 delete_tempfile(&buffer_file);
967 strbuf_release(&signer_stderr);
968 strbuf_release(&ssh_signature_filename);
969 FREE_AND_NULL(ssh_signing_key_file);
970 return ret;