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