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