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
,
213 &ssh_diffiehellman
};
215 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
217 static void nullmac_key(unsigned char *key
) { }
218 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
219 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
220 const static struct ssh_mac ssh_mac_none
= {
221 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
223 const static struct ssh_mac
*macs
[] = {
224 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
};
225 const static struct ssh_mac
*buggymacs
[] = {
226 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
};
228 static void ssh_comp_none_init(void) { }
229 static int ssh_comp_none_block(unsigned char *block
, int len
,
230 unsigned char **outblock
, int *outlen
) {
233 static int ssh_comp_none_disable(void) { return 0; }
234 const static struct ssh_compress ssh_comp_none
= {
236 ssh_comp_none_init
, ssh_comp_none_block
,
237 ssh_comp_none_init
, ssh_comp_none_block
,
238 ssh_comp_none_disable
240 extern const struct ssh_compress ssh_zlib
;
241 const static struct ssh_compress
*compressions
[] = {
242 &ssh_zlib
, &ssh_comp_none
};
244 enum { /* channel types */
251 * 2-3-4 tree storing channels.
254 unsigned remoteid
, localid
;
257 struct ssh2_data_channel
{
258 unsigned char *outbuffer
;
259 unsigned outbuflen
, outbufsize
;
260 unsigned remwindow
, remmaxpkt
;
263 struct ssh_agent_channel
{
264 unsigned char *message
;
265 unsigned char msglen
[4];
266 int lensofar
, totallen
;
268 struct ssh_x11_channel
{
283 static SHA_State exhash
, exhashbase
;
285 static Socket s
= NULL
;
287 static unsigned char session_key
[32];
288 static int ssh1_compressing
;
289 static int ssh1_remote_protoflags
;
290 static int ssh1_local_protoflags
;
291 static int ssh_agentfwd_enabled
;
292 static int ssh_X11_fwd_enabled
;
293 static int ssh_remote_bugs
;
294 static const struct ssh_cipher
*cipher
= NULL
;
295 static const struct ssh2_cipher
*cscipher
= NULL
;
296 static const struct ssh2_cipher
*sccipher
= NULL
;
297 static const struct ssh_mac
*csmac
= NULL
;
298 static const struct ssh_mac
*scmac
= NULL
;
299 static const struct ssh_compress
*cscomp
= NULL
;
300 static const struct ssh_compress
*sccomp
= NULL
;
301 static const struct ssh_kex
*kex
= NULL
;
302 static const struct ssh_signkey
*hostkey
= NULL
;
303 static unsigned char ssh2_session_id
[20];
304 int (*ssh_get_line
)(const char *prompt
, char *str
, int maxlen
,
307 static char *savedhost
;
308 static int savedport
;
309 static int ssh_send_ok
;
310 static int ssh_echoing
, ssh_editing
;
312 static tree234
*ssh_channels
; /* indexed by local id */
313 static struct ssh_channel
*mainchan
; /* primary session channel */
317 SSH_STATE_BEFORE_SIZE
,
321 } ssh_state
= SSH_STATE_PREPACKET
;
323 static int size_needed
= FALSE
, eof_needed
= FALSE
;
325 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
326 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
327 static unsigned char *deferred_send_data
= NULL
;
328 static int deferred_len
= 0, deferred_size
= 0;
330 static int ssh_version
;
331 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
332 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
333 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
334 static void ssh_size(void);
335 static void ssh_special (Telnet_Special
);
336 static void ssh2_try_send(struct ssh_channel
*c
);
337 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
339 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
341 static struct rdpkt1_state_tag
{
342 long len
, pad
, biglen
, to_read
;
343 unsigned long realcrc
, gotcrc
;
349 static struct rdpkt2_state_tag
{
350 long len
, pad
, payload
, packetlen
, maclen
;
353 unsigned long incoming_sequence
;
356 static int ssh_channelcmp(void *av
, void *bv
) {
357 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
358 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
359 if (a
->localid
< b
->localid
) return -1;
360 if (a
->localid
> b
->localid
) return +1;
363 static int ssh_channelfind(void *av
, void *bv
) {
364 unsigned *a
= (unsigned *)av
;
365 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
366 if (*a
< b
->localid
) return -1;
367 if (*a
> b
->localid
) return +1;
371 static int alloc_channel_id(void) {
372 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
373 unsigned low
, high
, mid
;
375 struct ssh_channel
*c
;
378 * First-fit allocation of channel numbers: always pick the
379 * lowest unused one. To do this, binary-search using the
380 * counted B-tree to find the largest channel ID which is in a
381 * contiguous sequence from the beginning. (Precisely
382 * everything in that sequence must have ID equal to its tree
383 * index plus CHANNEL_NUMBER_OFFSET.)
385 tsize
= count234(ssh_channels
);
387 low
= -1; high
= tsize
;
388 while (high
- low
> 1) {
389 mid
= (high
+ low
) / 2;
390 c
= index234(ssh_channels
, mid
);
391 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
392 low
= mid
; /* this one is fine */
394 high
= mid
; /* this one is past it */
397 * Now low points to either -1, or the tree index of the
398 * largest ID in the initial sequence.
401 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
402 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
404 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
407 static void c_write (char *buf
, int len
) {
408 if ((flags
& FLAG_STDERR
)) {
410 for (i
= 0; i
< len
; i
++)
412 fputc(buf
[i
], stderr
);
415 from_backend(1, buf
, len
);
418 static void c_write_untrusted(char *buf
, int len
) {
420 for (i
= 0; i
< len
; i
++) {
423 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
428 static void c_write_str (char *buf
) {
429 c_write(buf
, strlen(buf
));
433 * Collect incoming data in the incoming packet buffer.
434 * Decipher and verify the packet when it is completely read.
435 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
436 * Update the *data and *datalen variables.
437 * Return the additional nr of bytes needed, or 0 when
438 * a complete packet is available.
440 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
442 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
451 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
452 while ((*datalen
) == 0)
454 st
->len
= (st
->len
<< 8) + **data
;
455 (*data
)++, (*datalen
)--;
459 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
460 st
->len
= 0x300; /* big enough to carry to end */
464 st
->pad
= 8 - (st
->len
% 8);
465 st
->biglen
= st
->len
+ st
->pad
;
466 pktin
.length
= st
->len
- 5;
468 if (pktin
.maxlen
< st
->biglen
) {
469 pktin
.maxlen
= st
->biglen
;
470 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+APIEXTRA
) :
471 srealloc(pktin
.data
, st
->biglen
+APIEXTRA
));
473 fatalbox("Out of memory");
476 st
->to_read
= st
->biglen
;
478 while (st
->to_read
> 0) {
479 st
->chunk
= st
->to_read
;
480 while ((*datalen
) == 0)
481 crReturn(st
->to_read
);
482 if (st
->chunk
> (*datalen
))
483 st
->chunk
= (*datalen
);
484 memcpy(st
->p
, *data
, st
->chunk
);
486 *datalen
-= st
->chunk
;
488 st
->to_read
-= st
->chunk
;
492 cipher
->decrypt(pktin
.data
, st
->biglen
);
494 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
495 dmemdump(pktin
.data
, st
->biglen
);
498 st
->realcrc
= crc32(pktin
.data
, st
->biglen
-4);
499 st
->gotcrc
= GET_32BIT(pktin
.data
+st
->biglen
-4);
500 if (st
->gotcrc
!= st
->realcrc
) {
501 bombout(("Incorrect CRC received on packet"));
505 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
507 if (ssh1_compressing
) {
508 unsigned char *decompblk
;
511 debug(("Packet payload pre-decompression:\n"));
512 dmemdump(pktin
.body
-1, pktin
.length
+1);
514 zlib_decompress_block(pktin
.body
-1, pktin
.length
+1,
515 &decompblk
, &decomplen
);
517 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
518 pktin
.maxlen
= st
->pad
+ decomplen
;
519 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
);
520 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
522 fatalbox("Out of memory");
525 memcpy(pktin
.body
-1, decompblk
, decomplen
);
527 pktin
.length
= decomplen
-1;
529 debug(("Packet payload post-decompression:\n"));
530 dmemdump(pktin
.body
-1, pktin
.length
+1);
534 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
535 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
536 pktin
.type
== SSH1_MSG_DEBUG
||
537 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
538 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
539 long strlen
= GET_32BIT(pktin
.body
);
540 if (strlen
+ 4 != pktin
.length
) {
541 bombout(("Received data packet with bogus string length"));
546 pktin
.type
= pktin
.body
[-1];
548 if (pktin
.type
== SSH1_MSG_DEBUG
) {
549 /* log debug message */
551 int strlen
= GET_32BIT(pktin
.body
);
552 strcpy(buf
, "Remote: ");
553 if (strlen
> 70) strlen
= 70;
554 memcpy(buf
+8, pktin
.body
+4, strlen
);
555 buf
[8+strlen
] = '\0';
558 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
563 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
564 /* log reason code in disconnect message */
566 unsigned msglen
= GET_32BIT(pktin
.body
);
568 strcpy(buf
, "Remote sent disconnect: ");
569 nowlen
= strlen(buf
);
570 if (msglen
> sizeof(buf
)-nowlen
-1)
571 msglen
= sizeof(buf
)-nowlen
-1;
572 memcpy(buf
+nowlen
, pktin
.body
+4, msglen
);
573 buf
[nowlen
+msglen
] = '\0';
580 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
582 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
590 st
->cipherblk
= sccipher
->blksize
;
593 if (st
->cipherblk
< 8)
596 if (pktin
.maxlen
< st
->cipherblk
) {
597 pktin
.maxlen
= st
->cipherblk
;
598 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->cipherblk
+APIEXTRA
) :
599 srealloc(pktin
.data
, st
->cipherblk
+APIEXTRA
));
601 fatalbox("Out of memory");
605 * Acquire and decrypt the first block of the packet. This will
606 * contain the length and padding details.
608 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
609 while ((*datalen
) == 0)
610 crReturn(st
->cipherblk
-st
->i
);
611 pktin
.data
[st
->i
] = *(*data
)++;
615 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
620 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
623 * Now get the length and padding figures.
625 st
->len
= GET_32BIT(pktin
.data
);
626 st
->pad
= pktin
.data
[4];
629 * This enables us to deduce the payload length.
631 st
->payload
= st
->len
- st
->pad
- 1;
633 pktin
.length
= st
->payload
+ 5;
636 * So now we can work out the total packet length.
638 st
->packetlen
= st
->len
+ 4;
639 st
->maclen
= scmac ? scmac
->len
: 0;
642 * Adjust memory allocation if packet is too big.
644 if (pktin
.maxlen
< st
->packetlen
+st
->maclen
) {
645 pktin
.maxlen
= st
->packetlen
+st
->maclen
;
646 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
647 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
649 fatalbox("Out of memory");
653 * Read and decrypt the remainder of the packet.
655 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
; st
->i
++) {
656 while ((*datalen
) == 0)
657 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
658 pktin
.data
[st
->i
] = *(*data
)++;
661 /* Decrypt everything _except_ the MAC. */
663 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
664 st
->packetlen
- st
->cipherblk
);
667 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
668 dmemdump(pktin
.data
, st
->packetlen
);
674 if (scmac
&& !scmac
->verify(pktin
.data
, st
->len
+4, st
->incoming_sequence
)) {
675 bombout(("Incorrect MAC received on packet"));
678 st
->incoming_sequence
++; /* whether or not we MACed */
681 * Decompress packet payload.
684 unsigned char *newpayload
;
686 if (sccomp
&& sccomp
->decompress(pktin
.data
+5, pktin
.length
-5,
687 &newpayload
, &newlen
)) {
688 if (pktin
.maxlen
< newlen
+5) {
689 pktin
.maxlen
= newlen
+5;
690 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
691 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
693 fatalbox("Out of memory");
695 pktin
.length
= 5 + newlen
;
696 memcpy(pktin
.data
+5, newpayload
, newlen
);
698 debug(("Post-decompression payload:\n"));
699 dmemdump(pktin
.data
+5, newlen
);
707 pktin
.type
= pktin
.data
[5];
709 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
710 goto next_packet
; /* FIXME: print DEBUG message */
712 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
713 /* log reason code in disconnect message */
715 int reason
= GET_32BIT(pktin
.data
+6);
716 unsigned msglen
= GET_32BIT(pktin
.data
+10);
718 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
719 sprintf(buf
, "Received disconnect message (%s)",
720 ssh2_disconnect_reasons
[reason
]);
722 sprintf(buf
, "Received disconnect message (unknown type %d)", reason
);
725 strcpy(buf
, "Disconnection message text: ");
726 nowlen
= strlen(buf
);
727 if (msglen
> sizeof(buf
)-nowlen
-1)
728 msglen
= sizeof(buf
)-nowlen
-1;
729 memcpy(buf
+nowlen
, pktin
.data
+14, msglen
);
730 buf
[nowlen
+msglen
] = '\0';
737 static void ssh1_pktout_size(int len
) {
740 len
+= 5; /* type and CRC */
744 pktout
.length
= len
-5;
745 if (pktout
.maxlen
< biglen
) {
746 pktout
.maxlen
= biglen
;
748 /* Allocate enough buffer space for extra block
749 * for MS CryptEncrypt() */
750 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+12) :
751 srealloc(pktout
.data
, biglen
+12));
753 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+4) :
754 srealloc(pktout
.data
, biglen
+4));
757 fatalbox("Out of memory");
759 pktout
.body
= pktout
.data
+4+pad
+1;
762 static void s_wrpkt_start(int type
, int len
) {
763 ssh1_pktout_size(len
);
767 static int s_wrpkt_prepare(void) {
768 int pad
, len
, biglen
, i
;
771 pktout
.body
[-1] = pktout
.type
;
774 debug(("Packet payload pre-compression:\n"));
775 dmemdump(pktout
.body
-1, pktout
.length
+1);
778 if (ssh1_compressing
) {
779 unsigned char *compblk
;
781 zlib_compress_block(pktout
.body
-1, pktout
.length
+1,
783 ssh1_pktout_size(complen
-1);
784 memcpy(pktout
.body
-1, compblk
, complen
);
787 debug(("Packet payload post-compression:\n"));
788 dmemdump(pktout
.body
-1, pktout
.length
+1);
792 len
= pktout
.length
+ 5; /* type and CRC */
796 for (i
=0; i
<pad
; i
++)
797 pktout
.data
[i
+4] = random_byte();
798 crc
= crc32(pktout
.data
+4, biglen
-4);
799 PUT_32BIT(pktout
.data
+biglen
, crc
);
800 PUT_32BIT(pktout
.data
, len
);
803 debug(("Sending packet len=%d\n", biglen
+4));
804 dmemdump(pktout
.data
, biglen
+4);
807 cipher
->encrypt(pktout
.data
+4, biglen
);
812 static void s_wrpkt(void) {
814 len
= s_wrpkt_prepare();
815 sk_write(s
, pktout
.data
, len
);
818 static void s_wrpkt_defer(void) {
820 len
= s_wrpkt_prepare();
821 if (deferred_len
+ len
> deferred_size
) {
822 deferred_size
= deferred_len
+ len
+ 128;
823 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
825 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
830 * Construct a packet with the specified contents.
832 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
834 unsigned char *p
, *argp
, argchar
;
835 unsigned long argint
;
836 int pktlen
, argtype
, arglen
;
840 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
843 (void) va_arg(ap1
, int);
847 (void) va_arg(ap1
, char);
851 (void) va_arg(ap1
, unsigned char *);
852 arglen
= va_arg(ap1
, int);
856 argp
= va_arg(ap1
, unsigned char *);
857 arglen
= strlen(argp
);
858 pktlen
+= 4 + arglen
;
861 bn
= va_arg(ap1
, Bignum
);
862 pktlen
+= ssh1_bignum_length(bn
);
869 s_wrpkt_start(pkttype
, pktlen
);
872 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
875 argint
= va_arg(ap2
, int);
876 PUT_32BIT(p
, argint
);
880 argchar
= va_arg(ap2
, unsigned char);
885 argp
= va_arg(ap2
, unsigned char *);
886 arglen
= va_arg(ap2
, int);
887 memcpy(p
, argp
, arglen
);
891 argp
= va_arg(ap2
, unsigned char *);
892 arglen
= strlen(argp
);
893 PUT_32BIT(p
, arglen
);
894 memcpy(p
+ 4, argp
, arglen
);
898 bn
= va_arg(ap2
, Bignum
);
899 p
+= ssh1_write_bignum(p
, bn
);
905 static void send_packet(int pkttype
, ...) {
907 va_start(ap1
, pkttype
);
908 va_start(ap2
, pkttype
);
909 construct_packet(pkttype
, ap1
, ap2
);
913 static void defer_packet(int pkttype
, ...) {
915 va_start(ap1
, pkttype
);
916 va_start(ap2
, pkttype
);
917 construct_packet(pkttype
, ap1
, ap2
);
921 static int ssh_versioncmp(char *a
, char *b
) {
923 unsigned long av
, bv
;
925 av
= strtoul(a
, &ae
, 10);
926 bv
= strtoul(b
, &be
, 10);
927 if (av
!= bv
) return (av
< bv ?
-1 : +1);
928 if (*ae
== '.') ae
++;
929 if (*be
== '.') be
++;
930 av
= strtoul(ae
, &ae
, 10);
931 bv
= strtoul(be
, &be
, 10);
932 if (av
!= bv
) return (av
< bv ?
-1 : +1);
938 * Utility routines for putting an SSH-protocol `string' and
939 * `uint32' into a SHA state.
942 static void sha_string(SHA_State
*s
, void *str
, int len
) {
943 unsigned char lenblk
[4];
944 PUT_32BIT(lenblk
, len
);
945 SHA_Bytes(s
, lenblk
, 4);
946 SHA_Bytes(s
, str
, len
);
949 static void sha_uint32(SHA_State
*s
, unsigned i
) {
950 unsigned char intblk
[4];
951 PUT_32BIT(intblk
, i
);
952 SHA_Bytes(s
, intblk
, 4);
956 * SSH2 packet construction functions.
958 static void ssh2_pkt_ensure(int length
) {
959 if (pktout
.maxlen
< length
) {
960 pktout
.maxlen
= length
+ 256;
961 pktout
.data
= (pktout
.data
== NULL ?
smalloc(pktout
.maxlen
+APIEXTRA
) :
962 srealloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
964 fatalbox("Out of memory");
967 static void ssh2_pkt_adddata(void *data
, int len
) {
968 pktout
.length
+= len
;
969 ssh2_pkt_ensure(pktout
.length
);
970 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
972 static void ssh2_pkt_addbyte(unsigned char byte
) {
973 ssh2_pkt_adddata(&byte
, 1);
975 static void ssh2_pkt_init(int pkt_type
) {
977 ssh2_pkt_addbyte((unsigned char)pkt_type
);
979 static void ssh2_pkt_addbool(unsigned char value
) {
980 ssh2_pkt_adddata(&value
, 1);
982 static void ssh2_pkt_adduint32(unsigned long value
) {
985 ssh2_pkt_adddata(x
, 4);
987 static void ssh2_pkt_addstring_start(void) {
988 ssh2_pkt_adduint32(0);
989 pktout
.savedpos
= pktout
.length
;
991 static void ssh2_pkt_addstring_str(char *data
) {
992 ssh2_pkt_adddata(data
, strlen(data
));
993 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
994 pktout
.length
- pktout
.savedpos
);
996 static void ssh2_pkt_addstring_data(char *data
, int len
) {
997 ssh2_pkt_adddata(data
, len
);
998 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
999 pktout
.length
- pktout
.savedpos
);
1001 static void ssh2_pkt_addstring(char *data
) {
1002 ssh2_pkt_addstring_start();
1003 ssh2_pkt_addstring_str(data
);
1005 static char *ssh2_mpint_fmt(Bignum b
, int *len
) {
1007 int i
, n
= (bignum_bitcount(b
)+7)/8;
1010 fatalbox("out of memory");
1012 for (i
= 1; i
<= n
; i
++)
1013 p
[i
] = bignum_byte(b
, n
-i
);
1015 while (i
<= n
&& p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
1017 memmove(p
, p
+i
, n
+1-i
);
1021 static void ssh2_pkt_addmp(Bignum b
) {
1024 p
= ssh2_mpint_fmt(b
, &len
);
1025 ssh2_pkt_addstring_start();
1026 ssh2_pkt_addstring_data(p
, len
);
1031 * Construct an SSH2 final-form packet: compress it, encrypt it,
1032 * put the MAC on it. Final packet, ready to be sent, is stored in
1033 * pktout.data. Total length is returned.
1035 static int ssh2_pkt_construct(void) {
1036 int cipherblk
, maclen
, padding
, i
;
1037 static unsigned long outgoing_sequence
= 0;
1040 * Compress packet payload.
1043 debug(("Pre-compression payload:\n"));
1044 dmemdump(pktout
.data
+5, pktout
.length
-5);
1047 unsigned char *newpayload
;
1049 if (cscomp
&& cscomp
->compress(pktout
.data
+5, pktout
.length
-5,
1050 &newpayload
, &newlen
)) {
1052 ssh2_pkt_adddata(newpayload
, newlen
);
1058 * Add padding. At least four bytes, and must also bring total
1059 * length (minus MAC) up to a multiple of the block size.
1061 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1062 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1064 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1065 maclen
= csmac ? csmac
->len
: 0;
1066 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1067 pktout
.data
[4] = padding
;
1068 for (i
= 0; i
< padding
; i
++)
1069 pktout
.data
[pktout
.length
+ i
] = random_byte();
1070 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1072 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1074 outgoing_sequence
++; /* whether or not we MACed */
1077 debug(("Sending packet len=%d\n", pktout
.length
+padding
));
1078 dmemdump(pktout
.data
, pktout
.length
+padding
);
1082 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1084 /* Ready-to-send packet starts at pktout.data. We return length. */
1085 return pktout
.length
+ padding
+ maclen
;
1089 * Construct and send an SSH2 packet immediately.
1091 static void ssh2_pkt_send(void) {
1092 int len
= ssh2_pkt_construct();
1093 sk_write(s
, pktout
.data
, len
);
1097 * Construct an SSH2 packet and add it to a deferred data block.
1098 * Useful for sending multiple packets in a single sk_write() call,
1099 * to prevent a traffic-analysing listener from being able to work
1100 * out the length of any particular packet (such as the password
1103 * Note that because SSH2 sequence-numbers its packets, this can
1104 * NOT be used as an m4-style `defer' allowing packets to be
1105 * constructed in one order and sent in another.
1107 static void ssh2_pkt_defer(void) {
1108 int len
= ssh2_pkt_construct();
1109 if (deferred_len
+ len
> deferred_size
) {
1110 deferred_size
= deferred_len
+ len
+ 128;
1111 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1113 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
1114 deferred_len
+= len
;
1118 * Send the whole deferred data block constructed by
1119 * ssh2_pkt_defer() or SSH1's defer_packet().
1121 static void ssh_pkt_defersend(void) {
1122 sk_write(s
, deferred_send_data
, deferred_len
);
1123 deferred_len
= deferred_size
= 0;
1124 sfree(deferred_send_data
);
1125 deferred_send_data
= NULL
;
1129 void bndebug(char *string
, Bignum b
) {
1132 p
= ssh2_mpint_fmt(b
, &len
);
1133 debug(("%s", string
));
1134 for (i
= 0; i
< len
; i
++)
1135 debug((" %02x", p
[i
]));
1141 static void sha_mpint(SHA_State
*s
, Bignum b
) {
1144 p
= ssh2_mpint_fmt(b
, &len
);
1145 sha_string(s
, p
, len
);
1150 * SSH2 packet decode functions.
1152 static unsigned long ssh2_pkt_getuint32(void) {
1153 unsigned long value
;
1154 if (pktin
.length
- pktin
.savedpos
< 4)
1155 return 0; /* arrgh, no way to decline (FIXME?) */
1156 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1157 pktin
.savedpos
+= 4;
1160 static int ssh2_pkt_getbool(void) {
1161 unsigned long value
;
1162 if (pktin
.length
- pktin
.savedpos
< 1)
1163 return 0; /* arrgh, no way to decline (FIXME?) */
1164 value
= pktin
.data
[pktin
.savedpos
] != 0;
1168 static void ssh2_pkt_getstring(char **p
, int *length
) {
1170 if (pktin
.length
- pktin
.savedpos
< 4)
1172 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1173 pktin
.savedpos
+= 4;
1174 if (pktin
.length
- pktin
.savedpos
< *length
)
1176 *p
= pktin
.data
+pktin
.savedpos
;
1177 pktin
.savedpos
+= *length
;
1179 static Bignum
ssh2_pkt_getmp(void) {
1184 ssh2_pkt_getstring(&p
, &length
);
1188 bombout(("internal error: Can't handle negative mpints"));
1191 b
= bignum_from_bytes(p
, length
);
1196 * Examine the remote side's version string and compare it against
1197 * a list of known buggy implementations.
1199 static void ssh_detect_bugs(char *vstring
) {
1200 char *imp
; /* pointer to implementation part */
1202 imp
+= strcspn(imp
, "-");
1204 imp
+= strcspn(imp
, "-");
1207 ssh_remote_bugs
= 0;
1209 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1210 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1211 !strcmp(imp
, "1.2.22")) {
1213 * These versions don't support SSH1_MSG_IGNORE, so we have
1214 * to use a different defence against password length
1217 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1218 logevent("We believe remote version has SSH1 ignore bug");
1221 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1222 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1223 !strncmp(imp
, "2.1 ", 4)) {
1225 * These versions have the HMAC bug.
1227 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1228 logevent("We believe remote version has SSH2 HMAC bug");
1232 static int do_ssh_init(unsigned char c
) {
1234 static char version
[10];
1235 static char *vstring
;
1236 static int vstrsize
;
1242 /* Search for the string "SSH-" in the input. */
1245 static const int transS
[] = { 1, 2, 2, 1 };
1246 static const int transH
[] = { 0, 0, 3, 0 };
1247 static const int transminus
[] = { 0, 0, 0, -1 };
1248 if (c
== 'S') i
= transS
[i
];
1249 else if (c
== 'H') i
= transH
[i
];
1250 else if (c
== '-') i
= transminus
[i
];
1254 crReturn(1); /* get another character */
1257 vstring
= smalloc(16);
1259 strcpy(vstring
, "SSH-");
1263 crReturn(1); /* get another char */
1264 if (vslen
>= vstrsize
-1) {
1266 vstring
= srealloc(vstring
, vstrsize
);
1268 vstring
[vslen
++] = c
;
1273 } else if (i
< sizeof(version
)-1)
1280 ssh_agentfwd_enabled
= FALSE
;
1281 rdpkt2_state
.incoming_sequence
= 0;
1284 vlog
= smalloc(20 + vslen
);
1285 sprintf(vlog
, "Server version: %s", vstring
);
1286 ssh_detect_bugs(vstring
);
1287 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1292 * Server version "1.99" means we can choose whether we use v1
1293 * or v2 protocol. Choice is based on cfg.sshprot.
1295 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1297 * This is a v2 server. Begin v2 protocol.
1299 char verstring
[80], vlog
[100];
1300 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1301 SHA_Init(&exhashbase
);
1303 * Hash our version string and their version string.
1305 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1306 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1307 sprintf(vlog
, "We claim version: %s", verstring
);
1309 strcat(verstring
, "\n");
1310 logevent("Using SSH protocol version 2");
1311 sk_write(s
, verstring
, strlen(verstring
));
1312 ssh_protocol
= ssh2_protocol
;
1314 s_rdpkt
= ssh2_rdpkt
;
1317 * This is a v1 server. Begin v1 protocol.
1319 char verstring
[80], vlog
[100];
1320 sprintf(verstring
, "SSH-%s-%s",
1321 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1323 sprintf(vlog
, "We claim version: %s", verstring
);
1325 strcat(verstring
, "\n");
1326 logevent("Using SSH protocol version 1");
1327 sk_write(s
, verstring
, strlen(verstring
));
1328 ssh_protocol
= ssh1_protocol
;
1330 s_rdpkt
= ssh1_rdpkt
;
1332 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1339 static void ssh_gotdata(unsigned char *data
, int datalen
)
1344 * To begin with, feed the characters one by one to the
1345 * protocol initialisation / selection function do_ssh_init().
1346 * When that returns 0, we're done with the initial greeting
1347 * exchange and can move on to packet discipline.
1352 crReturnV
; /* more data please */
1353 ret
= do_ssh_init(*data
);
1360 * We emerge from that loop when the initial negotiation is
1361 * over and we have selected an s_rdpkt function. Now pass
1362 * everything to s_rdpkt, and then pass the resulting packets
1363 * to the proper protocol handler.
1368 while (datalen
> 0) {
1369 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
1370 ssh_protocol(NULL
, 0, 1);
1371 if (ssh_state
== SSH_STATE_CLOSED
) {
1381 static int ssh_closing (Plug plug
, char *error_msg
, int error_code
, int calling_back
) {
1382 ssh_state
= SSH_STATE_CLOSED
;
1386 /* A socket error has occurred. */
1387 connection_fatal (error_msg
);
1389 /* Otherwise, the remote side closed the connection normally. */
1394 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
) {
1395 ssh_gotdata (data
, len
);
1396 if (ssh_state
== SSH_STATE_CLOSED
) {
1407 * Connect to specified host and port.
1408 * Returns an error message, or NULL on success.
1409 * Also places the canonical host name into `realhost'.
1411 static char *connect_to_host(char *host
, int port
, char **realhost
)
1413 static struct plug_function_table fn_table
= {
1416 }, *fn_table_ptr
= &fn_table
;
1425 savedhost
= smalloc(1+strlen(host
));
1427 fatalbox("Out of memory");
1428 strcpy(savedhost
, host
);
1431 port
= 22; /* default ssh port */
1444 addr
= sk_namelookup(host
, realhost
);
1445 if ( (err
= sk_addr_error(addr
)) )
1455 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1456 if ( (err
= sk_socket_error(s
)) )
1460 sk_write(s
, "connect ", 8);
1461 sk_write(s
, FWhost
, strlen(FWhost
));
1464 sprintf(buf
, " %d\n", FWport
);
1465 sk_write(s
, buf
, strlen(buf
));
1473 * Handle the key exchange and user authentication phases.
1475 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1478 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1479 unsigned char cookie
[8];
1480 struct RSAKey servkey
, hostkey
;
1481 struct MD5Context md5c
;
1482 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1483 static int tried_publickey
;
1484 static unsigned char session_id
[16];
1486 static char username
[100];
1490 if (!ispkt
) crWaitUntil(ispkt
);
1492 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1493 bombout(("Public key packet not received"));
1497 logevent("Received public keys");
1499 memcpy(cookie
, pktin
.body
, 8);
1501 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1502 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1505 * Log the host key fingerprint.
1509 logevent("Host key fingerprint is:");
1510 strcpy(logmsg
, " ");
1511 hostkey
.comment
= NULL
;
1512 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1517 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+8+i
+j
);
1518 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1519 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1521 ssh1_local_protoflags
= ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1522 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1525 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1526 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1527 MD5Update(&md5c
, pktin
.body
, 8);
1528 MD5Final(session_id
, &md5c
);
1530 for (i
=0; i
<32; i
++)
1531 session_key
[i
] = random_byte();
1533 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1535 rsabuf
= smalloc(len
);
1537 fatalbox("Out of memory");
1540 * Verify the host key.
1544 * First format the key into a string.
1546 int len
= rsastr_len(&hostkey
);
1547 char fingerprint
[100];
1548 char *keystr
= smalloc(len
);
1550 fatalbox("Out of memory");
1551 rsastr_fmt(keystr
, &hostkey
);
1552 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1553 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1557 for (i
=0; i
<32; i
++) {
1558 rsabuf
[i
] = session_key
[i
];
1560 rsabuf
[i
] ^= session_id
[i
];
1563 if (hostkey
.bytes
> servkey
.bytes
) {
1564 rsaencrypt(rsabuf
, 32, &servkey
);
1565 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1567 rsaencrypt(rsabuf
, 32, &hostkey
);
1568 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1571 logevent("Encrypted session key");
1573 switch (cfg
.cipher
) {
1574 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
; break;
1575 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
; break;
1576 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
; break;
1578 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1579 cipher_type
= SSH_CIPHER_3DES
;
1582 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1583 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1584 cipher_type
= SSH_CIPHER_3DES
;
1585 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1586 bombout(("Server violates SSH 1 protocol by "
1587 "not supporting 3DES encryption"));
1591 switch (cipher_type
) {
1592 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1593 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1594 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1597 send_packet(SSH1_CMSG_SESSION_KEY
,
1598 PKT_CHAR
, cipher_type
,
1599 PKT_DATA
, cookie
, 8,
1600 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1601 PKT_DATA
, rsabuf
, len
,
1602 PKT_INT
, ssh1_local_protoflags
,
1605 logevent("Trying to enable encryption...");
1609 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1610 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1612 cipher
->sesskey(session_key
);
1616 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1617 bombout(("Encryption not successfully enabled"));
1621 logevent("Successfully started encryption");
1627 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1629 if (!ssh_get_line("login as: ",
1630 username
, sizeof(username
), FALSE
)) {
1632 * get_line failed to get a username.
1635 logevent("No username provided. Abandoning session.");
1636 ssh_state
= SSH_STATE_CLOSED
;
1640 c_write_str("login as: ");
1643 crWaitUntil(!ispkt
);
1644 while (inlen
--) switch (c
= *in
++) {
1651 c_write_str("\b \b");
1657 c_write_str("\b \b");
1666 if (((c
>= ' ' && c
<= '~') ||
1667 ((unsigned char)c
>= 160)) && pos
< 40) {
1668 username
[pos
++] = c
;
1674 c_write_str("\r\n");
1675 username
[strcspn(username
, "\n\r")] = '\0';
1678 strncpy(username
, cfg
.username
, 99);
1679 username
[99] = '\0';
1682 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1684 char userlog
[22+sizeof(username
)];
1685 sprintf(userlog
, "Sent username \"%s\"", username
);
1687 if (flags
& FLAG_INTERACTIVE
&&
1688 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1689 strcat(userlog
, "\r\n");
1690 c_write_str(userlog
);
1697 tried_publickey
= 0;
1699 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1700 static char password
[100];
1701 static char prompt
[200];
1704 static int pwpkt_type
;
1706 * Show password prompt, having first obtained it via a TIS
1707 * or CryptoCard exchange if we're doing TIS or CryptoCard
1710 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1711 if (agent_exists()) {
1713 * Attempt RSA authentication using Pageant.
1715 static unsigned char request
[5], *response
, *p
;
1716 static int responselen
;
1717 static int i
, nkeys
;
1718 static int authed
= FALSE
;
1721 logevent("Pageant is running. Requesting keys.");
1723 /* Request the keys held by the agent. */
1724 PUT_32BIT(request
, 1);
1725 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1726 agent_query(request
, 5, &r
, &responselen
);
1727 response
= (unsigned char *)r
;
1728 if (response
&& responselen
>= 5 &&
1729 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
1731 nkeys
= GET_32BIT(p
); p
+= 4;
1732 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1734 for (i
= 0; i
< nkeys
; i
++) {
1735 static struct RSAKey key
;
1736 static Bignum challenge
;
1737 static char *commentp
;
1738 static int commentlen
;
1740 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1743 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1744 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1745 commentlen
= GET_32BIT(p
); p
+= 4;
1746 commentp
= p
; p
+= commentlen
;
1747 send_packet(SSH1_CMSG_AUTH_RSA
,
1748 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1750 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1751 logevent("Key refused");
1754 logevent("Received RSA challenge");
1755 ssh1_read_bignum(pktin
.body
, &challenge
);
1757 char *agentreq
, *q
, *ret
;
1759 len
= 1 + 4; /* message type, bit count */
1760 len
+= ssh1_bignum_length(key
.exponent
);
1761 len
+= ssh1_bignum_length(key
.modulus
);
1762 len
+= ssh1_bignum_length(challenge
);
1763 len
+= 16; /* session id */
1764 len
+= 4; /* response format */
1765 agentreq
= smalloc(4 + len
);
1766 PUT_32BIT(agentreq
, len
);
1768 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1769 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
1771 q
+= ssh1_write_bignum(q
, key
.exponent
);
1772 q
+= ssh1_write_bignum(q
, key
.modulus
);
1773 q
+= ssh1_write_bignum(q
, challenge
);
1774 memcpy(q
, session_id
, 16); q
+= 16;
1775 PUT_32BIT(q
, 1); /* response format */
1776 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1779 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1780 logevent("Sending Pageant's response");
1781 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1782 PKT_DATA
, ret
+5, 16, PKT_END
);
1785 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1786 logevent("Pageant's response accepted");
1787 if (flags
& FLAG_VERBOSE
) {
1788 c_write_str("Authenticated using RSA key \"");
1789 c_write(commentp
, commentlen
);
1790 c_write_str("\" from agent\r\n");
1794 logevent("Pageant's response not accepted");
1796 logevent("Pageant failed to answer challenge");
1800 logevent("No reply received from Pageant");
1803 freebn(key
.exponent
);
1804 freebn(key
.modulus
);
1813 if (*cfg
.keyfile
&& !tried_publickey
)
1814 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1816 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1818 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1819 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1820 logevent("Requested TIS authentication");
1821 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1823 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1824 logevent("TIS authentication declined");
1825 if (flags
& FLAG_INTERACTIVE
)
1826 c_write_str("TIS authentication refused.\r\n");
1828 int challengelen
= ((pktin
.body
[0] << 24) |
1829 (pktin
.body
[1] << 16) |
1830 (pktin
.body
[2] << 8) |
1832 logevent("Received TIS challenge");
1833 if (challengelen
> sizeof(prompt
)-1)
1834 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1835 memcpy(prompt
, pktin
.body
+4, challengelen
);
1836 prompt
[challengelen
] = '\0';
1839 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1841 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1842 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1843 logevent("Requested CryptoCard authentication");
1844 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1846 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1847 logevent("CryptoCard authentication declined");
1848 c_write_str("CryptoCard authentication refused.\r\n");
1850 int challengelen
= ((pktin
.body
[0] << 24) |
1851 (pktin
.body
[1] << 16) |
1852 (pktin
.body
[2] << 8) |
1854 logevent("Received CryptoCard challenge");
1855 if (challengelen
> sizeof(prompt
)-1)
1856 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1857 memcpy(prompt
, pktin
.body
+4, challengelen
);
1858 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1859 sizeof(prompt
)-challengelen
);
1860 prompt
[sizeof(prompt
)-1] = '\0';
1863 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1864 sprintf(prompt
, "%.90s@%.90s's password: ",
1865 username
, savedhost
);
1867 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1868 char *comment
= NULL
;
1869 if (flags
& FLAG_VERBOSE
)
1870 c_write_str("Trying public key authentication.\r\n");
1871 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1872 if (flags
& FLAG_VERBOSE
)
1873 c_write_str("No passphrase required.\r\n");
1876 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1881 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
1883 * get_line failed to get a password (for example
1884 * because one was supplied on the command line
1885 * which has already failed to work). Terminate.
1887 logevent("No more passwords to try");
1888 ssh_state
= SSH_STATE_CLOSED
;
1892 c_write_str(prompt
);
1896 crWaitUntil(!ispkt
);
1897 while (inlen
--) switch (c
= *in
++) {
1914 if (((c
>= ' ' && c
<= '~') ||
1915 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1916 password
[pos
++] = c
;
1920 c_write_str("\r\n");
1924 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1926 * Try public key authentication with the specified
1929 static struct RSAKey pubkey
;
1930 static Bignum challenge
, response
;
1932 static unsigned char buffer
[32];
1934 tried_publickey
= 1;
1935 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1937 c_write_str("Couldn't load public key from ");
1938 c_write_str(cfg
.keyfile
);
1939 c_write_str(".\r\n");
1940 continue; /* go and try password */
1943 c_write_str("Wrong passphrase.\r\n");
1944 tried_publickey
= 0;
1945 continue; /* try again */
1949 * Send a public key attempt.
1951 send_packet(SSH1_CMSG_AUTH_RSA
,
1952 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1955 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1956 c_write_str("Server refused our public key.\r\n");
1957 continue; /* go and try password */
1959 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1960 bombout(("Bizarre response to offer of public key"));
1963 ssh1_read_bignum(pktin
.body
, &challenge
);
1964 response
= rsadecrypt(challenge
, &pubkey
);
1965 freebn(pubkey
.private_exponent
); /* burn the evidence */
1967 for (i
= 0; i
< 32; i
++) {
1968 buffer
[i
] = bignum_byte(response
, 31-i
);
1972 MD5Update(&md5c
, buffer
, 32);
1973 MD5Update(&md5c
, session_id
, 16);
1974 MD5Final(buffer
, &md5c
);
1976 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1977 PKT_DATA
, buffer
, 16, PKT_END
);
1980 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1981 if (flags
& FLAG_VERBOSE
)
1982 c_write_str("Failed to authenticate with our public key.\r\n");
1983 continue; /* go and try password */
1984 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1985 bombout(("Bizarre response to RSA authentication response"));
1989 break; /* we're through! */
1991 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1993 * Defence against traffic analysis: we send a
1994 * whole bunch of packets containing strings of
1995 * different lengths. One of these strings is the
1996 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1997 * The others are all random data in
1998 * SSH1_MSG_IGNORE packets. This way a passive
1999 * listener can't tell which is the password, and
2000 * hence can't deduce the password length.
2002 * Anybody with a password length greater than 16
2003 * bytes is going to have enough entropy in their
2004 * password that a listener won't find it _that_
2005 * much help to know how long it is. So what we'll
2008 * - if password length < 16, we send 15 packets
2009 * containing string lengths 1 through 15
2011 * - otherwise, we let N be the nearest multiple
2012 * of 8 below the password length, and send 8
2013 * packets containing string lengths N through
2014 * N+7. This won't obscure the order of
2015 * magnitude of the password length, but it will
2016 * introduce a bit of extra uncertainty.
2018 * A few servers (the old 1.2.18 through 1.2.22)
2019 * can't deal with SSH1_MSG_IGNORE. For these
2020 * servers, we need an alternative defence. We make
2021 * use of the fact that the password is interpreted
2022 * as a C string: so we can append a NUL, then some
2025 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2030 len
= strlen(password
);
2031 if (len
< sizeof(string
)) {
2033 strcpy(string
, password
);
2034 len
++; /* cover the zero byte */
2035 while (len
< sizeof(string
)) {
2036 string
[len
++] = (char)random_byte();
2041 send_packet(pwpkt_type
, PKT_INT
, len
,
2042 PKT_DATA
, s
, len
, PKT_END
);
2044 int bottom
, top
, pwlen
, i
;
2047 pwlen
= strlen(password
);
2049 bottom
= 0; /* zero length passwords are OK! :-) */
2052 bottom
= pwlen
&~ 7;
2056 assert(pwlen
>= bottom
&& pwlen
<= top
);
2058 randomstr
= smalloc(top
+1);
2060 for (i
= bottom
; i
<= top
; i
++) {
2062 defer_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2064 for (j
= 0; j
< i
; j
++) {
2066 randomstr
[j
] = random_byte();
2067 } while (randomstr
[j
] == '\0');
2069 randomstr
[i
] = '\0';
2070 defer_packet(SSH1_MSG_IGNORE
,
2071 PKT_STR
, randomstr
, PKT_END
);
2074 ssh_pkt_defersend();
2077 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2080 logevent("Sent password");
2081 memset(password
, 0, strlen(password
));
2083 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2084 if (flags
& FLAG_VERBOSE
)
2085 c_write_str("Access denied\r\n");
2086 logevent("Authentication refused");
2087 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2088 logevent("Received disconnect request");
2089 ssh_state
= SSH_STATE_CLOSED
;
2091 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2092 bombout(("Strange packet received, type %d", pktin
.type
));
2097 logevent("Authentication successful");
2102 void sshfwd_close(struct ssh_channel
*c
) {
2103 if (c
&& !c
->closes
) {
2104 if (ssh_version
== 1) {
2105 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
, PKT_END
);
2107 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2108 ssh2_pkt_adduint32(c
->remoteid
);
2112 if (c
->type
== CHAN_X11
) {
2114 logevent("X11 connection terminated");
2119 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
) {
2120 if (ssh_version
== 1) {
2121 send_packet(SSH1_MSG_CHANNEL_DATA
,
2122 PKT_INT
, c
->remoteid
,
2127 ssh2_add_channel_data(c
, buf
, len
);
2132 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
2137 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2140 if (ssh_state
== SSH_STATE_CLOSED
)
2143 if (cfg
.agentfwd
&& agent_exists()) {
2144 logevent("Requesting agent forwarding");
2145 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2146 do { crReturnV
; } while (!ispkt
);
2147 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2148 bombout(("Protocol confusion"));
2150 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2151 logevent("Agent forwarding refused");
2153 logevent("Agent forwarding enabled");
2154 ssh_agentfwd_enabled
= TRUE
;
2158 if (cfg
.x11_forward
) {
2159 char proto
[20], data
[64];
2160 logevent("Requesting X11 forwarding");
2161 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2162 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2163 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2164 PKT_STR
, proto
, PKT_STR
, data
,
2168 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2169 PKT_STR
, proto
, PKT_STR
, data
,
2172 do { crReturnV
; } while (!ispkt
);
2173 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2174 bombout(("Protocol confusion"));
2176 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2177 logevent("X11 forwarding refused");
2179 logevent("X11 forwarding enabled");
2180 ssh_X11_fwd_enabled
= TRUE
;
2185 send_packet(SSH1_CMSG_REQUEST_PTY
,
2186 PKT_STR
, cfg
.termtype
,
2187 PKT_INT
, rows
, PKT_INT
, cols
,
2188 PKT_INT
, 0, PKT_INT
, 0,
2191 ssh_state
= SSH_STATE_INTERMED
;
2192 do { crReturnV
; } while (!ispkt
);
2193 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2194 bombout(("Protocol confusion"));
2196 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2197 c_write_str("Server refused to allocate pty\r\n");
2198 ssh_editing
= ssh_echoing
= 1;
2200 logevent("Allocated pty");
2202 ssh_editing
= ssh_echoing
= 1;
2205 if (cfg
.compression
) {
2206 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2207 do { crReturnV
; } while (!ispkt
);
2208 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2209 bombout(("Protocol confusion"));
2211 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2212 c_write_str("Server refused to compress\r\n");
2214 logevent("Started compression");
2215 ssh1_compressing
= TRUE
;
2216 zlib_compress_init();
2217 zlib_decompress_init();
2220 if (*cfg
.remote_cmd_ptr
)
2221 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
, PKT_END
);
2223 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2224 logevent("Started session");
2226 ssh_state
= SSH_STATE_SESSION
;
2230 ssh_special(TS_EOF
);
2232 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2234 ssh_channels
= newtree234(ssh_channelcmp
);
2238 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2239 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2240 long len
= GET_32BIT(pktin
.body
);
2241 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2243 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2244 ssh_state
= SSH_STATE_CLOSED
;
2245 logevent("Received disconnect request");
2247 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2248 /* Remote side is trying to open a channel to talk to our
2249 * X-Server. Give them back a local channel number. */
2250 struct ssh_channel
*c
;
2252 logevent("Received X11 connect request");
2253 /* Refuse if X11 forwarding is disabled. */
2254 if (!ssh_X11_fwd_enabled
) {
2255 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2256 PKT_INT
, GET_32BIT(pktin
.body
),
2258 logevent("Rejected X11 connect request");
2260 c
= smalloc(sizeof(struct ssh_channel
));
2262 if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2263 logevent("opening X11 forward connection failed");
2265 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2266 PKT_INT
, GET_32BIT(pktin
.body
),
2269 logevent("opening X11 forward connection succeeded");
2270 c
->remoteid
= GET_32BIT(pktin
.body
);
2271 c
->localid
= alloc_channel_id();
2273 c
->type
= CHAN_X11
; /* identify channel type */
2274 add234(ssh_channels
, c
);
2275 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2276 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2278 logevent("Opened X11 forward channel");
2281 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2282 /* Remote side is trying to open a channel to talk to our
2283 * agent. Give them back a local channel number. */
2284 struct ssh_channel
*c
;
2286 /* Refuse if agent forwarding is disabled. */
2287 if (!ssh_agentfwd_enabled
) {
2288 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2289 PKT_INT
, GET_32BIT(pktin
.body
),
2292 c
= smalloc(sizeof(struct ssh_channel
));
2293 c
->remoteid
= GET_32BIT(pktin
.body
);
2294 c
->localid
= alloc_channel_id();
2296 c
->type
= CHAN_AGENT
; /* identify channel type */
2297 c
->u
.a
.lensofar
= 0;
2298 add234(ssh_channels
, c
);
2299 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2300 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2303 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2304 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2305 /* Remote side closes a channel. */
2306 unsigned i
= GET_32BIT(pktin
.body
);
2307 struct ssh_channel
*c
;
2308 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2311 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2312 if (!(c
->closes
& closetype
))
2313 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
2314 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2315 logevent("X11 connection closed");
2316 assert(c
->u
.x11
.s
!= NULL
);
2317 x11_close(c
->u
.x11
.s
);
2320 c
->closes
|= closetype
;
2321 if (c
->closes
== 3) {
2322 del234(ssh_channels
, c
);
2326 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2327 /* Data sent down one of our channels. */
2328 int i
= GET_32BIT(pktin
.body
);
2329 int len
= GET_32BIT(pktin
.body
+4);
2330 unsigned char *p
= pktin
.body
+8;
2331 struct ssh_channel
*c
;
2332 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2336 x11_send(c
->u
.x11
.s
, p
, len
);
2339 /* Data for an agent message. Buffer it. */
2341 if (c
->u
.a
.lensofar
< 4) {
2342 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2343 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
2344 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2346 if (c
->u
.a
.lensofar
== 4) {
2347 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
2348 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2349 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2351 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2352 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
2353 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
2354 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2356 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2357 void *reply
, *sentreply
;
2359 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
2364 /* Fake SSH_AGENT_FAILURE. */
2365 sentreply
= "\0\0\0\1\5";
2368 send_packet(SSH1_MSG_CHANNEL_DATA
,
2369 PKT_INT
, c
->remoteid
,
2371 PKT_DATA
, sentreply
, replylen
,
2375 sfree(c
->u
.a
.message
);
2376 c
->u
.a
.lensofar
= 0;
2382 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2383 /* may be from EXEC_SHELL on some servers */
2384 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2385 /* may be from EXEC_SHELL on some servers
2386 * if no pty is available or in other odd cases. Ignore */
2387 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2388 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2390 bombout(("Strange packet received: type %d", pktin
.type
));
2395 int len
= min(inlen
, 512);
2396 send_packet(SSH1_CMSG_STDIN_DATA
,
2397 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2408 * Utility routine for decoding comma-separated strings in KEXINIT.
2410 static int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
2411 int needlen
= strlen(needle
);
2414 * Is it at the start of the string?
2416 if (haylen
>= needlen
&& /* haystack is long enough */
2417 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2418 (haylen
== needlen
|| haystack
[needlen
] == ',')
2419 /* either , or EOS follows */
2423 * If not, search for the next comma and resume after that.
2424 * If no comma found, terminate.
2426 while (haylen
> 0 && *haystack
!= ',')
2427 haylen
--, haystack
++;
2430 haylen
--, haystack
++; /* skip over comma itself */
2435 * SSH2 key creation method.
2437 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
, char *keyspace
) {
2439 /* First 20 bytes. */
2442 SHA_Bytes(&s
, H
, 20);
2443 SHA_Bytes(&s
, &chr
, 1);
2444 SHA_Bytes(&s
, sessid
, 20);
2445 SHA_Final(&s
, keyspace
);
2446 /* Next 20 bytes. */
2449 SHA_Bytes(&s
, H
, 20);
2450 SHA_Bytes(&s
, keyspace
, 20);
2451 SHA_Final(&s
, keyspace
+20);
2455 * Handle the SSH2 transport layer.
2457 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2459 static int i
, j
, len
, nbits
, pbits
;
2461 static Bignum p
, g
, e
, f
, K
;
2462 static int kex_init_value
, kex_reply_value
;
2463 static const struct ssh_mac
**maclist
;
2465 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2466 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2467 static const struct ssh_mac
*csmac_tobe
= NULL
;
2468 static const struct ssh_mac
*scmac_tobe
= NULL
;
2469 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2470 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2471 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2472 static int hostkeylen
, siglen
;
2473 static void *hkey
; /* actual host key */
2474 static unsigned char exchange_hash
[20];
2475 static unsigned char keyspace
[40];
2476 static const struct ssh2_ciphers
*preferred_cipher
;
2477 static const struct ssh_compress
*preferred_comp
;
2478 static int first_kex
;
2485 * Set up the preferred cipher and compression.
2487 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2488 preferred_cipher
= &ssh2_blowfish
;
2489 } else if (cfg
.cipher
== CIPHER_DES
) {
2490 logevent("Single DES not supported in SSH2; using 3DES");
2491 preferred_cipher
= &ssh2_3des
;
2492 } else if (cfg
.cipher
== CIPHER_3DES
) {
2493 preferred_cipher
= &ssh2_3des
;
2494 } else if (cfg
.cipher
== CIPHER_AES
) {
2495 preferred_cipher
= &ssh2_aes
;
2497 /* Shouldn't happen, but we do want to initialise to _something_. */
2498 preferred_cipher
= &ssh2_3des
;
2500 if (cfg
.compression
)
2501 preferred_comp
= &ssh_zlib
;
2503 preferred_comp
= &ssh_comp_none
;
2506 * Be prepared to work around the buggy MAC problem.
2508 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2509 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2511 maclist
= macs
, nmacs
= lenof(macs
);
2515 * Construct and send our key exchange packet.
2517 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2518 for (i
= 0; i
< 16; i
++)
2519 ssh2_pkt_addbyte((unsigned char)random_byte());
2520 /* List key exchange algorithms. */
2521 ssh2_pkt_addstring_start();
2522 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2523 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2524 if (i
< lenof(kex_algs
)-1)
2525 ssh2_pkt_addstring_str(",");
2527 /* List server host key algorithms. */
2528 ssh2_pkt_addstring_start();
2529 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2530 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2531 if (i
< lenof(hostkey_algs
)-1)
2532 ssh2_pkt_addstring_str(",");
2534 /* List client->server encryption algorithms. */
2535 ssh2_pkt_addstring_start();
2536 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2537 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2538 for (j
= 0; j
< c
->nciphers
; j
++) {
2539 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2540 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2541 ssh2_pkt_addstring_str(",");
2544 /* List server->client encryption algorithms. */
2545 ssh2_pkt_addstring_start();
2546 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2547 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2548 for (j
= 0; j
< c
->nciphers
; j
++) {
2549 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2550 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2551 ssh2_pkt_addstring_str(",");
2554 /* List client->server MAC algorithms. */
2555 ssh2_pkt_addstring_start();
2556 for (i
= 0; i
< nmacs
; i
++) {
2557 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2559 ssh2_pkt_addstring_str(",");
2561 /* List server->client MAC algorithms. */
2562 ssh2_pkt_addstring_start();
2563 for (i
= 0; i
< nmacs
; i
++) {
2564 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2566 ssh2_pkt_addstring_str(",");
2568 /* List client->server compression algorithms. */
2569 ssh2_pkt_addstring_start();
2570 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2571 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2572 ssh2_pkt_addstring_str(c
->name
);
2573 if (i
< lenof(compressions
))
2574 ssh2_pkt_addstring_str(",");
2576 /* List server->client compression algorithms. */
2577 ssh2_pkt_addstring_start();
2578 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2579 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2580 ssh2_pkt_addstring_str(c
->name
);
2581 if (i
< lenof(compressions
))
2582 ssh2_pkt_addstring_str(",");
2584 /* List client->server languages. Empty list. */
2585 ssh2_pkt_addstring_start();
2586 /* List server->client languages. Empty list. */
2587 ssh2_pkt_addstring_start();
2588 /* First KEX packet does _not_ follow, because we're not that brave. */
2589 ssh2_pkt_addbool(FALSE
);
2591 ssh2_pkt_adduint32(0);
2593 exhash
= exhashbase
;
2594 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
2598 if (!ispkt
) crWaitUntil(ispkt
);
2599 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
2602 * Now examine the other side's KEXINIT to see what we're up
2605 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2606 bombout(("expected key exchange packet from server"));
2609 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
2610 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
2611 pktin
.savedpos
+= 16; /* skip garbage cookie */
2612 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2613 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2614 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2619 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2620 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2621 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2622 hostkey
= hostkey_algs
[i
];
2626 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2627 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2628 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2629 for (j
= 0; j
< c
->nciphers
; j
++) {
2630 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2631 cscipher_tobe
= c
->list
[j
];
2638 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2639 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2640 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2641 for (j
= 0; j
< c
->nciphers
; j
++) {
2642 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2643 sccipher_tobe
= c
->list
[j
];
2650 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2651 for (i
= 0; i
< nmacs
; i
++) {
2652 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2653 csmac_tobe
= maclist
[i
];
2657 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2658 for (i
= 0; i
< nmacs
; i
++) {
2659 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2660 scmac_tobe
= maclist
[i
];
2664 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2665 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2666 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2667 if (in_commasep_string(c
->name
, str
, len
)) {
2672 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2673 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2674 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2675 if (in_commasep_string(c
->name
, str
, len
)) {
2682 * Work out the number of bits of key we will need from the key
2683 * exchange. We start with the maximum key length of either
2689 csbits
= cscipher_tobe
->keylen
;
2690 scbits
= sccipher_tobe
->keylen
;
2691 nbits
= (csbits
> scbits ? csbits
: scbits
);
2693 /* The keys only have 160-bit entropy, since they're based on
2694 * a SHA-1 hash. So cap the key size at 160 bits. */
2695 if (nbits
> 160) nbits
= 160;
2698 * If we're doing Diffie-Hellman group exchange, start by
2699 * requesting a group.
2701 if (kex
== &ssh_diffiehellman_gex
) {
2702 logevent("Doing Diffie-Hellman group exchange");
2704 * Work out how big a DH group we will need to allow that
2707 pbits
= 512 << ((nbits
-1) / 64);
2708 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2709 ssh2_pkt_adduint32(pbits
);
2713 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2714 bombout(("expected key exchange group packet from server"));
2717 p
= ssh2_pkt_getmp();
2718 g
= ssh2_pkt_getmp();
2719 dh_setup_group(p
, g
);
2720 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2721 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2724 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2725 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2728 logevent("Doing Diffie-Hellman key exchange");
2730 * Now generate and send e for Diffie-Hellman.
2732 e
= dh_create_e(nbits
*2);
2733 ssh2_pkt_init(kex_init_value
);
2738 if (pktin
.type
!= kex_reply_value
) {
2739 bombout(("expected key exchange reply packet from server"));
2742 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2743 f
= ssh2_pkt_getmp();
2744 ssh2_pkt_getstring(&sigdata
, &siglen
);
2748 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2749 if (kex
== &ssh_diffiehellman_gex
) {
2750 sha_uint32(&exhash
, pbits
);
2751 sha_mpint(&exhash
, p
);
2752 sha_mpint(&exhash
, g
);
2754 sha_mpint(&exhash
, e
);
2755 sha_mpint(&exhash
, f
);
2756 sha_mpint(&exhash
, K
);
2757 SHA_Final(&exhash
, exchange_hash
);
2762 debug(("Exchange hash is:\n"));
2763 dmemdump(exchange_hash
, 20);
2766 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2767 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2768 bombout(("Server failed host key check"));
2773 * Expect SSH2_MSG_NEWKEYS from server.
2776 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2777 bombout(("expected new-keys packet from server"));
2782 * Authenticate remote host: verify host key. (We've already
2783 * checked the signature of the exchange hash.)
2785 keystr
= hostkey
->fmtkey(hkey
);
2786 fingerprint
= hostkey
->fingerprint(hkey
);
2787 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2788 keystr
, fingerprint
);
2789 if (first_kex
) { /* don't bother logging this in rekeys */
2790 logevent("Host key fingerprint is:");
2791 logevent(fingerprint
);
2795 hostkey
->freekey(hkey
);
2798 * Send SSH2_MSG_NEWKEYS.
2800 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2804 * Create and initialise session keys.
2806 cscipher
= cscipher_tobe
;
2807 sccipher
= sccipher_tobe
;
2810 cscomp
= cscomp_tobe
;
2811 sccomp
= sccomp_tobe
;
2812 cscomp
->compress_init();
2813 sccomp
->decompress_init();
2815 * Set IVs after keys. Here we use the exchange hash from the
2816 * _first_ key exchange.
2819 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
2820 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
2821 cscipher
->setcskey(keyspace
);
2822 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
2823 sccipher
->setsckey(keyspace
);
2824 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
2825 cscipher
->setcsiv(keyspace
);
2826 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
2827 sccipher
->setsciv(keyspace
);
2828 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
2829 csmac
->setcskey(keyspace
);
2830 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
2831 scmac
->setsckey(keyspace
);
2834 * If this is the first key exchange phase, we must pass the
2835 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2836 * wants to see it but because it will need time to initialise
2837 * itself before it sees an actual packet. In subsequent key
2838 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2839 * it would only confuse the layer above.
2847 * Now we're encrypting. Begin returning 1 to the protocol main
2848 * function so that other things can run on top of the
2849 * transport. If we ever see a KEXINIT, we must go back to the
2852 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
2855 logevent("Server initiated key re-exchange");
2856 goto begin_key_exchange
;
2862 * Add data to an SSH2 channel output buffer.
2864 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
) {
2865 if (c
->v2
.outbufsize
<
2866 c
->v2
.outbuflen
+ len
) {
2868 c
->v2
.outbuflen
+ len
+ 1024;
2869 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
,
2872 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
,
2874 c
->v2
.outbuflen
+= len
;
2878 * Attempt to send data on an SSH2 channel.
2880 static void ssh2_try_send(struct ssh_channel
*c
) {
2881 while (c
->v2
.remwindow
> 0 &&
2882 c
->v2
.outbuflen
> 0) {
2883 unsigned len
= c
->v2
.remwindow
;
2884 if (len
> c
->v2
.outbuflen
)
2885 len
= c
->v2
.outbuflen
;
2886 if (len
> c
->v2
.remmaxpkt
)
2887 len
= c
->v2
.remmaxpkt
;
2888 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2889 ssh2_pkt_adduint32(c
->remoteid
);
2890 ssh2_pkt_addstring_start();
2891 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
2893 c
->v2
.outbuflen
-= len
;
2894 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+len
,
2896 c
->v2
.remwindow
-= len
;
2901 * Handle the SSH2 userauth and connection layers.
2903 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2905 static unsigned long remote_winsize
;
2906 static unsigned long remote_maxpkt
;
2908 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
, AUTH_PASSWORD
2912 AUTH_TYPE_PUBLICKEY
,
2913 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
2914 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
2917 static int gotit
, need_pw
, can_pubkey
, can_passwd
;
2918 static int tried_pubkey_config
, tried_agent
;
2919 static int we_are_in
;
2920 static char username
[100];
2921 static char pwprompt
[200];
2922 static char password
[100];
2927 * Request userauth protocol, and await a response to it.
2929 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2930 ssh2_pkt_addstring("ssh-userauth");
2932 crWaitUntilV(ispkt
);
2933 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2934 bombout(("Server refused user authentication protocol"));
2939 * We repeat this whole loop, including the username prompt,
2940 * until we manage a successful authentication. If the user
2941 * types the wrong _password_, they are sent back to the
2942 * beginning to try another username. (If they specify a
2943 * username in the config, they are never asked, even if they
2944 * do give a wrong password.)
2946 * I think this best serves the needs of
2948 * - the people who have no configuration, no keys, and just
2949 * want to try repeated (username,password) pairs until they
2950 * type both correctly
2952 * - people who have keys and configuration but occasionally
2953 * need to fall back to passwords
2955 * - people with a key held in Pageant, who might not have
2956 * logged in to a particular machine before; so they want to
2957 * type a username, and then _either_ their key will be
2958 * accepted, _or_ they will type a password. If they mistype
2959 * the username they will want to be able to get back and
2970 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2972 if (!ssh_get_line("login as: ",
2973 username
, sizeof(username
), FALSE
)) {
2975 * get_line failed to get a username.
2978 logevent("No username provided. Abandoning session.");
2979 ssh_state
= SSH_STATE_CLOSED
;
2983 c_write_str("login as: ");
2986 crWaitUntilV(!ispkt
);
2987 while (inlen
--) switch (c
= *in
++) {
2994 c_write_str("\b \b");
3000 c_write_str("\b \b");
3009 if (((c
>= ' ' && c
<= '~') ||
3010 ((unsigned char)c
>= 160)) && pos
< 40) {
3011 username
[pos
++] = c
;
3018 c_write_str("\r\n");
3019 username
[strcspn(username
, "\n\r")] = '\0';
3022 strncpy(username
, cfg
.username
, 99);
3023 username
[99] = '\0';
3024 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3025 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3031 * Send an authentication request using method "none": (a)
3032 * just in case it succeeds, and (b) so that we know what
3033 * authentication methods we can usefully try next.
3035 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3036 ssh2_pkt_addstring(username
);
3037 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3038 ssh2_pkt_addstring("none"); /* method */
3040 type
= AUTH_TYPE_NONE
;
3044 tried_pubkey_config
= FALSE
;
3045 tried_agent
= FALSE
;
3049 * Wait for the result of the last authentication request.
3052 crWaitUntilV(ispkt
);
3053 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3057 * Don't show the banner if we're operating in
3058 * non-verbose non-interactive mode. (It's probably
3059 * a script, which means nobody will read the
3060 * banner _anyway_, and moreover the printing of
3061 * the banner will screw up processing on the
3062 * output of (say) plink.)
3064 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3065 ssh2_pkt_getstring(&banner
, &size
);
3067 c_write_untrusted(banner
, size
);
3069 crWaitUntilV(ispkt
);
3071 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3072 logevent("Access granted");
3077 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3078 bombout(("Strange packet received during authentication: type %d",
3086 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3087 * we can look at the string in it and know what we can
3088 * helpfully try next.
3093 ssh2_pkt_getstring(&methods
, &methlen
);
3094 if (!ssh2_pkt_getbool()) {
3096 * We have received an unequivocal Access
3097 * Denied. This can translate to a variety of
3100 * - if we'd just tried "none" authentication,
3101 * it's not worth printing anything at all
3103 * - if we'd just tried a public key _offer_,
3104 * the message should be "Server refused our
3105 * key" (or no message at all if the key
3106 * came from Pageant)
3108 * - if we'd just tried anything else, the
3109 * message really should be "Access denied".
3111 * Additionally, if we'd just tried password
3112 * authentication, we should break out of this
3113 * whole loop so as to go back to the username
3116 if (type
== AUTH_TYPE_NONE
) {
3118 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3119 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3120 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3121 c_write_str("Server refused our key\r\n");
3122 logevent("Server refused public key");
3124 c_write_str("Access denied\r\n");
3125 logevent("Access denied");
3126 if (type
== AUTH_TYPE_PASSWORD
) {
3132 c_write_str("Further authentication required\r\n");
3133 logevent("Further authentication required");
3136 can_pubkey
= in_commasep_string("publickey", methods
, methlen
);
3137 can_passwd
= in_commasep_string("password", methods
, methlen
);
3142 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3144 * Attempt public-key authentication using Pageant.
3146 static unsigned char request
[5], *response
, *p
;
3147 static int responselen
;
3148 static int i
, nkeys
;
3149 static int authed
= FALSE
;
3154 logevent("Pageant is running. Requesting keys.");
3156 /* Request the keys held by the agent. */
3157 PUT_32BIT(request
, 1);
3158 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3159 agent_query(request
, 5, &r
, &responselen
);
3160 response
= (unsigned char *)r
;
3161 if (response
&& responselen
>= 5 &&
3162 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3164 nkeys
= GET_32BIT(p
); p
+= 4;
3165 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3167 for (i
= 0; i
< nkeys
; i
++) {
3168 static char *pkblob
, *alg
, *commentp
;
3169 static int pklen
, alglen
, commentlen
;
3170 static int siglen
, retlen
, len
;
3171 static char *q
, *agentreq
, *ret
;
3173 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
3175 pklen
= GET_32BIT(p
); p
+= 4;
3176 pkblob
= p
; p
+= pklen
;
3177 alglen
= GET_32BIT(pkblob
);
3179 commentlen
= GET_32BIT(p
); p
+= 4;
3180 commentp
= p
; p
+= commentlen
;
3181 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3182 ssh2_pkt_addstring(username
);
3183 ssh2_pkt_addstring("ssh-connection");/* service requested */
3184 ssh2_pkt_addstring("publickey");/* method */
3185 ssh2_pkt_addbool(FALSE
); /* no signature included */
3186 ssh2_pkt_addstring_start();
3187 ssh2_pkt_addstring_data(alg
, alglen
);
3188 ssh2_pkt_addstring_start();
3189 ssh2_pkt_addstring_data(pkblob
, pklen
);
3192 crWaitUntilV(ispkt
);
3193 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3194 logevent("Key refused");
3198 if (flags
& FLAG_VERBOSE
) {
3199 c_write_str("Authenticating with public key \"");
3200 c_write(commentp
, commentlen
);
3201 c_write_str("\" from agent\r\n");
3205 * Server is willing to accept the key.
3206 * Construct a SIGN_REQUEST.
3208 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3209 ssh2_pkt_addstring(username
);
3210 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3211 ssh2_pkt_addstring("publickey"); /* method */
3212 ssh2_pkt_addbool(TRUE
);
3213 ssh2_pkt_addstring_start();
3214 ssh2_pkt_addstring_data(alg
, alglen
);
3215 ssh2_pkt_addstring_start();
3216 ssh2_pkt_addstring_data(pkblob
, pklen
);
3218 siglen
= pktout
.length
- 5 + 4 + 20;
3219 len
= 1; /* message type */
3220 len
+= 4 + pklen
; /* key blob */
3221 len
+= 4 + siglen
; /* data to sign */
3222 len
+= 4; /* flags */
3223 agentreq
= smalloc(4 + len
);
3224 PUT_32BIT(agentreq
, len
);
3226 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3227 PUT_32BIT(q
, pklen
); q
+= 4;
3228 memcpy(q
, pkblob
, pklen
); q
+= pklen
;
3229 PUT_32BIT(q
, siglen
); q
+= 4;
3230 /* Now the data to be signed... */
3231 PUT_32BIT(q
, 20); q
+= 4;
3232 memcpy(q
, ssh2_session_id
, 20); q
+= 20;
3233 memcpy(q
, pktout
.data
+5, pktout
.length
-5);
3234 q
+= pktout
.length
-5;
3235 /* And finally the (zero) flags word. */
3237 agent_query(agentreq
, len
+4, &ret
, &retlen
);
3240 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3241 logevent("Sending Pageant's response");
3242 ssh2_pkt_addstring_start();
3243 ssh2_pkt_addstring_data(ret
+9, GET_32BIT(ret
+5));
3248 logevent("Pageant failed to answer challenge");
3258 if (!method
&& can_pubkey
&& *cfg
.keyfile
&& !tried_pubkey_config
) {
3259 unsigned char *pub_blob
;
3260 char *algorithm
, *comment
;
3263 tried_pubkey_config
= TRUE
;
3266 * Try the public key supplied in the configuration.
3268 * First, offer the public blob to see if the server is
3269 * willing to accept it.
3271 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3274 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3275 ssh2_pkt_addstring(username
);
3276 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3277 ssh2_pkt_addstring("publickey");/* method */
3278 ssh2_pkt_addbool(FALSE
); /* no signature included */
3279 ssh2_pkt_addstring(algorithm
);
3280 ssh2_pkt_addstring_start();
3281 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3283 logevent("Offered public key"); /* FIXME */
3285 crWaitUntilV(ispkt
);
3286 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3288 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3289 continue; /* key refused; give up on it */
3292 logevent("Offer of public key accepted");
3294 * Actually attempt a serious authentication using
3297 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3298 sprintf(pwprompt
, "Passphrase for key \"%.100s\": ", comment
);
3303 c_write_str("Authenticating with public key \"");
3304 c_write_str(comment
);
3305 c_write_str("\"\r\n");
3306 method
= AUTH_PUBLICKEY_FILE
;
3310 if (!method
&& can_passwd
) {
3311 method
= AUTH_PASSWORD
;
3312 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
, savedhost
);
3318 if (!ssh_get_line(pwprompt
, password
,
3319 sizeof(password
), TRUE
)) {
3321 * get_line failed to get a password (for
3322 * example because one was supplied on the
3323 * command line which has already failed to
3326 logevent("No more passwords to try");
3327 ssh_state
= SSH_STATE_CLOSED
;
3334 c_write_str(pwprompt
);
3339 crWaitUntilV(!ispkt
);
3340 while (inlen
--) switch (c
= *in
++) {
3357 if (((c
>= ' ' && c
<= '~') ||
3358 ((unsigned char)c
>= 160)) && pos
< 40)
3359 password
[pos
++] = c
;
3363 c_write_str("\r\n");
3367 if (method
== AUTH_PUBLICKEY_FILE
) {
3369 * We have our passphrase. Now try the actual authentication.
3371 struct ssh2_userkey
*key
;
3373 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3374 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3375 if (key
== SSH2_WRONG_PASSPHRASE
) {
3376 c_write_str("Wrong passphrase\r\n");
3377 tried_pubkey_config
= FALSE
;
3379 c_write_str("Unable to load private key\r\n");
3380 tried_pubkey_config
= TRUE
;
3382 /* Send a spurious AUTH_NONE to return to the top. */
3383 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3384 ssh2_pkt_addstring(username
);
3385 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3386 ssh2_pkt_addstring("none"); /* method */
3388 type
= AUTH_TYPE_NONE
;
3390 unsigned char *blob
, *sigdata
;
3391 int blob_len
, sigdata_len
;
3394 * We have loaded the private key and the server
3395 * has announced that it's willing to accept it.
3396 * Hallelujah. Generate a signature and send it.
3398 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3399 ssh2_pkt_addstring(username
);
3400 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3401 ssh2_pkt_addstring("publickey"); /* method */
3402 ssh2_pkt_addbool(TRUE
);
3403 ssh2_pkt_addstring(key
->alg
->name
);
3404 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3405 ssh2_pkt_addstring_start();
3406 ssh2_pkt_addstring_data(blob
, blob_len
);
3410 * The data to be signed is:
3414 * followed by everything so far placed in the
3417 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3418 sigdata
= smalloc(sigdata_len
);
3419 PUT_32BIT(sigdata
, 20);
3420 memcpy(sigdata
+4, ssh2_session_id
, 20);
3421 memcpy(sigdata
+24, pktout
.data
+5, pktout
.length
-5);
3422 blob
= key
->alg
->sign(key
->data
, sigdata
, sigdata_len
, &blob_len
);
3423 ssh2_pkt_addstring_start();
3424 ssh2_pkt_addstring_data(blob
, blob_len
);
3429 type
= AUTH_TYPE_PUBLICKEY
;
3431 } else if (method
== AUTH_PASSWORD
) {
3433 * We send the password packet lumped tightly together with
3434 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3435 * string long enough to make the total length of the two
3436 * packets constant. This should ensure that a passive
3437 * listener doing traffic analyis can't work out the length
3440 * For this to work, we need an assumption about the
3441 * maximum length of the password packet. I think 256 is
3442 * pretty conservative. Anyone using a password longer than
3443 * that probably doesn't have much to worry about from
3444 * people who find out how long their password is!
3446 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3447 ssh2_pkt_addstring(username
);
3448 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3449 ssh2_pkt_addstring("password");
3450 ssh2_pkt_addbool(FALSE
);
3451 ssh2_pkt_addstring(password
);
3454 * We'll include a string that's an exact multiple of the
3455 * cipher block size. If the cipher is NULL for some
3456 * reason, we don't do this trick at all because we gain
3462 stringlen
= (256 - deferred_len
);
3463 stringlen
+= cscipher
->blksize
- 1;
3464 stringlen
-= (stringlen
% cscipher
->blksize
);
3467 * Temporarily disable actual compression,
3468 * so we can guarantee to get this string
3469 * exactly the length we want it. The
3470 * compression-disabling routine should
3471 * return an integer indicating how many
3472 * bytes we should adjust our string length
3475 stringlen
-= cscomp
->disable_compression();
3477 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3478 ssh2_pkt_addstring_start();
3479 for (i
= 0; i
< stringlen
; i
++) {
3480 char c
= (char)random_byte();
3481 ssh2_pkt_addstring_data(&c
, 1);
3485 ssh_pkt_defersend();
3486 logevent("Sent password");
3487 type
= AUTH_TYPE_PASSWORD
;
3489 c_write_str("No supported authentication methods left to try!\r\n");
3490 logevent("No supported authentications offered. Disconnecting");
3491 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3492 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3493 ssh2_pkt_addstring("No supported authentication methods available");
3494 ssh2_pkt_addstring("en"); /* language tag */
3496 ssh_state
= SSH_STATE_CLOSED
;
3500 } while (!we_are_in
);
3503 * Now we're authenticated for the connection protocol. The
3504 * connection protocol will automatically have started at this
3505 * point; there's no need to send SERVICE_REQUEST.
3509 * So now create a channel with a session in it.
3511 ssh_channels
= newtree234(ssh_channelcmp
);
3512 mainchan
= smalloc(sizeof(struct ssh_channel
));
3513 mainchan
->localid
= alloc_channel_id();
3514 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3515 ssh2_pkt_addstring("session");
3516 ssh2_pkt_adduint32(mainchan
->localid
);
3517 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3518 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3520 crWaitUntilV(ispkt
);
3521 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3522 bombout(("Server refused to open a session"));
3524 /* FIXME: error data comes back in FAILURE packet */
3526 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3527 bombout(("Server's channel confirmation cited wrong channel"));
3530 mainchan
->remoteid
= ssh2_pkt_getuint32();
3531 mainchan
->type
= CHAN_MAINSESSION
;
3532 mainchan
->closes
= 0;
3533 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3534 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3535 mainchan
->v2
.outbuffer
= NULL
;
3536 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3537 add234(ssh_channels
, mainchan
);
3538 logevent("Opened channel for session");
3541 * Potentially enable X11 forwarding.
3543 if (cfg
.x11_forward
) {
3544 char proto
[20], data
[64];
3545 logevent("Requesting X11 forwarding");
3546 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3547 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3548 ssh2_pkt_adduint32(mainchan
->remoteid
);
3549 ssh2_pkt_addstring("x11-req");
3550 ssh2_pkt_addbool(1); /* want reply */
3551 ssh2_pkt_addbool(0); /* many connections */
3552 ssh2_pkt_addstring(proto
);
3553 ssh2_pkt_addstring(data
);
3554 ssh2_pkt_adduint32(0); /* screen number */
3558 crWaitUntilV(ispkt
);
3559 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3560 unsigned i
= ssh2_pkt_getuint32();
3561 struct ssh_channel
*c
;
3562 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3564 continue; /* nonexistent channel */
3565 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3567 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3569 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3570 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3571 bombout(("Server got confused by X11 forwarding request"));
3574 logevent("X11 forwarding refused");
3576 logevent("X11 forwarding enabled");
3577 ssh_X11_fwd_enabled
= TRUE
;
3582 * Potentially enable agent forwarding.
3584 if (cfg
.agentfwd
&& agent_exists()) {
3585 logevent("Requesting OpenSSH-style agent forwarding");
3586 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3587 ssh2_pkt_adduint32(mainchan
->remoteid
);
3588 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3589 ssh2_pkt_addbool(1); /* want reply */
3593 crWaitUntilV(ispkt
);
3594 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3595 unsigned i
= ssh2_pkt_getuint32();
3596 struct ssh_channel
*c
;
3597 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3599 continue; /* nonexistent channel */
3600 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3602 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3604 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3605 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3606 bombout(("Server got confused by agent forwarding request"));
3609 logevent("Agent forwarding refused");
3611 logevent("Agent forwarding enabled");
3612 ssh_agentfwd_enabled
= TRUE
;
3617 * Now allocate a pty for the session.
3620 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3621 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3622 ssh2_pkt_addstring("pty-req");
3623 ssh2_pkt_addbool(1); /* want reply */
3624 ssh2_pkt_addstring(cfg
.termtype
);
3625 ssh2_pkt_adduint32(cols
);
3626 ssh2_pkt_adduint32(rows
);
3627 ssh2_pkt_adduint32(0); /* pixel width */
3628 ssh2_pkt_adduint32(0); /* pixel height */
3629 ssh2_pkt_addstring_start();
3630 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3632 ssh_state
= SSH_STATE_INTERMED
;
3635 crWaitUntilV(ispkt
);
3636 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3637 unsigned i
= ssh2_pkt_getuint32();
3638 struct ssh_channel
*c
;
3639 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3641 continue; /* nonexistent channel */
3642 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3644 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3646 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3647 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3648 bombout(("Server got confused by pty request"));
3651 c_write_str("Server refused to allocate pty\r\n");
3652 ssh_editing
= ssh_echoing
= 1;
3654 logevent("Allocated pty");
3657 ssh_editing
= ssh_echoing
= 1;
3661 * Start a shell or a remote command.
3663 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3664 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3665 if (cfg
.ssh_subsys
) {
3666 ssh2_pkt_addstring("subsystem");
3667 ssh2_pkt_addbool(1); /* want reply */
3668 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3669 } else if (*cfg
.remote_cmd_ptr
) {
3670 ssh2_pkt_addstring("exec");
3671 ssh2_pkt_addbool(1); /* want reply */
3672 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3674 ssh2_pkt_addstring("shell");
3675 ssh2_pkt_addbool(1); /* want reply */
3679 crWaitUntilV(ispkt
);
3680 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3681 unsigned i
= ssh2_pkt_getuint32();
3682 struct ssh_channel
*c
;
3683 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3685 continue; /* nonexistent channel */
3686 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3688 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3689 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3690 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3691 bombout(("Server got confused by shell/command request"));
3694 bombout(("Server refused to start a shell/command"));
3697 logevent("Started a shell/command");
3700 ssh_state
= SSH_STATE_SESSION
;
3704 ssh_special(TS_EOF
);
3709 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3712 static int try_send
;
3716 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3717 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3720 unsigned i
= ssh2_pkt_getuint32();
3721 struct ssh_channel
*c
;
3722 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3724 continue; /* nonexistent channel */
3725 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3726 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3727 continue; /* extended but not stderr */
3728 ssh2_pkt_getstring(&data
, &length
);
3731 case CHAN_MAINSESSION
:
3732 from_backend(pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
,
3736 x11_send(c
->u
.x11
.s
, data
, length
);
3739 while (length
> 0) {
3740 if (c
->u
.a
.lensofar
< 4) {
3741 int l
= min(4 - c
->u
.a
.lensofar
, length
);
3742 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, data
, l
);
3743 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3745 if (c
->u
.a
.lensofar
== 4) {
3746 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
3747 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3748 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3750 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
3751 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3753 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, data
, l
);
3754 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3756 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3757 void *reply
, *sentreply
;
3759 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
3764 /* Fake SSH_AGENT_FAILURE. */
3765 sentreply
= "\0\0\0\1\5";
3768 ssh2_add_channel_data(c
, sentreply
, replylen
);
3772 sfree(c
->u
.a
.message
);
3773 c
->u
.a
.lensofar
= 0;
3779 * Enlarge the window again at the remote
3780 * side, just in case it ever runs down and
3781 * they fail to send us any more data.
3783 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3784 ssh2_pkt_adduint32(c
->remoteid
);
3785 ssh2_pkt_adduint32(length
);
3788 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
3789 ssh_state
= SSH_STATE_CLOSED
;
3790 logevent("Received disconnect message");
3792 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
3793 continue; /* exit status et al; ignore (FIXME?) */
3794 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
3795 unsigned i
= ssh2_pkt_getuint32();
3796 struct ssh_channel
*c
;
3798 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3800 continue; /* nonexistent channel */
3802 if (c
->type
== CHAN_X11
) {
3804 * Remote EOF on an X11 channel means we should
3805 * wrap up and close the channel ourselves.
3807 x11_close(c
->u
.x11
.s
);
3809 } else if (c
->type
== CHAN_AGENT
) {
3812 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
3813 unsigned i
= ssh2_pkt_getuint32();
3814 struct ssh_channel
*c
;
3816 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3818 continue; /* nonexistent channel */
3819 if (c
->closes
== 0) {
3820 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3821 ssh2_pkt_adduint32(c
->remoteid
);
3824 /* Do pre-close processing on the channel. */
3826 case CHAN_MAINSESSION
:
3827 break; /* nothing to see here, move along */
3833 del234(ssh_channels
, c
);
3834 sfree(c
->v2
.outbuffer
);
3838 * See if that was the last channel left open.
3840 if (count234(ssh_channels
) == 0) {
3841 logevent("All channels closed. Disconnecting");
3842 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3843 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3844 ssh2_pkt_addstring("All open channels closed");
3845 ssh2_pkt_addstring("en"); /* language tag */
3847 ssh_state
= SSH_STATE_CLOSED
;
3850 continue; /* remote sends close; ignore (FIXME) */
3851 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3852 unsigned i
= ssh2_pkt_getuint32();
3853 struct ssh_channel
*c
;
3854 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3856 continue; /* nonexistent channel */
3857 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3859 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
3863 struct ssh_channel
*c
;
3864 ssh2_pkt_getstring(&type
, &typelen
);
3865 c
= smalloc(sizeof(struct ssh_channel
));
3867 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
3868 if (!ssh_X11_fwd_enabled
)
3869 error
= "X11 forwarding is not enabled";
3870 else if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3871 error
= "Unable to open an X11 connection";
3875 } else if (typelen
== 22 &&
3876 !memcmp(type
, "auth-agent@openssh.com", 3)) {
3877 if (!ssh_agentfwd_enabled
)
3878 error
= "Agent forwarding is not enabled";
3880 c
->type
= CHAN_AGENT
; /* identify channel type */
3881 c
->u
.a
.lensofar
= 0;
3884 error
= "Unsupported channel type requested";
3887 c
->remoteid
= ssh2_pkt_getuint32();
3889 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
3890 ssh2_pkt_adduint32(c
->remoteid
);
3891 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
3892 ssh2_pkt_addstring(error
);
3893 ssh2_pkt_addstring("en"); /* language tag */
3897 c
->localid
= alloc_channel_id();
3899 c
->v2
.remwindow
= ssh2_pkt_getuint32();
3900 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3901 c
->v2
.outbuffer
= NULL
;
3902 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
3903 add234(ssh_channels
, c
);
3904 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
3905 ssh2_pkt_adduint32(c
->remoteid
);
3906 ssh2_pkt_adduint32(c
->localid
);
3907 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3908 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3912 bombout(("Strange packet received: type %d", pktin
.type
));
3917 * We have spare data. Add it to the channel buffer.
3919 ssh2_add_channel_data(mainchan
, in
, inlen
);
3924 struct ssh_channel
*c
;
3926 * Try to send data on all channels if we can.
3928 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++)
3937 * Handle the top-level SSH2 protocol.
3939 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
3941 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
3943 do_ssh2_authconn(in
, inlen
, ispkt
);
3947 * Called to set up the connection.
3949 * Returns an error message, or NULL on success.
3951 static char *ssh_init (char *host
, int port
, char **realhost
) {
3955 if(crypto_startup() == 0)
3956 return "Microsoft high encryption pack not installed!";
3963 p
= connect_to_host(host
, port
, realhost
);
3971 * Called to send data down the Telnet connection.
3973 static void ssh_send (char *buf
, int len
) {
3974 if (s
== NULL
|| ssh_protocol
== NULL
)
3977 ssh_protocol(buf
, len
, 0);
3981 * Called to set the size of the window from SSH's POV.
3983 static void ssh_size(void) {
3984 switch (ssh_state
) {
3985 case SSH_STATE_BEFORE_SIZE
:
3986 case SSH_STATE_PREPACKET
:
3987 case SSH_STATE_CLOSED
:
3988 break; /* do nothing */
3989 case SSH_STATE_INTERMED
:
3990 size_needed
= TRUE
; /* buffer for later */
3992 case SSH_STATE_SESSION
:
3994 if (ssh_version
== 1) {
3995 send_packet(SSH1_CMSG_WINDOW_SIZE
,
3996 PKT_INT
, rows
, PKT_INT
, cols
,
3997 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
3999 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4000 ssh2_pkt_adduint32(mainchan
->remoteid
);
4001 ssh2_pkt_addstring("window-change");
4002 ssh2_pkt_addbool(0);
4003 ssh2_pkt_adduint32(cols
);
4004 ssh2_pkt_adduint32(rows
);
4005 ssh2_pkt_adduint32(0);
4006 ssh2_pkt_adduint32(0);
4015 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4016 * can send an EOF and collect resulting output (e.g. `plink
4019 static void ssh_special (Telnet_Special code
) {
4020 if (code
== TS_EOF
) {
4021 if (ssh_state
!= SSH_STATE_SESSION
) {
4023 * Buffer the EOF in case we are pre-SESSION, so we can
4024 * send it as soon as we reach SESSION.
4030 if (ssh_version
== 1) {
4031 send_packet(SSH1_CMSG_EOF
, PKT_END
);
4033 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4034 ssh2_pkt_adduint32(mainchan
->remoteid
);
4037 logevent("Sent EOF message");
4038 } else if (code
== TS_PING
) {
4039 if (ssh_state
== SSH_STATE_CLOSED
|| ssh_state
== SSH_STATE_PREPACKET
)
4041 if (ssh_version
== 1) {
4042 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
4044 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4045 ssh2_pkt_addstring_start();
4053 static Socket
ssh_socket(void) { return s
; }
4055 static int ssh_sendok(void) { return ssh_send_ok
; }
4057 static int ssh_ldisc(int option
) {
4058 if (option
== LD_ECHO
) return ssh_echoing
;
4059 if (option
== LD_EDIT
) return ssh_editing
;
4063 Backend ssh_backend
= {