Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2
3 #include "git-compat-util.h"
4 #include "commit.h"
5 #include "config.h"
6 #include "date.h"
7 #include "gettext.h"
8 #include "run-command.h"
9 #include "strbuf.h"
10 #include "dir.h"
11 #include "ident.h"
12 #include "gpg-interface.h"
13 #include "path.h"
14 #include "sigchain.h"
15 #include "tempfile.h"
16 #include "alias.h"
17
18 static int git_gpg_config(const char *, const char *,
19 const struct config_context *, void *);
20
21 static void gpg_interface_lazy_init(void)
22 {
23 static int done;
24
25 if (done)
26 return;
27 done = 1;
28 repo_config(the_repository, git_gpg_config, NULL);
29 }
30
31 static char *configured_signing_key;
32 static char *ssh_default_key_command;
33 static char *ssh_allowed_signers;
34 static char *ssh_revocation_file;
35 static enum signature_trust_level configured_min_trust_level = TRUST_UNDEFINED;
36
37 struct gpg_format {
38 const char *name;
39 const char *program;
40 const char **verify_args;
41 const char **sigs;
42 int (*verify_signed_buffer)(struct signature_check *sigc,
43 struct gpg_format *fmt,
44 const char *signature,
45 size_t signature_size);
46 int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
47 const char *signing_key);
48 char *(*get_default_key)(void);
49 char *(*get_key_id)(void);
50 };
51
52 static const char *openpgp_verify_args[] = {
53 "--keyid-format=long",
54 NULL
55 };
56 static const char *openpgp_sigs[] = {
57 "-----BEGIN PGP SIGNATURE-----",
58 "-----BEGIN PGP MESSAGE-----",
59 NULL
60 };
61
62 static const char *x509_verify_args[] = {
63 NULL
64 };
65 static const char *x509_sigs[] = {
66 "-----BEGIN SIGNED MESSAGE-----",
67 NULL
68 };
69
70 static const char *ssh_verify_args[] = { NULL };
71 static const char *ssh_sigs[] = {
72 "-----BEGIN SSH SIGNATURE-----",
73 NULL
74 };
75
76 static int verify_gpg_signed_buffer(struct signature_check *sigc,
77 struct gpg_format *fmt,
78 const char *signature,
79 size_t signature_size);
80 static int verify_ssh_signed_buffer(struct signature_check *sigc,
81 struct gpg_format *fmt,
82 const char *signature,
83 size_t signature_size);
84 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
85 const char *signing_key);
86 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
87 const char *signing_key);
88
89 static char *get_default_ssh_signing_key(void);
90
91 static char *get_ssh_key_id(void);
92
93 static struct gpg_format gpg_format[] = {
94 {
95 .name = "openpgp",
96 .program = "gpg",
97 .verify_args = openpgp_verify_args,
98 .sigs = openpgp_sigs,
99 .verify_signed_buffer = verify_gpg_signed_buffer,
100 .sign_buffer = sign_buffer_gpg,
101 .get_default_key = NULL,
102 .get_key_id = NULL,
103 },
104 {
105 .name = "x509",
106 .program = "gpgsm",
107 .verify_args = x509_verify_args,
108 .sigs = x509_sigs,
109 .verify_signed_buffer = verify_gpg_signed_buffer,
110 .sign_buffer = sign_buffer_gpg,
111 .get_default_key = NULL,
112 .get_key_id = NULL,
113 },
114 {
115 .name = "ssh",
116 .program = "ssh-keygen",
117 .verify_args = ssh_verify_args,
118 .sigs = ssh_sigs,
119 .verify_signed_buffer = verify_ssh_signed_buffer,
120 .sign_buffer = sign_buffer_ssh,
121 .get_default_key = get_default_ssh_signing_key,
122 .get_key_id = get_ssh_key_id,
123 },
124 };
125
126 static struct gpg_format *use_format = &gpg_format[0];
127
128 static struct gpg_format *get_format_by_name(const char *str)
129 {
130 for (size_t i = 0; i < ARRAY_SIZE(gpg_format); i++)
131 if (!strcmp(gpg_format[i].name, str))
132 return gpg_format + i;
133 return NULL;
134 }
135
136 static struct gpg_format *get_format_by_sig(const char *sig)
137 {
138 int j;
139
140 for (size_t i = 0; i < ARRAY_SIZE(gpg_format); i++)
141 for (j = 0; gpg_format[i].sigs[j]; j++)
142 if (starts_with(sig, gpg_format[i].sigs[j]))
143 return gpg_format + i;
144 return NULL;
145 }
146
147 const char *get_signature_format(const char *buf)
148 {
149 struct gpg_format *format = get_format_by_sig(buf);
150 return format ? format->name : "unknown";
151 }
152
153 int valid_signature_format(const char *format)
154 {
155 return (!!get_format_by_name(format) ||
156 !strcmp(format, "unknown"));
157 }
158
159 void signature_check_clear(struct signature_check *sigc)
160 {
161 FREE_AND_NULL(sigc->payload);
162 FREE_AND_NULL(sigc->output);
163 FREE_AND_NULL(sigc->gpg_status);
164 FREE_AND_NULL(sigc->signer);
165 FREE_AND_NULL(sigc->key);
166 FREE_AND_NULL(sigc->fingerprint);
167 FREE_AND_NULL(sigc->primary_key_fingerprint);
168 }
169
170 /* An exclusive status -- only one of them can appear in output */
171 #define GPG_STATUS_EXCLUSIVE (1<<0)
172 /* The status includes key identifier */
173 #define GPG_STATUS_KEYID (1<<1)
174 /* The status includes user identifier */
175 #define GPG_STATUS_UID (1<<2)
176 /* The status includes key fingerprints */
177 #define GPG_STATUS_FINGERPRINT (1<<3)
178 /* The status includes trust level */
179 #define GPG_STATUS_TRUST_LEVEL (1<<4)
180
181 /* Short-hand for standard exclusive *SIG status with keyid & UID */
182 #define GPG_STATUS_STDSIG (GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID|GPG_STATUS_UID)
183
184 static struct {
185 char result;
186 const char *check;
187 unsigned int flags;
188 } sigcheck_gpg_status[] = {
189 { 'G', "GOODSIG ", GPG_STATUS_STDSIG },
190 { 'B', "BADSIG ", GPG_STATUS_STDSIG },
191 { 'E', "ERRSIG ", GPG_STATUS_EXCLUSIVE|GPG_STATUS_KEYID },
192 { 'X', "EXPSIG ", GPG_STATUS_STDSIG },
193 { 'Y', "EXPKEYSIG ", GPG_STATUS_STDSIG },
194 { 'R', "REVKEYSIG ", GPG_STATUS_STDSIG },
195 { 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
196 { 0, "TRUST_", GPG_STATUS_TRUST_LEVEL },
197 };
198
199 /* Keep the order same as enum signature_trust_level */
200 static struct sigcheck_gpg_trust_level {
201 const char *key;
202 const char *display_key;
203 enum signature_trust_level value;
204 } sigcheck_gpg_trust_level[] = {
205 { "UNDEFINED", "undefined", TRUST_UNDEFINED },
206 { "NEVER", "never", TRUST_NEVER },
207 { "MARGINAL", "marginal", TRUST_MARGINAL },
208 { "FULLY", "fully", TRUST_FULLY },
209 { "ULTIMATE", "ultimate", TRUST_ULTIMATE },
210 };
211
212 static void replace_cstring(char **field, const char *line, const char *next)
213 {
214 free(*field);
215
216 if (line && next)
217 *field = xmemdupz(line, next - line);
218 else
219 *field = NULL;
220 }
221
222 static int parse_gpg_trust_level(const char *level,
223 enum signature_trust_level *res)
224 {
225 size_t i;
226
227 for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_trust_level); i++) {
228 if (!strcmp(sigcheck_gpg_trust_level[i].key, level)) {
229 *res = sigcheck_gpg_trust_level[i].value;
230 return 0;
231 }
232 }
233 return 1;
234 }
235
236 static void parse_gpg_output(struct signature_check *sigc)
237 {
238 const char *buf = sigc->gpg_status;
239 const char *line, *next;
240 int j;
241 int seen_exclusive_status = 0;
242
243 /* Iterate over all lines */
244 for (line = buf; *line; line = strchrnul(line+1, '\n')) {
245 while (*line == '\n')
246 line++;
247 if (!*line)
248 break;
249
250 /* Skip lines that don't start with GNUPG status */
251 if (!skip_prefix(line, "[GNUPG:] ", &line))
252 continue;
253
254 /* Iterate over all search strings */
255 for (size_t i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
256 if (skip_prefix(line, sigcheck_gpg_status[i].check, &line)) {
257 /*
258 * GOODSIG, BADSIG etc. can occur only once for
259 * each signature. Therefore, if we had more
260 * than one then we're dealing with multiple
261 * signatures. We don't support them
262 * currently, and they're rather hard to
263 * create, so something is likely fishy and we
264 * should reject them altogether.
265 */
266 if (sigcheck_gpg_status[i].flags & GPG_STATUS_EXCLUSIVE) {
267 if (seen_exclusive_status++)
268 goto error;
269 }
270
271 if (sigcheck_gpg_status[i].result)
272 sigc->result = sigcheck_gpg_status[i].result;
273 /* Do we have key information? */
274 if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
275 next = strchrnul(line, ' ');
276 replace_cstring(&sigc->key, line, next);
277 /* Do we have signer information? */
278 if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
279 line = next + 1;
280 next = strchrnul(line, '\n');
281 replace_cstring(&sigc->signer, line, next);
282 }
283 }
284
285 /* Do we have trust level? */
286 if (sigcheck_gpg_status[i].flags & GPG_STATUS_TRUST_LEVEL) {
287 /*
288 * GPG v1 and v2 differs in how the
289 * TRUST_ lines are written. Some
290 * trust lines contain no additional
291 * space-separated information for v1.
292 */
293 size_t trust_size = strcspn(line, " \n");
294 char *trust = xmemdupz(line, trust_size);
295
296 if (parse_gpg_trust_level(trust, &sigc->trust_level)) {
297 free(trust);
298 goto error;
299 }
300 free(trust);
301 }
302
303 /* Do we have fingerprint? */
304 if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
305 const char *limit;
306 char **field;
307
308 next = strchrnul(line, ' ');
309 replace_cstring(&sigc->fingerprint, line, next);
310
311 /*
312 * Skip interim fields. The search is
313 * limited to the same line since only
314 * OpenPGP signatures has a field with
315 * the primary fingerprint.
316 */
317 limit = strchrnul(line, '\n');
318 for (j = 9; j > 0; j--) {
319 if (!*next || limit <= next)
320 break;
321 line = next + 1;
322 next = strchrnul(line, ' ');
323 }
324
325 field = &sigc->primary_key_fingerprint;
326 if (!j) {
327 next = strchrnul(line, '\n');
328 replace_cstring(field, line, next);
329 } else {
330 replace_cstring(field, NULL, NULL);
331 }
332 }
333
334 break;
335 }
336 }
337 }
338 return;
339
340 error:
341 sigc->result = 'E';
342 /* Clear partial data to avoid confusion */
343 FREE_AND_NULL(sigc->primary_key_fingerprint);
344 FREE_AND_NULL(sigc->fingerprint);
345 FREE_AND_NULL(sigc->signer);
346 FREE_AND_NULL(sigc->key);
347 }
348
349 static int verify_gpg_signed_buffer(struct signature_check *sigc,
350 struct gpg_format *fmt,
351 const char *signature,
352 size_t signature_size)
353 {
354 struct child_process gpg = CHILD_PROCESS_INIT;
355 struct tempfile *temp;
356 int ret;
357 struct strbuf gpg_stdout = STRBUF_INIT;
358 struct strbuf gpg_stderr = STRBUF_INIT;
359
360 temp = mks_tempfile_t(".git_vtag_tmpXXXXXX");
361 if (!temp)
362 return error_errno(_("could not create temporary file"));
363 if (write_in_full(temp->fd, signature, signature_size) < 0 ||
364 close_tempfile_gently(temp) < 0) {
365 error_errno(_("failed writing detached signature to '%s'"),
366 temp->filename.buf);
367 delete_tempfile(&temp);
368 return -1;
369 }
370
371 strvec_push(&gpg.args, fmt->program);
372 strvec_pushv(&gpg.args, fmt->verify_args);
373 strvec_pushl(&gpg.args,
374 "--status-fd=1",
375 "--verify", temp->filename.buf, "-",
376 NULL);
377
378 sigchain_push(SIGPIPE, SIG_IGN);
379 ret = pipe_command(&gpg, sigc->payload, sigc->payload_len, &gpg_stdout, 0,
380 &gpg_stderr, 0);
381 sigchain_pop(SIGPIPE);
382
383 delete_tempfile(&temp);
384
385 ret |= !strstr(gpg_stdout.buf, "\n[GNUPG:] GOODSIG ") &&
386 !strstr(gpg_stdout.buf, "\n[GNUPG:] EXPKEYSIG ");
387 sigc->output = strbuf_detach(&gpg_stderr, NULL);
388 sigc->gpg_status = strbuf_detach(&gpg_stdout, NULL);
389
390 parse_gpg_output(sigc);
391
392 strbuf_release(&gpg_stdout);
393 strbuf_release(&gpg_stderr);
394
395 return ret;
396 }
397
398 static void parse_ssh_output(struct signature_check *sigc)
399 {
400 const char *line, *principal, *search;
401 char *to_free;
402 const char *key;
403
404 /*
405 * ssh-keygen output should be:
406 * Good "git" signature for PRINCIPAL with RSA key SHA256:FINGERPRINT
407 *
408 * or for valid but unknown keys:
409 * Good "git" signature with RSA key SHA256:FINGERPRINT
410 *
411 * Note that "PRINCIPAL" can contain whitespace, "RSA" and
412 * "SHA256" part could be a different token that names of
413 * the algorithms used, and "FINGERPRINT" is a hexadecimal
414 * string. By finding the last occurrence of " with ", we can
415 * reliably parse out the PRINCIPAL.
416 */
417 sigc->result = 'B';
418 sigc->trust_level = TRUST_NEVER;
419
420 line = to_free = xmemdupz(sigc->output, strcspn(sigc->output, "\n"));
421
422 if (skip_prefix(line, "Good \"git\" signature for ", &line)) {
423 /* Search for the last "with" to get the full principal */
424 principal = line;
425 do {
426 search = strstr(line, " with ");
427 if (search)
428 line = search + 1;
429 } while (search != NULL);
430 if (line == principal)
431 goto cleanup;
432
433 /* Valid signature and known principal */
434 sigc->result = 'G';
435 sigc->trust_level = TRUST_FULLY;
436 sigc->signer = xmemdupz(principal, line - principal - 1);
437 } else if (skip_prefix(line, "Good \"git\" signature with ", &line)) {
438 /* Valid signature, but key unknown */
439 sigc->result = 'G';
440 sigc->trust_level = TRUST_UNDEFINED;
441 } else {
442 goto cleanup;
443 }
444
445 key = strstr(line, "key ");
446 if (key) {
447 sigc->fingerprint = xstrdup(key + 4);
448 sigc->key = xstrdup(sigc->fingerprint);
449 } else {
450 /*
451 * Output did not match what we expected
452 * Treat the signature as bad
453 */
454 sigc->result = 'B';
455 }
456
457 cleanup:
458 free(to_free);
459 }
460
461 static int verify_ssh_signed_buffer(struct signature_check *sigc,
462 struct gpg_format *fmt,
463 const char *signature,
464 size_t signature_size)
465 {
466 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
467 struct tempfile *buffer_file;
468 int ret = -1;
469 const char *line;
470 char *principal;
471 struct strbuf ssh_principals_out = STRBUF_INIT;
472 struct strbuf ssh_principals_err = STRBUF_INIT;
473 struct strbuf ssh_keygen_out = STRBUF_INIT;
474 struct strbuf ssh_keygen_err = STRBUF_INIT;
475 struct strbuf verify_time = STRBUF_INIT;
476 const struct date_mode verify_date_mode = {
477 .type = DATE_STRFTIME,
478 .strftime_fmt = "%Y%m%d%H%M%S",
479 /* SSH signing key validity has no timezone information - Use the local timezone */
480 .local = 1,
481 };
482
483 if (!ssh_allowed_signers) {
484 error(_("gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification"));
485 return -1;
486 }
487
488 buffer_file = mks_tempfile_t(".git_vtag_tmpXXXXXX");
489 if (!buffer_file)
490 return error_errno(_("could not create temporary file"));
491 if (write_in_full(buffer_file->fd, signature, signature_size) < 0 ||
492 close_tempfile_gently(buffer_file) < 0) {
493 error_errno(_("failed writing detached signature to '%s'"),
494 buffer_file->filename.buf);
495 delete_tempfile(&buffer_file);
496 return -1;
497 }
498
499 if (sigc->payload_timestamp)
500 strbuf_addf(&verify_time, "-Overify-time=%s",
501 show_date(sigc->payload_timestamp, 0, verify_date_mode));
502
503 /* Find the principal from the signers */
504 strvec_pushl(&ssh_keygen.args, fmt->program,
505 "-Y", "find-principals",
506 "-f", ssh_allowed_signers,
507 "-s", buffer_file->filename.buf,
508 verify_time.buf,
509 NULL);
510 ret = pipe_command(&ssh_keygen, NULL, 0, &ssh_principals_out, 0,
511 &ssh_principals_err, 0);
512 if (ret && strstr(ssh_principals_err.buf, "usage:")) {
513 error(_("ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"));
514 goto out;
515 }
516 if (ret || !ssh_principals_out.len) {
517 /*
518 * We did not find a matching principal in the allowedSigners
519 * Check without validation
520 */
521 child_process_init(&ssh_keygen);
522 strvec_pushl(&ssh_keygen.args, fmt->program,
523 "-Y", "check-novalidate",
524 "-n", "git",
525 "-s", buffer_file->filename.buf,
526 verify_time.buf,
527 NULL);
528 pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
529 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
530
531 /*
532 * Fail on unknown keys
533 * we still call check-novalidate to display the signature info
534 */
535 ret = -1;
536 } else {
537 /* Check every principal we found (one per line) */
538 const char *next;
539 for (line = ssh_principals_out.buf;
540 *line;
541 line = next) {
542 const char *end_of_text;
543
544 next = end_of_text = strchrnul(line, '\n');
545
546 /* Did we find a LF, and did we have CR before it? */
547 if (*end_of_text &&
548 line < end_of_text &&
549 end_of_text[-1] == '\r')
550 end_of_text--;
551
552 /* Unless we hit NUL, skip over the LF we found */
553 if (*next)
554 next++;
555
556 /* Not all lines are data. Skip empty ones */
557 if (line == end_of_text)
558 continue;
559
560 /* We now know we have an non-empty line. Process it */
561 principal = xmemdupz(line, end_of_text - line);
562
563 child_process_init(&ssh_keygen);
564 strbuf_release(&ssh_keygen_out);
565 strbuf_release(&ssh_keygen_err);
566 strvec_push(&ssh_keygen.args, fmt->program);
567 /*
568 * We found principals
569 * Try with each until we find a match
570 */
571 strvec_pushl(&ssh_keygen.args, "-Y", "verify",
572 "-n", "git",
573 "-f", ssh_allowed_signers,
574 "-I", principal,
575 "-s", buffer_file->filename.buf,
576 verify_time.buf,
577 NULL);
578
579 if (ssh_revocation_file) {
580 if (file_exists(ssh_revocation_file)) {
581 strvec_pushl(&ssh_keygen.args, "-r",
582 ssh_revocation_file, NULL);
583 } else {
584 warning(_("ssh signing revocation file configured but not found: %s"),
585 ssh_revocation_file);
586 }
587 }
588
589 sigchain_push(SIGPIPE, SIG_IGN);
590 ret = pipe_command(&ssh_keygen, sigc->payload, sigc->payload_len,
591 &ssh_keygen_out, 0, &ssh_keygen_err, 0);
592 sigchain_pop(SIGPIPE);
593
594 FREE_AND_NULL(principal);
595
596 if (!ret)
597 ret = !starts_with(ssh_keygen_out.buf, "Good");
598
599 if (!ret)
600 break;
601 }
602 }
603
604 strbuf_stripspace(&ssh_keygen_out, NULL);
605 strbuf_stripspace(&ssh_keygen_err, NULL);
606 /* Add stderr outputs to show the user actual ssh-keygen errors */
607 strbuf_add(&ssh_keygen_out, ssh_principals_err.buf, ssh_principals_err.len);
608 strbuf_add(&ssh_keygen_out, ssh_keygen_err.buf, ssh_keygen_err.len);
609 sigc->output = strbuf_detach(&ssh_keygen_out, NULL);
610 sigc->gpg_status = xstrdup(sigc->output);
611
612 parse_ssh_output(sigc);
613
614 out:
615 if (buffer_file)
616 delete_tempfile(&buffer_file);
617 strbuf_release(&ssh_principals_out);
618 strbuf_release(&ssh_principals_err);
619 strbuf_release(&ssh_keygen_out);
620 strbuf_release(&ssh_keygen_err);
621 strbuf_release(&verify_time);
622
623 return ret;
624 }
625
626 static int parse_payload_metadata(struct signature_check *sigc)
627 {
628 const char *ident_line = NULL;
629 size_t ident_len;
630 struct ident_split ident;
631 const char *signer_header;
632
633 switch (sigc->payload_type) {
634 case SIGNATURE_PAYLOAD_COMMIT:
635 signer_header = "committer";
636 break;
637 case SIGNATURE_PAYLOAD_TAG:
638 signer_header = "tagger";
639 break;
640 case SIGNATURE_PAYLOAD_UNDEFINED:
641 case SIGNATURE_PAYLOAD_PUSH_CERT:
642 /* Ignore payloads we don't want to parse */
643 return 0;
644 default:
645 BUG("invalid value for sigc->payload_type");
646 }
647
648 ident_line = find_commit_header(sigc->payload, signer_header, &ident_len);
649 if (!ident_line || !ident_len)
650 return 1;
651
652 if (split_ident_line(&ident, ident_line, ident_len))
653 return 1;
654
655 if (!sigc->payload_timestamp && ident.date_begin && ident.date_end)
656 sigc->payload_timestamp = parse_timestamp(ident.date_begin, NULL, 10);
657
658 return 0;
659 }
660
661 int check_signature(struct signature_check *sigc,
662 const char *signature, size_t slen)
663 {
664 struct gpg_format *fmt;
665 int status;
666
667 gpg_interface_lazy_init();
668
669 sigc->result = 'N';
670 sigc->trust_level = TRUST_UNDEFINED;
671
672 fmt = get_format_by_sig(signature);
673 if (!fmt)
674 die(_("bad/incompatible signature '%s'"), signature);
675
676 if (parse_payload_metadata(sigc))
677 return 1;
678
679 status = fmt->verify_signed_buffer(sigc, fmt, signature, slen);
680
681 if (status && !sigc->output)
682 return !!status;
683
684 status |= sigc->result != 'G' && sigc->result != 'Y';
685 status |= sigc->trust_level < configured_min_trust_level;
686
687 return !!status;
688 }
689
690 void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
691 {
692 const char *output = flags & GPG_VERIFY_RAW ? sigc->gpg_status :
693 sigc->output;
694
695 if (flags & GPG_VERIFY_VERBOSE && sigc->payload)
696 fwrite(sigc->payload, 1, sigc->payload_len, stdout);
697
698 if (output)
699 fputs(output, stderr);
700 }
701
702 size_t parse_signed_buffer(const char *buf, size_t size)
703 {
704 size_t len = 0;
705 size_t match = size;
706 while (len < size) {
707 const char *eol;
708
709 if (get_format_by_sig(buf + len))
710 match = len;
711
712 eol = memchr(buf + len, '\n', size - len);
713 len += eol ? (size_t) (eol - (buf + len) + 1) : size - len;
714 }
715 return match;
716 }
717
718 int parse_signature(const char *buf, size_t size, struct strbuf *payload, struct strbuf *signature)
719 {
720 size_t match = parse_signed_buffer(buf, size);
721 if (match != size) {
722 strbuf_add(payload, buf, match);
723 remove_signature(payload);
724 strbuf_add(signature, buf + match, size - match);
725 return 1;
726 }
727 return 0;
728 }
729
730 void set_signing_key(const char *key)
731 {
732 gpg_interface_lazy_init();
733
734 free(configured_signing_key);
735 configured_signing_key = xstrdup(key);
736 }
737
738 static int git_gpg_config(const char *var, const char *value,
739 const struct config_context *ctx UNUSED,
740 void *cb UNUSED)
741 {
742 struct gpg_format *fmt = NULL;
743 const char *fmtname = NULL;
744 char *trust;
745 int ret;
746
747 if (!strcmp(var, "user.signingkey")) {
748 if (!value)
749 return config_error_nonbool(var);
750 set_signing_key(value);
751 return 0;
752 }
753
754 if (!strcmp(var, "gpg.format")) {
755 if (!value)
756 return config_error_nonbool(var);
757 fmt = get_format_by_name(value);
758 if (!fmt)
759 return error(_("invalid value for '%s': '%s'"),
760 var, value);
761 use_format = fmt;
762 return 0;
763 }
764
765 if (!strcmp(var, "gpg.mintrustlevel")) {
766 if (!value)
767 return config_error_nonbool(var);
768
769 trust = xstrdup_toupper(value);
770 ret = parse_gpg_trust_level(trust, &configured_min_trust_level);
771 free(trust);
772
773 if (ret)
774 return error(_("invalid value for '%s': '%s'"),
775 var, value);
776 return 0;
777 }
778
779 if (!strcmp(var, "gpg.ssh.defaultkeycommand"))
780 return git_config_string(&ssh_default_key_command, var, value);
781
782 if (!strcmp(var, "gpg.ssh.allowedsignersfile"))
783 return git_config_pathname(&ssh_allowed_signers, var, value);
784
785 if (!strcmp(var, "gpg.ssh.revocationfile"))
786 return git_config_pathname(&ssh_revocation_file, var, value);
787
788 if (!strcmp(var, "gpg.program") || !strcmp(var, "gpg.openpgp.program"))
789 fmtname = "openpgp";
790
791 if (!strcmp(var, "gpg.x509.program"))
792 fmtname = "x509";
793
794 if (!strcmp(var, "gpg.ssh.program"))
795 fmtname = "ssh";
796
797 if (fmtname) {
798 char *program;
799 int status;
800
801 fmt = get_format_by_name(fmtname);
802 status = git_config_pathname(&program, var, value);
803 if (status)
804 return status;
805 if (program)
806 fmt->program = program;
807 return status;
808 }
809
810 return 0;
811 }
812
813 /*
814 * Returns 1 if `string` contains a literal ssh key, 0 otherwise
815 * `key` will be set to the start of the actual key if a prefix is present.
816 */
817 static int is_literal_ssh_key(const char *string, const char **key)
818 {
819 if (skip_prefix(string, "key::", key))
820 return 1;
821 if (starts_with(string, "ssh-")) {
822 *key = string;
823 return 1;
824 }
825 return 0;
826 }
827
828 static char *get_ssh_key_fingerprint(const char *signing_key)
829 {
830 struct child_process ssh_keygen = CHILD_PROCESS_INIT;
831 int ret = -1;
832 struct strbuf fingerprint_stdout = STRBUF_INIT;
833 char *fingerprint_ret, *begin, *delim;
834 const char *literal_key = NULL;
835
836 /*
837 * With SSH Signing this can contain a filename or a public key
838 * For textual representation we usually want a fingerprint
839 */
840 if (is_literal_ssh_key(signing_key, &literal_key)) {
841 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf", "-", NULL);
842 ret = pipe_command(&ssh_keygen, literal_key,
843 strlen(literal_key), &fingerprint_stdout, 0,
844 NULL, 0);
845 } else {
846 strvec_pushl(&ssh_keygen.args, "ssh-keygen", "-lf",
847 configured_signing_key, NULL);
848 ret = pipe_command(&ssh_keygen, NULL, 0, &fingerprint_stdout, 0,
849 NULL, 0);
850 }
851
852 if (!!ret)
853 die_errno(_("failed to get the ssh fingerprint for key '%s'"),
854 signing_key);
855
856 begin = fingerprint_stdout.buf;
857 delim = strchr(begin, ' ');
858 if (!delim)
859 die(_("failed to get the ssh fingerprint for key %s"),
860 signing_key);
861 begin = delim + 1;
862 delim = strchr(begin, ' ');
863 if (!delim)
864 die(_("failed to get the ssh fingerprint for key %s"),
865 signing_key);
866 fingerprint_ret = xmemdupz(begin, delim - begin);
867 strbuf_release(&fingerprint_stdout);
868 return fingerprint_ret;
869 }
870
871 /* Returns the first public key from an ssh-agent to use for signing */
872 static char *get_default_ssh_signing_key(void)
873 {
874 struct child_process ssh_default_key = CHILD_PROCESS_INIT;
875 int ret = -1;
876 struct strbuf key_stdout = STRBUF_INIT, key_stderr = STRBUF_INIT;
877 char *key_command = NULL;
878 const char **argv;
879 int n;
880 char *default_key = NULL;
881 const char *literal_key = NULL;
882 char *begin, *new_line, *first_line;
883
884 if (!ssh_default_key_command)
885 die(_("either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured"));
886
887 key_command = xstrdup(ssh_default_key_command);
888 n = split_cmdline(key_command, &argv);
889
890 if (n < 0)
891 die(_("malformed build-time gpg.ssh.defaultKeyCommand: %s"),
892 split_cmdline_strerror(n));
893
894 strvec_pushv(&ssh_default_key.args, argv);
895 ret = pipe_command(&ssh_default_key, NULL, 0, &key_stdout, 0,
896 &key_stderr, 0);
897
898 if (!ret) {
899 begin = key_stdout.buf;
900 new_line = strchr(begin, '\n');
901 if (new_line)
902 first_line = xmemdupz(begin, new_line - begin);
903 else
904 first_line = xstrdup(begin);
905 if (is_literal_ssh_key(first_line, &literal_key)) {
906 /*
907 * We only use `is_literal_ssh_key` here to check validity
908 * The prefix will be stripped when the key is used.
909 */
910 default_key = first_line;
911 } else {
912 free(first_line);
913 warning(_("gpg.ssh.defaultKeyCommand succeeded but returned no keys: %s %s"),
914 key_stderr.buf, key_stdout.buf);
915 }
916
917 } else {
918 warning(_("gpg.ssh.defaultKeyCommand failed: %s %s"),
919 key_stderr.buf, key_stdout.buf);
920 }
921
922 free(key_command);
923 free(argv);
924 strbuf_release(&key_stdout);
925
926 return default_key;
927 }
928
929 static char *get_ssh_key_id(void)
930 {
931 char *signing_key = get_signing_key();
932 char *key_id = get_ssh_key_fingerprint(signing_key);
933 free(signing_key);
934 return key_id;
935 }
936
937 /* Returns a textual but unique representation of the signing key */
938 char *get_signing_key_id(void)
939 {
940 gpg_interface_lazy_init();
941
942 if (use_format->get_key_id) {
943 return use_format->get_key_id();
944 }
945
946 /* GPG/GPGSM only store a key id on this variable */
947 return get_signing_key();
948 }
949
950 char *get_signing_key(void)
951 {
952 gpg_interface_lazy_init();
953
954 if (configured_signing_key)
955 return xstrdup(configured_signing_key);
956 if (use_format->get_default_key) {
957 return use_format->get_default_key();
958 }
959
960 return xstrdup(git_committer_info(IDENT_STRICT | IDENT_NO_DATE));
961 }
962
963 const char *gpg_trust_level_to_str(enum signature_trust_level level)
964 {
965 struct sigcheck_gpg_trust_level *trust;
966
967 if (level < 0 || level >= ARRAY_SIZE(sigcheck_gpg_trust_level))
968 BUG("invalid trust level requested %d", level);
969
970 trust = &sigcheck_gpg_trust_level[level];
971 if (trust->value != level)
972 BUG("sigcheck_gpg_trust_level[] unsorted");
973
974 return sigcheck_gpg_trust_level[level].display_key;
975 }
976
977 int sign_buffer(struct strbuf *buffer, struct strbuf *signature,
978 const char *signing_key, enum sign_buffer_flags flags)
979 {
980 char *keyid_to_free = NULL;
981 int ret = 0;
982
983 gpg_interface_lazy_init();
984
985 if ((flags & SIGN_BUFFER_USE_DEFAULT_KEY) && (!signing_key || !*signing_key))
986 signing_key = keyid_to_free = get_signing_key();
987
988 ret = use_format->sign_buffer(buffer, signature, signing_key);
989 free(keyid_to_free);
990 return ret;
991 }
992
993 /* Strip CR before LF from the line endings, in case we are on Windows. */
994 static void strip_cr_before_lf(struct strbuf *buffer, size_t offset)
995 {
996 size_t i, j;
997
998 for (i = j = offset; i < buffer->len; i++) {
999 if (buffer->buf[i] == '\r' &&
1000 i + 1 < buffer->len && buffer->buf[i + 1] == '\n')
1001 continue;
1002 buffer->buf[j++] = buffer->buf[i];
1003 }
1004
1005 strbuf_setlen(buffer, j);
1006 }
1007
1008 static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
1009 const char *signing_key)
1010 {
1011 struct child_process gpg = CHILD_PROCESS_INIT;
1012 int ret;
1013 size_t bottom;
1014 const char *cp;
1015 struct strbuf gpg_status = STRBUF_INIT;
1016
1017 strvec_pushl(&gpg.args,
1018 use_format->program,
1019 "--status-fd=2",
1020 "-bsau", signing_key,
1021 NULL);
1022
1023 bottom = signature->len;
1024
1025 /*
1026 * When the username signingkey is bad, program could be terminated
1027 * because gpg exits without reading and then write gets SIGPIPE.
1028 */
1029 sigchain_push(SIGPIPE, SIG_IGN);
1030 ret = pipe_command(&gpg, buffer->buf, buffer->len,
1031 signature, 1024, &gpg_status, 0);
1032 sigchain_pop(SIGPIPE);
1033
1034 for (cp = gpg_status.buf;
1035 cp && (cp = strstr(cp, "[GNUPG:] SIG_CREATED "));
1036 cp++) {
1037 if (cp == gpg_status.buf || cp[-1] == '\n')
1038 break; /* found */
1039 }
1040 ret |= !cp;
1041 if (ret) {
1042 error(_("gpg failed to sign the data:\n%s"),
1043 gpg_status.len ? gpg_status.buf : "(no gpg output)");
1044 strbuf_release(&gpg_status);
1045 return -1;
1046 }
1047 strbuf_release(&gpg_status);
1048
1049 /* Strip CR before LF from the line endings, in case we are on Windows. */
1050 strip_cr_before_lf(signature, bottom);
1051
1052 return 0;
1053 }
1054
1055 static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
1056 const char *signing_key)
1057 {
1058 struct child_process signer = CHILD_PROCESS_INIT;
1059 int ret = -1;
1060 size_t bottom, keylen;
1061 struct strbuf signer_stderr = STRBUF_INIT;
1062 struct tempfile *key_file = NULL, *buffer_file = NULL;
1063 char *ssh_signing_key_file = NULL;
1064 struct strbuf ssh_signature_filename = STRBUF_INIT;
1065 const char *literal_key = NULL;
1066 int literal_ssh_key = 0;
1067
1068 if (!signing_key || signing_key[0] == '\0')
1069 return error(
1070 _("user.signingKey needs to be set for ssh signing"));
1071
1072 if (is_literal_ssh_key(signing_key, &literal_key)) {
1073 /* A literal ssh key */
1074 literal_ssh_key = 1;
1075 key_file = mks_tempfile_t(".git_signing_key_tmpXXXXXX");
1076 if (!key_file)
1077 return error_errno(
1078 _("could not create temporary file"));
1079 keylen = strlen(literal_key);
1080 if (write_in_full(key_file->fd, literal_key, keylen) < 0 ||
1081 close_tempfile_gently(key_file) < 0) {
1082 error_errno(_("failed writing ssh signing key to '%s'"),
1083 key_file->filename.buf);
1084 goto out;
1085 }
1086 ssh_signing_key_file = xstrdup(key_file->filename.buf);
1087 } else {
1088 /* We assume a file */
1089 ssh_signing_key_file = interpolate_path(signing_key, 1);
1090 }
1091
1092 buffer_file = mks_tempfile_t(".git_signing_buffer_tmpXXXXXX");
1093 if (!buffer_file) {
1094 error_errno(_("could not create temporary file"));
1095 goto out;
1096 }
1097
1098 if (write_in_full(buffer_file->fd, buffer->buf, buffer->len) < 0 ||
1099 close_tempfile_gently(buffer_file) < 0) {
1100 error_errno(_("failed writing ssh signing key buffer to '%s'"),
1101 buffer_file->filename.buf);
1102 goto out;
1103 }
1104
1105 strvec_pushl(&signer.args, use_format->program,
1106 "-Y", "sign",
1107 "-n", "git",
1108 "-f", ssh_signing_key_file,
1109 NULL);
1110 if (literal_ssh_key)
1111 strvec_push(&signer.args, "-U");
1112 strvec_push(&signer.args, buffer_file->filename.buf);
1113
1114 sigchain_push(SIGPIPE, SIG_IGN);
1115 ret = pipe_command(&signer, NULL, 0, NULL, 0, &signer_stderr, 0);
1116 sigchain_pop(SIGPIPE);
1117
1118 if (ret) {
1119 if (strstr(signer_stderr.buf, "usage:"))
1120 error(_("ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"));
1121
1122 ret = error("%s", signer_stderr.buf);
1123 goto out;
1124 }
1125
1126 bottom = signature->len;
1127
1128 strbuf_addbuf(&ssh_signature_filename, &buffer_file->filename);
1129 strbuf_addstr(&ssh_signature_filename, ".sig");
1130 if (strbuf_read_file(signature, ssh_signature_filename.buf, 0) < 0) {
1131 ret = error_errno(
1132 _("failed reading ssh signing data buffer from '%s'"),
1133 ssh_signature_filename.buf);
1134 goto out;
1135 }
1136 /* Strip CR before LF from the line endings, in case we are on Windows. */
1137 strip_cr_before_lf(signature, bottom);
1138
1139 out:
1140 if (key_file)
1141 delete_tempfile(&key_file);
1142 if (buffer_file)
1143 delete_tempfile(&buffer_file);
1144 if (ssh_signature_filename.len)
1145 unlink_or_warn(ssh_signature_filename.buf);
1146 strbuf_release(&signer_stderr);
1147 strbuf_release(&ssh_signature_filename);
1148 FREE_AND_NULL(ssh_signing_key_file);
1149 return ret;
1150 }
1151
1152 int parse_sign_mode(const char *arg, enum sign_mode *mode, const char **keyid)
1153 {
1154 if (!strcmp(arg, "abort")) {
1155 *mode = SIGN_ABORT;
1156 } else if (!strcmp(arg, "verbatim") || !strcmp(arg, "ignore")) {
1157 *mode = SIGN_VERBATIM;
1158 } else if (!strcmp(arg, "warn-verbatim") || !strcmp(arg, "warn")) {
1159 *mode = SIGN_WARN_VERBATIM;
1160 } else if (!strcmp(arg, "warn-strip")) {
1161 *mode = SIGN_WARN_STRIP;
1162 } else if (!strcmp(arg, "strip")) {
1163 *mode = SIGN_STRIP;
1164 } else if (!strcmp(arg, "abort-if-invalid")) {
1165 *mode = SIGN_ABORT_IF_INVALID;
1166 } else if (!strcmp(arg, "strip-if-invalid")) {
1167 *mode = SIGN_STRIP_IF_INVALID;
1168 } else if (!strcmp(arg, "sign-if-invalid")) {
1169 *mode = SIGN_SIGN_IF_INVALID;
1170 } else if (skip_prefix(arg, "sign-if-invalid=", &arg)) {
1171 *mode = SIGN_SIGN_IF_INVALID;
1172 if (keyid)
1173 *keyid = arg;
1174 } else {
1175 return -1;
1176 }
1177 return 0;
1178 }