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