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