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