1 /* $OpenBSD: sshconnect2.c,v 1.171 2009/03/05 07:18:19 djm Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2008 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 <sys/types.h>
28 #include <sys/socket.h>
29 #include <sys/wait.h>
30 #include <sys/queue.h>
31 #include <sys/stat.h>
32
33 #include <errno.h>
34 #include <netdb.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <signal.h>
38 #include <pwd.h>
39 #include <unistd.h>
40 #include <vis.h>
41
42 #include "xmalloc.h"
43 #include "ssh.h"
44 #include "ssh2.h"
45 #include "buffer.h"
46 #include "packet.h"
47 #include "compat.h"
48 #include "cipher.h"
49 #include "key.h"
50 #include "kex.h"
51 #include "myproposal.h"
52 #include "sshconnect.h"
53 #include "authfile.h"
54 #include "dh.h"
55 #include "authfd.h"
56 #include "log.h"
57 #include "readconf.h"
58 #include "misc.h"
59 #include "match.h"
60 #include "dispatch.h"
61 #include "canohost.h"
62 #include "msg.h"
63 #include "pathnames.h"
64 #include "uidswap.h"
65
66 __RCSID("$MirOS: src/usr.bin/ssh/sshconnect2.c,v 1.17 2014/03/28 22:31:58 tg Exp $");
67
68 /* for now */
69 extern const EVP_MD *evp_ssh_sha256(void);
70 #define EVP_sha256 evp_ssh_sha256
71
72 /* import */
73 extern char *client_version_string;
74 extern char *server_version_string;
75 extern Options options;
76
77 /*
78 * SSH2 key exchange
79 */
80
81 u_char *session_id2 = NULL;
82 u_int session_id2_len = 0;
83
84 char *xxx_host;
85 struct sockaddr *xxx_hostaddr;
86
87 Kex *xxx_kex = NULL;
88
89 static int
verify_host_key_callback(Key * hostkey)90 verify_host_key_callback(Key *hostkey)
91 {
92 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
93 fatal("Host key verification failed.");
94 return 0;
95 }
96
97 void
ssh_kex2(char * host,struct sockaddr * hostaddr)98 ssh_kex2(char *host, struct sockaddr *hostaddr)
99 {
100 Kex *kex;
101
102 xxx_host = host;
103 xxx_hostaddr = hostaddr;
104
105 if (options.ciphers == (char *)-1) {
106 logit("No valid ciphers for protocol version 2 given, using defaults.");
107 options.ciphers = NULL;
108 }
109 if (options.ciphers != NULL) {
110 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
111 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
112 }
113 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
114 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
115 myproposal[PROPOSAL_ENC_ALGS_STOC] =
116 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
117 if (options.compression) {
118 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
119 myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib@openssh.com,zlib,none";
120 } else {
121 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
122 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com,zlib";
123 }
124 if (options.macs != NULL) {
125 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
126 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
127 }
128 if (options.hostkeyalgorithms != NULL)
129 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
130 options.hostkeyalgorithms;
131
132 if (options.rekey_limit)
133 packet_set_rekey_limit((u_int32_t)options.rekey_limit);
134
135 /* start key exchange */
136 kex = kex_setup(myproposal);
137 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
138 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
139 kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
140 kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
141 kex->client_version_string=client_version_string;
142 kex->server_version_string=server_version_string;
143 kex->verify_host_key=&verify_host_key_callback;
144
145 xxx_kex = kex;
146
147 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
148
149 session_id2 = kex->session_id;
150 session_id2_len = kex->session_id_len;
151
152 #ifdef DEBUG_KEXDH
153 /* send 1st encrypted/maced/compressed message */
154 packet_start(SSH2_MSG_IGNORE);
155 packet_put_cstring("markus");
156 packet_send();
157 packet_write_wait();
158 #endif
159 }
160
161 /*
162 * Authenticate user
163 */
164
165 typedef struct Authctxt Authctxt;
166 typedef struct Authmethod Authmethod;
167 typedef struct identity Identity;
168 typedef struct idlist Idlist;
169
170 struct identity {
171 TAILQ_ENTRY(identity) next;
172 AuthenticationConnection *ac; /* set if agent supports key */
173 Key *key; /* public/private key */
174 char *filename; /* comment for agent-only keys */
175 int tried;
176 int isprivate; /* key points to the private key */
177 };
178 TAILQ_HEAD(idlist, identity);
179
180 struct Authctxt {
181 const char *server_user;
182 const char *local_user;
183 const char *host;
184 const char *service;
185 Authmethod *method;
186 int success;
187 char *authlist;
188 /* pubkey */
189 Idlist keys;
190 AuthenticationConnection *agent;
191 /* hostbased */
192 Sensitive *sensitive;
193 /* kbd-interactive */
194 int info_req_seen;
195 /* generic */
196 void *methoddata;
197 };
198 struct Authmethod {
199 const char *name; /* string to compare against server's list */
200 int (*userauth)(Authctxt *authctxt);
201 void (*cleanup)(Authctxt *authctxt);
202 int *enabled; /* flag in option struct that enables method */
203 int *batch_flag; /* flag in option struct that disables method */
204 };
205
206 void input_userauth_success(int, u_int32_t, void *);
207 void input_userauth_failure(int, u_int32_t, void *);
208 void input_userauth_banner(int, u_int32_t, void *);
209 void input_userauth_error(int, u_int32_t, void *) __dead;
210 void input_userauth_info_req(int, u_int32_t, void *);
211 void input_userauth_pk_ok(int, u_int32_t, void *);
212 void input_userauth_passwd_changereq(int, u_int32_t, void *);
213
214 int userauth_none(Authctxt *);
215 int userauth_pubkey(Authctxt *);
216 int userauth_passwd(Authctxt *);
217 int userauth_kbdint(Authctxt *);
218 int userauth_hostbased(Authctxt *);
219
220 void userauth(Authctxt *, char *);
221
222 static int sign_and_send_pubkey(Authctxt *, Identity *);
223 static void pubkey_prepare(Authctxt *);
224 static void pubkey_cleanup(Authctxt *);
225 static Key *load_identity_file(char *);
226
227 static Authmethod *authmethod_get(char *authlist);
228 static Authmethod *authmethod_lookup(const char *name);
229 static char *authmethods_get(void);
230
231 Authmethod authmethods[] = {
232 {"hostbased",
233 userauth_hostbased,
234 NULL,
235 &options.hostbased_authentication,
236 NULL},
237 {"publickey",
238 userauth_pubkey,
239 NULL,
240 &options.pubkey_authentication,
241 NULL},
242 {"keyboard-interactive",
243 userauth_kbdint,
244 NULL,
245 &options.kbd_interactive_authentication,
246 &options.batch_mode},
247 {"password",
248 userauth_passwd,
249 NULL,
250 &options.password_authentication,
251 &options.batch_mode},
252 {"none",
253 userauth_none,
254 NULL,
255 NULL,
256 NULL},
257 {NULL, NULL, NULL, NULL, NULL}
258 };
259
260 void
ssh_userauth2(const char * local_user,const char * server_user,char * host,Sensitive * sensitive)261 ssh_userauth2(const char *local_user, const char *server_user, char *host,
262 Sensitive *sensitive)
263 {
264 Authctxt authctxt;
265 int type;
266
267 if (options.challenge_response_authentication)
268 options.kbd_interactive_authentication = 1;
269
270 packet_start(SSH2_MSG_SERVICE_REQUEST);
271 packet_put_cstring("ssh-userauth");
272 packet_send();
273 debug("SSH2_MSG_SERVICE_REQUEST sent");
274 packet_write_wait();
275 type = packet_read();
276 if (type != SSH2_MSG_SERVICE_ACCEPT)
277 fatal("Server denied authentication request: %d", type);
278 if (packet_remaining() > 0) {
279 char *reply = packet_get_string(NULL);
280 debug2("service_accept: %s", reply);
281 xfree(reply);
282 } else {
283 debug2("buggy server: service_accept w/o service");
284 }
285 packet_check_eom();
286 debug("SSH2_MSG_SERVICE_ACCEPT received");
287
288 if (options.preferred_authentications == NULL)
289 options.preferred_authentications = authmethods_get();
290
291 /* setup authentication context */
292 memset(&authctxt, 0, sizeof(authctxt));
293 pubkey_prepare(&authctxt);
294 authctxt.server_user = server_user;
295 authctxt.local_user = local_user;
296 authctxt.host = host;
297 authctxt.service = "ssh-connection"; /* service name */
298 authctxt.success = 0;
299 authctxt.method = authmethod_lookup("none");
300 authctxt.authlist = NULL;
301 authctxt.methoddata = NULL;
302 authctxt.sensitive = sensitive;
303 authctxt.info_req_seen = 0;
304 if (authctxt.method == NULL)
305 fatal("ssh_userauth2: internal error: cannot send userauth none request");
306
307 /* initial userauth request */
308 userauth_none(&authctxt);
309
310 dispatch_init(&input_userauth_error);
311 dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
312 dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
313 dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
314 dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt); /* loop until success */
315
316 pubkey_cleanup(&authctxt);
317 dispatch_range(SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
318
319 debug("Authentication succeeded (%s).", authctxt.method->name);
320 }
321
322 void
userauth(Authctxt * authctxt,char * authlist)323 userauth(Authctxt *authctxt, char *authlist)
324 {
325 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
326 authctxt->method->cleanup(authctxt);
327
328 if (authctxt->methoddata) {
329 xfree(authctxt->methoddata);
330 authctxt->methoddata = NULL;
331 }
332 if (authlist == NULL) {
333 authlist = authctxt->authlist;
334 } else {
335 if (authctxt->authlist)
336 xfree(authctxt->authlist);
337 authctxt->authlist = authlist;
338 }
339 for (;;) {
340 Authmethod *method = authmethod_get(authlist);
341 if (method == NULL)
342 fatal("Permission denied (%s).", authlist);
343 authctxt->method = method;
344
345 /* reset the per method handler */
346 dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
347 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
348
349 /* and try new method */
350 if (method->userauth(authctxt) != 0) {
351 debug2("we sent a %s packet, wait for reply", method->name);
352 break;
353 } else {
354 debug2("we did not send a packet, disable method");
355 method->enabled = NULL;
356 }
357 }
358 }
359
360 /* ARGSUSED */
361 void
input_userauth_error(int type,u_int32_t seq,void * ctxt)362 input_userauth_error(int type, u_int32_t seq, void *ctxt)
363 {
364 fatal("input_userauth_error: bad message during authentication: "
365 "type %d", type);
366 }
367
368 /* ARGSUSED */
369 void
input_userauth_banner(int type,u_int32_t seq,void * ctxt)370 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
371 {
372 char *msg, *raw, *lang;
373 u_int len;
374
375 debug3("input_userauth_banner");
376 raw = packet_get_string(&len);
377 lang = packet_get_string(NULL);
378 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) {
379 if (len > 65536)
380 len = 65536;
381 msg = xmalloc(len * 4 + 1); /* max expansion from strnvis() */
382 strnvis(msg, raw, len * 4 + 1, VIS_SAFE|VIS_OCTAL);
383 fprintf(stderr, "%s", msg);
384 xfree(msg);
385 }
386 xfree(raw);
387 xfree(lang);
388 }
389
390 /* ARGSUSED */
391 void
input_userauth_success(int type,u_int32_t seq,void * ctxt)392 input_userauth_success(int type, u_int32_t seq, void *ctxt)
393 {
394 Authctxt *authctxt = ctxt;
395 if (authctxt == NULL)
396 fatal("input_userauth_success: no authentication context");
397 if (authctxt->authlist) {
398 xfree(authctxt->authlist);
399 authctxt->authlist = NULL;
400 }
401 if (authctxt->methoddata) {
402 xfree(authctxt->methoddata);
403 authctxt->methoddata = NULL;
404 }
405 authctxt->success = 1; /* break out */
406 }
407
408 /* ARGSUSED */
409 void
input_userauth_failure(int type,u_int32_t seq,void * ctxt)410 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
411 {
412 Authctxt *authctxt = ctxt;
413 char *authlist = NULL;
414 int partial;
415
416 if (authctxt == NULL)
417 fatal("input_userauth_failure: no authentication context");
418
419 authlist = packet_get_string(NULL);
420 partial = packet_get_char();
421 packet_check_eom();
422
423 if (partial != 0)
424 logit("Authenticated with partial success.");
425 debug("Authentications that can continue: %s", authlist);
426
427 userauth(authctxt, authlist);
428 }
429
430 /* ARGSUSED */
431 void
input_userauth_pk_ok(int type,u_int32_t seq,void * ctxt)432 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
433 {
434 Authctxt *authctxt = ctxt;
435 Key *key = NULL;
436 Identity *id = NULL;
437 Buffer b;
438 int pktype, sent = 0;
439 u_int alen, blen;
440 char *pkalg, *fp;
441 u_char *pkblob;
442
443 if (authctxt == NULL)
444 fatal("input_userauth_pk_ok: no authentication context");
445 if (datafellows & SSH_BUG_PKOK) {
446 /* this is similar to SSH_BUG_PKAUTH */
447 debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
448 pkblob = packet_get_string(&blen);
449 buffer_init(&b);
450 buffer_append(&b, pkblob, blen);
451 pkalg = buffer_get_string(&b, &alen);
452 buffer_free(&b);
453 } else {
454 pkalg = packet_get_string(&alen);
455 pkblob = packet_get_string(&blen);
456 }
457 packet_check_eom();
458
459 debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
460
461 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
462 debug("unknown pkalg %s", pkalg);
463 goto done;
464 }
465 if ((key = key_from_blob(pkblob, blen)) == NULL) {
466 debug("no key from blob. pkalg %s", pkalg);
467 goto done;
468 }
469 if (key->type != pktype) {
470 error("input_userauth_pk_ok: type mismatch "
471 "for decoded key (received %d, expected %d)",
472 key->type, pktype);
473 goto done;
474 }
475 fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
476 debug2("input_userauth_pk_ok: fp %s", fp);
477 xfree(fp);
478
479 /*
480 * search keys in the reverse order, because last candidate has been
481 * moved to the end of the queue. this also avoids confusion by
482 * duplicate keys
483 */
484 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
485 if (key_equal(key, id->key)) {
486 sent = sign_and_send_pubkey(authctxt, id);
487 break;
488 }
489 }
490 done:
491 if (key != NULL)
492 key_free(key);
493 xfree(pkalg);
494 xfree(pkblob);
495
496 /* try another method if we did not send a packet */
497 if (sent == 0)
498 userauth(authctxt, NULL);
499 }
500
501 int
userauth_none(Authctxt * authctxt)502 userauth_none(Authctxt *authctxt)
503 {
504 /* initial userauth request */
505 packet_start(SSH2_MSG_USERAUTH_REQUEST);
506 packet_put_cstring(authctxt->server_user);
507 packet_put_cstring(authctxt->service);
508 packet_put_cstring(authctxt->method->name);
509 packet_send();
510 return 1;
511 }
512
513 int
userauth_passwd(Authctxt * authctxt)514 userauth_passwd(Authctxt *authctxt)
515 {
516 static int attempt = 0;
517 char prompt[150];
518 char *password;
519
520 if (attempt++ >= options.number_of_password_prompts)
521 return 0;
522
523 if (attempt != 1)
524 error("Permission denied, please try again.");
525
526 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
527 authctxt->server_user, authctxt->host);
528 password = read_passphrase(prompt, 0);
529 packet_start(SSH2_MSG_USERAUTH_REQUEST);
530 packet_put_cstring(authctxt->server_user);
531 packet_put_cstring(authctxt->service);
532 packet_put_cstring(authctxt->method->name);
533 packet_put_char(0);
534 packet_put_cstring(password);
535 memset(password, 0, strlen(password));
536 xfree(password);
537 packet_add_padding(64);
538 packet_send();
539
540 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
541 &input_userauth_passwd_changereq);
542
543 return 1;
544 }
545
546 /*
547 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
548 */
549 /* ARGSUSED */
550 void
input_userauth_passwd_changereq(int type,u_int32_t seqnr,void * ctxt)551 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
552 {
553 Authctxt *authctxt = ctxt;
554 char *info, *lang, *password = NULL, *retype = NULL;
555 char prompt[150];
556
557 debug2("input_userauth_passwd_changereq");
558
559 if (authctxt == NULL)
560 fatal("input_userauth_passwd_changereq: "
561 "no authentication context");
562
563 info = packet_get_string(NULL);
564 lang = packet_get_string(NULL);
565 if (strlen(info) > 0)
566 logit("%s", info);
567 xfree(info);
568 xfree(lang);
569 packet_start(SSH2_MSG_USERAUTH_REQUEST);
570 packet_put_cstring(authctxt->server_user);
571 packet_put_cstring(authctxt->service);
572 packet_put_cstring(authctxt->method->name);
573 packet_put_char(1); /* additional info */
574 snprintf(prompt, sizeof(prompt),
575 "Enter %.30s@%.128s's old password: ",
576 authctxt->server_user, authctxt->host);
577 password = read_passphrase(prompt, 0);
578 packet_put_cstring(password);
579 memset(password, 0, strlen(password));
580 xfree(password);
581 password = NULL;
582 while (password == NULL) {
583 snprintf(prompt, sizeof(prompt),
584 "Enter %.30s@%.128s's new password: ",
585 authctxt->server_user, authctxt->host);
586 password = read_passphrase(prompt, RP_ALLOW_EOF);
587 if (password == NULL) {
588 /* bail out */
589 return;
590 }
591 snprintf(prompt, sizeof(prompt),
592 "Retype %.30s@%.128s's new password: ",
593 authctxt->server_user, authctxt->host);
594 retype = read_passphrase(prompt, 0);
595 if (strcmp(password, retype) != 0) {
596 memset(password, 0, strlen(password));
597 xfree(password);
598 logit("Mismatch; try again, EOF to quit.");
599 password = NULL;
600 }
601 memset(retype, 0, strlen(retype));
602 xfree(retype);
603 }
604 packet_put_cstring(password);
605 memset(password, 0, strlen(password));
606 xfree(password);
607 packet_add_padding(64);
608 packet_send();
609
610 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
611 &input_userauth_passwd_changereq);
612 }
613
614 static int
identity_sign(Identity * id,u_char ** sigp,u_int * lenp,u_char * data,u_int datalen)615 identity_sign(Identity *id, u_char **sigp, u_int *lenp,
616 u_char *data, u_int datalen)
617 {
618 Key *prv;
619 int ret;
620
621 /* the agent supports this key */
622 if (id->ac)
623 return (ssh_agent_sign(id->ac, id->key, sigp, lenp,
624 data, datalen));
625 /*
626 * we have already loaded the private key or
627 * the private key is stored in external hardware
628 */
629 if (id->isprivate || (id->key->flags & KEY_FLAG_EXT))
630 return (key_sign(id->key, sigp, lenp, data, datalen));
631 /* load the private key from the file */
632 if ((prv = load_identity_file(id->filename)) == NULL)
633 return (-1);
634 ret = key_sign(prv, sigp, lenp, data, datalen);
635 key_free(prv);
636 return (ret);
637 }
638
639 static int
sign_and_send_pubkey(Authctxt * authctxt,Identity * id)640 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
641 {
642 Buffer b;
643 u_char *blob, *signature;
644 u_int bloblen, slen;
645 u_int skip = 0;
646 int ret = -1;
647 int have_sig = 1;
648
649 debug3("sign_and_send_pubkey");
650
651 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
652 /* we cannot handle this key */
653 debug3("sign_and_send_pubkey: cannot handle key");
654 return 0;
655 }
656 /* data to be signed */
657 buffer_init(&b);
658 if (datafellows & SSH_OLD_SESSIONID) {
659 buffer_append(&b, session_id2, session_id2_len);
660 skip = session_id2_len;
661 } else {
662 buffer_put_string(&b, session_id2, session_id2_len);
663 skip = buffer_len(&b);
664 }
665 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
666 buffer_put_cstring(&b, authctxt->server_user);
667 buffer_put_cstring(&b,
668 datafellows & SSH_BUG_PKSERVICE ?
669 "ssh-userauth" :
670 authctxt->service);
671 if (datafellows & SSH_BUG_PKAUTH) {
672 buffer_put_char(&b, have_sig);
673 } else {
674 buffer_put_cstring(&b, authctxt->method->name);
675 buffer_put_char(&b, have_sig);
676 buffer_put_cstring(&b, key_ssh_name(id->key));
677 }
678 buffer_put_string(&b, blob, bloblen);
679
680 /* generate signature */
681 ret = identity_sign(id, &signature, &slen,
682 buffer_ptr(&b), buffer_len(&b));
683 if (ret == -1) {
684 xfree(blob);
685 buffer_free(&b);
686 return 0;
687 }
688 #ifdef DEBUG_PK
689 buffer_dump(&b);
690 #endif
691 if (datafellows & SSH_BUG_PKSERVICE) {
692 buffer_clear(&b);
693 buffer_append(&b, session_id2, session_id2_len);
694 skip = session_id2_len;
695 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
696 buffer_put_cstring(&b, authctxt->server_user);
697 buffer_put_cstring(&b, authctxt->service);
698 buffer_put_cstring(&b, authctxt->method->name);
699 buffer_put_char(&b, have_sig);
700 if (!(datafellows & SSH_BUG_PKAUTH))
701 buffer_put_cstring(&b, key_ssh_name(id->key));
702 buffer_put_string(&b, blob, bloblen);
703 }
704 xfree(blob);
705
706 /* append signature */
707 buffer_put_string(&b, signature, slen);
708 xfree(signature);
709
710 /* skip session id and packet type */
711 if (buffer_len(&b) < skip + 1)
712 fatal("userauth_pubkey: internal error");
713 buffer_consume(&b, skip + 1);
714
715 /* put remaining data from buffer into packet */
716 packet_start(SSH2_MSG_USERAUTH_REQUEST);
717 packet_put_raw(buffer_ptr(&b), buffer_len(&b));
718 buffer_free(&b);
719 packet_send();
720
721 return 1;
722 }
723
724 static int
send_pubkey_test(Authctxt * authctxt,Identity * id)725 send_pubkey_test(Authctxt *authctxt, Identity *id)
726 {
727 u_char *blob;
728 u_int bloblen, have_sig = 0;
729
730 debug3("send_pubkey_test");
731
732 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
733 /* we cannot handle this key */
734 debug3("send_pubkey_test: cannot handle key");
735 return 0;
736 }
737 /* register callback for USERAUTH_PK_OK message */
738 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
739
740 packet_start(SSH2_MSG_USERAUTH_REQUEST);
741 packet_put_cstring(authctxt->server_user);
742 packet_put_cstring(authctxt->service);
743 packet_put_cstring(authctxt->method->name);
744 packet_put_char(have_sig);
745 if (!(datafellows & SSH_BUG_PKAUTH))
746 packet_put_cstring(key_ssh_name(id->key));
747 packet_put_string(blob, bloblen);
748 xfree(blob);
749 packet_send();
750 return 1;
751 }
752
753 static Key *
load_identity_file(char * filename)754 load_identity_file(char *filename)
755 {
756 Key *private;
757 char prompt[300], *passphrase;
758 int perm_ok, quit, i;
759 struct stat st;
760
761 if (stat(filename, &st) < 0) {
762 debug3("no such identity: %s", filename);
763 return NULL;
764 }
765 private = key_load_private_type(KEY_UNSPEC, filename, "", NULL, &perm_ok);
766 if (!perm_ok)
767 return NULL;
768 if (private == NULL) {
769 if (options.batch_mode)
770 return NULL;
771 snprintf(prompt, sizeof prompt,
772 "Enter passphrase for key '%.100s': ", filename);
773 for (i = 0; i < options.number_of_password_prompts; i++) {
774 passphrase = read_passphrase(prompt, 0);
775 if (strcmp(passphrase, "") != 0) {
776 private = key_load_private_type(KEY_UNSPEC,
777 filename, passphrase, NULL, NULL);
778 quit = 0;
779 } else {
780 debug2("no passphrase given, try next key");
781 quit = 1;
782 }
783 memset(passphrase, 0, strlen(passphrase));
784 xfree(passphrase);
785 if (private != NULL || quit)
786 break;
787 debug2("bad passphrase given, try again...");
788 }
789 }
790 return private;
791 }
792
793 /*
794 * try keys in the following order:
795 * 1. agent keys that are found in the config file
796 * 2. other agent keys
797 * 3. keys that are only listed in the config file
798 */
799 static void
pubkey_prepare(Authctxt * authctxt)800 pubkey_prepare(Authctxt *authctxt)
801 {
802 Identity *id;
803 Idlist agent, files, *preferred;
804 Key *key;
805 AuthenticationConnection *ac;
806 char *comment;
807 int i, found;
808
809 TAILQ_INIT(&agent); /* keys from the agent */
810 TAILQ_INIT(&files); /* keys from the config file */
811 preferred = &authctxt->keys;
812 TAILQ_INIT(preferred); /* preferred order of keys */
813
814 /* list of keys stored in the filesystem */
815 for (i = 0; i < options.num_identity_files; i++) {
816 key = options.identity_keys[i];
817 if (key && key->type == KEY_RSA1)
818 continue;
819 options.identity_keys[i] = NULL;
820 id = xcalloc(1, sizeof(*id));
821 id->key = key;
822 id->filename = xstrdup(options.identity_files[i]);
823 TAILQ_INSERT_TAIL(&files, id, next);
824 }
825 /* list of keys supported by the agent */
826 if ((ac = ssh_get_authentication_connection())) {
827 for (key = ssh_get_first_identity(ac, &comment, 2);
828 key != NULL;
829 key = ssh_get_next_identity(ac, &comment, 2)) {
830 found = 0;
831 TAILQ_FOREACH(id, &files, next) {
832 /* agent keys from the config file are preferred */
833 if (key_equal(key, id->key)) {
834 key_free(key);
835 xfree(comment);
836 TAILQ_REMOVE(&files, id, next);
837 TAILQ_INSERT_TAIL(preferred, id, next);
838 id->ac = ac;
839 found = 1;
840 break;
841 }
842 }
843 if (!found && !options.identities_only) {
844 id = xcalloc(1, sizeof(*id));
845 id->key = key;
846 id->filename = comment;
847 id->ac = ac;
848 TAILQ_INSERT_TAIL(&agent, id, next);
849 }
850 }
851 /* append remaining agent keys */
852 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
853 TAILQ_REMOVE(&agent, id, next);
854 TAILQ_INSERT_TAIL(preferred, id, next);
855 }
856 authctxt->agent = ac;
857 }
858 /* append remaining keys from the config file */
859 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
860 TAILQ_REMOVE(&files, id, next);
861 TAILQ_INSERT_TAIL(preferred, id, next);
862 }
863 TAILQ_FOREACH(id, preferred, next) {
864 debug2("key: %s (%p)", id->filename, id->key);
865 }
866 }
867
868 static void
pubkey_cleanup(Authctxt * authctxt)869 pubkey_cleanup(Authctxt *authctxt)
870 {
871 Identity *id;
872
873 if (authctxt->agent != NULL)
874 ssh_close_authentication_connection(authctxt->agent);
875 for (id = TAILQ_FIRST(&authctxt->keys); id;
876 id = TAILQ_FIRST(&authctxt->keys)) {
877 TAILQ_REMOVE(&authctxt->keys, id, next);
878 if (id->key)
879 key_free(id->key);
880 if (id->filename)
881 xfree(id->filename);
882 xfree(id);
883 }
884 }
885
886 int
userauth_pubkey(Authctxt * authctxt)887 userauth_pubkey(Authctxt *authctxt)
888 {
889 Identity *id;
890 int sent = 0;
891
892 while ((id = TAILQ_FIRST(&authctxt->keys))) {
893 if (id->tried++)
894 return (0);
895 /* move key to the end of the queue */
896 TAILQ_REMOVE(&authctxt->keys, id, next);
897 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
898 /*
899 * send a test message if we have the public key. for
900 * encrypted keys we cannot do this and have to load the
901 * private key instead
902 */
903 if (id->key && id->key->type != KEY_RSA1) {
904 debug("Offering public key: %s", id->filename);
905 sent = send_pubkey_test(authctxt, id);
906 } else if (id->key == NULL) {
907 debug("Trying private key: %s", id->filename);
908 id->key = load_identity_file(id->filename);
909 if (id->key != NULL) {
910 id->isprivate = 1;
911 sent = sign_and_send_pubkey(authctxt, id);
912 key_free(id->key);
913 id->key = NULL;
914 }
915 }
916 if (sent)
917 return (sent);
918 }
919 return (0);
920 }
921
922 /*
923 * Send userauth request message specifying keyboard-interactive method.
924 */
925 int
userauth_kbdint(Authctxt * authctxt)926 userauth_kbdint(Authctxt *authctxt)
927 {
928 static int attempt = 0;
929
930 if (attempt++ >= options.number_of_password_prompts)
931 return 0;
932 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
933 if (attempt > 1 && !authctxt->info_req_seen) {
934 debug3("userauth_kbdint: disable: no info_req_seen");
935 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
936 return 0;
937 }
938
939 debug2("userauth_kbdint");
940 packet_start(SSH2_MSG_USERAUTH_REQUEST);
941 packet_put_cstring(authctxt->server_user);
942 packet_put_cstring(authctxt->service);
943 packet_put_cstring(authctxt->method->name);
944 packet_put_cstring(""); /* lang */
945 packet_put_cstring(options.kbd_interactive_devices ?
946 options.kbd_interactive_devices : "");
947 packet_send();
948
949 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
950 return 1;
951 }
952
953 /*
954 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
955 */
956 void
input_userauth_info_req(int type,u_int32_t seq,void * ctxt)957 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
958 {
959 Authctxt *authctxt = ctxt;
960 char *name, *inst, *lang, *prompt, *response;
961 u_int num_prompts, i;
962 int echo = 0;
963
964 debug2("input_userauth_info_req");
965
966 if (authctxt == NULL)
967 fatal("input_userauth_info_req: no authentication context");
968
969 authctxt->info_req_seen = 1;
970
971 name = packet_get_string(NULL);
972 inst = packet_get_string(NULL);
973 lang = packet_get_string(NULL);
974 if (strlen(name) > 0)
975 logit("%s", name);
976 if (strlen(inst) > 0)
977 logit("%s", inst);
978 xfree(name);
979 xfree(inst);
980 xfree(lang);
981
982 num_prompts = packet_get_int();
983 /*
984 * Begin to build info response packet based on prompts requested.
985 * We commit to providing the correct number of responses, so if
986 * further on we run into a problem that prevents this, we have to
987 * be sure and clean this up and send a correct error response.
988 */
989 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
990 packet_put_int(num_prompts);
991
992 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
993 for (i = 0; i < num_prompts; i++) {
994 prompt = packet_get_string(NULL);
995 echo = packet_get_char();
996
997 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
998
999 packet_put_cstring(response);
1000 memset(response, 0, strlen(response));
1001 xfree(response);
1002 xfree(prompt);
1003 }
1004 packet_check_eom(); /* done with parsing incoming message. */
1005
1006 packet_add_padding(64);
1007 packet_send();
1008 }
1009
1010 static int
ssh_keysign(Key * key,u_char ** sigp,u_int * lenp,u_char * data,u_int datalen)1011 ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1012 u_char *data, u_int datalen)
1013 {
1014 Buffer b;
1015 struct stat st;
1016 pid_t pid;
1017 int to[2], from[2], status, version = 2;
1018
1019 debug2("ssh_keysign called");
1020
1021 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1022 error("ssh_keysign: no installed: %s", strerror(errno));
1023 return -1;
1024 }
1025 if (fflush(stdout) != 0)
1026 error("ssh_keysign: fflush: %s", strerror(errno));
1027 if (pipe(to) < 0) {
1028 error("ssh_keysign: pipe: %s", strerror(errno));
1029 return -1;
1030 }
1031 if (pipe(from) < 0) {
1032 error("ssh_keysign: pipe: %s", strerror(errno));
1033 return -1;
1034 }
1035 if ((pid = fork()) < 0) {
1036 error("ssh_keysign: fork: %s", strerror(errno));
1037 return -1;
1038 }
1039 if (pid == 0) {
1040 permanently_drop_suid(getuid());
1041 close(from[0]);
1042 if (dup2(from[1], STDOUT_FILENO) < 0)
1043 fatal("ssh_keysign: dup2: %s", strerror(errno));
1044 close(to[1]);
1045 if (dup2(to[0], STDIN_FILENO) < 0)
1046 fatal("ssh_keysign: dup2: %s", strerror(errno));
1047 close(from[1]);
1048 close(to[0]);
1049 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1050 fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1051 strerror(errno));
1052 }
1053 close(from[1]);
1054 close(to[0]);
1055
1056 buffer_init(&b);
1057 buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1058 buffer_put_string(&b, data, datalen);
1059 if (ssh_msg_send(to[1], version, &b) == -1)
1060 fatal("ssh_keysign: couldn't send request");
1061
1062 if (ssh_msg_recv(from[0], &b) < 0) {
1063 error("ssh_keysign: no reply");
1064 buffer_free(&b);
1065 return -1;
1066 }
1067 close(from[0]);
1068 close(to[1]);
1069
1070 while (waitpid(pid, &status, 0) < 0)
1071 if (errno != EINTR)
1072 break;
1073
1074 if (buffer_get_char(&b) != version) {
1075 error("ssh_keysign: bad version");
1076 buffer_free(&b);
1077 return -1;
1078 }
1079 *sigp = buffer_get_string(&b, lenp);
1080 buffer_free(&b);
1081
1082 return 0;
1083 }
1084
1085 int
userauth_hostbased(Authctxt * authctxt)1086 userauth_hostbased(Authctxt *authctxt)
1087 {
1088 Key *private = NULL;
1089 Sensitive *sensitive = authctxt->sensitive;
1090 Buffer b;
1091 u_char *signature, *blob;
1092 char *chost, *pkalg, *p, myname[NI_MAXHOST];
1093 const char *service;
1094 u_int blen, slen;
1095 int ok, i, len, found = 0;
1096
1097 /* check for a useful key */
1098 for (i = 0; i < sensitive->nkeys; i++) {
1099 private = sensitive->keys[i];
1100 if (private && private->type != KEY_RSA1) {
1101 found = 1;
1102 /* we take and free the key */
1103 sensitive->keys[i] = NULL;
1104 break;
1105 }
1106 }
1107 if (!found) {
1108 debug("No more client hostkeys for hostbased authentication.");
1109 return 0;
1110 }
1111 if (key_to_blob(private, &blob, &blen) == 0) {
1112 key_free(private);
1113 return 0;
1114 }
1115 /* figure out a name for the client host */
1116 p = NULL;
1117 if (packet_connection_is_on_socket())
1118 p = get_local_name(packet_get_connection_in());
1119 if (p == NULL) {
1120 if (gethostname(myname, sizeof(myname)) == -1) {
1121 verbose("userauth_hostbased: gethostname: %s",
1122 strerror(errno));
1123 } else
1124 p = xstrdup(myname);
1125 }
1126 if (p == NULL) {
1127 error("userauth_hostbased: cannot get local ipaddr/name");
1128 key_free(private);
1129 xfree(blob);
1130 return 0;
1131 }
1132 len = strlen(p) + 2;
1133 xasprintf(&chost, "%s.", p);
1134 debug2("userauth_hostbased: chost %s", chost);
1135 xfree(p);
1136
1137 service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1138 authctxt->service;
1139 pkalg = xstrdup(key_ssh_name(private));
1140 buffer_init(&b);
1141 /* construct data */
1142 buffer_put_string(&b, session_id2, session_id2_len);
1143 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1144 buffer_put_cstring(&b, authctxt->server_user);
1145 buffer_put_cstring(&b, service);
1146 buffer_put_cstring(&b, authctxt->method->name);
1147 buffer_put_cstring(&b, pkalg);
1148 buffer_put_string(&b, blob, blen);
1149 buffer_put_cstring(&b, chost);
1150 buffer_put_cstring(&b, authctxt->local_user);
1151 #ifdef DEBUG_PK
1152 buffer_dump(&b);
1153 #endif
1154 if (sensitive->external_keysign)
1155 ok = ssh_keysign(private, &signature, &slen,
1156 buffer_ptr(&b), buffer_len(&b));
1157 else
1158 ok = key_sign(private, &signature, &slen,
1159 buffer_ptr(&b), buffer_len(&b));
1160 key_free(private);
1161 buffer_free(&b);
1162 if (ok != 0) {
1163 error("key_sign failed");
1164 xfree(chost);
1165 xfree(pkalg);
1166 xfree(blob);
1167 return 0;
1168 }
1169 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1170 packet_put_cstring(authctxt->server_user);
1171 packet_put_cstring(authctxt->service);
1172 packet_put_cstring(authctxt->method->name);
1173 packet_put_cstring(pkalg);
1174 packet_put_string(blob, blen);
1175 packet_put_cstring(chost);
1176 packet_put_cstring(authctxt->local_user);
1177 packet_put_string(signature, slen);
1178 memset(signature, 's', slen);
1179 xfree(signature);
1180 xfree(chost);
1181 xfree(pkalg);
1182 xfree(blob);
1183
1184 packet_send();
1185 return 1;
1186 }
1187
1188 /* find auth method */
1189
1190 /*
1191 * given auth method name, if configurable options permit this method fill
1192 * in auth_ident field and return true, otherwise return false.
1193 */
1194 static int
authmethod_is_enabled(Authmethod * method)1195 authmethod_is_enabled(Authmethod *method)
1196 {
1197 if (method == NULL)
1198 return 0;
1199 /* return false if options indicate this method is disabled */
1200 if (method->enabled == NULL || *method->enabled == 0)
1201 return 0;
1202 /* return false if batch mode is enabled but method needs interactive mode */
1203 if (method->batch_flag != NULL && *method->batch_flag != 0)
1204 return 0;
1205 return 1;
1206 }
1207
1208 static Authmethod *
authmethod_lookup(const char * name)1209 authmethod_lookup(const char *name)
1210 {
1211 Authmethod *method = NULL;
1212 if (name != NULL)
1213 for (method = authmethods; method->name != NULL; method++)
1214 if (strcmp(name, method->name) == 0)
1215 return method;
1216 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1217 return NULL;
1218 }
1219
1220 /* XXX internal state */
1221 static Authmethod *current = NULL;
1222 static char *supported = NULL;
1223 static char *preferred = NULL;
1224
1225 /*
1226 * Given the authentication method list sent by the server, return the
1227 * next method we should try. If the server initially sends a nil list,
1228 * use a built-in default list.
1229 */
1230 static Authmethod *
authmethod_get(char * authlist)1231 authmethod_get(char *authlist)
1232 {
1233 char *name = NULL;
1234 u_int next;
1235
1236 /* Use a suitable default if we're passed a nil list. */
1237 if (authlist == NULL || strlen(authlist) == 0)
1238 authlist = options.preferred_authentications;
1239
1240 if (supported == NULL || strcmp(authlist, supported) != 0) {
1241 debug3("start over, passed a different list %s", authlist);
1242 if (supported != NULL)
1243 xfree(supported);
1244 supported = xstrdup(authlist);
1245 preferred = options.preferred_authentications;
1246 debug3("preferred %s", preferred);
1247 current = NULL;
1248 } else if (current != NULL && authmethod_is_enabled(current))
1249 return current;
1250
1251 for (;;) {
1252 if ((name = match_list(preferred, supported, &next)) == NULL) {
1253 debug("No more authentication methods to try.");
1254 current = NULL;
1255 return NULL;
1256 }
1257 preferred += next;
1258 debug3("authmethod_lookup %s", name);
1259 debug3("remaining preferred: %s", preferred);
1260 if ((current = authmethod_lookup(name)) != NULL &&
1261 authmethod_is_enabled(current)) {
1262 debug3("authmethod_is_enabled %s", name);
1263 debug("Next authentication method: %s", name);
1264 return current;
1265 }
1266 }
1267 }
1268
1269 static char *
authmethods_get(void)1270 authmethods_get(void)
1271 {
1272 Authmethod *method = NULL;
1273 Buffer b;
1274 char *list;
1275
1276 buffer_init(&b);
1277 for (method = authmethods; method->name != NULL; method++) {
1278 if (authmethod_is_enabled(method)) {
1279 if (buffer_len(&b) > 0)
1280 buffer_append(&b, ",", 1);
1281 buffer_append(&b, method->name, strlen(method->name));
1282 }
1283 }
1284 buffer_append(&b, "\0", 1);
1285 list = xstrdup(buffer_ptr(&b));
1286 buffer_free(&b);
1287 return list;
1288 }
1289