help: handle NULL value for alias.* config
[alt-git.git] / gpg-interface.c
blob48f43c5a21d34569bdc966eefd652da38003d157
1 #include "git-compat-util.h"
2 #include "commit.h"
3 #include "config.h"
4 #include "date.h"
5 #include "gettext.h"
6 #include "run-command.h"
7 #include "strbuf.h"
8 #include "dir.h"
9 #include "ident.h"
10 #include "gpg-interface.h"
11 #include "path.h"
12 #include "sigchain.h"
13 #include "tempfile.h"
14 #include "alias.h"
15 #include "environment.h"
17 static int git_gpg_config(const char *, const char *,
18 const struct config_context *, void *);
20 static void gpg_interface_lazy_init(void)
22 static int done;
24 if (done)
25 return;
26 done = 1;
27 git_config(git_gpg_config, NULL);
30 static char *configured_signing_key;
31 static const char *ssh_default_key_command, *ssh_allowed_signers, *ssh_revocation_file;
32 static enum signature_trust_level configured_min_trust_level = TRUST_UNDEFINED;
34 struct gpg_format {
35 const char *name;
36 const char *program;
37 const char **verify_args;
38 const char **sigs;
39 int (*verify_signed_buffer)(struct signature_check *sigc,
40 struct gpg_format *fmt,
41 const char *signature,
42 size_t signature_size);
43 int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
44 const char *signing_key);
45 const char *(*get_default_key)(void);
46 const char *(*get_key_id)(void);
49 static const char *openpgp_verify_args[] = {
50 "--keyid-format=long",
51 NULL
53 static const char *openpgp_sigs[] = {
54 "-----BEGIN PGP SIGNATURE-----",
55 "-----BEGIN PGP MESSAGE-----",
56 NULL
59 static const char *x509_verify_args[] = {
60 NULL
62 static const char *x509_sigs[] = {
63 "-----BEGIN SIGNED MESSAGE-----",
64 NULL
67 static const char *ssh_verify_args[] = { NULL };
68 static const char *ssh_sigs[] = {
69 "-----BEGIN SSH SIGNATURE-----",
70 NULL
73 static int verify_gpg_signed_buffer(struct signature_check *sigc,
74 struct gpg_format *fmt,
75 const char *signature,
76 size_t signature_size);
77 static int verify_ssh_signed_buffer(struct signature_check *sigc,
78 struct gpg_format *fmt,
79 const char *signature,
80 size_t signature_size);
81 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
82 const char *signing_key);
83 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
84 const char *signing_key);
86 static const char *get_default_ssh_signing_key(void);
88 static const char *get_ssh_key_id(void);
90 static struct gpg_format gpg_format[] = {
92 .name = "openpgp",
93 .program = "gpg",
94 .verify_args = openpgp_verify_args,
95 .sigs = openpgp_sigs,
96 .verify_signed_buffer = verify_gpg_signed_buffer,
97 .sign_buffer = sign_buffer_gpg,
98 .get_default_key = NULL,
99 .get_key_id = NULL,
102 .name = "x509",
103 .program = "gpgsm",
104 .verify_args = x509_verify_args,
105 .sigs = x509_sigs,
106 .verify_signed_buffer = verify_gpg_signed_buffer,
107 .sign_buffer = sign_buffer_gpg,
108 .get_default_key = NULL,
109 .get_key_id = NULL,
112 .name = "ssh",
113 .program = "ssh-keygen",
114 .verify_args = ssh_verify_args,
115 .sigs = ssh_sigs,
116 .verify_signed_buffer = verify_ssh_signed_buffer,
117 .sign_buffer = sign_buffer_ssh,
118 .get_default_key = get_default_ssh_signing_key,
119 .get_key_id = get_ssh_key_id,
123 static struct gpg_format *use_format = &gpg_format[0];
125 static struct gpg_format *get_format_by_name(const char *str)
127 int i;
129 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
130 if (!strcmp(gpg_format[i].name, str))
131 return gpg_format + i;
132 return NULL;
135 static struct gpg_format *get_format_by_sig(const char *sig)
137 int i, j;
139 for (i = 0; i < ARRAY_SIZE(gpg_format); i++)
140 for (j = 0; gpg_format[i].sigs[j]; j++)
141 if (starts_with(sig, gpg_format[i].sigs[j]))
142 return gpg_format + i;
143 return NULL;
146 void signature_check_clear(struct signature_check *sigc)
148 FREE_AND_NULL(sigc->payload);
149 FREE_AND_NULL(sigc->output);
150 FREE_AND_NULL(sigc->gpg_status);
151 FREE_AND_NULL(sigc->signer);
152 FREE_AND_NULL(sigc->key);
153 FREE_AND_NULL(sigc->fingerprint);
154 FREE_AND_NULL(sigc->primary_key_fingerprint);
157 /* An exclusive status -- only one of them can appear in output */
158 #define GPG_STATUS_EXCLUSIVE (1<<0)
159 /* The status includes key identifier */
160 #define GPG_STATUS_KEYID (1<<1)
161 /* The status includes user identifier */
162 #define GPG_STATUS_UID (1<<2)
163 /* The status includes key fingerprints */
164 #define GPG_STATUS_FINGERPRINT (1<<3)
165 /* The status includes trust level */
166 #define GPG_STATUS_TRUST_LEVEL (1<<4)
168 /* Short-hand for standard exclusive *SIG status with keyid & UID */
169 #define GPG_STATUS_STDSIG (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
171 static struct {
172 char result;
173 const char *check;
174 unsigned int flags;
175 } sigcheck_gpg_status[] = {
176 { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
177 { 'B', "BADSIG ", GPG_STATUS_STDSIG },
178 { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
179 { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
180 { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
181 { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
182 { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
183 { 0, "TRUST_", GPG_STATUS_TRUST_LEVEL },
186 /* Keep the order same as enum signature_trust_level */
187 static struct sigcheck_gpg_trust_level {
188 const char *key;
189 const char *display_key;
190 enum signature_trust_level value;
191 } sigcheck_gpg_trust_level[] = {
192 { "UNDEFINED", "undefined", TRUST_UNDEFINED },
193 { "NEVER", "never", TRUST_NEVER },
194 { "MARGINAL", "marginal", TRUST_MARGINAL },
195 { "FULLY", "fully", TRUST_FULLY },
196 { "ULTIMATE", "ultimate", TRUST_ULTIMATE },
199 static void replace_cstring(char **field, const char *line, const char *next)
201 free(*field);
203 if (line && next)
204 *field = xmemdupz(line, next - line);
205 else
206 *field = NULL;
209 static int parse_gpg_trust_level(const char *level,
210 enum signature_trust_level *res)
212 size_t i;
214 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_trust_level); i++) {
215 if (!strcmp(sigcheck_gpg_trust_level[i].key, level)) {
216 *res = sigcheck_gpg_trust_level[i].value;
217 return 0;
220 return 1;
223 static void parse_gpg_output(struct signature_check *sigc)
225 const char *buf = sigc->gpg_status;
226 const char *line, *next;
227 int i, j;
228 int seen_exclusive_status = 0;
230 /* Iterate over all lines */
231 for (line = buf; *line; line = strchrnul(line+1, '\n')) {
232 while (*line == '\n')
233 line++;
234 if (!*line)
235 break;
237 /* Skip lines that don't start with GNUPG status */
238 if (!skip_prefix(line, "[GNUPG:] ", &line))
239 continue;
241 /* Iterate over all search strings */
242 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
243 if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
245 * GOODSIG, BADSIG etc. can occur only once for
246 * each signature. Therefore, if we had more
247 * than one then we're dealing with multiple
248 * signatures. We don't support them
249 * currently, and they're rather hard to
250 * create, so something is likely fishy and we
251 * should reject them altogether.
253 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
254 if (seen_exclusive_status++)
255 goto error;
258 if (sigcheck_gpg_status[i].result)
259 sigc->result = sigcheck_gpg_status[i].result;
260 /* Do we have key information? */
261 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
262 next = strchrnul(line, ' ');
263 replace_cstring(&sigc->key, line, next);
264 /* Do we have signer information? */
265 if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
266 line = next + 1;
267 next = strchrnul(line, '\n');
268 replace_cstring(&sigc->signer, line, next);
272 /* Do we have trust level? */
273 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
275 * GPG v1 and v2 differs in how the
276 * TRUST_ lines are written. Some
277 * trust lines contain no additional
278 * space-separated information for v1.
280 size_t trust_size = strcspn(line, " \n");
281 char *trust = xmemdupz(line, trust_size);
283 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
284 free(trust);
285 goto error;
287 free(trust);
290 /* Do we have fingerprint? */
291 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
292 const char *limit;
293 char **field;
295 next = strchrnul(line, ' ');
296 replace_cstring(&sigc->fingerprint, line, next);
299 * Skip interim fields. The search is
300 * limited to the same line since only
301 * OpenPGP signatures has a field with
302 * the primary fingerprint.
304 limit = strchrnul(line, '\n');
305 for (j = 9; j > 0; j--) {
306 if (!*next || limit <= next)
307 break;
308 line = next + 1;
309 next = strchrnul(line, ' ');
312 field = &sigc->primary_key_fingerprint;
313 if (!j) {
314 next = strchrnul(line, '\n');
315 replace_cstring(field, line, next);
316 } else {
317 replace_cstring(field, NULL, NULL);
321 break;
325 return;
327 error:
328 sigc->result = 'E';
329 /* Clear partial data to avoid confusion */
330 FREE_AND_NULL(sigc->primary_key_fingerprint);
331 FREE_AND_NULL(sigc->fingerprint);
332 FREE_AND_NULL(sigc->signer);
333 FREE_AND_NULL(sigc->key);
336 static int verify_gpg_signed_buffer(struct signature_check *sigc,
337 struct gpg_format *fmt,
338 const char *signature,
339 size_t signature_size)
341 struct child_process gpg = CHILD_PROCESS_INIT;
342 struct tempfile *temp;
343 int ret;
344 struct strbuf gpg_stdout = STRBUF_INIT;
345 struct strbuf gpg_stderr = STRBUF_INIT;
347 temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
348 if (!temp)
349 return error_errno(_("could not create temporary file"));
350 if (write_in_full(temp->fd, signature, signature_size) < 0 ||
351 close_tempfile_gently(temp) < 0) {
352 error_errno(_("failed writing detached signature to '%s'"),
353 temp->filename.buf);
354 delete_tempfile(&temp);
355 return -1;
358 strvec_push(&gpg.args, fmt->program);
359 strvec_pushv(&gpg.args, fmt->verify_args);
360 strvec_pushl(&gpg.args,
361 "--status-fd=1",
362 "--verify", temp->filename.buf, "-",
363 NULL);
365 sigchain_push(SIGPIPE, SIG_IGN);
366 ret = pipe_command(&gpg, sigc->payload, sigc->payload_len, &gpg_stdout, 0,
367 &gpg_stderr, 0);
368 sigchain_pop(SIGPIPE);
370 delete_tempfile(&temp);
372 ret |= !strstr(gpg_stdout.buf, "\n[GNUPG:] GOODSIG ");
373 sigc->output = strbuf_detach(&gpg_stderr, NULL);
374 sigc->gpg_status = strbuf_detach(&gpg_stdout, NULL);
376 parse_gpg_output(sigc);
378 strbuf_release(&gpg_stdout);
379 strbuf_release(&gpg_stderr);
381 return ret;
384 static void parse_ssh_output(struct signature_check *sigc)
386 const char *line, *principal, *search;
387 char *to_free;
388 char *key = NULL;
391 * ssh-keygen output should be:
392 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
394 * or for valid but unknown keys:
395 * Good "git" signature with RSA key SHA256:FINGERPRINT
397 * Note that "PRINCIPAL" can contain whitespace, "RSA" and
398 * "SHA256" part could be a different token that names of
399 * the algorithms used, and "FINGERPRINT" is a hexadecimal
400 * string. By finding the last occurence of " with ", we can
401 * reliably parse out the PRINCIPAL.
403 sigc->result = 'B';
404 sigc->trust_level = TRUST_NEVER;
406 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
408 if (skip_prefix(line, "Good \"git\" signature for ", &line)) {
409 /* Search for the last "with" to get the full principal */
410 principal = line;
411 do {
412 search = strstr(line, " with ");
413 if (search)
414 line = search + 1;
415 } while (search != NULL);
416 if (line == principal)
417 goto cleanup;
419 /* Valid signature and known principal */
420 sigc->result = 'G';
421 sigc->trust_level = TRUST_FULLY;
422 sigc->signer = xmemdupz(principal, line - principal - 1);
423 } else if (skip_prefix(line, "Good \"git\" signature with ", &line)) {
424 /* Valid signature, but key unknown */
425 sigc->result = 'G';
426 sigc->trust_level = TRUST_UNDEFINED;
427 } else {
428 goto cleanup;
431 key = strstr(line, "key ");
432 if (key) {
433 sigc->fingerprint = xstrdup(strstr(line, "key ") + 4);
434 sigc->key = xstrdup(sigc->fingerprint);
435 } else {
437 * Output did not match what we expected
438 * Treat the signature as bad
440 sigc->result = 'B';
443 cleanup:
444 free(to_free);
447 static int verify_ssh_signed_buffer(struct signature_check *sigc,
448 struct gpg_format *fmt,
449 const char *signature,
450 size_t signature_size)
452 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
453 struct tempfile *buffer_file;
454 int ret = -1;
455 const char *line;
456 char *principal;
457 struct strbuf ssh_principals_out = STRBUF_INIT;
458 struct strbuf ssh_principals_err = STRBUF_INIT;
459 struct strbuf ssh_keygen_out = STRBUF_INIT;
460 struct strbuf ssh_keygen_err = STRBUF_INIT;
461 struct strbuf verify_time = STRBUF_INIT;
462 const struct date_mode verify_date_mode = {
463 .type = DATE_STRFTIME,
464 .strftime_fmt = "%Y%m%d%H%M%S",
465 /* SSH signing key validity has no timezone information - Use the local timezone */
466 .local = 1,
469 if (!ssh_allowed_signers) {
470 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
471 return -1;
474 buffer_file = mks_tempfile_t(".git_vtag_tmpXXXXXX");
475 if (!buffer_file)
476 return error_errno(_("could not create temporary file"));
477 if (write_in_full(buffer_file->fd, signature, signature_size) < 0 ||
478 close_tempfile_gently(buffer_file) < 0) {
479 error_errno(_("failed writing detached signature to '%s'"),
480 buffer_file->filename.buf);
481 delete_tempfile(&buffer_file);
482 return -1;
485 if (sigc->payload_timestamp)
486 strbuf_addf(&verify_time, "-Overify-time=%s",
487 show_date(sigc->payload_timestamp, 0, &verify_date_mode));
489 /* Find the principal from the signers */
490 strvec_pushl(&ssh_keygen.args, fmt->program,
491 "-Y", "find-principals",
492 "-f", ssh_allowed_signers,
493 "-s", buffer_file->filename.buf,
494 verify_time.buf,
495 NULL);
496 ret = pipe_command(&ssh_keygen, NULL, 0, &ssh_principals_out, 0,
497 &ssh_principals_err, 0);
498 if (ret && strstr(ssh_principals_err.buf, "usage:")) {
499 error(_("ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"));
500 goto out;
502 if (ret || !ssh_principals_out.len) {
504 * We did not find a matching principal in the allowedSigners
505 * Check without validation
507 child_process_init(&ssh_keygen);
508 strvec_pushl(&ssh_keygen.args, fmt->program,
509 "-Y", "check-novalidate",
510 "-n", "git",
511 "-s", buffer_file->filename.buf,
512 verify_time.buf,
513 NULL);
514 pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
515 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
518 * Fail on unknown keys
519 * we still call check-novalidate to display the signature info
521 ret = -1;
522 } else {
523 /* Check every principal we found (one per line) */
524 const char *next;
525 for (line = ssh_principals_out.buf;
526 *line;
527 line = next) {
528 const char *end_of_text;
530 next = end_of_text = strchrnul(line, '\n');
532 /* Did we find a LF, and did we have CR before it? */
533 if (*end_of_text &&
534 line < end_of_text &&
535 end_of_text[-1] == '\r')
536 end_of_text--;
538 /* Unless we hit NUL, skip over the LF we found */
539 if (*next)
540 next++;
542 /* Not all lines are data. Skip empty ones */
543 if (line == end_of_text)
544 continue;
546 /* We now know we have an non-empty line. Process it */
547 principal = xmemdupz(line, end_of_text - line);
549 child_process_init(&ssh_keygen);
550 strbuf_release(&ssh_keygen_out);
551 strbuf_release(&ssh_keygen_err);
552 strvec_push(&ssh_keygen.args, fmt->program);
554 * We found principals
555 * Try with each until we find a match
557 strvec_pushl(&ssh_keygen.args, "-Y", "verify",
558 "-n", "git",
559 "-f", ssh_allowed_signers,
560 "-I", principal,
561 "-s", buffer_file->filename.buf,
562 verify_time.buf,
563 NULL);
565 if (ssh_revocation_file) {
566 if (file_exists(ssh_revocation_file)) {
567 strvec_pushl(&ssh_keygen.args, "-r",
568 ssh_revocation_file, NULL);
569 } else {
570 warning(_("ssh signing revocation file configured but not found: %s"),
571 ssh_revocation_file);
575 sigchain_push(SIGPIPE, SIG_IGN);
576 ret = pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
577 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
578 sigchain_pop(SIGPIPE);
580 FREE_AND_NULL(principal);
582 if (!ret)
583 ret = !starts_with(ssh_keygen_out.buf, "Good");
585 if (!ret)
586 break;
590 strbuf_stripspace(&ssh_keygen_out, '\0');
591 strbuf_stripspace(&ssh_keygen_err, '\0');
592 /* Add stderr outputs to show the user actual ssh-keygen errors */
593 strbuf_add(&ssh_keygen_out, ssh_principals_err.buf, ssh_principals_err.len);
594 strbuf_add(&ssh_keygen_out, ssh_keygen_err.buf, ssh_keygen_err.len);
595 sigc->output = strbuf_detach(&ssh_keygen_out, NULL);
596 sigc->gpg_status = xstrdup(sigc->output);
598 parse_ssh_output(sigc);
600 out:
601 if (buffer_file)
602 delete_tempfile(&buffer_file);
603 strbuf_release(&ssh_principals_out);
604 strbuf_release(&ssh_principals_err);
605 strbuf_release(&ssh_keygen_out);
606 strbuf_release(&ssh_keygen_err);
607 strbuf_release(&verify_time);
609 return ret;
612 static int parse_payload_metadata(struct signature_check *sigc)
614 const char *ident_line = NULL;
615 size_t ident_len;
616 struct ident_split ident;
617 const char *signer_header;
619 switch (sigc->payload_type) {
620 case SIGNATURE_PAYLOAD_COMMIT:
621 signer_header = "committer";
622 break;
623 case SIGNATURE_PAYLOAD_TAG:
624 signer_header = "tagger";
625 break;
626 case SIGNATURE_PAYLOAD_UNDEFINED:
627 case SIGNATURE_PAYLOAD_PUSH_CERT:
628 /* Ignore payloads we don't want to parse */
629 return 0;
630 default:
631 BUG("invalid value for sigc->payload_type");
634 ident_line = find_commit_header(sigc->payload, signer_header, &ident_len);
635 if (!ident_line || !ident_len)
636 return 1;
638 if (split_ident_line(&ident, ident_line, ident_len))
639 return 1;
641 if (!sigc->payload_timestamp && ident.date_begin && ident.date_end)
642 sigc->payload_timestamp = parse_timestamp(ident.date_begin, NULL, 10);
644 return 0;
647 int check_signature(struct signature_check *sigc,
648 const char *signature, size_t slen)
650 struct gpg_format *fmt;
651 int status;
653 gpg_interface_lazy_init();
655 sigc->result = 'N';
656 sigc->trust_level = TRUST_UNDEFINED;
658 fmt = get_format_by_sig(signature);
659 if (!fmt)
660 die(_("bad/incompatible signature '%s'"), signature);
662 if (parse_payload_metadata(sigc))
663 return 1;
665 status = fmt->verify_signed_buffer(sigc, fmt, signature, slen);
667 if (status && !sigc->output)
668 return !!status;
670 status |= sigc->result != 'G';
671 status |= sigc->trust_level < configured_min_trust_level;
673 return !!status;
676 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
678 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
679 sigc->output;
681 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
682 fwrite(sigc->payload, 1, sigc->payload_len, stdout);
684 if (output)
685 fputs(output, stderr);
688 size_t parse_signed_buffer(const char *buf, size_t size)
690 size_t len = 0;
691 size_t match = size;
692 while (len < size) {
693 const char *eol;
695 if (get_format_by_sig(buf + len))
696 match = len;
698 eol = memchr(buf + len, '\n', size - len);
699 len += eol ? eol - (buf + len) + 1 : size - len;
701 return match;
704 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
706 size_t match = parse_signed_buffer(buf, size);
707 if (match != size) {
708 strbuf_add(payload, buf, match);
709 remove_signature(payload);
710 strbuf_add(signature, buf + match, size - match);
711 return 1;
713 return 0;
716 void set_signing_key(const char *key)
718 gpg_interface_lazy_init();
720 free(configured_signing_key);
721 configured_signing_key = xstrdup(key);
724 static int git_gpg_config(const char *var, const char *value,
725 const struct config_context *ctx UNUSED,
726 void *cb UNUSED)
728 struct gpg_format *fmt = NULL;
729 char *fmtname = NULL;
730 char *trust;
731 int ret;
733 if (!strcmp(var, "user.signingkey")) {
734 if (!value)
735 return config_error_nonbool(var);
736 set_signing_key(value);
737 return 0;
740 if (!strcmp(var, "gpg.format")) {
741 if (!value)
742 return config_error_nonbool(var);
743 fmt = get_format_by_name(value);
744 if (!fmt)
745 return error(_("invalid value for '%s': '%s'"),
746 var, value);
747 use_format = fmt;
748 return 0;
751 if (!strcmp(var, "gpg.mintrustlevel")) {
752 if (!value)
753 return config_error_nonbool(var);
755 trust = xstrdup_toupper(value);
756 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
757 free(trust);
759 if (ret)
760 return error(_("invalid value for '%s': '%s'"),
761 var, value);
762 return 0;
765 if (!strcmp(var, "gpg.ssh.defaultkeycommand")) {
766 if (!value)
767 return config_error_nonbool(var);
768 return git_config_string(&ssh_default_key_command, var, value);
771 if (!strcmp(var, "gpg.ssh.allowedsignersfile")) {
772 if (!value)
773 return config_error_nonbool(var);
774 return git_config_pathname(&ssh_allowed_signers, var, value);
777 if (!strcmp(var, "gpg.ssh.revocationfile")) {
778 if (!value)
779 return config_error_nonbool(var);
780 return git_config_pathname(&ssh_revocation_file, var, value);
783 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
784 fmtname = "openpgp";
786 if (!strcmp(var, "gpg.x509.program"))
787 fmtname = "x509";
789 if (!strcmp(var, "gpg.ssh.program"))
790 fmtname = "ssh";
792 if (fmtname) {
793 fmt = get_format_by_name(fmtname);
794 return git_config_string(&fmt->program, var, value);
797 return 0;
801 * Returns 1 if `string` contains a literal ssh key, 0 otherwise
802 * `key` will be set to the start of the actual key if a prefix is present.
804 static int is_literal_ssh_key(const char *string, const char **key)
806 if (skip_prefix(string, "key::", key))
807 return 1;
808 if (starts_with(string, "ssh-")) {
809 *key = string;
810 return 1;
812 return 0;
815 static char *get_ssh_key_fingerprint(const char *signing_key)
817 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
818 int ret = -1;
819 struct strbuf fingerprint_stdout = STRBUF_INIT;
820 struct strbuf **fingerprint;
821 char *fingerprint_ret;
822 const char *literal_key = NULL;
825 * With SSH Signing this can contain a filename or a public key
826 * For textual representation we usually want a fingerprint
828 if (is_literal_ssh_key(signing_key, &literal_key)) {
829 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
830 ret = pipe_command(&ssh_keygen, literal_key,
831 strlen(literal_key), &fingerprint_stdout, 0,
832 NULL, 0);
833 } else {
834 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
835 configured_signing_key, NULL);
836 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
837 NULL, 0);
840 if (!!ret)
841 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
842 signing_key);
844 fingerprint = strbuf_split_max(&fingerprint_stdout, ' ', 3);
845 if (!fingerprint[1])
846 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
847 signing_key);
849 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
850 strbuf_list_free(fingerprint);
851 strbuf_release(&fingerprint_stdout);
852 return fingerprint_ret;
855 /* Returns the first public key from an ssh-agent to use for signing */
856 static const char *get_default_ssh_signing_key(void)
858 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
859 int ret = -1;
860 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
861 struct strbuf **keys;
862 char *key_command = NULL;
863 const char **argv;
864 int n;
865 char *default_key = NULL;
866 const char *literal_key = NULL;
868 if (!ssh_default_key_command)
869 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
871 key_command = xstrdup(ssh_default_key_command);
872 n = split_cmdline(key_command, &argv);
874 if (n < 0)
875 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
876 split_cmdline_strerror(n));
878 strvec_pushv(&ssh_default_key.args, argv);
879 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
880 &key_stderr, 0);
882 if (!ret) {
883 keys = strbuf_split_max(&key_stdout, '\n', 2);
884 if (keys[0] && is_literal_ssh_key(keys[0]->buf, &literal_key)) {
886 * We only use `is_literal_ssh_key` here to check validity
887 * The prefix will be stripped when the key is used.
889 default_key = strbuf_detach(keys[0], NULL);
890 } else {
891 warning(_("gpg.ssh.defaultKeyCommand succeeded but returned no keys: %s %s"),
892 key_stderr.buf, key_stdout.buf);
895 strbuf_list_free(keys);
896 } else {
897 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
898 key_stderr.buf, key_stdout.buf);
901 free(key_command);
902 free(argv);
903 strbuf_release(&key_stdout);
905 return default_key;
908 static const char *get_ssh_key_id(void) {
909 return get_ssh_key_fingerprint(get_signing_key());
912 /* Returns a textual but unique representation of the signing key */
913 const char *get_signing_key_id(void)
915 gpg_interface_lazy_init();
917 if (use_format->get_key_id) {
918 return use_format->get_key_id();
921 /* GPG/GPGSM only store a key id on this variable */
922 return get_signing_key();
925 const char *get_signing_key(void)
927 gpg_interface_lazy_init();
929 if (configured_signing_key)
930 return configured_signing_key;
931 if (use_format->get_default_key) {
932 return use_format->get_default_key();
935 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
938 const char *gpg_trust_level_to_str(enum signature_trust_level level)
940 struct sigcheck_gpg_trust_level *trust;
942 if (level < 0 || level >= ARRAY_SIZE(sigcheck_gpg_trust_level))
943 BUG("invalid trust level requested %d", level);
945 trust = &sigcheck_gpg_trust_level[level];
946 if (trust->value != level)
947 BUG("sigcheck_gpg_trust_level[] unsorted");
949 return sigcheck_gpg_trust_level[level].display_key;
952 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
954 gpg_interface_lazy_init();
956 return use_format->sign_buffer(buffer, signature, signing_key);
960 * Strip CR from the line endings, in case we are on Windows.
961 * NEEDSWORK: make it trim only CRs before LFs and rename
963 static void remove_cr_after(struct strbuf *buffer, size_t offset)
965 size_t i, j;
967 for (i = j = offset; i < buffer->len; i++) {
968 if (buffer->buf[i] != '\r') {
969 if (i != j)
970 buffer->buf[j] = buffer->buf[i];
971 j++;
974 strbuf_setlen(buffer, j);
977 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
978 const char *signing_key)
980 struct child_process gpg = CHILD_PROCESS_INIT;
981 int ret;
982 size_t bottom;
983 const char *cp;
984 struct strbuf gpg_status = STRBUF_INIT;
986 strvec_pushl(&gpg.args,
987 use_format->program,
988 "--status-fd=2",
989 "-bsau", signing_key,
990 NULL);
992 bottom = signature->len;
995 * When the username signingkey is bad, program could be terminated
996 * because gpg exits without reading and then write gets SIGPIPE.
998 sigchain_push(SIGPIPE, SIG_IGN);
999 ret = pipe_command(&gpg, buffer->buf, buffer->len,
1000 signature, 1024, &gpg_status, 0);
1001 sigchain_pop(SIGPIPE);
1003 for (cp = gpg_status.buf;
1004 cp && (cp = strstr(cp, "[GNUPG:] SIG_CREATED "));
1005 cp++) {
1006 if (cp == gpg_status.buf || cp[-1] == '\n')
1007 break; /* found */
1009 ret |= !cp;
1010 if (ret) {
1011 error(_("gpg failed to sign the data:\n%s"),
1012 gpg_status.len ? gpg_status.buf : "(no gpg output)");
1013 strbuf_release(&gpg_status);
1014 return -1;
1016 strbuf_release(&gpg_status);
1018 /* Strip CR from the line endings, in case we are on Windows. */
1019 remove_cr_after(signature, bottom);
1021 return 0;
1024 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
1025 const char *signing_key)
1027 struct child_process signer = CHILD_PROCESS_INIT;
1028 int ret = -1;
1029 size_t bottom, keylen;
1030 struct strbuf signer_stderr = STRBUF_INIT;
1031 struct tempfile *key_file = NULL, *buffer_file = NULL;
1032 char *ssh_signing_key_file = NULL;
1033 struct strbuf ssh_signature_filename = STRBUF_INIT;
1034 const char *literal_key = NULL;
1035 int literal_ssh_key = 0;
1037 if (!signing_key || signing_key[0] == '\0')
1038 return error(
1039 _("user.signingKey needs to be set for ssh signing"));
1041 if (is_literal_ssh_key(signing_key, &literal_key)) {
1042 /* A literal ssh key */
1043 literal_ssh_key = 1;
1044 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
1045 if (!key_file)
1046 return error_errno(
1047 _("could not create temporary file"));
1048 keylen = strlen(literal_key);
1049 if (write_in_full(key_file->fd, literal_key, keylen) < 0 ||
1050 close_tempfile_gently(key_file) < 0) {
1051 error_errno(_("failed writing ssh signing key to '%s'"),
1052 key_file->filename.buf);
1053 goto out;
1055 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
1056 } else {
1057 /* We assume a file */
1058 ssh_signing_key_file = interpolate_path(signing_key, 1);
1061 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
1062 if (!buffer_file) {
1063 error_errno(_("could not create temporary file"));
1064 goto out;
1067 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
1068 close_tempfile_gently(buffer_file) < 0) {
1069 error_errno(_("failed writing ssh signing key buffer to '%s'"),
1070 buffer_file->filename.buf);
1071 goto out;
1074 strvec_pushl(&signer.args, use_format->program,
1075 "-Y", "sign",
1076 "-n", "git",
1077 "-f", ssh_signing_key_file,
1078 NULL);
1079 if (literal_ssh_key)
1080 strvec_push(&signer.args, "-U");
1081 strvec_push(&signer.args, buffer_file->filename.buf);
1083 sigchain_push(SIGPIPE, SIG_IGN);
1084 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
1085 sigchain_pop(SIGPIPE);
1087 if (ret) {
1088 if (strstr(signer_stderr.buf, "usage:"))
1089 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
1091 error("%s", signer_stderr.buf);
1092 goto out;
1095 bottom = signature->len;
1097 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
1098 strbuf_addstr(&ssh_signature_filename, ".sig");
1099 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
1100 ret = error_errno(
1101 _("failed reading ssh signing data buffer from '%s'"),
1102 ssh_signature_filename.buf);
1103 goto out;
1105 /* Strip CR from the line endings, in case we are on Windows. */
1106 remove_cr_after(signature, bottom);
1108 out:
1109 if (key_file)
1110 delete_tempfile(&key_file);
1111 if (buffer_file)
1112 delete_tempfile(&buffer_file);
1113 if (ssh_signature_filename.len)
1114 unlink_or_warn(ssh_signature_filename.buf);
1115 strbuf_release(&signer_stderr);
1116 strbuf_release(&ssh_signature_filename);
1117 FREE_AND_NULL(ssh_signing_key_file);
1118 return ret;