Coverage Report

Created: 2025-10-10 06:39

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