]> git.ipfire.org Git - thirdparty/git.git/blob - gpg-interface.c
test-lib-functions.sh: fix test_grep fail message wording
[thirdparty/git.git] / gpg-interface.c
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"
16
17 static int git_gpg_config(const char *, const char *,
18 const struct config_context *, void *);
19
20 static void gpg_interface_lazy_init(void)
21 {
22 static int done;
23
24 if (done)
25 return;
26 done = 1;
27 git_config(git_gpg_config, NULL);
28 }
29
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;
33
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);
47 };
48
49 static const char *openpgp_verify_args[] = {
50 "--keyid-format=long",
51 NULL
52 };
53 static const char *openpgp_sigs[] = {
54 "-----BEGIN PGP SIGNATURE-----",
55 "-----BEGIN PGP MESSAGE-----",
56 NULL
57 };
58
59 static const char *x509_verify_args[] = {
60 NULL
61 };
62 static const char *x509_sigs[] = {
63 "-----BEGIN SIGNED MESSAGE-----",
64 NULL
65 };
66
67 static const char *ssh_verify_args[] = { NULL };
68 static const char *ssh_sigs[] = {
69 "-----BEGIN SSH SIGNATURE-----",
70 NULL
71 };
72
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);
85
86 static const char *get_default_ssh_signing_key(void);
87
88 static const char *get_ssh_key_id(void);
89
90 static struct gpg_format gpg_format[] = {
91 {
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,
100 },
101 {
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,
110 },
111 {
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,
120 },
121 };
122
123 static struct gpg_format *use_format = &gpg_format[0];
124
125 static struct gpg_format *get_format_by_name(const char *str)
126 {
127 int i;
128
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;
133 }
134
135 static struct gpg_format *get_format_by_sig(const char *sig)
136 {
137 int i, j;
138
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;
144 }
145
146 void signature_check_clear(struct signature_check *sigc)
147 {
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);
155 }
156
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)
167
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)
170
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 },
184 };
185
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 },
197 };
198
199 static void replace_cstring(char **field, const char *line, const char *next)
200 {
201 free(*field);
202
203 if (line && next)
204 *field = xmemdupz(line, next - line);
205 else
206 *field = NULL;
207 }
208
209 static int parse_gpg_trust_level(const char *level,
210 enum signature_trust_level *res)
211 {
212 size_t i;
213
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;
218 }
219 }
220 return 1;
221 }
222
223 static void parse_gpg_output(struct signature_check *sigc)
224 {
225 const char *buf = sigc->gpg_status;
226 const char *line, *next;
227 int i, j;
228 int seen_exclusive_status = 0;
229
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;
236
237 /* Skip lines that don't start with GNUPG status */
238 if (!skip_prefix(line, "[GNUPG:] ", &line))
239 continue;
240
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)) {
244 /*
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.
252 */
253 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
254 if (seen_exclusive_status++)
255 goto error;
256 }
257
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);
269 }
270 }
271
272 /* Do we have trust level? */
273 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
274 /*
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.
279 */
280 size_t trust_size = strcspn(line, " \n");
281 char *trust = xmemdupz(line, trust_size);
282
283 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
284 free(trust);
285 goto error;
286 }
287 free(trust);
288 }
289
290 /* Do we have fingerprint? */
291 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
292 const char *limit;
293 char **field;
294
295 next = strchrnul(line, ' ');
296 replace_cstring(&sigc->fingerprint, line, next);
297
298 /*
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.
303 */
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, ' ');
310 }
311
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);
318 }
319 }
320
321 break;
322 }
323 }
324 }
325 return;
326
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);
334 }
335
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)
340 {
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;
346
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;
356 }
357
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);
364
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);
369
370 delete_tempfile(&temp);
371
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);
375
376 parse_gpg_output(sigc);
377
378 strbuf_release(&gpg_stdout);
379 strbuf_release(&gpg_stderr);
380
381 return ret;
382 }
383
384 static void parse_ssh_output(struct signature_check *sigc)
385 {
386 const char *line, *principal, *search;
387 char *to_free;
388 char *key = NULL;
389
390 /*
391 * ssh-keygen output should be:
392 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
393 *
394 * or for valid but unknown keys:
395 * Good "git" signature with RSA key SHA256:FINGERPRINT
396 *
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.
402 */
403 sigc->result = 'B';
404 sigc->trust_level = TRUST_NEVER;
405
406 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
407
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;
418
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;
429 }
430
431 key = strstr(line, "key ");
432 if (key) {
433 sigc->fingerprint = xstrdup(strstr(line, "key ") + 4);
434 sigc->key = xstrdup(sigc->fingerprint);
435 } else {
436 /*
437 * Output did not match what we expected
438 * Treat the signature as bad
439 */
440 sigc->result = 'B';
441 }
442
443 cleanup:
444 free(to_free);
445 }
446
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)
451 {
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,
467 };
468
469 if (!ssh_allowed_signers) {
470 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
471 return -1;
472 }
473
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;
483 }
484
485 if (sigc->payload_timestamp)
486 strbuf_addf(&verify_time, "-Overify-time=%s",
487 show_date(sigc->payload_timestamp, 0, &verify_date_mode));
488
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;
501 }
502 if (ret || !ssh_principals_out.len) {
503 /*
504 * We did not find a matching principal in the allowedSigners
505 * Check without validation
506 */
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);
516
517 /*
518 * Fail on unknown keys
519 * we still call check-novalidate to display the signature info
520 */
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;
529
530 next = end_of_text = strchrnul(line, '\n');
531
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--;
537
538 /* Unless we hit NUL, skip over the LF we found */
539 if (*next)
540 next++;
541
542 /* Not all lines are data. Skip empty ones */
543 if (line == end_of_text)
544 continue;
545
546 /* We now know we have an non-empty line. Process it */
547 principal = xmemdupz(line, end_of_text - line);
548
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);
553 /*
554 * We found principals
555 * Try with each until we find a match
556 */
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);
564
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);
572 }
573 }
574
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);
579
580 FREE_AND_NULL(principal);
581
582 if (!ret)
583 ret = !starts_with(ssh_keygen_out.buf, "Good");
584
585 if (!ret)
586 break;
587 }
588 }
589
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);
597
598 parse_ssh_output(sigc);
599
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);
608
609 return ret;
610 }
611
612 static int parse_payload_metadata(struct signature_check *sigc)
613 {
614 const char *ident_line = NULL;
615 size_t ident_len;
616 struct ident_split ident;
617 const char *signer_header;
618
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");
632 }
633
634 ident_line = find_commit_header(sigc->payload, signer_header, &ident_len);
635 if (!ident_line || !ident_len)
636 return 1;
637
638 if (split_ident_line(&ident, ident_line, ident_len))
639 return 1;
640
641 if (!sigc->payload_timestamp && ident.date_begin && ident.date_end)
642 sigc->payload_timestamp = parse_timestamp(ident.date_begin, NULL, 10);
643
644 return 0;
645 }
646
647 int check_signature(struct signature_check *sigc,
648 const char *signature, size_t slen)
649 {
650 struct gpg_format *fmt;
651 int status;
652
653 gpg_interface_lazy_init();
654
655 sigc->result = 'N';
656 sigc->trust_level = TRUST_UNDEFINED;
657
658 fmt = get_format_by_sig(signature);
659 if (!fmt)
660 die(_("bad/incompatible signature '%s'"), signature);
661
662 if (parse_payload_metadata(sigc))
663 return 1;
664
665 status = fmt->verify_signed_buffer(sigc, fmt, signature, slen);
666
667 if (status && !sigc->output)
668 return !!status;
669
670 status |= sigc->result != 'G';
671 status |= sigc->trust_level < configured_min_trust_level;
672
673 return !!status;
674 }
675
676 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
677 {
678 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
679 sigc->output;
680
681 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
682 fwrite(sigc->payload, 1, sigc->payload_len, stdout);
683
684 if (output)
685 fputs(output, stderr);
686 }
687
688 size_t parse_signed_buffer(const char *buf, size_t size)
689 {
690 size_t len = 0;
691 size_t match = size;
692 while (len < size) {
693 const char *eol;
694
695 if (get_format_by_sig(buf + len))
696 match = len;
697
698 eol = memchr(buf + len, '\n', size - len);
699 len += eol ? eol - (buf + len) + 1 : size - len;
700 }
701 return match;
702 }
703
704 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
705 {
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;
712 }
713 return 0;
714 }
715
716 void set_signing_key(const char *key)
717 {
718 gpg_interface_lazy_init();
719
720 free(configured_signing_key);
721 configured_signing_key = xstrdup(key);
722 }
723
724 static int git_gpg_config(const char *var, const char *value,
725 const struct config_context *ctx UNUSED,
726 void *cb UNUSED)
727 {
728 struct gpg_format *fmt = NULL;
729 char *fmtname = NULL;
730 char *trust;
731 int ret;
732
733 if (!strcmp(var, "user.signingkey")) {
734 if (!value)
735 return config_error_nonbool(var);
736 set_signing_key(value);
737 return 0;
738 }
739
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;
749 }
750
751 if (!strcmp(var, "gpg.mintrustlevel")) {
752 if (!value)
753 return config_error_nonbool(var);
754
755 trust = xstrdup_toupper(value);
756 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
757 free(trust);
758
759 if (ret)
760 return error(_("invalid value for '%s': '%s'"),
761 var, value);
762 return 0;
763 }
764
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);
769 }
770
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);
775 }
776
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);
781 }
782
783 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
784 fmtname = "openpgp";
785
786 if (!strcmp(var, "gpg.x509.program"))
787 fmtname = "x509";
788
789 if (!strcmp(var, "gpg.ssh.program"))
790 fmtname = "ssh";
791
792 if (fmtname) {
793 fmt = get_format_by_name(fmtname);
794 return git_config_string(&fmt->program, var, value);
795 }
796
797 return 0;
798 }
799
800 /*
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.
803 */
804 static int is_literal_ssh_key(const char *string, const char **key)
805 {
806 if (skip_prefix(string, "key::", key))
807 return 1;
808 if (starts_with(string, "ssh-")) {
809 *key = string;
810 return 1;
811 }
812 return 0;
813 }
814
815 static char *get_ssh_key_fingerprint(const char *signing_key)
816 {
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;
823
824 /*
825 * With SSH Signing this can contain a filename or a public key
826 * For textual representation we usually want a fingerprint
827 */
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);
838 }
839
840 if (!!ret)
841 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
842 signing_key);
843
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);
848
849 fingerprint_ret = strbuf_detach(fingerprint[1], NULL);
850 strbuf_list_free(fingerprint);
851 strbuf_release(&fingerprint_stdout);
852 return fingerprint_ret;
853 }
854
855 /* Returns the first public key from an ssh-agent to use for signing */
856 static const char *get_default_ssh_signing_key(void)
857 {
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;
867
868 if (!ssh_default_key_command)
869 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
870
871 key_command = xstrdup(ssh_default_key_command);
872 n = split_cmdline(key_command, &argv);
873
874 if (n < 0)
875 die("malformed build-time gpg.ssh.defaultKeyCommand: %s",
876 split_cmdline_strerror(n));
877
878 strvec_pushv(&ssh_default_key.args, argv);
879 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
880 &key_stderr, 0);
881
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)) {
885 /*
886 * We only use `is_literal_ssh_key` here to check validity
887 * The prefix will be stripped when the key is used.
888 */
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);
893 }
894
895 strbuf_list_free(keys);
896 } else {
897 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
898 key_stderr.buf, key_stdout.buf);
899 }
900
901 free(key_command);
902 free(argv);
903 strbuf_release(&key_stdout);
904
905 return default_key;
906 }
907
908 static const char *get_ssh_key_id(void) {
909 return get_ssh_key_fingerprint(get_signing_key());
910 }
911
912 /* Returns a textual but unique representation of the signing key */
913 const char *get_signing_key_id(void)
914 {
915 gpg_interface_lazy_init();
916
917 if (use_format->get_key_id) {
918 return use_format->get_key_id();
919 }
920
921 /* GPG/GPGSM only store a key id on this variable */
922 return get_signing_key();
923 }
924
925 const char *get_signing_key(void)
926 {
927 gpg_interface_lazy_init();
928
929 if (configured_signing_key)
930 return configured_signing_key;
931 if (use_format->get_default_key) {
932 return use_format->get_default_key();
933 }
934
935 return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
936 }
937
938 const char *gpg_trust_level_to_str(enum signature_trust_level level)
939 {
940 struct sigcheck_gpg_trust_level *trust;
941
942 if (level < 0 || level >= ARRAY_SIZE(sigcheck_gpg_trust_level))
943 BUG("invalid trust level requested %d", level);
944
945 trust = &sigcheck_gpg_trust_level[level];
946 if (trust->value != level)
947 BUG("sigcheck_gpg_trust_level[] unsorted");
948
949 return sigcheck_gpg_trust_level[level].display_key;
950 }
951
952 int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
953 {
954 gpg_interface_lazy_init();
955
956 return use_format->sign_buffer(buffer, signature, signing_key);
957 }
958
959 /*
960 * Strip CR from the line endings, in case we are on Windows.
961 * NEEDSWORK: make it trim only CRs before LFs and rename
962 */
963 static void remove_cr_after(struct strbuf *buffer, size_t offset)
964 {
965 size_t i, j;
966
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++;
972 }
973 }
974 strbuf_setlen(buffer, j);
975 }
976
977 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
978 const char *signing_key)
979 {
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;
985
986 strvec_pushl(&gpg.args,
987 use_format->program,
988 "--status-fd=2",
989 "-bsau", signing_key,
990 NULL);
991
992 bottom = signature->len;
993
994 /*
995 * When the username signingkey is bad, program could be terminated
996 * because gpg exits without reading and then write gets SIGPIPE.
997 */
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);
1002
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 */
1008 }
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;
1015 }
1016 strbuf_release(&gpg_status);
1017
1018 /* Strip CR from the line endings, in case we are on Windows. */
1019 remove_cr_after(signature, bottom);
1020
1021 return 0;
1022 }
1023
1024 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
1025 const char *signing_key)
1026 {
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;
1036
1037 if (!signing_key || signing_key[0] == '\0')
1038 return error(
1039 _("user.signingKey needs to be set for ssh signing"));
1040
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;
1054 }
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);
1059 }
1060
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;
1065 }
1066
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;
1072 }
1073
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);
1082
1083 sigchain_push(SIGPIPE, SIG_IGN);
1084 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
1085 sigchain_pop(SIGPIPE);
1086
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+)"));
1090
1091 error("%s", signer_stderr.buf);
1092 goto out;
1093 }
1094
1095 bottom = signature->len;
1096
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;
1104 }
1105 /* Strip CR from the line endings, in case we are on Windows. */
1106 remove_cr_after(signature, bottom);
1107
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;
1119 }