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