1/* $NetBSD: ssh-pkcs11-client.c,v 1.19 2023/12/20 17:15:21 christos Exp $ */ 2/* $OpenBSD: ssh-pkcs11-client.c,v 1.19 2023/12/18 14:46:56 djm Exp $ */ 3 4/* 5 * Copyright (c) 2010 Markus Friedl. All rights reserved. 6 * Copyright (c) 2014 Pedro Martelletto. All rights reserved. 7 * 8 * Permission to use, copy, modify, and distribute this software for any 9 * purpose with or without fee is hereby granted, provided that the above 10 * copyright notice and this permission notice appear in all copies. 11 * 12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 19 */ 20#include "includes.h" 21__RCSID("$NetBSD: ssh-pkcs11-client.c,v 1.19 2023/12/20 17:15:21 christos Exp $"); 22 23#include <sys/types.h> 24#include <sys/time.h> 25#include <sys/socket.h> 26 27#include <stdarg.h> 28#include <string.h> 29#include <unistd.h> 30#include <errno.h> 31#include <limits.h> 32 33#include <openssl/ecdsa.h> 34#include <openssl/rsa.h> 35 36#include "pathnames.h" 37#include "xmalloc.h" 38#include "sshbuf.h" 39#include "log.h" 40#include "misc.h" 41#include "sshkey.h" 42#include "authfd.h" 43#include "atomicio.h" 44#include "ssh-pkcs11.h" 45#include "ssherr.h" 46 47/* borrows code from sftp-server and ssh-agent */ 48 49/* 50 * Maintain a list of ssh-pkcs11-helper subprocesses. These may be looked up 51 * by provider path or their unique EC/RSA METHOD pointers. 52 */ 53struct helper { 54 char *path; 55 pid_t pid; 56 int fd; 57 RSA_METHOD *rsa_meth; 58 EC_KEY_METHOD *ec_meth; 59 int (*rsa_finish)(RSA *rsa); 60 void (*ec_finish)(EC_KEY *key); 61 size_t nrsa, nec; /* number of active keys of each type */ 62}; 63static struct helper **helpers; 64static size_t nhelpers; 65 66static struct helper * 67helper_by_provider(const char *path) 68{ 69 size_t i; 70 71 for (i = 0; i < nhelpers; i++) { 72 if (helpers[i] == NULL || helpers[i]->path == NULL || 73 helpers[i]->fd == -1) 74 continue; 75 if (strcmp(helpers[i]->path, path) == 0) 76 return helpers[i]; 77 } 78 return NULL; 79} 80 81static struct helper * 82helper_by_rsa(const RSA *rsa) 83{ 84 size_t i; 85 const RSA_METHOD *meth; 86 87 if ((meth = RSA_get_method(rsa)) == NULL) 88 return NULL; 89 for (i = 0; i < nhelpers; i++) { 90 if (helpers[i] != NULL && helpers[i]->rsa_meth == meth) 91 return helpers[i]; 92 } 93 return NULL; 94 95} 96 97static struct helper * 98helper_by_ec(const EC_KEY *ec) 99{ 100 size_t i; 101 const EC_KEY_METHOD *meth; 102 103 if ((meth = EC_KEY_get_method(ec)) == NULL) 104 return NULL; 105 for (i = 0; i < nhelpers; i++) { 106 if (helpers[i] != NULL && helpers[i]->ec_meth == meth) 107 return helpers[i]; 108 } 109 return NULL; 110 111} 112 113static void 114helper_free(struct helper *helper) 115{ 116 size_t i; 117 int found = 0; 118 119 if (helper == NULL) 120 return; 121 if (helper->path == NULL || helper->ec_meth == NULL || 122 helper->rsa_meth == NULL) 123 fatal_f("inconsistent helper"); 124 debug3_f("free helper for provider %s", helper->path); 125 for (i = 0; i < nhelpers; i++) { 126 if (helpers[i] == helper) { 127 if (found) 128 fatal_f("helper recorded more than once"); 129 found = 1; 130 } 131 else if (found) 132 helpers[i - 1] = helpers[i]; 133 } 134 if (found) { 135 helpers = xrecallocarray(helpers, nhelpers, 136 nhelpers - 1, sizeof(*helpers)); 137 nhelpers--; 138 } 139 free(helper->path); 140 EC_KEY_METHOD_free(helper->ec_meth); 141 RSA_meth_free(helper->rsa_meth); 142 free(helper); 143} 144 145static void 146helper_terminate(struct helper *helper) 147{ 148 if (helper == NULL) { 149 return; 150 } else if (helper->fd == -1) { 151 debug3_f("already terminated"); 152 } else { 153 debug3_f("terminating helper for %s; " 154 "remaining %zu RSA %zu ECDSA", 155 helper->path, helper->nrsa, helper->nec); 156 close(helper->fd); 157 /* XXX waitpid() */ 158 helper->fd = -1; 159 helper->pid = -1; 160 } 161 /* 162 * Don't delete the helper entry until there are no remaining keys 163 * that reference it. Otherwise, any signing operation would call 164 * a free'd METHOD pointer and that would be bad. 165 */ 166 if (helper->nrsa == 0 && helper->nec == 0) 167 helper_free(helper); 168} 169 170static void 171send_msg(int fd, struct sshbuf *m) 172{ 173 u_char buf[4]; 174 size_t mlen = sshbuf_len(m); 175 int r; 176 177 if (fd == -1) 178 return; 179 POKE_U32(buf, mlen); 180 if (atomicio(vwrite, fd, buf, 4) != 4 || 181 atomicio(vwrite, fd, sshbuf_mutable_ptr(m), 182 sshbuf_len(m)) != sshbuf_len(m)) 183 error("write to helper failed"); 184 if ((r = sshbuf_consume(m, mlen)) != 0) 185 fatal_fr(r, "consume"); 186} 187 188static int 189recv_msg(int fd, struct sshbuf *m) 190{ 191 u_int l, len; 192 u_char c, buf[1024]; 193 int r; 194 195 sshbuf_reset(m); 196 if (fd == -1) 197 return 0; /* XXX */ 198 if ((len = atomicio(read, fd, buf, 4)) != 4) { 199 error("read from helper failed: %u", len); 200 return (0); /* XXX */ 201 } 202 len = PEEK_U32(buf); 203 if (len > 256 * 1024) 204 fatal("response too long: %u", len); 205 /* read len bytes into m */ 206 while (len > 0) { 207 l = len; 208 if (l > sizeof(buf)) 209 l = sizeof(buf); 210 if (atomicio(read, fd, buf, l) != l) { 211 error("response from helper failed."); 212 return (0); /* XXX */ 213 } 214 if ((r = sshbuf_put(m, buf, l)) != 0) 215 fatal_fr(r, "sshbuf_put"); 216 len -= l; 217 } 218 if ((r = sshbuf_get_u8(m, &c)) != 0) 219 fatal_fr(r, "parse type"); 220 return c; 221} 222 223int 224pkcs11_init(int interactive) 225{ 226 return 0; 227} 228 229void 230pkcs11_terminate(void) 231{ 232 size_t i; 233 234 debug3_f("terminating %zu helpers", nhelpers); 235 for (i = 0; i < nhelpers; i++) 236 helper_terminate(helpers[i]); 237} 238 239static int 240rsa_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa, int padding) 241{ 242 struct sshkey *key = NULL; 243 struct sshbuf *msg = NULL; 244 u_char *blob = NULL, *signature = NULL; 245 size_t blen, slen = 0; 246 int r, ret = -1; 247 struct helper *helper; 248 249 if ((helper = helper_by_rsa(rsa)) == NULL || helper->fd == -1) 250 fatal_f("no helper for PKCS11 key"); 251 debug3_f("signing with PKCS11 provider %s", helper->path); 252 if (padding != RSA_PKCS1_PADDING) 253 goto fail; 254 key = sshkey_new(KEY_UNSPEC); 255 if (key == NULL) { 256 error_f("sshkey_new failed"); 257 goto fail; 258 } 259 key->type = KEY_RSA; 260 RSA_up_ref(rsa); 261 key->rsa = rsa; 262 if ((r = sshkey_to_blob(key, &blob, &blen)) != 0) { 263 error_fr(r, "encode key"); 264 goto fail; 265 } 266 if ((msg = sshbuf_new()) == NULL) 267 fatal_f("sshbuf_new failed"); 268 if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_SIGN_REQUEST)) != 0 || 269 (r = sshbuf_put_string(msg, blob, blen)) != 0 || 270 (r = sshbuf_put_string(msg, from, flen)) != 0 || 271 (r = sshbuf_put_u32(msg, 0)) != 0) 272 fatal_fr(r, "compose"); 273 send_msg(helper->fd, msg); 274 sshbuf_reset(msg); 275 276 if (recv_msg(helper->fd, msg) == SSH2_AGENT_SIGN_RESPONSE) { 277 if ((r = sshbuf_get_string(msg, &signature, &slen)) != 0) 278 fatal_fr(r, "parse"); 279 if (slen <= (size_t)RSA_size(rsa)) { 280 memcpy(to, signature, slen); 281 ret = slen; 282 } 283 free(signature); 284 } 285 fail: 286 free(blob); 287 sshkey_free(key); 288 sshbuf_free(msg); 289 return (ret); 290} 291 292static int 293rsa_finish(RSA *rsa) 294{ 295 struct helper *helper; 296 297 if ((helper = helper_by_rsa(rsa)) == NULL) 298 fatal_f("no helper for PKCS11 key"); 299 debug3_f("free PKCS11 RSA key for provider %s", helper->path); 300 if (helper->rsa_finish != NULL) 301 helper->rsa_finish(rsa); 302 if (helper->nrsa == 0) 303 fatal_f("RSA refcount error"); 304 helper->nrsa--; 305 debug3_f("provider %s remaining keys: %zu RSA %zu ECDSA", 306 helper->path, helper->nrsa, helper->nec); 307 if (helper->nrsa == 0 && helper->nec == 0) 308 helper_terminate(helper); 309 return 1; 310} 311 312static ECDSA_SIG * 313ecdsa_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *inv, 314 const BIGNUM *rp, EC_KEY *ec) 315{ 316 struct sshkey *key = NULL; 317 struct sshbuf *msg = NULL; 318 ECDSA_SIG *ret = NULL; 319 const u_char *cp; 320 u_char *blob = NULL, *signature = NULL; 321 size_t blen, slen = 0; 322 int r, nid; 323 struct helper *helper; 324 325 if ((helper = helper_by_ec(ec)) == NULL || helper->fd == -1) 326 fatal_f("no helper for PKCS11 key"); 327 debug3_f("signing with PKCS11 provider %s", helper->path); 328 nid = sshkey_ecdsa_key_to_nid(ec); 329 if (nid < 0) { 330 error_f("couldn't get curve nid"); 331 goto fail; 332 } 333 334 key = sshkey_new(KEY_UNSPEC); 335 if (key == NULL) { 336 error_f("sshkey_new failed"); 337 goto fail; 338 } 339 key->ecdsa = ec; 340 key->ecdsa_nid = nid; 341 key->type = KEY_ECDSA; 342 EC_KEY_up_ref(ec); 343 344 if ((r = sshkey_to_blob(key, &blob, &blen)) != 0) { 345 error_fr(r, "encode key"); 346 goto fail; 347 } 348 if ((msg = sshbuf_new()) == NULL) 349 fatal_f("sshbuf_new failed"); 350 if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_SIGN_REQUEST)) != 0 || 351 (r = sshbuf_put_string(msg, blob, blen)) != 0 || 352 (r = sshbuf_put_string(msg, dgst, dgst_len)) != 0 || 353 (r = sshbuf_put_u32(msg, 0)) != 0) 354 fatal_fr(r, "compose"); 355 send_msg(helper->fd, msg); 356 sshbuf_reset(msg); 357 358 if (recv_msg(helper->fd, msg) == SSH2_AGENT_SIGN_RESPONSE) { 359 if ((r = sshbuf_get_string(msg, &signature, &slen)) != 0) 360 fatal_fr(r, "parse"); 361 cp = signature; 362 ret = d2i_ECDSA_SIG(NULL, &cp, slen); 363 free(signature); 364 } 365 366 fail: 367 free(blob); 368 sshkey_free(key); 369 sshbuf_free(msg); 370 return (ret); 371} 372 373static void 374ecdsa_do_finish(EC_KEY *ec) 375{ 376 struct helper *helper; 377 378 if ((helper = helper_by_ec(ec)) == NULL) 379 fatal_f("no helper for PKCS11 key"); 380 debug3_f("free PKCS11 ECDSA key for provider %s", helper->path); 381 if (helper->ec_finish != NULL) 382 helper->ec_finish(ec); 383 if (helper->nec == 0) 384 fatal_f("ECDSA refcount error"); 385 helper->nec--; 386 debug3_f("provider %s remaining keys: %zu RSA %zu ECDSA", 387 helper->path, helper->nrsa, helper->nec); 388 if (helper->nrsa == 0 && helper->nec == 0) 389 helper_terminate(helper); 390} 391 392/* redirect private key crypto operations to the ssh-pkcs11-helper */ 393static void 394wrap_key(struct helper *helper, struct sshkey *k) 395{ 396 debug3_f("wrap %s for provider %s", sshkey_type(k), helper->path); 397 if (k->type == KEY_RSA) { 398 RSA_set_method(k->rsa, helper->rsa_meth); 399 if (helper->nrsa++ >= INT_MAX) 400 fatal_f("RSA refcount error"); 401 } else if (k->type == KEY_ECDSA) { 402 EC_KEY_set_method(k->ecdsa, helper->ec_meth); 403 if (helper->nec++ >= INT_MAX) 404 fatal_f("EC refcount error"); 405 } else 406 fatal_f("unknown key type"); 407 k->flags |= SSHKEY_FLAG_EXT; 408 debug3_f("provider %s remaining keys: %zu RSA %zu ECDSA", 409 helper->path, helper->nrsa, helper->nec); 410} 411 412/* 413 * Make a private PKCS#11-backed certificate by grafting a previously-loaded 414 * PKCS#11 private key and a public certificate key. 415 */ 416int 417pkcs11_make_cert(const struct sshkey *priv, 418 const struct sshkey *certpub, struct sshkey **certprivp) 419{ 420 struct helper *helper = NULL; 421 struct sshkey *ret; 422 int r; 423 424 debug3_f("private key type %s cert type %s", sshkey_type(priv), 425 sshkey_type(certpub)); 426 *certprivp = NULL; 427 if (!sshkey_is_cert(certpub) || sshkey_is_cert(priv) || 428 !sshkey_equal_public(priv, certpub)) { 429 error_f("private key %s doesn't match cert %s", 430 sshkey_type(priv), sshkey_type(certpub)); 431 return SSH_ERR_INVALID_ARGUMENT; 432 } 433 *certprivp = NULL; 434 if (priv->type == KEY_RSA) { 435 if ((helper = helper_by_rsa(priv->rsa)) == NULL || 436 helper->fd == -1) 437 fatal_f("no helper for PKCS11 RSA key"); 438 if ((r = sshkey_from_private(priv, &ret)) != 0) 439 fatal_fr(r, "copy key"); 440 RSA_set_method(ret->rsa, helper->rsa_meth); 441 if (helper->nrsa++ >= INT_MAX) 442 fatal_f("RSA refcount error"); 443 } else if (priv->type == KEY_ECDSA) { 444 if ((helper = helper_by_ec(priv->ecdsa)) == NULL || 445 helper->fd == -1) 446 fatal_f("no helper for PKCS11 EC key"); 447 if ((r = sshkey_from_private(priv, &ret)) != 0) 448 fatal_fr(r, "copy key"); 449 EC_KEY_set_method(ret->ecdsa, helper->ec_meth); 450 if (helper->nec++ >= INT_MAX) 451 fatal_f("EC refcount error"); 452 } else 453 fatal_f("unknown key type %s", sshkey_type(priv)); 454 455 ret->flags |= SSHKEY_FLAG_EXT; 456 if ((r = sshkey_to_certified(ret)) != 0 || 457 (r = sshkey_cert_copy(certpub, ret)) != 0) 458 fatal_fr(r, "graft certificate"); 459 debug3_f("provider %s remaining keys: %zu RSA %zu ECDSA", 460 helper->path, helper->nrsa, helper->nec); 461 /* success */ 462 *certprivp = ret; 463 return 0; 464} 465 466static int 467pkcs11_start_helper_methods(struct helper *helper) 468{ 469 int (*ec_init)(EC_KEY *key); 470 int (*ec_copy)(EC_KEY *dest, const EC_KEY *src); 471 int (*ec_set_group)(EC_KEY *key, const EC_GROUP *grp); 472 int (*ec_set_private)(EC_KEY *key, const BIGNUM *priv_key); 473 int (*ec_set_public)(EC_KEY *key, const EC_POINT *pub_key); 474 int (*ec_sign)(int, const unsigned char *, int, unsigned char *, 475 unsigned int *, const BIGNUM *, const BIGNUM *, EC_KEY *) = NULL; 476 RSA_METHOD *rsa_meth; 477 EC_KEY_METHOD *ec_meth; 478 479 if ((ec_meth = EC_KEY_METHOD_new(EC_KEY_OpenSSL())) == NULL) 480 return -1; 481 EC_KEY_METHOD_get_sign(ec_meth, &ec_sign, NULL, NULL); 482 EC_KEY_METHOD_set_sign(ec_meth, ec_sign, NULL, ecdsa_do_sign); 483 EC_KEY_METHOD_get_init(ec_meth, &ec_init, &helper->ec_finish, 484 &ec_copy, &ec_set_group, &ec_set_private, &ec_set_public); 485 EC_KEY_METHOD_set_init(ec_meth, ec_init, ecdsa_do_finish, 486 ec_copy, ec_set_group, ec_set_private, ec_set_public); 487 488 if ((rsa_meth = RSA_meth_dup(RSA_get_default_method())) == NULL) 489 fatal_f("RSA_meth_dup failed"); 490 helper->rsa_finish = RSA_meth_get_finish(rsa_meth); 491 if (!RSA_meth_set1_name(rsa_meth, "ssh-pkcs11-helper") || 492 !RSA_meth_set_priv_enc(rsa_meth, rsa_encrypt) || 493 !RSA_meth_set_finish(rsa_meth, rsa_finish)) 494 fatal_f("failed to prepare method"); 495 496 helper->ec_meth = ec_meth; 497 helper->rsa_meth = rsa_meth; 498 return 0; 499} 500 501static struct helper * 502pkcs11_start_helper(const char *path) 503{ 504 int pair[2]; 505 const char *prog, *verbosity = NULL; 506 struct helper *helper; 507 pid_t pid; 508 509 if (nhelpers >= INT_MAX) 510 fatal_f("too many helpers"); 511 debug3_f("start helper for %s", path); 512 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) { 513 error_f("socketpair: %s", strerror(errno)); 514 return NULL; 515 } 516 helper = xcalloc(1, sizeof(*helper)); 517 if (pkcs11_start_helper_methods(helper) == -1) { 518 error_f("pkcs11_start_helper_methods failed"); 519 goto fail; 520 } 521 if ((pid = fork()) == -1) { 522 error_f("fork: %s", strerror(errno)); 523 fail: 524 close(pair[0]); 525 close(pair[1]); 526 RSA_meth_free(helper->rsa_meth); 527 EC_KEY_METHOD_free(helper->ec_meth); 528 free(helper); 529 return NULL; 530 } else if (pid == 0) { 531 if ((dup2(pair[1], STDIN_FILENO) == -1) || 532 (dup2(pair[1], STDOUT_FILENO) == -1)) { 533 fprintf(stderr, "dup2: %s\n", strerror(errno)); 534 _exit(1); 535 } 536 close(pair[0]); 537 close(pair[1]); 538 prog = getenv("SSH_PKCS11_HELPER"); 539 if (prog == NULL || strlen(prog) == 0) 540 prog = _PATH_SSH_PKCS11_HELPER; 541 if (log_level_get() >= SYSLOG_LEVEL_DEBUG1) 542 verbosity = "-vvv"; 543 debug_f("starting %s %s", prog, 544 verbosity == NULL ? "" : verbosity); 545 execlp(prog, prog, verbosity, (char *)NULL); 546 fprintf(stderr, "exec: %s: %s\n", prog, strerror(errno)); 547 _exit(1); 548 } 549 close(pair[1]); 550 helper->fd = pair[0]; 551 helper->path = xstrdup(path); 552 helper->pid = pid; 553 debug3_f("helper %zu for \"%s\" on fd %d pid %ld", nhelpers, 554 helper->path, helper->fd, (long)helper->pid); 555 helpers = xrecallocarray(helpers, nhelpers, 556 nhelpers + 1, sizeof(*helpers)); 557 helpers[nhelpers++] = helper; 558 return helper; 559} 560 561int 562pkcs11_add_provider(char *name, char *pin, struct sshkey ***keysp, 563 char ***labelsp) 564{ 565 struct sshkey *k; 566 int r, type; 567 u_char *blob; 568 char *label; 569 size_t blen; 570 u_int nkeys, i; 571 struct sshbuf *msg; 572 struct helper *helper; 573 574 if ((helper = helper_by_provider(name)) == NULL && 575 (helper = pkcs11_start_helper(name)) == NULL) 576 return -1; 577 578 if ((msg = sshbuf_new()) == NULL) 579 fatal_f("sshbuf_new failed"); 580 if ((r = sshbuf_put_u8(msg, SSH_AGENTC_ADD_SMARTCARD_KEY)) != 0 || 581 (r = sshbuf_put_cstring(msg, name)) != 0 || 582 (r = sshbuf_put_cstring(msg, pin)) != 0) 583 fatal_fr(r, "compose"); 584 send_msg(helper->fd, msg); 585 sshbuf_reset(msg); 586 587 type = recv_msg(helper->fd, msg); 588 if (type == SSH2_AGENT_IDENTITIES_ANSWER) { 589 if ((r = sshbuf_get_u32(msg, &nkeys)) != 0) 590 fatal_fr(r, "parse nkeys"); 591 *keysp = xcalloc(nkeys, sizeof(struct sshkey *)); 592 if (labelsp) 593 *labelsp = xcalloc(nkeys, sizeof(char *)); 594 for (i = 0; i < nkeys; i++) { 595 /* XXX clean up properly instead of fatal() */ 596 if ((r = sshbuf_get_string(msg, &blob, &blen)) != 0 || 597 (r = sshbuf_get_cstring(msg, &label, NULL)) != 0) 598 fatal_fr(r, "parse key"); 599 if ((r = sshkey_from_blob(blob, blen, &k)) != 0) 600 fatal_fr(r, "decode key"); 601 wrap_key(helper, k); 602 (*keysp)[i] = k; 603 if (labelsp) 604 (*labelsp)[i] = label; 605 else 606 free(label); 607 free(blob); 608 } 609 } else if (type == SSH2_AGENT_FAILURE) { 610 if ((r = sshbuf_get_u32(msg, &nkeys)) != 0) 611 nkeys = -1; 612 } else { 613 nkeys = -1; 614 } 615 sshbuf_free(msg); 616 return (nkeys); 617} 618 619int 620pkcs11_del_provider(char *name) 621{ 622 struct helper *helper; 623 624 /* 625 * ssh-agent deletes keys before calling this, so the helper entry 626 * should be gone before we get here. 627 */ 628 debug3_f("delete %s", name); 629 if ((helper = helper_by_provider(name)) != NULL) 630 helper_terminate(helper); 631 return 0; 632} 633