18 /* uncomment this for packet level debugging */
19 /* #define DUMP_PACKETS */
21 #define logevent(s) { logevent(s); \
22 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
23 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
25 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
26 (s ? sk_close(s), s = NULL : 0), \
27 connection_fatal msg )
29 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
30 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
31 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
32 #define SSH1_CMSG_USER 4 /* 0x4 */
33 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
34 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
35 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
36 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
37 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
38 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
39 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
40 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
41 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
42 #define SSH1_SMSG_FAILURE 15 /* 0xf */
43 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
44 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
45 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
46 #define SSH1_CMSG_EOF 19 /* 0x13 */
47 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
48 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
49 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
50 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
51 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
52 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
53 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
54 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
55 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
56 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
57 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
58 #define SSH1_MSG_IGNORE 32 /* 0x20 */
59 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
60 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
61 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
62 #define SSH1_MSG_DEBUG 36 /* 0x24 */
63 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
64 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
65 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
66 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
67 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
68 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
69 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
71 #define SSH1_AUTH_TIS 5 /* 0x5 */
72 #define SSH1_AUTH_CCARD 16 /* 0x10 */
74 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
75 /* Mask for protoflags we will echo back to server if seen */
76 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
78 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
79 #define SSH2_MSG_IGNORE 2 /* 0x2 */
80 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
81 #define SSH2_MSG_DEBUG 4 /* 0x4 */
82 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
83 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
84 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
85 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
86 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
87 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
88 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
89 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
91 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
92 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
93 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
94 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
95 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
96 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
97 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
98 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
99 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
100 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
101 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
102 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
103 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
104 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
105 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
106 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
107 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
108 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
109 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
110 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
111 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
113 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
114 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
115 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
116 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
117 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
118 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
119 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
120 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
121 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
122 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
123 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
124 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
125 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
126 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
127 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
129 static const char *const ssh2_disconnect_reasons
[] = {
131 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
132 "SSH_DISCONNECT_PROTOCOL_ERROR",
133 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
134 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
135 "SSH_DISCONNECT_MAC_ERROR",
136 "SSH_DISCONNECT_COMPRESSION_ERROR",
137 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
138 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
139 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
140 "SSH_DISCONNECT_CONNECTION_LOST",
141 "SSH_DISCONNECT_BY_APPLICATION",
142 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
143 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
144 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
145 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
148 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
149 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
150 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
151 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
153 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
156 * Various remote-bug flags.
158 #define BUG_CHOKES_ON_SSH1_IGNORE 1
159 #define BUG_SSH2_HMAC 2
161 #define GET_32BIT(cp) \
162 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
163 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
164 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
165 ((unsigned long)(unsigned char)(cp)[3]))
167 #define PUT_32BIT(cp, value) { \
168 (cp)[0] = (unsigned char)((value) >> 24); \
169 (cp)[1] = (unsigned char)((value) >> 16); \
170 (cp)[2] = (unsigned char)((value) >> 8); \
171 (cp)[3] = (unsigned char)(value); }
173 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
175 /* Coroutine mechanics for the sillier bits of the code */
176 #define crBegin1 static int crLine = 0;
177 #define crBegin2 switch(crLine) { case 0:;
178 #define crBegin crBegin1; crBegin2;
179 #define crFinish(z) } crLine = 0; return (z)
180 #define crFinishV } crLine = 0; return
181 #define crReturn(z) \
183 crLine=__LINE__; return (z); case __LINE__:;\
187 crLine=__LINE__; return; case __LINE__:;\
189 #define crStop(z) do{ crLine = 0; return (z); }while(0)
190 #define crStopV do{ crLine = 0; return; }while(0)
191 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
192 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
194 extern char *x11_init(Socket
*, char *, void *);
195 extern void x11_close(Socket
);
196 extern void x11_send(Socket
, char *, int);
197 extern void x11_invent_auth(char *, int, char *, int);
200 * Ciphers for SSH2. We miss out single-DES because it isn't
201 * supported; also 3DES and Blowfish are both done differently from
202 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
203 * endianness and different-sized keys.)
205 const static struct ssh2_ciphers
*ciphers
[] = {
211 const static struct ssh_kex
*kex_algs
[] = {
212 &ssh_diffiehellman_gex
,
216 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
218 static void nullmac_key(unsigned char *key
)
221 static void nullmac_generate(unsigned char *blk
, int len
,
225 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
229 const static struct ssh_mac ssh_mac_none
= {
230 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
232 const static struct ssh_mac
*macs
[] = {
233 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
235 const static struct ssh_mac
*buggymacs
[] = {
236 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
239 static void ssh_comp_none_init(void)
242 static int ssh_comp_none_block(unsigned char *block
, int len
,
243 unsigned char **outblock
, int *outlen
)
247 static int ssh_comp_none_disable(void)
251 const static struct ssh_compress ssh_comp_none
= {
253 ssh_comp_none_init
, ssh_comp_none_block
,
254 ssh_comp_none_init
, ssh_comp_none_block
,
255 ssh_comp_none_disable
257 extern const struct ssh_compress ssh_zlib
;
258 const static struct ssh_compress
*compressions
[] = {
259 &ssh_zlib
, &ssh_comp_none
262 enum { /* channel types */
269 * 2-3-4 tree storing channels.
272 unsigned remoteid
, localid
;
275 struct ssh2_data_channel
{
276 unsigned char *outbuffer
;
277 unsigned outbuflen
, outbufsize
;
278 unsigned remwindow
, remmaxpkt
;
281 struct ssh_agent_channel
{
282 unsigned char *message
;
283 unsigned char msglen
[4];
284 int lensofar
, totallen
;
286 struct ssh_x11_channel
{
301 static SHA_State exhash
, exhashbase
;
303 static Socket s
= NULL
;
305 static unsigned char session_key
[32];
306 static int ssh1_compressing
;
307 static int ssh1_remote_protoflags
;
308 static int ssh1_local_protoflags
;
309 static int ssh_agentfwd_enabled
;
310 static int ssh_X11_fwd_enabled
;
311 static int ssh_remote_bugs
;
312 static const struct ssh_cipher
*cipher
= NULL
;
313 static const struct ssh2_cipher
*cscipher
= NULL
;
314 static const struct ssh2_cipher
*sccipher
= NULL
;
315 static const struct ssh_mac
*csmac
= NULL
;
316 static const struct ssh_mac
*scmac
= NULL
;
317 static const struct ssh_compress
*cscomp
= NULL
;
318 static const struct ssh_compress
*sccomp
= NULL
;
319 static const struct ssh_kex
*kex
= NULL
;
320 static const struct ssh_signkey
*hostkey
= NULL
;
321 static unsigned char ssh2_session_id
[20];
322 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
325 static char *savedhost
;
326 static int savedport
;
327 static int ssh_send_ok
;
328 static int ssh_echoing
, ssh_editing
;
330 static tree234
*ssh_channels
; /* indexed by local id */
331 static struct ssh_channel
*mainchan
; /* primary session channel */
335 SSH_STATE_BEFORE_SIZE
,
339 } ssh_state
= SSH_STATE_PREPACKET
;
341 static int size_needed
= FALSE
, eof_needed
= FALSE
;
343 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
344 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
345 static unsigned char *deferred_send_data
= NULL
;
346 static int deferred_len
= 0, deferred_size
= 0;
348 static int ssh_version
;
349 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
350 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
351 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
352 static void ssh_size(void);
353 static void ssh_special(Telnet_Special
);
354 static void ssh2_try_send(struct ssh_channel
*c
);
355 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
358 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
360 static struct rdpkt1_state_tag
{
361 long len
, pad
, biglen
, to_read
;
362 unsigned long realcrc
, gotcrc
;
368 static struct rdpkt2_state_tag
{
369 long len
, pad
, payload
, packetlen
, maclen
;
372 unsigned long incoming_sequence
;
375 static int ssh_channelcmp(void *av
, void *bv
)
377 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
378 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
379 if (a
->localid
< b
->localid
)
381 if (a
->localid
> b
->localid
)
385 static int ssh_channelfind(void *av
, void *bv
)
387 unsigned *a
= (unsigned *) av
;
388 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
396 static int alloc_channel_id(void)
398 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
399 unsigned low
, high
, mid
;
401 struct ssh_channel
*c
;
404 * First-fit allocation of channel numbers: always pick the
405 * lowest unused one. To do this, binary-search using the
406 * counted B-tree to find the largest channel ID which is in a
407 * contiguous sequence from the beginning. (Precisely
408 * everything in that sequence must have ID equal to its tree
409 * index plus CHANNEL_NUMBER_OFFSET.)
411 tsize
= count234(ssh_channels
);
415 while (high
- low
> 1) {
416 mid
= (high
+ low
) / 2;
417 c
= index234(ssh_channels
, mid
);
418 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
419 low
= mid
; /* this one is fine */
421 high
= mid
; /* this one is past it */
424 * Now low points to either -1, or the tree index of the
425 * largest ID in the initial sequence.
428 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
429 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
431 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
434 static void c_write(char *buf
, int len
)
436 if ((flags
& FLAG_STDERR
)) {
438 for (i
= 0; i
< len
; i
++)
440 fputc(buf
[i
], stderr
);
443 from_backend(1, buf
, len
);
446 static void c_write_untrusted(char *buf
, int len
)
449 for (i
= 0; i
< len
; i
++) {
452 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
457 static void c_write_str(char *buf
)
459 c_write(buf
, strlen(buf
));
463 * Collect incoming data in the incoming packet buffer.
464 * Decipher and verify the packet when it is completely read.
465 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
466 * Update the *data and *datalen variables.
467 * Return the additional nr of bytes needed, or 0 when
468 * a complete packet is available.
470 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
472 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
481 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
482 while ((*datalen
) == 0)
484 st
->len
= (st
->len
<< 8) + **data
;
485 (*data
)++, (*datalen
)--;
489 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
490 st
->len
= 0x300; /* big enough to carry to end */
494 st
->pad
= 8 - (st
->len
% 8);
495 st
->biglen
= st
->len
+ st
->pad
;
496 pktin
.length
= st
->len
- 5;
498 if (pktin
.maxlen
< st
->biglen
) {
499 pktin
.maxlen
= st
->biglen
;
500 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
501 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
503 fatalbox("Out of memory");
506 st
->to_read
= st
->biglen
;
508 while (st
->to_read
> 0) {
509 st
->chunk
= st
->to_read
;
510 while ((*datalen
) == 0)
511 crReturn(st
->to_read
);
512 if (st
->chunk
> (*datalen
))
513 st
->chunk
= (*datalen
);
514 memcpy(st
->p
, *data
, st
->chunk
);
516 *datalen
-= st
->chunk
;
518 st
->to_read
-= st
->chunk
;
522 cipher
->decrypt(pktin
.data
, st
->biglen
);
524 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
525 dmemdump(pktin
.data
, st
->biglen
);
528 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
529 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
530 if (st
->gotcrc
!= st
->realcrc
) {
531 bombout(("Incorrect CRC received on packet"));
535 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
537 if (ssh1_compressing
) {
538 unsigned char *decompblk
;
541 debug(("Packet payload pre-decompression:\n"));
542 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
544 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
545 &decompblk
, &decomplen
);
547 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
548 pktin
.maxlen
= st
->pad
+ decomplen
;
549 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
550 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
552 fatalbox("Out of memory");
555 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
557 pktin
.length
= decomplen
- 1;
559 debug(("Packet payload post-decompression:\n"));
560 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
564 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
565 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
566 pktin
.type
== SSH1_MSG_DEBUG
||
567 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
568 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
569 long strlen
= GET_32BIT(pktin
.body
);
570 if (strlen
+ 4 != pktin
.length
) {
571 bombout(("Received data packet with bogus string length"));
576 pktin
.type
= pktin
.body
[-1];
578 if (pktin
.type
== SSH1_MSG_DEBUG
) {
579 /* log debug message */
581 int strlen
= GET_32BIT(pktin
.body
);
582 strcpy(buf
, "Remote: ");
585 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
586 buf
[8 + strlen
] = '\0';
589 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
594 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
595 /* log reason code in disconnect message */
597 unsigned msglen
= GET_32BIT(pktin
.body
);
599 strcpy(buf
, "Remote sent disconnect: ");
600 nowlen
= strlen(buf
);
601 if (msglen
> sizeof(buf
) - nowlen
- 1)
602 msglen
= sizeof(buf
) - nowlen
- 1;
603 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
604 buf
[nowlen
+ msglen
] = '\0';
611 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
613 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
621 st
->cipherblk
= sccipher
->blksize
;
624 if (st
->cipherblk
< 8)
627 if (pktin
.maxlen
< st
->cipherblk
) {
628 pktin
.maxlen
= st
->cipherblk
;
631 NULL ?
smalloc(st
->cipherblk
+
632 APIEXTRA
) : srealloc(pktin
.data
,
636 fatalbox("Out of memory");
640 * Acquire and decrypt the first block of the packet. This will
641 * contain the length and padding details.
643 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
644 while ((*datalen
) == 0)
645 crReturn(st
->cipherblk
- st
->i
);
646 pktin
.data
[st
->i
] = *(*data
)++;
650 if (!memcmp(pktin
.data
, "Remo", 4)) { /* "Remo"te server has closed ... */
655 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
658 * Now get the length and padding figures.
660 st
->len
= GET_32BIT(pktin
.data
);
661 st
->pad
= pktin
.data
[4];
664 * This enables us to deduce the payload length.
666 st
->payload
= st
->len
- st
->pad
- 1;
668 pktin
.length
= st
->payload
+ 5;
671 * So now we can work out the total packet length.
673 st
->packetlen
= st
->len
+ 4;
674 st
->maclen
= scmac ? scmac
->len
: 0;
677 * Adjust memory allocation if packet is too big.
679 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
680 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
683 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
688 fatalbox("Out of memory");
692 * Read and decrypt the remainder of the packet.
694 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
696 while ((*datalen
) == 0)
697 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
698 pktin
.data
[st
->i
] = *(*data
)++;
701 /* Decrypt everything _except_ the MAC. */
703 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
704 st
->packetlen
- st
->cipherblk
);
707 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
708 dmemdump(pktin
.data
, st
->packetlen
);
715 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
716 st
->incoming_sequence
)) {
717 bombout(("Incorrect MAC received on packet"));
720 st
->incoming_sequence
++; /* whether or not we MACed */
723 * Decompress packet payload.
726 unsigned char *newpayload
;
728 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
729 &newpayload
, &newlen
)) {
730 if (pktin
.maxlen
< newlen
+ 5) {
731 pktin
.maxlen
= newlen
+ 5;
734 NULL ?
smalloc(pktin
.maxlen
+
735 APIEXTRA
) : srealloc(pktin
.data
,
739 fatalbox("Out of memory");
741 pktin
.length
= 5 + newlen
;
742 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
744 debug(("Post-decompression payload:\n"));
745 dmemdump(pktin
.data
+ 5, newlen
);
753 pktin
.type
= pktin
.data
[5];
755 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
756 goto next_packet
; /* FIXME: print DEBUG message */
758 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
759 /* log reason code in disconnect message */
761 int reason
= GET_32BIT(pktin
.data
+ 6);
762 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
764 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
765 sprintf(buf
, "Received disconnect message (%s)",
766 ssh2_disconnect_reasons
[reason
]);
768 sprintf(buf
, "Received disconnect message (unknown type %d)",
772 strcpy(buf
, "Disconnection message text: ");
773 nowlen
= strlen(buf
);
774 if (msglen
> sizeof(buf
) - nowlen
- 1)
775 msglen
= sizeof(buf
) - nowlen
- 1;
776 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
777 buf
[nowlen
+ msglen
] = '\0';
784 static void ssh1_pktout_size(int len
)
788 len
+= 5; /* type and CRC */
792 pktout
.length
= len
- 5;
793 if (pktout
.maxlen
< biglen
) {
794 pktout
.maxlen
= biglen
;
796 /* Allocate enough buffer space for extra block
797 * for MS CryptEncrypt() */
798 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
799 srealloc(pktout
.data
, biglen
+ 12));
801 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
802 srealloc(pktout
.data
, biglen
+ 4));
805 fatalbox("Out of memory");
807 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
810 static void s_wrpkt_start(int type
, int len
)
812 ssh1_pktout_size(len
);
816 static int s_wrpkt_prepare(void)
818 int pad
, len
, biglen
, i
;
821 pktout
.body
[-1] = pktout
.type
;
824 debug(("Packet payload pre-compression:\n"));
825 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
828 if (ssh1_compressing
) {
829 unsigned char *compblk
;
831 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
833 ssh1_pktout_size(complen
- 1);
834 memcpy(pktout
.body
- 1, compblk
, complen
);
837 debug(("Packet payload post-compression:\n"));
838 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
842 len
= pktout
.length
+ 5; /* type and CRC */
846 for (i
= 0; i
< pad
; i
++)
847 pktout
.data
[i
+ 4] = random_byte();
848 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
849 PUT_32BIT(pktout
.data
+ biglen
, crc
);
850 PUT_32BIT(pktout
.data
, len
);
853 debug(("Sending packet len=%d\n", biglen
+ 4));
854 dmemdump(pktout
.data
, biglen
+ 4);
857 cipher
->encrypt(pktout
.data
+ 4, biglen
);
862 static void s_wrpkt(void)
865 len
= s_wrpkt_prepare();
866 sk_write(s
, pktout
.data
, len
);
869 static void s_wrpkt_defer(void)
872 len
= s_wrpkt_prepare();
873 if (deferred_len
+ len
> deferred_size
) {
874 deferred_size
= deferred_len
+ len
+ 128;
875 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
877 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
882 * Construct a packet with the specified contents.
884 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
886 unsigned char *p
, *argp
, argchar
;
887 unsigned long argint
;
888 int pktlen
, argtype
, arglen
;
892 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
895 (void) va_arg(ap1
, int);
899 (void) va_arg(ap1
, char);
903 (void) va_arg(ap1
, unsigned char *);
904 arglen
= va_arg(ap1
, int);
908 argp
= va_arg(ap1
, unsigned char *);
909 arglen
= strlen(argp
);
910 pktlen
+= 4 + arglen
;
913 bn
= va_arg(ap1
, Bignum
);
914 pktlen
+= ssh1_bignum_length(bn
);
921 s_wrpkt_start(pkttype
, pktlen
);
924 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
927 argint
= va_arg(ap2
, int);
928 PUT_32BIT(p
, argint
);
932 argchar
= va_arg(ap2
, unsigned char);
937 argp
= va_arg(ap2
, unsigned char *);
938 arglen
= va_arg(ap2
, int);
939 memcpy(p
, argp
, arglen
);
943 argp
= va_arg(ap2
, unsigned char *);
944 arglen
= strlen(argp
);
945 PUT_32BIT(p
, arglen
);
946 memcpy(p
+ 4, argp
, arglen
);
950 bn
= va_arg(ap2
, Bignum
);
951 p
+= ssh1_write_bignum(p
, bn
);
957 static void send_packet(int pkttype
, ...)
960 va_start(ap1
, pkttype
);
961 va_start(ap2
, pkttype
);
962 construct_packet(pkttype
, ap1
, ap2
);
966 static void defer_packet(int pkttype
, ...)
969 va_start(ap1
, pkttype
);
970 va_start(ap2
, pkttype
);
971 construct_packet(pkttype
, ap1
, ap2
);
975 static int ssh_versioncmp(char *a
, char *b
)
978 unsigned long av
, bv
;
980 av
= strtoul(a
, &ae
, 10);
981 bv
= strtoul(b
, &be
, 10);
983 return (av
< bv ?
-1 : +1);
988 av
= strtoul(ae
, &ae
, 10);
989 bv
= strtoul(be
, &be
, 10);
991 return (av
< bv ?
-1 : +1);
997 * Utility routines for putting an SSH-protocol `string' and
998 * `uint32' into a SHA state.
1001 static void sha_string(SHA_State
* s
, void *str
, int len
)
1003 unsigned char lenblk
[4];
1004 PUT_32BIT(lenblk
, len
);
1005 SHA_Bytes(s
, lenblk
, 4);
1006 SHA_Bytes(s
, str
, len
);
1009 static void sha_uint32(SHA_State
* s
, unsigned i
)
1011 unsigned char intblk
[4];
1012 PUT_32BIT(intblk
, i
);
1013 SHA_Bytes(s
, intblk
, 4);
1017 * SSH2 packet construction functions.
1019 static void ssh2_pkt_ensure(int length
)
1021 if (pktout
.maxlen
< length
) {
1022 pktout
.maxlen
= length
+ 256;
1025 NULL ?
smalloc(pktout
.maxlen
+
1026 APIEXTRA
) : srealloc(pktout
.data
,
1030 fatalbox("Out of memory");
1033 static void ssh2_pkt_adddata(void *data
, int len
)
1035 pktout
.length
+= len
;
1036 ssh2_pkt_ensure(pktout
.length
);
1037 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1039 static void ssh2_pkt_addbyte(unsigned char byte
)
1041 ssh2_pkt_adddata(&byte
, 1);
1043 static void ssh2_pkt_init(int pkt_type
)
1046 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1048 static void ssh2_pkt_addbool(unsigned char value
)
1050 ssh2_pkt_adddata(&value
, 1);
1052 static void ssh2_pkt_adduint32(unsigned long value
)
1055 PUT_32BIT(x
, value
);
1056 ssh2_pkt_adddata(x
, 4);
1058 static void ssh2_pkt_addstring_start(void)
1060 ssh2_pkt_adduint32(0);
1061 pktout
.savedpos
= pktout
.length
;
1063 static void ssh2_pkt_addstring_str(char *data
)
1065 ssh2_pkt_adddata(data
, strlen(data
));
1066 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1067 pktout
.length
- pktout
.savedpos
);
1069 static void ssh2_pkt_addstring_data(char *data
, int len
)
1071 ssh2_pkt_adddata(data
, len
);
1072 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1073 pktout
.length
- pktout
.savedpos
);
1075 static void ssh2_pkt_addstring(char *data
)
1077 ssh2_pkt_addstring_start();
1078 ssh2_pkt_addstring_str(data
);
1080 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1083 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1086 fatalbox("out of memory");
1088 for (i
= 1; i
<= n
; i
++)
1089 p
[i
] = bignum_byte(b
, n
- i
);
1091 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1093 memmove(p
, p
+ i
, n
+ 1 - i
);
1097 static void ssh2_pkt_addmp(Bignum b
)
1101 p
= ssh2_mpint_fmt(b
, &len
);
1102 ssh2_pkt_addstring_start();
1103 ssh2_pkt_addstring_data(p
, len
);
1108 * Construct an SSH2 final-form packet: compress it, encrypt it,
1109 * put the MAC on it. Final packet, ready to be sent, is stored in
1110 * pktout.data. Total length is returned.
1112 static int ssh2_pkt_construct(void)
1114 int cipherblk
, maclen
, padding
, i
;
1115 static unsigned long outgoing_sequence
= 0;
1118 * Compress packet payload.
1121 debug(("Pre-compression payload:\n"));
1122 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1125 unsigned char *newpayload
;
1127 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1128 &newpayload
, &newlen
)) {
1130 ssh2_pkt_adddata(newpayload
, newlen
);
1136 * Add padding. At least four bytes, and must also bring total
1137 * length (minus MAC) up to a multiple of the block size.
1139 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1140 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1143 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1144 maclen
= csmac ? csmac
->len
: 0;
1145 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1146 pktout
.data
[4] = padding
;
1147 for (i
= 0; i
< padding
; i
++)
1148 pktout
.data
[pktout
.length
+ i
] = random_byte();
1149 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1151 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1153 outgoing_sequence
++; /* whether or not we MACed */
1156 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1157 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1161 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1163 /* Ready-to-send packet starts at pktout.data. We return length. */
1164 return pktout
.length
+ padding
+ maclen
;
1168 * Construct and send an SSH2 packet immediately.
1170 static void ssh2_pkt_send(void)
1172 int len
= ssh2_pkt_construct();
1173 sk_write(s
, pktout
.data
, len
);
1177 * Construct an SSH2 packet and add it to a deferred data block.
1178 * Useful for sending multiple packets in a single sk_write() call,
1179 * to prevent a traffic-analysing listener from being able to work
1180 * out the length of any particular packet (such as the password
1183 * Note that because SSH2 sequence-numbers its packets, this can
1184 * NOT be used as an m4-style `defer' allowing packets to be
1185 * constructed in one order and sent in another.
1187 static void ssh2_pkt_defer(void)
1189 int len
= ssh2_pkt_construct();
1190 if (deferred_len
+ len
> deferred_size
) {
1191 deferred_size
= deferred_len
+ len
+ 128;
1192 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1194 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1195 deferred_len
+= len
;
1199 * Send the whole deferred data block constructed by
1200 * ssh2_pkt_defer() or SSH1's defer_packet().
1202 static void ssh_pkt_defersend(void)
1204 sk_write(s
, deferred_send_data
, deferred_len
);
1205 deferred_len
= deferred_size
= 0;
1206 sfree(deferred_send_data
);
1207 deferred_send_data
= NULL
;
1211 void bndebug(char *string
, Bignum b
)
1215 p
= ssh2_mpint_fmt(b
, &len
);
1216 debug(("%s", string
));
1217 for (i
= 0; i
< len
; i
++)
1218 debug((" %02x", p
[i
]));
1224 static void sha_mpint(SHA_State
* s
, Bignum b
)
1228 p
= ssh2_mpint_fmt(b
, &len
);
1229 sha_string(s
, p
, len
);
1234 * SSH2 packet decode functions.
1236 static unsigned long ssh2_pkt_getuint32(void)
1238 unsigned long value
;
1239 if (pktin
.length
- pktin
.savedpos
< 4)
1240 return 0; /* arrgh, no way to decline (FIXME?) */
1241 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1242 pktin
.savedpos
+= 4;
1245 static int ssh2_pkt_getbool(void)
1247 unsigned long value
;
1248 if (pktin
.length
- pktin
.savedpos
< 1)
1249 return 0; /* arrgh, no way to decline (FIXME?) */
1250 value
= pktin
.data
[pktin
.savedpos
] != 0;
1254 static void ssh2_pkt_getstring(char **p
, int *length
)
1257 if (pktin
.length
- pktin
.savedpos
< 4)
1259 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1260 pktin
.savedpos
+= 4;
1261 if (pktin
.length
- pktin
.savedpos
< *length
)
1263 *p
= pktin
.data
+ pktin
.savedpos
;
1264 pktin
.savedpos
+= *length
;
1266 static Bignum
ssh2_pkt_getmp(void)
1272 ssh2_pkt_getstring(&p
, &length
);
1276 bombout(("internal error: Can't handle negative mpints"));
1279 b
= bignum_from_bytes(p
, length
);
1284 * Examine the remote side's version string and compare it against
1285 * a list of known buggy implementations.
1287 static void ssh_detect_bugs(char *vstring
)
1289 char *imp
; /* pointer to implementation part */
1291 imp
+= strcspn(imp
, "-");
1294 imp
+= strcspn(imp
, "-");
1298 ssh_remote_bugs
= 0;
1300 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1301 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1302 !strcmp(imp
, "1.2.22")) {
1304 * These versions don't support SSH1_MSG_IGNORE, so we have
1305 * to use a different defence against password length
1308 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1309 logevent("We believe remote version has SSH1 ignore bug");
1312 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1313 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1314 !strncmp(imp
, "2.1 ", 4)) {
1316 * These versions have the HMAC bug.
1318 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1319 logevent("We believe remote version has SSH2 HMAC bug");
1323 static int do_ssh_init(unsigned char c
)
1326 static char version
[10];
1327 static char *vstring
;
1328 static int vstrsize
;
1334 /* Search for the string "SSH-" in the input. */
1337 static const int transS
[] = { 1, 2, 2, 1 };
1338 static const int transH
[] = { 0, 0, 3, 0 };
1339 static const int transminus
[] = { 0, 0, 0, -1 };
1350 crReturn(1); /* get another character */
1353 vstring
= smalloc(16);
1355 strcpy(vstring
, "SSH-");
1359 crReturn(1); /* get another char */
1360 if (vslen
>= vstrsize
- 1) {
1362 vstring
= srealloc(vstring
, vstrsize
);
1364 vstring
[vslen
++] = c
;
1369 } else if (i
< sizeof(version
) - 1)
1371 } else if (c
== '\n')
1375 ssh_agentfwd_enabled
= FALSE
;
1376 rdpkt2_state
.incoming_sequence
= 0;
1379 vlog
= smalloc(20 + vslen
);
1380 sprintf(vlog
, "Server version: %s", vstring
);
1381 ssh_detect_bugs(vstring
);
1382 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1387 * Server version "1.99" means we can choose whether we use v1
1388 * or v2 protocol. Choice is based on cfg.sshprot.
1390 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1392 * This is a v2 server. Begin v2 protocol.
1394 char verstring
[80], vlog
[100];
1395 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1396 SHA_Init(&exhashbase
);
1398 * Hash our version string and their version string.
1400 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1401 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1402 sprintf(vlog
, "We claim version: %s", verstring
);
1404 strcat(verstring
, "\n");
1405 logevent("Using SSH protocol version 2");
1406 sk_write(s
, verstring
, strlen(verstring
));
1407 ssh_protocol
= ssh2_protocol
;
1409 s_rdpkt
= ssh2_rdpkt
;
1412 * This is a v1 server. Begin v1 protocol.
1414 char verstring
[80], vlog
[100];
1415 sprintf(verstring
, "SSH-%s-%s",
1416 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1418 sprintf(vlog
, "We claim version: %s", verstring
);
1420 strcat(verstring
, "\n");
1421 logevent("Using SSH protocol version 1");
1422 sk_write(s
, verstring
, strlen(verstring
));
1423 ssh_protocol
= ssh1_protocol
;
1425 s_rdpkt
= ssh1_rdpkt
;
1427 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1434 static void ssh_gotdata(unsigned char *data
, int datalen
)
1439 * To begin with, feed the characters one by one to the
1440 * protocol initialisation / selection function do_ssh_init().
1441 * When that returns 0, we're done with the initial greeting
1442 * exchange and can move on to packet discipline.
1447 crReturnV
; /* more data please */
1448 ret
= do_ssh_init(*data
);
1456 * We emerge from that loop when the initial negotiation is
1457 * over and we have selected an s_rdpkt function. Now pass
1458 * everything to s_rdpkt, and then pass the resulting packets
1459 * to the proper protocol handler.
1464 while (datalen
> 0) {
1465 if (s_rdpkt(&data
, &datalen
) == 0) {
1466 ssh_protocol(NULL
, 0, 1);
1467 if (ssh_state
== SSH_STATE_CLOSED
) {
1477 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1480 ssh_state
= SSH_STATE_CLOSED
;
1484 /* A socket error has occurred. */
1485 connection_fatal(error_msg
);
1487 /* Otherwise, the remote side closed the connection normally. */
1492 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1494 ssh_gotdata(data
, len
);
1495 if (ssh_state
== SSH_STATE_CLOSED
) {
1506 * Connect to specified host and port.
1507 * Returns an error message, or NULL on success.
1508 * Also places the canonical host name into `realhost'. It must be
1509 * freed by the caller.
1511 static char *connect_to_host(char *host
, int port
, char **realhost
)
1513 static struct plug_function_table fn_table
= {
1516 }, *fn_table_ptr
= &fn_table
;
1525 savedhost
= smalloc(1 + strlen(host
));
1527 fatalbox("Out of memory");
1528 strcpy(savedhost
, host
);
1531 port
= 22; /* default ssh port */
1544 addr
= sk_namelookup(host
, realhost
);
1545 if ((err
= sk_addr_error(addr
)))
1549 *realhost
= strdup(FWhost
);
1555 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1556 if ((err
= sk_socket_error(s
)))
1560 sk_write(s
, "connect ", 8);
1561 sk_write(s
, FWhost
, strlen(FWhost
));
1564 sprintf(buf
, " %d\n", FWport
);
1565 sk_write(s
, buf
, strlen(buf
));
1573 * Handle the key exchange and user authentication phases.
1575 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1578 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1579 unsigned char cookie
[8];
1580 struct RSAKey servkey
, hostkey
;
1581 struct MD5Context md5c
;
1582 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1583 static int tried_publickey
;
1584 static unsigned char session_id
[16];
1586 static char username
[100];
1593 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1594 bombout(("Public key packet not received"));
1598 logevent("Received public keys");
1600 memcpy(cookie
, pktin
.body
, 8);
1602 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1603 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1606 * Log the host key fingerprint.
1610 logevent("Host key fingerprint is:");
1611 strcpy(logmsg
, " ");
1612 hostkey
.comment
= NULL
;
1613 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1614 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1618 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1619 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1620 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1622 ssh1_local_protoflags
=
1623 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1624 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1627 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1628 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1629 MD5Update(&md5c
, pktin
.body
, 8);
1630 MD5Final(session_id
, &md5c
);
1632 for (i
= 0; i
< 32; i
++)
1633 session_key
[i
] = random_byte();
1635 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1637 rsabuf
= smalloc(len
);
1639 fatalbox("Out of memory");
1642 * Verify the host key.
1646 * First format the key into a string.
1648 int len
= rsastr_len(&hostkey
);
1649 char fingerprint
[100];
1650 char *keystr
= smalloc(len
);
1652 fatalbox("Out of memory");
1653 rsastr_fmt(keystr
, &hostkey
);
1654 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1655 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1660 for (i
= 0; i
< 32; i
++) {
1661 rsabuf
[i
] = session_key
[i
];
1663 rsabuf
[i
] ^= session_id
[i
];
1666 if (hostkey
.bytes
> servkey
.bytes
) {
1667 rsaencrypt(rsabuf
, 32, &servkey
);
1668 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1670 rsaencrypt(rsabuf
, 32, &hostkey
);
1671 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1674 logevent("Encrypted session key");
1676 switch (cfg
.cipher
) {
1677 case CIPHER_BLOWFISH
:
1678 cipher_type
= SSH_CIPHER_BLOWFISH
;
1681 cipher_type
= SSH_CIPHER_DES
;
1684 cipher_type
= SSH_CIPHER_3DES
;
1687 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1688 cipher_type
= SSH_CIPHER_3DES
;
1691 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1693 ("Selected cipher not supported, falling back to 3DES\r\n");
1694 cipher_type
= SSH_CIPHER_3DES
;
1695 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1696 bombout(("Server violates SSH 1 protocol by "
1697 "not supporting 3DES encryption"));
1701 switch (cipher_type
) {
1702 case SSH_CIPHER_3DES
:
1703 logevent("Using 3DES encryption");
1705 case SSH_CIPHER_DES
:
1706 logevent("Using single-DES encryption");
1708 case SSH_CIPHER_BLOWFISH
:
1709 logevent("Using Blowfish encryption");
1713 send_packet(SSH1_CMSG_SESSION_KEY
,
1714 PKT_CHAR
, cipher_type
,
1715 PKT_DATA
, cookie
, 8,
1716 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1717 PKT_DATA
, rsabuf
, len
,
1718 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1720 logevent("Trying to enable encryption...");
1724 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1725 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1726 cipher
->sesskey(session_key
);
1730 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1731 bombout(("Encryption not successfully enabled"));
1735 logevent("Successfully started encryption");
1741 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1743 if (!ssh_get_line("login as: ",
1744 username
, sizeof(username
), FALSE
)) {
1746 * get_line failed to get a username.
1749 logevent("No username provided. Abandoning session.");
1750 ssh_state
= SSH_STATE_CLOSED
;
1754 c_write_str("login as: ");
1757 crWaitUntil(!ispkt
);
1759 switch (c
= *in
++) {
1768 c_write_str("\b \b");
1775 c_write_str("\b \b");
1785 if (((c
>= ' ' && c
<= '~') ||
1786 ((unsigned char) c
>= 160)) && pos
< 40) {
1787 username
[pos
++] = c
;
1793 c_write_str("\r\n");
1794 username
[strcspn(username
, "\n\r")] = '\0';
1797 strncpy(username
, cfg
.username
, 99);
1798 username
[99] = '\0';
1801 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1803 char userlog
[22 + sizeof(username
)];
1804 sprintf(userlog
, "Sent username \"%s\"", username
);
1806 if (flags
& FLAG_INTERACTIVE
&&
1807 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1808 strcat(userlog
, "\r\n");
1809 c_write_str(userlog
);
1816 tried_publickey
= 0;
1818 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1819 static char password
[100];
1820 static char prompt
[200];
1823 static int pwpkt_type
;
1825 * Show password prompt, having first obtained it via a TIS
1826 * or CryptoCard exchange if we're doing TIS or CryptoCard
1829 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1830 if (agent_exists()) {
1832 * Attempt RSA authentication using Pageant.
1834 static unsigned char request
[5], *response
, *p
;
1835 static int responselen
;
1836 static int i
, nkeys
;
1837 static int authed
= FALSE
;
1840 logevent("Pageant is running. Requesting keys.");
1842 /* Request the keys held by the agent. */
1843 PUT_32BIT(request
, 1);
1844 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1845 agent_query(request
, 5, &r
, &responselen
);
1846 response
= (unsigned char *) r
;
1847 if (response
&& responselen
>= 5 &&
1848 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
1850 nkeys
= GET_32BIT(p
);
1854 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1857 for (i
= 0; i
< nkeys
; i
++) {
1858 static struct RSAKey key
;
1859 static Bignum challenge
;
1860 static char *commentp
;
1861 static int commentlen
;
1865 sprintf(buf
, "Trying Pageant key #%d", i
);
1869 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1870 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1871 commentlen
= GET_32BIT(p
);
1875 send_packet(SSH1_CMSG_AUTH_RSA
,
1876 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1878 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1879 logevent("Key refused");
1882 logevent("Received RSA challenge");
1883 ssh1_read_bignum(pktin
.body
, &challenge
);
1885 char *agentreq
, *q
, *ret
;
1887 len
= 1 + 4; /* message type, bit count */
1888 len
+= ssh1_bignum_length(key
.exponent
);
1889 len
+= ssh1_bignum_length(key
.modulus
);
1890 len
+= ssh1_bignum_length(challenge
);
1891 len
+= 16; /* session id */
1892 len
+= 4; /* response format */
1893 agentreq
= smalloc(4 + len
);
1894 PUT_32BIT(agentreq
, len
);
1896 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1897 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
1899 q
+= ssh1_write_bignum(q
, key
.exponent
);
1900 q
+= ssh1_write_bignum(q
, key
.modulus
);
1901 q
+= ssh1_write_bignum(q
, challenge
);
1902 memcpy(q
, session_id
, 16);
1904 PUT_32BIT(q
, 1); /* response format */
1905 agent_query(agentreq
, len
+ 4, &ret
, &retlen
);
1908 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1909 logevent("Sending Pageant's response");
1910 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1911 PKT_DATA
, ret
+ 5, 16,
1915 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1917 ("Pageant's response accepted");
1918 if (flags
& FLAG_VERBOSE
) {
1920 ("Authenticated using RSA key \"");
1921 c_write(commentp
, commentlen
);
1922 c_write_str("\" from agent\r\n");
1927 ("Pageant's response not accepted");
1930 ("Pageant failed to answer challenge");
1934 logevent("No reply received from Pageant");
1937 freebn(key
.exponent
);
1938 freebn(key
.modulus
);
1947 if (*cfg
.keyfile
&& !tried_publickey
)
1948 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1950 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1952 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
))) {
1953 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1954 logevent("Requested TIS authentication");
1955 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1957 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1958 logevent("TIS authentication declined");
1959 if (flags
& FLAG_INTERACTIVE
)
1960 c_write_str("TIS authentication refused.\r\n");
1962 int challengelen
= ((pktin
.body
[0] << 24) |
1963 (pktin
.body
[1] << 16) |
1964 (pktin
.body
[2] << 8) |
1966 logevent("Received TIS challenge");
1967 if (challengelen
> sizeof(prompt
) - 1)
1968 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
1969 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
1970 prompt
[challengelen
] = '\0';
1973 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1975 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
))) {
1976 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1977 logevent("Requested CryptoCard authentication");
1978 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1980 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1981 logevent("CryptoCard authentication declined");
1982 c_write_str("CryptoCard authentication refused.\r\n");
1984 int challengelen
= ((pktin
.body
[0] << 24) |
1985 (pktin
.body
[1] << 16) |
1986 (pktin
.body
[2] << 8) |
1988 logevent("Received CryptoCard challenge");
1989 if (challengelen
> sizeof(prompt
) - 1)
1990 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
1991 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
1992 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1993 sizeof(prompt
) - challengelen
);
1994 prompt
[sizeof(prompt
) - 1] = '\0';
1997 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1998 sprintf(prompt
, "%.90s@%.90s's password: ",
1999 username
, savedhost
);
2001 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2002 char *comment
= NULL
;
2003 if (flags
& FLAG_VERBOSE
)
2004 c_write_str("Trying public key authentication.\r\n");
2005 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2006 if (flags
& FLAG_VERBOSE
)
2007 c_write_str("No passphrase required.\r\n");
2010 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2015 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2017 * get_line failed to get a password (for example
2018 * because one was supplied on the command line
2019 * which has already failed to work). Terminate.
2021 send_packet(SSH1_MSG_DISCONNECT
,
2022 PKT_STR
, "No more passwords available to try",
2024 connection_fatal("Unable to authenticate");
2025 ssh_state
= SSH_STATE_CLOSED
;
2029 c_write_str(prompt
);
2033 crWaitUntil(!ispkt
);
2035 switch (c
= *in
++) {
2056 if (((c
>= ' ' && c
<= '~') ||
2057 ((unsigned char) c
>= 160))
2058 && pos
< sizeof(password
))
2059 password
[pos
++] = c
;
2063 c_write_str("\r\n");
2067 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2069 * Try public key authentication with the specified
2072 static struct RSAKey pubkey
;
2073 static Bignum challenge
, response
;
2075 static unsigned char buffer
[32];
2077 tried_publickey
= 1;
2078 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2080 c_write_str("Couldn't load public key from ");
2081 c_write_str(cfg
.keyfile
);
2082 c_write_str(".\r\n");
2083 continue; /* go and try password */
2086 c_write_str("Wrong passphrase.\r\n");
2087 tried_publickey
= 0;
2088 continue; /* try again */
2092 * Send a public key attempt.
2094 send_packet(SSH1_CMSG_AUTH_RSA
,
2095 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2098 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2099 c_write_str("Server refused our public key.\r\n");
2100 continue; /* go and try password */
2102 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2103 bombout(("Bizarre response to offer of public key"));
2106 ssh1_read_bignum(pktin
.body
, &challenge
);
2107 response
= rsadecrypt(challenge
, &pubkey
);
2108 freebn(pubkey
.private_exponent
); /* burn the evidence */
2110 for (i
= 0; i
< 32; i
++) {
2111 buffer
[i
] = bignum_byte(response
, 31 - i
);
2115 MD5Update(&md5c
, buffer
, 32);
2116 MD5Update(&md5c
, session_id
, 16);
2117 MD5Final(buffer
, &md5c
);
2119 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2120 PKT_DATA
, buffer
, 16, PKT_END
);
2123 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2124 if (flags
& FLAG_VERBOSE
)
2126 ("Failed to authenticate with our public key.\r\n");
2127 continue; /* go and try password */
2128 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2130 ("Bizarre response to RSA authentication response"));
2134 break; /* we're through! */
2136 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2138 * Defence against traffic analysis: we send a
2139 * whole bunch of packets containing strings of
2140 * different lengths. One of these strings is the
2141 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2142 * The others are all random data in
2143 * SSH1_MSG_IGNORE packets. This way a passive
2144 * listener can't tell which is the password, and
2145 * hence can't deduce the password length.
2147 * Anybody with a password length greater than 16
2148 * bytes is going to have enough entropy in their
2149 * password that a listener won't find it _that_
2150 * much help to know how long it is. So what we'll
2153 * - if password length < 16, we send 15 packets
2154 * containing string lengths 1 through 15
2156 * - otherwise, we let N be the nearest multiple
2157 * of 8 below the password length, and send 8
2158 * packets containing string lengths N through
2159 * N+7. This won't obscure the order of
2160 * magnitude of the password length, but it will
2161 * introduce a bit of extra uncertainty.
2163 * A few servers (the old 1.2.18 through 1.2.22)
2164 * can't deal with SSH1_MSG_IGNORE. For these
2165 * servers, we need an alternative defence. We make
2166 * use of the fact that the password is interpreted
2167 * as a C string: so we can append a NUL, then some
2170 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2175 len
= strlen(password
);
2176 if (len
< sizeof(string
)) {
2178 strcpy(string
, password
);
2179 len
++; /* cover the zero byte */
2180 while (len
< sizeof(string
)) {
2181 string
[len
++] = (char) random_byte();
2186 send_packet(pwpkt_type
, PKT_INT
, len
,
2187 PKT_DATA
, s
, len
, PKT_END
);
2189 int bottom
, top
, pwlen
, i
;
2192 pwlen
= strlen(password
);
2194 bottom
= 0; /* zero length passwords are OK! :-) */
2197 bottom
= pwlen
& ~7;
2201 assert(pwlen
>= bottom
&& pwlen
<= top
);
2203 randomstr
= smalloc(top
+ 1);
2205 for (i
= bottom
; i
<= top
; i
++) {
2207 defer_packet(pwpkt_type
, PKT_STR
, password
,
2210 for (j
= 0; j
< i
; j
++) {
2212 randomstr
[j
] = random_byte();
2213 } while (randomstr
[j
] == '\0');
2215 randomstr
[i
] = '\0';
2216 defer_packet(SSH1_MSG_IGNORE
,
2217 PKT_STR
, randomstr
, PKT_END
);
2220 ssh_pkt_defersend();
2223 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2226 logevent("Sent password");
2227 memset(password
, 0, strlen(password
));
2229 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2230 if (flags
& FLAG_VERBOSE
)
2231 c_write_str("Access denied\r\n");
2232 logevent("Authentication refused");
2233 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2234 logevent("Received disconnect request");
2235 ssh_state
= SSH_STATE_CLOSED
;
2237 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2238 bombout(("Strange packet received, type %d", pktin
.type
));
2243 logevent("Authentication successful");
2248 void sshfwd_close(struct ssh_channel
*c
)
2250 if (c
&& !c
->closes
) {
2251 if (ssh_version
== 1) {
2252 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2255 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2256 ssh2_pkt_adduint32(c
->remoteid
);
2260 if (c
->type
== CHAN_X11
) {
2262 logevent("X11 connection terminated");
2267 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2269 if (ssh_version
== 1) {
2270 send_packet(SSH1_MSG_CHANNEL_DATA
,
2271 PKT_INT
, c
->remoteid
,
2272 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2274 ssh2_add_channel_data(c
, buf
, len
);
2279 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2285 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2288 if (ssh_state
== SSH_STATE_CLOSED
)
2291 if (cfg
.agentfwd
&& agent_exists()) {
2292 logevent("Requesting agent forwarding");
2293 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2297 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2298 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2299 bombout(("Protocol confusion"));
2301 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2302 logevent("Agent forwarding refused");
2304 logevent("Agent forwarding enabled");
2305 ssh_agentfwd_enabled
= TRUE
;
2309 if (cfg
.x11_forward
) {
2310 char proto
[20], data
[64];
2311 logevent("Requesting X11 forwarding");
2312 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2313 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2314 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2315 PKT_STR
, proto
, PKT_STR
, data
,
2316 PKT_INT
, 0, PKT_END
);
2318 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2319 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2324 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2325 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2326 bombout(("Protocol confusion"));
2328 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2329 logevent("X11 forwarding refused");
2331 logevent("X11 forwarding enabled");
2332 ssh_X11_fwd_enabled
= TRUE
;
2337 send_packet(SSH1_CMSG_REQUEST_PTY
,
2338 PKT_STR
, cfg
.termtype
,
2339 PKT_INT
, rows
, PKT_INT
, cols
,
2340 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2341 ssh_state
= SSH_STATE_INTERMED
;
2345 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2346 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2347 bombout(("Protocol confusion"));
2349 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2350 c_write_str("Server refused to allocate pty\r\n");
2351 ssh_editing
= ssh_echoing
= 1;
2353 logevent("Allocated pty");
2355 ssh_editing
= ssh_echoing
= 1;
2358 if (cfg
.compression
) {
2359 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2363 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2364 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2365 bombout(("Protocol confusion"));
2367 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2368 c_write_str("Server refused to compress\r\n");
2370 logevent("Started compression");
2371 ssh1_compressing
= TRUE
;
2372 zlib_compress_init();
2373 zlib_decompress_init();
2376 if (*cfg
.remote_cmd_ptr
)
2377 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
,
2380 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2381 logevent("Started session");
2383 ssh_state
= SSH_STATE_SESSION
;
2387 ssh_special(TS_EOF
);
2389 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2391 ssh_channels
= newtree234(ssh_channelcmp
);
2395 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2396 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2397 long len
= GET_32BIT(pktin
.body
);
2398 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2399 pktin
.body
+ 4, len
);
2400 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2401 ssh_state
= SSH_STATE_CLOSED
;
2402 logevent("Received disconnect request");
2404 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2405 /* Remote side is trying to open a channel to talk to our
2406 * X-Server. Give them back a local channel number. */
2407 struct ssh_channel
*c
;
2409 logevent("Received X11 connect request");
2410 /* Refuse if X11 forwarding is disabled. */
2411 if (!ssh_X11_fwd_enabled
) {
2412 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2413 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2414 logevent("Rejected X11 connect request");
2416 c
= smalloc(sizeof(struct ssh_channel
));
2418 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2419 logevent("opening X11 forward connection failed");
2421 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2422 PKT_INT
, GET_32BIT(pktin
.body
),
2426 ("opening X11 forward connection succeeded");
2427 c
->remoteid
= GET_32BIT(pktin
.body
);
2428 c
->localid
= alloc_channel_id();
2430 c
->type
= CHAN_X11
; /* identify channel type */
2431 add234(ssh_channels
, c
);
2432 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2433 PKT_INT
, c
->remoteid
, PKT_INT
,
2434 c
->localid
, PKT_END
);
2435 logevent("Opened X11 forward channel");
2438 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2439 /* Remote side is trying to open a channel to talk to our
2440 * agent. Give them back a local channel number. */
2441 struct ssh_channel
*c
;
2443 /* Refuse if agent forwarding is disabled. */
2444 if (!ssh_agentfwd_enabled
) {
2445 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2446 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2448 c
= smalloc(sizeof(struct ssh_channel
));
2449 c
->remoteid
= GET_32BIT(pktin
.body
);
2450 c
->localid
= alloc_channel_id();
2452 c
->type
= CHAN_AGENT
; /* identify channel type */
2453 c
->u
.a
.lensofar
= 0;
2454 add234(ssh_channels
, c
);
2455 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2456 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2459 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2460 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2461 /* Remote side closes a channel. */
2462 unsigned i
= GET_32BIT(pktin
.body
);
2463 struct ssh_channel
*c
;
2464 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2468 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2469 if (!(c
->closes
& closetype
))
2470 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2472 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2473 logevent("X11 connection closed");
2474 assert(c
->u
.x11
.s
!= NULL
);
2475 x11_close(c
->u
.x11
.s
);
2478 c
->closes
|= closetype
;
2479 if (c
->closes
== 3) {
2480 del234(ssh_channels
, c
);
2484 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2485 /* Data sent down one of our channels. */
2486 int i
= GET_32BIT(pktin
.body
);
2487 int len
= GET_32BIT(pktin
.body
+ 4);
2488 unsigned char *p
= pktin
.body
+ 8;
2489 struct ssh_channel
*c
;
2490 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2494 x11_send(c
->u
.x11
.s
, p
, len
);
2497 /* Data for an agent message. Buffer it. */
2499 if (c
->u
.a
.lensofar
< 4) {
2500 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2501 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2505 c
->u
.a
.lensofar
+= l
;
2507 if (c
->u
.a
.lensofar
== 4) {
2509 4 + GET_32BIT(c
->u
.a
.msglen
);
2510 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2511 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2513 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2515 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
2517 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
2521 c
->u
.a
.lensofar
+= l
;
2523 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2524 void *reply
, *sentreply
;
2526 agent_query(c
->u
.a
.message
,
2527 c
->u
.a
.totallen
, &reply
,
2532 /* Fake SSH_AGENT_FAILURE. */
2533 sentreply
= "\0\0\0\1\5";
2536 send_packet(SSH1_MSG_CHANNEL_DATA
,
2537 PKT_INT
, c
->remoteid
,
2539 PKT_DATA
, sentreply
, replylen
,
2543 sfree(c
->u
.a
.message
);
2544 c
->u
.a
.lensofar
= 0;
2550 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2551 /* may be from EXEC_SHELL on some servers */
2552 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2553 /* may be from EXEC_SHELL on some servers
2554 * if no pty is available or in other odd cases. Ignore */
2555 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2556 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2558 bombout(("Strange packet received: type %d", pktin
.type
));
2563 int len
= min(inlen
, 512);
2564 send_packet(SSH1_CMSG_STDIN_DATA
,
2565 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2576 * Utility routine for decoding comma-separated strings in KEXINIT.
2578 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
2580 int needlen
= strlen(needle
);
2583 * Is it at the start of the string?
2585 if (haylen
>= needlen
&& /* haystack is long enough */
2586 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2587 (haylen
== needlen
|| haystack
[needlen
] == ',')
2588 /* either , or EOS follows */
2592 * If not, search for the next comma and resume after that.
2593 * If no comma found, terminate.
2595 while (haylen
> 0 && *haystack
!= ',')
2596 haylen
--, haystack
++;
2599 haylen
--, haystack
++; /* skip over comma itself */
2604 * SSH2 key creation method.
2606 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
2610 /* First 20 bytes. */
2613 SHA_Bytes(&s
, H
, 20);
2614 SHA_Bytes(&s
, &chr
, 1);
2615 SHA_Bytes(&s
, sessid
, 20);
2616 SHA_Final(&s
, keyspace
);
2617 /* Next 20 bytes. */
2620 SHA_Bytes(&s
, H
, 20);
2621 SHA_Bytes(&s
, keyspace
, 20);
2622 SHA_Final(&s
, keyspace
+ 20);
2626 * Handle the SSH2 transport layer.
2628 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2630 static int i
, j
, len
, nbits
, pbits
;
2632 static Bignum p
, g
, e
, f
, K
;
2633 static int kex_init_value
, kex_reply_value
;
2634 static const struct ssh_mac
**maclist
;
2636 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2637 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2638 static const struct ssh_mac
*csmac_tobe
= NULL
;
2639 static const struct ssh_mac
*scmac_tobe
= NULL
;
2640 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2641 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2642 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2643 static int hostkeylen
, siglen
;
2644 static void *hkey
; /* actual host key */
2645 static unsigned char exchange_hash
[20];
2646 static unsigned char keyspace
[40];
2647 static const struct ssh2_ciphers
*preferred_cipher
;
2648 static const struct ssh_compress
*preferred_comp
;
2649 static int first_kex
;
2656 * Set up the preferred cipher and compression.
2658 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2659 preferred_cipher
= &ssh2_blowfish
;
2660 } else if (cfg
.cipher
== CIPHER_DES
) {
2661 logevent("Single DES not supported in SSH2; using 3DES");
2662 preferred_cipher
= &ssh2_3des
;
2663 } else if (cfg
.cipher
== CIPHER_3DES
) {
2664 preferred_cipher
= &ssh2_3des
;
2665 } else if (cfg
.cipher
== CIPHER_AES
) {
2666 preferred_cipher
= &ssh2_aes
;
2668 /* Shouldn't happen, but we do want to initialise to _something_. */
2669 preferred_cipher
= &ssh2_3des
;
2671 if (cfg
.compression
)
2672 preferred_comp
= &ssh_zlib
;
2674 preferred_comp
= &ssh_comp_none
;
2677 * Be prepared to work around the buggy MAC problem.
2679 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2680 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2682 maclist
= macs
, nmacs
= lenof(macs
);
2686 * Construct and send our key exchange packet.
2688 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2689 for (i
= 0; i
< 16; i
++)
2690 ssh2_pkt_addbyte((unsigned char) random_byte());
2691 /* List key exchange algorithms. */
2692 ssh2_pkt_addstring_start();
2693 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2694 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2695 if (i
< lenof(kex_algs
) - 1)
2696 ssh2_pkt_addstring_str(",");
2698 /* List server host key algorithms. */
2699 ssh2_pkt_addstring_start();
2700 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2701 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2702 if (i
< lenof(hostkey_algs
) - 1)
2703 ssh2_pkt_addstring_str(",");
2705 /* List client->server encryption algorithms. */
2706 ssh2_pkt_addstring_start();
2707 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2708 const struct ssh2_ciphers
*c
=
2709 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2710 for (j
= 0; j
< c
->nciphers
; j
++) {
2711 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2712 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
2713 ssh2_pkt_addstring_str(",");
2716 /* List server->client encryption algorithms. */
2717 ssh2_pkt_addstring_start();
2718 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2719 const struct ssh2_ciphers
*c
=
2720 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2721 for (j
= 0; j
< c
->nciphers
; j
++) {
2722 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2723 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
2724 ssh2_pkt_addstring_str(",");
2727 /* List client->server MAC algorithms. */
2728 ssh2_pkt_addstring_start();
2729 for (i
= 0; i
< nmacs
; i
++) {
2730 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2732 ssh2_pkt_addstring_str(",");
2734 /* List server->client MAC algorithms. */
2735 ssh2_pkt_addstring_start();
2736 for (i
= 0; i
< nmacs
; i
++) {
2737 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2739 ssh2_pkt_addstring_str(",");
2741 /* List client->server compression algorithms. */
2742 ssh2_pkt_addstring_start();
2743 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2744 const struct ssh_compress
*c
=
2745 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2746 ssh2_pkt_addstring_str(c
->name
);
2747 if (i
< lenof(compressions
))
2748 ssh2_pkt_addstring_str(",");
2750 /* List server->client compression algorithms. */
2751 ssh2_pkt_addstring_start();
2752 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2753 const struct ssh_compress
*c
=
2754 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2755 ssh2_pkt_addstring_str(c
->name
);
2756 if (i
< lenof(compressions
))
2757 ssh2_pkt_addstring_str(",");
2759 /* List client->server languages. Empty list. */
2760 ssh2_pkt_addstring_start();
2761 /* List server->client languages. Empty list. */
2762 ssh2_pkt_addstring_start();
2763 /* First KEX packet does _not_ follow, because we're not that brave. */
2764 ssh2_pkt_addbool(FALSE
);
2766 ssh2_pkt_adduint32(0);
2768 exhash
= exhashbase
;
2769 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
2775 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
2778 * Now examine the other side's KEXINIT to see what we're up
2781 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2782 bombout(("expected key exchange packet from server"));
2787 cscipher_tobe
= NULL
;
2788 sccipher_tobe
= NULL
;
2793 pktin
.savedpos
+= 16; /* skip garbage cookie */
2794 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2795 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2796 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2801 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2802 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2803 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2804 hostkey
= hostkey_algs
[i
];
2808 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2809 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2810 const struct ssh2_ciphers
*c
=
2811 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2812 for (j
= 0; j
< c
->nciphers
; j
++) {
2813 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2814 cscipher_tobe
= c
->list
[j
];
2821 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2822 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2823 const struct ssh2_ciphers
*c
=
2824 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2825 for (j
= 0; j
< c
->nciphers
; j
++) {
2826 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2827 sccipher_tobe
= c
->list
[j
];
2834 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2835 for (i
= 0; i
< nmacs
; i
++) {
2836 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2837 csmac_tobe
= maclist
[i
];
2841 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2842 for (i
= 0; i
< nmacs
; i
++) {
2843 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2844 scmac_tobe
= maclist
[i
];
2848 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2849 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2850 const struct ssh_compress
*c
=
2851 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2852 if (in_commasep_string(c
->name
, str
, len
)) {
2857 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2858 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2859 const struct ssh_compress
*c
=
2860 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2861 if (in_commasep_string(c
->name
, str
, len
)) {
2868 * Work out the number of bits of key we will need from the key
2869 * exchange. We start with the maximum key length of either
2875 csbits
= cscipher_tobe
->keylen
;
2876 scbits
= sccipher_tobe
->keylen
;
2877 nbits
= (csbits
> scbits ? csbits
: scbits
);
2879 /* The keys only have 160-bit entropy, since they're based on
2880 * a SHA-1 hash. So cap the key size at 160 bits. */
2885 * If we're doing Diffie-Hellman group exchange, start by
2886 * requesting a group.
2888 if (kex
== &ssh_diffiehellman_gex
) {
2889 logevent("Doing Diffie-Hellman group exchange");
2891 * Work out how big a DH group we will need to allow that
2894 pbits
= 512 << ((nbits
- 1) / 64);
2895 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2896 ssh2_pkt_adduint32(pbits
);
2900 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2901 bombout(("expected key exchange group packet from server"));
2904 p
= ssh2_pkt_getmp();
2905 g
= ssh2_pkt_getmp();
2906 dh_setup_group(p
, g
);
2907 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2908 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2911 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2912 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2915 logevent("Doing Diffie-Hellman key exchange");
2917 * Now generate and send e for Diffie-Hellman.
2919 e
= dh_create_e(nbits
* 2);
2920 ssh2_pkt_init(kex_init_value
);
2925 if (pktin
.type
!= kex_reply_value
) {
2926 bombout(("expected key exchange reply packet from server"));
2929 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2930 f
= ssh2_pkt_getmp();
2931 ssh2_pkt_getstring(&sigdata
, &siglen
);
2935 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2936 if (kex
== &ssh_diffiehellman_gex
) {
2937 sha_uint32(&exhash
, pbits
);
2938 sha_mpint(&exhash
, p
);
2939 sha_mpint(&exhash
, g
);
2941 sha_mpint(&exhash
, e
);
2942 sha_mpint(&exhash
, f
);
2943 sha_mpint(&exhash
, K
);
2944 SHA_Final(&exhash
, exchange_hash
);
2949 debug(("Exchange hash is:\n"));
2950 dmemdump(exchange_hash
, 20);
2953 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2954 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2955 bombout(("Server failed host key check"));
2960 * Expect SSH2_MSG_NEWKEYS from server.
2963 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2964 bombout(("expected new-keys packet from server"));
2969 * Authenticate remote host: verify host key. (We've already
2970 * checked the signature of the exchange hash.)
2972 keystr
= hostkey
->fmtkey(hkey
);
2973 fingerprint
= hostkey
->fingerprint(hkey
);
2974 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2975 keystr
, fingerprint
);
2976 if (first_kex
) { /* don't bother logging this in rekeys */
2977 logevent("Host key fingerprint is:");
2978 logevent(fingerprint
);
2982 hostkey
->freekey(hkey
);
2985 * Send SSH2_MSG_NEWKEYS.
2987 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2991 * Create and initialise session keys.
2993 cscipher
= cscipher_tobe
;
2994 sccipher
= sccipher_tobe
;
2997 cscomp
= cscomp_tobe
;
2998 sccomp
= sccomp_tobe
;
2999 cscomp
->compress_init();
3000 sccomp
->decompress_init();
3002 * Set IVs after keys. Here we use the exchange hash from the
3003 * _first_ key exchange.
3006 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3007 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3008 cscipher
->setcskey(keyspace
);
3009 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3010 sccipher
->setsckey(keyspace
);
3011 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3012 cscipher
->setcsiv(keyspace
);
3013 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3014 sccipher
->setsciv(keyspace
);
3015 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3016 csmac
->setcskey(keyspace
);
3017 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3018 scmac
->setsckey(keyspace
);
3021 * If this is the first key exchange phase, we must pass the
3022 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3023 * wants to see it but because it will need time to initialise
3024 * itself before it sees an actual packet. In subsequent key
3025 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3026 * it would only confuse the layer above.
3034 * Now we're encrypting. Begin returning 1 to the protocol main
3035 * function so that other things can run on top of the
3036 * transport. If we ever see a KEXINIT, we must go back to the
3039 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3042 logevent("Server initiated key re-exchange");
3043 goto begin_key_exchange
;
3049 * Add data to an SSH2 channel output buffer.
3051 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3054 if (c
->v2
.outbufsize
< c
->v2
.outbuflen
+ len
) {
3055 c
->v2
.outbufsize
= c
->v2
.outbuflen
+ len
+ 1024;
3056 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
, c
->v2
.outbufsize
);
3058 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
, buf
, len
);
3059 c
->v2
.outbuflen
+= len
;
3063 * Attempt to send data on an SSH2 channel.
3065 static void ssh2_try_send(struct ssh_channel
*c
)
3067 while (c
->v2
.remwindow
> 0 && c
->v2
.outbuflen
> 0) {
3068 unsigned len
= c
->v2
.remwindow
;
3069 if (len
> c
->v2
.outbuflen
)
3070 len
= c
->v2
.outbuflen
;
3071 if (len
> c
->v2
.remmaxpkt
)
3072 len
= c
->v2
.remmaxpkt
;
3073 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3074 ssh2_pkt_adduint32(c
->remoteid
);
3075 ssh2_pkt_addstring_start();
3076 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
3078 c
->v2
.outbuflen
-= len
;
3079 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+ len
, c
->v2
.outbuflen
);
3080 c
->v2
.remwindow
-= len
;
3085 * Handle the SSH2 userauth and connection layers.
3087 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3089 static unsigned long remote_winsize
;
3090 static unsigned long remote_maxpkt
;
3092 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3097 AUTH_TYPE_PUBLICKEY
,
3098 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3099 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3102 static int gotit
, need_pw
, can_pubkey
, can_passwd
;
3103 static int tried_pubkey_config
, tried_agent
;
3104 static int we_are_in
;
3105 static char username
[100];
3106 static char pwprompt
[200];
3107 static char password
[100];
3112 * Request userauth protocol, and await a response to it.
3114 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3115 ssh2_pkt_addstring("ssh-userauth");
3117 crWaitUntilV(ispkt
);
3118 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3119 bombout(("Server refused user authentication protocol"));
3124 * We repeat this whole loop, including the username prompt,
3125 * until we manage a successful authentication. If the user
3126 * types the wrong _password_, they are sent back to the
3127 * beginning to try another username. (If they specify a
3128 * username in the config, they are never asked, even if they
3129 * do give a wrong password.)
3131 * I think this best serves the needs of
3133 * - the people who have no configuration, no keys, and just
3134 * want to try repeated (username,password) pairs until they
3135 * type both correctly
3137 * - people who have keys and configuration but occasionally
3138 * need to fall back to passwords
3140 * - people with a key held in Pageant, who might not have
3141 * logged in to a particular machine before; so they want to
3142 * type a username, and then _either_ their key will be
3143 * accepted, _or_ they will type a password. If they mistype
3144 * the username they will want to be able to get back and
3155 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3157 if (!ssh_get_line("login as: ",
3158 username
, sizeof(username
), FALSE
)) {
3160 * get_line failed to get a username.
3163 logevent("No username provided. Abandoning session.");
3164 ssh_state
= SSH_STATE_CLOSED
;
3168 c_write_str("login as: ");
3171 crWaitUntilV(!ispkt
);
3173 switch (c
= *in
++) {
3182 c_write_str("\b \b");
3189 c_write_str("\b \b");
3199 if (((c
>= ' ' && c
<= '~') ||
3200 ((unsigned char) c
>= 160)) && pos
< 40) {
3201 username
[pos
++] = c
;
3208 c_write_str("\r\n");
3209 username
[strcspn(username
, "\n\r")] = '\0';
3212 strncpy(username
, cfg
.username
, 99);
3213 username
[99] = '\0';
3214 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3215 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3221 * Send an authentication request using method "none": (a)
3222 * just in case it succeeds, and (b) so that we know what
3223 * authentication methods we can usefully try next.
3225 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3226 ssh2_pkt_addstring(username
);
3227 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3228 ssh2_pkt_addstring("none"); /* method */
3230 type
= AUTH_TYPE_NONE
;
3234 tried_pubkey_config
= FALSE
;
3235 tried_agent
= FALSE
;
3239 * Wait for the result of the last authentication request.
3242 crWaitUntilV(ispkt
);
3243 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3247 * Don't show the banner if we're operating in
3248 * non-verbose non-interactive mode. (It's probably
3249 * a script, which means nobody will read the
3250 * banner _anyway_, and moreover the printing of
3251 * the banner will screw up processing on the
3252 * output of (say) plink.)
3254 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3255 ssh2_pkt_getstring(&banner
, &size
);
3257 c_write_untrusted(banner
, size
);
3259 crWaitUntilV(ispkt
);
3261 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3262 logevent("Access granted");
3267 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3269 ("Strange packet received during authentication: type %d",
3277 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3278 * we can look at the string in it and know what we can
3279 * helpfully try next.
3284 ssh2_pkt_getstring(&methods
, &methlen
);
3285 if (!ssh2_pkt_getbool()) {
3287 * We have received an unequivocal Access
3288 * Denied. This can translate to a variety of
3291 * - if we'd just tried "none" authentication,
3292 * it's not worth printing anything at all
3294 * - if we'd just tried a public key _offer_,
3295 * the message should be "Server refused our
3296 * key" (or no message at all if the key
3297 * came from Pageant)
3299 * - if we'd just tried anything else, the
3300 * message really should be "Access denied".
3302 * Additionally, if we'd just tried password
3303 * authentication, we should break out of this
3304 * whole loop so as to go back to the username
3307 if (type
== AUTH_TYPE_NONE
) {
3309 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3310 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3311 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3312 c_write_str("Server refused our key\r\n");
3313 logevent("Server refused public key");
3315 c_write_str("Access denied\r\n");
3316 logevent("Access denied");
3317 if (type
== AUTH_TYPE_PASSWORD
) {
3323 c_write_str("Further authentication required\r\n");
3324 logevent("Further authentication required");
3328 in_commasep_string("publickey", methods
, methlen
);
3330 in_commasep_string("password", methods
, methlen
);
3335 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3337 * Attempt public-key authentication using Pageant.
3339 static unsigned char request
[5], *response
, *p
;
3340 static int responselen
;
3341 static int i
, nkeys
;
3342 static int authed
= FALSE
;
3347 logevent("Pageant is running. Requesting keys.");
3349 /* Request the keys held by the agent. */
3350 PUT_32BIT(request
, 1);
3351 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3352 agent_query(request
, 5, &r
, &responselen
);
3353 response
= (unsigned char *) r
;
3354 if (response
&& responselen
>= 5 &&
3355 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3357 nkeys
= GET_32BIT(p
);
3361 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3364 for (i
= 0; i
< nkeys
; i
++) {
3365 static char *pkblob
, *alg
, *commentp
;
3366 static int pklen
, alglen
, commentlen
;
3367 static int siglen
, retlen
, len
;
3368 static char *q
, *agentreq
, *ret
;
3372 sprintf(buf
, "Trying Pageant key #%d", i
);
3375 pklen
= GET_32BIT(p
);
3379 alglen
= GET_32BIT(pkblob
);
3381 commentlen
= GET_32BIT(p
);
3385 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3386 ssh2_pkt_addstring(username
);
3387 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3388 ssh2_pkt_addstring("publickey"); /* method */
3389 ssh2_pkt_addbool(FALSE
); /* no signature included */
3390 ssh2_pkt_addstring_start();
3391 ssh2_pkt_addstring_data(alg
, alglen
);
3392 ssh2_pkt_addstring_start();
3393 ssh2_pkt_addstring_data(pkblob
, pklen
);
3396 crWaitUntilV(ispkt
);
3397 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3398 logevent("Key refused");
3402 if (flags
& FLAG_VERBOSE
) {
3404 ("Authenticating with public key \"");
3405 c_write(commentp
, commentlen
);
3406 c_write_str("\" from agent\r\n");
3410 * Server is willing to accept the key.
3411 * Construct a SIGN_REQUEST.
3413 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3414 ssh2_pkt_addstring(username
);
3415 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3416 ssh2_pkt_addstring("publickey"); /* method */
3417 ssh2_pkt_addbool(TRUE
);
3418 ssh2_pkt_addstring_start();
3419 ssh2_pkt_addstring_data(alg
, alglen
);
3420 ssh2_pkt_addstring_start();
3421 ssh2_pkt_addstring_data(pkblob
, pklen
);
3423 siglen
= pktout
.length
- 5 + 4 + 20;
3424 len
= 1; /* message type */
3425 len
+= 4 + pklen
; /* key blob */
3426 len
+= 4 + siglen
; /* data to sign */
3427 len
+= 4; /* flags */
3428 agentreq
= smalloc(4 + len
);
3429 PUT_32BIT(agentreq
, len
);
3431 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3432 PUT_32BIT(q
, pklen
);
3434 memcpy(q
, pkblob
, pklen
);
3436 PUT_32BIT(q
, siglen
);
3438 /* Now the data to be signed... */
3441 memcpy(q
, ssh2_session_id
, 20);
3443 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
3444 q
+= pktout
.length
- 5;
3445 /* And finally the (zero) flags word. */
3447 agent_query(agentreq
, len
+ 4, &ret
, &retlen
);
3450 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3451 logevent("Sending Pageant's response");
3452 ssh2_pkt_addstring_start();
3453 ssh2_pkt_addstring_data(ret
+ 9,
3461 ("Pageant failed to answer challenge");
3471 if (!method
&& can_pubkey
&& *cfg
.keyfile
3472 && !tried_pubkey_config
) {
3473 unsigned char *pub_blob
;
3474 char *algorithm
, *comment
;
3477 tried_pubkey_config
= TRUE
;
3480 * Try the public key supplied in the configuration.
3482 * First, offer the public blob to see if the server is
3483 * willing to accept it.
3485 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3488 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3489 ssh2_pkt_addstring(username
);
3490 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3491 ssh2_pkt_addstring("publickey"); /* method */
3492 ssh2_pkt_addbool(FALSE
); /* no signature included */
3493 ssh2_pkt_addstring(algorithm
);
3494 ssh2_pkt_addstring_start();
3495 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3497 logevent("Offered public key"); /* FIXME */
3499 crWaitUntilV(ispkt
);
3500 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3502 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3503 continue; /* key refused; give up on it */
3506 logevent("Offer of public key accepted");
3508 * Actually attempt a serious authentication using
3511 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3513 "Passphrase for key \"%.100s\": ",
3519 c_write_str("Authenticating with public key \"");
3520 c_write_str(comment
);
3521 c_write_str("\"\r\n");
3522 method
= AUTH_PUBLICKEY_FILE
;
3526 if (!method
&& can_passwd
) {
3527 method
= AUTH_PASSWORD
;
3528 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
3535 if (!ssh_get_line(pwprompt
, password
,
3536 sizeof(password
), TRUE
)) {
3538 * get_line failed to get a password (for
3539 * example because one was supplied on the
3540 * command line which has already failed to
3543 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3544 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3546 ("No more passwords available to try");
3547 ssh2_pkt_addstring("en"); /* language tag */
3549 connection_fatal("Unable to authenticate");
3550 ssh_state
= SSH_STATE_CLOSED
;
3557 c_write_str(pwprompt
);
3562 crWaitUntilV(!ispkt
);
3564 switch (c
= *in
++) {
3585 if (((c
>= ' ' && c
<= '~') ||
3586 ((unsigned char) c
>= 160))
3588 password
[pos
++] = c
;
3592 c_write_str("\r\n");
3596 if (method
== AUTH_PUBLICKEY_FILE
) {
3598 * We have our passphrase. Now try the actual authentication.
3600 struct ssh2_userkey
*key
;
3602 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3603 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3604 if (key
== SSH2_WRONG_PASSPHRASE
) {
3605 c_write_str("Wrong passphrase\r\n");
3606 tried_pubkey_config
= FALSE
;
3608 c_write_str("Unable to load private key\r\n");
3609 tried_pubkey_config
= TRUE
;
3611 /* Send a spurious AUTH_NONE to return to the top. */
3612 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3613 ssh2_pkt_addstring(username
);
3614 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3615 ssh2_pkt_addstring("none"); /* method */
3617 type
= AUTH_TYPE_NONE
;
3619 unsigned char *blob
, *sigdata
;
3620 int blob_len
, sigdata_len
;
3623 * We have loaded the private key and the server
3624 * has announced that it's willing to accept it.
3625 * Hallelujah. Generate a signature and send it.
3627 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3628 ssh2_pkt_addstring(username
);
3629 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3630 ssh2_pkt_addstring("publickey"); /* method */
3631 ssh2_pkt_addbool(TRUE
);
3632 ssh2_pkt_addstring(key
->alg
->name
);
3633 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3634 ssh2_pkt_addstring_start();
3635 ssh2_pkt_addstring_data(blob
, blob_len
);
3639 * The data to be signed is:
3643 * followed by everything so far placed in the
3646 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3647 sigdata
= smalloc(sigdata_len
);
3648 PUT_32BIT(sigdata
, 20);
3649 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
3650 memcpy(sigdata
+ 24, pktout
.data
+ 5,
3653 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
3655 ssh2_pkt_addstring_start();
3656 ssh2_pkt_addstring_data(blob
, blob_len
);
3661 type
= AUTH_TYPE_PUBLICKEY
;
3663 } else if (method
== AUTH_PASSWORD
) {
3665 * We send the password packet lumped tightly together with
3666 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3667 * string long enough to make the total length of the two
3668 * packets constant. This should ensure that a passive
3669 * listener doing traffic analyis can't work out the length
3672 * For this to work, we need an assumption about the
3673 * maximum length of the password packet. I think 256 is
3674 * pretty conservative. Anyone using a password longer than
3675 * that probably doesn't have much to worry about from
3676 * people who find out how long their password is!
3678 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3679 ssh2_pkt_addstring(username
);
3680 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3681 ssh2_pkt_addstring("password");
3682 ssh2_pkt_addbool(FALSE
);
3683 ssh2_pkt_addstring(password
);
3686 * We'll include a string that's an exact multiple of the
3687 * cipher block size. If the cipher is NULL for some
3688 * reason, we don't do this trick at all because we gain
3694 stringlen
= (256 - deferred_len
);
3695 stringlen
+= cscipher
->blksize
- 1;
3696 stringlen
-= (stringlen
% cscipher
->blksize
);
3699 * Temporarily disable actual compression,
3700 * so we can guarantee to get this string
3701 * exactly the length we want it. The
3702 * compression-disabling routine should
3703 * return an integer indicating how many
3704 * bytes we should adjust our string length
3707 stringlen
-= cscomp
->disable_compression();
3709 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3710 ssh2_pkt_addstring_start();
3711 for (i
= 0; i
< stringlen
; i
++) {
3712 char c
= (char) random_byte();
3713 ssh2_pkt_addstring_data(&c
, 1);
3717 ssh_pkt_defersend();
3718 logevent("Sent password");
3719 type
= AUTH_TYPE_PASSWORD
;
3722 ("No supported authentication methods left to try!\r\n");
3724 ("No supported authentications offered. Disconnecting");
3725 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3726 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3728 ("No supported authentication methods available");
3729 ssh2_pkt_addstring("en"); /* language tag */
3731 ssh_state
= SSH_STATE_CLOSED
;
3735 } while (!we_are_in
);
3738 * Now we're authenticated for the connection protocol. The
3739 * connection protocol will automatically have started at this
3740 * point; there's no need to send SERVICE_REQUEST.
3744 * So now create a channel with a session in it.
3746 ssh_channels
= newtree234(ssh_channelcmp
);
3747 mainchan
= smalloc(sizeof(struct ssh_channel
));
3748 mainchan
->localid
= alloc_channel_id();
3749 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3750 ssh2_pkt_addstring("session");
3751 ssh2_pkt_adduint32(mainchan
->localid
);
3752 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3753 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3755 crWaitUntilV(ispkt
);
3756 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3757 bombout(("Server refused to open a session"));
3759 /* FIXME: error data comes back in FAILURE packet */
3761 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3762 bombout(("Server's channel confirmation cited wrong channel"));
3765 mainchan
->remoteid
= ssh2_pkt_getuint32();
3766 mainchan
->type
= CHAN_MAINSESSION
;
3767 mainchan
->closes
= 0;
3768 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3769 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3770 mainchan
->v2
.outbuffer
= NULL
;
3771 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3772 add234(ssh_channels
, mainchan
);
3773 logevent("Opened channel for session");
3776 * Potentially enable X11 forwarding.
3778 if (cfg
.x11_forward
) {
3779 char proto
[20], data
[64];
3780 logevent("Requesting X11 forwarding");
3781 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3782 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3783 ssh2_pkt_adduint32(mainchan
->remoteid
);
3784 ssh2_pkt_addstring("x11-req");
3785 ssh2_pkt_addbool(1); /* want reply */
3786 ssh2_pkt_addbool(0); /* many connections */
3787 ssh2_pkt_addstring(proto
);
3788 ssh2_pkt_addstring(data
);
3789 ssh2_pkt_adduint32(0); /* screen number */
3793 crWaitUntilV(ispkt
);
3794 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3795 unsigned i
= ssh2_pkt_getuint32();
3796 struct ssh_channel
*c
;
3797 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3799 continue; /* nonexistent channel */
3800 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3802 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3804 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3805 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3806 bombout(("Server got confused by X11 forwarding request"));
3809 logevent("X11 forwarding refused");
3811 logevent("X11 forwarding enabled");
3812 ssh_X11_fwd_enabled
= TRUE
;
3817 * Potentially enable agent forwarding.
3819 if (cfg
.agentfwd
&& agent_exists()) {
3820 logevent("Requesting OpenSSH-style agent forwarding");
3821 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3822 ssh2_pkt_adduint32(mainchan
->remoteid
);
3823 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3824 ssh2_pkt_addbool(1); /* want reply */
3828 crWaitUntilV(ispkt
);
3829 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3830 unsigned i
= ssh2_pkt_getuint32();
3831 struct ssh_channel
*c
;
3832 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3834 continue; /* nonexistent channel */
3835 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3837 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3839 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3840 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3842 ("Server got confused by agent forwarding request"));
3845 logevent("Agent forwarding refused");
3847 logevent("Agent forwarding enabled");
3848 ssh_agentfwd_enabled
= TRUE
;
3853 * Now allocate a pty for the session.
3856 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3857 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3858 ssh2_pkt_addstring("pty-req");
3859 ssh2_pkt_addbool(1); /* want reply */
3860 ssh2_pkt_addstring(cfg
.termtype
);
3861 ssh2_pkt_adduint32(cols
);
3862 ssh2_pkt_adduint32(rows
);
3863 ssh2_pkt_adduint32(0); /* pixel width */
3864 ssh2_pkt_adduint32(0); /* pixel height */
3865 ssh2_pkt_addstring_start();
3866 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
3868 ssh_state
= SSH_STATE_INTERMED
;
3871 crWaitUntilV(ispkt
);
3872 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3873 unsigned i
= ssh2_pkt_getuint32();
3874 struct ssh_channel
*c
;
3875 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3877 continue; /* nonexistent channel */
3878 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3880 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3882 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3883 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3884 bombout(("Server got confused by pty request"));
3887 c_write_str("Server refused to allocate pty\r\n");
3888 ssh_editing
= ssh_echoing
= 1;
3890 logevent("Allocated pty");
3893 ssh_editing
= ssh_echoing
= 1;
3897 * Start a shell or a remote command.
3899 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3900 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3901 if (cfg
.ssh_subsys
) {
3902 ssh2_pkt_addstring("subsystem");
3903 ssh2_pkt_addbool(1); /* want reply */
3904 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3905 } else if (*cfg
.remote_cmd_ptr
) {
3906 ssh2_pkt_addstring("exec");
3907 ssh2_pkt_addbool(1); /* want reply */
3908 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3910 ssh2_pkt_addstring("shell");
3911 ssh2_pkt_addbool(1); /* want reply */
3915 crWaitUntilV(ispkt
);
3916 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3917 unsigned i
= ssh2_pkt_getuint32();
3918 struct ssh_channel
*c
;
3919 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3921 continue; /* nonexistent channel */
3922 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3924 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3925 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3926 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3927 bombout(("Server got confused by shell/command request"));
3930 bombout(("Server refused to start a shell/command"));
3933 logevent("Started a shell/command");
3936 ssh_state
= SSH_STATE_SESSION
;
3940 ssh_special(TS_EOF
);
3945 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3948 static int try_send
;
3952 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3953 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3956 unsigned i
= ssh2_pkt_getuint32();
3957 struct ssh_channel
*c
;
3958 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3960 continue; /* nonexistent channel */
3961 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3962 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3963 continue; /* extended but not stderr */
3964 ssh2_pkt_getstring(&data
, &length
);
3967 case CHAN_MAINSESSION
:
3968 from_backend(pktin
.type
==
3969 SSH2_MSG_CHANNEL_EXTENDED_DATA
, data
,
3973 x11_send(c
->u
.x11
.s
, data
, length
);
3976 while (length
> 0) {
3977 if (c
->u
.a
.lensofar
< 4) {
3978 int l
= min(4 - c
->u
.a
.lensofar
, length
);
3979 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
3983 c
->u
.a
.lensofar
+= l
;
3985 if (c
->u
.a
.lensofar
== 4) {
3987 4 + GET_32BIT(c
->u
.a
.msglen
);
3988 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3989 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3991 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
3993 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3995 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
3999 c
->u
.a
.lensofar
+= l
;
4001 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4002 void *reply
, *sentreply
;
4004 agent_query(c
->u
.a
.message
,
4005 c
->u
.a
.totallen
, &reply
,
4010 /* Fake SSH_AGENT_FAILURE. */
4011 sentreply
= "\0\0\0\1\5";
4014 ssh2_add_channel_data(c
, sentreply
,
4019 sfree(c
->u
.a
.message
);
4020 c
->u
.a
.lensofar
= 0;
4026 * Enlarge the window again at the remote
4027 * side, just in case it ever runs down and
4028 * they fail to send us any more data.
4030 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4031 ssh2_pkt_adduint32(c
->remoteid
);
4032 ssh2_pkt_adduint32(length
);
4035 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4036 ssh_state
= SSH_STATE_CLOSED
;
4037 logevent("Received disconnect message");
4039 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4040 continue; /* exit status et al; ignore (FIXME?) */
4041 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4042 unsigned i
= ssh2_pkt_getuint32();
4043 struct ssh_channel
*c
;
4045 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4047 continue; /* nonexistent channel */
4049 if (c
->type
== CHAN_X11
) {
4051 * Remote EOF on an X11 channel means we should
4052 * wrap up and close the channel ourselves.
4054 x11_close(c
->u
.x11
.s
);
4056 } else if (c
->type
== CHAN_AGENT
) {
4059 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4060 unsigned i
= ssh2_pkt_getuint32();
4061 struct ssh_channel
*c
;
4063 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4065 continue; /* nonexistent channel */
4066 if (c
->closes
== 0) {
4067 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4068 ssh2_pkt_adduint32(c
->remoteid
);
4071 /* Do pre-close processing on the channel. */
4073 case CHAN_MAINSESSION
:
4074 break; /* nothing to see here, move along */
4080 del234(ssh_channels
, c
);
4081 sfree(c
->v2
.outbuffer
);
4085 * See if that was the last channel left open.
4087 if (count234(ssh_channels
) == 0) {
4088 logevent("All channels closed. Disconnecting");
4089 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4090 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4091 ssh2_pkt_addstring("All open channels closed");
4092 ssh2_pkt_addstring("en"); /* language tag */
4094 ssh_state
= SSH_STATE_CLOSED
;
4097 continue; /* remote sends close; ignore (FIXME) */
4098 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4099 unsigned i
= ssh2_pkt_getuint32();
4100 struct ssh_channel
*c
;
4101 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4103 continue; /* nonexistent channel */
4104 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4106 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4110 struct ssh_channel
*c
;
4111 ssh2_pkt_getstring(&type
, &typelen
);
4112 c
= smalloc(sizeof(struct ssh_channel
));
4114 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4115 if (!ssh_X11_fwd_enabled
)
4116 error
= "X11 forwarding is not enabled";
4117 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4119 error
= "Unable to open an X11 connection";
4123 } else if (typelen
== 22 &&
4124 !memcmp(type
, "auth-agent@openssh.com", 3)) {
4125 if (!ssh_agentfwd_enabled
)
4126 error
= "Agent forwarding is not enabled";
4128 c
->type
= CHAN_AGENT
; /* identify channel type */
4129 c
->u
.a
.lensofar
= 0;
4132 error
= "Unsupported channel type requested";
4135 c
->remoteid
= ssh2_pkt_getuint32();
4137 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
4138 ssh2_pkt_adduint32(c
->remoteid
);
4139 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
4140 ssh2_pkt_addstring(error
);
4141 ssh2_pkt_addstring("en"); /* language tag */
4145 c
->localid
= alloc_channel_id();
4147 c
->v2
.remwindow
= ssh2_pkt_getuint32();
4148 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
4149 c
->v2
.outbuffer
= NULL
;
4150 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
4151 add234(ssh_channels
, c
);
4152 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
4153 ssh2_pkt_adduint32(c
->remoteid
);
4154 ssh2_pkt_adduint32(c
->localid
);
4155 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
4156 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4160 bombout(("Strange packet received: type %d", pktin
.type
));
4165 * We have spare data. Add it to the channel buffer.
4167 ssh2_add_channel_data(mainchan
, in
, inlen
);
4172 struct ssh_channel
*c
;
4174 * Try to send data on all channels if we can.
4176 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++)
4185 * Handle the top-level SSH2 protocol.
4187 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
4189 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
4191 do_ssh2_authconn(in
, inlen
, ispkt
);
4195 * Called to set up the connection.
4197 * Returns an error message, or NULL on success.
4199 static char *ssh_init(char *host
, int port
, char **realhost
)
4204 if (crypto_startup() == 0)
4205 return "Microsoft high encryption pack not installed!";
4212 p
= connect_to_host(host
, port
, realhost
);
4220 * Called to send data down the Telnet connection.
4222 static void ssh_send(char *buf
, int len
)
4224 if (s
== NULL
|| ssh_protocol
== NULL
)
4227 ssh_protocol(buf
, len
, 0);
4231 * Called to set the size of the window from SSH's POV.
4233 static void ssh_size(void)
4235 switch (ssh_state
) {
4236 case SSH_STATE_BEFORE_SIZE
:
4237 case SSH_STATE_PREPACKET
:
4238 case SSH_STATE_CLOSED
:
4239 break; /* do nothing */
4240 case SSH_STATE_INTERMED
:
4241 size_needed
= TRUE
; /* buffer for later */
4243 case SSH_STATE_SESSION
:
4245 if (ssh_version
== 1) {
4246 send_packet(SSH1_CMSG_WINDOW_SIZE
,
4247 PKT_INT
, rows
, PKT_INT
, cols
,
4248 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
4250 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4251 ssh2_pkt_adduint32(mainchan
->remoteid
);
4252 ssh2_pkt_addstring("window-change");
4253 ssh2_pkt_addbool(0);
4254 ssh2_pkt_adduint32(cols
);
4255 ssh2_pkt_adduint32(rows
);
4256 ssh2_pkt_adduint32(0);
4257 ssh2_pkt_adduint32(0);
4266 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4267 * can send an EOF and collect resulting output (e.g. `plink
4270 static void ssh_special(Telnet_Special code
)
4272 if (code
== TS_EOF
) {
4273 if (ssh_state
!= SSH_STATE_SESSION
) {
4275 * Buffer the EOF in case we are pre-SESSION, so we can
4276 * send it as soon as we reach SESSION.
4282 if (ssh_version
== 1) {
4283 send_packet(SSH1_CMSG_EOF
, PKT_END
);
4285 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4286 ssh2_pkt_adduint32(mainchan
->remoteid
);
4289 logevent("Sent EOF message");
4290 } else if (code
== TS_PING
) {
4291 if (ssh_state
== SSH_STATE_CLOSED
4292 || ssh_state
== SSH_STATE_PREPACKET
) return;
4293 if (ssh_version
== 1) {
4294 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
4296 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4297 ssh2_pkt_addstring_start();
4305 static Socket
ssh_socket(void)
4310 static int ssh_sendok(void)
4315 static int ssh_ldisc(int option
)
4317 if (option
== LD_ECHO
)
4319 if (option
== LD_EDIT
)
4324 Backend ssh_backend
= {