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