]> git.ipfire.org Git - thirdparty/git.git/blob - gpg-interface.c
Merge branch 'ab/pkt-line-cleanup'
[thirdparty/git.git] / gpg-interface.c
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"
11
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;
15
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);
29 };
30
31 static const char *openpgp_verify_args[] = {
32 "--keyid-format=long",
33 NULL
34 };
35 static const char *openpgp_sigs[] = {
36 "-----BEGIN PGP SIGNATURE-----",
37 "-----BEGIN PGP MESSAGE-----",
38 NULL
39 };
40
41 static const char *x509_verify_args[] = {
42 NULL
43 };
44 static const char *x509_sigs[] = {
45 "-----BEGIN SIGNED MESSAGE-----",
46 NULL
47 };
48
49 static const char *ssh_verify_args[] = { NULL };
50 static const char *ssh_sigs[] = {
51 "-----BEGIN SSH SIGNATURE-----",
52 NULL
53 };
54
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);
67
68 static const char *get_default_ssh_signing_key(void);
69
70 static const char *get_ssh_key_id(void);
71
72 static struct gpg_format gpg_format[] = {
73 {
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,
82 },
83 {
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,
92 },
93 {
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,
102 },
103 };
104
105 static struct gpg_format *use_format = &gpg_format[0];
106
107 static struct gpg_format *get_format_by_name(const char *str)
108 {
109 int i;
110
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;
115 }
116
117 static struct gpg_format *get_format_by_sig(const char *sig)
118 {
119 int i, j;
120
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;
126 }
127
128 void signature_check_clear(struct signature_check *sigc)
129 {
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);
137 }
138
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)
149
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)
152
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 },
166 };
167
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 },
177 };
178
179 static void replace_cstring(char **field, const char *line, const char *next)
180 {
181 free(*field);
182
183 if (line && next)
184 *field = xmemdupz(line, next - line);
185 else
186 *field = NULL;
187 }
188
189 static int parse_gpg_trust_level(const char *level,
190 enum signature_trust_level *res)
191 {
192 size_t i;
193
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;
198 }
199 }
200 return 1;
201 }
202
203 static void parse_gpg_output(struct signature_check *sigc)
204 {
205 const char *buf = sigc->gpg_status;
206 const char *line, *next;
207 int i, j;
208 int seen_exclusive_status = 0;
209
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;
216
217 /* Skip lines that don't start with GNUPG status */
218 if (!skip_prefix(line, "[GNUPG:] ", &line))
219 continue;
220
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)) {
224 /*
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.
232 */
233 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
234 if (seen_exclusive_status++)
235 goto error;
236 }
237
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);
249 }
250 }
251
252 /* Do we have trust level? */
253 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
254 /*
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.
259 */
260 size_t trust_size = strcspn(line, " \n");
261 char *trust = xmemdupz(line, trust_size);
262
263 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
264 free(trust);
265 goto error;
266 }
267 free(trust);
268 }
269
270 /* Do we have fingerprint? */
271 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
272 const char *limit;
273 char **field;
274
275 next = strchrnul(line, ' ');
276 replace_cstring(&sigc->fingerprint, line, next);
277
278 /*
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.
283 */
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, ' ');
290 }
291
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);
298 }
299 }
300
301 break;
302 }
303 }
304 }
305 return;
306
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);
314 }
315
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)
320 {
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;
326
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;
336 }
337
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);
344
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);
349
350 delete_tempfile(&temp);
351
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);
356
357 parse_gpg_output(sigc);
358
359 strbuf_release(&gpg_stdout);
360 strbuf_release(&gpg_stderr);
361
362 return ret;
363 }
364
365 static void parse_ssh_output(struct signature_check *sigc)
366 {
367 const char *line, *principal, *search;
368 char *to_free;
369 char *key = NULL;
370
371 /*
372 * ssh-keygen output should be:
373 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
374 *
375 * or for valid but unknown keys:
376 * Good "git" signature with RSA key SHA256:FINGERPRINT
377 *
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.
383 */
384 sigc->result = 'B';
385 sigc->trust_level = TRUST_NEVER;
386
387 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
388
389 if (skip_prefix(line, "Good \"git\" signature for ", &line)) {
390 /* Valid signature and known principal */
391 sigc->result = 'G';
392 sigc->trust_level = TRUST_FULLY;
393
394 /* Search for the last "with" to get the full principal */
395 principal = line;
396 do {
397 search = strstr(line, " with ");
398 if (search)
399 line = search + 1;
400 } while (search != NULL);
401 sigc->signer = xmemdupz(principal, line - principal - 1);
402 } else if (skip_prefix(line, "Good \"git\" signature with ", &line)) {
403 /* Valid signature, but key unknown */
404 sigc->result = 'G';
405 sigc->trust_level = TRUST_UNDEFINED;
406 } else {
407 goto cleanup;
408 }
409
410 key = strstr(line, "key");
411 if (key) {
412 sigc->fingerprint = xstrdup(strstr(line, "key") + 4);
413 sigc->key = xstrdup(sigc->fingerprint);
414 } else {
415 /*
416 * Output did not match what we expected
417 * Treat the signature as bad
418 */
419 sigc->result = 'B';
420 }
421
422 cleanup:
423 free(to_free);
424 }
425
426 static int verify_ssh_signed_buffer(struct signature_check *sigc,
427 struct gpg_format *fmt, const char *payload,
428 size_t payload_size, const char *signature,
429 size_t signature_size)
430 {
431 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
432 struct tempfile *buffer_file;
433 int ret = -1;
434 const char *line;
435 size_t trust_size;
436 char *principal;
437 struct strbuf ssh_principals_out = STRBUF_INIT;
438 struct strbuf ssh_principals_err = STRBUF_INIT;
439 struct strbuf ssh_keygen_out = STRBUF_INIT;
440 struct strbuf ssh_keygen_err = STRBUF_INIT;
441
442 if (!ssh_allowed_signers) {
443 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
444 return -1;
445 }
446
447 buffer_file = mks_tempfile_t(".git_vtag_tmpXXXXXX");
448 if (!buffer_file)
449 return error_errno(_("could not create temporary file"));
450 if (write_in_full(buffer_file->fd, signature, signature_size) < 0 ||
451 close_tempfile_gently(buffer_file) < 0) {
452 error_errno(_("failed writing detached signature to '%s'"),
453 buffer_file->filename.buf);
454 delete_tempfile(&buffer_file);
455 return -1;
456 }
457
458 /* Find the principal from the signers */
459 strvec_pushl(&ssh_keygen.args, fmt->program,
460 "-Y", "find-principals",
461 "-f", ssh_allowed_signers,
462 "-s", buffer_file->filename.buf,
463 NULL);
464 ret = pipe_command(&ssh_keygen, NULL, 0, &ssh_principals_out, 0,
465 &ssh_principals_err, 0);
466 if (ret && strstr(ssh_principals_err.buf, "usage:")) {
467 error(_("ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"));
468 goto out;
469 }
470 if (ret || !ssh_principals_out.len) {
471 /*
472 * We did not find a matching principal in the allowedSigners
473 * Check without validation
474 */
475 child_process_init(&ssh_keygen);
476 strvec_pushl(&ssh_keygen.args, fmt->program,
477 "-Y", "check-novalidate",
478 "-n", "git",
479 "-s", buffer_file->filename.buf,
480 NULL);
481 pipe_command(&ssh_keygen, payload, payload_size,
482 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
483
484 /*
485 * Fail on unknown keys
486 * we still call check-novalidate to display the signature info
487 */
488 ret = -1;
489 } else {
490 /* Check every principal we found (one per line) */
491 for (line = ssh_principals_out.buf; *line;
492 line = strchrnul(line + 1, '\n')) {
493 while (*line == '\n')
494 line++;
495 if (!*line)
496 break;
497
498 trust_size = strcspn(line, "\n");
499 principal = xmemdupz(line, trust_size);
500
501 child_process_init(&ssh_keygen);
502 strbuf_release(&ssh_keygen_out);
503 strbuf_release(&ssh_keygen_err);
504 strvec_push(&ssh_keygen.args, fmt->program);
505 /*
506 * We found principals
507 * Try with each until we find a match
508 */
509 strvec_pushl(&ssh_keygen.args, "-Y", "verify",
510 "-n", "git",
511 "-f", ssh_allowed_signers,
512 "-I", principal,
513 "-s", buffer_file->filename.buf,
514 NULL);
515
516 if (ssh_revocation_file) {
517 if (file_exists(ssh_revocation_file)) {
518 strvec_pushl(&ssh_keygen.args, "-r",
519 ssh_revocation_file, NULL);
520 } else {
521 warning(_("ssh signing revocation file configured but not found: %s"),
522 ssh_revocation_file);
523 }
524 }
525
526 sigchain_push(SIGPIPE, SIG_IGN);
527 ret = pipe_command(&ssh_keygen, payload, payload_size,
528 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
529 sigchain_pop(SIGPIPE);
530
531 FREE_AND_NULL(principal);
532
533 if (!ret)
534 ret = !starts_with(ssh_keygen_out.buf, "Good");
535
536 if (!ret)
537 break;
538 }
539 }
540
541 sigc->payload = xmemdupz(payload, payload_size);
542 strbuf_stripspace(&ssh_keygen_out, 0);
543 strbuf_stripspace(&ssh_keygen_err, 0);
544 /* Add stderr outputs to show the user actual ssh-keygen errors */
545 strbuf_add(&ssh_keygen_out, ssh_principals_err.buf, ssh_principals_err.len);
546 strbuf_add(&ssh_keygen_out, ssh_keygen_err.buf, ssh_keygen_err.len);
547 sigc->output = strbuf_detach(&ssh_keygen_out, NULL);
548 sigc->gpg_status = xstrdup(sigc->output);
549
550 parse_ssh_output(sigc);
551
552 out:
553 if (buffer_file)
554 delete_tempfile(&buffer_file);
555 strbuf_release(&ssh_principals_out);
556 strbuf_release(&ssh_principals_err);
557 strbuf_release(&ssh_keygen_out);
558 strbuf_release(&ssh_keygen_err);
559
560 return ret;
561 }
562
563 int check_signature(const char *payload, size_t plen, const char *signature,
564 size_t slen, struct signature_check *sigc)
565 {
566 struct gpg_format *fmt;
567 int status;
568
569 sigc->result = 'N';
570 sigc->trust_level = -1;
571
572 fmt = get_format_by_sig(signature);
573 if (!fmt)
574 die(_("bad/incompatible signature '%s'"), signature);
575
576 status = fmt->verify_signed_buffer(sigc, fmt, payload, plen, signature,
577 slen);
578
579 if (status && !sigc->output)
580 return !!status;
581
582 status |= sigc->result != 'G';
583 status |= sigc->trust_level < configured_min_trust_level;
584
585 return !!status;
586 }
587
588 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
589 {
590 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
591 sigc->output;
592
593 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
594 fputs(sigc->payload, stdout);
595
596 if (output)
597 fputs(output, stderr);
598 }
599
600 size_t parse_signed_buffer(const char *buf, size_t size)
601 {
602 size_t len = 0;
603 size_t match = size;
604 while (len < size) {
605 const char *eol;
606
607 if (get_format_by_sig(buf + len))
608 match = len;
609
610 eol = memchr(buf + len, '\n', size - len);
611 len += eol ? eol - (buf + len) + 1 : size - len;
612 }
613 return match;
614 }
615
616 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
617 {
618 size_t match = parse_signed_buffer(buf, size);
619 if (match != size) {
620 strbuf_add(payload, buf, match);
621 remove_signature(payload);
622 strbuf_add(signature, buf + match, size - match);
623 return 1;
624 }
625 return 0;
626 }
627
628 void set_signing_key(const char *key)
629 {
630 free(configured_signing_key);
631 configured_signing_key = xstrdup(key);
632 }
633
634 int git_gpg_config(const char *var, const char *value, void *cb)
635 {
636 struct gpg_format *fmt = NULL;
637 char *fmtname = NULL;
638 char *trust;
639 int ret;
640
641 if (!strcmp(var, "user.signingkey")) {
642 if (!value)
643 return config_error_nonbool(var);
644 set_signing_key(value);
645 return 0;
646 }
647
648 if (!strcmp(var, "gpg.format")) {
649 if (!value)
650 return config_error_nonbool(var);
651 fmt = get_format_by_name(value);
652 if (!fmt)
653 return error("unsupported value for %s: %s",
654 var, value);
655 use_format = fmt;
656 return 0;
657 }
658
659 if (!strcmp(var, "gpg.mintrustlevel")) {
660 if (!value)
661 return config_error_nonbool(var);
662
663 trust = xstrdup_toupper(value);
664 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
665 free(trust);
666
667 if (ret)
668 return error("unsupported value for %s: %s", var,
669 value);
670 return 0;
671 }
672
673 if (!strcmp(var, "gpg.ssh.defaultkeycommand")) {
674 if (!value)
675 return config_error_nonbool(var);
676 return git_config_string(&ssh_default_key_command, var, value);
677 }
678
679 if (!strcmp(var, "gpg.ssh.allowedsignersfile")) {
680 if (!value)
681 return config_error_nonbool(var);
682 return git_config_pathname(&ssh_allowed_signers, var, value);
683 }
684
685 if (!strcmp(var, "gpg.ssh.revocationfile")) {
686 if (!value)
687 return config_error_nonbool(var);
688 return git_config_pathname(&ssh_revocation_file, var, value);
689 }
690
691 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
692 fmtname = "openpgp";
693
694 if (!strcmp(var, "gpg.x509.program"))
695 fmtname = "x509";
696
697 if (!strcmp(var, "gpg.ssh.program"))
698 fmtname = "ssh";
699
700 if (fmtname) {
701 fmt = get_format_by_name(fmtname);
702 return git_config_string(&fmt->program, var, value);
703 }
704
705 return 0;
706 }
707
708 static char *get_ssh_key_fingerprint(const char *signing_key)
709 {
710 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
711 int ret = -1;
712 struct strbuf fingerprint_stdout = STRBUF_INIT;
713 struct strbuf **fingerprint;
714 char *fingerprint_ret;
715
716 /*
717 * With SSH Signing this can contain a filename or a public key
718 * For textual representation we usually want a fingerprint
719 */
720 if (starts_with(signing_key, "ssh-")) {
721 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
722 ret = pipe_command(&ssh_keygen, signing_key,
723 strlen(signing_key), &fingerprint_stdout, 0,
724 NULL, 0);
725 } else {
726 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
727 configured_signing_key, NULL);
728 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
729 NULL, 0);
730 }
731
732 if (!!ret)
733 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
734 signing_key);
735
736 fingerprint = strbuf_split_max(&fingerprint_stdout, ' ', 3);
737 if (!fingerprint[1])
738 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
739 signing_key);
740
741 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
742 strbuf_list_free(fingerprint);
743 strbuf_release(&fingerprint_stdout);
744 return fingerprint_ret;
745 }
746
747 /* Returns the first public key from an ssh-agent to use for signing */
748 static const char *get_default_ssh_signing_key(void)
749 {
750 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
751 int ret = -1;
752 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
753 struct strbuf **keys;
754 char *key_command = NULL;
755 const char **argv;
756 int n;
757 char *default_key = NULL;
758
759 if (!ssh_default_key_command)
760 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
761
762 key_command = xstrdup(ssh_default_key_command);
763 n = split_cmdline(key_command, &argv);
764
765 if (n < 0)
766 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
767 split_cmdline_strerror(n));
768
769 strvec_pushv(&ssh_default_key.args, argv);
770 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
771 &key_stderr, 0);
772
773 if (!ret) {
774 keys = strbuf_split_max(&key_stdout, '\n', 2);
775 if (keys[0] && starts_with(keys[0]->buf, "ssh-")) {
776 default_key = strbuf_detach(keys[0], NULL);
777 } else {
778 warning(_("gpg.ssh.defaultKeycommand succeeded but returned no keys: %s %s"),
779 key_stderr.buf, key_stdout.buf);
780 }
781
782 strbuf_list_free(keys);
783 } else {
784 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
785 key_stderr.buf, key_stdout.buf);
786 }
787
788 free(key_command);
789 free(argv);
790 strbuf_release(&key_stdout);
791
792 return default_key;
793 }
794
795 static const char *get_ssh_key_id(void) {
796 return get_ssh_key_fingerprint(get_signing_key());
797 }
798
799 /* Returns a textual but unique representation of the signing key */
800 const char *get_signing_key_id(void)
801 {
802 if (use_format->get_key_id) {
803 return use_format->get_key_id();
804 }
805
806 /* GPG/GPGSM only store a key id on this variable */
807 return get_signing_key();
808 }
809
810 const char *get_signing_key(void)
811 {
812 if (configured_signing_key)
813 return configured_signing_key;
814 if (use_format->get_default_key) {
815 return use_format->get_default_key();
816 }
817
818 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
819 }
820
821 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
822 {
823 return use_format->sign_buffer(buffer, signature, signing_key);
824 }
825
826 /*
827 * Strip CR from the line endings, in case we are on Windows.
828 * NEEDSWORK: make it trim only CRs before LFs and rename
829 */
830 static void remove_cr_after(struct strbuf *buffer, size_t offset)
831 {
832 size_t i, j;
833
834 for (i = j = offset; i < buffer->len; i++) {
835 if (buffer->buf[i] != '\r') {
836 if (i != j)
837 buffer->buf[j] = buffer->buf[i];
838 j++;
839 }
840 }
841 strbuf_setlen(buffer, j);
842 }
843
844 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
845 const char *signing_key)
846 {
847 struct child_process gpg = CHILD_PROCESS_INIT;
848 int ret;
849 size_t bottom;
850 struct strbuf gpg_status = STRBUF_INIT;
851
852 strvec_pushl(&gpg.args,
853 use_format->program,
854 "--status-fd=2",
855 "-bsau", signing_key,
856 NULL);
857
858 bottom = signature->len;
859
860 /*
861 * When the username signingkey is bad, program could be terminated
862 * because gpg exits without reading and then write gets SIGPIPE.
863 */
864 sigchain_push(SIGPIPE, SIG_IGN);
865 ret = pipe_command(&gpg, buffer->buf, buffer->len,
866 signature, 1024, &gpg_status, 0);
867 sigchain_pop(SIGPIPE);
868
869 ret |= !strstr(gpg_status.buf, "\n[GNUPG:] SIG_CREATED ");
870 strbuf_release(&gpg_status);
871 if (ret)
872 return error(_("gpg failed to sign the data"));
873
874 /* Strip CR from the line endings, in case we are on Windows. */
875 remove_cr_after(signature, bottom);
876
877 return 0;
878 }
879
880 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
881 const char *signing_key)
882 {
883 struct child_process signer = CHILD_PROCESS_INIT;
884 int ret = -1;
885 size_t bottom, keylen;
886 struct strbuf signer_stderr = STRBUF_INIT;
887 struct tempfile *key_file = NULL, *buffer_file = NULL;
888 char *ssh_signing_key_file = NULL;
889 struct strbuf ssh_signature_filename = STRBUF_INIT;
890
891 if (!signing_key || signing_key[0] == '\0')
892 return error(
893 _("user.signingkey needs to be set for ssh signing"));
894
895 if (starts_with(signing_key, "ssh-")) {
896 /* A literal ssh key */
897 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
898 if (!key_file)
899 return error_errno(
900 _("could not create temporary file"));
901 keylen = strlen(signing_key);
902 if (write_in_full(key_file->fd, signing_key, keylen) < 0 ||
903 close_tempfile_gently(key_file) < 0) {
904 error_errno(_("failed writing ssh signing key to '%s'"),
905 key_file->filename.buf);
906 goto out;
907 }
908 ssh_signing_key_file = strbuf_detach(&key_file->filename, NULL);
909 } else {
910 /* We assume a file */
911 ssh_signing_key_file = expand_user_path(signing_key, 1);
912 }
913
914 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
915 if (!buffer_file) {
916 error_errno(_("could not create temporary file"));
917 goto out;
918 }
919
920 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
921 close_tempfile_gently(buffer_file) < 0) {
922 error_errno(_("failed writing ssh signing key buffer to '%s'"),
923 buffer_file->filename.buf);
924 goto out;
925 }
926
927 strvec_pushl(&signer.args, use_format->program,
928 "-Y", "sign",
929 "-n", "git",
930 "-f", ssh_signing_key_file,
931 buffer_file->filename.buf,
932 NULL);
933
934 sigchain_push(SIGPIPE, SIG_IGN);
935 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
936 sigchain_pop(SIGPIPE);
937
938 if (ret) {
939 if (strstr(signer_stderr.buf, "usage:"))
940 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
941
942 error("%s", signer_stderr.buf);
943 goto out;
944 }
945
946 bottom = signature->len;
947
948 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
949 strbuf_addstr(&ssh_signature_filename, ".sig");
950 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
951 error_errno(
952 _("failed reading ssh signing data buffer from '%s'"),
953 ssh_signature_filename.buf);
954 }
955 unlink_or_warn(ssh_signature_filename.buf);
956
957 /* Strip CR from the line endings, in case we are on Windows. */
958 remove_cr_after(signature, bottom);
959
960 out:
961 if (key_file)
962 delete_tempfile(&key_file);
963 if (buffer_file)
964 delete_tempfile(&buffer_file);
965 strbuf_release(&signer_stderr);
966 strbuf_release(&ssh_signature_filename);
967 FREE_AND_NULL(ssh_signing_key_file);
968 return ret;
969 }