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