Coverage Report

Created: 2025-08-29 06:46

/src/openssh/ssh-pkcs11-client.c
Line
Count
Source (jump to first uncovered line)
1
/* $OpenBSD: ssh-pkcs11-client.c,v 1.24 2025/07/30 10:17:13 dtucker Exp $ */
2
/*
3
 * Copyright (c) 2010 Markus Friedl.  All rights reserved.
4
 * Copyright (c) 2014 Pedro Martelletto. All rights reserved.
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 */
18
19
#include "includes.h"
20
21
#include <sys/types.h>
22
#ifdef HAVE_SYS_TIME_H
23
# include <sys/time.h>
24
#endif
25
#include <sys/socket.h>
26
27
#include <stdarg.h>
28
#include <stdlib.h>
29
#include <string.h>
30
#include <unistd.h>
31
#include <errno.h>
32
#include <limits.h>
33
34
#include "pathnames.h"
35
#include "xmalloc.h"
36
#include "sshbuf.h"
37
#include "log.h"
38
#include "misc.h"
39
#include "sshkey.h"
40
#include "authfd.h"
41
#include "atomicio.h"
42
#include "ssh-pkcs11.h"
43
#include "ssherr.h"
44
45
/* borrows code from sftp-server and ssh-agent */
46
47
/*
48
 * Maintain a list of ssh-pkcs11-helper subprocesses. These may be looked up
49
 * by provider path or their unique keyblobs.
50
 */
51
struct helper {
52
  char *path;
53
  pid_t pid;
54
  int fd;
55
  size_t nkeyblobs;
56
  struct sshbuf **keyblobs; /* XXX use a tree or something faster */
57
};
58
static struct helper **helpers;
59
static size_t nhelpers;
60
61
static struct helper *
62
helper_by_provider(const char *path)
63
0
{
64
0
  size_t i;
65
66
0
  for (i = 0; i < nhelpers; i++) {
67
0
    if (helpers[i] == NULL || helpers[i]->path == NULL ||
68
0
        helpers[i]->fd == -1)
69
0
      continue;
70
0
    if (strcmp(helpers[i]->path, path) == 0)
71
0
      return helpers[i];
72
0
  }
73
0
  return NULL;
74
0
}
75
76
static struct helper *
77
helper_by_key(const struct sshkey *key)
78
0
{
79
0
  size_t i, j;
80
0
  struct sshbuf *keyblob = NULL;
81
0
  int r;
82
83
0
  if ((keyblob = sshbuf_new()) == NULL)
84
0
    fatal_f("sshbuf_new failed");
85
0
  if ((r = sshkey_putb(key, keyblob)) != 0)
86
0
    fatal_fr(r, "serialise key");
87
88
0
  for (i = 0; i < nhelpers; i++) {
89
0
    if (helpers[i] == NULL)
90
0
      continue;
91
0
    for (j = 0; j < helpers[i]->nkeyblobs; j++) {
92
0
      if (sshbuf_equals(keyblob,
93
0
          helpers[i]->keyblobs[j]) == 0) {
94
0
        sshbuf_free(keyblob);
95
0
        return helpers[i];
96
0
      }
97
0
    }
98
0
  }
99
0
  sshbuf_free(keyblob);
100
0
  return NULL;
101
102
0
}
103
104
static void
105
helper_add_key(struct helper *helper, struct sshkey *key)
106
0
{
107
0
  int r;
108
109
0
  helper->keyblobs = xrecallocarray(helper->keyblobs, helper->nkeyblobs,
110
0
      helper->nkeyblobs + 1, sizeof(*helper->keyblobs));
111
0
  if ((helper->keyblobs[helper->nkeyblobs] = sshbuf_new()) == NULL)
112
0
    fatal_f("sshbuf_new failed");
113
0
  if ((r = sshkey_putb(key, helper->keyblobs[helper->nkeyblobs])) != 0)
114
0
    fatal_fr(r, "shkey_putb failed");
115
0
  helper->nkeyblobs++;
116
0
  debug3_f("added %s key for provider %s, now has %zu keys",
117
0
      sshkey_type(key), helper->path, helper->nkeyblobs);
118
0
}
119
120
static void
121
helper_terminate(struct helper *helper)
122
0
{
123
0
  size_t i;
124
0
  int found = 0;
125
126
0
  if (helper == NULL)
127
0
    return;
128
0
  if (helper->path == NULL)
129
0
    fatal_f("inconsistent helper");
130
131
0
  debug3_f("terminating helper for %s; remaining %zu keys",
132
0
      helper->path, helper->nkeyblobs);
133
134
0
  close(helper->fd);
135
  /* XXX waitpid() */
136
0
  helper->fd = -1;
137
0
  helper->pid = -1;
138
139
  /* repack helpers */
140
0
  for (i = 0; i < nhelpers; i++) {
141
0
    if (helpers[i] == helper) {
142
0
      if (found)
143
0
        fatal_f("helper recorded more than once");
144
0
      found = 1;
145
0
    } else if (found)
146
0
      helpers[i - 1] = helpers[i];
147
0
  }
148
0
  if (found) {
149
0
    helpers = xrecallocarray(helpers, nhelpers,
150
0
        nhelpers - 1, sizeof(*helpers));
151
0
    nhelpers--;
152
0
  }
153
0
  for (i = 0; i < helper->nkeyblobs; i++)
154
0
    sshbuf_free(helper->keyblobs[i]);
155
0
  free(helper->path);
156
0
  free(helper);
157
0
}
158
159
static void
160
send_msg(int fd, struct sshbuf *m)
161
0
{
162
0
  u_char buf[4];
163
0
  size_t mlen = sshbuf_len(m);
164
0
  int r;
165
166
0
  if (fd == -1)
167
0
    return;
168
0
  POKE_U32(buf, mlen);
169
0
  if (atomicio(vwrite, fd, buf, 4) != 4 ||
170
0
      atomicio(vwrite, fd, sshbuf_mutable_ptr(m),
171
0
      sshbuf_len(m)) != sshbuf_len(m))
172
0
    error("write to helper failed");
173
0
  if ((r = sshbuf_consume(m, mlen)) != 0)
174
0
    fatal_fr(r, "consume");
175
0
}
176
177
static int
178
recv_msg(int fd, struct sshbuf *m)
179
0
{
180
0
  u_int l, len;
181
0
  u_char c, buf[1024];
182
0
  int r;
183
184
0
  sshbuf_reset(m);
185
0
  if (fd == -1)
186
0
    return 0; /* XXX */
187
0
  if ((len = atomicio(read, fd, buf, 4)) != 4) {
188
0
    error("read from helper failed: %u", len);
189
0
    return (0); /* XXX */
190
0
  }
191
0
  len = PEEK_U32(buf);
192
0
  if (len > 256 * 1024)
193
0
    fatal("response too long: %u", len);
194
  /* read len bytes into m */
195
0
  while (len > 0) {
196
0
    l = len;
197
0
    if (l > sizeof(buf))
198
0
      l = sizeof(buf);
199
0
    if (atomicio(read, fd, buf, l) != l) {
200
0
      error("response from helper failed.");
201
0
      return (0); /* XXX */
202
0
    }
203
0
    if ((r = sshbuf_put(m, buf, l)) != 0)
204
0
      fatal_fr(r, "sshbuf_put");
205
0
    len -= l;
206
0
  }
207
0
  if ((r = sshbuf_get_u8(m, &c)) != 0)
208
0
    fatal_fr(r, "parse type");
209
0
  return c;
210
0
}
211
212
int
213
pkcs11_init(int interactive)
214
0
{
215
0
  return 0;
216
0
}
217
218
void
219
pkcs11_terminate(void)
220
0
{
221
0
  size_t i;
222
223
0
  debug3_f("terminating %zu helpers", nhelpers);
224
0
  for (i = 0; i < nhelpers; i++)
225
0
    helper_terminate(helpers[i]);
226
0
}
227
228
int
229
pkcs11_sign(struct sshkey *key,
230
    u_char **sigp, size_t *lenp,
231
    const u_char *data, size_t datalen,
232
    const char *alg, const char *sk_provider,
233
    const char *sk_pin, u_int compat)
234
0
{
235
0
  struct sshbuf *msg = NULL;
236
0
  struct helper *helper;
237
0
  int status, r;
238
0
  u_char *signature = NULL;
239
0
  size_t signature_len = 0;
240
0
  int ret = SSH_ERR_INTERNAL_ERROR;
241
242
0
  if (sigp != NULL)
243
0
    *sigp = NULL;
244
0
  if (lenp != NULL)
245
0
    *lenp = 0;
246
247
0
  if ((helper = helper_by_key(key)) == NULL || helper->fd == -1)
248
0
    fatal_f("no helper for %s key", sshkey_type(key));
249
250
0
  if ((msg = sshbuf_new()) == NULL)
251
0
    return SSH_ERR_ALLOC_FAIL;
252
0
  if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_SIGN_REQUEST)) != 0 ||
253
0
      (r = sshkey_puts_plain(key, msg)) != 0 ||
254
0
      (r = sshbuf_put_string(msg, data, datalen)) != 0 ||
255
0
      (r = sshbuf_put_cstring(msg, alg == NULL ? "" : alg)) != 0 ||
256
0
      (r = sshbuf_put_u32(msg, compat)) != 0)
257
0
    fatal_fr(r, "compose");
258
0
  send_msg(helper->fd, msg);
259
0
  sshbuf_reset(msg);
260
261
0
  if ((status = recv_msg(helper->fd, msg)) != SSH2_AGENT_SIGN_RESPONSE) {
262
    /* XXX translate status to something useful */
263
0
    debug_fr(r, "recv_msg");
264
0
    ret = SSH_ERR_AGENT_FAILURE;
265
0
    goto fail;
266
0
  }
267
268
0
  if ((r = sshbuf_get_string(msg, &signature, &signature_len)) != 0)
269
0
    fatal_fr(r, "parse");
270
271
  /* success */
272
0
  if (sigp != NULL) {
273
0
    *sigp = signature;
274
0
    signature = NULL;
275
0
  }
276
0
  if (lenp != NULL)
277
0
    *lenp = signature_len;
278
0
  ret = 0;
279
280
0
 fail:
281
0
  free(signature);
282
0
  sshbuf_free(msg);
283
0
  return ret;
284
0
}
285
286
/*
287
 * Make a private PKCS#11-backed certificate by grafting a previously-loaded
288
 * PKCS#11 private key and a public certificate key.
289
 */
290
int
291
pkcs11_make_cert(const struct sshkey *priv,
292
    const struct sshkey *certpub, struct sshkey **certprivp)
293
0
{
294
0
  struct helper *helper = NULL;
295
0
  struct sshkey *ret;
296
0
  int r;
297
298
0
  if ((helper = helper_by_key(priv)) == NULL || helper->fd == -1)
299
0
    fatal_f("no helper for %s key", sshkey_type(priv));
300
301
0
  debug3_f("private key type %s cert type %s on provider %s",
302
0
      sshkey_type(priv), sshkey_type(certpub), helper->path);
303
304
0
  *certprivp = NULL;
305
0
  if (!sshkey_is_cert(certpub) || sshkey_is_cert(priv) ||
306
0
      !sshkey_equal_public(priv, certpub)) {
307
0
    error_f("private key %s doesn't match cert %s",
308
0
        sshkey_type(priv), sshkey_type(certpub));
309
0
    return SSH_ERR_INVALID_ARGUMENT;
310
0
  }
311
0
  *certprivp = NULL;
312
0
  if ((r = sshkey_from_private(priv, &ret)) != 0)
313
0
    fatal_fr(r, "copy key");
314
315
0
  ret->flags |= SSHKEY_FLAG_EXT;
316
0
  if ((r = sshkey_to_certified(ret)) != 0 ||
317
0
      (r = sshkey_cert_copy(certpub, ret)) != 0)
318
0
    fatal_fr(r, "graft certificate");
319
320
0
  helper_add_key(helper, ret);
321
322
0
  debug3_f("provider %s: %zu remaining keys",
323
0
      helper->path, helper->nkeyblobs);
324
325
  /* success */
326
0
  *certprivp = ret;
327
0
  return 0;
328
0
}
329
330
static struct helper *
331
pkcs11_start_helper(const char *path)
332
0
{
333
0
  int pair[2];
334
0
  char *prog, *verbosity = NULL;
335
0
  struct helper *helper;
336
0
  pid_t pid;
337
338
0
  if (nhelpers >= INT_MAX)
339
0
    fatal_f("too many helpers");
340
0
  debug3_f("start helper for %s", path);
341
0
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) {
342
0
    error_f("socketpair: %s", strerror(errno));
343
0
    return NULL;
344
0
  }
345
0
  helper = xcalloc(1, sizeof(*helper));
346
0
  if ((pid = fork()) == -1) {
347
0
    error_f("fork: %s", strerror(errno));
348
0
    close(pair[0]);
349
0
    close(pair[1]);
350
0
    free(helper);
351
0
    return NULL;
352
0
  } else if (pid == 0) {
353
0
    if ((dup2(pair[1], STDIN_FILENO) == -1) ||
354
0
        (dup2(pair[1], STDOUT_FILENO) == -1)) {
355
0
      fprintf(stderr, "dup2: %s\n", strerror(errno));
356
0
      _exit(1);
357
0
    }
358
0
    close(pair[0]);
359
0
    close(pair[1]);
360
0
    prog = getenv("SSH_PKCS11_HELPER");
361
0
    if (prog == NULL || strlen(prog) == 0)
362
0
      prog = _PATH_SSH_PKCS11_HELPER;
363
0
    if (log_level_get() >= SYSLOG_LEVEL_DEBUG1)
364
0
      verbosity = "-vvv";
365
0
    debug_f("starting %s %s", prog,
366
0
        verbosity == NULL ? "" : verbosity);
367
0
    execlp(prog, prog, verbosity, (char *)NULL);
368
0
    fprintf(stderr, "exec: %s: %s\n", prog, strerror(errno));
369
0
    _exit(1);
370
0
  }
371
0
  close(pair[1]);
372
0
  helper->fd = pair[0];
373
0
  helper->path = xstrdup(path);
374
0
  helper->pid = pid;
375
0
  debug3_f("helper %zu for \"%s\" on fd %d pid %ld", nhelpers,
376
0
      helper->path, helper->fd, (long)helper->pid);
377
0
  helpers = xrecallocarray(helpers, nhelpers,
378
0
      nhelpers + 1, sizeof(*helpers));
379
0
  helpers[nhelpers++] = helper;
380
0
  return helper;
381
0
}
382
383
int
384
pkcs11_add_provider(char *name, char *pin, struct sshkey ***keysp,
385
    char ***labelsp)
386
0
{
387
0
  struct sshkey *k;
388
0
  int r, type;
389
0
  char *label;
390
0
  u_int ret = -1, nkeys, i;
391
0
  struct sshbuf *msg;
392
0
  struct helper *helper;
393
394
0
  if ((helper = helper_by_provider(name)) == NULL &&
395
0
      (helper = pkcs11_start_helper(name)) == NULL)
396
0
    return -1;
397
398
0
  debug3_f("add %s", helper->path);
399
400
0
  if ((msg = sshbuf_new()) == NULL)
401
0
    fatal_f("sshbuf_new failed");
402
0
  if ((r = sshbuf_put_u8(msg, SSH_AGENTC_ADD_SMARTCARD_KEY)) != 0 ||
403
0
      (r = sshbuf_put_cstring(msg, name)) != 0 ||
404
0
      (r = sshbuf_put_cstring(msg, pin)) != 0)
405
0
    fatal_fr(r, "compose");
406
0
  send_msg(helper->fd, msg);
407
0
  sshbuf_reset(msg);
408
409
0
  type = recv_msg(helper->fd, msg);
410
0
  debug3_f("response %d", type);
411
0
  if (type == SSH2_AGENT_IDENTITIES_ANSWER) {
412
0
    if ((r = sshbuf_get_u32(msg, &nkeys)) != 0)
413
0
      fatal_fr(r, "parse nkeys");
414
0
    debug3_f("helper return %u keys", nkeys);
415
0
    *keysp = xcalloc(nkeys, sizeof(struct sshkey *));
416
0
    if (labelsp)
417
0
      *labelsp = xcalloc(nkeys, sizeof(char *));
418
0
    for (i = 0; i < nkeys; i++) {
419
      /* XXX clean up properly instead of fatal() */
420
0
      if ((r = sshkey_froms(msg, &k)) != 0 ||
421
0
          (r = sshbuf_get_cstring(msg, &label, NULL)) != 0)
422
0
        fatal_fr(r, "parse key");
423
0
      k->flags |= SSHKEY_FLAG_EXT;
424
0
      helper_add_key(helper, k);
425
0
      (*keysp)[i] = k;
426
0
      if (labelsp)
427
0
        (*labelsp)[i] = label;
428
0
      else
429
0
        free(label);
430
0
    }
431
    /* success */
432
0
    ret = 0;
433
0
  } else if (type == SSH2_AGENT_FAILURE) {
434
0
    if ((r = sshbuf_get_u32(msg, &nkeys)) != 0)
435
0
      error_fr(r, "failed to parse failure response");
436
0
  }
437
0
  if (ret != 0) {
438
0
    debug_f("no keys; terminate helper");
439
0
    helper_terminate(helper);
440
0
  }
441
0
  sshbuf_free(msg);
442
0
  return ret == 0 ? (int)nkeys : -1;
443
0
}
444
445
int
446
pkcs11_del_provider(char *name)
447
0
{
448
0
  struct helper *helper;
449
450
  /*
451
   * ssh-agent deletes keys before calling this, so the helper entry
452
   * should be gone before we get here.
453
   */
454
0
  debug3_f("delete %s", name ? name : "(null)");
455
0
  if ((helper = helper_by_provider(name)) != NULL)
456
0
    helper_terminate(helper);
457
0
  return 0;
458
0
}
459
460
void
461
pkcs11_key_free(struct sshkey *key)
462
0
{
463
0
  struct helper *helper;
464
0
  struct sshbuf *keyblob = NULL;
465
0
  size_t i;
466
0
  int r, found = 0;
467
468
0
  debug3_f("free %s key", sshkey_type(key));
469
470
0
  if ((helper = helper_by_key(key)) == NULL || helper->fd == -1)
471
0
    fatal_f("no helper for %s key", sshkey_type(key));
472
0
  if ((keyblob = sshbuf_new()) == NULL)
473
0
    fatal_f("sshbuf_new failed");
474
0
  if ((r = sshkey_putb(key, keyblob)) != 0)
475
0
    fatal_fr(r, "serialise key");
476
477
  /* repack keys */
478
0
  for (i = 0; i < helper->nkeyblobs; i++) {
479
0
    if (sshbuf_equals(keyblob, helper->keyblobs[i]) == 0) {
480
0
      if (found)
481
0
        fatal_f("key recorded more than once");
482
0
      found = 1;
483
0
    } else if (found)
484
0
      helper->keyblobs[i - 1] = helper->keyblobs[i];
485
0
  }
486
0
  if (found) {
487
0
    helper->keyblobs = xrecallocarray(helper->keyblobs,
488
0
        helper->nkeyblobs, helper->nkeyblobs - 1,
489
0
        sizeof(*helper->keyblobs));
490
0
    helper->nkeyblobs--;
491
0
  }
492
0
  if (helper->nkeyblobs == 0)
493
0
    helper_terminate(helper);
494
0
}