source: trunk/third/ssh/newchannels.c @ 12646

Revision 12646, 67.8 KB checked in by danw, 26 years ago (diff)
This commit was generated by cvs2svn to compensate for changes in r12645, which included commits to RCS files with non-trunk default branches.
Line 
1/*
2
3channels.c
4
5Author: Tatu Ylonen <ylo@cs.hut.fi>
6
7Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
8                   All rights reserved
9
10Created: Fri Mar 24 16:35:24 1995 ylo
11
12This file contains functions for generic socket connection forwarding.
13There is also code for initiating connection forwarding for X11 connections,
14arbitrary tcp/ip connections, and the authentication agent connection.
15
16*/
17
18/*
19 * $Id: newchannels.c,v 1.1.1.4 1999-03-08 17:43:15 danw Exp $
20 * $Log: not supported by cvs2svn $
21 * Revision 1.46  1998/07/08 00:46:01  kivinen
22 *      Splitted ip address display name from
23 *      HPSUX_NONSTANDARD_X11_KLUDGE to separate
24 *      NONSTANDARD_IP_ADDRESS_X11_KLUDGE ifdef.
25 *      Changed deny/allow stuff to use match_host instead of
26 *      match_pattern.
27 *
28 * Revision 1.45  1998/06/11 00:25:48  kivinen
29 *      Fixed typo in strncpy call.
30 *
31 * Revision 1.44  1998/06/11 00:08:20  kivinen
32 *      Added date to X11 connection rejected message. Added checking
33 *      of /var/X directory first and if that doesn't exists then try
34 *      X11_DIR and if that doesn't exists try /tmp/.X11-unix.
35 *
36 * Revision 1.43  1998/05/23  20:22:30  kivinen
37 *      Changed () -> (void). Fixed typo in debug text. Added check
38 *      that chown succeeds.
39 *
40 * Revision 1.42  1998/03/27  16:58:26  kivinen
41 *      Added gatewayports support.
42 *
43 * Revision 1.41  1998/01/03 06:41:38  kivinen
44 *      Fixed bug in allow/deny forward to host name handling.
45 *
46 * Revision 1.40  1997/08/21 22:16:26  ylo
47 *      Fixed security bug with port number > 65535 in remote forwarding.
48 *
49 * Revision 1.39  1997/04/27 22:20:11  kivinen
50 *      Fixed bug in port number parsing in
51 *      channel_add_{allow,deny}_forwd_to.
52 *
53 * Revision 1.38  1997/04/27 21:52:42  kivinen
54 *      Added F-SECURE stuff. Added {Allow,Deny}Forwarding{To,Port}
55 *      feature.
56 *
57 * Revision 1.37  1997/04/17 04:01:22  kivinen
58 *      Removed extra port variable. Added return -1 to
59 *      channel_allocate to get rid of warning.
60 *
61 * Revision 1.36  1997/04/05 21:48:54  kivinen
62 *      Fixed some debug messages (removed extra newline at the end).
63 *      Added clearing of input buffer after output have closed.
64 *
65 * Revision 1.35  1997/03/26 07:14:47  kivinen
66 *      Added checks about failed read and write for open channel.
67 *
68 * Revision 1.34  1997/03/25 05:39:36  kivinen
69 *      Added check that hp == NULL in hpux kludge display setting.
70 *
71 * Revision 1.33  1997/03/19 19:25:01  kivinen
72 *      Added input buffer clearing for error conditions, so packet.c
73 *      can check that buffer must be empty before new packet is read
74 *      in.
75 *
76 * Revision 1.32  1997/03/19 17:58:10  kivinen
77 *      Added checks that x11 and authentication agent forwarding is
78 *      really requested when open requests is received.
79 *      Added checks that strlen(hostname) <= 255.
80 *
81 * Revision 1.31  1997/01/23 14:41:35  ttsalo
82 *     Fixed a typo (%.200d -> %.200s)
83 *
84 * Revision 1.30  1997/01/22 21:18:58  ttsalo
85 *     Fixed a memory deallocation bug
86 *
87 * Revision 1.29  1996/12/04 19:04:40  ttsalo
88 *     Changed a debug message
89 *
90 * Revision 1.28  1996/12/04 18:16:52  ttsalo
91 *     Added printing of channel type in allocation
92 *
93 * Revision 1.27  1996/11/27 15:38:24  ttsalo
94 *     Added X11DisplayOffset-option
95 *
96 * Revision 1.26  1996/11/24 08:22:39  kivinen
97 *      Added tcp wrapper code to x11 and port forwarding.
98 *      Removed extra channel_send_ieof from rejected
99 *      X11 channel open.
100 *      Fixed channel_request_remote_forwarding so it wont call fatal
101 *      if the other ends doens't permit forwarding.
102 *      Changed auth_input_request_forwarding to return true if it
103 *      succeeds and false otherwise. Changed it to send errors with
104 *      packet_send_debug to client instead of disconnect. Made the
105 *      error messages more verbose.
106 *
107 * Revision 1.25  1996/11/09 17:00:32  ttsalo
108 *       Chdir out from socket directory before deleting it
109 *
110 * Revision 1.24  1996/11/04 06:34:45  ylo
111 *      Fixed a number of erroneous messages.
112 *
113 * Revision 1.23  1996/10/30 14:24:53  ttsalo
114 *       Changed two stats to lstats
115 *
116 * Revision 1.22  1996/10/29 22:42:43  kivinen
117 *      log -> log_msg. Fixed auth_input_request_forwarding to check
118 *      that the parent directory of SSH_AGENT_SOCKET_DIR and the ..
119 *      are same (check that the last component of agent directory
120 *      isn't symlink).
121 *      Disconnect if agent directory mkdir fails.
122 *      Renamed remotech to remote_channel in
123 *      auth_input_open_request.
124 *
125 * Revision 1.21  1996/10/29 14:18:51  ttsalo
126 *       Fixed a bug
127 *
128 * Revision 1.20  1996/10/29 14:07:24  ttsalo
129 *       Clarified some error messages
130 *
131 * Revision 1.19  1996/10/29 13:38:45  ttsalo
132 *      Improved the security of auth_input_request_forwarding()
133 *
134 * Revision 1.18  1996/10/24 14:05:10  ttsalo
135 *       Cleaning up old fd-auth trash
136 *
137 * Revision 1.17  1996/10/20 16:27:34  ttsalo
138 *      Many changes, agent stuff should now work as defined in the specs
139 *
140 * Revision 1.16  1996/09/28 16:26:09  ylo
141 *      Added a workaround for channel deadlocks...  This may cause
142 *      sshd to grow occasionally, and indefinitely in some situations.
143 *
144 * Revision 1.15  1996/09/27 17:21:39  ylo
145 *      Merged ultrix, Next and Linux patches from Corey Satten. This
146 *      effectively puts all file descriptors in non-blocking mode,
147 *      because these systems appear to sometimes wake up from select
148 *      and then block in write even when they are not supposed to.
149 *
150 * Revision 1.14  1996/09/27 14:00:11  ttsalo
151 *      Replaced a chmod with umask setting, chmod was dangerous.
152 *
153 * Revision 1.13  1996/09/14 08:44:12  ylo
154 *      Print X11 auth protocols if different.
155 *
156 * Revision 1.12  1996/09/14 08:42:14  ylo
157 *      Fixed a (minor) bug in interactive output packet sizing.
158 *      Reduced maximum non-interactive packet size to 8192.
159 *
160 * Revision 1.11  1996/09/12 18:31:11  ttsalo
161 *      st->uid to st->st.uid
162 *
163 * Revision 1.10  1996/09/11 17:56:22  kivinen
164 *      Fixed serious security bug in auth_input_request_forwarding,
165 *      now we chown the directory only if we created it. Changed
166 *      auth_input_request_forwarding to check the permissions of
167 *      directory itself and not to call
168 *      userfile_check_owner_permissions (it doesn't check for read
169 *      and execute permissions).
170 *
171 * Revision 1.9  1996/09/08 17:21:06  ttsalo
172 *      A lot of changes in agent-socket handling
173 *
174 * Revision 1.8  1996/09/04 12:41:49  ttsalo
175 *      Minor fixes
176 *
177 * Revision 1.7  1996/08/29 14:51:25  ttsalo
178 *      Agent-socket directory handling implemented
179 *
180 * Revision 1.6  1996/08/21 20:43:54  ttsalo
181 *      Made ssh-agent use a different, more secure way of storing
182 *      it's initial socket.
183 *
184 * Revision 1.5  1996/07/31 07:10:35  huima
185 *      Fixed the connection closing bug.
186 *
187 * Revision 1.4  1996/07/15 00:28:57  ylo
188 *      When an X11 connection is rejected, log where the rejected
189 *      connection came from.
190 *
191 * Revision 1.3  1996/07/12 07:22:47  ttsalo
192 *      Patch from <Rein.Tollevik@si.sintef.no> to handle HP-UX
193 *      nonstandard X11 socket kludging.
194 *
195 * Revision 1.2  1996/05/06 09:53:24  huima
196 * Fixed a major in the channels allocation.
197 *
198 * Revision 1.1  1996/04/22  23:43:52  huima
199 * New channels code added to the repository.
200 *
201 * Revision 1.1.1.1  1996/02/18  21:38:12  ylo
202 *      Imported ssh-1.2.13
203 *
204 * Revision 1.13  1995/10/02  01:20:08  ylo
205 *      Added a cast to avoid compiler warning.
206 *
207 * Revision 1.12  1995/09/24  23:58:49  ylo
208 *      Added support for screen number in X11 forwarding.
209 *      Reduced max packet size in interactive mode from 1024 bytes to
210 *      512 bytes for forwarded connections.
211 *
212 * Revision 1.11  1995/09/21  17:08:40  ylo
213 *      Support AF_UNIX_SIZE.
214 *
215 * Revision 1.10  1995/09/10  23:25:35  ylo
216 *      Fixed HPSUX DISPLAY kludge.
217 *
218 * Revision 1.9  1995/09/10  22:45:23  ylo
219 *      Changed Unix domain socket and umask stuff.
220 *
221 * Revision 1.8  1995/09/09  21:26:39  ylo
222 * /m/shadows/u2/users/ylo/ssh/README
223 *
224 * Revision 1.7  1995/09/06  15:58:14  ylo
225 *      Added BROKEN_INET_ADDR.
226 *
227 * Revision 1.6  1995/08/29  22:20:40  ylo
228 *      New file descriptor code for agent forwarding.
229 *
230 * Revision 1.5  1995/08/21  23:22:49  ylo
231 *      Clear sockaddr_in structures before use.
232 *
233 *      Reject X11 connections that don't match fake data.
234 *
235 * Revision 1.4  1995/08/18  22:47:11  ylo
236 *      Fixed a typo (missing parentheses in packet_is_interactive
237 *      call).
238 *
239 *      Removed extra shutdown in channel_close_all().  This caused
240 *      the "accept: software caused connection abort" messages and
241 *      busy looping that made the previous version of ssh unusable on
242 *      most systems.
243 *
244 * Revision 1.3  1995/07/27  02:16:43  ylo
245 *      Fixed output draining on forwarded TCP/IP connections.
246 *      Use smaller packets for interactive sessions.
247 *
248 * Revision 1.2  1995/07/13  01:19:29  ylo
249 *      Removed "Last modified" header.
250 *      Added cvs log.
251 *
252 * $Endlog$
253 */
254
255#include "includes.h"
256#if !defined(HAVE_GETHOSTNAME) || defined(NONSTANDARD_IP_ADDRESS_X11_KLUDGE)
257#include <sys/utsname.h>
258#endif
259#include "ssh.h"
260#include "packet.h"
261#include "xmalloc.h"
262#include "buffer.h"
263#include "authfd.h"
264#include "emulate.h"
265#include "servconf.h"
266#ifdef LIBWRAP
267#include <tcpd.h>
268#include <syslog.h>
269#ifdef NEED_SYS_SYSLOG_H
270#include <sys/syslog.h>
271#endif /* NEED_SYS_SYSLOG_H */
272#endif /* LIBWRAP */
273
274/* Directory in which the fake unix-domain X11 displays reside. */
275#ifndef X11_DIR
276#define X11_DIR "/tmp/.X11-unix"
277#endif
278
279/* Maximum number of fake X11 displays to try. */
280#define MAX_DISPLAYS  1000
281
282/* Definitions for channel types. */
283#define SSH_CHANNEL_FREE                0 /* This channel is free (unused). */
284#define SSH_CHANNEL_X11_LISTENER        1 /* Listening for inet X11 conn. */
285#define SSH_CHANNEL_PORT_LISTENER       2 /* Listening on a port. */
286#define SSH_CHANNEL_OPENING             3 /* waiting for confirmation */
287#define SSH_CHANNEL_OPEN                4 /* normal open two-way channel */
288/* obsolete SSH_CHANNEL_CLOSED          5    waiting for close confirmation */
289/* obsolete SSH_CHANNEL_AUTH_FD         6    authentication fd */
290/* obsolete SSH_CHANNEL_AUTH_SOCKET     7    authentication socket */
291/* obsolete SSH_CHANNEL_AUTH_SOCKET_FD  8    connection to auth socket */
292#define SSH_CHANNEL_X11_OPEN            9 /* reading first X11 packet */
293#define SSH_CHANNEL_AUTH_LISTENER      10 /* Agent proxy listening for
294                                             connections */
295
296/* Status flags */
297
298#define STATUS_INPUT_SOCKET_CLOSED      0x0001
299#define STATUS_OUTPUT_SOCKET_CLOSED     0x0002
300#define STATUS_EOF_SENT                 0x0004
301#define STATUS_EOF_RECEIVED             0x0008
302#define STATUS_CLOSE_SENT               0x0010
303#define STATUS_CLOSE_RECEIVED           0x0020
304#define STATUS_KLUDGE_A                 0x0040
305#define STATUS_KLUDGE_B                 0x0080
306
307#define STATUS_TERMINATE                0x003f
308
309/* Data structure for channel data.  This is iniailized in channel_allocate
310   and cleared in channel_free. */
311
312typedef struct
313{
314  int type;
315  int sock;
316
317  int remote_id, local_id;
318  int status_flags; /* for keeping book on the internal state */
319
320  Buffer input;
321  Buffer output;
322
323  char path[200]; /* path for unix domain sockets, or host name for forwards */
324  int host_port;  /* port to connect for forwards */
325  int listening_port; /* port being listened for forwards */
326  char *remote_name;
327
328  int is_x_connection;
329} Channel;
330
331/* Pointer to an array containing all allocated channels.  The array is
332   dynamically extended as needed. */
333static Channel *channels = NULL;
334
335/* Size of the channel array.  All slots of the array must always be
336   initialized (at least the type field); unused slots are marked with
337   type SSH_CHANNEL_FREE. */
338static int channels_alloc = 0;
339
340/* Number of currently used channels.  Used to determine if we should
341   expand the array. */
342static int channels_used = 0;
343
344/* Maximum file descriptor value used in any of the channels.  This is updated
345   in channel_allocate. */
346static int channel_max_fd_value = 0;
347
348/* These two variables are for authentication agent forwarding. */
349static int channel_forwarded_auth_fd = -1;
350static char *channel_forwarded_auth_socket_name = NULL;
351
352/* Agent forwarding socket directory name */
353static char *channel_forwarded_auth_socket_dir_name = NULL;
354
355/* Saved X11 authentication protocol name. */
356char *x11_saved_proto = NULL;
357
358/* Saved X11 authentication data.  This is the real data. */
359char *x11_saved_data = NULL;
360unsigned int x11_saved_data_len = 0;
361
362/* Fake X11 authentication data.  This is what the server will be sending
363   us; we should replace any occurrences of this by the real data. */
364char *x11_fake_data = NULL;
365unsigned int x11_fake_data_len;
366
367#ifdef F_SECURE_COMMERCIAL
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390#endif /* F_SECURE_COMMERCIAL */
391
392/* Data structure for storing which hosts are permitted for forward requests.
393   The local sides of any remote forwards are stored in this array to prevent
394   a corrupt remote server from accessing arbitrary TCP/IP ports on our
395   local network (which might be behind a firewall). */
396typedef struct
397{
398  char *host;           /* Host name. */
399  int port;             /* Port number. */
400} ForwardPermission;
401
402/* List of all permitted host/port pairs to connect. */
403static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
404/* Number of permitted host/port pairs in the array. */
405static int num_permitted_opens = 0;
406/* If this is true, all opens are permitted.  This is the case on the
407   server on which we have to trust the client anyway, and the user could
408   do anything after logging in anyway. */
409static int all_opens_permitted = 0;
410
411/* X11 forwarding permitted */
412static int x11_forwarding_permitted = 0;
413
414/* Agent forwarding permitted */
415static int auth_forwarding_permitted = 0;
416
417/* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
418static int have_hostname_in_open = 0;
419
420/* Sets specific protocol options. */
421
422void channel_set_options(int hostname_in_open)
423{
424  have_hostname_in_open = hostname_in_open;
425}
426
427/* Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
428   called by the server, because the user could connect to any port anyway,
429   and the server has no way to know but to trust the client anyway. */
430
431void channel_permit_all_opens(void)
432{
433  all_opens_permitted = 1;
434}
435
436/* Allocate a new channel object and set its type and socket.
437   This will cause remote_name to be freed. */
438
439int channel_allocate(int type, int sock, char *remote_name)
440{
441  int i;
442
443  /* Update the maximum file descriptor value. */
444  if (sock > channel_max_fd_value)
445    channel_max_fd_value = sock;
446
447  /* Do initial allocation if this is the first call. */
448  if (channels_alloc == 0)
449    {
450      channels_alloc = 10;
451      channels = xmalloc(channels_alloc * sizeof(Channel));
452      for (i = 0; i < channels_alloc; i++)
453        channels[i].type = SSH_CHANNEL_FREE;
454
455      /* Kludge: arrange a call to channel_stop_listening if we terminate
456         with fatal(). */
457      fatal_add_cleanup((void (*)(void *))channel_stop_listening, NULL);
458    }
459
460  i = 0;
461
462  if (channels_used == channels_alloc)
463    {
464      /* There are no free slots.  Must expand the array. */
465      channels_alloc += 10;
466      debug("Expanding the array...");
467      channels = xrealloc(channels, channels_alloc * sizeof(Channel));
468      for (i = channels_used; i < channels_alloc; i++)
469        channels[i].type = SSH_CHANNEL_FREE;
470      i = channels_used;
471      debug("Array now %d channels [first free at %d].",
472            channels_alloc, i);
473    }
474
475  /* Try to find a free slot where to put the new channel. */
476  while (i < channels_alloc)
477    {
478      if (channels[i].type == SSH_CHANNEL_FREE)
479        {
480          /* Found a free slot.
481             Initialize the fields and return its number. */
482          buffer_init(&channels[i].input);
483          buffer_init(&channels[i].output);
484          channels[i].type = type;
485          channels[i].sock = sock;
486          channels[i].remote_id = -1;
487          channels[i].remote_name = remote_name;
488          channels[i].status_flags = 0;
489          channels[i].local_id = i;
490          channels[i].is_x_connection = 0;
491          channels_used++;
492          debug("Allocated channel %d of type %d.", i, type);
493          return i;
494        }
495      i++;
496    }
497  fatal ("Internal bug in channel_allocate.");
498  return -1;
499}
500
501/* Free the channel and close its socket. */
502
503void channel_free(int channel)
504{
505  assert(channel >= 0 && channel < channels_alloc &&
506         channels[channel].type != SSH_CHANNEL_FREE);
507  close(channels[channel].sock);
508  buffer_free(&channels[channel].input);
509  buffer_free(&channels[channel].output);
510  channels[channel].type = SSH_CHANNEL_FREE;
511  channels_used--;
512  if (channels[channel].remote_name)
513    {
514      xfree(channels[channel].remote_name);
515      channels[channel].remote_name = NULL;
516    }
517}
518
519/* Support for the new protocol */
520
521/* A channel can be freed when it has sent and received
522   input eof and output closed */
523
524void channel_check_termination(Channel *ch)
525{
526  if ((ch->status_flags & STATUS_TERMINATE) == STATUS_TERMINATE)
527    {
528#ifdef SUPPORT_OLD_CHANNELS
529      if ((emulation_information & EMULATE_OLD_CHANNEL_CODE)
530          && !(ch->status_flags & STATUS_KLUDGE_A))
531        {
532          ch->status_flags &= ~(STATUS_CLOSE_RECEIVED | STATUS_EOF_RECEIVED);
533          debug("Discarding termination of channel %d.", ch->local_id);
534          return;
535        }
536#endif
537      debug("Channel %d terminates.", ch->local_id);
538#ifdef SUPPORT_OLD_CHANNELS
539      if (emulation_information & EMULATE_OLD_CHANNEL_CODE)
540        if (ch->status_flags & STATUS_KLUDGE_B)
541          {
542            packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
543            packet_put_int(ch->remote_id);
544            packet_send();
545          }
546#endif
547      channel_free(ch->local_id);
548    }
549}
550
551/* If ieof has not yet been sent, send it */
552
553void channel_send_ieof(Channel *ch)
554{
555  if (!(ch->status_flags & STATUS_EOF_SENT))
556    {
557      debug("Channel %d sends ieof.", ch->local_id);
558      ch->status_flags |= STATUS_EOF_SENT;
559
560#ifdef SUPPORT_OLD_CHANNELS
561      /* This is SSH_MSG_CHANNEL_CLOSE in the old protocol */
562#endif
563
564      packet_start(SSH_MSG_CHANNEL_INPUT_EOF);
565      packet_put_int(ch->remote_id);
566      packet_send();
567
568#ifdef SUPPORT_OLD_CHANNELS
569      if (emulation_information & EMULATE_OLD_CHANNEL_CODE)
570        ch->status_flags |= STATUS_CLOSE_SENT;
571#endif
572
573      channel_check_termination(ch);
574    }
575}
576
577/* If oclosed has not yet been sent, send it */
578#ifdef SUPPORT_OLD_CHANNELS
579/* This will be never called if we're emulating the old code */
580#endif
581
582void channel_send_oclosed(Channel *ch)
583{
584 
585  if (!(ch->status_flags & STATUS_CLOSE_SENT))
586    {
587      debug("Channel %d sends oclosed.", ch->local_id);
588      ch->status_flags |= STATUS_CLOSE_SENT;
589
590      packet_start(SSH_MSG_CHANNEL_OUTPUT_CLOSED);
591      packet_put_int(ch->remote_id);
592      packet_send();
593
594      channel_check_termination(ch);
595    }
596}
597
598/* Close input if hasn't been done yet. Input buffer is not discarded,
599   because we want to drain it over the channel. */
600
601#ifdef SUPPORT_OLD_CHANNELS
602void channel_close_output(Channel *ch);
603#endif
604
605void channel_close_input(Channel *ch)
606{
607  if (!(ch->status_flags & STATUS_INPUT_SOCKET_CLOSED))
608    {
609      debug("Channel %d closes incoming data stream.", ch->local_id);
610      ch->status_flags |= STATUS_INPUT_SOCKET_CLOSED;
611      shutdown(ch->sock, 0);
612      if (ch->type != SSH_CHANNEL_OPEN)
613        {
614          channel_send_ieof(ch);
615        }
616#ifdef SUPPORT_OLD_CHANNELS
617      if (emulation_information & EMULATE_OLD_CHANNEL_CODE)
618        {
619          channel_close_output(ch);
620        }
621#endif
622    }
623}
624
625/* Close output if it hasn't been done yet. Output buffer is
626   discarded, because we couldn't put it anywhere else (as the socket
627   is closed). Send info about the close immediately. */
628
629void channel_close_output(Channel *ch)
630{
631  if (!(ch->status_flags & STATUS_OUTPUT_SOCKET_CLOSED))
632    {
633      debug("Channel %d closes outgoing data stream.", ch->local_id);
634      ch->status_flags |= STATUS_OUTPUT_SOCKET_CLOSED;
635      shutdown(ch->sock, 1);
636      if (buffer_len(&ch->output))
637        buffer_consume(&ch->output, buffer_len(&ch->output));
638#ifdef SUPPORT_OLD_CHANNELS
639      if (emulation_information & EMULATE_OLD_CHANNEL_CODE)
640        {
641          debug("This is emulation.");
642          channel_close_input(ch);
643        }
644      else
645#endif
646        channel_send_oclosed(ch);     
647    }
648}
649
650/* Receive input eof. Nothing is done yet, because the output buffer
651   might want to drain away. */
652
653void channel_receive_ieof(Channel *ch)
654{
655  if (ch->status_flags & STATUS_EOF_RECEIVED)
656    packet_disconnect("Received double input eof.");
657
658  debug("Channel %d receives input eof.", ch->local_id);
659  ch->status_flags |= STATUS_EOF_RECEIVED;
660  if (ch->is_x_connection)
661    {
662      debug("X problem fix: close the other direction.");
663      channel_close_input(ch);
664    }
665  if (ch->type != SSH_CHANNEL_OPEN)
666    channel_close_output(ch);
667  channel_check_termination(ch);
668}
669
670/* Receive output closed. Input will be immediately closed,
671   because the other party is not interested in our packets. */
672
673void channel_receive_oclosed(Channel *ch)
674{
675  if (ch->status_flags & STATUS_CLOSE_RECEIVED)
676    packet_disconnect("Received double close.");
677
678  debug("Channel %d receives output closed.", ch->local_id);
679  ch->status_flags |= STATUS_CLOSE_RECEIVED;
680  buffer_clear(&ch->input);
681  channel_close_input(ch);
682  channel_check_termination(ch);
683}
684
685/* This is called after receiving CHANNEL_INPUT_EOF */
686
687void channel_ieof(void)
688{
689  int channel;
690  /* Get the channel number and verify it. */
691  channel = packet_get_int();
692  if (channel < 0 || channel >= channels_alloc ||
693      channels[channel].type == SSH_CHANNEL_FREE)
694    packet_disconnect("Received ieof for nonexistent channel %d.", channel);
695
696  channel_receive_ieof(&channels[channel]);
697}
698
699/* This is called after receiving CHANNEL_OUTPUT_CLOSED */
700void channel_oclosed(void)
701{
702  int channel;
703  /* Get the channel number and verify it. */
704  channel = packet_get_int();
705  if (channel < 0 || channel >= channels_alloc ||
706      channels[channel].type == SSH_CHANNEL_FREE)
707    packet_disconnect("Received oclosed for nonexistent channel %d.", channel);
708
709  channel_receive_oclosed(&channels[channel]);
710}
711
712#ifdef SUPPORT_OLD_CHANNELS
713void channel_emulated_close(int set_a)
714{
715  int channel;
716 
717  debug("Emulated close.");
718
719  channel = packet_get_int();
720  if (channel < 0 || channel >= channels_alloc ||
721      channels[channel].type == SSH_CHANNEL_FREE)
722    packet_disconnect("Received emulated_close for nonexistent channel %d.",
723                      channel);
724
725  if (set_a)
726    channels[channel].status_flags |= STATUS_KLUDGE_A;
727  else
728    channels[channel].status_flags |= STATUS_KLUDGE_B;
729
730  channel_receive_ieof(&channels[channel]); 
731  channel_receive_oclosed(&channels[channel]);
732}
733#endif
734
735/* This is called just before select() to add any bits relevant to
736   channels in the select bitmasks. */
737
738void channel_prepare_select(fd_set *readset, fd_set *writeset)
739{
740  int i;
741  Channel *ch;
742  unsigned char *ucp;
743  unsigned int proto_len, data_len;
744
745  for (i = 0; i < channels_alloc; i++)
746    {
747      ch = &channels[i];
748    redo:
749      switch (ch->type)
750        {
751        case SSH_CHANNEL_X11_LISTENER:
752        case SSH_CHANNEL_PORT_LISTENER:
753        case SSH_CHANNEL_AUTH_LISTENER:
754          FD_SET(ch->sock, readset);
755          break;
756         
757        case SSH_CHANNEL_OPEN:
758
759          if ((buffer_len(&ch->input) < packet_max_size() / 2)
760              && (!(ch->status_flags & STATUS_INPUT_SOCKET_CLOSED)))
761            FD_SET(ch->sock, readset);
762
763          if (!(ch->status_flags & STATUS_OUTPUT_SOCKET_CLOSED))
764            {
765              if (buffer_len(&ch->output) > 0)
766                {
767                  FD_SET(ch->sock, writeset);
768                }
769              else
770                {
771                  if (ch->status_flags & STATUS_EOF_RECEIVED)
772                    {
773                      channel_close_output(ch);
774                    }
775                }
776            }
777
778          break;
779         
780        case SSH_CHANNEL_X11_OPEN:
781          /* This is a special state for X11 authentication spoofing.  An
782             opened X11 connection (when authentication spoofing is being
783             done) remains in this state until the first packet has been
784             completely read.  The authentication data in that packet is
785             then substituted by the real data if it matches the fake data,
786             and the channel is put into normal mode. */
787
788          /* Check if the fixed size part of the packet is in buffer. */
789          if (buffer_len(&ch->output) < 12)
790            break;
791
792          /* Parse the lengths of variable-length fields. */
793          ucp = (unsigned char *)buffer_ptr(&ch->output);
794          if (ucp[0] == 0x42)
795            { /* Byte order MSB first. */
796              proto_len = 256 * ucp[6] + ucp[7];
797              data_len = 256 * ucp[8] + ucp[9];
798            }
799          else
800            if (ucp[0] == 0x6c)
801              { /* Byte order LSB first. */
802                proto_len = ucp[6] + 256 * ucp[7];
803                data_len = ucp[8] + 256 * ucp[9];
804              }
805            else
806              {
807                debug("Initial X11 packet contains bad byte order byte: 0x%x",
808                      ucp[0]);
809                ch->type = SSH_CHANNEL_OPEN;
810                goto reject;
811              }
812
813          /* Check if the whole packet is in buffer. */
814          if (buffer_len(&ch->output) <
815              12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
816            break;
817         
818          /* Check if authentication protocol matches. */
819          if (proto_len != strlen(x11_saved_proto) ||
820              memcmp(ucp + 12, x11_saved_proto, proto_len) != 0)
821            {
822              if (proto_len > 100)
823                proto_len = 100; /* Limit length of output. */
824              debug("X11 connection uses different authentication protocol: '%.100s' vs. '%.*s'.",
825                    x11_saved_proto,
826                    proto_len, (const char *)(ucp + 12));
827              ch->type = SSH_CHANNEL_OPEN;
828              goto reject;
829            }
830
831          /* Check if authentication data matches our fake data. */
832          if (data_len != x11_fake_data_len ||
833              memcmp(ucp + 12 + ((proto_len + 3) & ~3),
834                     x11_fake_data, x11_fake_data_len) != 0)
835            {
836              debug("X11 auth data does not match fake data.");
837              ch->type = SSH_CHANNEL_OPEN;
838              goto reject;
839            }
840
841          /* Received authentication protocol and data match our fake data.
842             Substitute the fake data with real data. */
843          assert(x11_fake_data_len == x11_saved_data_len);
844          memcpy(ucp + 12 + ((proto_len + 3) & ~3),
845                 x11_saved_data, x11_saved_data_len);
846
847          /* Start normal processing for the channel. */
848          ch->type = SSH_CHANNEL_OPEN;
849          goto redo;
850         
851        reject:
852          /* We have received an X11 connection that has bad authentication
853             information. */
854          {
855            time_t t;
856            char buffer[255], *p;
857
858            t = time(NULL);
859            strncpy(buffer, ctime(&t), sizeof(buffer));
860            buffer[sizeof(buffer) - 1] = '\0';
861
862            p = strchr(buffer, '\n');
863            if (p)
864              *p = '\0';
865            p = strchr(buffer, '\r');
866            if (p)
867              *p = '\0';
868           
869            log_msg("X11 connection rejected because of wrong authentication at %s.\r\na",
870                    buffer);
871            if (ch->remote_name)
872              log_msg("Rejected connection at %s: %.200s\r\n", buffer,
873                      ch->remote_name);
874          }
875          buffer_clear(&ch->input);
876          buffer_clear(&ch->output);
877          channel_close_input(ch);
878          channel_close_output(ch);
879          /* Output closed has been sent in close_output except if
880             we're emulating the old code, but then we wouldn't send
881             it anyway. */
882          /* We will then wait until both closing packets have come,
883             then the channel gets destroyed - and the socket
884             closed. */
885          break;
886         
887        case SSH_CHANNEL_FREE:
888        default:
889          continue;
890        }
891    }
892}
893
894/* After select, perform any appropriate operations for channels which
895   have events pending. */
896
897void channel_after_select(fd_set *readset, fd_set *writeset)
898{
899  struct sockaddr addr;
900  int addrlen, newsock, i, newch, len, temp;
901  Channel *ch;
902  char buf[16384], *remote_hostname;
903 
904  /* Loop over all channels... */
905  for (i = 0; i < channels_alloc; i++)
906    {
907      ch = &channels[i];
908      switch (ch->type)
909        {
910        case SSH_CHANNEL_X11_LISTENER:
911          /* This is our fake X11 server socket. */
912          if (FD_ISSET(ch->sock, readset))
913            {
914              debug("X11 connection requested.");
915              addrlen = sizeof(addr);
916              newsock = accept(ch->sock, &addr, &addrlen);
917              if (newsock < 0)
918                {
919                  error("accept: %.100s", strerror(errno));
920                  break;
921                }
922              remote_hostname = get_remote_hostname(newsock);
923              sprintf(buf, "X11 connection from %.200s port %d",
924                      remote_hostname, get_peer_port(newsock));
925              xfree(remote_hostname);
926#ifdef LIBWRAP
927              {
928                struct request_info req;
929                struct servent *serv;
930               
931                /* fill req struct with port name and fd number */
932                request_init(&req, RQ_DAEMON, "sshdfwd-X11",
933                             RQ_FILE, newsock, NULL);
934                fromhost(&req);
935                if (!hosts_access(&req))
936                  {
937                    packet_send_debug("Fwd X11 connection from %.500s refused by tcp_wrappers.", eval_client(&req));
938                    error("Fwd X11 connection from %.500s refused by tcp_wrappers.",
939                          eval_client(&req));
940                    shutdown(newsock, 2);
941                    close(newsock);
942                    break;
943                  }
944                log_msg("fwd X11 connect from %.500s", eval_client(&req));
945              }
946#endif /* LIBWRAP */
947              newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
948                                       xstrdup(buf));
949              channels[newch].is_x_connection = 1;
950              packet_start(SSH_SMSG_X11_OPEN);
951              packet_put_int(newch);
952              if (have_hostname_in_open)
953                packet_put_string(buf, strlen(buf));
954              packet_send();
955            }
956          break;
957         
958        case SSH_CHANNEL_PORT_LISTENER:
959          /* This socket is listening for connections to a forwarded TCP/IP
960             port. */
961          if (FD_ISSET(ch->sock, readset))
962            {
963              debug("Connection to port %d forwarding to %.100s:%d requested.",
964                    ch->listening_port, ch->path, ch->host_port);
965              addrlen = sizeof(addr);
966              newsock = accept(ch->sock, &addr, &addrlen);
967              if (newsock < 0)
968                {
969                  error("accept: %.100s", strerror(errno));
970                  break;
971                }
972              remote_hostname = get_remote_hostname(newsock);
973              sprintf(buf, "port %d, connection from %.200s port %d",
974                      ch->listening_port, remote_hostname,
975                      get_peer_port(newsock));
976              xfree(remote_hostname);
977#ifdef LIBWRAP
978              {
979                struct request_info req;
980                struct servent *serv;
981                char fwdportname[32];
982               
983                /* try to find port's name in /etc/services */
984                serv = getservbyport(htons(ch->listening_port), "tcp");
985                if (serv == NULL)
986                  {
987                    /* not found (or faulty getservbyport) -
988                       use the number as a name */
989                    sprintf(fwdportname,"sshdfwd-%d", ch->listening_port);
990                  }
991                else
992                  {
993                    sprintf(fwdportname, "sshdfwd-%.20s", serv->s_name);
994                  }
995                /* fill req struct with port name and fd number */
996                request_init(&req, RQ_DAEMON, fwdportname,
997                             RQ_FILE, newsock, NULL);
998                fromhost(&req);
999                if (!hosts_access(&req))
1000                  {
1001                    packet_send_debug("Fwd connection from %.500s to local port %s refused by tcp_wrappers.",
1002                                      eval_client(&req), fwdportname);
1003                    error("Fwd connection from %.500s to local port %s refused by tcp_wrappers.",
1004                          eval_client(&req), fwdportname);
1005                    shutdown(newsock, 2);
1006                    close(newsock);
1007                    break;
1008                  }
1009                log_msg("fwd connect from %.500s to local port %s",
1010                    eval_client(&req), fwdportname);
1011              }
1012#endif /* LIBWRAP */
1013              newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
1014                                       xstrdup(buf));
1015              packet_start(SSH_MSG_PORT_OPEN);
1016              packet_put_int(newch);
1017              packet_put_string(ch->path, strlen(ch->path));
1018              packet_put_int(ch->host_port);
1019              if (have_hostname_in_open)
1020                packet_put_string(buf, strlen(buf));
1021              packet_send();
1022            }
1023          break;
1024
1025        case SSH_CHANNEL_AUTH_LISTENER:
1026          /* This socket is listening for connections to a forwarded agent
1027             port. */
1028          if (FD_ISSET(ch->sock, readset))
1029            {
1030              debug("Connection to agent proxy requested from unix domain socket.");
1031              addrlen = sizeof(addr);
1032              newsock = accept(ch->sock, &addr, &addrlen);
1033              if (newsock < 0)
1034                {
1035                  error("accept: %.100s", strerror(errno));
1036                  break;
1037                }
1038              sprintf(buf, "Forwarded agent connection");
1039              newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
1040                                       xstrdup(buf));
1041              packet_start(SSH_SMSG_AGENT_OPEN);
1042              packet_put_int(newch);
1043              packet_send();
1044            }
1045          break;
1046
1047        case SSH_CHANNEL_OPEN:
1048          /* This is an open two-way communication channel.  It is not of
1049             interest to us at this point what kind of data is being
1050             transmitted. */
1051          /* Read available incoming data and append it to buffer. */
1052          if (FD_ISSET(ch->sock, readset))
1053            {
1054              len = sizeof(buf);
1055              if (len > packet_max_size() / 4)
1056                len = packet_max_size() / 4;
1057              len = read(ch->sock, buf, len);
1058              if (len < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
1059                goto no_rdata;
1060              if (len <= 0)
1061                {
1062                  channel_close_input(ch);
1063                  break;
1064                }
1065              buffer_append(&ch->input, buf, len);
1066            }
1067        no_rdata:
1068          /* Send buffered output data to the socket. */
1069          if (FD_ISSET(ch->sock, writeset) &&
1070              (temp = buffer_len(&ch->output)) > 0)
1071            {
1072              len = write(ch->sock, buffer_ptr(&ch->output), temp);
1073              if (len < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
1074                goto no_wdata;
1075              if (len <= 0)
1076                {
1077                  channel_close_output(ch);
1078                  break;
1079                }
1080              buffer_consume(&ch->output, len);
1081            }
1082        no_wdata:
1083          break;
1084
1085        case SSH_CHANNEL_X11_OPEN:
1086        case SSH_CHANNEL_FREE:
1087        default:
1088          continue;
1089        }
1090    }
1091}
1092
1093/* If there is data to send to the connection, send some of it now. */
1094
1095void channel_output_poll(void)
1096{
1097  int len, i;
1098  Channel *ch;
1099
1100  for (i = 0; i < channels_alloc; i++)
1101    {
1102      /* If we have very much data going to the output socket, don't send more
1103         now. */
1104      if (!packet_not_very_much_data_to_write())
1105        break; /* Don't send any more data now. */
1106
1107      ch = &channels[i];
1108      /* We are only interested in channels that can have buffered incoming
1109         data. */
1110      if (ch->type != SSH_CHANNEL_OPEN)
1111        continue;
1112
1113      /* Get the amount of buffered data for this channel. */
1114      len = buffer_len(&ch->input);
1115      if (len > 0)
1116        {
1117          /* Send some data for the other side over the secure connection. */
1118          if (packet_is_interactive())
1119            {
1120              if (len > 512)
1121                len = 512;
1122            }
1123          else
1124            {
1125              if (len > 8192)
1126                len = 8192;  /* Keep the packets at reasonable size. */
1127              if (len > packet_max_size() / 2)
1128                len = packet_max_size() / 2;
1129            }
1130          packet_start(SSH_MSG_CHANNEL_DATA);
1131          packet_put_int(ch->remote_id);
1132          packet_put_string(buffer_ptr(&ch->input), len);
1133          packet_send();
1134          buffer_consume(&ch->input, len);
1135        }
1136      /* check if we should send epsilon out */
1137      else
1138        {
1139          /* input buffer is empty, input socket closed,
1140             input eof not sent, send it now */
1141          if ((ch->status_flags & (STATUS_INPUT_SOCKET_CLOSED |
1142                                   STATUS_EOF_SENT)) ==
1143              STATUS_INPUT_SOCKET_CLOSED)
1144            {
1145              channel_send_ieof(ch);
1146            }
1147        }
1148    }
1149}
1150
1151/* This is called when a packet of type CHANNEL_DATA has just been received.
1152   The message type has already been consumed, but channel number and data
1153   is still there. */
1154
1155void channel_input_data(void)
1156{
1157  int channel;
1158  char *data;
1159  unsigned int data_len;
1160
1161  /* Get the channel number and verify it. */
1162  channel = packet_get_int();
1163  if (channel < 0 || channel >= channels_alloc ||
1164      channels[channel].type == SSH_CHANNEL_FREE)
1165    packet_disconnect("Received data for nonexistent channel %d.", channel);
1166 
1167  /* Ignore any data for non-open channels (might happen on close) */
1168  if (channels[channel].type != SSH_CHANNEL_OPEN &&
1169      channels[channel].type != SSH_CHANNEL_X11_OPEN)
1170    {
1171      packet_get_all();
1172      return;
1173    }
1174 
1175  /* Get the data. */
1176 
1177  if (channels[channel].status_flags & STATUS_EOF_RECEIVED)
1178    packet_disconnect("Other party sent data after eof for channel %d.",
1179                      channel);
1180 
1181  if (!(channels[channel].status_flags & STATUS_OUTPUT_SOCKET_CLOSED)) {
1182    data = packet_get_string(&data_len);
1183    buffer_append(&channels[channel].output, data, data_len);
1184    xfree(data);
1185  } else {
1186    packet_get_all();
1187  }
1188}
1189
1190/* Returns true if no channel has too much buffered data, and false if
1191   one or more channel is overfull. */
1192
1193int channel_not_very_much_buffered_data(void)
1194{
1195#if 0
1196  unsigned int i;
1197  Channel *ch;
1198 
1199  for (i = 0; i < channels_alloc; i++)
1200    {
1201      ch = &channels[i];
1202      switch (channels[i].type)
1203        {
1204        case SSH_CHANNEL_X11_LISTENER:
1205        case SSH_CHANNEL_PORT_LISTENER:
1206        case SSH_CHANNEL_AUTH_LISTENER:
1207          continue;
1208        case SSH_CHANNEL_OPEN:
1209          if (buffer_len(&ch->input) > 32000)
1210            return 0;
1211          if (buffer_len(&ch->output) > 32000)
1212            return 0;
1213          continue;
1214        case SSH_CHANNEL_X11_OPEN:
1215        case SSH_CHANNEL_FREE:
1216        default:
1217          continue;
1218        }
1219    }
1220#endif /* 0 */
1221  return 1;
1222}
1223
1224#ifdef SUPPORT_OLD_CHANNELS
1225void channel_input_close_confirmation(void)
1226{
1227  if (emulation_information & EMULATE_OLD_CHANNEL_CODE)
1228    channel_emulated_close(1);
1229  else
1230    channel_oclosed();
1231}
1232
1233void channel_input_close(void)
1234{
1235  if (emulation_information & EMULATE_OLD_CHANNEL_CODE)
1236    channel_emulated_close(0);
1237  else
1238    channel_ieof();
1239}
1240#endif
1241
1242/* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
1243
1244void channel_input_open_confirmation(void)
1245{
1246  int channel, remote_channel;
1247
1248  /* Get the channel number and verify it. */
1249  channel = packet_get_int();
1250  if (channel < 0 || channel >= channels_alloc ||
1251      channels[channel].type != SSH_CHANNEL_OPENING)
1252    packet_disconnect("Received open confirmation for non-opening channel %d.",
1253                      channel);
1254 
1255  /* Get remote side's id for this channel. */
1256  remote_channel = packet_get_int();
1257
1258  /* Record the remote channel number and mark that the channel is now open. */
1259  debug("Channel now open, status bits %x", channels[channel].status_flags);
1260  channels[channel].remote_id = remote_channel;
1261  channels[channel].type = SSH_CHANNEL_OPEN;
1262}
1263
1264/* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
1265
1266void channel_input_open_failure(void)
1267{
1268  int channel;
1269
1270  /* Get the channel number and verify it. */
1271  channel = packet_get_int();
1272  if (channel < 0 || channel >= channels_alloc ||
1273      channels[channel].type != SSH_CHANNEL_OPENING)
1274    packet_disconnect("Received open failure for non-opening channel %d.",
1275                      channel);
1276 
1277  /* Free the channel.  This will also close the socket. */
1278  channel_free(channel);
1279}
1280
1281/* Stops listening for channels, and removes any unix domain sockets that
1282   we might have. */
1283
1284void channel_stop_listening(void)
1285{
1286  int i;
1287  for (i = 0; i < channels_alloc; i++)
1288    {
1289      switch (channels[i].type)
1290        {
1291        case SSH_CHANNEL_AUTH_LISTENER:
1292          auth_delete_socket(NULL);
1293          break;
1294        case SSH_CHANNEL_PORT_LISTENER:
1295        case SSH_CHANNEL_X11_LISTENER:
1296          close(channels[i].sock);
1297          channel_free(i);
1298          break;
1299        default:
1300          break;
1301        }
1302    }
1303}
1304
1305/* Closes the sockets of all channels.  This is used to close extra file
1306   descriptors after a fork. */
1307
1308void channel_close_all(void)
1309{
1310  int i;
1311  for (i = 0; i < channels_alloc; i++)
1312    {
1313      if (channels[i].type != SSH_CHANNEL_FREE)
1314        close(channels[i].sock);
1315    }
1316}
1317
1318/* Returns the maximum file descriptor number used by the channels. */
1319
1320int channel_max_fd(void)
1321{
1322  return channel_max_fd_value;
1323}
1324
1325/* Returns true if any channel is still open. */
1326
1327int channel_still_open(void)
1328{
1329  unsigned int i;
1330  for (i = 0; i < channels_alloc; i++)
1331    switch (channels[i].type)
1332      {
1333      case SSH_CHANNEL_FREE:
1334      case SSH_CHANNEL_X11_LISTENER:
1335      case SSH_CHANNEL_PORT_LISTENER:
1336      case SSH_CHANNEL_AUTH_LISTENER:
1337        continue;
1338      case SSH_CHANNEL_OPENING:
1339      case SSH_CHANNEL_OPEN:
1340      case SSH_CHANNEL_X11_OPEN:
1341        return 1;
1342      default:
1343        fatal("channel_still_open: bad channel type %d", channels[i].type);
1344        /*NOTREACHED*/
1345      }
1346  return 0;
1347}
1348
1349/* Returns a message describing the currently open forwarded
1350   connections, suitable for sending to the client.  The message
1351   contains crlf pairs for newlines. */
1352
1353char *channel_open_message(void)
1354{
1355  Buffer buffer;
1356  int i;
1357  char buf[512], *cp;
1358
1359  buffer_init(&buffer);
1360  sprintf(buf, "The following connections are open:\r\n");
1361  buffer_append(&buffer, buf, strlen(buf));
1362  for (i = 0; i < channels_alloc; i++)
1363    switch (channels[i].type)
1364      {
1365      case SSH_CHANNEL_FREE:
1366      case SSH_CHANNEL_X11_LISTENER:
1367      case SSH_CHANNEL_PORT_LISTENER:
1368      case SSH_CHANNEL_AUTH_LISTENER:
1369        continue;
1370      case SSH_CHANNEL_OPENING:
1371      case SSH_CHANNEL_OPEN:
1372      case SSH_CHANNEL_X11_OPEN:
1373        sprintf(buf, "  %.300s\r\n", channels[i].remote_name);
1374        buffer_append(&buffer, buf, strlen(buf));
1375        continue;
1376      default:
1377        fatal("channel_still_open: bad channel type %d", channels[i].type);
1378        /*NOTREACHED*/
1379      }
1380  buffer_append(&buffer, "\0", 1);
1381  cp = xstrdup(buffer_ptr(&buffer));
1382  buffer_free(&buffer);
1383  return cp;
1384}
1385
1386/* Initiate forwarding of connections to local port "port" through the secure
1387   channel to host:port from remote side. */
1388
1389void channel_request_local_forwarding(int port, const char *host,
1390                                      int host_port, int gatewayports)
1391{
1392  int ch, sock;
1393  struct sockaddr_in sin;
1394
1395  if (strlen(host) > sizeof(channels[0].path) - 1)
1396    packet_disconnect("Forward host name too long.");
1397 
1398  /* Create a port to listen for the host. */
1399  sock = socket(AF_INET, SOCK_STREAM, 0);
1400  if (sock < 0)
1401    packet_disconnect("socket: %.100s", strerror(errno));
1402
1403#if defined(O_NONBLOCK) && !defined(O_NONBLOCK_BROKEN)
1404  (void)fcntl(sock, F_SETFL, O_NONBLOCK);
1405#else /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
1406  (void)fcntl(sock, F_SETFL, O_NDELAY);
1407#endif /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
1408
1409  /* Initialize socket address. */
1410  memset(&sin, 0, sizeof(sin));
1411  sin.sin_family = AF_INET;
1412  if (gatewayports)
1413    sin.sin_addr.s_addr = INADDR_ANY;
1414  else
1415#ifdef BROKEN_INET_ADDR
1416    sin.sin_addr.s_addr = inet_network("127.0.0.1");
1417#else /* BROKEN_INET_ADDR */
1418    sin.sin_addr.s_addr = inet_addr("127.0.0.1");
1419#endif /* BROKEN_INET_ADDR */
1420  sin.sin_port = htons(port);
1421 
1422  /* Bind the socket to the address. */
1423  if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1424    packet_disconnect("bind: %.100s", strerror(errno));
1425     
1426  /* Start listening for connections on the socket. */
1427  if (listen(sock, 5) < 0)
1428    packet_disconnect("listen: %.100s", strerror(errno));
1429           
1430  /* Allocate a channel number for the socket. */
1431  ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
1432                        xstrdup("port listener"));
1433  strcpy(channels[ch].path, host); /* note: host name stored here */
1434  channels[ch].host_port = host_port; /* port on host to connect to */
1435  channels[ch].listening_port = port; /* port being listened */
1436
1437
1438/* Initiate forwarding of connections to port "port" on remote host through
1439   the secure channel to host:port from local side. */
1440
1441void channel_request_remote_forwarding(int port, const char *host,
1442                                       int remote_port)
1443{
1444  int type;
1445 
1446  /* Send the forward request to the remote side. */
1447  packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1448  packet_put_int(port);
1449  packet_put_string(host, strlen(host));
1450  packet_put_int(remote_port);
1451  packet_send();
1452  packet_write_wait();
1453 
1454  /* Wait for response from the remote side.  It will send a disconnect
1455     message on failure, and we will never see it here. */
1456  type = packet_read();
1457  if (type == SSH_SMSG_FAILURE)
1458    {
1459      debug("Remote end denied port forwarding to %d:%.50s:%d",
1460            port, host, remote_port);
1461      return;
1462    }
1463  if (type != SSH_SMSG_SUCCESS)
1464    packet_disconnect("Protocol error: expected packet type %d, got %d",
1465                      SSH_SMSG_SUCCESS, type);
1466 
1467  /* Record locally that connection to this host/port is permitted. */
1468  if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1469    fatal("channel_request_remote_forwarding: too many forwards");
1470  permitted_opens[num_permitted_opens].host = xstrdup(host);
1471  permitted_opens[num_permitted_opens].port = remote_port;
1472  num_permitted_opens++;
1473}
1474
1475#ifdef F_SECURE_COMMERCIAL
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551#endif /* F_SECURE_COMMERCIAL */
1552
1553/* This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
1554   listening for the port, and sends back a success reply (or disconnect
1555   message if there was an error).  This never returns if there was an
1556   error. */
1557
1558void channel_input_port_forward_request(int is_root)
1559{
1560  int port, host_port;
1561  char *hostname;
1562 
1563  /* Get arguments from the packet. */
1564  port = packet_get_int();
1565  hostname = packet_get_string(NULL);
1566  host_port = packet_get_int();
1567
1568  if (strlen(hostname) > 255)
1569    packet_disconnect("Requested forwarding hostname too long: %.200s.",
1570                      hostname);
1571 
1572  /* Check that an unprivileged user is not trying to forward a privileged
1573     port. */
1574  if ((port < 1024 || port > 65535) && !is_root)
1575    packet_disconnect("Requested forwarding of port %d but user is not root.",
1576                      port);
1577
1578#ifdef F_SECURE_COMMERCIAL
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605#endif /* F_SECURE_COMMERCIAL */
1606  /* Initiate forwarding. */
1607  channel_request_local_forwarding(port, hostname, host_port, 1);
1608
1609  /* Free the argument string. */
1610  xfree(hostname);
1611  return;
1612fail:
1613  xfree(hostname);
1614  return;
1615}
1616
1617/* This is called after receiving PORT_OPEN message.  This attempts to connect
1618   to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
1619   CHANNEL_OPEN_FAILURE. */
1620
1621void channel_input_port_open(void)
1622{
1623  int remote_channel, sock, newch, host_port, i;
1624  struct sockaddr_in sin;
1625  char *host, *originator_string;
1626  struct hostent *hp;
1627
1628  /* Get remote channel number. */
1629  remote_channel = packet_get_int();
1630
1631  /* Get host name to connect to. */
1632  host = packet_get_string(NULL);
1633
1634  if (strlen(host) > 255)
1635    packet_disconnect("Requested forwarding hostname too long: %.200s.",
1636                      host);
1637 
1638  /* Get port to connect to. */
1639  host_port = packet_get_int();
1640
1641  /* Get remote originator name. */
1642  if (have_hostname_in_open)
1643    originator_string = packet_get_string(NULL);
1644  else
1645    originator_string = xstrdup("unknown (remote did not supply name)");
1646
1647  /* Check if opening that port is permitted. */
1648  if (!all_opens_permitted)
1649    {
1650      /* Go trough all permitted ports. */
1651      for (i = 0; i < num_permitted_opens; i++)
1652        if (permitted_opens[i].port == host_port &&
1653            strcmp(permitted_opens[i].host, host) == 0)
1654          break;
1655
1656      /* Check if we found the requested port among those permitted. */
1657      if (i >= num_permitted_opens)
1658        {
1659          /* The port is not permitted. */
1660          log_msg("Received request to connect to %.100s:%d, but the request was denied.",
1661              host, host_port);
1662          goto fail;
1663        }
1664    }
1665 
1666  memset(&sin, 0, sizeof(sin));
1667#ifdef BROKEN_INET_ADDR
1668  sin.sin_addr.s_addr = inet_network(host);
1669#else /* BROKEN_INET_ADDR */
1670  sin.sin_addr.s_addr = inet_addr(host);
1671#endif /* BROKEN_INET_ADDR */
1672  if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1673    {
1674      /* It was a valid numeric host address. */
1675      sin.sin_family = AF_INET;
1676    }
1677  else
1678    {
1679      /* Look up the host address from the name servers. */
1680      hp = gethostbyname(host);
1681      if (!hp)
1682        {
1683          error("%.100s: unknown host.", host);
1684          goto fail;
1685        }
1686      if (!hp->h_addr_list[0])
1687        {
1688          error("%.100s: host has no IP address.", host);
1689          goto fail;
1690        }
1691      sin.sin_family = hp->h_addrtype;
1692      memcpy(&sin.sin_addr, hp->h_addr_list[0],
1693             sizeof(sin.sin_addr));
1694    }
1695  sin.sin_port = htons(host_port);
1696 
1697#ifdef F_SECURE_COMMERCIAL
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730#endif /* F_SECURE_COMMERCIAL */
1731
1732  /* Create the socket. */
1733  sock = socket(sin.sin_family, SOCK_STREAM, 0);
1734  if (sock < 0)
1735    {
1736      error("socket: %.100s", strerror(errno));
1737      goto fail;
1738    }
1739
1740  /* Connect to the host/port. */
1741  if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1742    {
1743      error("connect %.100s:%d: %.100s", host, host_port,
1744            strerror(errno));
1745      close(sock);
1746      goto fail;
1747    }
1748
1749  /* Successful connection. */
1750
1751#if defined(O_NONBLOCK) && !defined(O_NONBLOCK_BROKEN)
1752  (void)fcntl(sock, F_SETFL, O_NONBLOCK);
1753#else /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
1754  (void)fcntl(sock, F_SETFL, O_NDELAY);
1755#endif /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
1756
1757  /* Allocate a channel for this connection. */
1758  newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1759  channels[newch].remote_id = remote_channel;
1760 
1761  /* Send a confirmation to the remote host. */
1762  packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1763  packet_put_int(remote_channel);
1764  packet_put_int(newch);
1765  packet_send();
1766
1767  /* Free the argument string. */
1768  xfree(host);
1769 
1770  return;
1771
1772 fail:
1773  /* Free the argument string. */
1774  xfree(host);
1775  xfree(originator_string);
1776
1777  /* Send refusal to the remote host. */
1778  packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1779  packet_put_int(remote_channel);
1780  packet_send();
1781}
1782
1783/* Creates an internet domain socket for listening for X11 connections.
1784   Returns a suitable value for the DISPLAY variable, or NULL if an error
1785   occurs. */
1786
1787char *x11_create_display_inet(int screen_number)
1788{
1789  extern ServerOptions options;
1790  int display_number, port, sock;
1791  struct sockaddr_in sin;
1792  char buf[512];
1793#ifdef HAVE_GETHOSTNAME
1794  char hostname[257];
1795#else
1796  struct utsname uts;
1797#endif
1798
1799  /* open first vacant display, starting at an offset (default 1) so
1800   * as not to clobber the low numbers. (Modification by Jari Kokko)
1801   */
1802  for (display_number = options.x11_display_offset; display_number < MAX_DISPLAYS; display_number++)
1803    {
1804      port = 6000 + display_number;
1805      memset(&sin, 0, sizeof(sin));
1806      sin.sin_family = AF_INET;
1807      sin.sin_addr.s_addr = INADDR_ANY;
1808      sin.sin_port = htons(port);
1809     
1810      sock = socket(AF_INET, SOCK_STREAM, 0);
1811      if (sock < 0)
1812        {
1813          error("socket: %.100s", strerror(errno));
1814          return NULL;
1815        }
1816
1817#if defined(O_NONBLOCK) && !defined(O_NONBLOCK_BROKEN)
1818      (void)fcntl(sock, F_SETFL, O_NONBLOCK);
1819#else /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
1820      (void)fcntl(sock, F_SETFL, O_NDELAY);
1821#endif /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
1822     
1823      if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1824        {
1825          debug("bind port %d: %.100s", port, strerror(errno));
1826          shutdown(sock, 2);
1827          close(sock);
1828          continue;
1829        }
1830      break;
1831    }
1832  if (display_number >= MAX_DISPLAYS)
1833    {
1834      error("Failed to allocate internet-domain X11 display socket.");
1835      return NULL;
1836    }
1837
1838  /* Start listening for connections on the socket. */
1839  if (listen(sock, 5) < 0)
1840    {
1841      error("listen: %.100s", strerror(errno));
1842      shutdown(sock, 2);
1843      close(sock);
1844      return NULL;
1845    }
1846
1847  /* Set up a suitable value for the DISPLAY variable. */
1848#ifdef NONSTANDARD_IP_ADDRESS_X11_KLUDGE
1849  /* HPSUX has some special shared memory stuff in their X server, which
1850     appears to be enabled if the host name matches that of the local machine.
1851     However, it can be circumvented by using the IP address of the local
1852     machine instead.  */
1853  if (gethostname(hostname, sizeof(hostname)) < 0)
1854    fatal("gethostname: %.100s", strerror(errno));
1855  {
1856    struct hostent *hp;
1857    struct in_addr addr;
1858    hp = gethostbyname(hostname);
1859    if (hp == NULL || !hp->h_addr_list[0])
1860      {
1861        error("Could not get server IP address for %.200s.", hostname);
1862        packet_send_debug("Could not get server IP address for %.200s.",
1863                          hostname);
1864        shutdown(sock, 2);
1865        close(sock);
1866        return NULL;
1867      }
1868    memcpy(&addr, hp->h_addr_list[0], sizeof(addr));
1869    sprintf(buf, "%.100s:%d.%d", inet_ntoa(addr), display_number,
1870            screen_number);
1871  }
1872#else /* NONSTANDARD_IP_ADDRESS_X11_KLUDGE */
1873#ifdef HAVE_GETHOSTNAME
1874  if (gethostname(hostname, sizeof(hostname)) < 0)
1875    fatal("gethostname: %.100s", strerror(errno));
1876  sprintf(buf, "%.400s:%d.%d", hostname, display_number, screen_number);
1877#else /* HAVE_GETHOSTNAME */
1878  if (uname(&uts) < 0)
1879    fatal("uname: %s", strerror(errno));
1880  sprintf(buf, "%.400s:%d.%d", uts.nodename, display_number, screen_number);
1881#endif /* HAVE_GETHOSTNAME */
1882#endif /* NONSTANDARD_IP_ADDRESS_X11_KLUDGE */
1883           
1884  /* Allocate a channel for the socket. */
1885  (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1886                         xstrdup("X11 inet listener"));
1887
1888  /* Return a suitable value for the DISPLAY environment variable. */
1889  return xstrdup(buf);
1890}
1891
1892/* This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
1893   the remote channel number.  We should do whatever we want, and respond
1894   with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
1895
1896void x11_input_open(void)
1897{
1898  int remote_channel, display_number, sock, newch;
1899  const char *display;
1900  struct sockaddr_un ssun;
1901  struct sockaddr_in sin;
1902  char buf[255], *cp, *remote_host;
1903  struct hostent *hp;
1904
1905  /* Get remote channel number. */
1906  remote_channel = packet_get_int();
1907
1908  /* Get remote originator name. */
1909  if (have_hostname_in_open)
1910    remote_host = packet_get_string(NULL);
1911  else
1912    remote_host = xstrdup("unknown (remote did not supply name)");
1913
1914  debug("Received X11 open request.");
1915
1916  if (!x11_forwarding_permitted)
1917    {
1918      error("Warning: Server attempted X11 forwarding without client request");
1919      error("Warning: This is a probable break-in attempt (compromised server?)");
1920      goto fail;
1921    }
1922 
1923
1924  /* Try to open a socket for the local X server. */
1925  display = getenv("DISPLAY");
1926  if (!display)
1927    {
1928      error("DISPLAY not set.");
1929      goto fail;
1930    }
1931 
1932  /* Now we decode the value of the DISPLAY variable and make a connection
1933     to the real X server. */
1934
1935  /* Check if it is a unix domain socket.  Unix domain displays are in one
1936     of the following formats: unix:d[.s], :d[.s], ::d[.s] */
1937  if (strncmp(display, "unix:", 5) == 0 ||
1938      display[0] == ':')
1939    {
1940      /* Connect to the unix domain socket. */
1941      if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
1942        {
1943          error("Could not parse display number from DISPLAY: %.100s",
1944                display);
1945          goto fail;
1946        }
1947      /* Create a socket. */
1948      sock = socket(AF_UNIX, SOCK_STREAM, 0);
1949      if (sock < 0)
1950        {
1951          error("socket: %.100s", strerror(errno));
1952          goto fail;
1953        }
1954      /* Connect it to the display socket. */
1955      ssun.sun_family = AF_UNIX;
1956#ifdef HPSUX_NONSTANDARD_X11_KLUDGE
1957      {
1958        /* HPSUX release 10.X uses /var/spool/sockets/X11/0 for the
1959           unix-domain sockets, while earlier releases stores the
1960           socket in /usr/spool/sockets/X11/0 with soft-link from
1961           /tmp/.X11-unix/`uname -n`0 */
1962
1963        struct stat st;
1964
1965        if (stat("/var/spool/sockets/X11", &st) == 0)
1966          {
1967            sprintf(ssun.sun_path, "%s/%d",
1968                    "/var/spool/sockets/X11", display_number);
1969          }
1970        else
1971          {
1972            if (stat("/usr/spool/sockets/X11", &st) == 0)
1973              {
1974                sprintf(ssun.sun_path, "%s/%d",
1975                        "/usr/spool/sockets/X11", display_number);
1976              }
1977            else
1978              {
1979                struct utsname utsbuf;
1980                /* HPSUX stores unix-domain sockets in
1981                   /tmp/.X11-unix/`hostname`0
1982                   instead of the normal /tmp/.X11-unix/X0. */
1983                if (uname(&utsbuf) < 0)
1984                  fatal("uname: %.100s", strerror(errno));
1985                sprintf(ssun.sun_path, "%.20s/%.64s%d",
1986                        X11_DIR, utsbuf.nodename, display_number);
1987              }
1988          }
1989      }
1990#else /* HPSUX_NONSTANDARD_X11_KLUDGE */
1991      {
1992        struct stat st;
1993
1994        if (stat("/var/X", &st) == 0)
1995          {
1996            sprintf(ssun.sun_path, "%.80s/X%d", "/var/X/.X11-unix",
1997                    display_number);
1998          }
1999        else if (stat(X11_DIR, &st) == 0)
2000          {
2001            sprintf(ssun.sun_path, "%.80s/X%d", X11_DIR, display_number);
2002          }
2003        else
2004          {
2005            sprintf(ssun.sun_path, "%.80s/X%d", "/tmp/.X11-unix",
2006                    display_number);
2007          }
2008      }
2009#endif /* HPSUX_NONSTANDARD_X11_KLUDGE */
2010      if (connect(sock, (struct sockaddr *)&ssun, AF_UNIX_SIZE(ssun)) < 0)
2011        {
2012          error("connect %.100s: %.100s", ssun.sun_path, strerror(errno));
2013          close(sock);
2014          goto fail;
2015        }
2016
2017      /* OK, we now have a connection to the display. */
2018      goto success;
2019    }
2020 
2021  /* Connect to an inet socket.  The DISPLAY value is supposedly
2022      hostname:d[.s], where hostname may also be numeric IP address. */
2023  strncpy(buf, display, sizeof(buf));
2024  buf[sizeof(buf) - 1] = 0;
2025  cp = strchr(buf, ':');
2026  if (!cp)
2027    {
2028      error("Could not find ':' in DISPLAY: %.100s", display);
2029      goto fail;
2030    }
2031  *cp = 0;
2032  /* buf now contains the host name.  But first we parse the display number. */
2033  if (sscanf(cp + 1, "%d", &display_number) != 1)
2034    {
2035       error("Could not parse display number from DISPLAY: %.100s",
2036             display);
2037      goto fail;
2038    }
2039 
2040  /* Try to parse the host name as a numeric IP address. */
2041  memset(&sin, 0, sizeof(sin));
2042#ifdef BROKEN_INET_ADDR
2043  sin.sin_addr.s_addr = inet_network(buf);
2044#else /* BROKEN_INET_ADDR */
2045  sin.sin_addr.s_addr = inet_addr(buf);
2046#endif /* BROKEN_INET_ADDR */
2047  if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
2048    {
2049      /* It was a valid numeric host address. */
2050      sin.sin_family = AF_INET;
2051    }
2052  else
2053    {
2054      /* Not a numeric IP address. */
2055      /* Look up the host address from the name servers. */
2056      hp = gethostbyname(buf);
2057      if (!hp)
2058        {
2059          error("%.100s: unknown host.", buf);
2060          goto fail;
2061        }
2062      if (!hp->h_addr_list[0])
2063        {
2064          error("%.100s: host has no IP address.", buf);
2065          goto fail;
2066        }
2067      sin.sin_family = hp->h_addrtype;
2068      memcpy(&sin.sin_addr, hp->h_addr_list[0],
2069             sizeof(sin.sin_addr));
2070    }
2071  /* Set port number. */
2072  sin.sin_port = htons(6000 + display_number);
2073
2074  /* Create a socket. */
2075  sock = socket(sin.sin_family, SOCK_STREAM, 0);
2076  if (sock < 0)
2077    {
2078      error("socket: %.100s", strerror(errno));
2079      goto fail;
2080    }
2081  /* Connect it to the display. */
2082  if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
2083    {
2084      error("connect %.100s:%d: %.100s", buf, 6000 + display_number,
2085            strerror(errno));
2086      close(sock);
2087      goto fail;
2088    }
2089
2090 success:
2091  /* We have successfully obtained a connection to the real X display. */
2092
2093#if defined(O_NONBLOCK) && !defined(O_NONBLOCK_BROKEN)
2094      (void)fcntl(sock, F_SETFL, O_NONBLOCK);
2095#else /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
2096      (void)fcntl(sock, F_SETFL, O_NDELAY);
2097#endif /* O_NONBLOCK && !O_NONBLOCK_BROKEN */
2098 
2099  /* Allocate a channel for this connection. */
2100  if (x11_saved_proto == NULL)
2101    newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
2102  else
2103    newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
2104  channels[newch].is_x_connection = 1;
2105  channels[newch].remote_id = remote_channel;
2106 
2107  debug("Sending open confirmation to the remote host.");
2108
2109  /* Send a confirmation to the remote host. */
2110  packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2111  packet_put_int(remote_channel);
2112  packet_put_int(newch);
2113  packet_send();
2114 
2115  return;
2116
2117 fail:
2118  debug ("Failed...");
2119  /* Send refusal to the remote host. */
2120  packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2121  packet_put_int(remote_channel);
2122  packet_send();
2123}
2124
2125/* Requests forwarding of X11 connections, generates fake authentication
2126   data, and enables authentication spoofing. */
2127
2128void x11_request_forwarding_with_spoofing(RandomState *state,
2129                                          const char *proto, const char *data)
2130{
2131  unsigned int data_len = (unsigned int)strlen(data) / 2;
2132  unsigned int i, value;
2133  char *new_data;
2134  int screen_number;
2135  const char *cp;
2136
2137  cp = getenv("DISPLAY");
2138  if (cp)
2139    cp = strchr(cp, ':');
2140  if (cp)
2141    cp = strchr(cp, '.');
2142  if (cp)
2143    screen_number = atoi(cp + 1);
2144  else
2145    screen_number = 0;
2146
2147  /* Save protocol name. */
2148  x11_saved_proto = xstrdup(proto);
2149
2150  /* Extract real authentication data and generate fake data of the same
2151     length. */
2152  x11_saved_data = xmalloc(data_len);
2153  x11_fake_data = xmalloc(data_len);
2154  for (i = 0; i < data_len; i++)
2155    {
2156      if (sscanf(data + 2 * i, "%2x", &value) != 1)
2157        fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2158      x11_saved_data[i] = value;
2159      x11_fake_data[i] = random_get_byte(state);
2160    }
2161  x11_saved_data_len = data_len;
2162  x11_fake_data_len = data_len;
2163
2164  /* Convert the fake data into hex. */
2165  new_data = xmalloc(2 * data_len + 1);
2166  for (i = 0; i < data_len; i++)
2167    sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
2168
2169  /* Send the request packet. */
2170  packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2171  packet_put_string(proto, strlen(proto));
2172  packet_put_string(new_data, strlen(new_data));
2173  packet_put_int(screen_number);
2174  packet_send();
2175  packet_write_wait();
2176  xfree(new_data);
2177  x11_forwarding_permitted = 1;
2178}
2179
2180/* Sends a message to the server to request authentication fd forwarding. */
2181
2182void auth_request_forwarding(void)
2183{
2184  packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2185  packet_send();
2186  packet_write_wait();
2187  auth_forwarding_permitted = 1;
2188}
2189
2190/* Returns the number of the file descriptor to pass to child programs as
2191   the authentication fd.  Returns -1 if there is no forwarded authentication
2192   fd. */
2193
2194int auth_get_fd(void)
2195{
2196  return channel_forwarded_auth_fd;
2197}
2198
2199/* Returns the name of the forwarded authentication socket.  Returns NULL
2200   if there is no forwarded authentication socket.  The returned value
2201   points to a static buffer. */
2202
2203char *auth_get_socket_name(void)
2204{
2205  return channel_forwarded_auth_socket_name;
2206}
2207
2208/* Called on exit, tries to remove authentication socket and per-user
2209   socket directory */
2210
2211void auth_delete_socket(void *context)
2212{
2213  if (channel_forwarded_auth_socket_name)
2214    {
2215      remove(channel_forwarded_auth_socket_name);
2216      xfree(channel_forwarded_auth_socket_name);
2217      channel_forwarded_auth_socket_name = NULL;
2218    }
2219  if (channel_forwarded_auth_socket_dir_name)
2220    {
2221      chdir("/");
2222      rmdir(channel_forwarded_auth_socket_dir_name);
2223      xfree(channel_forwarded_auth_socket_dir_name);
2224      channel_forwarded_auth_socket_dir_name = NULL;
2225    }
2226}
2227
2228/* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2229   This starts forwarding authentication requests.
2230   Socket directory will be owned by the user, and will have 700-
2231   permissions. Actual socket will have 222-permissions and can be
2232   owned by anyone (sshd's socket will be owned by root and
2233   ssh-agent's by user). This returns true if everything succeeds, otherwise it
2234   will return false (agent forwarding disabled). */
2235
2236int auth_input_request_forwarding(struct passwd *pw)
2237{
2238  int ret;
2239  int sock, newch, directory_created;
2240  struct sockaddr_un sunaddr;
2241  struct stat st, st2, parent_st;
2242  mode_t old_umask;
2243  char *last_dir;
2244 
2245  if (auth_get_socket_name() != NULL)
2246    fatal("Protocol error: authentication forwarding requested twice.");
2247 
2248  /* Allocate a buffer for the socket name, and format the name.
2249     And directory name. */
2250  channel_forwarded_auth_socket_name = xmalloc(strlen(SSH_AGENT_SOCKET_DIR) +
2251                                               strlen(SSH_AGENT_SOCKET) +
2252                                               strlen(pw->pw_name) + 10);
2253  channel_forwarded_auth_socket_dir_name =
2254    xmalloc(strlen(SSH_AGENT_SOCKET_DIR) +
2255            strlen(pw->pw_name) + 10);
2256
2257  sprintf(channel_forwarded_auth_socket_dir_name,
2258          SSH_AGENT_SOCKET_DIR, pw->pw_name);
2259  /* Use the plain socket name for now, change to absolute
2260     path later */
2261  sprintf(channel_forwarded_auth_socket_name,
2262          SSH_AGENT_SOCKET, (int)getpid());
2263 
2264  /* Register the cleanup function before making the directory */
2265  fatal_add_cleanup(&auth_delete_socket, NULL);
2266
2267  /* Stat parent dir */
2268  last_dir = strrchr(channel_forwarded_auth_socket_dir_name, '/');
2269  if (last_dir == NULL || last_dir == channel_forwarded_auth_socket_dir_name)
2270    {
2271      packet_send_debug("* Remote error: Invalid SSH_AGENT_SOCKET_DIR \'%.100s\', it should contain at least one /.",
2272            channel_forwarded_auth_socket_dir_name);
2273      packet_send_debug("* Remote error: Authentication fowarding disabled.");
2274      return 0;
2275    }
2276  *last_dir = '\0';
2277  ret = stat(channel_forwarded_auth_socket_dir_name, &parent_st);
2278  if (ret < 0)
2279    {
2280      packet_send_debug("* Remote error: Agent parent directory \'%.100s\' stat failed: %.100s",
2281            channel_forwarded_auth_socket_dir_name,
2282            strerror(errno));
2283      packet_send_debug("* Remote error: Authentication fowarding disabled.");
2284      return 0;
2285    }
2286  *last_dir = '/';
2287 
2288  /* Check the per-user socket directory. Stat it, if it
2289     doesn't exist, mkdir it and stat it. Then chdir to it
2290     and stat "." and compare it with the earlier stat (dev
2291     and inode) so that we can be sure we ended where we
2292     wanted. Then stat ".." and check that it is sticky.
2293     Only after this we can think about chowning the ".". */
2294 
2295  ret = lstat(channel_forwarded_auth_socket_dir_name, &st);
2296  directory_created = 0;
2297  if (ret < 0 && errno != ENOENT)
2298    {
2299      packet_send_debug("* Remote error: stat of agent directory \'%.100s\' failed: %.100s",
2300            channel_forwarded_auth_socket_dir_name,
2301            strerror(errno));
2302      packet_send_debug("* Remote error: Authentication fowarding disabled.");
2303      return 0;
2304    }
2305  if (ret < 0 && errno == ENOENT)
2306    {
2307      if (mkdir(channel_forwarded_auth_socket_dir_name, S_IRWXU) == 0)
2308        {
2309          directory_created = 1;
2310          ret = lstat(channel_forwarded_auth_socket_dir_name, &st);
2311        }
2312      else
2313        {
2314          packet_send_debug("* Remote error: Agent directory \'%.100s\' mkdir failed: %.100s",
2315                channel_forwarded_auth_socket_dir_name,
2316                strerror(errno));
2317          packet_send_debug("* Remote error: Authentication fowarding disabled.");
2318          return 0;
2319        }
2320    }
2321  else
2322    {
2323      /* Simple owner & mode check. If directory has just been created,
2324         don't care about the owner yet. */
2325      if ((st.st_uid != pw->pw_uid) || (st.st_mode & 077) != 0)
2326        {
2327          packet_send_debug("* Remote error: Agent socket creation:"
2328                "Bad modes/owner for directory \'%s\' (modes are %o, should be 040700)",
2329                channel_forwarded_auth_socket_dir_name,
2330                st.st_mode);
2331          packet_send_debug("* Remote error: Authentication fowarding disabled.");
2332          return 0;
2333        }
2334    }
2335  chdir(channel_forwarded_auth_socket_dir_name);
2336 
2337  /* Check that we really are where we wanted to go */
2338  if (stat(".", &st2) != 0)
2339    {
2340      packet_send_debug("* Remote error: stat \'.\' failed after chdir to \'%.100s\': %.100s",
2341            channel_forwarded_auth_socket_dir_name, strerror(errno));
2342      packet_send_debug("* Remote error: Authentication fowarding disabled.");
2343      return 0;
2344    }
2345  if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
2346    {
2347      packet_send_debug("* Remote error: Agent socket creation: wrong directory after chdir");
2348      packet_send_debug("* Remote error: Authentication fowarding disabled.");
2349      return 0;
2350    }
2351
2352  /* Check that parent is sticky, and it really is what it is supposed to be */
2353  if (stat("..", &st) != 0)
2354    {
2355      packet_send_debug("* Remote error: Agent socket directory stat \'..\' failed: %.100s",
2356            strerror(errno));
2357      packet_send_debug("* Remote error: Authentication fowarding disabled.");
2358      return 0;
2359    }
2360  if ((st.st_mode & 01000) == 0)
2361    {
2362      packet_send_debug("* Remote error: Agent socket creation: Directory \'%s/..\' is not sticky, mode is %o, should be 041777",
2363            channel_forwarded_auth_socket_dir_name, st.st_mode);
2364      packet_send_debug("* Remote error: Authentication forwarding disabled.");
2365      return 0;
2366    }
2367  if (st.st_dev != parent_st.st_dev || st.st_ino != parent_st.st_ino)
2368    {
2369      packet_send_debug("* Remote error: Agent socket creation: wrong parent directory after chdir (last component of socket name is symlink?)");
2370      packet_send_debug("* Remote error: Authentication fowarding disabled.");
2371      return 0;
2372    }
2373 
2374  /* Create the socket. */
2375  sock = socket(AF_UNIX, SOCK_STREAM, 0);
2376  if (sock < 0)
2377    packet_disconnect("Agent socket creation failed: %.100s", strerror(errno));
2378 
2379  /* Bind it to the name. */
2380  memset(&sunaddr, 0, AF_UNIX_SIZE(sunaddr));
2381  sunaddr.sun_family = AF_UNIX;
2382  strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2383          sizeof(sunaddr.sun_path));
2384 
2385  /* Use umask to get desired permissions, chmod is too dangerous
2386     NOTE: If your system doesn't handle umask correctly when
2387     creating unix-domain sockets, you might not be able to use
2388     ssh-agent connections on your system */
2389  old_umask = umask(S_IRUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
2390 
2391  if (bind(sock, (struct sockaddr *)&sunaddr, AF_UNIX_SIZE(sunaddr)) < 0)
2392    packet_disconnect("Agent socket bind failed: %.100s", strerror(errno));
2393 
2394  umask(old_umask);
2395 
2396  if (directory_created)
2397    if (chown(".", pw->pw_uid, pw->pw_gid) < 0)
2398      packet_disconnect("Agent socket directory chown failed: %.100s",
2399                        strerror(errno));
2400
2401  /* Start listening on the socket. */
2402  if (listen(sock, 5) < 0)
2403    packet_disconnect("Agent socket listen failed: %.100s", strerror(errno));
2404
2405  /* Change the relative socket name to absolute */
2406  sprintf(channel_forwarded_auth_socket_name,
2407          SSH_AGENT_SOCKET_DIR"/"SSH_AGENT_SOCKET,
2408          pw->pw_name, (int)getpid());
2409   
2410  /* Allocate a channel for the authentication agent socket. */
2411  newch = channel_allocate(SSH_CHANNEL_AUTH_LISTENER, sock,
2412                           xstrdup("auth socket"));
2413  strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
2414  return 1;
2415}
2416
2417/* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2418
2419void auth_input_open_request(void)
2420{
2421  int remote_channel, sock, newch;
2422  char *dummyname;
2423
2424  /* Read the port number from the message. */
2425  remote_channel = packet_get_int();
2426
2427  if (!auth_forwarding_permitted)
2428    {
2429      error("Warning: Server attempted agent forwarding without client request");
2430      error("Warning: This is a probable break-in attempt (compromised server?)");
2431      packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2432      packet_put_int(remote_channel);
2433      packet_send();
2434      return;
2435    }
2436  /* Get a connection to the local authentication agent (this may again get
2437     forwarded). */
2438  sock = ssh_get_authentication_connection_fd();
2439
2440  /* If we could not connect the agent, inform the server side that
2441     opening failed. This should never happen unless the agent
2442     dies, because authentication forwarding is only enabled if we
2443     have an agent. */
2444  if (sock < 0)
2445    {
2446      packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2447      packet_put_int(remote_channel);
2448      packet_send();
2449      return;
2450    }
2451 
2452  debug("Forwarding authentication connection.");
2453
2454  dummyname = xstrdup("authentication agent connection");
2455 
2456  /* Allocate a channel for this connection. */
2457  newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2458  channels[newch].remote_id = remote_channel;
2459 
2460  /* Send a confirmation to the remote host. */
2461  packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2462  packet_put_int(remote_channel);
2463  packet_put_int(newch);
2464  packet_send();
2465}
Note: See TracBrowser for help on using the repository browser.