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