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