Add support for mechanisms with no integrity
[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_localname(int, Buffer *);
175 int mm_answer_gss_checkmic(int, Buffer *);
176 int mm_answer_gss_sign(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_AUTH, 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_ISAUTH, 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_GSSLOCALNAME, MON_ISAUTH, mm_answer_gss_localname},
246     {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
247     {MONITOR_REQ_GSSSIGN, MON_ONCE, mm_answer_gss_sign},
248 #endif
249 #ifdef JPAKE
250     {MONITOR_REQ_JPAKE_GET_PWDATA, MON_ONCE, mm_answer_jpake_get_pwdata},
251     {MONITOR_REQ_JPAKE_STEP1, MON_ISAUTH, mm_answer_jpake_step1},
252     {MONITOR_REQ_JPAKE_STEP2, MON_ONCE, mm_answer_jpake_step2},
253     {MONITOR_REQ_JPAKE_KEY_CONFIRM, MON_ONCE, mm_answer_jpake_key_confirm},
254     {MONITOR_REQ_JPAKE_CHECK_CONFIRM, MON_AUTH, mm_answer_jpake_check_confirm},
255 #endif
256     {0, 0, NULL}
257 };
258
259 struct mon_table mon_dispatch_postauth20[] = {
260 #ifdef GSSAPI
261     {MONITOR_REQ_GSSSETUP, 0, mm_answer_gss_setup_ctx},
262     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
263     {MONITOR_REQ_GSSSIGN, 0, mm_answer_gss_sign},
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         username = buffer_get_string(m, NULL);
656
657         pwent = getpwnamallow(username);
658
659         if (authctxt->user) xfree(authctxt->user);
660         authctxt->user = xstrdup(username);
661         setproctitle("%s [priv]", pwent ? username : "unknown");
662         xfree(username);
663
664         buffer_clear(m);
665
666         if (pwent == NULL) {
667                 buffer_put_char(m, 0);
668                 authctxt->pw = fakepw();
669                 goto out;
670         }
671
672         allowed = 1;
673         authctxt->pw = pwent;
674         authctxt->valid = 1;
675
676         buffer_put_char(m, 1);
677         buffer_put_string(m, pwent, sizeof(struct passwd));
678         buffer_put_cstring(m, pwent->pw_name);
679         buffer_put_cstring(m, "*");
680         buffer_put_cstring(m, pwent->pw_gecos);
681 #ifdef HAVE_PW_CLASS_IN_PASSWD
682         buffer_put_cstring(m, pwent->pw_class);
683 #endif
684         buffer_put_cstring(m, pwent->pw_dir);
685         buffer_put_cstring(m, pwent->pw_shell);
686
687  out:
688         buffer_put_string(m, &options, sizeof(options));
689         if (options.banner != NULL)
690                 buffer_put_cstring(m, options.banner);
691         debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
692         mm_request_send(sock, MONITOR_ANS_PWNAM, m);
693
694         /* For SSHv1 allow authentication now */
695         if (!compat20)
696                 monitor_permit_authentications(1);
697         else {
698                 /* Allow service/style information on the auth context */
699                 monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
700                 monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
701         }
702
703 #ifdef USE_PAM
704         if (options.use_pam)
705                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
706 #endif
707
708         return (0);
709 }
710
711 int mm_answer_auth2_read_banner(int sock, Buffer *m)
712 {
713         char *banner;
714
715         buffer_clear(m);
716         banner = auth2_read_banner();
717         buffer_put_cstring(m, banner != NULL ? banner : "");
718         mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
719
720         if (banner != NULL)
721                 xfree(banner);
722
723         return (0);
724 }
725
726 int
727 mm_answer_authserv(int sock, Buffer *m)
728 {
729         monitor_permit_authentications(1);
730
731         authctxt->service = buffer_get_string(m, NULL);
732         authctxt->style = buffer_get_string(m, NULL);
733         debug3("%s: service=%s, style=%s",
734             __func__, authctxt->service, authctxt->style);
735
736         if (strlen(authctxt->style) == 0) {
737                 xfree(authctxt->style);
738                 authctxt->style = NULL;
739         }
740
741         return (0);
742 }
743
744 int
745 mm_answer_authpassword(int sock, Buffer *m)
746 {
747         static int call_count;
748         char *passwd;
749         int authenticated;
750         u_int plen;
751
752         passwd = buffer_get_string(m, &plen);
753         /* Only authenticate if the context is valid */
754         authenticated = options.password_authentication &&
755             auth_password(authctxt, passwd);
756         memset(passwd, 0, strlen(passwd));
757         xfree(passwd);
758
759         buffer_clear(m);
760         buffer_put_int(m, authenticated);
761
762         debug3("%s: sending result %d", __func__, authenticated);
763         mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
764
765         call_count++;
766         if (plen == 0 && call_count == 1)
767                 auth_method = "none";
768         else
769                 auth_method = "password";
770
771         /* Causes monitor loop to terminate if authenticated */
772         return (authenticated);
773 }
774
775 #ifdef BSD_AUTH
776 int
777 mm_answer_bsdauthquery(int sock, Buffer *m)
778 {
779         char *name, *infotxt;
780         u_int numprompts;
781         u_int *echo_on;
782         char **prompts;
783         u_int success;
784
785         success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
786             &prompts, &echo_on) < 0 ? 0 : 1;
787
788         buffer_clear(m);
789         buffer_put_int(m, success);
790         if (success)
791                 buffer_put_cstring(m, prompts[0]);
792
793         debug3("%s: sending challenge success: %u", __func__, success);
794         mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
795
796         if (success) {
797                 xfree(name);
798                 xfree(infotxt);
799                 xfree(prompts);
800                 xfree(echo_on);
801         }
802
803         return (0);
804 }
805
806 int
807 mm_answer_bsdauthrespond(int sock, Buffer *m)
808 {
809         char *response;
810         int authok;
811
812         if (authctxt->as == 0)
813                 fatal("%s: no bsd auth session", __func__);
814
815         response = buffer_get_string(m, NULL);
816         authok = options.challenge_response_authentication &&
817             auth_userresponse(authctxt->as, response, 0);
818         authctxt->as = NULL;
819         debug3("%s: <%s> = <%d>", __func__, response, authok);
820         xfree(response);
821
822         buffer_clear(m);
823         buffer_put_int(m, authok);
824
825         debug3("%s: sending authenticated: %d", __func__, authok);
826         mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
827
828         auth_method = "bsdauth";
829
830         return (authok != 0);
831 }
832 #endif
833
834 #ifdef SKEY
835 int
836 mm_answer_skeyquery(int sock, Buffer *m)
837 {
838         struct skey skey;
839         char challenge[1024];
840         u_int success;
841
842         success = _compat_skeychallenge(&skey, authctxt->user, challenge,
843             sizeof(challenge)) < 0 ? 0 : 1;
844
845         buffer_clear(m);
846         buffer_put_int(m, success);
847         if (success)
848                 buffer_put_cstring(m, challenge);
849
850         debug3("%s: sending challenge success: %u", __func__, success);
851         mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m);
852
853         return (0);
854 }
855
856 int
857 mm_answer_skeyrespond(int sock, Buffer *m)
858 {
859         char *response;
860         int authok;
861
862         response = buffer_get_string(m, NULL);
863
864         authok = (options.challenge_response_authentication &&
865             authctxt->valid &&
866             skey_haskey(authctxt->pw->pw_name) == 0 &&
867             skey_passcheck(authctxt->pw->pw_name, response) != -1);
868
869         xfree(response);
870
871         buffer_clear(m);
872         buffer_put_int(m, authok);
873
874         debug3("%s: sending authenticated: %d", __func__, authok);
875         mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m);
876
877         auth_method = "skey";
878
879         return (authok != 0);
880 }
881 #endif
882
883 #ifdef USE_PAM
884 int
885 mm_answer_pam_start(int sock, Buffer *m)
886 {
887         if (!options.use_pam)
888                 fatal("UsePAM not set, but ended up in %s anyway", __func__);
889
890         start_pam(authctxt);
891
892         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
893
894         return (0);
895 }
896
897 int
898 mm_answer_pam_account(int sock, Buffer *m)
899 {
900         u_int ret;
901
902         if (!options.use_pam)
903                 fatal("UsePAM not set, but ended up in %s anyway", __func__);
904
905         ret = do_pam_account();
906
907         buffer_put_int(m, ret);
908         buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
909
910         mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
911
912         return (ret);
913 }
914
915 static void *sshpam_ctxt, *sshpam_authok;
916 extern KbdintDevice sshpam_device;
917
918 int
919 mm_answer_pam_init_ctx(int sock, Buffer *m)
920 {
921
922         debug3("%s", __func__);
923         authctxt->user = buffer_get_string(m, NULL);
924         sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
925         sshpam_authok = NULL;
926         buffer_clear(m);
927         if (sshpam_ctxt != NULL) {
928                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
929                 buffer_put_int(m, 1);
930         } else {
931                 buffer_put_int(m, 0);
932         }
933         mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
934         return (0);
935 }
936
937 int
938 mm_answer_pam_query(int sock, Buffer *m)
939 {
940         char *name = NULL, *info = NULL, **prompts = NULL;
941         u_int i, num = 0, *echo_on = 0;
942         int ret;
943
944         debug3("%s", __func__);
945         sshpam_authok = NULL;
946         ret = (sshpam_device.query)(sshpam_ctxt, &name, &info, &num, &prompts, &echo_on);
947         if (ret == 0 && num == 0)
948                 sshpam_authok = sshpam_ctxt;
949         if (num > 1 || name == NULL || info == NULL)
950                 ret = -1;
951         buffer_clear(m);
952         buffer_put_int(m, ret);
953         buffer_put_cstring(m, name);
954         xfree(name);
955         buffer_put_cstring(m, info);
956         xfree(info);
957         buffer_put_int(m, num);
958         for (i = 0; i < num; ++i) {
959                 buffer_put_cstring(m, prompts[i]);
960                 xfree(prompts[i]);
961                 buffer_put_int(m, echo_on[i]);
962         }
963         if (prompts != NULL)
964                 xfree(prompts);
965         if (echo_on != NULL)
966                 xfree(echo_on);
967         auth_method = "keyboard-interactive/pam";
968         mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
969         return (0);
970 }
971
972 int
973 mm_answer_pam_respond(int sock, Buffer *m)
974 {
975         char **resp;
976         u_int i, num;
977         int ret;
978
979         debug3("%s", __func__);
980         sshpam_authok = NULL;
981         num = buffer_get_int(m);
982         if (num > 0) {
983                 resp = xcalloc(num, sizeof(char *));
984                 for (i = 0; i < num; ++i)
985                         resp[i] = buffer_get_string(m, NULL);
986                 ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
987                 for (i = 0; i < num; ++i)
988                         xfree(resp[i]);
989                 xfree(resp);
990         } else {
991                 ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
992         }
993         buffer_clear(m);
994         buffer_put_int(m, ret);
995         mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
996         auth_method = "keyboard-interactive/pam";
997         if (ret == 0)
998                 sshpam_authok = sshpam_ctxt;
999         return (0);
1000 }
1001
1002 int
1003 mm_answer_pam_free_ctx(int sock, Buffer *m)
1004 {
1005
1006         debug3("%s", __func__);
1007         (sshpam_device.free_ctx)(sshpam_ctxt);
1008         buffer_clear(m);
1009         mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1010         auth_method = "keyboard-interactive/pam";
1011         return (sshpam_authok == sshpam_ctxt);
1012 }
1013 #endif
1014
1015 int
1016 mm_answer_keyallowed(int sock, Buffer *m)
1017 {
1018         Key *key;
1019         char *cuser, *chost;
1020         u_char *blob;
1021         u_int bloblen;
1022         enum mm_keytype type = 0;
1023         int allowed = 0;
1024
1025         debug3("%s entering", __func__);
1026
1027         type = buffer_get_int(m);
1028         cuser = buffer_get_string(m, NULL);
1029         chost = buffer_get_string(m, NULL);
1030         blob = buffer_get_string(m, &bloblen);
1031
1032         key = key_from_blob(blob, bloblen);
1033
1034         if ((compat20 && type == MM_RSAHOSTKEY) ||
1035             (!compat20 && type != MM_RSAHOSTKEY))
1036                 fatal("%s: key type and protocol mismatch", __func__);
1037
1038         debug3("%s: key_from_blob: %p", __func__, key);
1039
1040         if (key != NULL && authctxt->valid) {
1041                 switch (type) {
1042                 case MM_USERKEY:
1043                         allowed = options.pubkey_authentication &&
1044                             user_key_allowed(authctxt->pw, key);
1045                         auth_method = "publickey";
1046                         if (options.pubkey_authentication && allowed != 1)
1047                                 auth_clear_options();
1048                         break;
1049                 case MM_HOSTKEY:
1050                         allowed = options.hostbased_authentication &&
1051                             hostbased_key_allowed(authctxt->pw,
1052                             cuser, chost, key);
1053                         auth_method = "hostbased";
1054                         break;
1055                 case MM_RSAHOSTKEY:
1056                         key->type = KEY_RSA1; /* XXX */
1057                         allowed = options.rhosts_rsa_authentication &&
1058                             auth_rhosts_rsa_key_allowed(authctxt->pw,
1059                             cuser, chost, key);
1060                         if (options.rhosts_rsa_authentication && allowed != 1)
1061                                 auth_clear_options();
1062                         auth_method = "rsa";
1063                         break;
1064                 default:
1065                         fatal("%s: unknown key type %d", __func__, type);
1066                         break;
1067                 }
1068         }
1069         if (key != NULL)
1070                 key_free(key);
1071
1072         /* clear temporarily storage (used by verify) */
1073         monitor_reset_key_state();
1074
1075         if (allowed) {
1076                 /* Save temporarily for comparison in verify */
1077                 key_blob = blob;
1078                 key_bloblen = bloblen;
1079                 key_blobtype = type;
1080                 hostbased_cuser = cuser;
1081                 hostbased_chost = chost;
1082         } else {
1083                 /* Log failed attempt */
1084                 auth_log(authctxt, 0, auth_method, compat20 ? " ssh2" : "");
1085                 xfree(blob);
1086                 xfree(cuser);
1087                 xfree(chost);
1088         }
1089
1090         debug3("%s: key %p is %s",
1091             __func__, key, allowed ? "allowed" : "not allowed");
1092
1093         buffer_clear(m);
1094         buffer_put_int(m, allowed);
1095         buffer_put_int(m, forced_command != NULL);
1096
1097         mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1098
1099         if (type == MM_RSAHOSTKEY)
1100                 monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1101
1102         return (0);
1103 }
1104
1105 static int
1106 monitor_valid_userblob(u_char *data, u_int datalen)
1107 {
1108         Buffer b;
1109         char *p;
1110         u_int len;
1111         int fail = 0;
1112
1113         buffer_init(&b);
1114         buffer_append(&b, data, datalen);
1115
1116         if (datafellows & SSH_OLD_SESSIONID) {
1117                 p = buffer_ptr(&b);
1118                 len = buffer_len(&b);
1119                 if ((session_id2 == NULL) ||
1120                     (len < session_id2_len) ||
1121                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1122                         fail++;
1123                 buffer_consume(&b, session_id2_len);
1124         } else {
1125                 p = buffer_get_string(&b, &len);
1126                 if ((session_id2 == NULL) ||
1127                     (len != session_id2_len) ||
1128                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1129                         fail++;
1130                 xfree(p);
1131         }
1132         if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1133                 fail++;
1134         p = buffer_get_string(&b, NULL);
1135         if (strcmp(authctxt->user, p) != 0) {
1136                 logit("wrong user name passed to monitor: expected %s != %.100s",
1137                     authctxt->user, p);
1138                 fail++;
1139         }
1140         xfree(p);
1141         buffer_skip_string(&b);
1142         if (datafellows & SSH_BUG_PKAUTH) {
1143                 if (!buffer_get_char(&b))
1144                         fail++;
1145         } else {
1146                 p = buffer_get_string(&b, NULL);
1147                 if (strcmp("publickey", p) != 0)
1148                         fail++;
1149                 xfree(p);
1150                 if (!buffer_get_char(&b))
1151                         fail++;
1152                 buffer_skip_string(&b);
1153         }
1154         buffer_skip_string(&b);
1155         if (buffer_len(&b) != 0)
1156                 fail++;
1157         buffer_free(&b);
1158         return (fail == 0);
1159 }
1160
1161 static int
1162 monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
1163     char *chost)
1164 {
1165         Buffer b;
1166         char *p;
1167         u_int len;
1168         int fail = 0;
1169
1170         buffer_init(&b);
1171         buffer_append(&b, data, datalen);
1172
1173         p = buffer_get_string(&b, &len);
1174         if ((session_id2 == NULL) ||
1175             (len != session_id2_len) ||
1176             (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1177                 fail++;
1178         xfree(p);
1179
1180         if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1181                 fail++;
1182         p = buffer_get_string(&b, NULL);
1183         if (strcmp(authctxt->user, p) != 0) {
1184                 logit("wrong user name passed to monitor: expected %s != %.100s",
1185                     authctxt->user, p);
1186                 fail++;
1187         }
1188         xfree(p);
1189         buffer_skip_string(&b); /* service */
1190         p = buffer_get_string(&b, NULL);
1191         if (strcmp(p, "hostbased") != 0)
1192                 fail++;
1193         xfree(p);
1194         buffer_skip_string(&b); /* pkalg */
1195         buffer_skip_string(&b); /* pkblob */
1196
1197         /* verify client host, strip trailing dot if necessary */
1198         p = buffer_get_string(&b, NULL);
1199         if (((len = strlen(p)) > 0) && p[len - 1] == '.')
1200                 p[len - 1] = '\0';
1201         if (strcmp(p, chost) != 0)
1202                 fail++;
1203         xfree(p);
1204
1205         /* verify client user */
1206         p = buffer_get_string(&b, NULL);
1207         if (strcmp(p, cuser) != 0)
1208                 fail++;
1209         xfree(p);
1210
1211         if (buffer_len(&b) != 0)
1212                 fail++;
1213         buffer_free(&b);
1214         return (fail == 0);
1215 }
1216
1217 int
1218 mm_answer_keyverify(int sock, Buffer *m)
1219 {
1220         Key *key;
1221         u_char *signature, *data, *blob;
1222         u_int signaturelen, datalen, bloblen;
1223         int verified = 0;
1224         int valid_data = 0;
1225
1226         blob = buffer_get_string(m, &bloblen);
1227         signature = buffer_get_string(m, &signaturelen);
1228         data = buffer_get_string(m, &datalen);
1229
1230         if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1231           !monitor_allowed_key(blob, bloblen))
1232                 fatal("%s: bad key, not previously allowed", __func__);
1233
1234         key = key_from_blob(blob, bloblen);
1235         if (key == NULL)
1236                 fatal("%s: bad public key blob", __func__);
1237
1238         switch (key_blobtype) {
1239         case MM_USERKEY:
1240                 valid_data = monitor_valid_userblob(data, datalen);
1241                 break;
1242         case MM_HOSTKEY:
1243                 valid_data = monitor_valid_hostbasedblob(data, datalen,
1244                     hostbased_cuser, hostbased_chost);
1245                 break;
1246         default:
1247                 valid_data = 0;
1248                 break;
1249         }
1250         if (!valid_data)
1251                 fatal("%s: bad signature data blob", __func__);
1252
1253         verified = key_verify(key, signature, signaturelen, data, datalen);
1254         debug3("%s: key %p signature %s",
1255             __func__, key, (verified == 1) ? "verified" : "unverified");
1256
1257         key_free(key);
1258         xfree(blob);
1259         xfree(signature);
1260         xfree(data);
1261
1262         auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
1263
1264         monitor_reset_key_state();
1265
1266         buffer_clear(m);
1267         buffer_put_int(m, verified);
1268         mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1269
1270         return (verified == 1);
1271 }
1272
1273 static void
1274 mm_record_login(Session *s, struct passwd *pw)
1275 {
1276         socklen_t fromlen;
1277         struct sockaddr_storage from;
1278
1279         /*
1280          * Get IP address of client. If the connection is not a socket, let
1281          * the address be 0.0.0.0.
1282          */
1283         memset(&from, 0, sizeof(from));
1284         fromlen = sizeof(from);
1285         if (packet_connection_is_on_socket()) {
1286                 if (getpeername(packet_get_connection_in(),
1287                     (struct sockaddr *)&from, &fromlen) < 0) {
1288                         debug("getpeername: %.100s", strerror(errno));
1289                         cleanup_exit(255);
1290                 }
1291         }
1292         /* Record that there was a login on that tty from the remote host. */
1293         record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1294             get_remote_name_or_ip(utmp_len, options.use_dns),
1295             (struct sockaddr *)&from, fromlen);
1296 }
1297
1298 static void
1299 mm_session_close(Session *s)
1300 {
1301         debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1302         if (s->ttyfd != -1) {
1303                 debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1304                 session_pty_cleanup2(s);
1305         }
1306         session_unused(s->self);
1307 }
1308
1309 int
1310 mm_answer_pty(int sock, Buffer *m)
1311 {
1312         extern struct monitor *pmonitor;
1313         Session *s;
1314         int res, fd0;
1315
1316         debug3("%s entering", __func__);
1317
1318         buffer_clear(m);
1319         s = session_new();
1320         if (s == NULL)
1321                 goto error;
1322         s->authctxt = authctxt;
1323         s->pw = authctxt->pw;
1324         s->pid = pmonitor->m_pid;
1325         res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1326         if (res == 0)
1327                 goto error;
1328         pty_setowner(authctxt->pw, s->tty);
1329
1330         buffer_put_int(m, 1);
1331         buffer_put_cstring(m, s->tty);
1332
1333         /* We need to trick ttyslot */
1334         if (dup2(s->ttyfd, 0) == -1)
1335                 fatal("%s: dup2", __func__);
1336
1337         mm_record_login(s, authctxt->pw);
1338
1339         /* Now we can close the file descriptor again */
1340         close(0);
1341
1342         /* send messages generated by record_login */
1343         buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1344         buffer_clear(&loginmsg);
1345
1346         mm_request_send(sock, MONITOR_ANS_PTY, m);
1347
1348         if (mm_send_fd(sock, s->ptyfd) == -1 ||
1349             mm_send_fd(sock, s->ttyfd) == -1)
1350                 fatal("%s: send fds failed", __func__);
1351
1352         /* make sure nothing uses fd 0 */
1353         if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1354                 fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1355         if (fd0 != 0)
1356                 error("%s: fd0 %d != 0", __func__, fd0);
1357
1358         /* slave is not needed */
1359         close(s->ttyfd);
1360         s->ttyfd = s->ptyfd;
1361         /* no need to dup() because nobody closes ptyfd */
1362         s->ptymaster = s->ptyfd;
1363
1364         debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1365
1366         return (0);
1367
1368  error:
1369         if (s != NULL)
1370                 mm_session_close(s);
1371         buffer_put_int(m, 0);
1372         mm_request_send(sock, MONITOR_ANS_PTY, m);
1373         return (0);
1374 }
1375
1376 int
1377 mm_answer_pty_cleanup(int sock, Buffer *m)
1378 {
1379         Session *s;
1380         char *tty;
1381
1382         debug3("%s entering", __func__);
1383
1384         tty = buffer_get_string(m, NULL);
1385         if ((s = session_by_tty(tty)) != NULL)
1386                 mm_session_close(s);
1387         buffer_clear(m);
1388         xfree(tty);
1389         return (0);
1390 }
1391
1392 int
1393 mm_answer_sesskey(int sock, Buffer *m)
1394 {
1395         BIGNUM *p;
1396         int rsafail;
1397
1398         /* Turn off permissions */
1399         monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0);
1400
1401         if ((p = BN_new()) == NULL)
1402                 fatal("%s: BN_new", __func__);
1403
1404         buffer_get_bignum2(m, p);
1405
1406         rsafail = ssh1_session_key(p);
1407
1408         buffer_clear(m);
1409         buffer_put_int(m, rsafail);
1410         buffer_put_bignum2(m, p);
1411
1412         BN_clear_free(p);
1413
1414         mm_request_send(sock, MONITOR_ANS_SESSKEY, m);
1415
1416         /* Turn on permissions for sessid passing */
1417         monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1);
1418
1419         return (0);
1420 }
1421
1422 int
1423 mm_answer_sessid(int sock, Buffer *m)
1424 {
1425         int i;
1426
1427         debug3("%s entering", __func__);
1428
1429         if (buffer_len(m) != 16)
1430                 fatal("%s: bad ssh1 session id", __func__);
1431         for (i = 0; i < 16; i++)
1432                 session_id[i] = buffer_get_char(m);
1433
1434         /* Turn on permissions for getpwnam */
1435         monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
1436
1437         return (0);
1438 }
1439
1440 int
1441 mm_answer_rsa_keyallowed(int sock, Buffer *m)
1442 {
1443         BIGNUM *client_n;
1444         Key *key = NULL;
1445         u_char *blob = NULL;
1446         u_int blen = 0;
1447         int allowed = 0;
1448
1449         debug3("%s entering", __func__);
1450
1451         auth_method = "rsa";
1452         if (options.rsa_authentication && authctxt->valid) {
1453                 if ((client_n = BN_new()) == NULL)
1454                         fatal("%s: BN_new", __func__);
1455                 buffer_get_bignum2(m, client_n);
1456                 allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key);
1457                 BN_clear_free(client_n);
1458         }
1459         buffer_clear(m);
1460         buffer_put_int(m, allowed);
1461         buffer_put_int(m, forced_command != NULL);
1462
1463         /* clear temporarily storage (used by generate challenge) */
1464         monitor_reset_key_state();
1465
1466         if (allowed && key != NULL) {
1467                 key->type = KEY_RSA;    /* cheat for key_to_blob */
1468                 if (key_to_blob(key, &blob, &blen) == 0)
1469                         fatal("%s: key_to_blob failed", __func__);
1470                 buffer_put_string(m, blob, blen);
1471
1472                 /* Save temporarily for comparison in verify */
1473                 key_blob = blob;
1474                 key_bloblen = blen;
1475                 key_blobtype = MM_RSAUSERKEY;
1476         }
1477         if (key != NULL)
1478                 key_free(key);
1479
1480         mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m);
1481
1482         monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1483         monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0);
1484         return (0);
1485 }
1486
1487 int
1488 mm_answer_rsa_challenge(int sock, Buffer *m)
1489 {
1490         Key *key = NULL;
1491         u_char *blob;
1492         u_int blen;
1493
1494         debug3("%s entering", __func__);
1495
1496         if (!authctxt->valid)
1497                 fatal("%s: authctxt not valid", __func__);
1498         blob = buffer_get_string(m, &blen);
1499         if (!monitor_allowed_key(blob, blen))
1500                 fatal("%s: bad key, not previously allowed", __func__);
1501         if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1502                 fatal("%s: key type mismatch", __func__);
1503         if ((key = key_from_blob(blob, blen)) == NULL)
1504                 fatal("%s: received bad key", __func__);
1505         if (key->type != KEY_RSA)
1506                 fatal("%s: received bad key type %d", __func__, key->type);
1507         key->type = KEY_RSA1;
1508         if (ssh1_challenge)
1509                 BN_clear_free(ssh1_challenge);
1510         ssh1_challenge = auth_rsa_generate_challenge(key);
1511
1512         buffer_clear(m);
1513         buffer_put_bignum2(m, ssh1_challenge);
1514
1515         debug3("%s sending reply", __func__);
1516         mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);
1517
1518         monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);
1519
1520         xfree(blob);
1521         key_free(key);
1522         return (0);
1523 }
1524
1525 int
1526 mm_answer_rsa_response(int sock, Buffer *m)
1527 {
1528         Key *key = NULL;
1529         u_char *blob, *response;
1530         u_int blen, len;
1531         int success;
1532
1533         debug3("%s entering", __func__);
1534
1535         if (!authctxt->valid)
1536                 fatal("%s: authctxt not valid", __func__);
1537         if (ssh1_challenge == NULL)
1538                 fatal("%s: no ssh1_challenge", __func__);
1539
1540         blob = buffer_get_string(m, &blen);
1541         if (!monitor_allowed_key(blob, blen))
1542                 fatal("%s: bad key, not previously allowed", __func__);
1543         if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1544                 fatal("%s: key type mismatch: %d", __func__, key_blobtype);
1545         if ((key = key_from_blob(blob, blen)) == NULL)
1546                 fatal("%s: received bad key", __func__);
1547         response = buffer_get_string(m, &len);
1548         if (len != 16)
1549                 fatal("%s: received bad response to challenge", __func__);
1550         success = auth_rsa_verify_response(key, ssh1_challenge, response);
1551
1552         xfree(blob);
1553         key_free(key);
1554         xfree(response);
1555
1556         auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa";
1557
1558         /* reset state */
1559         BN_clear_free(ssh1_challenge);
1560         ssh1_challenge = NULL;
1561         monitor_reset_key_state();
1562
1563         buffer_clear(m);
1564         buffer_put_int(m, success);
1565         mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m);
1566
1567         return (success);
1568 }
1569
1570 int
1571 mm_answer_term(int sock, Buffer *req)
1572 {
1573         extern struct monitor *pmonitor;
1574         int res, status;
1575
1576         debug3("%s: tearing down sessions", __func__);
1577
1578         /* The child is terminating */
1579         session_destroy_all(&mm_session_close);
1580
1581 #ifdef USE_PAM
1582         if (options.use_pam)
1583                 sshpam_cleanup();
1584 #endif
1585
1586         while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1587                 if (errno != EINTR)
1588                         exit(1);
1589
1590         res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1591
1592         /* Terminate process */
1593         exit(res);
1594 }
1595
1596 #ifdef SSH_AUDIT_EVENTS
1597 /* Report that an audit event occurred */
1598 int
1599 mm_answer_audit_event(int socket, Buffer *m)
1600 {
1601         ssh_audit_event_t event;
1602
1603         debug3("%s entering", __func__);
1604
1605         event = buffer_get_int(m);
1606         switch(event) {
1607         case SSH_AUTH_FAIL_PUBKEY:
1608         case SSH_AUTH_FAIL_HOSTBASED:
1609         case SSH_AUTH_FAIL_GSSAPI:
1610         case SSH_LOGIN_EXCEED_MAXTRIES:
1611         case SSH_LOGIN_ROOT_DENIED:
1612         case SSH_CONNECTION_CLOSE:
1613         case SSH_INVALID_USER:
1614                 audit_event(event);
1615                 break;
1616         default:
1617                 fatal("Audit event type %d not permitted", event);
1618         }
1619
1620         return (0);
1621 }
1622
1623 int
1624 mm_answer_audit_command(int socket, Buffer *m)
1625 {
1626         u_int len;
1627         char *cmd;
1628
1629         debug3("%s entering", __func__);
1630         cmd = buffer_get_string(m, &len);
1631         /* sanity check command, if so how? */
1632         audit_run_command(cmd);
1633         xfree(cmd);
1634         return (0);
1635 }
1636 #endif /* SSH_AUDIT_EVENTS */
1637
1638 void
1639 monitor_apply_keystate(struct monitor *pmonitor)
1640 {
1641         if (compat20) {
1642                 set_newkeys(MODE_IN);
1643                 set_newkeys(MODE_OUT);
1644         } else {
1645                 packet_set_protocol_flags(child_state.ssh1protoflags);
1646                 packet_set_encryption_key(child_state.ssh1key,
1647                     child_state.ssh1keylen, child_state.ssh1cipher);
1648                 xfree(child_state.ssh1key);
1649         }
1650
1651         /* for rc4 and other stateful ciphers */
1652         packet_set_keycontext(MODE_OUT, child_state.keyout);
1653         xfree(child_state.keyout);
1654         packet_set_keycontext(MODE_IN, child_state.keyin);
1655         xfree(child_state.keyin);
1656
1657         if (!compat20) {
1658                 packet_set_iv(MODE_OUT, child_state.ivout);
1659                 xfree(child_state.ivout);
1660                 packet_set_iv(MODE_IN, child_state.ivin);
1661                 xfree(child_state.ivin);
1662         }
1663
1664         memcpy(&incoming_stream, &child_state.incoming,
1665             sizeof(incoming_stream));
1666         memcpy(&outgoing_stream, &child_state.outgoing,
1667             sizeof(outgoing_stream));
1668
1669         /* Update with new address */
1670         if (options.compression)
1671                 mm_init_compression(pmonitor->m_zlib);
1672
1673         /* Network I/O buffers */
1674         /* XXX inefficient for large buffers, need: buffer_init_from_string */
1675         buffer_clear(packet_get_input());
1676         buffer_append(packet_get_input(), child_state.input, child_state.ilen);
1677         memset(child_state.input, 0, child_state.ilen);
1678         xfree(child_state.input);
1679
1680         buffer_clear(packet_get_output());
1681         buffer_append(packet_get_output(), child_state.output,
1682                       child_state.olen);
1683         memset(child_state.output, 0, child_state.olen);
1684         xfree(child_state.output);
1685
1686         /* Roaming */
1687         if (compat20)
1688                 roam_set_bytes(child_state.sent_bytes, child_state.recv_bytes);
1689 }
1690
1691 static Kex *
1692 mm_get_kex(Buffer *m)
1693 {
1694         Kex *kex;
1695         void *blob;
1696         u_int bloblen;
1697
1698         kex = xcalloc(1, sizeof(*kex));
1699         kex->session_id = buffer_get_string(m, &kex->session_id_len);
1700         if (session_id2 == NULL ||
1701             kex->session_id_len != session_id2_len ||
1702             timingsafe_bcmp(kex->session_id, session_id2, session_id2_len) != 0)
1703                 fatal("mm_get_get: internal error: bad session id");
1704         kex->we_need = buffer_get_int(m);
1705         kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1706         kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1707         kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1708         kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1709         kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1710 #ifdef GSSAPI
1711         if (options.gss_keyex) {
1712                 kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
1713                 kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
1714                 kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
1715         }
1716 #endif
1717         kex->server = 1;
1718         kex->hostkey_type = buffer_get_int(m);
1719         kex->kex_type = buffer_get_int(m);
1720         blob = buffer_get_string(m, &bloblen);
1721         buffer_init(&kex->my);
1722         buffer_append(&kex->my, blob, bloblen);
1723         xfree(blob);
1724         blob = buffer_get_string(m, &bloblen);
1725         buffer_init(&kex->peer);
1726         buffer_append(&kex->peer, blob, bloblen);
1727         xfree(blob);
1728         kex->done = 1;
1729         kex->flags = buffer_get_int(m);
1730         kex->client_version_string = buffer_get_string(m, NULL);
1731         kex->server_version_string = buffer_get_string(m, NULL);
1732         kex->load_host_public_key=&get_hostkey_public_by_type;
1733         kex->load_host_private_key=&get_hostkey_private_by_type;
1734         kex->host_key_index=&get_hostkey_index;
1735
1736         return (kex);
1737 }
1738
1739 /* This function requries careful sanity checking */
1740
1741 void
1742 mm_get_keystate(struct monitor *pmonitor)
1743 {
1744         Buffer m;
1745         u_char *blob, *p;
1746         u_int bloblen, plen;
1747         u_int32_t seqnr, packets;
1748         u_int64_t blocks, bytes;
1749
1750         debug3("%s: Waiting for new keys", __func__);
1751
1752         buffer_init(&m);
1753         mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT, &m);
1754         if (!compat20) {
1755                 child_state.ssh1protoflags = buffer_get_int(&m);
1756                 child_state.ssh1cipher = buffer_get_int(&m);
1757                 child_state.ssh1key = buffer_get_string(&m,
1758                     &child_state.ssh1keylen);
1759                 child_state.ivout = buffer_get_string(&m,
1760                     &child_state.ivoutlen);
1761                 child_state.ivin = buffer_get_string(&m, &child_state.ivinlen);
1762                 goto skip;
1763         } else {
1764                 /* Get the Kex for rekeying */
1765                 *pmonitor->m_pkex = mm_get_kex(&m);
1766         }
1767
1768         blob = buffer_get_string(&m, &bloblen);
1769         current_keys[MODE_OUT] = mm_newkeys_from_blob(blob, bloblen);
1770         xfree(blob);
1771
1772         debug3("%s: Waiting for second key", __func__);
1773         blob = buffer_get_string(&m, &bloblen);
1774         current_keys[MODE_IN] = mm_newkeys_from_blob(blob, bloblen);
1775         xfree(blob);
1776
1777         /* Now get sequence numbers for the packets */
1778         seqnr = buffer_get_int(&m);
1779         blocks = buffer_get_int64(&m);
1780         packets = buffer_get_int(&m);
1781         bytes = buffer_get_int64(&m);
1782         packet_set_state(MODE_OUT, seqnr, blocks, packets, bytes);
1783         seqnr = buffer_get_int(&m);
1784         blocks = buffer_get_int64(&m);
1785         packets = buffer_get_int(&m);
1786         bytes = buffer_get_int64(&m);
1787         packet_set_state(MODE_IN, seqnr, blocks, packets, bytes);
1788
1789  skip:
1790         /* Get the key context */
1791         child_state.keyout = buffer_get_string(&m, &child_state.keyoutlen);
1792         child_state.keyin  = buffer_get_string(&m, &child_state.keyinlen);
1793
1794         debug3("%s: Getting compression state", __func__);
1795         /* Get compression state */
1796         p = buffer_get_string(&m, &plen);
1797         if (plen != sizeof(child_state.outgoing))
1798                 fatal("%s: bad request size", __func__);
1799         memcpy(&child_state.outgoing, p, sizeof(child_state.outgoing));
1800         xfree(p);
1801
1802         p = buffer_get_string(&m, &plen);
1803         if (plen != sizeof(child_state.incoming))
1804                 fatal("%s: bad request size", __func__);
1805         memcpy(&child_state.incoming, p, sizeof(child_state.incoming));
1806         xfree(p);
1807
1808         /* Network I/O buffers */
1809         debug3("%s: Getting Network I/O buffers", __func__);
1810         child_state.input = buffer_get_string(&m, &child_state.ilen);
1811         child_state.output = buffer_get_string(&m, &child_state.olen);
1812
1813         /* Roaming */
1814         if (compat20) {
1815                 child_state.sent_bytes = buffer_get_int64(&m);
1816                 child_state.recv_bytes = buffer_get_int64(&m);
1817         }
1818
1819         buffer_free(&m);
1820 }
1821
1822
1823 /* Allocation functions for zlib */
1824 void *
1825 mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
1826 {
1827         size_t len = (size_t) size * ncount;
1828         void *address;
1829
1830         if (len == 0 || ncount > SIZE_T_MAX / size)
1831                 fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
1832
1833         address = mm_malloc(mm, len);
1834
1835         return (address);
1836 }
1837
1838 void
1839 mm_zfree(struct mm_master *mm, void *address)
1840 {
1841         mm_free(mm, address);
1842 }
1843
1844 void
1845 mm_init_compression(struct mm_master *mm)
1846 {
1847         outgoing_stream.zalloc = (alloc_func)mm_zalloc;
1848         outgoing_stream.zfree = (free_func)mm_zfree;
1849         outgoing_stream.opaque = mm;
1850
1851         incoming_stream.zalloc = (alloc_func)mm_zalloc;
1852         incoming_stream.zfree = (free_func)mm_zfree;
1853         incoming_stream.opaque = mm;
1854 }
1855
1856 /* XXX */
1857
1858 #define FD_CLOSEONEXEC(x) do { \
1859         if (fcntl(x, F_SETFD, 1) == -1) \
1860                 fatal("fcntl(%d, F_SETFD)", x); \
1861 } while (0)
1862
1863 static void
1864 monitor_socketpair(int *pair)
1865 {
1866 #ifdef HAVE_SOCKETPAIR
1867         if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1868                 fatal("%s: socketpair", __func__);
1869 #else
1870         fatal("%s: UsePrivilegeSeparation=yes not supported",
1871             __func__);
1872 #endif
1873         FD_CLOSEONEXEC(pair[0]);
1874         FD_CLOSEONEXEC(pair[1]);
1875 }
1876
1877 #define MM_MEMSIZE      65536
1878
1879 struct monitor *
1880 monitor_init(void)
1881 {
1882         struct monitor *mon;
1883         int pair[2];
1884
1885         mon = xcalloc(1, sizeof(*mon));
1886
1887         monitor_socketpair(pair);
1888
1889         mon->m_recvfd = pair[0];
1890         mon->m_sendfd = pair[1];
1891
1892         /* Used to share zlib space across processes */
1893         if (options.compression) {
1894                 mon->m_zback = mm_create(NULL, MM_MEMSIZE);
1895                 mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
1896
1897                 /* Compression needs to share state across borders */
1898                 mm_init_compression(mon->m_zlib);
1899         }
1900
1901         return mon;
1902 }
1903
1904 void
1905 monitor_reinit(struct monitor *mon)
1906 {
1907         int pair[2];
1908
1909         monitor_socketpair(pair);
1910
1911         mon->m_recvfd = pair[0];
1912         mon->m_sendfd = pair[1];
1913 }
1914
1915 #ifdef GSSAPI
1916 int
1917 mm_answer_gss_setup_ctx(int sock, Buffer *m)
1918 {
1919         gss_OID_desc goid;
1920         OM_uint32 major;
1921         u_int len;
1922
1923         if (!options.gss_authentication && !options.gss_keyex)
1924                 fatal("In GSSAPI monitor when GSSAPI is disabled");
1925
1926         goid.elements = buffer_get_string(m, &len);
1927         goid.length = len;
1928
1929         major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1930
1931         xfree(goid.elements);
1932
1933         buffer_clear(m);
1934         buffer_put_int(m, major);
1935
1936         mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1937
1938         /* Now we have a context, enable the step */
1939         monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1940
1941         return (0);
1942 }
1943
1944 int
1945 mm_answer_gss_accept_ctx(int sock, Buffer *m)
1946 {
1947         gss_buffer_desc in;
1948         gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1949         OM_uint32 major, minor;
1950         OM_uint32 flags = 0; /* GSI needs this */
1951         u_int len;
1952
1953         if (!options.gss_authentication && !options.gss_keyex)
1954                 fatal("In GSSAPI monitor when GSSAPI is disabled");
1955
1956         in.value = buffer_get_string(m, &len);
1957         in.length = len;
1958         major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1959         xfree(in.value);
1960
1961         buffer_clear(m);
1962         buffer_put_int(m, major);
1963         buffer_put_string(m, out.value, out.length);
1964         buffer_put_int(m, flags);
1965         mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1966
1967         gss_release_buffer(&minor, &out);
1968
1969         if (major == GSS_S_COMPLETE) {
1970                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1971                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1972                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1973                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSIGN, 1);
1974         }
1975         return (0);
1976 }
1977
1978 int
1979 mm_answer_gss_checkmic(int sock, Buffer *m)
1980 {
1981         gss_buffer_desc gssbuf, mic;
1982         OM_uint32 ret;
1983         u_int len;
1984
1985         if (!options.gss_authentication && !options.gss_keyex)
1986                 fatal("In GSSAPI monitor when GSSAPI is disabled");
1987
1988         gssbuf.value = buffer_get_string(m, &len);
1989         gssbuf.length = len;
1990         mic.value = buffer_get_string(m, &len);
1991         mic.length = len;
1992
1993         ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1994
1995         xfree(gssbuf.value);
1996         xfree(mic.value);
1997
1998         buffer_clear(m);
1999         buffer_put_int(m, ret);
2000
2001         mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
2002
2003         if (!GSS_ERROR(ret))
2004                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
2005
2006         return (0);
2007 }
2008
2009 int
2010 mm_answer_gss_userok(int sock, Buffer *m)
2011 {
2012         int authenticated;
2013
2014         if (!options.gss_authentication && !options.gss_keyex)
2015                 fatal("In GSSAPI monitor when GSSAPI is disabled");
2016
2017         authenticated = authctxt->valid && 
2018             ssh_gssapi_userok(authctxt->user, authctxt->pw);
2019
2020         buffer_clear(m);
2021         buffer_put_int(m, authenticated);
2022
2023         debug3("%s: sending result %d", __func__, authenticated);
2024         mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
2025
2026         auth_method = "gssapi-with-mic";
2027
2028         /* Monitor loop will terminate if authenticated */
2029         return (authenticated);
2030 }
2031
2032 int
2033 mm_answer_gss_localname(int socket, Buffer *m) {
2034         char *name;
2035
2036         ssh_gssapi_localname(&name);
2037
2038     buffer_clear(m);
2039         if (name) {
2040             buffer_put_cstring(m, name);
2041             debug3("%s: sending result %s", __func__, name);
2042             xfree(name);
2043         } else {
2044             buffer_put_cstring(m, "");
2045             debug3("%s: sending result \"\"", __func__);
2046         }
2047
2048     mm_request_send(socket, MONITOR_ANS_GSSLOCALNAME, m);
2049
2050     return(0);
2051 }
2052
2053 int 
2054 mm_answer_gss_sign(int socket, Buffer *m)
2055 {
2056         gss_buffer_desc data;
2057         gss_buffer_desc hash = GSS_C_EMPTY_BUFFER;
2058         OM_uint32 major, minor;
2059         u_int len;
2060
2061         if (!options.gss_authentication && !options.gss_keyex)
2062                 fatal("In GSSAPI monitor when GSSAPI is disabled");
2063
2064         data.value = buffer_get_string(m, &len);
2065         data.length = len;
2066         if (data.length != 20) 
2067                 fatal("%s: data length incorrect: %d", __func__, 
2068                     (int) data.length);
2069
2070         /* Save the session ID on the first time around */
2071         if (session_id2_len == 0) {
2072                 session_id2_len = data.length;
2073                 session_id2 = xmalloc(session_id2_len);
2074                 memcpy(session_id2, data.value, session_id2_len);
2075         }
2076         major = ssh_gssapi_sign(gsscontext, &data, &hash);
2077
2078         xfree(data.value);
2079
2080         buffer_clear(m);
2081         buffer_put_int(m, major);
2082         buffer_put_string(m, hash.value, hash.length);
2083
2084         mm_request_send(socket, MONITOR_ANS_GSSSIGN, m);
2085
2086         gss_release_buffer(&minor, &hash);
2087
2088         /* Turn on getpwnam permissions */
2089         monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
2090         
2091         /* And credential updating, for when rekeying */
2092         monitor_permit(mon_dispatch, MONITOR_REQ_GSSUPCREDS, 1);
2093
2094         return (0);
2095 }
2096
2097 #endif /* GSSAPI */
2098
2099 #ifdef JPAKE
2100 int
2101 mm_answer_jpake_step1(int sock, Buffer *m)
2102 {
2103         struct jpake_ctx *pctx;
2104         u_char *x3_proof, *x4_proof;
2105         u_int x3_proof_len, x4_proof_len;
2106
2107         if (!options.zero_knowledge_password_authentication)
2108                 fatal("zero_knowledge_password_authentication disabled");
2109
2110         if (authctxt->jpake_ctx != NULL)
2111                 fatal("%s: authctxt->jpake_ctx already set (%p)",
2112                     __func__, authctxt->jpake_ctx);
2113         authctxt->jpake_ctx = pctx = jpake_new();
2114
2115         jpake_step1(pctx->grp,
2116             &pctx->server_id, &pctx->server_id_len,
2117             &pctx->x3, &pctx->x4, &pctx->g_x3, &pctx->g_x4,
2118             &x3_proof, &x3_proof_len,
2119             &x4_proof, &x4_proof_len);
2120
2121         JPAKE_DEBUG_CTX((pctx, "step1 done in %s", __func__));
2122
2123         buffer_clear(m);
2124
2125         buffer_put_string(m, pctx->server_id, pctx->server_id_len);
2126         buffer_put_bignum2(m, pctx->g_x3);
2127         buffer_put_bignum2(m, pctx->g_x4);
2128         buffer_put_string(m, x3_proof, x3_proof_len);
2129         buffer_put_string(m, x4_proof, x4_proof_len);
2130
2131         debug3("%s: sending step1", __func__);
2132         mm_request_send(sock, MONITOR_ANS_JPAKE_STEP1, m);
2133
2134         bzero(x3_proof, x3_proof_len);
2135         bzero(x4_proof, x4_proof_len);
2136         xfree(x3_proof);
2137         xfree(x4_proof);
2138
2139         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_GET_PWDATA, 1);
2140         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 0);
2141
2142         return 0;
2143 }
2144
2145 int
2146 mm_answer_jpake_get_pwdata(int sock, Buffer *m)
2147 {
2148         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2149         char *hash_scheme, *salt;
2150
2151         if (pctx == NULL)
2152                 fatal("%s: pctx == NULL", __func__);
2153
2154         auth2_jpake_get_pwdata(authctxt, &pctx->s, &hash_scheme, &salt);
2155
2156         buffer_clear(m);
2157         /* pctx->s is sensitive, not returned to slave */
2158         buffer_put_cstring(m, hash_scheme);
2159         buffer_put_cstring(m, salt);
2160
2161         debug3("%s: sending pwdata", __func__);
2162         mm_request_send(sock, MONITOR_ANS_JPAKE_GET_PWDATA, m);
2163
2164         bzero(hash_scheme, strlen(hash_scheme));
2165         bzero(salt, strlen(salt));
2166         xfree(hash_scheme);
2167         xfree(salt);
2168
2169         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP2, 1);
2170
2171         return 0;
2172 }
2173
2174 int
2175 mm_answer_jpake_step2(int sock, Buffer *m)
2176 {
2177         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2178         u_char *x1_proof, *x2_proof, *x4_s_proof;
2179         u_int x1_proof_len, x2_proof_len, x4_s_proof_len;
2180
2181         if (pctx == NULL)
2182                 fatal("%s: pctx == NULL", __func__);
2183
2184         if ((pctx->g_x1 = BN_new()) == NULL ||
2185             (pctx->g_x2 = BN_new()) == NULL)
2186                 fatal("%s: BN_new", __func__);
2187         buffer_get_bignum2(m, pctx->g_x1);
2188         buffer_get_bignum2(m, pctx->g_x2);
2189         pctx->client_id = buffer_get_string(m, &pctx->client_id_len);
2190         x1_proof = buffer_get_string(m, &x1_proof_len);
2191         x2_proof = buffer_get_string(m, &x2_proof_len);
2192
2193         jpake_step2(pctx->grp, pctx->s, pctx->g_x3,
2194             pctx->g_x1, pctx->g_x2, pctx->x4,
2195             pctx->client_id, pctx->client_id_len,
2196             pctx->server_id, pctx->server_id_len,
2197             x1_proof, x1_proof_len,
2198             x2_proof, x2_proof_len,
2199             &pctx->b,
2200             &x4_s_proof, &x4_s_proof_len);
2201
2202         JPAKE_DEBUG_CTX((pctx, "step2 done in %s", __func__));
2203
2204         bzero(x1_proof, x1_proof_len);
2205         bzero(x2_proof, x2_proof_len);
2206         xfree(x1_proof);
2207         xfree(x2_proof);
2208
2209         buffer_clear(m);
2210
2211         buffer_put_bignum2(m, pctx->b);
2212         buffer_put_string(m, x4_s_proof, x4_s_proof_len);
2213
2214         debug3("%s: sending step2", __func__);
2215         mm_request_send(sock, MONITOR_ANS_JPAKE_STEP2, m);
2216
2217         bzero(x4_s_proof, x4_s_proof_len);
2218         xfree(x4_s_proof);
2219
2220         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_KEY_CONFIRM, 1);
2221
2222         return 0;
2223 }
2224
2225 int
2226 mm_answer_jpake_key_confirm(int sock, Buffer *m)
2227 {
2228         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2229         u_char *x2_s_proof;
2230         u_int x2_s_proof_len;
2231
2232         if (pctx == NULL)
2233                 fatal("%s: pctx == NULL", __func__);
2234
2235         if ((pctx->a = BN_new()) == NULL)
2236                 fatal("%s: BN_new", __func__);
2237         buffer_get_bignum2(m, pctx->a);
2238         x2_s_proof = buffer_get_string(m, &x2_s_proof_len);
2239
2240         jpake_key_confirm(pctx->grp, pctx->s, pctx->a,
2241             pctx->x4, pctx->g_x3, pctx->g_x4, pctx->g_x1, pctx->g_x2,
2242             pctx->server_id, pctx->server_id_len,
2243             pctx->client_id, pctx->client_id_len,
2244             session_id2, session_id2_len,
2245             x2_s_proof, x2_s_proof_len,
2246             &pctx->k,
2247             &pctx->h_k_sid_sessid, &pctx->h_k_sid_sessid_len);
2248
2249         JPAKE_DEBUG_CTX((pctx, "key_confirm done in %s", __func__));
2250
2251         bzero(x2_s_proof, x2_s_proof_len);
2252         buffer_clear(m);
2253
2254         /* pctx->k is sensitive, not sent */
2255         buffer_put_string(m, pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len);
2256
2257         debug3("%s: sending confirmation hash", __func__);
2258         mm_request_send(sock, MONITOR_ANS_JPAKE_KEY_CONFIRM, m);
2259
2260         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_CHECK_CONFIRM, 1);
2261
2262         return 0;
2263 }
2264
2265 int
2266 mm_answer_jpake_check_confirm(int sock, Buffer *m)
2267 {
2268         int authenticated = 0;
2269         u_char *peer_confirm_hash;
2270         u_int peer_confirm_hash_len;
2271         struct jpake_ctx *pctx = authctxt->jpake_ctx;
2272
2273         if (pctx == NULL)
2274                 fatal("%s: pctx == NULL", __func__);
2275
2276         peer_confirm_hash = buffer_get_string(m, &peer_confirm_hash_len);
2277
2278         authenticated = jpake_check_confirm(pctx->k,
2279             pctx->client_id, pctx->client_id_len,
2280             session_id2, session_id2_len,
2281             peer_confirm_hash, peer_confirm_hash_len) && authctxt->valid;
2282
2283         JPAKE_DEBUG_CTX((pctx, "check_confirm done in %s", __func__));
2284
2285         bzero(peer_confirm_hash, peer_confirm_hash_len);
2286         xfree(peer_confirm_hash);
2287
2288         buffer_clear(m);
2289         buffer_put_int(m, authenticated);
2290
2291         debug3("%s: sending result %d", __func__, authenticated);
2292         mm_request_send(sock, MONITOR_ANS_JPAKE_CHECK_CONFIRM, m);
2293
2294         monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 1);
2295
2296         auth_method = "jpake-01@openssh.com";
2297         return authenticated;
2298 }
2299
2300 #endif /* JPAKE */