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