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