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