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