Major cleanup of the base IPFilter:
[dragonfly.git] / crypto / openssh / sshconnect2.c
1 /*
2  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24
25 #include "includes.h"
26 RCSID("$OpenBSD: sshconnect2.c,v 1.107 2002/07/01 19:48:46 markus Exp $");
27 RCSID("$FreeBSD: src/crypto/openssh/sshconnect2.c,v 1.1.1.2.2.7 2003/02/03 17:31:08 des Exp $");
28 RCSID("$DragonFly: src/crypto/openssh/Attic/sshconnect2.c,v 1.2 2003/06/17 04:24:36 dillon Exp $");
29
30 #include "ssh.h"
31 #include "ssh2.h"
32 #include "xmalloc.h"
33 #include "buffer.h"
34 #include "packet.h"
35 #include "compat.h"
36 #include "bufaux.h"
37 #include "cipher.h"
38 #include "kex.h"
39 #include "myproposal.h"
40 #include "sshconnect.h"
41 #include "authfile.h"
42 #include "dh.h"
43 #include "authfd.h"
44 #include "log.h"
45 #include "readconf.h"
46 #include "readpass.h"
47 #include "match.h"
48 #include "dispatch.h"
49 #include "canohost.h"
50 #include "msg.h"
51 #include "pathnames.h"
52
53 /* import */
54 extern char *client_version_string;
55 extern char *server_version_string;
56 extern Options options;
57
58 /*
59  * SSH2 key exchange
60  */
61
62 u_char *session_id2 = NULL;
63 int session_id2_len = 0;
64
65 char *xxx_host;
66 struct sockaddr *xxx_hostaddr;
67
68 Kex *xxx_kex = NULL;
69
70 static int
71 verify_host_key_callback(Key *hostkey)
72 {
73         if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
74                 fatal("Host key verification failed.");
75         return 0;
76 }
77
78 void
79 ssh_kex2(char *host, struct sockaddr *hostaddr)
80 {
81         Kex *kex;
82
83         xxx_host = host;
84         xxx_hostaddr = hostaddr;
85
86         if (options.ciphers == (char *)-1) {
87                 log("No valid ciphers for protocol version 2 given, using defaults.");
88                 options.ciphers = NULL;
89         }
90         if (options.ciphers != NULL) {
91                 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
92                 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
93         }
94         myproposal[PROPOSAL_ENC_ALGS_CTOS] =
95             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
96         myproposal[PROPOSAL_ENC_ALGS_STOC] =
97             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
98         if (options.compression) {
99                 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
100                 myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib,none";
101         } else {
102                 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
103                 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib";
104         }
105         if (options.macs != NULL) {
106                 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
107                 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
108         }
109         if (options.hostkeyalgorithms != NULL)
110                 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
111                     options.hostkeyalgorithms;
112
113         /* start key exchange */
114         kex = kex_setup(myproposal);
115         kex->client_version_string=client_version_string;
116         kex->server_version_string=server_version_string;
117         kex->verify_host_key=&verify_host_key_callback;
118
119         xxx_kex = kex;
120
121         dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
122
123         session_id2 = kex->session_id;
124         session_id2_len = kex->session_id_len;
125
126 #ifdef DEBUG_KEXDH
127         /* send 1st encrypted/maced/compressed message */
128         packet_start(SSH2_MSG_IGNORE);
129         packet_put_cstring("markus");
130         packet_send();
131         packet_write_wait();
132 #endif
133         debug("done: ssh_kex2.");
134 }
135
136 /*
137  * Authenticate user
138  */
139
140 typedef struct Authctxt Authctxt;
141 typedef struct Authmethod Authmethod;
142
143 typedef int sign_cb_fn(
144     Authctxt *authctxt, Key *key,
145     u_char **sigp, u_int *lenp, u_char *data, u_int datalen);
146
147 struct Authctxt {
148         const char *server_user;
149         const char *local_user;
150         const char *host;
151         const char *service;
152         Authmethod *method;
153         int success;
154         char *authlist;
155         /* pubkey */
156         Key *last_key;
157         sign_cb_fn *last_key_sign;
158         int last_key_hint;
159         AuthenticationConnection *agent;
160         /* hostbased */
161         Sensitive *sensitive;
162         /* kbd-interactive */
163         int info_req_seen;
164 };
165 struct Authmethod {
166         char    *name;          /* string to compare against server's list */
167         int     (*userauth)(Authctxt *authctxt);
168         int     *enabled;       /* flag in option struct that enables method */
169         int     *batch_flag;    /* flag in option struct that disables method */
170 };
171
172 void    input_userauth_success(int, u_int32_t, void *);
173 void    input_userauth_failure(int, u_int32_t, void *);
174 void    input_userauth_banner(int, u_int32_t, void *);
175 void    input_userauth_error(int, u_int32_t, void *);
176 void    input_userauth_info_req(int, u_int32_t, void *);
177 void    input_userauth_pk_ok(int, u_int32_t, void *);
178 void    input_userauth_passwd_changereq(int, u_int32_t, void *);
179
180 int     userauth_none(Authctxt *);
181 int     userauth_pubkey(Authctxt *);
182 int     userauth_passwd(Authctxt *);
183 int     userauth_kbdint(Authctxt *);
184 int     userauth_hostbased(Authctxt *);
185
186 void    userauth(Authctxt *, char *);
187
188 static int sign_and_send_pubkey(Authctxt *, Key *, sign_cb_fn *);
189 static void clear_auth_state(Authctxt *);
190
191 static Authmethod *authmethod_get(char *authlist);
192 static Authmethod *authmethod_lookup(const char *name);
193 static char *authmethods_get(void);
194
195 Authmethod authmethods[] = {
196         {"hostbased",
197                 userauth_hostbased,
198                 &options.hostbased_authentication,
199                 NULL},
200         {"publickey",
201                 userauth_pubkey,
202                 &options.pubkey_authentication,
203                 NULL},
204         {"keyboard-interactive",
205                 userauth_kbdint,
206                 &options.kbd_interactive_authentication,
207                 &options.batch_mode},
208         {"password",
209                 userauth_passwd,
210                 &options.password_authentication,
211                 &options.batch_mode},
212         {"none",
213                 userauth_none,
214                 NULL,
215                 NULL},
216         {NULL, NULL, NULL, NULL}
217 };
218
219 void
220 ssh_userauth2(const char *local_user, const char *server_user, char *host,
221     Sensitive *sensitive)
222 {
223         Authctxt authctxt;
224         int type;
225
226         if (options.challenge_response_authentication)
227                 options.kbd_interactive_authentication = 1;
228
229         debug("send SSH2_MSG_SERVICE_REQUEST");
230         packet_start(SSH2_MSG_SERVICE_REQUEST);
231         packet_put_cstring("ssh-userauth");
232         packet_send();
233         packet_write_wait();
234         type = packet_read();
235         if (type != SSH2_MSG_SERVICE_ACCEPT) {
236                 fatal("denied SSH2_MSG_SERVICE_ACCEPT: %d", type);
237         }
238         if (packet_remaining() > 0) {
239                 char *reply = packet_get_string(NULL);
240                 debug("service_accept: %s", reply);
241                 xfree(reply);
242         } else {
243                 debug("buggy server: service_accept w/o service");
244         }
245         packet_check_eom();
246         debug("got SSH2_MSG_SERVICE_ACCEPT");
247
248         if (options.preferred_authentications == NULL)
249                 options.preferred_authentications = authmethods_get();
250
251         /* setup authentication context */
252         memset(&authctxt, 0, sizeof(authctxt));
253         authctxt.agent = ssh_get_authentication_connection();
254         authctxt.server_user = server_user;
255         authctxt.local_user = local_user;
256         authctxt.host = host;
257         authctxt.service = "ssh-connection";            /* service name */
258         authctxt.success = 0;
259         authctxt.method = authmethod_lookup("none");
260         authctxt.authlist = NULL;
261         authctxt.sensitive = sensitive;
262         authctxt.info_req_seen = 0;
263         if (authctxt.method == NULL)
264                 fatal("ssh_userauth2: internal error: cannot send userauth none request");
265
266         /* initial userauth request */
267         userauth_none(&authctxt);
268
269         dispatch_init(&input_userauth_error);
270         dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
271         dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
272         dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
273         dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt);     /* loop until success */
274
275         if (authctxt.agent != NULL)
276                 ssh_close_authentication_connection(authctxt.agent);
277
278         debug("ssh-userauth2 successful: method %s", authctxt.method->name);
279 }
280 void
281 userauth(Authctxt *authctxt, char *authlist)
282 {
283         if (authlist == NULL) {
284                 authlist = authctxt->authlist;
285         } else {
286                 if (authctxt->authlist)
287                         xfree(authctxt->authlist);
288                 authctxt->authlist = authlist;
289         }
290         for (;;) {
291                 Authmethod *method = authmethod_get(authlist);
292                 if (method == NULL)
293                         fatal("Permission denied (%s).", authlist);
294                 authctxt->method = method;
295                 if (method->userauth(authctxt) != 0) {
296                         debug2("we sent a %s packet, wait for reply", method->name);
297                         break;
298                 } else {
299                         debug2("we did not send a packet, disable method");
300                         method->enabled = NULL;
301                 }
302         }
303 }
304
305 void
306 input_userauth_error(int type, u_int32_t seq, void *ctxt)
307 {
308         fatal("input_userauth_error: bad message during authentication: "
309            "type %d", type);
310 }
311
312 void
313 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
314 {
315         char *msg, *lang;
316         debug3("input_userauth_banner");
317         msg = packet_get_string(NULL);
318         lang = packet_get_string(NULL);
319         fprintf(stderr, "%s", msg);
320         xfree(msg);
321         xfree(lang);
322 }
323
324 void
325 input_userauth_success(int type, u_int32_t seq, void *ctxt)
326 {
327         Authctxt *authctxt = ctxt;
328         if (authctxt == NULL)
329                 fatal("input_userauth_success: no authentication context");
330         if (authctxt->authlist)
331                 xfree(authctxt->authlist);
332         clear_auth_state(authctxt);
333         authctxt->success = 1;                  /* break out */
334 }
335
336 void
337 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
338 {
339         Authctxt *authctxt = ctxt;
340         char *authlist = NULL;
341         int partial;
342
343         if (authctxt == NULL)
344                 fatal("input_userauth_failure: no authentication context");
345
346         authlist = packet_get_string(NULL);
347         partial = packet_get_char();
348         packet_check_eom();
349
350         if (partial != 0)
351                 log("Authenticated with partial success.");
352         debug("authentications that can continue: %s", authlist);
353
354         clear_auth_state(authctxt);
355         userauth(authctxt, authlist);
356 }
357 void
358 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
359 {
360         Authctxt *authctxt = ctxt;
361         Key *key = NULL;
362         Buffer b;
363         int pktype, sent = 0;
364         u_int alen, blen;
365         char *pkalg, *fp;
366         u_char *pkblob;
367
368         if (authctxt == NULL)
369                 fatal("input_userauth_pk_ok: no authentication context");
370         if (datafellows & SSH_BUG_PKOK) {
371                 /* this is similar to SSH_BUG_PKAUTH */
372                 debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
373                 pkblob = packet_get_string(&blen);
374                 buffer_init(&b);
375                 buffer_append(&b, pkblob, blen);
376                 pkalg = buffer_get_string(&b, &alen);
377                 buffer_free(&b);
378         } else {
379                 pkalg = packet_get_string(&alen);
380                 pkblob = packet_get_string(&blen);
381         }
382         packet_check_eom();
383
384         debug("input_userauth_pk_ok: pkalg %s blen %u lastkey %p hint %d",
385             pkalg, blen, authctxt->last_key, authctxt->last_key_hint);
386
387         do {
388                 if (authctxt->last_key == NULL ||
389                     authctxt->last_key_sign == NULL) {
390                         debug("no last key or no sign cb");
391                         break;
392                 }
393                 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
394                         debug("unknown pkalg %s", pkalg);
395                         break;
396                 }
397                 if ((key = key_from_blob(pkblob, blen)) == NULL) {
398                         debug("no key from blob. pkalg %s", pkalg);
399                         break;
400                 }
401                 if (key->type != pktype) {
402                         error("input_userauth_pk_ok: type mismatch "
403                             "for decoded key (received %d, expected %d)",
404                             key->type, pktype);
405                         break;
406                 }
407                 fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
408                 debug2("input_userauth_pk_ok: fp %s", fp);
409                 xfree(fp);
410                 if (!key_equal(key, authctxt->last_key)) {
411                         debug("key != last_key");
412                         break;
413                 }
414                 sent = sign_and_send_pubkey(authctxt, key,
415                    authctxt->last_key_sign);
416         } while (0);
417
418         if (key != NULL)
419                 key_free(key);
420         xfree(pkalg);
421         xfree(pkblob);
422
423         /* unregister */
424         clear_auth_state(authctxt);
425         dispatch_set(SSH2_MSG_USERAUTH_PK_OK, NULL);
426
427         /* try another method if we did not send a packet */
428         if (sent == 0)
429                 userauth(authctxt, NULL);
430
431 }
432
433 int
434 userauth_none(Authctxt *authctxt)
435 {
436         /* initial userauth request */
437         packet_start(SSH2_MSG_USERAUTH_REQUEST);
438         packet_put_cstring(authctxt->server_user);
439         packet_put_cstring(authctxt->service);
440         packet_put_cstring(authctxt->method->name);
441         packet_send();
442         return 1;
443 }
444
445 int
446 userauth_passwd(Authctxt *authctxt)
447 {
448         static int attempt = 0;
449         char prompt[150];
450         char *password;
451
452         if (attempt++ >= options.number_of_password_prompts)
453                 return 0;
454
455         if (attempt != 1)
456                 error("Permission denied, please try again.");
457
458         snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
459             authctxt->server_user, authctxt->host);
460         password = read_passphrase(prompt, 0);
461         packet_start(SSH2_MSG_USERAUTH_REQUEST);
462         packet_put_cstring(authctxt->server_user);
463         packet_put_cstring(authctxt->service);
464         packet_put_cstring(authctxt->method->name);
465         packet_put_char(0);
466         packet_put_cstring(password);
467         memset(password, 0, strlen(password));
468         xfree(password);
469         packet_add_padding(64);
470         packet_send();
471
472         dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
473             &input_userauth_passwd_changereq);
474
475         return 1;
476 }
477 /*
478  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
479  */
480 void
481 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
482 {
483         Authctxt *authctxt = ctxt;
484         char *info, *lang, *password = NULL, *retype = NULL;
485         char prompt[150];
486
487         debug2("input_userauth_passwd_changereq");
488
489         if (authctxt == NULL)
490                 fatal("input_userauth_passwd_changereq: "
491                     "no authentication context");
492
493         info = packet_get_string(NULL);
494         lang = packet_get_string(NULL);
495         if (strlen(info) > 0)
496                 log("%s", info);
497         xfree(info);
498         xfree(lang);
499         packet_start(SSH2_MSG_USERAUTH_REQUEST);
500         packet_put_cstring(authctxt->server_user);
501         packet_put_cstring(authctxt->service);
502         packet_put_cstring(authctxt->method->name);
503         packet_put_char(1);                     /* additional info */
504         snprintf(prompt, sizeof(prompt),
505             "Enter %.30s@%.128s's old password: ",
506             authctxt->server_user, authctxt->host);
507         password = read_passphrase(prompt, 0);
508         packet_put_cstring(password);
509         memset(password, 0, strlen(password));
510         xfree(password);
511         password = NULL;
512         while (password == NULL) {
513                 snprintf(prompt, sizeof(prompt),
514                     "Enter %.30s@%.128s's new password: ",
515                     authctxt->server_user, authctxt->host);
516                 password = read_passphrase(prompt, RP_ALLOW_EOF);
517                 if (password == NULL) {
518                         /* bail out */
519                         return;
520                 }
521                 snprintf(prompt, sizeof(prompt),
522                     "Retype %.30s@%.128s's new password: ",
523                     authctxt->server_user, authctxt->host);
524                 retype = read_passphrase(prompt, 0);
525                 if (strcmp(password, retype) != 0) {
526                         memset(password, 0, strlen(password));
527                         xfree(password);
528                         log("Mismatch; try again, EOF to quit.");
529                         password = NULL;
530                 }
531                 memset(retype, 0, strlen(retype));
532                 xfree(retype);
533         }
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
544 static void
545 clear_auth_state(Authctxt *authctxt)
546 {
547         /* XXX clear authentication state */
548         dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, NULL);
549
550         if (authctxt->last_key != NULL && authctxt->last_key_hint == -1) {
551                 debug3("clear_auth_state: key_free %p", authctxt->last_key);
552                 key_free(authctxt->last_key);
553         }
554         authctxt->last_key = NULL;
555         authctxt->last_key_hint = -2;
556         authctxt->last_key_sign = NULL;
557 }
558
559 static int
560 sign_and_send_pubkey(Authctxt *authctxt, Key *k, sign_cb_fn *sign_callback)
561 {
562         Buffer b;
563         u_char *blob, *signature;
564         u_int bloblen, slen;
565         int skip = 0;
566         int ret = -1;
567         int have_sig = 1;
568
569         debug3("sign_and_send_pubkey");
570
571         if (key_to_blob(k, &blob, &bloblen) == 0) {
572                 /* we cannot handle this key */
573                 debug3("sign_and_send_pubkey: cannot handle key");
574                 return 0;
575         }
576         /* data to be signed */
577         buffer_init(&b);
578         if (datafellows & SSH_OLD_SESSIONID) {
579                 buffer_append(&b, session_id2, session_id2_len);
580                 skip = session_id2_len;
581         } else {
582                 buffer_put_string(&b, session_id2, session_id2_len);
583                 skip = buffer_len(&b);
584         }
585         buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
586         buffer_put_cstring(&b, authctxt->server_user);
587         buffer_put_cstring(&b,
588             datafellows & SSH_BUG_PKSERVICE ?
589             "ssh-userauth" :
590             authctxt->service);
591         if (datafellows & SSH_BUG_PKAUTH) {
592                 buffer_put_char(&b, have_sig);
593         } else {
594                 buffer_put_cstring(&b, authctxt->method->name);
595                 buffer_put_char(&b, have_sig);
596                 buffer_put_cstring(&b, key_ssh_name(k));
597         }
598         buffer_put_string(&b, blob, bloblen);
599
600         /* generate signature */
601         ret = (*sign_callback)(authctxt, k, &signature, &slen,
602             buffer_ptr(&b), buffer_len(&b));
603         if (ret == -1) {
604                 xfree(blob);
605                 buffer_free(&b);
606                 return 0;
607         }
608 #ifdef DEBUG_PK
609         buffer_dump(&b);
610 #endif
611         if (datafellows & SSH_BUG_PKSERVICE) {
612                 buffer_clear(&b);
613                 buffer_append(&b, session_id2, session_id2_len);
614                 skip = session_id2_len;
615                 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
616                 buffer_put_cstring(&b, authctxt->server_user);
617                 buffer_put_cstring(&b, authctxt->service);
618                 buffer_put_cstring(&b, authctxt->method->name);
619                 buffer_put_char(&b, have_sig);
620                 if (!(datafellows & SSH_BUG_PKAUTH))
621                         buffer_put_cstring(&b, key_ssh_name(k));
622                 buffer_put_string(&b, blob, bloblen);
623         }
624         xfree(blob);
625
626         /* append signature */
627         buffer_put_string(&b, signature, slen);
628         xfree(signature);
629
630         /* skip session id and packet type */
631         if (buffer_len(&b) < skip + 1)
632                 fatal("userauth_pubkey: internal error");
633         buffer_consume(&b, skip + 1);
634
635         /* put remaining data from buffer into packet */
636         packet_start(SSH2_MSG_USERAUTH_REQUEST);
637         packet_put_raw(buffer_ptr(&b), buffer_len(&b));
638         buffer_free(&b);
639         packet_send();
640
641         return 1;
642 }
643
644 static int
645 send_pubkey_test(Authctxt *authctxt, Key *k, sign_cb_fn *sign_callback,
646     int hint)
647 {
648         u_char *blob;
649         u_int bloblen, have_sig = 0;
650
651         debug3("send_pubkey_test");
652
653         if (key_to_blob(k, &blob, &bloblen) == 0) {
654                 /* we cannot handle this key */
655                 debug3("send_pubkey_test: cannot handle key");
656                 return 0;
657         }
658         /* register callback for USERAUTH_PK_OK message */
659         authctxt->last_key_sign = sign_callback;
660         authctxt->last_key_hint = hint;
661         authctxt->last_key = k;
662         dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
663
664         packet_start(SSH2_MSG_USERAUTH_REQUEST);
665         packet_put_cstring(authctxt->server_user);
666         packet_put_cstring(authctxt->service);
667         packet_put_cstring(authctxt->method->name);
668         packet_put_char(have_sig);
669         if (!(datafellows & SSH_BUG_PKAUTH))
670                 packet_put_cstring(key_ssh_name(k));
671         packet_put_string(blob, bloblen);
672         xfree(blob);
673         packet_send();
674         return 1;
675 }
676
677 static Key *
678 load_identity_file(char *filename)
679 {
680         Key *private;
681         char prompt[300], *passphrase;
682         int quit, i;
683         struct stat st;
684
685         if (stat(filename, &st) < 0) {
686                 debug3("no such identity: %s", filename);
687                 return NULL;
688         }
689         private = key_load_private_type(KEY_UNSPEC, filename, "", NULL);
690         if (private == NULL) {
691                 if (options.batch_mode)
692                         return NULL;
693                 snprintf(prompt, sizeof prompt,
694                     "Enter passphrase for key '%.100s': ", filename);
695                 for (i = 0; i < options.number_of_password_prompts; i++) {
696                         passphrase = read_passphrase(prompt, 0);
697                         if (strcmp(passphrase, "") != 0) {
698                                 private = key_load_private_type(KEY_UNSPEC, filename,
699                                     passphrase, NULL);
700                                 quit = 0;
701                         } else {
702                                 debug2("no passphrase given, try next key");
703                                 quit = 1;
704                         }
705                         memset(passphrase, 0, strlen(passphrase));
706                         xfree(passphrase);
707                         if (private != NULL || quit)
708                                 break;
709                         debug2("bad passphrase given, try again...");
710                 }
711         }
712         return private;
713 }
714
715 static int
716 identity_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
717     u_char *data, u_int datalen)
718 {
719         Key *private;
720         int idx, ret;
721
722         idx = authctxt->last_key_hint;
723         if (idx < 0)
724                 return -1;
725
726         /* private key is stored in external hardware */
727         if (options.identity_keys[idx]->flags & KEY_FLAG_EXT)
728                 return key_sign(options.identity_keys[idx], sigp, lenp, data, datalen);
729
730         private = load_identity_file(options.identity_files[idx]);
731         if (private == NULL)
732                 return -1;
733         ret = key_sign(private, sigp, lenp, data, datalen);
734         key_free(private);
735         return ret;
736 }
737
738 static int
739 agent_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
740     u_char *data, u_int datalen)
741 {
742         return ssh_agent_sign(authctxt->agent, key, sigp, lenp, data, datalen);
743 }
744
745 static int
746 key_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
747     u_char *data, u_int datalen)
748 {
749         return key_sign(key, sigp, lenp, data, datalen);
750 }
751
752 static int
753 userauth_pubkey_agent(Authctxt *authctxt)
754 {
755         static int called = 0;
756         int ret = 0;
757         char *comment;
758         Key *k;
759
760         if (called == 0) {
761                 if (ssh_get_num_identities(authctxt->agent, 2) == 0)
762                         debug2("userauth_pubkey_agent: no keys at all");
763                 called = 1;
764         }
765         k = ssh_get_next_identity(authctxt->agent, &comment, 2);
766         if (k == NULL) {
767                 debug2("userauth_pubkey_agent: no more keys");
768         } else {
769                 debug("userauth_pubkey_agent: testing agent key %s", comment);
770                 xfree(comment);
771                 ret = send_pubkey_test(authctxt, k, agent_sign_cb, -1);
772                 if (ret == 0)
773                         key_free(k);
774         }
775         if (ret == 0)
776                 debug2("userauth_pubkey_agent: no message sent");
777         return ret;
778 }
779
780 int
781 userauth_pubkey(Authctxt *authctxt)
782 {
783         static int idx = 0;
784         int sent = 0;
785         Key *key;
786         char *filename;
787
788         if (authctxt->agent != NULL) {
789                 do {
790                         sent = userauth_pubkey_agent(authctxt);
791                 } while (!sent && authctxt->agent->howmany > 0);
792         }
793         while (!sent && idx < options.num_identity_files) {
794                 key = options.identity_keys[idx];
795                 filename = options.identity_files[idx];
796                 if (key == NULL) {
797                         debug("try privkey: %s", filename);
798                         key = load_identity_file(filename);
799                         if (key != NULL) {
800                                 sent = sign_and_send_pubkey(authctxt, key,
801                                     key_sign_cb);
802                                 key_free(key);
803                         }
804                 } else if (key->type != KEY_RSA1) {
805                         debug("try pubkey: %s", filename);
806                         sent = send_pubkey_test(authctxt, key,
807                             identity_sign_cb, idx);
808                 }
809                 idx++;
810         }
811         return sent;
812 }
813
814 /*
815  * Send userauth request message specifying keyboard-interactive method.
816  */
817 int
818 userauth_kbdint(Authctxt *authctxt)
819 {
820         static int attempt = 0;
821
822         if (attempt++ >= options.number_of_password_prompts)
823                 return 0;
824         /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
825         if (attempt > 1 && !authctxt->info_req_seen) {
826                 debug3("userauth_kbdint: disable: no info_req_seen");
827                 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
828                 return 0;
829         }
830
831         debug2("userauth_kbdint");
832         packet_start(SSH2_MSG_USERAUTH_REQUEST);
833         packet_put_cstring(authctxt->server_user);
834         packet_put_cstring(authctxt->service);
835         packet_put_cstring(authctxt->method->name);
836         packet_put_cstring("");                                 /* lang */
837         packet_put_cstring(options.kbd_interactive_devices ?
838             options.kbd_interactive_devices : "");
839         packet_send();
840
841         dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
842         return 1;
843 }
844
845 /*
846  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
847  */
848 void
849 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
850 {
851         Authctxt *authctxt = ctxt;
852         char *name, *inst, *lang, *prompt, *response;
853         u_int num_prompts, i;
854         int echo = 0;
855
856         debug2("input_userauth_info_req");
857
858         if (authctxt == NULL)
859                 fatal("input_userauth_info_req: no authentication context");
860
861         authctxt->info_req_seen = 1;
862
863         name = packet_get_string(NULL);
864         inst = packet_get_string(NULL);
865         lang = packet_get_string(NULL);
866         if (strlen(name) > 0)
867                 log("%s", name);
868         if (strlen(inst) > 0)
869                 log("%s", inst);
870         xfree(name);
871         xfree(inst);
872         xfree(lang);
873
874         num_prompts = packet_get_int();
875         /*
876          * Begin to build info response packet based on prompts requested.
877          * We commit to providing the correct number of responses, so if
878          * further on we run into a problem that prevents this, we have to
879          * be sure and clean this up and send a correct error response.
880          */
881         packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
882         packet_put_int(num_prompts);
883
884         debug2("input_userauth_info_req: num_prompts %d", num_prompts);
885         for (i = 0; i < num_prompts; i++) {
886                 prompt = packet_get_string(NULL);
887                 echo = packet_get_char();
888
889                 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
890
891                 packet_put_cstring(response);
892                 memset(response, 0, strlen(response));
893                 xfree(response);
894                 xfree(prompt);
895         }
896         packet_check_eom(); /* done with parsing incoming message. */
897
898         packet_add_padding(64);
899         packet_send();
900 }
901
902 static int
903 ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
904     u_char *data, u_int datalen)
905 {
906         Buffer b;
907         struct stat st;
908         pid_t pid;
909         int to[2], from[2], status, version = 2;
910
911         debug("ssh_keysign called");
912
913         if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
914                 error("ssh_keysign: no installed: %s", strerror(errno));
915                 return -1;
916         }
917         if (fflush(stdout) != 0)
918                 error("ssh_keysign: fflush: %s", strerror(errno));
919         if (pipe(to) < 0) {
920                 error("ssh_keysign: pipe: %s", strerror(errno));
921                 return -1;
922         }
923         if (pipe(from) < 0) {
924                 error("ssh_keysign: pipe: %s", strerror(errno));
925                 return -1;
926         }
927         if ((pid = fork()) < 0) {
928                 error("ssh_keysign: fork: %s", strerror(errno));
929                 return -1;
930         }
931         if (pid == 0) {
932                 seteuid(getuid());
933                 setuid(getuid());
934                 close(from[0]);
935                 if (dup2(from[1], STDOUT_FILENO) < 0)
936                         fatal("ssh_keysign: dup2: %s", strerror(errno));
937                 close(to[1]);
938                 if (dup2(to[0], STDIN_FILENO) < 0)
939                         fatal("ssh_keysign: dup2: %s", strerror(errno));
940                 close(from[1]);
941                 close(to[0]);
942                 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
943                 fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
944                     strerror(errno));
945         }
946         close(from[1]);
947         close(to[0]);
948
949         buffer_init(&b);
950         buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
951         buffer_put_string(&b, data, datalen);
952         ssh_msg_send(to[1], version, &b);
953
954         if (ssh_msg_recv(from[0], &b) < 0) {
955                 error("ssh_keysign: no reply");
956                 buffer_clear(&b);
957                 return -1;
958         }
959         close(from[0]);
960         close(to[1]);
961
962         while (waitpid(pid, &status, 0) < 0)
963                 if (errno != EINTR)
964                         break;
965
966         if (buffer_get_char(&b) != version) {
967                 error("ssh_keysign: bad version");
968                 buffer_clear(&b);
969                 return -1;
970         }
971         *sigp = buffer_get_string(&b, lenp);
972         buffer_clear(&b);
973
974         return 0;
975 }
976
977 int
978 userauth_hostbased(Authctxt *authctxt)
979 {
980         Key *private = NULL;
981         Sensitive *sensitive = authctxt->sensitive;
982         Buffer b;
983         u_char *signature, *blob;
984         char *chost, *pkalg, *p;
985         const char *service;
986         u_int blen, slen;
987         int ok, i, len, found = 0;
988
989         /* check for a useful key */
990         for (i = 0; i < sensitive->nkeys; i++) {
991                 private = sensitive->keys[i];
992                 if (private && private->type != KEY_RSA1) {
993                         found = 1;
994                         /* we take and free the key */
995                         sensitive->keys[i] = NULL;
996                         break;
997                 }
998         }
999         if (!found) {
1000                 debug("userauth_hostbased: no more client hostkeys");
1001                 return 0;
1002         }
1003         if (key_to_blob(private, &blob, &blen) == 0) {
1004                 key_free(private);
1005                 return 0;
1006         }
1007         /* figure out a name for the client host */
1008         p = get_local_name(packet_get_connection_in());
1009         if (p == NULL) {
1010                 error("userauth_hostbased: cannot get local ipaddr/name");
1011                 key_free(private);
1012                 return 0;
1013         }
1014         len = strlen(p) + 2;
1015         chost = xmalloc(len);
1016         strlcpy(chost, p, len);
1017         strlcat(chost, ".", len);
1018         debug2("userauth_hostbased: chost %s", chost);
1019
1020         service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1021             authctxt->service;
1022         pkalg = xstrdup(key_ssh_name(private));
1023         buffer_init(&b);
1024         /* construct data */
1025         buffer_put_string(&b, session_id2, session_id2_len);
1026         buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1027         buffer_put_cstring(&b, authctxt->server_user);
1028         buffer_put_cstring(&b, service);
1029         buffer_put_cstring(&b, authctxt->method->name);
1030         buffer_put_cstring(&b, pkalg);
1031         buffer_put_string(&b, blob, blen);
1032         buffer_put_cstring(&b, chost);
1033         buffer_put_cstring(&b, authctxt->local_user);
1034 #ifdef DEBUG_PK
1035         buffer_dump(&b);
1036 #endif
1037         if (sensitive->external_keysign)
1038                 ok = ssh_keysign(private, &signature, &slen,
1039                     buffer_ptr(&b), buffer_len(&b));
1040         else
1041                 ok = key_sign(private, &signature, &slen,
1042                     buffer_ptr(&b), buffer_len(&b));
1043         key_free(private);
1044         buffer_free(&b);
1045         if (ok != 0) {
1046                 error("key_sign failed");
1047                 xfree(chost);
1048                 xfree(pkalg);
1049                 return 0;
1050         }
1051         packet_start(SSH2_MSG_USERAUTH_REQUEST);
1052         packet_put_cstring(authctxt->server_user);
1053         packet_put_cstring(authctxt->service);
1054         packet_put_cstring(authctxt->method->name);
1055         packet_put_cstring(pkalg);
1056         packet_put_string(blob, blen);
1057         packet_put_cstring(chost);
1058         packet_put_cstring(authctxt->local_user);
1059         packet_put_string(signature, slen);
1060         memset(signature, 's', slen);
1061         xfree(signature);
1062         xfree(chost);
1063         xfree(pkalg);
1064
1065         packet_send();
1066         return 1;
1067 }
1068
1069 /* find auth method */
1070
1071 /*
1072  * given auth method name, if configurable options permit this method fill
1073  * in auth_ident field and return true, otherwise return false.
1074  */
1075 static int
1076 authmethod_is_enabled(Authmethod *method)
1077 {
1078         if (method == NULL)
1079                 return 0;
1080         /* return false if options indicate this method is disabled */
1081         if  (method->enabled == NULL || *method->enabled == 0)
1082                 return 0;
1083         /* return false if batch mode is enabled but method needs interactive mode */
1084         if  (method->batch_flag != NULL && *method->batch_flag != 0)
1085                 return 0;
1086         return 1;
1087 }
1088
1089 static Authmethod *
1090 authmethod_lookup(const char *name)
1091 {
1092         Authmethod *method = NULL;
1093         if (name != NULL)
1094                 for (method = authmethods; method->name != NULL; method++)
1095                         if (strcmp(name, method->name) == 0)
1096                                 return method;
1097         debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1098         return NULL;
1099 }
1100
1101 /* XXX internal state */
1102 static Authmethod *current = NULL;
1103 static char *supported = NULL;
1104 static char *preferred = NULL;
1105
1106 /*
1107  * Given the authentication method list sent by the server, return the
1108  * next method we should try.  If the server initially sends a nil list,
1109  * use a built-in default list.
1110  */
1111 static Authmethod *
1112 authmethod_get(char *authlist)
1113 {
1114
1115         char *name = NULL;
1116         u_int next;
1117
1118         /* Use a suitable default if we're passed a nil list.  */
1119         if (authlist == NULL || strlen(authlist) == 0)
1120                 authlist = options.preferred_authentications;
1121
1122         if (supported == NULL || strcmp(authlist, supported) != 0) {
1123                 debug3("start over, passed a different list %s", authlist);
1124                 if (supported != NULL)
1125                         xfree(supported);
1126                 supported = xstrdup(authlist);
1127                 preferred = options.preferred_authentications;
1128                 debug3("preferred %s", preferred);
1129                 current = NULL;
1130         } else if (current != NULL && authmethod_is_enabled(current))
1131                 return current;
1132
1133         for (;;) {
1134                 if ((name = match_list(preferred, supported, &next)) == NULL) {
1135                         debug("no more auth methods to try");
1136                         current = NULL;
1137                         return NULL;
1138                 }
1139                 preferred += next;
1140                 debug3("authmethod_lookup %s", name);
1141                 debug3("remaining preferred: %s", preferred);
1142                 if ((current = authmethod_lookup(name)) != NULL &&
1143                     authmethod_is_enabled(current)) {
1144                         debug3("authmethod_is_enabled %s", name);
1145                         debug("next auth method to try is %s", name);
1146                         return current;
1147                 }
1148         }
1149 }
1150
1151 static char *
1152 authmethods_get(void)
1153 {
1154         Authmethod *method = NULL;
1155         Buffer b;
1156         char *list;
1157
1158         buffer_init(&b);
1159         for (method = authmethods; method->name != NULL; method++) {
1160                 if (authmethod_is_enabled(method)) {
1161                         if (buffer_len(&b) > 0)
1162                                 buffer_append(&b, ",", 1);
1163                         buffer_append(&b, method->name, strlen(method->name));
1164                 }
1165         }
1166         buffer_append(&b, "\0", 1);
1167         list = xstrdup(buffer_ptr(&b));
1168         buffer_free(&b);
1169         return list;
1170 }