Note appropriate krb5 build dependency
[openssh.git] / monitor.c
1 /* $OpenBSD: monitor.c,v 1.110 2010/09/09 10:45:45 djm Exp $ */
2 /*
3  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
4  * Copyright 2002 Markus Friedl <markus@openbsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "includes.h"
29
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include "openbsd-compat/sys-tree.h"
34 #include <sys/wait.h>
35
36 #include <errno.h>
37 #include <fcntl.h>
38 #ifdef HAVE_PATHS_H
39 #include <paths.h>
40 #endif
41 #include <pwd.h>
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47
48 #ifdef SKEY
49 #include <skey.h>
50 #endif
51
52 #include <openssl/dh.h>
53
54 #include "openbsd-compat/sys-queue.h"
55 #include "xmalloc.h"
56 #include "ssh.h"
57 #include "key.h"
58 #include "buffer.h"
59 #include "hostfile.h"
60 #include "auth.h"
61 #include "cipher.h"
62 #include "kex.h"
63 #include "dh.h"
64 #ifdef TARGET_OS_MAC    /* XXX Broken krb5 headers on Mac */
65 #undef TARGET_OS_MAC
66 #include "zlib.h"
67 #define TARGET_OS_MAC 1
68 #else
69 #include "zlib.h"
70 #endif
71 #include "packet.h"
72 #include "auth-options.h"
73 #include "sshpty.h"
74 #include "channels.h"
75 #include "session.h"
76 #include "sshlogin.h"
77 #include "canohost.h"
78 #include "log.h"
79 #include "servconf.h"
80 #include "monitor.h"
81 #include "monitor_mm.h"
82 #ifdef GSSAPI
83 #include "ssh-gss.h"
84 #endif
85 #include "monitor_wrap.h"
86 #include "monitor_fdpass.h"
87 #include "misc.h"
88 #include "compat.h"
89 #include "ssh2.h"
90 #include "jpake.h"
91 #include "roaming.h"
92
93 #ifdef GSSAPI
94 static Gssctxt *gsscontext = NULL;
95 #endif
96
97 /* Imports */
98 extern ServerOptions options;
99 extern u_int utmp_len;
100 extern Newkeys *current_keys[];
101 extern z_stream incoming_stream;
102 extern z_stream outgoing_stream;
103 extern u_char session_id[];
104 extern Buffer auth_debug;
105 extern int auth_debug_init;
106 extern Buffer loginmsg;
107
108 /* State exported from the child */
109
110 struct {
111         z_stream incoming;
112         z_stream outgoing;
113         u_char *keyin;
114         u_int keyinlen;
115         u_char *keyout;
116         u_int keyoutlen;
117         u_char *ivin;
118         u_int ivinlen;
119         u_char *ivout;
120         u_int ivoutlen;
121         u_char *ssh1key;
122         u_int ssh1keylen;
123         int ssh1cipher;
124         int ssh1protoflags;
125         u_char *input;
126         u_int ilen;
127         u_char *output;
128         u_int olen;
129         u_int64_t sent_bytes;
130         u_int64_t recv_bytes;
131 } child_state;
132
133 /* Functions on the monitor that answer unprivileged requests */
134
135 int mm_answer_moduli(int, Buffer *);
136 int mm_answer_sign(int, Buffer *);
137 int mm_answer_pwnamallow(int, Buffer *);
138 int mm_answer_auth2_read_banner(int, Buffer *);
139 int mm_answer_authserv(int, Buffer *);
140 int mm_answer_authrole(int, Buffer *);
141 int mm_answer_authpassword(int, Buffer *);
142 int mm_answer_bsdauthquery(int, Buffer *);
143 int mm_answer_bsdauthrespond(int, Buffer *);
144 int mm_answer_skeyquery(int, Buffer *);
145 int mm_answer_skeyrespond(int, Buffer *);
146 int mm_answer_keyallowed(int, Buffer *);
147 int mm_answer_keyverify(int, Buffer *);
148 int mm_answer_pty(int, Buffer *);
149 int mm_answer_pty_cleanup(int, Buffer *);
150 int mm_answer_term(int, Buffer *);
151 int mm_answer_rsa_keyallowed(int, Buffer *);
152 int mm_answer_rsa_challenge(int, Buffer *);
153 int mm_answer_rsa_response(int, Buffer *);
154 int mm_answer_sesskey(int, Buffer *);
155 int mm_answer_sessid(int, Buffer *);
156 int mm_answer_jpake_get_pwdata(int, Buffer *);
157 int mm_answer_jpake_step1(int, Buffer *);
158 int mm_answer_jpake_step2(int, Buffer *);
159 int mm_answer_jpake_key_confirm(int, Buffer *);
160 int mm_answer_jpake_check_confirm(int, Buffer *);
161
162 #ifdef USE_PAM
163 int mm_answer_pam_start(int, Buffer *);
164 int mm_answer_pam_account(int, Buffer *);
165 int mm_answer_pam_init_ctx(int, Buffer *);
166 int mm_answer_pam_query(int, Buffer *);
167 int mm_answer_pam_respond(int, Buffer *);
168 int mm_answer_pam_free_ctx(int, Buffer *);
169 #endif
170
171 #ifdef GSSAPI
172 int mm_answer_gss_setup_ctx(int, Buffer *);
173 int mm_answer_gss_accept_ctx(int, Buffer *);
174 int mm_answer_gss_userok(int, Buffer *);
175 int mm_answer_gss_checkmic(int, Buffer *);
176 int mm_answer_gss_sign(int, Buffer *);
177 int mm_answer_gss_updatecreds(int, Buffer *);
178 #endif
179
180 #ifdef SSH_AUDIT_EVENTS
181 int mm_answer_audit_event(int, Buffer *);
182 int mm_answer_audit_command(int, Buffer *);
183 #endif
184
185 static Authctxt *authctxt;
186 static BIGNUM *ssh1_challenge = NULL;   /* used for ssh1 rsa auth */
187
188 /* local state for key verify */
189 static u_char *key_blob = NULL;
190 static u_int key_bloblen = 0;
191 static int key_blobtype = MM_NOKEY;
192 static char *hostbased_cuser = NULL;
193 static char *hostbased_chost = NULL;
194 static char *auth_method = "unknown";
195 static u_int session_id2_len = 0;
196 static u_char *session_id2 = NULL;
197 static pid_t monitor_child_pid;
198
199 struct mon_table {
200         enum monitor_reqtype type;
201         int flags;
202         int (*f)(int, Buffer *);
203 };
204
205 #define MON_ISAUTH      0x0004  /* Required for Authentication */
206 #define MON_AUTHDECIDE  0x0008  /* Decides Authentication */
207 #define MON_ONCE        0x0010  /* Disable after calling */
208 #define MON_ALOG        0x0020  /* Log auth attempt without authenticating */
209
210 #define MON_AUTH        (MON_ISAUTH|MON_AUTHDECIDE)
211
212 #define MON_PERMIT      0x1000  /* Request is permitted */
213
214 struct mon_table mon_dispatch_proto20[] = {
215     {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
216     {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
217     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
218     {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
219     {MONITOR_REQ_AUTHROLE, MON_ONCE, mm_answer_authrole},
220     {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
221     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
222 #ifdef USE_PAM
223     {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
224     {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
225     {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
226     {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
227     {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
228     {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
229 #endif
230 #ifdef SSH_AUDIT_EVENTS
231     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
232 #endif
233 #ifdef BSD_AUTH
234     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
235     {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
236 #endif
237 #ifdef SKEY
238     {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
239     {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
240 #endif
241     {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
242     {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
243 #ifdef GSSAPI
244     {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
245     {MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx},
246     {MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok},
247     {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
248     {MONITOR_REQ_GSSSIGN, MON_ONCE, mm_answer_gss_sign},
249 #endif
250 #ifdef JPAKE
251     {MONITOR_REQ_JPAKE_GET_PWDATA, MON_ONCE, mm_answer_jpake_get_pwdata},
252     {MONITOR_REQ_JPAKE_STEP1, MON_ISAUTH, mm_answer_jpake_step1},
253     {MONITOR_REQ_JPAKE_STEP2, MON_ONCE, mm_answer_jpake_step2},
254     {MONITOR_REQ_JPAKE_KEY_CONFIRM, MON_ONCE, mm_answer_jpake_key_confirm},
255     {MONITOR_REQ_JPAKE_CHECK_CONFIRM, MON_AUTH, mm_answer_jpake_check_confirm},
256 #endif
257     {0, 0, NULL}
258 };
259
260 struct mon_table mon_dispatch_postauth20[] = {
261 #ifdef GSSAPI
262     {MONITOR_REQ_GSSSETUP, 0, mm_answer_gss_setup_ctx},
263     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
264     {MONITOR_REQ_GSSSIGN, 0, mm_answer_gss_sign},
265     {MONITOR_REQ_GSSUPCREDS, 0, mm_answer_gss_updatecreds},
266 #endif
267     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
268     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
269     {MONITOR_REQ_PTY, 0, mm_answer_pty},
270     {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
271     {MONITOR_REQ_TERM, 0, mm_answer_term},
272 #ifdef SSH_AUDIT_EVENTS
273     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
274     {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT, mm_answer_audit_command},
275 #endif
276     {0, 0, NULL}
277 };
278
279 struct mon_table mon_dispatch_proto15[] = {
280     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
281     {MONITOR_REQ_SESSKEY, MON_ONCE, mm_answer_sesskey},
282     {MONITOR_REQ_SESSID, MON_ONCE, mm_answer_sessid},
283     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
284     {MONITOR_REQ_RSAKEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_rsa_keyallowed},
285     {MONITOR_REQ_KEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_keyallowed},
286     {MONITOR_REQ_RSACHALLENGE, MON_ONCE, mm_answer_rsa_challenge},
287     {MONITOR_REQ_RSARESPONSE, MON_ONCE|MON_AUTHDECIDE, mm_answer_rsa_response},
288 #ifdef BSD_AUTH
289     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
290     {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
291 #endif
292 #ifdef SKEY
293     {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
294     {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
295 #endif
296 #ifdef USE_PAM
297     {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
298     {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
299     {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
300     {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
301     {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
302     {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
303 #endif
304 #ifdef SSH_AUDIT_EVENTS
305     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
306 #endif
307     {0, 0, NULL}
308 };
309
310 struct mon_table mon_dispatch_postauth15[] = {
311     {MONITOR_REQ_PTY, MON_ONCE, mm_answer_pty},
312     {MONITOR_REQ_PTYCLEANUP, MON_ONCE, mm_answer_pty_cleanup},
313     {MONITOR_REQ_TERM, 0, mm_answer_term},
314 #ifdef SSH_AUDIT_EVENTS
315     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
316     {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT|MON_ONCE, mm_answer_audit_command},
317 #endif
318     {0, 0, NULL}
319 };
320
321 struct mon_table *mon_dispatch;
322
323 /* Specifies if a certain message is allowed at the moment */
324
325 static void
326 monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
327 {
328         while (ent->f != NULL) {
329                 if (ent->type == type) {
330                         ent->flags &= ~MON_PERMIT;
331                         ent->flags |= permit ? MON_PERMIT : 0;
332                         return;
333                 }
334                 ent++;
335         }
336 }
337
338 static void
339 monitor_permit_authentications(int permit)
340 {
341         struct mon_table *ent = mon_dispatch;
342
343         while (ent->f != NULL) {
344                 if (ent->flags & MON_AUTH) {
345                         ent->flags &= ~MON_PERMIT;
346                         ent->flags |= permit ? MON_PERMIT : 0;
347                 }
348                 ent++;
349         }
350 }
351
352 void
353 monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
354 {
355         struct mon_table *ent;
356         int authenticated = 0;
357
358         debug3("preauth child monitor started");
359
360         authctxt = _authctxt;
361         memset(authctxt, 0, sizeof(*authctxt));
362
363         authctxt->loginmsg = &loginmsg;
364
365         if (compat20) {
366                 mon_dispatch = mon_dispatch_proto20;
367
368                 /* Permit requests for moduli and signatures */
369                 monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
370                 monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
371 #ifdef GSSAPI
372                 /* and for the GSSAPI key exchange */
373                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
374 #endif
375         } else {
376                 mon_dispatch = mon_dispatch_proto15;
377
378                 monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 1);
379         }
380
381         /* The first few requests do not require asynchronous access */
382         while (!authenticated) {
383                 auth_method = "unknown";
384                 authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
385                 if (authenticated) {
386                         if (!(ent->flags & MON_AUTHDECIDE))
387                                 fatal("%s: unexpected authentication from %d",
388                                     __func__, ent->type);
389                         if (authctxt->pw->pw_uid == 0 &&
390                             !auth_root_allowed(auth_method))
391                                 authenticated = 0;
392 #ifdef USE_PAM
393                         /* PAM needs to perform account checks after auth */
394                         if (options.use_pam && authenticated) {
395                                 Buffer m;
396
397                                 buffer_init(&m);
398                                 mm_request_receive_expect(pmonitor->m_sendfd,
399                                     MONITOR_REQ_PAM_ACCOUNT, &m);
400                                 authenticated = mm_answer_pam_account(pmonitor->m_sendfd, &m);
401                                 buffer_free(&m);
402                         }
403 #endif
404                 }
405
406                 if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
407                         auth_log(authctxt, authenticated, auth_method,
408                             compat20 ? " ssh2" : "");
409                         if (!authenticated)
410                                 authctxt->failures++;
411                 }
412 #ifdef JPAKE
413                 /* Cleanup JPAKE context after authentication */
414                 if (ent->flags & MON_AUTHDECIDE) {
415                         if (authctxt->jpake_ctx != NULL) {
416                                 jpake_free(authctxt->jpake_ctx);
417                                 authctxt->jpake_ctx = NULL;
418                         }
419                 }
420 #endif
421         }
422
423         if (!authctxt->valid)
424                 fatal("%s: authenticated invalid user", __func__);
425         if (strcmp(auth_method, "unknown") == 0)
426                 fatal("%s: authentication method name unknown", __func__);
427
428         debug("%s: %s has been authenticated by privileged process",
429             __func__, authctxt->user);
430
431         mm_get_keystate(pmonitor);
432 }
433
434 static void
435 monitor_set_child_handler(pid_t pid)
436 {
437         monitor_child_pid = pid;
438 }
439
440 static void
441 monitor_child_handler(int sig)
442 {
443         kill(monitor_child_pid, sig);
444 }
445
446 void
447 monitor_child_postauth(struct monitor *pmonitor)
448 {
449         monitor_set_child_handler(pmonitor->m_pid);
450         signal(SIGHUP, &monitor_child_handler);
451         signal(SIGTERM, &monitor_child_handler);
452         signal(SIGINT, &monitor_child_handler);
453
454         if (compat20) {
455                 mon_dispatch = mon_dispatch_postauth20;
456
457                 /* Permit requests for moduli and signatures */
458                 monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
459                 monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
460                 monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
461 #ifdef GSSAPI
462                 /* and for the GSSAPI key exchange */
463                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
464 #endif          
465         } else {
466                 mon_dispatch = mon_dispatch_postauth15;
467                 monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
468         }
469         if (!no_pty_flag) {
470                 monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
471                 monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
472         }
473
474         for (;;)
475                 monitor_read(pmonitor, mon_dispatch, NULL);
476 }
477
478 void
479 monitor_sync(struct monitor *pmonitor)
480 {
481         if (options.compression) {
482                 /* The member allocation is not visible, so sync it */
483                 mm_share_sync(&pmonitor->m_zlib, &pmonitor->m_zback);
484         }
485 }
486
487 int
488 monitor_read(struct monitor *pmonitor, struct mon_table *ent,
489     struct mon_table **pent)
490 {
491         Buffer m;
492         int ret;
493         u_char type;
494
495         buffer_init(&m);
496
497         mm_request_receive(pmonitor->m_sendfd, &m);
498         type = buffer_get_char(&m);
499
500         debug3("%s: checking request %d", __func__, type);
501
502         while (ent->f != NULL) {
503                 if (ent->type == type)
504                         break;
505                 ent++;
506         }
507
508         if (ent->f != NULL) {
509                 if (!(ent->flags & MON_PERMIT))
510                         fatal("%s: unpermitted request %d", __func__,
511                             type);
512                 ret = (*ent->f)(pmonitor->m_sendfd, &m);
513                 buffer_free(&m);
514
515                 /* The child may use this request only once, disable it */
516                 if (ent->flags & MON_ONCE) {
517                         debug2("%s: %d used once, disabling now", __func__,
518                             type);
519                         ent->flags &= ~MON_PERMIT;
520                 }
521
522                 if (pent != NULL)
523                         *pent = ent;
524
525                 return ret;
526         }
527
528         fatal("%s: unsupported request: %d", __func__, type);
529
530         /* NOTREACHED */
531         return (-1);
532 }
533
534 /* allowed key state */
535 static int
536 monitor_allowed_key(u_char *blob, u_int bloblen)
537 {
538         /* make sure key is allowed */
539         if (key_blob == NULL || key_bloblen != bloblen ||
540             timingsafe_bcmp(key_blob, blob, key_bloblen))
541                 return (0);
542         return (1);
543 }
544
545 static void
546 monitor_reset_key_state(void)
547 {
548         /* reset state */
549         if (key_blob != NULL)
550                 xfree(key_blob);
551         if (hostbased_cuser != NULL)
552                 xfree(hostbased_cuser);
553         if (hostbased_chost != NULL)
554                 xfree(hostbased_chost);
555         key_blob = NULL;
556         key_bloblen = 0;
557         key_blobtype = MM_NOKEY;
558         hostbased_cuser = NULL;
559         hostbased_chost = NULL;
560 }
561
562 int
563 mm_answer_moduli(int sock, Buffer *m)
564 {
565         DH *dh;
566         int min, want, max;
567
568         min = buffer_get_int(m);
569         want = buffer_get_int(m);
570         max = buffer_get_int(m);
571
572         debug3("%s: got parameters: %d %d %d",
573             __func__, min, want, max);
574         /* We need to check here, too, in case the child got corrupted */
575         if (max < min || want < min || max < want)
576                 fatal("%s: bad parameters: %d %d %d",
577                     __func__, min, want, max);
578
579         buffer_clear(m);
580
581         dh = choose_dh(min, want, max);
582         if (dh == NULL) {
583                 buffer_put_char(m, 0);
584                 return (0);
585         } else {
586                 /* Send first bignum */
587                 buffer_put_char(m, 1);
588                 buffer_put_bignum2(m, dh->p);
589                 buffer_put_bignum2(m, dh->g);
590
591                 DH_free(dh);
592         }
593         mm_request_send(sock, MONITOR_ANS_MODULI, m);
594         return (0);
595 }
596
597 int
598 mm_answer_sign(int sock, Buffer *m)
599 {
600         Key *key;
601         u_char *p;
602         u_char *signature;
603         u_int siglen, datlen;
604         int keyid;
605
606         debug3("%s", __func__);
607
608         keyid = buffer_get_int(m);
609         p = buffer_get_string(m, &datlen);
610
611         /*
612          * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
613          * SHA384 (48 bytes) and SHA512 (64 bytes).
614          */
615         if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64)
616                 fatal("%s: data length incorrect: %u", __func__, datlen);
617
618         /* save session id, it will be passed on the first call */
619         if (session_id2_len == 0) {
620                 session_id2_len = datlen;
621                 session_id2 = xmalloc(session_id2_len);
622                 memcpy(session_id2, p, session_id2_len);
623         }
624
625         if ((key = get_hostkey_by_index(keyid)) == NULL)
626                 fatal("%s: no hostkey from index %d", __func__, keyid);
627         if (key_sign(key, &signature, &siglen, p, datlen) < 0)
628                 fatal("%s: key_sign failed", __func__);
629
630         debug3("%s: signature %p(%u)", __func__, signature, siglen);
631
632         buffer_clear(m);
633         buffer_put_string(m, signature, siglen);
634
635         xfree(p);
636         xfree(signature);
637
638         mm_request_send(sock, MONITOR_ANS_SIGN, m);
639
640         /* Turn on permissions for getpwnam */
641         monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
642
643         return (0);
644 }
645
646 /* Retrieves the password entry and also checks if the user is permitted */
647
648 int
649 mm_answer_pwnamallow(int sock, Buffer *m)
650 {
651         char *username;
652         struct passwd *pwent;
653         int allowed = 0;
654
655         debug3("%s", __func__);
656
657         if (authctxt->attempt++ != 0)
658                 fatal("%s: multiple attempts for getpwnam", __func__);
659
660         username = buffer_get_string(m, NULL);
661
662         pwent = getpwnamallow(username);
663
664         authctxt->user = xstrdup(username);
665         setproctitle("%s [priv]", pwent ? username : "unknown");
666         xfree(username);
667
668         buffer_clear(m);
669
670         if (pwent == NULL) {
671                 buffer_put_char(m, 0);
672                 authctxt->pw = fakepw();
673                 goto out;
674         }
675
676         allowed = 1;
677         authctxt->pw = pwent;
678         authctxt->valid = 1;
679
680         buffer_put_char(m, 1);
681         buffer_put_string(m, pwent, sizeof(struct passwd));
682         buffer_put_cstring(m, pwent->pw_name);
683         buffer_put_cstring(m, "*");
684         buffer_put_cstring(m, pwent->pw_gecos);
685 #ifdef HAVE_PW_CLASS_IN_PASSWD
686         buffer_put_cstring(m, pwent->pw_class);
687 #endif
688         buffer_put_cstring(m, pwent->pw_dir);
689         buffer_put_cstring(m, pwent->pw_shell);
690
691  out:
692         buffer_put_string(m, &options, sizeof(options));
693         if (options.banner != NULL)
694                 buffer_put_cstring(m, options.banner);
695         debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
696         mm_request_send(sock, MONITOR_ANS_PWNAM, m);
697
698         /* For SSHv1 allow authentication now */
699         if (!compat20)
700                 monitor_permit_authentications(1);
701         else {
702                 /* Allow service/style information on the auth context */
703                 monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
704                 monitor_permit(mon_dispatch, MONITOR_REQ_AUTHROLE, 1);
705                 monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
706         }
707
708 #ifdef USE_PAM
709         if (options.use_pam)
710                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
711 #endif
712
713         return (0);
714 }
715
716 int mm_answer_auth2_read_banner(int sock, Buffer *m)
717 {
718         char *banner;
719
720         buffer_clear(m);
721         banner = auth2_read_banner();
722         buffer_put_cstring(m, banner != NULL ? banner : "");
723         mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
724
725         if (banner != NULL)
726                 xfree(banner);
727
728         return (0);
729 }
730
731 int
732 mm_answer_authserv(int sock, Buffer *m)
733 {
734         monitor_permit_authentications(1);
735
736         authctxt->service = buffer_get_string(m, NULL);
737         authctxt->style = buffer_get_string(m, NULL);
738         authctxt->role = buffer_get_string(m, NULL);
739         debug3("%s: service=%s, style=%s, role=%s",
740             __func__, authctxt->service, authctxt->style, authctxt->role);
741
742         if (strlen(authctxt->style) == 0) {
743                 xfree(authctxt->style);
744                 authctxt->style = NULL;
745         }
746
747         if (strlen(authctxt->role) == 0) {
748                 xfree(authctxt->role);
749                 authctxt->role = NULL;
750         }
751
752         return (0);
753 }
754
755 int
756 mm_answer_authrole(int sock, Buffer *m)
757 {
758         monitor_permit_authentications(1);
759
760         authctxt->role = buffer_get_string(m, NULL);
761         debug3("%s: role=%s",
762             __func__, authctxt->role);
763
764         if (strlen(authctxt->role) == 0) {
765                 xfree(authctxt->role);
766                 authctxt->role = NULL;
767         }
768
769         return (0);
770 }
771
772 int
773 mm_answer_authpassword(int sock, Buffer *m)
774 {
775         static int call_count;
776         char *passwd;
777         int authenticated;
778         u_int plen;
779
780         passwd = buffer_get_string(m, &plen);
781         /* Only authenticate if the context is valid */
782         authenticated = options.password_authentication &&
783             auth_password(authctxt, passwd);
784         memset(passwd, 0, strlen(passwd));
785         xfree(passwd);
786
787         buffer_clear(m);
788         buffer_put_int(m, authenticated);
789
790         debug3("%s: sending result %d", __func__, authenticated);
791         mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
792
793         call_count++;
794         if (plen == 0 && call_count == 1)
795                 auth_method = "none";
796         else
797                 auth_method = "password";
798
799         /* Causes monitor loop to terminate if authenticated */
800         return (authenticated);
801 }
802
803 #ifdef BSD_AUTH
804 int
805 mm_answer_bsdauthquery(int sock, Buffer *m)
806 {
807         char *name, *infotxt;
808         u_int numprompts;
809         u_int *echo_on;
810         char **prompts;
811         u_int success;
812
813         success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
814             &prompts, &echo_on) < 0 ? 0 : 1;
815
816         buffer_clear(m);
817         buffer_put_int(m, success);
818         if (success)
819                 buffer_put_cstring(m, prompts[0]);
820
821         debug3("%s: sending challenge success: %u", __func__, success);
822         mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
823
824         if (success) {
825                 xfree(name);
826                 xfree(infotxt);
827                 xfree(prompts);
828                 xfree(echo_on);
829         }
830
831         return (0);
832 }
833
834 int
835 mm_answer_bsdauthrespond(int sock, Buffer *m)
836 {
837         char *response;
838         int authok;
839
840         if (authctxt->as == 0)
841                 fatal("%s: no bsd auth session", __func__);
842
843         response = buffer_get_string(m, NULL);
844         authok = options.challenge_response_authentication &&
845             auth_userresponse(authctxt->as, response, 0);
846         authctxt->as = NULL;
847         debug3("%s: <%s> = <%d>", __func__, response, authok);
848         xfree(response);
849
850         buffer_clear(m);
851         buffer_put_int(m, authok);
852
853         debug3("%s: sending authenticated: %d", __func__, authok);
854         mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
855
856         auth_method = "bsdauth";
857
858         return (authok != 0);
859 }
860 #endif
861
862 #ifdef SKEY
863 int
864 mm_answer_skeyquery(int sock, Buffer *m)
865 {
866         struct skey skey;
867         char challenge[1024];
868         u_int success;
869
870         success = _compat_skeychallenge(&skey, authctxt->user, challenge,
871             sizeof(challenge)) < 0 ? 0 : 1;
872
873         buffer_clear(m);
874         buffer_put_int(m, success);
875         if (success)
876                 buffer_put_cstring(m, challenge);
877
878         debug3("%s: sending challenge success: %u", __func__, success);
879         mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m);
880
881         return (0);
882 }
883
884 int
885 mm_answer_skeyrespond(int sock, Buffer *m)
886 {
887         char *response;
888         int authok;
889
890         response = buffer_get_string(m, NULL);
891
892         authok = (options.challenge_response_authentication &&
893             authctxt->valid &&
894             skey_haskey(authctxt->pw->pw_name) == 0 &&
895             skey_passcheck(authctxt->pw->pw_name, response) != -1);
896
897         xfree(response);
898
899         buffer_clear(m);
900         buffer_put_int(m, authok);
901
902         debug3("%s: sending authenticated: %d", __func__, authok);
903         mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m);
904
905         auth_method = "skey";
906
907         return (authok != 0);
908 }
909 #endif
910
911 #ifdef USE_PAM
912 int
913 mm_answer_pam_start(int sock, Buffer *m)
914 {
915         if (!options.use_pam)
916                 fatal("UsePAM not set, but ended up in %s anyway", __func__);
917
918         start_pam(authctxt);
919
920         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
921
922         return (0);
923 }
924
925 int
926 mm_answer_pam_account(int sock, Buffer *m)
927 {
928         u_int ret;
929
930         if (!options.use_pam)
931                 fatal("UsePAM not set, but ended up in %s anyway", __func__);
932
933         ret = do_pam_account();
934
935         buffer_put_int(m, ret);
936         buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
937
938         mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
939
940         return (ret);
941 }
942
943 static void *sshpam_ctxt, *sshpam_authok;
944 extern KbdintDevice sshpam_device;
945
946 int
947 mm_answer_pam_init_ctx(int sock, Buffer *m)
948 {
949
950         debug3("%s", __func__);
951         authctxt->user = buffer_get_string(m, NULL);
952         sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
953         sshpam_authok = NULL;
954         buffer_clear(m);
955         if (sshpam_ctxt != NULL) {
956                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
957                 buffer_put_int(m, 1);
958         } else {
959                 buffer_put_int(m, 0);
960         }
961         mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
962         return (0);
963 }
964
965 int
966 mm_answer_pam_query(int sock, Buffer *m)
967 {
968         char *name = NULL, *info = NULL, **prompts = NULL;
969         u_int i, num = 0, *echo_on = 0;
970         int ret;
971
972         debug3("%s", __func__);
973         sshpam_authok = NULL;
974         ret = (sshpam_device.query)(sshpam_ctxt, &name, &info, &num, &prompts, &echo_on);
975         if (ret == 0 && num == 0)
976                 sshpam_authok = sshpam_ctxt;
977         if (num > 1 || name == NULL || info == NULL)
978                 ret = -1;
979         buffer_clear(m);
980         buffer_put_int(m, ret);
981         buffer_put_cstring(m, name);
982         xfree(name);
983         buffer_put_cstring(m, info);
984         xfree(info);
985         buffer_put_int(m, num);
986         for (i = 0; i < num; ++i) {
987                 buffer_put_cstring(m, prompts[i]);
988                 xfree(prompts[i]);
989                 buffer_put_int(m, echo_on[i]);
990         }
991         if (prompts != NULL)
992                 xfree(prompts);
993         if (echo_on != NULL)
994                 xfree(echo_on);
995         auth_method = "keyboard-interactive/pam";
996         mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
997         return (0);
998 }
999
1000 int
1001 mm_answer_pam_respond(int sock, Buffer *m)
1002 {
1003         char **resp;
1004         u_int i, num;
1005         int ret;
1006
1007         debug3("%s", __func__);
1008         sshpam_authok = NULL;
1009         num = buffer_get_int(m);
1010         if (num > 0) {
1011                 resp = xcalloc(num, sizeof(char *));
1012                 for (i = 0; i < num; ++i)
1013                         resp[i] = buffer_get_string(m, NULL);
1014                 ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
1015                 for (i = 0; i < num; ++i)
1016                         xfree(resp[i]);
1017                 xfree(resp);
1018         } else {
1019                 ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
1020         }
1021         buffer_clear(m);
1022         buffer_put_int(m, ret);
1023         mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
1024         auth_method = "keyboard-interactive/pam";
1025         if (ret == 0)
1026                 sshpam_authok = sshpam_ctxt;
1027         return (0);
1028 }
1029
1030 int
1031 mm_answer_pam_free_ctx(int sock, Buffer *m)
1032 {
1033
1034         debug3("%s", __func__);
1035         (sshpam_device.free_ctx)(sshpam_ctxt);
1036         buffer_clear(m);
1037         mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1038         auth_method = "keyboard-interactive/pam";
1039         return (sshpam_authok == sshpam_ctxt);
1040 }
1041 #endif
1042
1043 int
1044 mm_answer_keyallowed(int sock, Buffer *m)
1045 {
1046         Key *key;
1047         char *cuser, *chost;
1048         u_char *blob;
1049         u_int bloblen;
1050         enum mm_keytype type = 0;
1051         int allowed = 0;
1052
1053         debug3("%s entering", __func__);
1054
1055         type = buffer_get_int(m);
1056         cuser = buffer_get_string(m, NULL);
1057         chost = buffer_get_string(m, NULL);
1058         blob = buffer_get_string(m, &bloblen);
1059
1060         key = key_from_blob(blob, bloblen);
1061
1062         if ((compat20 && type == MM_RSAHOSTKEY) ||
1063             (!compat20 && type != MM_RSAHOSTKEY))
1064                 fatal("%s: key type and protocol mismatch", __func__);
1065
1066         debug3("%s: key_from_blob: %p", __func__, key);
1067
1068         if (key != NULL && authctxt->valid) {
1069                 switch (type) {
1070                 case MM_USERKEY:
1071                         allowed = options.pubkey_authentication &&
1072                             user_key_allowed(authctxt->pw, key);
1073                         auth_method = "publickey";
1074                         if (options.pubkey_authentication && allowed != 1)
1075                                 auth_clear_options();
1076                         break;
1077                 case MM_HOSTKEY:
1078                         allowed = options.hostbased_authentication &&
1079                             hostbased_key_allowed(authctxt->pw,
1080                             cuser, chost, key);
1081                         auth_method = "hostbased";
1082                         break;
1083                 case MM_RSAHOSTKEY:
1084                         key->type = KEY_RSA1; /* XXX */
1085                         allowed = options.rhosts_rsa_authentication &&
1086                             auth_rhosts_rsa_key_allowed(authctxt->pw,
1087                             cuser, chost, key);
1088                         if (options.rhosts_rsa_authentication && allowed != 1)
1089                                 auth_clear_options();
1090                         auth_method = "rsa";
1091                         break;
1092                 default:
1093                         fatal("%s: unknown key type %d", __func__, type);
1094                         break;
1095                 }
1096         }
1097         if (key != NULL)
1098                 key_free(key);
1099
1100         /* clear temporarily storage (used by verify) */
1101         monitor_reset_key_state();
1102
1103         if (allowed) {
1104                 /* Save temporarily for comparison in verify */
1105                 key_blob = blob;
1106                 key_bloblen = bloblen;
1107                 key_blobtype = type;
1108                 hostbased_cuser = cuser;
1109                 hostbased_chost = chost;
1110         } else {
1111                 /* Log failed attempt */
1112                 auth_log(authctxt, 0, auth_method, compat20 ? " ssh2" : "");
1113                 xfree(blob);
1114                 xfree(cuser);
1115                 xfree(chost);
1116         }
1117
1118         debug3("%s: key %p is %s",
1119             __func__, key, allowed ? "allowed" : "not allowed");
1120
1121         buffer_clear(m);
1122         buffer_put_int(m, allowed);
1123         buffer_put_int(m, forced_command != NULL);
1124
1125         mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1126
1127         if (type == MM_RSAHOSTKEY)
1128                 monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1129
1130         return (0);
1131 }
1132
1133 static int
1134 monitor_valid_userblob(u_char *data, u_int datalen)
1135 {
1136         Buffer b;
1137         char *p;
1138         u_int len;
1139         int fail = 0;
1140
1141         buffer_init(&b);
1142         buffer_append(&b, data, datalen);
1143
1144         if (datafellows & SSH_OLD_SESSIONID) {
1145                 p = buffer_ptr(&b);
1146                 len = buffer_len(&b);
1147                 if ((session_id2 == NULL) ||
1148                     (len < session_id2_len) ||
1149                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1150                         fail++;
1151                 buffer_consume(&b, session_id2_len);
1152         } else {
1153                 p = buffer_get_string(&b, &len);
1154                 if ((session_id2 == NULL) ||
1155                     (len != session_id2_len) ||
1156                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1157                         fail++;
1158                 xfree(p);
1159         }
1160         if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1161                 fail++;
1162         p = buffer_get_string(&b, NULL);
1163         if (strcmp(authctxt->user, p) != 0) {
1164                 logit("wrong user name passed to monitor: expected %s != %.100s",
1165                     authctxt->user, p);
1166                 fail++;
1167         }
1168         xfree(p);
1169         buffer_skip_string(&b);
1170         if (datafellows & SSH_BUG_PKAUTH) {
1171                 if (!buffer_get_char(&b))
1172                         fail++;
1173         } else {
1174                 p = buffer_get_string(&b, NULL);
1175                 if (strcmp("publickey", p) != 0)
1176                         fail++;
1177                 xfree(p);
1178                 if (!buffer_get_char(&b))
1179                         fail++;
1180                 buffer_skip_string(&b);
1181         }
1182         buffer_skip_string(&b);
1183         if (buffer_len(&b) != 0)
1184                 fail++;
1185         buffer_free(&b);
1186         return (fail == 0);
1187 }
1188
1189 static int
1190 monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
1191     char *chost)
1192 {
1193         Buffer b;
1194         char *p;
1195         u_int len;
1196         int fail = 0;
1197
1198         buffer_init(&b);
1199         buffer_append(&b, data, datalen);
1200
1201         p = buffer_get_string(&b, &len);
1202         if ((session_id2 == NULL) ||
1203             (len != session_id2_len) ||
1204             (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1205                 fail++;
1206         xfree(p);
1207
1208         if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1209                 fail++;
1210         p = buffer_get_string(&b, NULL);
1211         if (strcmp(authctxt->user, p) != 0) {
1212                 logit("wrong user name passed to monitor: expected %s != %.100s",
1213                     authctxt->user, p);
1214                 fail++;
1215         }
1216         xfree(p);
1217         buffer_skip_string(&b); /* service */
1218         p = buffer_get_string(&b, NULL);
1219         if (strcmp(p, "hostbased") != 0)
1220                 fail++;
1221         xfree(p);
1222         buffer_skip_string(&b); /* pkalg */
1223         buffer_skip_string(&b); /* pkblob */
1224
1225         /* verify client host, strip trailing dot if necessary */
1226         p = buffer_get_string(&b, NULL);
1227         if (((len = strlen(p)) > 0) && p[len - 1] == '.')
1228                 p[len - 1] = '\0';
1229         if (strcmp(p, chost) != 0)
1230                 fail++;
1231         xfree(p);
1232
1233         /* verify client user */
1234         p = buffer_get_string(&b, NULL);
1235         if (strcmp(p, cuser) != 0)
1236                 fail++;
1237         xfree(p);
1238
1239         if (buffer_len(&b) != 0)
1240                 fail++;
1241         buffer_free(&b);
1242         return (fail == 0);
1243 }
1244
1245 int
1246 mm_answer_keyverify(int sock, Buffer *m)
1247 {
1248         Key *key;
1249         u_char *signature, *data, *blob;
1250         u_int signaturelen, datalen, bloblen;
1251         int verified = 0;
1252         int valid_data = 0;
1253
1254         blob = buffer_get_string(m, &bloblen);
1255         signature = buffer_get_string(m, &signaturelen);
1256         data = buffer_get_string(m, &datalen);
1257
1258         if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1259           !monitor_allowed_key(blob, bloblen))
1260                 fatal("%s: bad key, not previously allowed", __func__);
1261
1262         key = key_from_blob(blob, bloblen);
1263         if (key == NULL)
1264                 fatal("%s: bad public key blob", __func__);
1265
1266         switch (key_blobtype) {
1267         case MM_USERKEY:
1268                 valid_data = monitor_valid_userblob(data, datalen);
1269                 break;
1270         case MM_HOSTKEY:
1271                 valid_data = monitor_valid_hostbasedblob(data, datalen,
1272                     hostbased_cuser, hostbased_chost);
1273                 break;
1274         default:
1275                 valid_data = 0;
1276                 break;
1277         }
1278         if (!valid_data)
1279                 fatal("%s: bad signature data blob", __func__);
1280
1281         verified = key_verify(key, signature, signaturelen, data, datalen);
1282         debug3("%s: key %p signature %s",
1283             __func__, key, (verified == 1) ? "verified" : "unverified");
1284
1285         key_free(key);
1286         xfree(blob);
1287         xfree(signature);
1288         xfree(data);
1289
1290         auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
1291
1292         monitor_reset_key_state();
1293
1294         buffer_clear(m);
1295         buffer_put_int(m, verified);
1296         mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1297
1298         return (verified == 1);
1299 }
1300
1301 static void
1302 mm_record_login(Session *s, struct passwd *pw)
1303 {
1304         socklen_t fromlen;
1305         struct sockaddr_storage from;
1306
1307         /*
1308          * Get IP address of client. If the connection is not a socket, let
1309          * the address be 0.0.0.0.
1310          */
1311         memset(&from, 0, sizeof(from));
1312         fromlen = sizeof(from);
1313         if (packet_connection_is_on_socket()) {
1314                 if (getpeername(packet_get_connection_in(),
1315                     (struct sockaddr *)&from, &fromlen) < 0) {
1316                         debug("getpeername: %.100s", strerror(errno));
1317                         cleanup_exit(255);
1318                 }
1319         }
1320         /* Record that there was a login on that tty from the remote host. */
1321         record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1322             get_remote_name_or_ip(utmp_len, options.use_dns),
1323             (struct sockaddr *)&from, fromlen);
1324 }
1325
1326 static void
1327 mm_session_close(Session *s)
1328 {
1329         debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1330         if (s->ttyfd != -1) {
1331                 debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1332                 session_pty_cleanup2(s);
1333         }
1334         session_unused(s->self);
1335 }
1336
1337 int
1338 mm_answer_pty(int sock, Buffer *m)
1339 {
1340         extern struct monitor *pmonitor;
1341         Session *s;
1342         int res, fd0;
1343
1344         debug3("%s entering", __func__);
1345
1346         buffer_clear(m);
1347         s = session_new();
1348         if (s == NULL)
1349                 goto error;
1350         s->authctxt = authctxt;
1351         s->pw = authctxt->pw;
1352         s->pid = pmonitor->m_pid;
1353         res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1354         if (res == 0)
1355                 goto error;
1356         pty_setowner(authctxt->pw, s->tty, authctxt->role);
1357
1358         buffer_put_int(m, 1);
1359         buffer_put_cstring(m, s->tty);
1360
1361         /* We need to trick ttyslot */
1362         if (dup2(s->ttyfd, 0) == -1)
1363                 fatal("%s: dup2", __func__);
1364
1365         mm_record_login(s, authctxt->pw);
1366
1367         /* Now we can close the file descriptor again */
1368         close(0);
1369
1370         /* send messages generated by record_login */
1371         buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1372         buffer_clear(&loginmsg);
1373
1374         mm_request_send(sock, MONITOR_ANS_PTY, m);
1375
1376         if (mm_send_fd(sock, s->ptyfd) == -1 ||
1377             mm_send_fd(sock, s->ttyfd) == -1)
1378                 fatal("%s: send fds failed", __func__);
1379
1380         /* make sure nothing uses fd 0 */
1381         if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1382                 fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1383         if (fd0 != 0)
1384                 error("%s: fd0 %d != 0", __func__, fd0);
1385
1386         /* slave is not needed */
1387         close(s->ttyfd);
1388         s->ttyfd = s->ptyfd;
1389         /* no need to dup() because nobody closes ptyfd */
1390         s->ptymaster = s->ptyfd;
1391
1392         debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1393
1394         return (0);
1395
1396  error:
1397         if (s != NULL)
1398                 mm_session_close(s);
1399         buffer_put_int(m, 0);
1400         mm_request_send(sock, MONITOR_ANS_PTY, m);
1401         return (0);
1402 }
1403
1404 int
1405 mm_answer_pty_cleanup(int sock, Buffer *m)
1406 {
1407         Session *s;
1408         char *tty;
1409
1410         debug3("%s entering", __func__);
1411
1412         tty = buffer_get_string(m, NULL);
1413         if ((s = session_by_tty(tty)) != NULL)
1414                 mm_session_close(s);
1415         buffer_clear(m);
1416         xfree(tty);
1417         return (0);
1418 }
1419
1420 int
1421 mm_answer_sesskey(int sock, Buffer *m)
1422 {
1423         BIGNUM *p;
1424         int rsafail;
1425
1426         /* Turn off permissions */
1427         monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0);
1428
1429         if ((p = BN_new()) == NULL)
1430                 fatal("%s: BN_new", __func__);
1431
1432         buffer_get_bignum2(m, p);
1433
1434         rsafail = ssh1_session_key(p);
1435
1436         buffer_clear(m);
1437         buffer_put_int(m, rsafail);
1438         buffer_put_bignum2(m, p);
1439
1440         BN_clear_free(p);
1441
1442         mm_request_send(sock, MONITOR_ANS_SESSKEY, m);
1443
1444         /* Turn on permissions for sessid passing */
1445         monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1);
1446
1447         return (0);
1448 }
1449
1450 int
1451 mm_answer_sessid(int sock, Buffer *m)
1452 {
1453         int i;
1454
1455         debug3("%s entering", __func__);
1456
1457         if (buffer_len(m) != 16)
1458                 fatal("%s: bad ssh1 session id", __func__);
1459         for (i = 0; i < 16; i++)
1460                 session_id[i] = buffer_get_char(m);
1461
1462         /* Turn on permissions for getpwnam */
1463         monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
1464
1465         return (0);
1466 }
1467
1468 int
1469 mm_answer_rsa_keyallowed(int sock, Buffer *m)
1470 {
1471         BIGNUM *client_n;
1472         Key *key = NULL;
1473         u_char *blob = NULL;
1474         u_int blen = 0;
1475         int allowed = 0;
1476
1477         debug3("%s entering", __func__);
1478
1479         auth_method = "rsa";
1480         if (options.rsa_authentication && authctxt->valid) {
1481                 if ((client_n = BN_new()) == NULL)
1482                         fatal("%s: BN_new", __func__);
1483                 buffer_get_bignum2(m, client_n);
1484                 allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key);
1485                 BN_clear_free(client_n);
1486         }
1487         buffer_clear(m);
1488         buffer_put_int(m, allowed);
1489         buffer_put_int(m, forced_command != NULL);
1490
1491         /* clear temporarily storage (used by generate challenge) */
1492         monitor_reset_key_state();
1493
1494         if (allowed && key != NULL) {
1495                 key->type = KEY_RSA;    /* cheat for key_to_blob */
1496                 if (key_to_blob(key, &blob, &blen) == 0)
1497                         fatal("%s: key_to_blob failed", __func__);
1498                 buffer_put_string(m, blob, blen);
1499
1500                 /* Save temporarily for comparison in verify */
1501                 key_blob = blob;
1502                 key_bloblen = blen;
1503                 key_blobtype = MM_RSAUSERKEY;
1504         }
1505         if (key != NULL)
1506                 key_free(key);
1507
1508         mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m);
1509
1510         monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1511         monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0);
1512         return (0);
1513 }
1514
1515 int
1516 mm_answer_rsa_challenge(int sock, Buffer *m)
1517 {
1518         Key *key = NULL;
1519         u_char *blob;
1520         u_int blen;
1521
1522         debug3("%s entering", __func__);
1523
1524         if (!authctxt->valid)
1525                 fatal("%s: authctxt not valid", __func__);
1526         blob = buffer_get_string(m, &blen);
1527         if (!monitor_allowed_key(blob, blen))
1528                 fatal("%s: bad key, not previously allowed", __func__);
1529         if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1530                 fatal("%s: key type mismatch", __func__);
1531         if ((key = key_from_blob(blob, blen)) == NULL)
1532                 fatal("%s: received bad key", __func__);
1533         if (key->type != KEY_RSA)
1534                 fatal("%s: received bad key type %d", __func__, key->type);
1535         key->type = KEY_RSA1;
1536         if (ssh1_challenge)
1537                 BN_clear_free(ssh1_challenge);
1538         ssh1_challenge = auth_rsa_generate_challenge(key);
1539
1540         buffer_clear(m);
1541         buffer_put_bignum2(m, ssh1_challenge);
1542
1543         debug3("%s sending reply", __func__);
1544         mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);
1545
1546         monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);
1547
1548         xfree(blob);
1549         key_free(key);
1550         return (0);
1551 }
1552
1553 int
1554 mm_answer_rsa_response(int sock, Buffer *m)
1555 {
1556         Key *key = NULL;
1557         u_char *blob, *response;
1558         u_int blen, len;
1559         int success;
1560
1561         debug3("%s entering", __func__);
1562
1563         if (!authctxt->valid)
1564                 fatal("%s: authctxt not valid", __func__);
1565         if (ssh1_challenge == NULL)
1566                 fatal("%s: no ssh1_challenge", __func__);
1567
1568         blob = buffer_get_string(m, &blen);
1569         if (!monitor_allowed_key(blob, blen))
1570                 fatal("%s: bad key, not previously allowed", __func__);
1571         if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1572                 fatal("%s: key type mismatch: %d", __func__, key_blobtype);
1573         if ((key = key_from_blob(blob, blen)) == NULL)
1574                 fatal("%s: received bad key", __func__);
1575         response = buffer_get_string(m, &len);
1576         if (len != 16)
1577                 fatal("%s: received bad response to challenge", __func__);
1578         success = auth_rsa_verify_response(key, ssh1_challenge, response);
1579
1580         xfree(blob);
1581         key_free(key);
1582         xfree(response);
1583
1584         auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa";
1585
1586         /* reset state */
1587         BN_clear_free(ssh1_challenge);
1588         ssh1_challenge = NULL;
1589         monitor_reset_key_state();
1590
1591         buffer_clear(m);
1592         buffer_put_int(m, success);
1593         mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m);
1594
1595         return (success);
1596 }
1597
1598 int
1599 mm_answer_term(int sock, Buffer *req)
1600 {
1601         extern struct monitor *pmonitor;
1602         int res, status;
1603
1604         debug3("%s: tearing down sessions", __func__);
1605
1606         /* The child is terminating */
1607         session_destroy_all(&mm_session_close);
1608
1609 #ifdef USE_PAM
1610         if (options.use_pam)
1611                 sshpam_cleanup();
1612 #endif
1613
1614         while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1615                 if (errno != EINTR)
1616                         exit(1);
1617
1618         res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1619
1620         /* Terminate process */
1621         exit(res);
1622 }
1623
1624 #ifdef SSH_AUDIT_EVENTS
1625 /* Report that an audit event occurred */
1626 int
1627 mm_answer_audit_event(int socket, Buffer *m)
1628 {
1629         ssh_audit_event_t event;
1630
1631         debug3("%s entering", __func__);
1632
1633         event = buffer_get_int(m);
1634         switch(event) {
1635         case SSH_AUTH_FAIL_PUBKEY:
1636         case SSH_AUTH_FAIL_HOSTBASED:
1637         case SSH_AUTH_FAIL_GSSAPI:
1638         case SSH_LOGIN_EXCEED_MAXTRIES:
1639         case SSH_LOGIN_ROOT_DENIED:
1640         case SSH_CONNECTION_CLOSE:
1641         case SSH_INVALID_USER:
1642                 audit_event(event);
1643                 break;
1644         default:
1645                 fatal("Audit event type %d not permitted", event);
1646         }
1647
1648         return (0);
1649 }
1650
1651 int
1652 mm_answer_audit_command(int socket, Buffer *m)
1653 {
1654         u_int len;
1655         char *cmd;
1656
1657         debug3("%s entering", __func__);
1658         cmd = buffer_get_string(m, &len);
1659         /* sanity check command, if so how? */
1660         audit_run_command(cmd);
1661         xfree(cmd);
1662         return (0);
1663 }
1664 #endif /* SSH_AUDIT_EVENTS */
1665
1666 void
1667 monitor_apply_keystate(struct monitor *pmonitor)
1668 {
1669         if (compat20) {
1670                 set_newkeys(MODE_IN);
1671                 set_newkeys(MODE_OUT);
1672         } else {
1673                 packet_set_protocol_flags(child_state.ssh1protoflags);
1674                 packet_set_encryption_key(child_state.ssh1key,
1675                     child_state.ssh1keylen, child_state.ssh1cipher);
1676                 xfree(child_state.ssh1key);
1677         }
1678
1679         /* for rc4 and other stateful ciphers */
1680         packet_set_keycontext(MODE_OUT, child_state.keyout);
1681         xfree(child_state.keyout);
1682         packet_set_keycontext(MODE_IN, child_state.keyin);
1683         xfree(child_state.keyin);
1684
1685         if (!compat20) {
1686                 packet_set_iv(MODE_OUT, child_state.ivout);
1687                 xfree(child_state.ivout);
1688                 packet_set_iv(MODE_IN, child_state.ivin);
1689                 xfree(child_state.ivin);
1690         }
1691
1692         memcpy(&incoming_stream, &child_state.incoming,
1693             sizeof(incoming_stream));
1694         memcpy(&outgoing_stream, &child_state.outgoing,
1695             sizeof(outgoing_stream));
1696
1697         /* Update with new address */
1698         if (options.compression)
1699                 mm_init_compression(pmonitor->m_zlib);
1700
1701         /* Network I/O buffers */
1702         /* XXX inefficient for large buffers, need: buffer_init_from_string */
1703         buffer_clear(packet_get_input());
1704         buffer_append(packet_get_input(), child_state.input, child_state.ilen);
1705         memset(child_state.input, 0, child_state.ilen);
1706         xfree(child_state.input);
1707
1708         buffer_clear(packet_get_output());
1709         buffer_append(packet_get_output(), child_state.output,
1710                       child_state.olen);
1711         memset(child_state.output, 0, child_state.olen);
1712         xfree(child_state.output);
1713
1714         /* Roaming */
1715         if (compat20)
1716                 roam_set_bytes(child_state.sent_bytes, child_state.recv_bytes);
1717 }
1718
1719 static Kex *
1720 mm_get_kex(Buffer *m)
1721 {
1722         Kex *kex;
1723         void *blob;
1724         u_int bloblen;
1725
1726         kex = xcalloc(1, sizeof(*kex));
1727         kex->session_id = buffer_get_string(m, &kex->session_id_len);
1728         if (session_id2 == NULL ||
1729             kex->session_id_len != session_id2_len ||
1730             timingsafe_bcmp(kex->session_id, session_id2, session_id2_len) != 0)
1731                 fatal("mm_get_get: internal error: bad session id");
1732         kex->we_need = buffer_get_int(m);
1733         kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1734         kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1735         kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1736         kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1737         kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1738 #ifdef GSSAPI
1739         if (options.gss_keyex) {
1740                 kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
1741                 kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
1742                 kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
1743         }
1744 #endif
1745         kex->server = 1;
1746         kex->hostkey_type = buffer_get_int(m);
1747         kex->kex_type = buffer_get_int(m);
1748         blob = buffer_get_string(m, &bloblen);
1749         buffer_init(&kex->my);
1750         buffer_append(&kex->my, blob, bloblen);
1751         xfree(blob);
1752         blob = buffer_get_string(m, &bloblen);
1753         buffer_init(&kex->peer);
1754         buffer_append(&kex->peer, blob, bloblen);
1755         xfree(blob);
1756         kex->done = 1;
1757         kex->flags = buffer_get_int(m);
1758         kex->client_version_string = buffer_get_string(m, NULL);
1759         kex->server_version_string = buffer_get_string(m, NULL);
1760         kex->load_host_public_key=&get_hostkey_public_by_type;
1761         kex->load_host_private_key=&get_hostkey_private_by_type;
1762         kex->host_key_index=&get_hostkey_index;
1763
1764         return (kex);
1765 }
1766
1767 /* This function requries careful sanity checking */
1768
1769 void
1770 mm_get_keystate(struct monitor *pmonitor)
1771 {
1772         Buffer m;
1773         u_char *blob, *p;
1774         u_int bloblen, plen;
1775         u_int32_t seqnr, packets;
1776         u_int64_t blocks, bytes;
1777
1778         debug3("%s: Waiting for new keys", __func__);
1779
1780         buffer_init(&m);
1781         mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT, &m);
1782         if (!compat20) {
1783                 child_state.ssh1protoflags = buffer_get_int(&m);
1784                 child_state.ssh1cipher = buffer_get_int(&m);
1785                 child_state.ssh1key = buffer_get_string(&m,
1786                     &child_state.ssh1keylen);
1787                 child_state.ivout = buffer_get_string(&m,
1788                     &child_state.ivoutlen);
1789                 child_state.ivin = buffer_get_string(&m, &child_state.ivinlen);
1790                 goto skip;
1791         } else {
1792                 /* Get the Kex for rekeying */
1793                 *pmonitor->m_pkex = mm_get_kex(&m);
1794         }
1795
1796         blob = buffer_get_string(&m, &bloblen);
1797         current_keys[MODE_OUT] = mm_newkeys_from_blob(blob, bloblen);
1798         xfree(blob);
1799
1800         debug3("%s: Waiting for second key", __func__);
1801         blob = buffer_get_string(&m, &bloblen);
1802         current_keys[MODE_IN] = mm_newkeys_from_blob(blob, bloblen);
1803         xfree(blob);
1804
1805         /* Now get sequence numbers for the packets */
1806         seqnr = buffer_get_int(&m);
1807         blocks = buffer_get_int64(&m);
1808         packets = buffer_get_int(&m);
1809         bytes = buffer_get_int64(&m);
1810         packet_set_state(MODE_OUT, seqnr, blocks, packets, bytes);
1811         seqnr = buffer_get_int(&m);
1812         blocks = buffer_get_int64(&m);
1813         packets = buffer_get_int(&m);
1814         bytes = buffer_get_int64(&m);
1815         packet_set_state(MODE_IN, seqnr, blocks, packets, bytes);
1816
1817  skip:
1818         /* Get the key context */
1819         child_state.keyout = buffer_get_string(&m, &child_state.keyoutlen);
1820         child_state.keyin  = buffer_get_string(&m, &child_state.keyinlen);
1821
1822         debug3("%s: Getting compression state", __func__);
1823         /* Get compression state */
1824         p = buffer_get_string(&m, &plen);
1825         if (plen != sizeof(child_state.outgoing))
1826                 fatal("%s: bad request size", __func__);
1827         memcpy(&child_state.outgoing, p, sizeof(child_state.outgoing));
1828         xfree(p);
1829
1830         p = buffer_get_string(&m, &plen);
1831         if (plen != sizeof(child_state.incoming))
1832                 fatal("%s: bad request size", __func__);
1833         memcpy(&child_state.incoming, p, sizeof(child_state.incoming));
1834         xfree(p);
1835
1836         /* Network I/O buffers */
1837         debug3("%s: Getting Network I/O buffers", __func__);
1838         child_state.input = buffer_get_string(&m, &child_state.ilen);
1839         child_state.output = buffer_get_string(&m, &child_state.olen);
1840
1841         /* Roaming */
1842         if (compat20) {
1843                 child_state.sent_bytes = buffer_get_int64(&m);
1844                 child_state.recv_bytes = buffer_get_int64(&m);
1845         }
1846
1847         buffer_free(&m);
1848 }
1849
1850
1851 /* Allocation functions for zlib */
1852 void *
1853 mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
1854 {
1855         size_t len = (size_t) size * ncount;
1856         void *address;
1857
1858         if (len == 0 || ncount > SIZE_T_MAX / size)
1859                 fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
1860
1861         address = mm_malloc(mm, len);
1862
1863         return (address);
1864 }
1865
1866 void
1867 mm_zfree(struct mm_master *mm, void *address)
1868 {
1869         mm_free(mm, address);
1870 }
1871
1872 void
1873 mm_init_compression(struct mm_master *mm)
1874 {
1875         outgoing_stream.zalloc = (alloc_func)mm_zalloc;
1876         outgoing_stream.zfree = (free_func)mm_zfree;
1877         outgoing_stream.opaque = mm;
1878
1879         incoming_stream.zalloc = (alloc_func)mm_zalloc;
1880         incoming_stream.zfree = (free_func)mm_zfree;
1881         incoming_stream.opaque = mm;
1882 }
1883
1884 /* XXX */
1885
1886 #define FD_CLOSEONEXEC(x) do { \
1887         if (fcntl(x, F_SETFD, 1) == -1) \
1888                 fatal("fcntl(%d, F_SETFD)", x); \
1889 } while (0)
1890
1891 static void
1892 monitor_socketpair(int *pair)
1893 {
1894 #ifdef HAVE_SOCKETPAIR
1895         if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1896                 fatal("%s: socketpair", __func__);
1897 #else
1898         fatal("%s: UsePrivilegeSeparation=yes not supported",
1899             __func__);
1900 #endif
1901         FD_CLOSEONEXEC(pair[0]);
1902         FD_CLOSEONEXEC(pair[1]);
1903 }
1904
1905 #define MM_MEMSIZE      65536
1906
1907 struct monitor *
1908 monitor_init(void)
1909 {
1910         struct monitor *mon;
1911         int pair[2];
1912
1913         mon = xcalloc(1, sizeof(*mon));
1914
1915         monitor_socketpair(pair);
1916
1917         mon->m_recvfd = pair[0];
1918         mon->m_sendfd = pair[1];
1919
1920         /* Used to share zlib space across processes */
1921         if (options.compression) {
1922                 mon->m_zback = mm_create(NULL, MM_MEMSIZE);
1923                 mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
1924
1925                 /* Compression needs to share state across borders */
1926                 mm_init_compression(mon->m_zlib);
1927         }
1928
1929         return mon;
1930 }
1931
1932 void
1933 monitor_reinit(struct monitor *mon)
1934 {
1935         int pair[2];
1936
1937         monitor_socketpair(pair);
1938
1939         mon->m_recvfd = pair[0];
1940         mon->m_sendfd = pair[1];
1941 }
1942
1943 #ifdef GSSAPI
1944 int
1945 mm_answer_gss_setup_ctx(int sock, Buffer *m)
1946 {
1947         gss_OID_desc goid;
1948         OM_uint32 major;
1949         u_int len;
1950
1951         if (!options.gss_authentication && !options.gss_keyex)
1952                 fatal("In GSSAPI monitor when GSSAPI is disabled");
1953
1954         goid.elements = buffer_get_string(m, &len);
1955         goid.length = len;
1956
1957         major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1958
1959         xfree(goid.elements);
1960
1961         buffer_clear(m);
1962         buffer_put_int(m, major);
1963
1964         mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1965
1966         /* Now we have a context, enable the step */
1967         monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1968
1969         return (0);
1970 }
1971
1972 int
1973 mm_answer_gss_accept_ctx(int sock, Buffer *m)
1974 {
1975         gss_buffer_desc in;
1976         gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1977         OM_uint32 major, minor;
1978         OM_uint32 flags = 0; /* GSI needs this */
1979         u_int len;
1980
1981         if (!options.gss_authentication && !options.gss_keyex)
1982                 fatal("In GSSAPI monitor when GSSAPI is disabled");
1983
1984         in.value = buffer_get_string(m, &len);
1985         in.length = len;
1986         major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1987         xfree(in.value);
1988
1989         buffer_clear(m);
1990         buffer_put_int(m, major);
1991         buffer_put_string(m, out.value, out.length);
1992         buffer_put_int(m, flags);
1993         mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1994
1995         gss_release_buffer(&minor, &out);
1996
1997         if (major == GSS_S_COMPLETE) {
1998                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1999                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
2000                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
2001                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSIGN, 1);
2002         }
2003         return (0);
2004 }
2005
2006 int
2007 mm_answer_gss_checkmic(int sock, Buffer *m)
2008 {
2009         gss_buffer_desc gssbuf, mic;
2010         OM_uint32 ret;
2011         u_int len;
2012
2013         if (!options.gss_authentication && !options.gss_keyex)
2014                 fatal("In GSSAPI monitor when GSSAPI is disabled");
2015
2016         gssbuf.value = buffer_get_string(m, &len);
2017         gssbuf.length = len;
2018         mic.value = buffer_get_string(m, &len);
2019         mic.length = len;
2020
2021         ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
2022
2023         xfree(gssbuf.value);
2024         xfree(mic.value);
2025
2026         buffer_clear(m);
2027         buffer_put_int(m, ret);
2028
2029         mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
2030
2031         if (!GSS_ERROR(ret))
2032                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
2033
2034         return (0);
2035 }
2036
2037 int
2038 mm_answer_gss_userok(int sock, Buffer *m)
2039 {
2040         int authenticated;
2041
2042         if (!options.gss_authentication && !options.gss_keyex)
2043                 fatal("In GSSAPI monitor when GSSAPI is disabled");
2044
2045         authenticated = authctxt->valid && 
2046             ssh_gssapi_userok(authctxt->user, authctxt->pw);
2047
2048         buffer_clear(m);
2049         buffer_put_int(m, authenticated);
2050
2051         debug3("%s: sending result %d", __func__, authenticated);
2052         mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
2053
2054         auth_method = "gssapi-with-mic";
2055
2056         /* Monitor loop will terminate if authenticated */
2057         return (authenticated);
2058 }
2059
2060 int 
2061 mm_answer_gss_sign(int socket, Buffer *m)
2062 {
2063         gss_buffer_desc data;
2064         gss_buffer_desc hash = GSS_C_EMPTY_BUFFER;
2065         OM_uint32 major, minor;
2066         u_int len;
2067
2068         if (!options.gss_authentication && !options.gss_keyex)
2069                 fatal("In GSSAPI monitor when GSSAPI is disabled");
2070
2071         data.value = buffer_get_string(m, &len);
2072         data.length = len;
2073         if (data.length != 20) 
2074                 fatal("%s: data length incorrect: %d", __func__, 
2075                     (int) data.length);
2076
2077         /* Save the session ID on the first time around */
2078         if (session_id2_len == 0) {
2079                 session_id2_len = data.length;
2080                 session_id2 = xmalloc(session_id2_len);
2081                 memcpy(session_id2, data.value, session_id2_len);
2082         }
2083         major = ssh_gssapi_sign(gsscontext, &data, &hash);
2084
2085         xfree(data.value);
2086
2087         buffer_clear(m);
2088         buffer_put_int(m, major);
2089         buffer_put_string(m, hash.value, hash.length);
2090
2091         mm_request_send(socket, MONITOR_ANS_GSSSIGN, m);
2092
2093         gss_release_buffer(&minor, &hash);
2094
2095         /* Turn on getpwnam permissions */
2096         monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
2097         
2098         /* And credential updating, for when rekeying */
2099         monitor_permit(mon_dispatch, MONITOR_REQ_GSSUPCREDS, 1);
2100
2101         return (0);
2102 }
2103
2104 int
2105 mm_answer_gss_updatecreds(int socket, Buffer *m) {
2106         ssh_gssapi_ccache store;
2107         int ok;
2108
2109         store.filename = buffer_get_string(m, NULL);
2110         store.envvar   = buffer_get_string(m, NULL);
2111         store.envval   = buffer_get_string(m, NULL);
2112
2113         ok = ssh_gssapi_update_creds(&store);
2114
2115         xfree(store.filename);
2116         xfree(store.envvar);
2117         xfree(store.envval);
2118
2119         buffer_clear(m);
2120         buffer_put_int(m, ok);
2121
2122         mm_request_send(socket, MONITOR_ANS_GSSUPCREDS, m);
2123
2124         return(0);
2125 }
2126
2127 #endif /* GSSAPI */
2128
2129 #ifdef JPAKE
2130 int
2131 mm_answer_jpake_step1(int sock, Buffer *m)
2132 {
2133         struct jpake_ctx *pctx;
2134         u_char *x3_proof, *x4_proof;
2135         u_int x3_proof_len, x4_proof_len;
2136
2137         if (!options.zero_knowledge_password_authentication)
2138                 fatal("zero_knowledge_password_authentication disabled");
2139
2140         if (authctxt->jpake_ctx != NULL)
2141                 fatal("%s: authctxt->jpake_ctx already set (%p)",
2142                     __func__, authctxt->jpake_ctx);
2143         authctxt->jpake_ctx = pctx = jpake_new();
2144
2145         jpake_step1(pctx->grp,
2146             &pctx->server_id, &pctx->server_id_len,
2147             &pctx->x3, &pctx->x4, &pctx->g_x3, &pctx->g_x4,
2148             &x3_proof, &x3_proof_len,
2149             &x4_proof, &x4_proof_len);
2150
2151         JPAKE_DEBUG_CTX((pctx, "step1 done in %s", __func__));
2152
2153         buffer_clear(m);
2154
2155         buffer_put_string(m, pctx->server_id, pctx->server_id_len);
2156         buffer_put_bignum2(m, pctx->g_x3);
2157         buffer_put_bignum2(m, pctx->g_x4);
2158         buffer_put_string(m, x3_proof, x3_proof_len);
2159         buffer_put_string(m, x4_proof, x4_proof_len);
2160
2161         debug3("%s: sending step1", __func__);
2162         mm_request_send(sock, MONITOR_ANS_JPAKE_STEP1, m);
2163
2164         bzero(x3_proof, x3_proof_len);
2165         bzero(x4_proof, x4_proof_len);
2166         xfree(x3_proof);
2167         xfree(x4_proof);
2168
2169         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_GET_PWDATA, 1);
2170         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 0);
2171
2172         return 0;
2173 }
2174
2175 int
2176 mm_answer_jpake_get_pwdata(int sock, Buffer *m)
2177 {
2178         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2179         char *hash_scheme, *salt;
2180
2181         if (pctx == NULL)
2182                 fatal("%s: pctx == NULL", __func__);
2183
2184         auth2_jpake_get_pwdata(authctxt, &pctx->s, &hash_scheme, &salt);
2185
2186         buffer_clear(m);
2187         /* pctx->s is sensitive, not returned to slave */
2188         buffer_put_cstring(m, hash_scheme);
2189         buffer_put_cstring(m, salt);
2190
2191         debug3("%s: sending pwdata", __func__);
2192         mm_request_send(sock, MONITOR_ANS_JPAKE_GET_PWDATA, m);
2193
2194         bzero(hash_scheme, strlen(hash_scheme));
2195         bzero(salt, strlen(salt));
2196         xfree(hash_scheme);
2197         xfree(salt);
2198
2199         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP2, 1);
2200
2201         return 0;
2202 }
2203
2204 int
2205 mm_answer_jpake_step2(int sock, Buffer *m)
2206 {
2207         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2208         u_char *x1_proof, *x2_proof, *x4_s_proof;
2209         u_int x1_proof_len, x2_proof_len, x4_s_proof_len;
2210
2211         if (pctx == NULL)
2212                 fatal("%s: pctx == NULL", __func__);
2213
2214         if ((pctx->g_x1 = BN_new()) == NULL ||
2215             (pctx->g_x2 = BN_new()) == NULL)
2216                 fatal("%s: BN_new", __func__);
2217         buffer_get_bignum2(m, pctx->g_x1);
2218         buffer_get_bignum2(m, pctx->g_x2);
2219         pctx->client_id = buffer_get_string(m, &pctx->client_id_len);
2220         x1_proof = buffer_get_string(m, &x1_proof_len);
2221         x2_proof = buffer_get_string(m, &x2_proof_len);
2222
2223         jpake_step2(pctx->grp, pctx->s, pctx->g_x3,
2224             pctx->g_x1, pctx->g_x2, pctx->x4,
2225             pctx->client_id, pctx->client_id_len,
2226             pctx->server_id, pctx->server_id_len,
2227             x1_proof, x1_proof_len,
2228             x2_proof, x2_proof_len,
2229             &pctx->b,
2230             &x4_s_proof, &x4_s_proof_len);
2231
2232         JPAKE_DEBUG_CTX((pctx, "step2 done in %s", __func__));
2233
2234         bzero(x1_proof, x1_proof_len);
2235         bzero(x2_proof, x2_proof_len);
2236         xfree(x1_proof);
2237         xfree(x2_proof);
2238
2239         buffer_clear(m);
2240
2241         buffer_put_bignum2(m, pctx->b);
2242         buffer_put_string(m, x4_s_proof, x4_s_proof_len);
2243
2244         debug3("%s: sending step2", __func__);
2245         mm_request_send(sock, MONITOR_ANS_JPAKE_STEP2, m);
2246
2247         bzero(x4_s_proof, x4_s_proof_len);
2248         xfree(x4_s_proof);
2249
2250         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_KEY_CONFIRM, 1);
2251
2252         return 0;
2253 }
2254
2255 int
2256 mm_answer_jpake_key_confirm(int sock, Buffer *m)
2257 {
2258         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2259         u_char *x2_s_proof;
2260         u_int x2_s_proof_len;
2261
2262         if (pctx == NULL)
2263                 fatal("%s: pctx == NULL", __func__);
2264
2265         if ((pctx->a = BN_new()) == NULL)
2266                 fatal("%s: BN_new", __func__);
2267         buffer_get_bignum2(m, pctx->a);
2268         x2_s_proof = buffer_get_string(m, &x2_s_proof_len);
2269
2270         jpake_key_confirm(pctx->grp, pctx->s, pctx->a,
2271             pctx->x4, pctx->g_x3, pctx->g_x4, pctx->g_x1, pctx->g_x2,
2272             pctx->server_id, pctx->server_id_len,
2273             pctx->client_id, pctx->client_id_len,
2274             session_id2, session_id2_len,
2275             x2_s_proof, x2_s_proof_len,
2276             &pctx->k,
2277             &pctx->h_k_sid_sessid, &pctx->h_k_sid_sessid_len);
2278
2279         JPAKE_DEBUG_CTX((pctx, "key_confirm done in %s", __func__));
2280
2281         bzero(x2_s_proof, x2_s_proof_len);
2282         buffer_clear(m);
2283
2284         /* pctx->k is sensitive, not sent */
2285         buffer_put_string(m, pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len);
2286
2287         debug3("%s: sending confirmation hash", __func__);
2288         mm_request_send(sock, MONITOR_ANS_JPAKE_KEY_CONFIRM, m);
2289
2290         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_CHECK_CONFIRM, 1);
2291
2292         return 0;
2293 }
2294
2295 int
2296 mm_answer_jpake_check_confirm(int sock, Buffer *m)
2297 {
2298         int authenticated = 0;
2299         u_char *peer_confirm_hash;
2300         u_int peer_confirm_hash_len;
2301         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2302
2303         if (pctx == NULL)
2304                 fatal("%s: pctx == NULL", __func__);
2305
2306         peer_confirm_hash = buffer_get_string(m, &peer_confirm_hash_len);
2307
2308         authenticated = jpake_check_confirm(pctx->k,
2309             pctx->client_id, pctx->client_id_len,
2310             session_id2, session_id2_len,
2311             peer_confirm_hash, peer_confirm_hash_len) && authctxt->valid;
2312
2313         JPAKE_DEBUG_CTX((pctx, "check_confirm done in %s", __func__));
2314
2315         bzero(peer_confirm_hash, peer_confirm_hash_len);
2316         xfree(peer_confirm_hash);
2317
2318         buffer_clear(m);
2319         buffer_put_int(m, authenticated);
2320
2321         debug3("%s: sending result %d", __func__, authenticated);
2322         mm_request_send(sock, MONITOR_ANS_JPAKE_CHECK_CONFIRM, m);
2323
2324         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 1);
2325
2326         auth_method = "jpake-01@openssh.com";
2327         return authenticated;
2328 }
2329
2330 #endif /* JPAKE */