Coverage Report

Created: 2026-10-28 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssh/auth2-pubkey.c
Line
Count
Source
1
/* $OpenBSD: auth2-pubkey.c,v 1.132 2026/10/11 20:41:20 dtucker Exp $ */
2
/*
3
 * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4
 * Copyright (c) 2010 Damien Miller.  All rights reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without
7
 * modification, are permitted provided that the following conditions
8
 * are met:
9
 * 1. Redistributions of source code must retain the above copyright
10
 *    notice, this list of conditions and the following disclaimer.
11
 * 2. Redistributions in binary form must reproduce the above copyright
12
 *    notice, this list of conditions and the following disclaimer in the
13
 *    documentation and/or other materials provided with the distribution.
14
 *
15
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
 */
26
27
#include "includes.h"
28
29
#include <sys/types.h>
30
31
#include <stdlib.h>
32
#include <errno.h>
33
#include <paths.h>
34
#include <pwd.h>
35
#include <glob.h>
36
#include <signal.h>
37
#include <stdio.h>
38
#include <stdarg.h>
39
#include <string.h>
40
#include <time.h>
41
#include <unistd.h>
42
#include <limits.h>
43
44
#include "xmalloc.h"
45
#include "ssh.h"
46
#include "ssh2.h"
47
#include "packet.h"
48
#include "kex.h"
49
#include "sshbuf.h"
50
#include "log.h"
51
#include "misc.h"
52
#include "servconf.h"
53
#include "compat.h"
54
#include "sshkey.h"
55
#include "hostfile.h"
56
#include "auth.h"
57
#include "pathnames.h"
58
#include "uidswap.h"
59
#include "auth-options.h"
60
#include "canohost.h"
61
#ifdef GSSAPI
62
#include "ssh-gss.h"
63
#endif
64
#include "monitor_wrap.h"
65
#include "authfile.h"
66
#include "match.h"
67
#include "ssherr.h"
68
#include "channels.h" /* XXX for session.h */
69
#include "session.h" /* XXX for child_set_env(); refactor? */
70
#include "sk-api.h"
71
72
/* import */
73
extern ServerOptions options;
74
extern struct authmethod_cfg methodcfg_pubkey;
75
76
static char *
77
format_key(const struct sshkey *key)
78
0
{
79
0
  char *ret, *fp = sshkey_fingerprint(key,
80
0
      options.fingerprint_hash, SSH_FP_DEFAULT);
81
82
0
  xasprintf(&ret, "%s %s", sshkey_type(key), fp);
83
0
  free(fp);
84
0
  return ret;
85
0
}
86
87
/*
88
 * Verify that the hostkey in a publickey-hostbound-v00@openssh.com userauth
89
 * request matches the hostkey that was negotiated during initial KEX.
90
 */
91
static void
92
check_hostbound_hostkey(struct ssh *ssh)
93
0
{
94
0
  int r;
95
0
  struct sshbuf *our_hostkey_blob, *their_hostkey_blob;
96
97
0
  if (ssh->kex->initial_hostkey == NULL)
98
0
    fatal_f("internal error: initial hostkey not recorded");
99
0
  if ((our_hostkey_blob = sshbuf_new()) == NULL)
100
0
    fatal_f("sshbuf_new failed");
101
0
  if ((r = sshpkt_getb_froms(ssh, &their_hostkey_blob)) != 0)
102
0
    fatal_fr(r, "parse hostkey");
103
0
  if ((r = sshkey_putb(ssh->kex->initial_hostkey, our_hostkey_blob)) != 0)
104
0
    fatal_fr(r, "serialise hostkey");
105
0
  if ((r = sshbuf_equals(our_hostkey_blob, their_hostkey_blob)) != 0)
106
0
    fatal_f("packet contained wrong host key");
107
0
  sshbuf_free(our_hostkey_blob);
108
0
  sshbuf_free(their_hostkey_blob);
109
0
}
110
111
static int
112
userauth_pubkey(struct ssh *ssh, const char *method)
113
4
{
114
4
  Authctxt *authctxt = ssh->authctxt;
115
4
  struct passwd *pw = authctxt->pw;
116
4
  struct sshbuf *keyblob = NULL, *b = NULL;
117
4
  struct sshkey *key = NULL, *hostkey = NULL;
118
4
  char *pkalg = NULL, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
119
4
  char *keystring = NULL;
120
4
  u_char *sig = NULL, have_sig;
121
4
  size_t slen;
122
4
  int hostbound, r, pktype;
123
4
  int req_presence = 0, req_verify = 0, authenticated = 0;
124
4
  struct sshauthopt *authopts = NULL;
125
4
  struct sshkey_sig_details *sig_details = NULL;
126
127
4
  hostbound = strcmp(method, "publickey-hostbound-v00@openssh.com") == 0;
128
129
4
  if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
130
3
      (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
131
1
      (r = sshpkt_getb_froms(ssh, &keyblob)) != 0)
132
4
    fatal_fr(r, "parse %s packet", method);
133
134
  /* hostbound auth includes the hostkey offered at initial KEX */
135
0
  if (hostbound)
136
0
    check_hostbound_hostkey(ssh); /* fatals on error */
137
138
0
  if (log_level_get() >= SYSLOG_LEVEL_DEBUG2) {
139
0
    if ((b = sshbuf_fromb(keyblob)) == NULL)
140
0
      fatal_f("sshbuf_fromb failed");
141
0
    if ((keystring = sshbuf_dtob64_string(b, 0)) == NULL)
142
0
      fatal_f("sshbuf_dtob64 failed");
143
0
    debug2_f("%s user %s %s public key %s %s",
144
0
        authctxt->valid ? "valid" : "invalid", authctxt->user,
145
0
        have_sig ? "attempting" : "querying", pkalg, keystring);
146
0
    sshbuf_free(b);
147
0
    b = NULL;
148
0
  }
149
150
0
  pktype = sshkey_type_from_name(pkalg);
151
0
  if (pktype == KEY_UNSPEC) {
152
    /* this is perfectly legal */
153
0
    verbose_f("unsupported public key algorithm: %s", pkalg);
154
0
    goto done;
155
0
  }
156
0
  if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
157
0
    logit_f("signature algorithm %s not in "
158
0
        "PubkeyAcceptedAlgorithms", pkalg);
159
0
    goto done;
160
0
  }
161
0
  if ((b = sshbuf_fromb(keyblob)) == NULL)
162
0
    fatal_f("sshbuf_fromb failed");
163
0
  switch ((r = sshkey_fromb_allowlist(b, &key,
164
0
      options.pubkey_accepted_algos, options.ca_sign_algorithms))) {
165
0
  case 0:
166
    /* ok */
167
0
    break;
168
0
  case SSH_ERR_KEY_ALG_UNSUPPORTED:
169
    /* This shouldn't happen unless the client is being weird */
170
0
    logit_f("key algorithm differs from signature algorithm %s and "
171
0
        "is not in PubkeyAcceptedAlgorithms", pkalg);
172
0
    goto done;
173
0
  case SSH_ERR_SIGN_ALG_UNSUPPORTED:
174
0
    logit_fr(r, "certificate signature algorithm not in "
175
0
        "CASignatureAlgorithm");
176
0
    goto done;
177
0
  default:
178
0
    error_fr(r, "parse key");
179
0
    goto done;
180
0
  }
181
0
  sshbuf_free(b);
182
0
  b = NULL;
183
184
  /* USERAUTH_REQUEST signature type should match key's type */
185
0
  if (key->type != pktype || (sshkey_type_plain(pktype) == KEY_ECDSA &&
186
0
      sshkey_ecdsa_nid_from_name(pkalg) != key->ecdsa_nid)) {
187
0
    error_f("key type mismatch for decoded key "
188
0
        "(received %s, expected %s)", sshkey_ssh_name(key), pkalg);
189
0
    goto done;
190
0
  }
191
0
  if (auth2_key_already_used(authctxt, key)) {
192
0
    logit("refusing previously-used %s key", sshkey_type(key));
193
0
    goto done;
194
0
  }
195
0
  if ((r = sshkey_check_rsa_length(key,
196
0
      options.required_rsa_size)) != 0) {
197
0
    logit_r(r, "refusing %s key", sshkey_type(key));
198
0
    goto done;
199
0
  }
200
0
  key_s = format_key(key);
201
0
  if (sshkey_is_cert(key))
202
0
    ca_s = format_key(key->cert->signature_key);
203
204
0
  if (have_sig) {
205
0
    debug3_f("%s have %s signature for %s%s%s",
206
0
        method, pkalg, key_s,
207
0
        ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
208
0
    if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
209
0
        (r = sshpkt_get_end(ssh)) != 0)
210
0
      fatal_fr(r, "parse signature packet");
211
0
    if ((b = sshbuf_new()) == NULL)
212
0
      fatal_f("sshbuf_new failed");
213
0
    if ((r = sshbuf_put_stringb(b,
214
0
        ssh->kex->session_id)) != 0)
215
0
      fatal_fr(r, "put session id");
216
0
    if (!authctxt->valid || authctxt->user == NULL) {
217
0
      debug2_f("disabled because of invalid user");
218
0
      goto done;
219
0
    }
220
    /* reconstruct packet */
221
0
    xasprintf(&userstyle, "%s%s%s", authctxt->user,
222
0
        authctxt->style ? ":" : "",
223
0
        authctxt->style ? authctxt->style : "");
224
0
    if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
225
0
        (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
226
0
        (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
227
0
        (r = sshbuf_put_cstring(b, method)) != 0 ||
228
0
        (r = sshbuf_put_u8(b, have_sig)) != 0 ||
229
0
        (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
230
0
        (r = sshbuf_put_stringb(b, keyblob)) != 0)
231
0
      fatal_fr(r, "reconstruct %s packet", method);
232
0
    if (hostbound &&
233
0
        (r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0)
234
0
      fatal_fr(r, "reconstruct %s packet", method);
235
#ifdef DEBUG_PK
236
    sshbuf_dump(b, stderr);
237
#endif
238
    /* test for correct signature */
239
0
    authenticated = 0;
240
0
    if (mm_user_key_allowed(ssh, pw, key, 1, &authopts) &&
241
0
        mm_sshkey_verify(key, sig, slen,
242
0
        sshbuf_ptr(b), sshbuf_len(b),
243
0
        (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
244
0
        ssh->compat, &sig_details) == 0) {
245
0
      authenticated = 1;
246
0
    }
247
0
    if (authenticated == 1 && sig_details != NULL) {
248
0
      auth2_record_info(authctxt, "signature count = %u",
249
0
          sig_details->sk_counter);
250
0
      debug_f("sk_counter = %u, sk_flags = 0x%02x",
251
0
          sig_details->sk_counter, sig_details->sk_flags);
252
0
      req_presence = (options.pubkey_auth_options &
253
0
          PUBKEYAUTH_TOUCH_REQUIRED) ||
254
0
          !authopts->no_require_user_presence;
255
0
      if (req_presence && (sig_details->sk_flags &
256
0
          SSH_SK_USER_PRESENCE_REQD) == 0) {
257
0
        error("public key %s signature for %s%s from "
258
0
            "%.128s port %d rejected: user presence "
259
0
            "(authenticator touch) requirement "
260
0
            "not met ", key_s,
261
0
            authctxt->valid ? "" : "invalid user ",
262
0
            authctxt->user, ssh_remote_ipaddr(ssh),
263
0
            ssh_remote_port(ssh));
264
0
        authenticated = 0;
265
0
        goto done;
266
0
      }
267
0
      req_verify = (options.pubkey_auth_options &
268
0
          PUBKEYAUTH_VERIFY_REQUIRED) ||
269
0
          authopts->require_verify;
270
0
      if (req_verify && (sig_details->sk_flags &
271
0
          SSH_SK_USER_VERIFICATION_REQD) == 0) {
272
0
        error("public key %s signature for %s%s from "
273
0
            "%.128s port %d rejected: user "
274
0
            "verification requirement not met ", key_s,
275
0
            authctxt->valid ? "" : "invalid user ",
276
0
            authctxt->user, ssh_remote_ipaddr(ssh),
277
0
            ssh_remote_port(ssh));
278
0
        authenticated = 0;
279
0
        goto done;
280
0
      }
281
0
    }
282
0
    auth2_record_key(authctxt, authenticated, key);
283
0
  } else {
284
0
    debug_f("%s test pkalg %s pkblob %s%s%s", method, pkalg, key_s,
285
0
        ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
286
287
0
    if ((r = sshpkt_get_end(ssh)) != 0)
288
0
      fatal_fr(r, "parse packet");
289
290
    /* XXX fake reply and always send PK_OK ? */
291
    /*
292
     * XXX this allows testing whether a user is allowed
293
     * to login: if you happen to have a valid pubkey this
294
     * message is sent. the message is NEVER sent at all
295
     * if a user is not allowed to login. is this an
296
     * issue? -markus
297
     */
298
0
    if (authctxt->valid && authctxt->user != NULL &&
299
0
        mm_user_key_allowed(ssh, pw, key, 0, NULL)) {
300
0
      if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
301
0
          != 0 ||
302
0
          (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
303
0
          (r = sshpkt_put_stringb(ssh, keyblob)) != 0 ||
304
0
          (r = sshpkt_send(ssh)) != 0 ||
305
0
          (r = ssh_packet_write_wait(ssh)) != 0)
306
0
        fatal_fr(r, "send packet");
307
0
      authctxt->postponed = 1;
308
0
    } else {
309
      /*
310
       * NB. invalid users must be accounted for in exactly
311
       * the same way as valid users whose key was refused,
312
       * otherwise MaxAuthTries becomes a username oracle.
313
       */
314
      /*
315
       * Don't count this as an authentication failure
316
       * unless we have already used up the separate
317
       * max-pk-ok budget (if any).
318
       */
319
0
      if (authctxt->pk_ok_failures++ < options.max_pubkey_ok)
320
0
        authctxt->auth_failure_already_counted = 1;
321
0
      debug3_f("pubkey test %d of %d%s",
322
0
          authctxt->pk_ok_failures, options.max_pubkey_ok,
323
0
          authctxt->auth_failure_already_counted ?
324
0
          "" : ": treating as authentication failure");
325
0
     }
326
0
  }
327
0
done:
328
0
  if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
329
0
    debug_f("key options inconsistent with existing");
330
0
    authenticated = 0;
331
0
  }
332
0
  debug2_f("authenticated %d pkalg %s", authenticated, pkalg);
333
334
0
  sshbuf_free(b);
335
0
  sshbuf_free(keyblob);
336
0
  sshauthopt_free(authopts);
337
0
  sshkey_free(key);
338
0
  sshkey_free(hostkey);
339
0
  free(keystring);
340
0
  free(userstyle);
341
0
  free(pkalg);
342
0
  free(key_s);
343
0
  free(ca_s);
344
0
  free(sig);
345
0
  sshkey_sig_details_free(sig_details);
346
0
  return authenticated;
347
0
}
348
349
static int
350
match_principals_file(struct passwd *pw, char *file,
351
    struct sshkey_cert *cert, struct sshauthopt **authoptsp)
352
0
{
353
0
  FILE *f;
354
0
  int r, success = 0;
355
0
  size_t i;
356
0
  glob_t gl;
357
0
  struct sshauthopt *opts = NULL;
358
359
0
  if (authoptsp != NULL)
360
0
    *authoptsp = NULL;
361
362
0
  temporarily_use_uid(pw);
363
0
  r = glob(file, 0, NULL, &gl);
364
0
  restore_uid();
365
0
  if (r != 0) {
366
0
    if (r != GLOB_NOMATCH) {
367
0
      logit_f("glob \"%s\" failed", file);
368
0
    }
369
0
    return 0;
370
0
  } else if (gl.gl_pathc > INT_MAX) {
371
0
    fatal_f("too many glob results for \"%s\"", file);
372
0
  } else if (gl.gl_pathc > 1) {
373
0
    debug2_f("glob \"%s\" returned %zu matches", file,
374
0
        gl.gl_pathc);
375
0
  }
376
0
  for (i = 0; !success && i < gl.gl_pathc; i++) {
377
0
    temporarily_use_uid(pw);
378
0
    debug("trying authorized principals file %s", file);
379
0
    if ((f = auth_openprincipals(gl.gl_pathv[i], pw,
380
0
        options.strict_modes)) == NULL) {
381
0
      restore_uid();
382
0
      continue;
383
0
    }
384
0
    success = auth_process_principals(f, gl.gl_pathv[i],
385
0
        cert, &opts);
386
0
    fclose(f);
387
0
    restore_uid();
388
0
    if (!success) {
389
0
      sshauthopt_free(opts);
390
0
      opts = NULL;
391
0
    }
392
0
  }
393
0
  globfree(&gl);
394
0
  if (success && authoptsp != NULL) {
395
0
    *authoptsp = opts;
396
0
    opts = NULL;
397
0
  }
398
0
  sshauthopt_free(opts);
399
0
  return success;
400
0
}
401
402
/*
403
 * Checks whether principal is allowed in output of command.
404
 * returns 1 if the principal is allowed or 0 otherwise.
405
 */
406
static int
407
match_principals_command(struct passwd *user_pw, const struct sshkey *key,
408
    const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
409
0
{
410
0
  struct passwd *runas_pw = NULL;
411
0
  const struct sshkey_cert *cert = key->cert;
412
0
  FILE *f = NULL;
413
0
  int r, ok, found_principal = 0;
414
0
  int i, ac = 0, uid_swapped = 0;
415
0
  pid_t pid;
416
0
  char *tmp, *username = NULL, *command = NULL, **av = NULL;
417
0
  char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
418
0
  char serial_s[32], uidstr[32];
419
0
  void (*osigchld)(int);
420
421
0
  if (authoptsp != NULL)
422
0
    *authoptsp = NULL;
423
0
  if (options.authorized_principals_command == NULL)
424
0
    return 0;
425
0
  if (options.authorized_principals_command_user == NULL) {
426
0
    error("No user for AuthorizedPrincipalsCommand specified, "
427
0
        "skipping");
428
0
    return 0;
429
0
  }
430
431
  /*
432
   * NB. all returns later this function should go via "out" to
433
   * ensure the original SIGCHLD handler is restored properly.
434
   */
435
0
  osigchld = ssh_signal(SIGCHLD, SIG_DFL);
436
437
  /* Prepare and verify the user for the command */
438
0
  username = percent_expand(options.authorized_principals_command_user,
439
0
      "u", user_pw->pw_name, (char *)NULL);
440
0
  runas_pw = getpwnam(username);
441
0
  if (runas_pw == NULL) {
442
0
    error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
443
0
        username, strerror(errno));
444
0
    goto out;
445
0
  }
446
447
  /* Turn the command into an argument vector */
448
0
  if (argv_split(options.authorized_principals_command,
449
0
      &ac, &av, 0) != 0) {
450
0
    error("AuthorizedPrincipalsCommand \"%s\" contains "
451
0
        "invalid quotes", options.authorized_principals_command);
452
0
    goto out;
453
0
  }
454
0
  if (ac == 0) {
455
0
    error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
456
0
        options.authorized_principals_command);
457
0
    goto out;
458
0
  }
459
0
  if ((ca_fp = sshkey_fingerprint(cert->signature_key,
460
0
      options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
461
0
    error_f("sshkey_fingerprint failed");
462
0
    goto out;
463
0
  }
464
0
  if ((key_fp = sshkey_fingerprint(key,
465
0
      options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
466
0
    error_f("sshkey_fingerprint failed");
467
0
    goto out;
468
0
  }
469
0
  if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
470
0
    error_fr(r, "sshkey_to_base64 failed");
471
0
    goto out;
472
0
  }
473
0
  if ((r = sshkey_to_base64(key, &keytext)) != 0) {
474
0
    error_fr(r, "sshkey_to_base64 failed");
475
0
    goto out;
476
0
  }
477
0
  snprintf(serial_s, sizeof(serial_s), "%llu",
478
0
      (unsigned long long)cert->serial);
479
0
  snprintf(uidstr, sizeof(uidstr), "%llu",
480
0
      (unsigned long long)user_pw->pw_uid);
481
0
  for (i = 1; i < ac; i++) {
482
0
    tmp = percent_expand(av[i],
483
0
        "C", conn_id,
484
0
        "D", rdomain,
485
0
        "U", uidstr,
486
0
        "u", user_pw->pw_name,
487
0
        "h", user_pw->pw_dir,
488
0
        "t", sshkey_ssh_name(key),
489
0
        "T", sshkey_ssh_name(cert->signature_key),
490
0
        "f", key_fp,
491
0
        "F", ca_fp,
492
0
        "k", keytext,
493
0
        "K", catext,
494
0
        "i", cert->key_id,
495
0
        "s", serial_s,
496
0
        (char *)NULL);
497
0
    if (tmp == NULL)
498
0
      fatal_f("percent_expand failed");
499
0
    free(av[i]);
500
0
    av[i] = tmp;
501
0
  }
502
  /* Prepare a printable command for logs, etc. */
503
0
  command = argv_assemble(ac, av);
504
505
0
  if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
506
0
      ac, av, &f,
507
0
      SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
508
0
      runas_pw, temporarily_use_uid, restore_uid)) == 0)
509
0
    goto out;
510
511
0
  uid_swapped = 1;
512
0
  temporarily_use_uid(runas_pw);
513
514
0
  ok = auth_process_principals(f, "(command)", cert, authoptsp);
515
516
0
  fclose(f);
517
0
  f = NULL;
518
519
0
  if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
520
0
    goto out;
521
522
  /* Read completed successfully */
523
0
  found_principal = ok;
524
0
 out:
525
0
  if (f != NULL)
526
0
    fclose(f);
527
0
  ssh_signal(SIGCHLD, osigchld);
528
0
  for (i = 0; i < ac; i++)
529
0
    free(av[i]);
530
0
  free(av);
531
0
  if (uid_swapped)
532
0
    restore_uid();
533
0
  free(command);
534
0
  free(username);
535
0
  free(ca_fp);
536
0
  free(key_fp);
537
0
  free(catext);
538
0
  free(keytext);
539
0
  return found_principal;
540
0
}
541
542
/* Authenticate a certificate key against TrustedUserCAKeys */
543
static int
544
user_cert_trusted_ca(struct passwd *pw, struct sshkey *key,
545
    const char *remote_ip, const char *remote_host,
546
    const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
547
0
{
548
0
  char *ca_fp, *principals_file = NULL;
549
0
  const char *reason;
550
0
  struct sshauthopt *principals_opts = NULL, *cert_opts = NULL;
551
0
  struct sshauthopt *final_opts = NULL;
552
0
  int r, ret = 0, found_principal = 0, use_authorized_principals;
553
554
0
  if (authoptsp != NULL)
555
0
    *authoptsp = NULL;
556
557
0
  if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL)
558
0
    return 0;
559
560
0
  if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
561
0
      options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
562
0
    return 0;
563
564
0
  if ((r = sshkey_in_file(key->cert->signature_key,
565
0
      options.trusted_user_ca_keys, 1, 0)) != 0) {
566
0
    debug2_fr(r, "CA %s %s is not listed in %s",
567
0
        sshkey_type(key->cert->signature_key), ca_fp,
568
0
        options.trusted_user_ca_keys);
569
0
    goto out;
570
0
  }
571
  /*
572
   * If AuthorizedPrincipals is in use, then compare the certificate
573
   * principals against the names in that file rather than matching
574
   * against the username.
575
   */
576
0
  if ((principals_file = authorized_principals_file(pw)) != NULL) {
577
0
    if (match_principals_file(pw, principals_file,
578
0
        key->cert, &principals_opts))
579
0
      found_principal = 1;
580
0
  }
581
  /* Try querying command if specified */
582
0
  if (!found_principal && match_principals_command(pw, key,
583
0
      conn_id, rdomain, &principals_opts))
584
0
    found_principal = 1;
585
  /* If principals file or command is specified, then require a match */
586
0
  use_authorized_principals = principals_file != NULL ||
587
0
      options.authorized_principals_command != NULL;
588
0
  if (!found_principal && use_authorized_principals) {
589
0
    reason = "Certificate does not contain an authorized principal";
590
0
    goto fail_reason;
591
0
  }
592
0
  if (use_authorized_principals && principals_opts == NULL)
593
0
    fatal_f("internal error: missing principals_opts");
594
0
  if (sshkey_cert_check_authority_now(key, 0, 0,
595
0
      use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
596
0
    goto fail_reason;
597
598
  /* Check authority from options in key and from principals file/cmd */
599
0
  if ((cert_opts = sshauthopt_from_cert(key)) == NULL) {
600
0
    reason = "Invalid certificate options";
601
0
    goto fail_reason;
602
0
  }
603
0
  if (auth_authorise_keyopts(pw, cert_opts, 0,
604
0
      remote_ip, remote_host, "cert") != 0) {
605
0
    reason = "Refused by certificate options";
606
0
    goto fail_reason;
607
0
  }
608
0
  if (principals_opts == NULL) {
609
0
    final_opts = cert_opts;
610
0
    cert_opts = NULL;
611
0
  } else {
612
0
    if (auth_authorise_keyopts(pw, principals_opts, 0,
613
0
        remote_ip, remote_host, "principals") != 0) {
614
0
      reason = "Refused by certificate principals options";
615
0
      goto fail_reason;
616
0
    }
617
0
    if ((final_opts = sshauthopt_merge(principals_opts,
618
0
        cert_opts, &reason)) == NULL) {
619
0
 fail_reason:
620
0
      error("Refusing certificate ID \"%s\" serial=%llu "
621
0
          "signed by %s CA %s: %s", key->cert->key_id,
622
0
          (unsigned long long)key->cert->serial,
623
0
          sshkey_type(key->cert->signature_key), ca_fp,
624
0
          reason);
625
0
      auth_debug_add("Refused Certificate ID \"%s\" "
626
0
          "serial=%llu: %s", key->cert->key_id,
627
0
          (unsigned long long)key->cert->serial, reason);
628
0
      goto out;
629
0
    }
630
0
  }
631
632
  /* Success */
633
0
  verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
634
0
      "%s CA %s via %s", key->cert->key_id,
635
0
      (unsigned long long)key->cert->serial,
636
0
      sshkey_type(key->cert->signature_key), ca_fp,
637
0
      options.trusted_user_ca_keys);
638
0
  if (authoptsp != NULL) {
639
0
    *authoptsp = final_opts;
640
0
    final_opts = NULL;
641
0
  }
642
0
  ret = 1;
643
0
 out:
644
0
  sshauthopt_free(principals_opts);
645
0
  sshauthopt_free(cert_opts);
646
0
  sshauthopt_free(final_opts);
647
0
  free(principals_file);
648
0
  free(ca_fp);
649
0
  return ret;
650
0
}
651
652
/*
653
 * Checks whether key is allowed in file.
654
 * returns 1 if the key is allowed or 0 otherwise.
655
 */
656
static int
657
user_key_allowed2(struct passwd *pw, struct sshkey *key,
658
    char *file, const char *remote_ip, const char *remote_host,
659
    struct sshauthopt **authoptsp)
660
0
{
661
0
  FILE *f;
662
0
  int found_key = 0;
663
664
0
  if (authoptsp != NULL)
665
0
    *authoptsp = NULL;
666
667
  /* Temporarily use the user's uid. */
668
0
  temporarily_use_uid(pw);
669
670
0
  debug("trying public key file %s", file);
671
0
  if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
672
0
    found_key = auth_check_authkeys_file(pw, f, file,
673
0
        key, remote_ip, remote_host, authoptsp);
674
0
    fclose(f);
675
0
  }
676
677
0
  restore_uid();
678
0
  return found_key;
679
0
}
680
681
/*
682
 * Checks whether key is allowed in output of command.
683
 * returns 1 if the key is allowed or 0 otherwise.
684
 */
685
static int
686
user_key_command_allowed2(struct passwd *user_pw, struct sshkey *key,
687
    const char *remote_ip, const char *remote_host,
688
    const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
689
0
{
690
0
  struct passwd *runas_pw = NULL;
691
0
  FILE *f = NULL;
692
0
  int r, ok, found_key = 0;
693
0
  int i, uid_swapped = 0, ac = 0;
694
0
  pid_t pid;
695
0
  char *username = NULL, *key_fp = NULL, *keytext = NULL;
696
0
  char uidstr[32], *tmp, *command = NULL, **av = NULL;
697
0
  void (*osigchld)(int);
698
699
0
  if (authoptsp != NULL)
700
0
    *authoptsp = NULL;
701
0
  if (options.authorized_keys_command == NULL)
702
0
    return 0;
703
0
  if (options.authorized_keys_command_user == NULL) {
704
0
    error("No user for AuthorizedKeysCommand specified, skipping");
705
0
    return 0;
706
0
  }
707
708
  /*
709
   * NB. all returns later this function should go via "out" to
710
   * ensure the original SIGCHLD handler is restored properly.
711
   */
712
0
  osigchld = ssh_signal(SIGCHLD, SIG_DFL);
713
714
  /* Prepare and verify the user for the command */
715
0
  username = percent_expand(options.authorized_keys_command_user,
716
0
      "u", user_pw->pw_name, (char *)NULL);
717
0
  runas_pw = getpwnam(username);
718
0
  if (runas_pw == NULL) {
719
0
    error("AuthorizedKeysCommandUser \"%s\" not found: %s",
720
0
        username, strerror(errno));
721
0
    goto out;
722
0
  }
723
724
  /* Prepare AuthorizedKeysCommand */
725
0
  if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
726
0
      SSH_FP_DEFAULT)) == NULL) {
727
0
    error_f("sshkey_fingerprint failed");
728
0
    goto out;
729
0
  }
730
0
  if ((r = sshkey_to_base64(key, &keytext)) != 0) {
731
0
    error_fr(r, "sshkey_to_base64 failed");
732
0
    goto out;
733
0
  }
734
735
  /* Turn the command into an argument vector */
736
0
  if (argv_split(options.authorized_keys_command, &ac, &av, 0) != 0) {
737
0
    error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
738
0
        options.authorized_keys_command);
739
0
    goto out;
740
0
  }
741
0
  if (ac == 0) {
742
0
    error("AuthorizedKeysCommand \"%s\" yielded no arguments",
743
0
        options.authorized_keys_command);
744
0
    goto out;
745
0
  }
746
0
  snprintf(uidstr, sizeof(uidstr), "%llu",
747
0
      (unsigned long long)user_pw->pw_uid);
748
0
  for (i = 1; i < ac; i++) {
749
0
    tmp = percent_expand(av[i],
750
0
        "C", conn_id,
751
0
        "D", rdomain,
752
0
        "U", uidstr,
753
0
        "u", user_pw->pw_name,
754
0
        "h", user_pw->pw_dir,
755
0
        "t", sshkey_ssh_name(key),
756
0
        "f", key_fp,
757
0
        "k", keytext,
758
0
        (char *)NULL);
759
0
    if (tmp == NULL)
760
0
      fatal_f("percent_expand failed");
761
0
    free(av[i]);
762
0
    av[i] = tmp;
763
0
  }
764
  /* Prepare a printable command for logs, etc. */
765
0
  command = argv_assemble(ac, av);
766
767
  /*
768
   * If AuthorizedKeysCommand was run without arguments
769
   * then fall back to the old behaviour of passing the
770
   * target username as a single argument.
771
   */
772
0
  if (ac == 1) {
773
0
    av = xreallocarray(av, ac + 2, sizeof(*av));
774
0
    av[1] = xstrdup(user_pw->pw_name);
775
0
    av[2] = NULL;
776
    /* Fix up command too, since it is used in log messages */
777
0
    free(command);
778
0
    xasprintf(&command, "%s %s", av[0], av[1]);
779
0
  }
780
781
0
  if ((pid = subprocess("AuthorizedKeysCommand", command,
782
0
      ac, av, &f,
783
0
      SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
784
0
      runas_pw, temporarily_use_uid, restore_uid)) == 0)
785
0
    goto out;
786
787
0
  uid_swapped = 1;
788
0
  temporarily_use_uid(runas_pw);
789
790
0
  ok = auth_check_authkeys_file(user_pw, f,
791
0
      options.authorized_keys_command, key, remote_ip,
792
0
      remote_host, authoptsp);
793
794
0
  fclose(f);
795
0
  f = NULL;
796
797
0
  if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
798
0
    goto out;
799
800
  /* Read completed successfully */
801
0
  found_key = ok;
802
0
 out:
803
0
  if (f != NULL)
804
0
    fclose(f);
805
0
  ssh_signal(SIGCHLD, osigchld);
806
0
  for (i = 0; i < ac; i++)
807
0
    free(av[i]);
808
0
  free(av);
809
0
  if (uid_swapped)
810
0
    restore_uid();
811
0
  free(command);
812
0
  free(username);
813
0
  free(key_fp);
814
0
  free(keytext);
815
0
  return found_key;
816
0
}
817
818
/*
819
 * Check whether key authenticates and authorises the user.
820
 */
821
int
822
user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
823
    int auth_attempt, struct sshauthopt **authoptsp)
824
0
{
825
0
  u_int success = 0, i, j;
826
0
  char *file = NULL, *conn_id;
827
0
  struct sshauthopt *opts = NULL;
828
0
  const char *rdomain, *remote_ip, *remote_host;
829
830
0
  if (authoptsp != NULL)
831
0
    *authoptsp = NULL;
832
833
0
  if (auth_key_is_revoked(key))
834
0
    return 0;
835
0
  if (sshkey_is_cert(key) &&
836
0
      auth_key_is_revoked(key->cert->signature_key))
837
0
    return 0;
838
839
0
  if ((rdomain = ssh_packet_rdomain_in(ssh)) == NULL)
840
0
    rdomain = "";
841
0
  remote_ip = ssh_remote_ipaddr(ssh);
842
0
  remote_host = auth_get_canonical_hostname(ssh, options.use_dns);
843
0
  xasprintf(&conn_id, "%s %d %s %d",
844
0
      ssh_local_ipaddr(ssh), ssh_local_port(ssh),
845
0
      remote_ip, ssh_remote_port(ssh));
846
847
0
  for (i = 0; !success && i < options.num_authkeys_files; i++) {
848
0
    int r;
849
0
    glob_t gl;
850
851
0
    if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
852
0
      continue;
853
0
    file = expand_authorized_keys(
854
0
        options.authorized_keys_files[i], pw);
855
0
    temporarily_use_uid(pw);
856
0
    r = glob(file, 0, NULL, &gl);
857
0
    restore_uid();
858
0
    if (r != 0) {
859
0
      if (r != GLOB_NOMATCH) {
860
0
        logit_f("glob \"%s\" failed", file);
861
0
      }
862
0
      free(file);
863
0
      file = NULL;
864
0
      continue;
865
0
    } else if (gl.gl_pathc > INT_MAX) {
866
0
      fatal_f("too many glob results for \"%s\"", file);
867
0
    } else if (gl.gl_pathc > 1) {
868
0
      debug2_f("glob \"%s\" returned %zu matches", file,
869
0
          gl.gl_pathc);
870
0
    }
871
0
    for (j = 0; !success && j < gl.gl_pathc; j++) {
872
0
      success = user_key_allowed2(pw, key, gl.gl_pathv[j],
873
0
          remote_ip, remote_host, &opts);
874
0
      if (!success) {
875
0
        sshauthopt_free(opts);
876
0
        opts = NULL;
877
0
      }
878
0
    }
879
0
    free(file);
880
0
    file = NULL;
881
0
    globfree(&gl);
882
0
  }
883
0
  if (success)
884
0
    goto out;
885
886
0
  if ((success = user_cert_trusted_ca(pw, key, remote_ip, remote_host,
887
0
      conn_id, rdomain, &opts)) != 0)
888
0
    goto out;
889
0
  sshauthopt_free(opts);
890
0
  opts = NULL;
891
892
0
  if ((success = user_key_command_allowed2(pw, key, remote_ip,
893
0
      remote_host, conn_id, rdomain, &opts)) != 0)
894
0
    goto out;
895
0
  sshauthopt_free(opts);
896
0
  opts = NULL;
897
898
0
 out:
899
0
  free(conn_id);
900
0
  if (success && authoptsp != NULL) {
901
0
    *authoptsp = opts;
902
    opts = NULL;
903
0
  }
904
0
  sshauthopt_free(opts);
905
0
  return success;
906
0
}
907
908
Authmethod method_pubkey = {
909
  &methodcfg_pubkey,
910
  userauth_pubkey,
911
};