]> andersk Git - openssh.git/blob - channels.c
Merged latest OpenBSD changes:
[openssh.git] / channels.c
1 /*
2
3 channels.c
4
5 Author: Tatu Ylonen <ylo@cs.hut.fi>
6
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
8                    All rights reserved
9
10 Created: Fri Mar 24 16:35:24 1995 ylo
11
12 This file contains functions for generic socket connection forwarding.
13 There is also code for initiating connection forwarding for X11 connections,
14 arbitrary tcp/ip connections, and the authentication agent connection.
15
16 */
17
18 #include "includes.h"
19 RCSID("$Id$");
20
21 #include "ssh.h"
22 #include "packet.h"
23 #include "xmalloc.h"
24 #include "buffer.h"
25 #include "authfd.h"
26 #include "uidswap.h"
27 #include "servconf.h"
28
29 #include "channels.h"
30 #include "nchan.h"
31 #include "compat.h"
32
33 /* Maximum number of fake X11 displays to try. */
34 #define MAX_DISPLAYS  1000
35
36 /* Max len of agent socket */
37 #define MAX_SOCKET_NAME 100
38
39 /* Pointer to an array containing all allocated channels.  The array is
40    dynamically extended as needed. */
41 static Channel *channels = NULL;
42
43 /* Size of the channel array.  All slots of the array must always be
44    initialized (at least the type field); unused slots are marked with
45    type SSH_CHANNEL_FREE. */
46 static int channels_alloc = 0;
47
48 /* Maximum file descriptor value used in any of the channels.  This is updated
49    in channel_allocate. */
50 static int channel_max_fd_value = 0;
51
52 /* Name and directory of socket for authentication agent forwarding. */
53 static char *channel_forwarded_auth_socket_name = NULL;
54 static char *channel_forwarded_auth_socket_dir  = NULL;
55
56 /* Saved X11 authentication protocol name. */
57 char *x11_saved_proto = NULL;
58
59 /* Saved X11 authentication data.  This is the real data. */
60 char *x11_saved_data = NULL;
61 unsigned int x11_saved_data_len = 0;
62
63 /* Fake X11 authentication data.  This is what the server will be sending
64    us; we should replace any occurrences of this by the real data. */
65 char *x11_fake_data = NULL;
66 unsigned int x11_fake_data_len;
67
68 /* Data structure for storing which hosts are permitted for forward requests.
69    The local sides of any remote forwards are stored in this array to prevent
70    a corrupt remote server from accessing arbitrary TCP/IP ports on our
71    local network (which might be behind a firewall). */
72 typedef struct
73 {
74   char *host;           /* Host name. */
75   int port;             /* Port number. */
76 } ForwardPermission;
77
78 /* List of all permitted host/port pairs to connect. */
79 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
80 /* Number of permitted host/port pairs in the array. */
81 static int num_permitted_opens = 0;
82 /* If this is true, all opens are permitted.  This is the case on the
83    server on which we have to trust the client anyway, and the user could
84    do anything after logging in anyway. */
85 static int all_opens_permitted = 0;
86
87 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
88 static int have_hostname_in_open = 0;
89
90 /* Sets specific protocol options. */
91
92 void channel_set_options(int hostname_in_open)
93 {
94   have_hostname_in_open = hostname_in_open;
95 }
96
97 /* Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
98    called by the server, because the user could connect to any port anyway,
99    and the server has no way to know but to trust the client anyway. */
100
101 void channel_permit_all_opens()
102 {
103   all_opens_permitted = 1;
104 }
105
106 /* Allocate a new channel object and set its type and socket. 
107    This will cause remote_name to be freed. */
108
109 int channel_allocate(int type, int sock, char *remote_name)
110 {
111   int i, found;
112   Channel *c;
113
114   /* Update the maximum file descriptor value. */
115   if (sock > channel_max_fd_value)
116     channel_max_fd_value = sock;
117
118   /* Do initial allocation if this is the first call. */
119   if (channels_alloc == 0)
120     {
121       channels_alloc = 10;
122       channels = xmalloc(channels_alloc * sizeof(Channel));
123       for (i = 0; i < channels_alloc; i++)
124         channels[i].type = SSH_CHANNEL_FREE;
125
126       /* Kludge: arrange a call to channel_stop_listening if we terminate
127          with fatal(). */
128       fatal_add_cleanup((void (*)(void *))channel_stop_listening, NULL);
129     }
130
131   /* Try to find a free slot where to put the new channel. */
132   for (found = -1, i = 0; i < channels_alloc; i++)
133     if (channels[i].type == SSH_CHANNEL_FREE)
134       {
135         /* Found a free slot. */
136         found = i;
137         break;
138       }
139
140   if (found == -1)
141     {
142       /* There are no free slots.  Take last+1 slot and expand the array.  */
143       found = channels_alloc;
144       channels_alloc += 10;
145       debug("channel: expanding %d", channels_alloc);
146       channels = xrealloc(channels, channels_alloc * sizeof(Channel));
147       for (i = found; i < channels_alloc; i++)
148         channels[i].type = SSH_CHANNEL_FREE;
149     }
150
151   /* Initialize and return new channel number. */
152   c=&channels[found];
153   buffer_init(&c->input);
154   buffer_init(&c->output);
155   chan_init_iostates(c);
156   c->self = found;
157   c->type = type;
158   c->sock = sock;
159   c->remote_id = -1;
160   c->remote_name = remote_name;
161   debug("channel %d: new [%s]", found, remote_name);
162   return found;
163 }
164
165 /* Free the channel and close its socket. */
166
167 void channel_free(int channel)
168 {
169   assert(channel >= 0 && channel < channels_alloc &&
170          channels[channel].type != SSH_CHANNEL_FREE);
171   if(compat13)
172     shutdown(channels[channel].sock, SHUT_RDWR);
173   close(channels[channel].sock);
174   buffer_free(&channels[channel].input);
175   buffer_free(&channels[channel].output);
176   channels[channel].type = SSH_CHANNEL_FREE;
177   if (channels[channel].remote_name)
178     {
179       xfree(channels[channel].remote_name);
180       channels[channel].remote_name = NULL;
181     }
182 }
183
184 /* This is called just before select() to add any bits relevant to
185    channels in the select bitmasks. */
186
187 void channel_prepare_select(fd_set *readset, fd_set *writeset)
188 {
189   int i;
190   Channel *ch;
191   unsigned char *ucp;
192   unsigned int proto_len, data_len;
193
194   for (i = 0; i < channels_alloc; i++)
195     {
196       ch = &channels[i];
197     redo:
198       switch (ch->type)
199         {
200         case SSH_CHANNEL_X11_LISTENER:
201         case SSH_CHANNEL_PORT_LISTENER:
202         case SSH_CHANNEL_AUTH_SOCKET:
203           FD_SET(ch->sock, readset);
204           break;
205
206         case SSH_CHANNEL_OPEN:
207           if(compat13){
208             if (buffer_len(&ch->input) < 32768)
209               FD_SET(ch->sock, readset);
210             if (buffer_len(&ch->output) > 0)
211               FD_SET(ch->sock, writeset);
212             break;
213           }
214           /* test whether sockets are 'alive' for read/write */
215           if (ch->istate == CHAN_INPUT_OPEN)
216             if (buffer_len(&ch->input) < 32768)
217               FD_SET(ch->sock, readset);
218           if (ch->ostate == CHAN_OUTPUT_OPEN || ch->ostate == CHAN_OUTPUT_WAIT_DRAIN){
219             if (buffer_len(&ch->output) > 0){
220               FD_SET(ch->sock, writeset);
221             }else if(ch->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
222               chan_obuf_empty(ch);
223             }
224           }
225           break;
226
227         case SSH_CHANNEL_INPUT_DRAINING:
228           if (!compat13)
229             fatal("cannot happen: IN_DRAIN");
230           if (buffer_len(&ch->input) == 0)
231             {
232               packet_start(SSH_MSG_CHANNEL_CLOSE);
233               packet_put_int(ch->remote_id);
234               packet_send();
235               ch->type = SSH_CHANNEL_CLOSED;
236               debug("Closing channel %d after input drain.", i);
237               break;
238             }
239           break;
240
241         case SSH_CHANNEL_OUTPUT_DRAINING:
242           if (!compat13)
243             fatal("cannot happen: OUT_DRAIN");
244           if (buffer_len(&ch->output) == 0)
245             {
246               /* debug("Freeing channel %d after output drain.", i); */
247               channel_free(i);
248               break;
249             }
250           FD_SET(ch->sock, writeset);
251           break;
252
253         case SSH_CHANNEL_X11_OPEN:
254           /* This is a special state for X11 authentication spoofing.  An
255              opened X11 connection (when authentication spoofing is being
256              done) remains in this state until the first packet has been
257              completely read.  The authentication data in that packet is
258              then substituted by the real data if it matches the fake data,
259              and the channel is put into normal mode. */
260
261           /* Check if the fixed size part of the packet is in buffer. */
262           if (buffer_len(&ch->output) < 12)
263             break;
264
265           /* Parse the lengths of variable-length fields. */
266           ucp = (unsigned char *)buffer_ptr(&ch->output);
267           if (ucp[0] == 0x42)
268             { /* Byte order MSB first. */
269               proto_len = 256 * ucp[6] + ucp[7];
270               data_len = 256 * ucp[8] + ucp[9];
271             }
272           else
273             if (ucp[0] == 0x6c)
274               { /* Byte order LSB first. */
275                 proto_len = ucp[6] + 256 * ucp[7];
276                 data_len = ucp[8] + 256 * ucp[9];
277               }
278             else
279               {
280                 debug("Initial X11 packet contains bad byte order byte: 0x%x",
281                       ucp[0]);
282                 ch->type = SSH_CHANNEL_OPEN;
283                 goto reject;
284               }
285
286           /* Check if the whole packet is in buffer. */
287           if (buffer_len(&ch->output) <
288               12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
289             break;
290           
291           /* Check if authentication protocol matches. */
292           if (proto_len != strlen(x11_saved_proto) || 
293               memcmp(ucp + 12, x11_saved_proto, proto_len) != 0)
294             {
295               debug("X11 connection uses different authentication protocol.");
296               ch->type = SSH_CHANNEL_OPEN;
297               goto reject;
298             }
299
300           /* Check if authentication data matches our fake data. */
301           if (data_len != x11_fake_data_len ||
302               memcmp(ucp + 12 + ((proto_len + 3) & ~3),
303                      x11_fake_data, x11_fake_data_len) != 0)
304             {
305               debug("X11 auth data does not match fake data.");
306               ch->type = SSH_CHANNEL_OPEN;
307               goto reject;
308             }
309
310           /* Received authentication protocol and data match our fake data.
311              Substitute the fake data with real data. */
312           assert(x11_fake_data_len == x11_saved_data_len);
313           memcpy(ucp + 12 + ((proto_len + 3) & ~3),
314                  x11_saved_data, x11_saved_data_len);
315
316           /* Start normal processing for the channel. */
317           ch->type = SSH_CHANNEL_OPEN;
318           goto redo;
319           
320         reject:
321           /* We have received an X11 connection that has bad authentication
322              information. */
323           log("X11 connection rejected because of wrong authentication.\r\n");
324           buffer_clear(&ch->input);
325           buffer_clear(&ch->output);
326           if (compat13) {
327             close(ch->sock);
328             ch->sock = -1;
329             ch->type = SSH_CHANNEL_CLOSED;
330             packet_start(SSH_MSG_CHANNEL_CLOSE);
331             packet_put_int(ch->remote_id);
332             packet_send();
333           }else{
334             debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
335             chan_read_failed(ch);
336             chan_write_failed(ch);
337             debug("X11 rejected %d i%d/o%d", ch->self, ch->istate, ch->ostate);
338           }
339           break;
340
341         case SSH_CHANNEL_FREE:
342         default:
343           continue;
344         }
345     }
346 }
347
348 /* After select, perform any appropriate operations for channels which
349    have events pending. */
350
351 void channel_after_select(fd_set *readset, fd_set *writeset)
352 {
353   struct sockaddr addr;
354   int addrlen, newsock, i, newch, len;
355   Channel *ch;
356   char buf[16384], *remote_hostname;
357   
358   /* Loop over all channels... */
359   for (i = 0; i < channels_alloc; i++)
360     {
361       ch = &channels[i];
362       switch (ch->type)
363         {
364         case SSH_CHANNEL_X11_LISTENER:
365           /* This is our fake X11 server socket. */
366           if (FD_ISSET(ch->sock, readset))
367             {
368               debug("X11 connection requested.");
369               addrlen = sizeof(addr);
370               newsock = accept(ch->sock, &addr, &addrlen);
371               if (newsock < 0)
372                 {
373                   error("accept: %.100s", strerror(errno));
374                   break;
375                 }
376               remote_hostname = get_remote_hostname(newsock);
377               snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
378                       remote_hostname, get_peer_port(newsock));
379               xfree(remote_hostname);
380               newch = channel_allocate(SSH_CHANNEL_OPENING, newsock, 
381                                        xstrdup(buf));
382               packet_start(SSH_SMSG_X11_OPEN);
383               packet_put_int(newch);
384               if (have_hostname_in_open)
385                 packet_put_string(buf, strlen(buf));
386               packet_send();
387             }
388           break;
389           
390         case SSH_CHANNEL_PORT_LISTENER:
391           /* This socket is listening for connections to a forwarded TCP/IP
392              port. */
393           if (FD_ISSET(ch->sock, readset))
394             {
395               debug("Connection to port %d forwarding to %.100s:%d requested.",
396                     ch->listening_port, ch->path, ch->host_port);
397               addrlen = sizeof(addr);
398               newsock = accept(ch->sock, &addr, &addrlen);
399               if (newsock < 0)
400                 {
401                   error("accept: %.100s", strerror(errno));
402                   break;
403                 }
404               remote_hostname = get_remote_hostname(newsock);
405               snprintf(buf, sizeof buf, "listen port %d:%.100s:%d, connect from %.200s:%d",
406                       ch->listening_port, ch->path, ch->host_port,
407                       remote_hostname, get_peer_port(newsock));
408               xfree(remote_hostname);
409               newch = channel_allocate(SSH_CHANNEL_OPENING, newsock, 
410                                        xstrdup(buf));
411               packet_start(SSH_MSG_PORT_OPEN);
412               packet_put_int(newch);
413               packet_put_string(ch->path, strlen(ch->path));
414               packet_put_int(ch->host_port);
415               if (have_hostname_in_open)
416                 packet_put_string(buf, strlen(buf));
417               packet_send();
418             }
419           break;
420
421         case SSH_CHANNEL_AUTH_SOCKET:
422           /* This is the authentication agent socket listening for connections
423              from clients. */
424           if (FD_ISSET(ch->sock, readset))
425             {
426               int nchan;
427               len = sizeof(addr);
428               newsock = accept(ch->sock, &addr, &len);
429               if (newsock < 0)
430                 {
431                   error("accept from auth socket: %.100s", strerror(errno));
432                   break;
433                 }
434
435               nchan = channel_allocate(SSH_CHANNEL_OPENING, newsock,
436                                      xstrdup("accepted auth socket"));
437               packet_start(SSH_SMSG_AGENT_OPEN);
438               packet_put_int(nchan);
439               packet_send();
440             }
441           break;
442
443         case SSH_CHANNEL_OPEN:
444           /* This is an open two-way communication channel.  It is not of
445              interest to us at this point what kind of data is being
446              transmitted. */
447
448           /* Read available incoming data and append it to buffer;
449              shutdown socket, if read or write failes */
450           if (FD_ISSET(ch->sock, readset))
451             {
452               len = read(ch->sock, buf, sizeof(buf));
453               if (len <= 0)
454                 {
455                   if (compat13) {
456                     buffer_consume(&ch->output, buffer_len(&ch->output));
457                     ch->type = SSH_CHANNEL_INPUT_DRAINING;
458                     debug("Channel %d status set to input draining.", i);
459                   }else{
460                     chan_read_failed(ch);
461                   }
462                   break;
463                 }
464               buffer_append(&ch->input, buf, len);
465             }
466           /* Send buffered output data to the socket. */
467           if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
468             {
469               len = write(ch->sock, buffer_ptr(&ch->output),
470                           buffer_len(&ch->output));
471               if (len <= 0)
472                 {
473                   if (compat13) {
474                     buffer_consume(&ch->output, buffer_len(&ch->output));
475                     debug("Channel %d status set to input draining.", i);
476                     ch->type = SSH_CHANNEL_INPUT_DRAINING;
477                   }else{
478                     chan_write_failed(ch);
479                   }
480                   break;
481                 }
482               buffer_consume(&ch->output, len);
483             }
484           break;
485
486         case SSH_CHANNEL_OUTPUT_DRAINING:
487           if (!compat13)
488                 fatal("cannot happen: OUT_DRAIN");
489           /* Send buffered output data to the socket. */
490           if (FD_ISSET(ch->sock, writeset) && buffer_len(&ch->output) > 0)
491             {
492               len = write(ch->sock, buffer_ptr(&ch->output),
493                           buffer_len(&ch->output));
494               if (len <= 0)
495                 buffer_consume(&ch->output, buffer_len(&ch->output));
496               else
497                 buffer_consume(&ch->output, len);
498             }
499           break;
500
501         case SSH_CHANNEL_X11_OPEN:
502         case SSH_CHANNEL_FREE:
503         default:
504           continue;
505         }
506     }
507 }
508
509 /* If there is data to send to the connection, send some of it now. */
510
511 void channel_output_poll()
512 {
513   int len, i;
514   Channel *ch;
515
516   for (i = 0; i < channels_alloc; i++)
517     {
518       ch = &channels[i];
519       /* We are only interested in channels that can have buffered incoming
520          data. */
521       if (ch->type != SSH_CHANNEL_OPEN && 
522           ch->type != SSH_CHANNEL_INPUT_DRAINING)
523         continue;
524
525       /* Get the amount of buffered data for this channel. */
526       len = buffer_len(&ch->input);
527       if (len > 0)
528         {
529           /* Send some data for the other side over the secure connection. */
530           if (packet_is_interactive())
531             {
532               if (len > 1024)
533                 len = 512;
534             }
535           else
536             {
537               if (len > 16384)
538                 len = 16384;  /* Keep the packets at reasonable size. */
539             }
540           packet_start(SSH_MSG_CHANNEL_DATA);
541           packet_put_int(ch->remote_id);
542           packet_put_string(buffer_ptr(&ch->input), len);
543           packet_send();
544           buffer_consume(&ch->input, len);
545         }
546       else if(ch->istate == CHAN_INPUT_WAIT_DRAIN)
547         {
548           if (compat13)
549              fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
550           /* input-buffer is empty and read-socket shutdown:
551              tell peer, that we will not send more data: send IEOF */
552           chan_ibuf_empty(ch);
553         }
554     }
555 }
556
557 /* This is called when a packet of type CHANNEL_DATA has just been received.
558    The message type has already been consumed, but channel number and data
559    is still there. */
560
561 void channel_input_data(int payload_len)
562 {
563   int channel;
564   char *data;
565   unsigned int data_len;
566
567   /* Get the channel number and verify it. */
568   channel = packet_get_int();
569   if (channel < 0 || channel >= channels_alloc ||
570       channels[channel].type == SSH_CHANNEL_FREE)
571     packet_disconnect("Received data for nonexistent channel %d.", channel);
572
573   /* Ignore any data for non-open channels (might happen on close) */
574   if (channels[channel].type != SSH_CHANNEL_OPEN &&
575       channels[channel].type != SSH_CHANNEL_X11_OPEN)
576     return; 
577
578   /* Get the data. */
579   data = packet_get_string(&data_len);
580   packet_integrity_check(payload_len, 4 + 4+data_len, SSH_MSG_CHANNEL_DATA);
581   buffer_append(&channels[channel].output, data, data_len);
582   xfree(data);
583 }
584
585 /* Returns true if no channel has too much buffered data, and false if
586    one or more channel is overfull. */
587
588 int channel_not_very_much_buffered_data()
589 {
590   unsigned int i;
591   Channel *ch;
592   
593   for (i = 0; i < channels_alloc; i++)
594     {
595       ch = &channels[i];
596       switch (ch->type)
597         {
598         case SSH_CHANNEL_X11_LISTENER:
599         case SSH_CHANNEL_PORT_LISTENER:
600         case SSH_CHANNEL_AUTH_SOCKET:
601           continue;
602         case SSH_CHANNEL_OPEN:
603           if (buffer_len(&ch->input) > 32768)
604             return 0;
605           if (buffer_len(&ch->output) > 32768)
606             return 0;
607           continue;
608         case SSH_CHANNEL_INPUT_DRAINING:
609         case SSH_CHANNEL_OUTPUT_DRAINING:
610         case SSH_CHANNEL_X11_OPEN:
611         case SSH_CHANNEL_FREE:
612         default:
613           continue;
614         }
615     }
616   return 1;
617 }
618
619 /* This is called after receiving CHANNEL_CLOSE/IEOF. */
620
621 void channel_input_close()
622 {
623   int channel;
624
625   /* Get the channel number and verify it. */
626   channel = packet_get_int();
627   if (channel < 0 || channel >= channels_alloc ||
628       channels[channel].type == SSH_CHANNEL_FREE)
629     packet_disconnect("Received data for nonexistent channel %d.", channel);
630
631   if(!compat13){
632     /* proto version 1.5 overloads CLOSE with IEOF */
633     chan_rcvd_ieof(&channels[channel]);
634     return;
635   }
636
637   /* Send a confirmation that we have closed the channel and no more data is
638      coming for it. */
639   packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
640   packet_put_int(channels[channel].remote_id);
641   packet_send();
642
643   /* If the channel is in closed state, we have sent a close request, and
644      the other side will eventually respond with a confirmation.  Thus,
645      we cannot free the channel here, because then there would be no-one to
646      receive the confirmation.  The channel gets freed when the confirmation
647      arrives. */
648   if (channels[channel].type != SSH_CHANNEL_CLOSED)
649     {
650       /* Not a closed channel - mark it as draining, which will cause it to
651          be freed later. */
652       buffer_consume(&channels[channel].input, 
653                      buffer_len(&channels[channel].input));
654       channels[channel].type = SSH_CHANNEL_OUTPUT_DRAINING;
655       /* debug("Setting status to output draining; output len = %d",
656          buffer_len(&channels[channel].output)); */
657     }
658 }
659
660 /* This is called after receiving CHANNEL_CLOSE_CONFIRMATION/OCLOSE. */
661
662 void channel_input_close_confirmation()
663 {
664   int channel;
665
666   /* Get the channel number and verify it. */
667   channel = packet_get_int();
668   if (channel < 0 || channel >= channels_alloc)
669     packet_disconnect("Received close confirmation for out-of-range channel %d.",
670                       channel);
671
672   if(!compat13){
673     /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
674     chan_rcvd_oclose(&channels[channel]);
675     return;
676   }
677
678   if (channels[channel].type != SSH_CHANNEL_CLOSED)
679     packet_disconnect("Received close confirmation for non-closed channel %d (type %d).",
680                       channel, channels[channel].type);
681
682   /* Free the channel. */
683   channel_free(channel);
684 }
685
686 /* This is called after receiving CHANNEL_OPEN_CONFIRMATION. */
687
688 void channel_input_open_confirmation()
689 {
690   int channel, remote_channel;
691
692   /* Get the channel number and verify it. */
693   channel = packet_get_int();
694   if (channel < 0 || channel >= channels_alloc ||
695       channels[channel].type != SSH_CHANNEL_OPENING)
696     packet_disconnect("Received open confirmation for non-opening channel %d.",
697                       channel);
698
699   /* Get remote side's id for this channel. */
700   remote_channel = packet_get_int();
701
702   /* Record the remote channel number and mark that the channel is now open. */
703   channels[channel].remote_id = remote_channel;
704   channels[channel].type = SSH_CHANNEL_OPEN;
705 }
706
707 /* This is called after receiving CHANNEL_OPEN_FAILURE from the other side. */
708
709 void channel_input_open_failure()
710 {
711   int channel;
712
713   /* Get the channel number and verify it. */
714   channel = packet_get_int();
715   if (channel < 0 || channel >= channels_alloc ||
716       channels[channel].type != SSH_CHANNEL_OPENING)
717     packet_disconnect("Received open failure for non-opening channel %d.",
718                       channel);
719   
720   /* Free the channel.  This will also close the socket. */
721   channel_free(channel);
722 }
723
724 /* Stops listening for channels, and removes any unix domain sockets that
725    we might have. */
726
727 void channel_stop_listening()
728 {
729   int i;
730   for (i = 0; i < channels_alloc; i++)
731     {
732       switch (channels[i].type)
733         {
734         case SSH_CHANNEL_AUTH_SOCKET:
735           close(channels[i].sock);
736           remove(channels[i].path);
737           channel_free(i);
738           break;
739         case SSH_CHANNEL_PORT_LISTENER:
740         case SSH_CHANNEL_X11_LISTENER:
741           close(channels[i].sock);
742           channel_free(i);
743           break;
744         default:
745           break;
746         }
747     }
748 }
749
750 /* Closes the sockets of all channels.  This is used to close extra file
751    descriptors after a fork. */
752
753 void channel_close_all()
754 {
755   int i;
756   for (i = 0; i < channels_alloc; i++)
757     {
758       if (channels[i].type != SSH_CHANNEL_FREE)
759         close(channels[i].sock);
760     }
761 }
762
763 /* Returns the maximum file descriptor number used by the channels. */
764
765 int channel_max_fd()
766 {
767   return channel_max_fd_value;
768 }
769
770 /* Returns true if any channel is still open. */
771
772 int channel_still_open()
773 {
774   unsigned int i;
775   for (i = 0; i < channels_alloc; i++)
776     switch (channels[i].type)
777       {
778       case SSH_CHANNEL_FREE:
779       case SSH_CHANNEL_X11_LISTENER:
780       case SSH_CHANNEL_PORT_LISTENER:
781       case SSH_CHANNEL_CLOSED:
782       case SSH_CHANNEL_AUTH_SOCKET:
783         continue;
784       case SSH_CHANNEL_OPENING:
785       case SSH_CHANNEL_OPEN:
786       case SSH_CHANNEL_X11_OPEN:
787         return 1;
788       case SSH_CHANNEL_INPUT_DRAINING:
789       case SSH_CHANNEL_OUTPUT_DRAINING:
790         if (!compat13)
791           fatal("cannot happen: OUT_DRAIN");
792         return 1;
793       default:
794         fatal("channel_still_open: bad channel type %d", channels[i].type);
795         /*NOTREACHED*/
796       }
797   return 0;
798 }
799
800 /* Returns a message describing the currently open forwarded
801    connections, suitable for sending to the client.  The message
802    contains crlf pairs for newlines. */
803
804 char *channel_open_message()
805 {
806   Buffer buffer;
807   int i;
808   char buf[512], *cp;
809
810   buffer_init(&buffer);
811   snprintf(buf, sizeof buf, "The following connections are open:\r\n");
812   buffer_append(&buffer, buf, strlen(buf));
813   for (i = 0; i < channels_alloc; i++){
814     Channel *c=&channels[i];
815     switch (c->type)
816       {
817       case SSH_CHANNEL_FREE:
818       case SSH_CHANNEL_X11_LISTENER:
819       case SSH_CHANNEL_PORT_LISTENER:
820       case SSH_CHANNEL_CLOSED:
821       case SSH_CHANNEL_AUTH_SOCKET:
822         continue;
823       case SSH_CHANNEL_OPENING:
824       case SSH_CHANNEL_OPEN:
825       case SSH_CHANNEL_X11_OPEN:
826       case SSH_CHANNEL_INPUT_DRAINING:
827       case SSH_CHANNEL_OUTPUT_DRAINING:
828         snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d o%d)\r\n",
829                  c->self,c->remote_name,
830                  c->type,c->remote_id, c->istate,c->ostate);
831         buffer_append(&buffer, buf, strlen(buf));
832         continue;
833       default:
834         fatal("channel_still_open: bad channel type %d", c->type);
835         /*NOTREACHED*/
836       }
837   }
838   buffer_append(&buffer, "\0", 1);
839   cp = xstrdup(buffer_ptr(&buffer));
840   buffer_free(&buffer);
841   return cp;
842 }
843
844 /* Initiate forwarding of connections to local port "port" through the secure
845    channel to host:port from remote side. */
846
847 void channel_request_local_forwarding(int port, const char *host,
848                                       int host_port)
849 {
850   int ch, sock;
851   struct sockaddr_in sin;
852   extern Options options;
853
854   if (strlen(host) > sizeof(channels[0].path) - 1)
855     packet_disconnect("Forward host name too long.");
856   
857   /* Create a port to listen for the host. */
858   sock = socket(AF_INET, SOCK_STREAM, 0);
859   if (sock < 0)
860     packet_disconnect("socket: %.100s", strerror(errno));
861
862   /* Initialize socket address. */
863   memset(&sin, 0, sizeof(sin));
864   sin.sin_family = AF_INET;
865   if (options.gateway_ports == 1)
866     sin.sin_addr.s_addr = htonl(INADDR_ANY);
867   else
868     sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
869   sin.sin_port = htons(port);
870   
871   /* Bind the socket to the address. */
872   if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
873     packet_disconnect("bind: %.100s", strerror(errno));
874       
875   /* Start listening for connections on the socket. */
876   if (listen(sock, 5) < 0)
877     packet_disconnect("listen: %.100s", strerror(errno));
878             
879   /* Allocate a channel number for the socket. */
880   ch = channel_allocate(SSH_CHANNEL_PORT_LISTENER, sock,
881                         xstrdup("port listener"));
882   strcpy(channels[ch].path, host); /* note: host name stored here */
883   channels[ch].host_port = host_port; /* port on host to connect to */
884   channels[ch].listening_port = port; /* port being listened */
885 }  
886
887 /* Initiate forwarding of connections to port "port" on remote host through
888    the secure channel to host:port from local side. */
889
890 void channel_request_remote_forwarding(int port, const char *host,
891                                        int remote_port)
892 {
893   int payload_len;
894   /* Record locally that connection to this host/port is permitted. */
895   if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
896     fatal("channel_request_remote_forwarding: too many forwards");
897   permitted_opens[num_permitted_opens].host = xstrdup(host);
898   permitted_opens[num_permitted_opens].port = remote_port;
899   num_permitted_opens++;
900
901   /* Send the forward request to the remote side. */
902   packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
903   packet_put_int(port);
904   packet_put_string(host, strlen(host));
905   packet_put_int(remote_port);
906   packet_send();
907   packet_write_wait();
908   
909   /* Wait for response from the remote side.  It will send a disconnect
910      message on failure, and we will never see it here. */
911   packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
912 }
913
914 /* This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
915    listening for the port, and sends back a success reply (or disconnect
916    message if there was an error).  This never returns if there was an 
917    error. */
918
919 void channel_input_port_forward_request(int is_root)
920 {
921   int port, host_port;
922   char *hostname;
923   
924   /* Get arguments from the packet. */
925   port = packet_get_int();
926   hostname = packet_get_string(NULL);
927   host_port = packet_get_int();
928   
929   /* Port numbers are 16 bit quantities. */
930   if ((port & 0xffff) != port)
931     packet_disconnect("Requested forwarding of nonexistent port %d.", port);
932
933   /* Check that an unprivileged user is not trying to forward a privileged
934      port. */
935   if (port < IPPORT_RESERVED && !is_root)
936     packet_disconnect("Requested forwarding of port %d but user is not root.",
937                       port);
938
939   /* Initiate forwarding. */
940   channel_request_local_forwarding(port, hostname, host_port);
941
942   /* Free the argument string. */
943   xfree(hostname);
944 }
945
946 /* This is called after receiving PORT_OPEN message.  This attempts to connect
947    to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION or
948    CHANNEL_OPEN_FAILURE. */
949
950 void channel_input_port_open(int payload_len)
951 {
952   int remote_channel, sock, newch, host_port, i;
953   struct sockaddr_in sin;
954   char *host, *originator_string;
955   struct hostent *hp;
956   int host_len, originator_len;
957
958   /* Get remote channel number. */
959   remote_channel = packet_get_int();
960
961   /* Get host name to connect to. */
962   host = packet_get_string(&host_len);
963
964   /* Get port to connect to. */
965   host_port = packet_get_int();
966
967   /* Get remote originator name. */
968   if (have_hostname_in_open)
969     originator_string = packet_get_string(&originator_len);
970   else
971     originator_string = xstrdup("unknown (remote did not supply name)");
972
973   packet_integrity_check(payload_len,
974                          4 + 4 + host_len + 4 + 4 + originator_len,
975                          SSH_MSG_PORT_OPEN);
976
977   /* Check if opening that port is permitted. */
978   if (!all_opens_permitted)
979     {
980       /* Go trough all permitted ports. */
981       for (i = 0; i < num_permitted_opens; i++)
982         if (permitted_opens[i].port == host_port &&
983             strcmp(permitted_opens[i].host, host) == 0)
984           break;
985
986       /* Check if we found the requested port among those permitted. */
987       if (i >= num_permitted_opens)
988         {
989           /* The port is not permitted. */
990           log("Received request to connect to %.100s:%d, but the request was denied.",
991               host, host_port);
992           packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
993           packet_put_int(remote_channel);
994           packet_send();
995         }
996     }
997   
998   memset(&sin, 0, sizeof(sin));
999   sin.sin_addr.s_addr = inet_addr(host);
1000   if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1001     {
1002       /* It was a valid numeric host address. */
1003       sin.sin_family = AF_INET;
1004     }
1005   else
1006     {
1007       /* Look up the host address from the name servers. */
1008       hp = gethostbyname(host);
1009       if (!hp)
1010         {
1011           error("%.100s: unknown host.", host);
1012           goto fail;
1013         }
1014       if (!hp->h_addr_list[0])
1015         {
1016           error("%.100s: host has no IP address.", host);
1017           goto fail;
1018         }
1019       sin.sin_family = hp->h_addrtype;
1020       memcpy(&sin.sin_addr, hp->h_addr_list[0], 
1021              sizeof(sin.sin_addr));
1022     }
1023   sin.sin_port = htons(host_port);
1024
1025   /* Create the socket. */
1026   sock = socket(sin.sin_family, SOCK_STREAM, 0);
1027   if (sock < 0)
1028     {
1029       error("socket: %.100s", strerror(errno));
1030       goto fail;
1031     }
1032
1033   /* Connect to the host/port. */
1034   if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1035     {
1036       error("connect %.100s:%d: %.100s", host, host_port,
1037             strerror(errno));
1038       close(sock);
1039       goto fail;
1040     }
1041
1042   /* Successful connection. */
1043
1044   /* Allocate a channel for this connection. */
1045   newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1046   channels[newch].remote_id = remote_channel;
1047   
1048   /* Send a confirmation to the remote host. */
1049   packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1050   packet_put_int(remote_channel);
1051   packet_put_int(newch);
1052   packet_send();
1053
1054   /* Free the argument string. */
1055   xfree(host);
1056   
1057   return;
1058
1059  fail:
1060   /* Free the argument string. */
1061   xfree(host);
1062
1063   /* Send refusal to the remote host. */
1064   packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1065   packet_put_int(remote_channel);
1066   packet_send();
1067 }
1068
1069 /* Creates an internet domain socket for listening for X11 connections. 
1070    Returns a suitable value for the DISPLAY variable, or NULL if an error
1071    occurs. */
1072
1073 char *x11_create_display_inet(int screen_number)
1074 {
1075   extern ServerOptions options;
1076   int display_number, port, sock;
1077   struct sockaddr_in sin;
1078   char buf[512];
1079   char hostname[MAXHOSTNAMELEN];
1080
1081   for (display_number = options.x11_display_offset; display_number < MAX_DISPLAYS; display_number++)
1082     {
1083       port = 6000 + display_number;
1084       memset(&sin, 0, sizeof(sin));
1085       sin.sin_family = AF_INET;
1086       sin.sin_addr.s_addr = htonl(INADDR_ANY);
1087       sin.sin_port = htons(port);
1088       
1089       sock = socket(AF_INET, SOCK_STREAM, 0);
1090       if (sock < 0)
1091         {
1092           error("socket: %.100s", strerror(errno));
1093           return NULL;
1094         }
1095       
1096       if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1097         {
1098           debug("bind port %d: %.100s", port, strerror(errno));
1099           shutdown(sock, SHUT_RDWR);
1100           close(sock);
1101           continue;
1102         }
1103       break;
1104     }
1105   if (display_number >= MAX_DISPLAYS)
1106     {
1107       error("Failed to allocate internet-domain X11 display socket.");
1108       return NULL;
1109     }
1110
1111   /* Start listening for connections on the socket. */
1112   if (listen(sock, 5) < 0)
1113     {
1114       error("listen: %.100s", strerror(errno));
1115       shutdown(sock, SHUT_RDWR);
1116       close(sock);
1117       return NULL;
1118     }
1119
1120   /* Set up a suitable value for the DISPLAY variable. */
1121   if (gethostname(hostname, sizeof(hostname)) < 0)
1122     fatal("gethostname: %.100s", strerror(errno));
1123   snprintf(buf, sizeof buf, "%.400s:%d.%d", hostname,
1124     display_number, screen_number);
1125             
1126   /* Allocate a channel for the socket. */
1127   (void)channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1128                          xstrdup("X11 inet listener"));
1129
1130   /* Return a suitable value for the DISPLAY environment variable. */
1131   return xstrdup(buf);
1132 }
1133
1134 #ifndef X_UNIX_PATH
1135 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1136 #endif
1137
1138 static
1139 int
1140 connect_local_xsocket(unsigned dnr)
1141 {
1142   static const char *const x_sockets[] = {
1143     X_UNIX_PATH "%u",
1144     "/var/X/.X11-unix/X" "%u",
1145     "/usr/spool/sockets/X11/" "%u",
1146     NULL
1147   };
1148   int sock;
1149   struct sockaddr_un addr;
1150   const char *const *path;
1151
1152   for (path = x_sockets; *path; ++path)
1153     {
1154       sock = socket(AF_UNIX, SOCK_STREAM, 0);
1155       if (sock < 0)
1156         error("socket: %.100s", strerror(errno));
1157       memset(&addr, 0, sizeof(addr));
1158       addr.sun_family = AF_UNIX;
1159       snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1160       if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
1161         return sock;
1162       close(sock);
1163     }
1164   error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1165   return -1;
1166 }
1167
1168
1169 /* This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
1170    the remote channel number.  We should do whatever we want, and respond
1171    with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. */
1172
1173 void x11_input_open(int payload_len)
1174 {
1175   int remote_channel, display_number, sock, newch;
1176   const char *display;
1177   struct sockaddr_in sin;
1178   char buf[1024], *cp, *remote_host;
1179   struct hostent *hp;
1180   int remote_len;
1181
1182   /* Get remote channel number. */
1183   remote_channel = packet_get_int();
1184
1185   /* Get remote originator name. */
1186   if (have_hostname_in_open)
1187     remote_host = packet_get_string(&remote_len);
1188   else
1189     remote_host = xstrdup("unknown (remote did not supply name)");
1190
1191   debug("Received X11 open request.");
1192   packet_integrity_check(payload_len, 4 + 4+remote_len, SSH_SMSG_X11_OPEN);
1193
1194   /* Try to open a socket for the local X server. */
1195   display = getenv("DISPLAY");
1196   if (!display)
1197     {
1198       error("DISPLAY not set.");
1199       goto fail;
1200     }
1201   
1202   /* Now we decode the value of the DISPLAY variable and make a connection
1203      to the real X server. */
1204
1205   /* Check if it is a unix domain socket.  Unix domain displays are in one
1206      of the following formats: unix:d[.s], :d[.s], ::d[.s] */
1207   if (strncmp(display, "unix:", 5) == 0 ||
1208       display[0] == ':')
1209     {
1210       /* Connect to the unix domain socket. */
1211       if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1)
1212         {
1213           error("Could not parse display number from DISPLAY: %.100s",
1214                 display);
1215           goto fail;
1216         }
1217       /* Create a socket. */
1218       sock = connect_local_xsocket(display_number);
1219       if (sock < 0)
1220         goto fail;
1221
1222       /* OK, we now have a connection to the display. */
1223       goto success;
1224     }
1225   
1226   /* Connect to an inet socket.  The DISPLAY value is supposedly
1227       hostname:d[.s], where hostname may also be numeric IP address. */
1228   strncpy(buf, display, sizeof(buf));
1229   buf[sizeof(buf) - 1] = 0;
1230   cp = strchr(buf, ':');
1231   if (!cp)
1232     {
1233       error("Could not find ':' in DISPLAY: %.100s", display);
1234       goto fail;
1235     }
1236   *cp = 0;
1237   /* buf now contains the host name.  But first we parse the display number. */
1238   if (sscanf(cp + 1, "%d", &display_number) != 1)
1239     {
1240        error("Could not parse display number from DISPLAY: %.100s",
1241              display);
1242       goto fail;
1243     }
1244   
1245   /* Try to parse the host name as a numeric IP address. */
1246   memset(&sin, 0, sizeof(sin));
1247   sin.sin_addr.s_addr = inet_addr(buf);
1248   if ((sin.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
1249     {
1250       /* It was a valid numeric host address. */
1251       sin.sin_family = AF_INET;
1252     }
1253   else
1254     {
1255       /* Not a numeric IP address. */
1256       /* Look up the host address from the name servers. */
1257       hp = gethostbyname(buf);
1258       if (!hp)
1259         {
1260           error("%.100s: unknown host.", buf);
1261           goto fail;
1262         }
1263       if (!hp->h_addr_list[0])
1264         {
1265           error("%.100s: host has no IP address.", buf);
1266           goto fail;
1267         }
1268       sin.sin_family = hp->h_addrtype;
1269       memcpy(&sin.sin_addr, hp->h_addr_list[0], 
1270              sizeof(sin.sin_addr));
1271     }
1272   /* Set port number. */
1273   sin.sin_port = htons(6000 + display_number);
1274
1275   /* Create a socket. */
1276   sock = socket(sin.sin_family, SOCK_STREAM, 0);
1277   if (sock < 0)
1278     {
1279       error("socket: %.100s", strerror(errno));
1280       goto fail;
1281     }
1282   /* Connect it to the display. */
1283   if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
1284     {
1285       error("connect %.100s:%d: %.100s", buf, 6000 + display_number, 
1286             strerror(errno));
1287       close(sock);
1288       goto fail;
1289     }
1290
1291  success:
1292   /* We have successfully obtained a connection to the real X display. */
1293   
1294   /* Allocate a channel for this connection. */
1295   if (x11_saved_proto == NULL)
1296     newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1297   else
1298     newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1299   channels[newch].remote_id = remote_channel;
1300   
1301   /* Send a confirmation to the remote host. */
1302   packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1303   packet_put_int(remote_channel);
1304   packet_put_int(newch);
1305   packet_send();
1306   
1307   return;
1308
1309  fail:
1310   /* Send refusal to the remote host. */
1311   packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1312   packet_put_int(remote_channel);
1313   packet_send();
1314 }
1315
1316 /* Requests forwarding of X11 connections, generates fake authentication
1317    data, and enables authentication spoofing. */
1318
1319 void x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1320 {
1321   unsigned int data_len = (unsigned int)strlen(data) / 2;
1322   unsigned int i, value;
1323   char *new_data;
1324   int screen_number;
1325   const char *cp;
1326   u_int32_t rand = 0;
1327
1328   cp = getenv("DISPLAY");
1329   if (cp)
1330     cp = strchr(cp, ':');
1331   if (cp)
1332     cp = strchr(cp, '.');
1333   if (cp)
1334     screen_number = atoi(cp + 1);
1335   else
1336     screen_number = 0;
1337
1338   /* Save protocol name. */
1339   x11_saved_proto = xstrdup(proto);
1340
1341   /* Extract real authentication data and generate fake data of the same
1342      length. */
1343   x11_saved_data = xmalloc(data_len);
1344   x11_fake_data = xmalloc(data_len);
1345   for (i = 0; i < data_len; i++)
1346     {
1347       if (sscanf(data + 2 * i, "%2x", &value) != 1)
1348         fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1349       if (i % 4 == 0)
1350         rand = arc4random();
1351       x11_saved_data[i] = value;
1352       x11_fake_data[i] = rand & 0xff;
1353       rand >>= 8;
1354     }
1355   x11_saved_data_len = data_len;
1356   x11_fake_data_len = data_len;
1357
1358   /* Convert the fake data into hex. */
1359   new_data = xmalloc(2 * data_len + 1);
1360   for (i = 0; i < data_len; i++)
1361     sprintf(new_data + 2 * i, "%02x", (unsigned char)x11_fake_data[i]);
1362
1363   /* Send the request packet. */
1364   packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
1365   packet_put_string(proto, strlen(proto));
1366   packet_put_string(new_data, strlen(new_data));
1367   packet_put_int(screen_number);
1368   packet_send();
1369   packet_write_wait();
1370   xfree(new_data);
1371 }
1372
1373 /* Sends a message to the server to request authentication fd forwarding. */
1374
1375 void auth_request_forwarding()
1376 {
1377   packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
1378   packet_send();
1379   packet_write_wait();
1380 }
1381
1382 /* Returns the name of the forwarded authentication socket.  Returns NULL
1383    if there is no forwarded authentication socket.  The returned value
1384    points to a static buffer. */
1385
1386 char *auth_get_socket_name()
1387 {
1388   return channel_forwarded_auth_socket_name;
1389 }
1390
1391 /* removes the agent forwarding socket */
1392
1393 void cleanup_socket(void) {
1394   remove(channel_forwarded_auth_socket_name);
1395   rmdir(channel_forwarded_auth_socket_dir);
1396 }
1397
1398 /* This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
1399    This starts forwarding authentication requests. */
1400
1401 void auth_input_request_forwarding(struct passwd *pw)
1402 {
1403   int sock, newch;
1404   struct sockaddr_un sunaddr;
1405   
1406   if (auth_get_socket_name() != NULL)
1407     fatal("Protocol error: authentication forwarding requested twice.");
1408
1409   /* Temporarily drop privileged uid for mkdir/bind. */
1410   temporarily_use_uid(pw->pw_uid);
1411
1412   /* Allocate a buffer for the socket name, and format the name. */
1413   channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
1414   channel_forwarded_auth_socket_dir  = xmalloc(MAX_SOCKET_NAME);
1415   strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
1416
1417   /* Create private directory for socket */
1418   if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
1419     packet_disconnect("mkdtemp: %.100s", strerror(errno));
1420   snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME,
1421            "%s/agent.%d", channel_forwarded_auth_socket_dir, (int)getpid());
1422
1423   if (atexit(cleanup_socket) < 0) {
1424     int saved=errno;
1425     cleanup_socket();
1426     packet_disconnect("socket: %.100s", strerror(saved));
1427   }
1428
1429   /* Create the socket. */
1430   sock = socket(AF_UNIX, SOCK_STREAM, 0);
1431   if (sock < 0)
1432     packet_disconnect("socket: %.100s", strerror(errno));
1433
1434   /* Bind it to the name. */
1435   memset(&sunaddr, 0, sizeof(sunaddr));
1436   sunaddr.sun_family = AF_UNIX;
1437   strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name, 
1438           sizeof(sunaddr.sun_path));
1439
1440   if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
1441     packet_disconnect("bind: %.100s", strerror(errno));
1442
1443   /* Restore the privileged uid. */
1444   restore_uid();
1445
1446   /* Start listening on the socket. */
1447   if (listen(sock, 5) < 0)
1448     packet_disconnect("listen: %.100s", strerror(errno));
1449
1450   /* Allocate a channel for the authentication agent socket. */
1451   newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
1452                        xstrdup("auth socket"));
1453   strcpy(channels[newch].path, channel_forwarded_auth_socket_name);
1454 }
1455
1456 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
1457
1458 void auth_input_open_request()
1459 {
1460   int remch, sock, newch;
1461   char *dummyname;
1462
1463   /* Read the remote channel number from the message. */
1464   remch = packet_get_int();
1465   
1466   /* Get a connection to the local authentication agent (this may again get
1467      forwarded). */
1468   sock = ssh_get_authentication_socket();
1469
1470   /* If we could not connect the agent, send an error message back to
1471      the server. This should never happen unless the agent
1472      dies, because authentication forwarding is only enabled if we have an
1473      agent. */
1474   if (sock < 0){
1475     packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1476     packet_put_int(remch);
1477     packet_send();
1478     return;
1479   }
1480
1481   debug("Forwarding authentication connection.");
1482
1483   /* Dummy host name.  This will be freed when the channel is freed; it will
1484      still be valid in the packet_put_string below since the channel cannot
1485      yet be freed at that point. */
1486   dummyname = xstrdup("authentication agent connection");
1487   
1488   newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
1489   channels[newch].remote_id = remch;
1490   
1491   /* Send a confirmation to the remote host. */
1492   packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1493   packet_put_int(remch);
1494   packet_put_int(newch);
1495   packet_send();
1496 }
This page took 1.892168 seconds and 5 git commands to generate.