18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 fprintf(stderr, "%s\n", s); }
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
23 (s ? sk_close(s), s = NULL : 0), \
24 connection_fatal msg )
26 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
29 #define SSH1_CMSG_USER 4 /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
38 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
39 #define SSH1_SMSG_FAILURE 15 /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
43 #define SSH1_CMSG_EOF 19 /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
55 #define SSH1_MSG_IGNORE 32 /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
68 #define SSH1_AUTH_TIS 5 /* 0x5 */
69 #define SSH1_AUTH_CCARD 16 /* 0x10 */
71 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
72 /* Mask for protoflags we will echo back to server if seen */
73 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
75 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
76 #define SSH2_MSG_IGNORE 2 /* 0x2 */
77 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
78 #define SSH2_MSG_DEBUG 4 /* 0x4 */
79 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
80 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
81 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
82 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
83 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
84 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
85 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
86 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
87 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
88 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
96 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
97 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
98 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
99 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
100 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
101 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
102 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
103 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
104 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
105 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
106 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
107 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
108 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
110 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
111 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
112 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
113 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
114 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
115 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
116 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
117 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
118 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
119 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
120 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
121 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
122 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
123 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
124 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
126 static const char *const ssh2_disconnect_reasons
[] = {
128 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
129 "SSH_DISCONNECT_PROTOCOL_ERROR",
130 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
131 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
132 "SSH_DISCONNECT_MAC_ERROR",
133 "SSH_DISCONNECT_COMPRESSION_ERROR",
134 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
135 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
136 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
137 "SSH_DISCONNECT_CONNECTION_LOST",
138 "SSH_DISCONNECT_BY_APPLICATION",
139 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
140 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
141 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
142 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
145 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
146 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
147 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
148 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
150 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
153 * Various remote-bug flags.
155 #define BUG_CHOKES_ON_SSH1_IGNORE 1
156 #define BUG_SSH2_HMAC 2
158 #define GET_32BIT(cp) \
159 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
160 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
161 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
162 ((unsigned long)(unsigned char)(cp)[3]))
164 #define PUT_32BIT(cp, value) { \
165 (cp)[0] = (unsigned char)((value) >> 24); \
166 (cp)[1] = (unsigned char)((value) >> 16); \
167 (cp)[2] = (unsigned char)((value) >> 8); \
168 (cp)[3] = (unsigned char)(value); }
170 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
172 /* Coroutine mechanics for the sillier bits of the code */
173 #define crBegin1 static int crLine = 0;
174 #define crBegin2 switch(crLine) { case 0:;
175 #define crBegin crBegin1; crBegin2;
176 #define crFinish(z) } crLine = 0; return (z)
177 #define crFinishV } crLine = 0; return
178 #define crReturn(z) \
180 crLine=__LINE__; return (z); case __LINE__:;\
184 crLine=__LINE__; return; case __LINE__:;\
186 #define crStop(z) do{ crLine = 0; return (z); }while(0)
187 #define crStopV do{ crLine = 0; return; }while(0)
188 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
189 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
191 extern char *x11_init (Socket
*, char *, void *);
192 extern void x11_close (Socket
);
193 extern void x11_send (Socket
, char *, int);
194 extern void x11_invent_auth(char *, int, char *, int);
197 * Ciphers for SSH2. We miss out single-DES because it isn't
198 * supported; also 3DES and Blowfish are both done differently from
199 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
200 * endianness and different-sized keys.)
202 const static struct ssh2_ciphers
*ciphers
[] = {
208 const static struct ssh_kex
*kex_algs
[] = {
209 &ssh_diffiehellman_gex
,
210 &ssh_diffiehellman
};
212 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
214 static void nullmac_key(unsigned char *key
) { }
215 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
216 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
217 const static struct ssh_mac ssh_mac_none
= {
218 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
220 const static struct ssh_mac
*macs
[] = {
221 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
};
222 const static struct ssh_mac
*buggymacs
[] = {
223 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
};
225 static void ssh_comp_none_init(void) { }
226 static int ssh_comp_none_block(unsigned char *block
, int len
,
227 unsigned char **outblock
, int *outlen
) {
230 static int ssh_comp_none_disable(void) { return 0; }
231 const static struct ssh_compress ssh_comp_none
= {
233 ssh_comp_none_init
, ssh_comp_none_block
,
234 ssh_comp_none_init
, ssh_comp_none_block
,
235 ssh_comp_none_disable
237 extern const struct ssh_compress ssh_zlib
;
238 const static struct ssh_compress
*compressions
[] = {
239 &ssh_zlib
, &ssh_comp_none
};
241 enum { /* channel types */
248 * 2-3-4 tree storing channels.
251 unsigned remoteid
, localid
;
254 struct ssh2_data_channel
{
255 unsigned char *outbuffer
;
256 unsigned outbuflen
, outbufsize
;
257 unsigned remwindow
, remmaxpkt
;
260 struct ssh_agent_channel
{
261 unsigned char *message
;
262 unsigned char msglen
[4];
263 int lensofar
, totallen
;
265 struct ssh_x11_channel
{
280 static SHA_State exhash
, exhashbase
;
282 static Socket s
= NULL
;
284 static unsigned char session_key
[32];
285 static int ssh1_compressing
;
286 static int ssh1_remote_protoflags
;
287 static int ssh1_local_protoflags
;
288 static int ssh_agentfwd_enabled
;
289 static int ssh_X11_fwd_enabled
;
290 static int ssh_remote_bugs
;
291 static const struct ssh_cipher
*cipher
= NULL
;
292 static const struct ssh2_cipher
*cscipher
= NULL
;
293 static const struct ssh2_cipher
*sccipher
= NULL
;
294 static const struct ssh_mac
*csmac
= NULL
;
295 static const struct ssh_mac
*scmac
= NULL
;
296 static const struct ssh_compress
*cscomp
= NULL
;
297 static const struct ssh_compress
*sccomp
= NULL
;
298 static const struct ssh_kex
*kex
= NULL
;
299 static const struct ssh_signkey
*hostkey
= NULL
;
300 static unsigned char ssh2_session_id
[20];
301 int (*ssh_get_line
)(const char *prompt
, char *str
, int maxlen
,
304 static char *savedhost
;
305 static int savedport
;
306 static int ssh_send_ok
;
307 static int ssh_echoing
, ssh_editing
;
309 static tree234
*ssh_channels
; /* indexed by local id */
310 static struct ssh_channel
*mainchan
; /* primary session channel */
314 SSH_STATE_BEFORE_SIZE
,
318 } ssh_state
= SSH_STATE_PREPACKET
;
320 static int size_needed
= FALSE
, eof_needed
= FALSE
;
322 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
323 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
324 static unsigned char *deferred_send_data
= NULL
;
325 static int deferred_len
= 0, deferred_size
= 0;
327 static int ssh_version
;
328 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
329 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
330 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
331 static void ssh_size(void);
332 static void ssh_special (Telnet_Special
);
333 static void ssh2_try_send(struct ssh_channel
*c
);
334 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
336 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
338 static struct rdpkt1_state_tag
{
339 long len
, pad
, biglen
, to_read
;
340 unsigned long realcrc
, gotcrc
;
346 static struct rdpkt2_state_tag
{
347 long len
, pad
, payload
, packetlen
, maclen
;
350 unsigned long incoming_sequence
;
353 static int ssh_channelcmp(void *av
, void *bv
) {
354 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
355 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
356 if (a
->localid
< b
->localid
) return -1;
357 if (a
->localid
> b
->localid
) return +1;
360 static int ssh_channelfind(void *av
, void *bv
) {
361 unsigned *a
= (unsigned *)av
;
362 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
363 if (*a
< b
->localid
) return -1;
364 if (*a
> b
->localid
) return +1;
368 static void c_write (char *buf
, int len
) {
369 if ((flags
& FLAG_STDERR
)) {
371 for (i
= 0; i
< len
; i
++)
373 fputc(buf
[i
], stderr
);
376 from_backend(1, buf
, len
);
379 static void c_write_untrusted(char *buf
, int len
) {
381 for (i
= 0; i
< len
; i
++) {
384 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
389 static void c_write_str (char *buf
) {
390 c_write(buf
, strlen(buf
));
394 * Collect incoming data in the incoming packet buffer.
395 * Decipher and verify the packet when it is completely read.
396 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
397 * Update the *data and *datalen variables.
398 * Return the additional nr of bytes needed, or 0 when
399 * a complete packet is available.
401 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
403 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
412 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
413 while ((*datalen
) == 0)
415 st
->len
= (st
->len
<< 8) + **data
;
416 (*data
)++, (*datalen
)--;
420 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
421 st
->len
= 0x300; /* big enough to carry to end */
425 st
->pad
= 8 - (st
->len
% 8);
426 st
->biglen
= st
->len
+ st
->pad
;
427 pktin
.length
= st
->len
- 5;
429 if (pktin
.maxlen
< st
->biglen
) {
430 pktin
.maxlen
= st
->biglen
;
431 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+APIEXTRA
) :
432 srealloc(pktin
.data
, st
->biglen
+APIEXTRA
));
434 fatalbox("Out of memory");
437 st
->to_read
= st
->biglen
;
439 while (st
->to_read
> 0) {
440 st
->chunk
= st
->to_read
;
441 while ((*datalen
) == 0)
442 crReturn(st
->to_read
);
443 if (st
->chunk
> (*datalen
))
444 st
->chunk
= (*datalen
);
445 memcpy(st
->p
, *data
, st
->chunk
);
447 *datalen
-= st
->chunk
;
449 st
->to_read
-= st
->chunk
;
453 cipher
->decrypt(pktin
.data
, st
->biglen
);
455 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
456 for (st
->i
= 0; st
->i
< st
->biglen
; st
->i
++)
457 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
461 st
->realcrc
= crc32(pktin
.data
, st
->biglen
-4);
462 st
->gotcrc
= GET_32BIT(pktin
.data
+st
->biglen
-4);
463 if (st
->gotcrc
!= st
->realcrc
) {
464 bombout(("Incorrect CRC received on packet"));
468 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
470 if (ssh1_compressing
) {
471 unsigned char *decompblk
;
476 debug(("Packet payload pre-decompression:\n"));
477 for (i
= -1; i
< pktin
.length
; i
++)
478 debug((" %02x", (unsigned char)pktin
.body
[i
]));
482 zlib_decompress_block(pktin
.body
-1, pktin
.length
+1,
483 &decompblk
, &decomplen
);
485 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
486 pktin
.maxlen
= st
->pad
+ decomplen
;
487 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
);
488 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
490 fatalbox("Out of memory");
493 memcpy(pktin
.body
-1, decompblk
, decomplen
);
495 pktin
.length
= decomplen
-1;
499 debug(("Packet payload post-decompression:\n"));
500 for (i
= -1; i
< pktin
.length
; i
++)
501 debug((" %02x", (unsigned char)pktin
.body
[i
]));
507 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
508 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
509 pktin
.type
== SSH1_MSG_DEBUG
||
510 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
511 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
512 long strlen
= GET_32BIT(pktin
.body
);
513 if (strlen
+ 4 != pktin
.length
) {
514 bombout(("Received data packet with bogus string length"));
519 pktin
.type
= pktin
.body
[-1];
521 if (pktin
.type
== SSH1_MSG_DEBUG
) {
522 /* log debug message */
524 int strlen
= GET_32BIT(pktin
.body
);
525 strcpy(buf
, "Remote: ");
526 if (strlen
> 70) strlen
= 70;
527 memcpy(buf
+8, pktin
.body
+4, strlen
);
528 buf
[8+strlen
] = '\0';
531 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
536 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
537 /* log reason code in disconnect message */
539 int msglen
= GET_32BIT(pktin
.body
);
541 strcpy(buf
, "Remote sent disconnect: ");
542 nowlen
= strlen(buf
);
543 if (msglen
> sizeof(buf
)-nowlen
-1)
544 msglen
= sizeof(buf
)-nowlen
-1;
545 memcpy(buf
+nowlen
, pktin
.body
+4, msglen
);
546 buf
[nowlen
+msglen
] = '\0';
553 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
555 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
563 st
->cipherblk
= sccipher
->blksize
;
566 if (st
->cipherblk
< 8)
569 if (pktin
.maxlen
< st
->cipherblk
) {
570 pktin
.maxlen
= st
->cipherblk
;
571 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->cipherblk
+APIEXTRA
) :
572 srealloc(pktin
.data
, st
->cipherblk
+APIEXTRA
));
574 fatalbox("Out of memory");
578 * Acquire and decrypt the first block of the packet. This will
579 * contain the length and padding details.
581 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
582 while ((*datalen
) == 0)
583 crReturn(st
->cipherblk
-st
->i
);
584 pktin
.data
[st
->i
] = *(*data
)++;
588 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
593 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
596 * Now get the length and padding figures.
598 st
->len
= GET_32BIT(pktin
.data
);
599 st
->pad
= pktin
.data
[4];
602 * This enables us to deduce the payload length.
604 st
->payload
= st
->len
- st
->pad
- 1;
606 pktin
.length
= st
->payload
+ 5;
609 * So now we can work out the total packet length.
611 st
->packetlen
= st
->len
+ 4;
612 st
->maclen
= scmac ? scmac
->len
: 0;
615 * Adjust memory allocation if packet is too big.
617 if (pktin
.maxlen
< st
->packetlen
+st
->maclen
) {
618 pktin
.maxlen
= st
->packetlen
+st
->maclen
;
619 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
620 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
622 fatalbox("Out of memory");
626 * Read and decrypt the remainder of the packet.
628 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
; st
->i
++) {
629 while ((*datalen
) == 0)
630 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
631 pktin
.data
[st
->i
] = *(*data
)++;
634 /* Decrypt everything _except_ the MAC. */
636 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
637 st
->packetlen
- st
->cipherblk
);
640 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
641 for (st
->i
= 0; st
->i
< st
->packetlen
; st
->i
++)
642 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
649 if (scmac
&& !scmac
->verify(pktin
.data
, st
->len
+4, st
->incoming_sequence
)) {
650 bombout(("Incorrect MAC received on packet"));
653 st
->incoming_sequence
++; /* whether or not we MACed */
656 * Decompress packet payload.
659 unsigned char *newpayload
;
661 if (sccomp
&& sccomp
->decompress(pktin
.data
+5, pktin
.length
-5,
662 &newpayload
, &newlen
)) {
663 if (pktin
.maxlen
< newlen
+5) {
664 pktin
.maxlen
= newlen
+5;
665 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
666 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
668 fatalbox("Out of memory");
670 pktin
.length
= 5 + newlen
;
671 memcpy(pktin
.data
+5, newpayload
, newlen
);
673 debug(("Post-decompression payload:\r\n"));
674 for (st
->i
= 0; st
->i
< newlen
; st
->i
++)
675 debug((" %02x", (unsigned char)pktin
.data
[5+st
->i
]));
684 pktin
.type
= pktin
.data
[5];
686 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
687 goto next_packet
; /* FIXME: print DEBUG message */
689 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
690 /* log reason code in disconnect message */
692 int reason
= GET_32BIT(pktin
.data
+6);
693 int msglen
= GET_32BIT(pktin
.data
+10);
695 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
696 sprintf(buf
, "Received disconnect message (%s)",
697 ssh2_disconnect_reasons
[reason
]);
699 sprintf(buf
, "Received disconnect message (unknown type %d)", reason
);
702 strcpy(buf
, "Disconnection message text: ");
703 nowlen
= strlen(buf
);
704 if (msglen
> sizeof(buf
)-nowlen
-1)
705 msglen
= sizeof(buf
)-nowlen
-1;
706 memcpy(buf
+nowlen
, pktin
.data
+14, msglen
);
707 buf
[nowlen
+msglen
] = '\0';
714 static void ssh1_pktout_size(int len
) {
717 len
+= 5; /* type and CRC */
721 pktout
.length
= len
-5;
722 if (pktout
.maxlen
< biglen
) {
723 pktout
.maxlen
= biglen
;
725 /* Allocate enough buffer space for extra block
726 * for MS CryptEncrypt() */
727 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+12) :
728 srealloc(pktout
.data
, biglen
+12));
730 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+4) :
731 srealloc(pktout
.data
, biglen
+4));
734 fatalbox("Out of memory");
736 pktout
.body
= pktout
.data
+4+pad
+1;
739 static void s_wrpkt_start(int type
, int len
) {
740 ssh1_pktout_size(len
);
744 static int s_wrpkt_prepare(void) {
745 int pad
, len
, biglen
, i
;
748 pktout
.body
[-1] = pktout
.type
;
751 debug(("Packet payload pre-compression:\n"));
752 for (i
= -1; i
< pktout
.length
; i
++)
753 debug((" %02x", (unsigned char)pktout
.body
[i
]));
757 if (ssh1_compressing
) {
758 unsigned char *compblk
;
760 zlib_compress_block(pktout
.body
-1, pktout
.length
+1,
762 ssh1_pktout_size(complen
-1);
763 memcpy(pktout
.body
-1, compblk
, complen
);
766 debug(("Packet payload post-compression:\n"));
767 for (i
= -1; i
< pktout
.length
; i
++)
768 debug((" %02x", (unsigned char)pktout
.body
[i
]));
773 len
= pktout
.length
+ 5; /* type and CRC */
777 for (i
=0; i
<pad
; i
++)
778 pktout
.data
[i
+4] = random_byte();
779 crc
= crc32(pktout
.data
+4, biglen
-4);
780 PUT_32BIT(pktout
.data
+biglen
, crc
);
781 PUT_32BIT(pktout
.data
, len
);
784 debug(("Sending packet len=%d\r\n", biglen
+4));
785 for (i
= 0; i
< biglen
+4; i
++)
786 debug((" %02x", (unsigned char)pktout
.data
[i
]));
790 cipher
->encrypt(pktout
.data
+4, biglen
);
795 static void s_wrpkt(void) {
797 len
= s_wrpkt_prepare();
798 sk_write(s
, pktout
.data
, len
);
801 static void s_wrpkt_defer(void) {
803 len
= s_wrpkt_prepare();
804 if (deferred_len
+ len
> deferred_size
) {
805 deferred_size
= deferred_len
+ len
+ 128;
806 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
808 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
813 * Construct a packet with the specified contents.
815 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
817 unsigned char *p
, *argp
, argchar
;
818 unsigned long argint
;
819 int pktlen
, argtype
, arglen
;
823 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
826 (void) va_arg(ap1
, int);
830 (void) va_arg(ap1
, char);
834 (void) va_arg(ap1
, unsigned char *);
835 arglen
= va_arg(ap1
, int);
839 argp
= va_arg(ap1
, unsigned char *);
840 arglen
= strlen(argp
);
841 pktlen
+= 4 + arglen
;
844 bn
= va_arg(ap1
, Bignum
);
845 pktlen
+= ssh1_bignum_length(bn
);
852 s_wrpkt_start(pkttype
, pktlen
);
855 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
858 argint
= va_arg(ap2
, int);
859 PUT_32BIT(p
, argint
);
863 argchar
= va_arg(ap2
, unsigned char);
868 argp
= va_arg(ap2
, unsigned char *);
869 arglen
= va_arg(ap2
, int);
870 memcpy(p
, argp
, arglen
);
874 argp
= va_arg(ap2
, unsigned char *);
875 arglen
= strlen(argp
);
876 PUT_32BIT(p
, arglen
);
877 memcpy(p
+ 4, argp
, arglen
);
881 bn
= va_arg(ap2
, Bignum
);
882 p
+= ssh1_write_bignum(p
, bn
);
888 static void send_packet(int pkttype
, ...) {
890 va_start(ap1
, pkttype
);
891 va_start(ap2
, pkttype
);
892 construct_packet(pkttype
, ap1
, ap2
);
896 static void defer_packet(int pkttype
, ...) {
898 va_start(ap1
, pkttype
);
899 va_start(ap2
, pkttype
);
900 construct_packet(pkttype
, ap1
, ap2
);
904 static int ssh_versioncmp(char *a
, char *b
) {
906 unsigned long av
, bv
;
908 av
= strtoul(a
, &ae
, 10);
909 bv
= strtoul(b
, &be
, 10);
910 if (av
!= bv
) return (av
< bv ?
-1 : +1);
911 if (*ae
== '.') ae
++;
912 if (*be
== '.') be
++;
913 av
= strtoul(ae
, &ae
, 10);
914 bv
= strtoul(be
, &be
, 10);
915 if (av
!= bv
) return (av
< bv ?
-1 : +1);
921 * Utility routines for putting an SSH-protocol `string' and
922 * `uint32' into a SHA state.
925 static void sha_string(SHA_State
*s
, void *str
, int len
) {
926 unsigned char lenblk
[4];
927 PUT_32BIT(lenblk
, len
);
928 SHA_Bytes(s
, lenblk
, 4);
929 SHA_Bytes(s
, str
, len
);
932 static void sha_uint32(SHA_State
*s
, unsigned i
) {
933 unsigned char intblk
[4];
934 PUT_32BIT(intblk
, i
);
935 SHA_Bytes(s
, intblk
, 4);
939 * SSH2 packet construction functions.
941 static void ssh2_pkt_ensure(int length
) {
942 if (pktout
.maxlen
< length
) {
943 pktout
.maxlen
= length
+ 256;
944 pktout
.data
= (pktout
.data
== NULL ?
smalloc(pktout
.maxlen
+APIEXTRA
) :
945 srealloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
947 fatalbox("Out of memory");
950 static void ssh2_pkt_adddata(void *data
, int len
) {
951 pktout
.length
+= len
;
952 ssh2_pkt_ensure(pktout
.length
);
953 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
955 static void ssh2_pkt_addbyte(unsigned char byte
) {
956 ssh2_pkt_adddata(&byte
, 1);
958 static void ssh2_pkt_init(int pkt_type
) {
960 ssh2_pkt_addbyte((unsigned char)pkt_type
);
962 static void ssh2_pkt_addbool(unsigned char value
) {
963 ssh2_pkt_adddata(&value
, 1);
965 static void ssh2_pkt_adduint32(unsigned long value
) {
968 ssh2_pkt_adddata(x
, 4);
970 static void ssh2_pkt_addstring_start(void) {
971 ssh2_pkt_adduint32(0);
972 pktout
.savedpos
= pktout
.length
;
974 static void ssh2_pkt_addstring_str(char *data
) {
975 ssh2_pkt_adddata(data
, strlen(data
));
976 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
977 pktout
.length
- pktout
.savedpos
);
979 static void ssh2_pkt_addstring_data(char *data
, int len
) {
980 ssh2_pkt_adddata(data
, len
);
981 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
982 pktout
.length
- pktout
.savedpos
);
984 static void ssh2_pkt_addstring(char *data
) {
985 ssh2_pkt_addstring_start();
986 ssh2_pkt_addstring_str(data
);
988 static char *ssh2_mpint_fmt(Bignum b
, int *len
) {
990 int i
, n
= (bignum_bitcount(b
)+7)/8;
993 fatalbox("out of memory");
995 for (i
= 1; i
<= n
; i
++)
996 p
[i
] = bignum_byte(b
, n
-i
);
998 while (i
<= n
&& p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
1000 memmove(p
, p
+i
, n
+1-i
);
1004 static void ssh2_pkt_addmp(Bignum b
) {
1007 p
= ssh2_mpint_fmt(b
, &len
);
1008 ssh2_pkt_addstring_start();
1009 ssh2_pkt_addstring_data(p
, len
);
1014 * Construct an SSH2 final-form packet: compress it, encrypt it,
1015 * put the MAC on it. Final packet, ready to be sent, is stored in
1016 * pktout.data. Total length is returned.
1018 static int ssh2_pkt_construct(void) {
1019 int cipherblk
, maclen
, padding
, i
;
1020 static unsigned long outgoing_sequence
= 0;
1023 * Compress packet payload.
1026 debug(("Pre-compression payload:\r\n"));
1027 for (i
= 5; i
< pktout
.length
; i
++)
1028 debug((" %02x", (unsigned char)pktout
.data
[i
]));
1032 unsigned char *newpayload
;
1034 if (cscomp
&& cscomp
->compress(pktout
.data
+5, pktout
.length
-5,
1035 &newpayload
, &newlen
)) {
1037 ssh2_pkt_adddata(newpayload
, newlen
);
1043 * Add padding. At least four bytes, and must also bring total
1044 * length (minus MAC) up to a multiple of the block size.
1046 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1047 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1049 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1050 maclen
= csmac ? csmac
->len
: 0;
1051 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1052 pktout
.data
[4] = padding
;
1053 for (i
= 0; i
< padding
; i
++)
1054 pktout
.data
[pktout
.length
+ i
] = random_byte();
1055 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1057 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1059 outgoing_sequence
++; /* whether or not we MACed */
1062 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
1063 for (i
= 0; i
< pktout
.length
+padding
; i
++)
1064 debug((" %02x", (unsigned char)pktout
.data
[i
]));
1069 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1071 /* Ready-to-send packet starts at pktout.data. We return length. */
1072 return pktout
.length
+ padding
+ maclen
;
1076 * Construct and send an SSH2 packet immediately.
1078 static void ssh2_pkt_send(void) {
1079 int len
= ssh2_pkt_construct();
1080 sk_write(s
, pktout
.data
, len
);
1084 * Construct an SSH2 packet and add it to a deferred data block.
1085 * Useful for sending multiple packets in a single sk_write() call,
1086 * to prevent a traffic-analysing listener from being able to work
1087 * out the length of any particular packet (such as the password
1090 * Note that because SSH2 sequence-numbers its packets, this can
1091 * NOT be used as an m4-style `defer' allowing packets to be
1092 * constructed in one order and sent in another.
1094 static void ssh2_pkt_defer(void) {
1095 int len
= ssh2_pkt_construct();
1096 if (deferred_len
+ len
> deferred_size
) {
1097 deferred_size
= deferred_len
+ len
+ 128;
1098 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1100 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
1101 deferred_len
+= len
;
1105 * Send the whole deferred data block constructed by
1106 * ssh2_pkt_defer() or SSH1's defer_packet().
1108 static void ssh_pkt_defersend(void) {
1109 sk_write(s
, deferred_send_data
, deferred_len
);
1110 deferred_len
= deferred_size
= 0;
1111 sfree(deferred_send_data
);
1112 deferred_send_data
= NULL
;
1116 void bndebug(char *string
, Bignum b
) {
1119 p
= ssh2_mpint_fmt(b
, &len
);
1120 debug(("%s", string
));
1121 for (i
= 0; i
< len
; i
++)
1122 debug((" %02x", p
[i
]));
1128 static void sha_mpint(SHA_State
*s
, Bignum b
) {
1131 p
= ssh2_mpint_fmt(b
, &len
);
1132 sha_string(s
, p
, len
);
1137 * SSH2 packet decode functions.
1139 static unsigned long ssh2_pkt_getuint32(void) {
1140 unsigned long value
;
1141 if (pktin
.length
- pktin
.savedpos
< 4)
1142 return 0; /* arrgh, no way to decline (FIXME?) */
1143 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1144 pktin
.savedpos
+= 4;
1147 static int ssh2_pkt_getbool(void) {
1148 unsigned long value
;
1149 if (pktin
.length
- pktin
.savedpos
< 1)
1150 return 0; /* arrgh, no way to decline (FIXME?) */
1151 value
= pktin
.data
[pktin
.savedpos
] != 0;
1155 static void ssh2_pkt_getstring(char **p
, int *length
) {
1157 if (pktin
.length
- pktin
.savedpos
< 4)
1159 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1160 pktin
.savedpos
+= 4;
1161 if (pktin
.length
- pktin
.savedpos
< *length
)
1163 *p
= pktin
.data
+pktin
.savedpos
;
1164 pktin
.savedpos
+= *length
;
1166 static Bignum
ssh2_pkt_getmp(void) {
1171 ssh2_pkt_getstring(&p
, &length
);
1175 bombout(("internal error: Can't handle negative mpints"));
1178 b
= bignum_from_bytes(p
, length
);
1183 * Examine the remote side's version string and compare it against
1184 * a list of known buggy implementations.
1186 static void ssh_detect_bugs(char *vstring
) {
1187 char *imp
; /* pointer to implementation part */
1189 imp
+= strcspn(imp
, "-");
1191 imp
+= strcspn(imp
, "-");
1194 ssh_remote_bugs
= 0;
1196 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1197 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1198 !strcmp(imp
, "1.2.22")) {
1200 * These versions don't support SSH1_MSG_IGNORE, so we have
1201 * to use a different defence against password length
1204 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1205 logevent("We believe remote version has SSH1 ignore bug");
1208 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1209 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1210 !strncmp(imp
, "2.1 ", 4)) {
1212 * These versions have the HMAC bug.
1214 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1215 logevent("We believe remote version has SSH2 HMAC bug");
1219 static int do_ssh_init(unsigned char c
) {
1221 static char version
[10];
1222 static char *vstring
;
1223 static int vstrsize
;
1229 /* Search for the string "SSH-" in the input. */
1232 static const int transS
[] = { 1, 2, 2, 1 };
1233 static const int transH
[] = { 0, 0, 3, 0 };
1234 static const int transminus
[] = { 0, 0, 0, -1 };
1235 if (c
== 'S') i
= transS
[i
];
1236 else if (c
== 'H') i
= transH
[i
];
1237 else if (c
== '-') i
= transminus
[i
];
1241 crReturn(1); /* get another character */
1244 vstring
= smalloc(16);
1246 strcpy(vstring
, "SSH-");
1250 crReturn(1); /* get another char */
1251 if (vslen
>= vstrsize
-1) {
1253 vstring
= srealloc(vstring
, vstrsize
);
1255 vstring
[vslen
++] = c
;
1260 } else if (i
< sizeof(version
)-1)
1267 ssh_agentfwd_enabled
= FALSE
;
1268 rdpkt2_state
.incoming_sequence
= 0;
1271 vlog
= smalloc(20 + vslen
);
1272 sprintf(vlog
, "Server version: %s", vstring
);
1273 ssh_detect_bugs(vstring
);
1274 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1279 * Server version "1.99" means we can choose whether we use v1
1280 * or v2 protocol. Choice is based on cfg.sshprot.
1282 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1284 * This is a v2 server. Begin v2 protocol.
1286 char verstring
[80], vlog
[100];
1287 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1288 SHA_Init(&exhashbase
);
1290 * Hash our version string and their version string.
1292 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1293 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1294 sprintf(vlog
, "We claim version: %s", verstring
);
1296 strcat(verstring
, "\n");
1297 logevent("Using SSH protocol version 2");
1298 sk_write(s
, verstring
, strlen(verstring
));
1299 ssh_protocol
= ssh2_protocol
;
1301 s_rdpkt
= ssh2_rdpkt
;
1304 * This is a v1 server. Begin v1 protocol.
1306 char verstring
[80], vlog
[100];
1307 sprintf(verstring
, "SSH-%s-%s",
1308 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1310 sprintf(vlog
, "We claim version: %s", verstring
);
1312 strcat(verstring
, "\n");
1313 logevent("Using SSH protocol version 1");
1314 sk_write(s
, verstring
, strlen(verstring
));
1315 ssh_protocol
= ssh1_protocol
;
1317 s_rdpkt
= ssh1_rdpkt
;
1319 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1326 static void ssh_gotdata(unsigned char *data
, int datalen
)
1331 * To begin with, feed the characters one by one to the
1332 * protocol initialisation / selection function do_ssh_init().
1333 * When that returns 0, we're done with the initial greeting
1334 * exchange and can move on to packet discipline.
1339 crReturnV
; /* more data please */
1340 ret
= do_ssh_init(*data
);
1347 * We emerge from that loop when the initial negotiation is
1348 * over and we have selected an s_rdpkt function. Now pass
1349 * everything to s_rdpkt, and then pass the resulting packets
1350 * to the proper protocol handler.
1355 while (datalen
> 0) {
1356 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
1357 ssh_protocol(NULL
, 0, 1);
1358 if (ssh_state
== SSH_STATE_CLOSED
) {
1368 static int ssh_closing (Plug plug
, char *error_msg
, int error_code
, int calling_back
) {
1369 ssh_state
= SSH_STATE_CLOSED
;
1373 /* A socket error has occurred. */
1374 connection_fatal (error_msg
);
1376 /* Otherwise, the remote side closed the connection normally. */
1381 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
) {
1382 ssh_gotdata (data
, len
);
1383 if (ssh_state
== SSH_STATE_CLOSED
) {
1394 * Connect to specified host and port.
1395 * Returns an error message, or NULL on success.
1396 * Also places the canonical host name into `realhost'.
1398 static char *connect_to_host(char *host
, int port
, char **realhost
)
1400 static struct plug_function_table fn_table
= {
1403 }, *fn_table_ptr
= &fn_table
;
1412 savedhost
= smalloc(1+strlen(host
));
1414 fatalbox("Out of memory");
1415 strcpy(savedhost
, host
);
1418 port
= 22; /* default ssh port */
1431 addr
= sk_namelookup(host
, realhost
);
1432 if ( (err
= sk_addr_error(addr
)) )
1442 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1443 if ( (err
= sk_socket_error(s
)) )
1447 sk_write(s
, "connect ", 8);
1448 sk_write(s
, FWhost
, strlen(FWhost
));
1451 sprintf(buf
, " %d\n", FWport
);
1452 sk_write(s
, buf
, strlen(buf
));
1460 * Handle the key exchange and user authentication phases.
1462 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1465 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1466 unsigned char cookie
[8];
1467 struct RSAKey servkey
, hostkey
;
1468 struct MD5Context md5c
;
1469 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1470 static int tried_publickey
;
1471 static unsigned char session_id
[16];
1473 static char username
[100];
1477 if (!ispkt
) crWaitUntil(ispkt
);
1479 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1480 bombout(("Public key packet not received"));
1484 logevent("Received public keys");
1486 memcpy(cookie
, pktin
.body
, 8);
1488 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1489 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1492 * Log the host key fingerprint.
1496 logevent("Host key fingerprint is:");
1497 strcpy(logmsg
, " ");
1498 hostkey
.comment
= NULL
;
1499 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1504 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+8+i
+j
);
1505 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1506 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1508 ssh1_local_protoflags
= ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1509 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1512 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1513 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1514 MD5Update(&md5c
, pktin
.body
, 8);
1515 MD5Final(session_id
, &md5c
);
1517 for (i
=0; i
<32; i
++)
1518 session_key
[i
] = random_byte();
1520 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1522 rsabuf
= smalloc(len
);
1524 fatalbox("Out of memory");
1527 * Verify the host key.
1531 * First format the key into a string.
1533 int len
= rsastr_len(&hostkey
);
1534 char fingerprint
[100];
1535 char *keystr
= smalloc(len
);
1537 fatalbox("Out of memory");
1538 rsastr_fmt(keystr
, &hostkey
);
1539 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1540 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1544 for (i
=0; i
<32; i
++) {
1545 rsabuf
[i
] = session_key
[i
];
1547 rsabuf
[i
] ^= session_id
[i
];
1550 if (hostkey
.bytes
> servkey
.bytes
) {
1551 rsaencrypt(rsabuf
, 32, &servkey
);
1552 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1554 rsaencrypt(rsabuf
, 32, &hostkey
);
1555 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1558 logevent("Encrypted session key");
1560 switch (cfg
.cipher
) {
1561 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
; break;
1562 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
; break;
1563 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
; break;
1565 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1566 cipher_type
= SSH_CIPHER_3DES
;
1569 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1570 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1571 cipher_type
= SSH_CIPHER_3DES
;
1572 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1573 bombout(("Server violates SSH 1 protocol by "
1574 "not supporting 3DES encryption"));
1578 switch (cipher_type
) {
1579 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1580 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1581 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1584 send_packet(SSH1_CMSG_SESSION_KEY
,
1585 PKT_CHAR
, cipher_type
,
1586 PKT_DATA
, cookie
, 8,
1587 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1588 PKT_DATA
, rsabuf
, len
,
1589 PKT_INT
, ssh1_local_protoflags
,
1592 logevent("Trying to enable encryption...");
1596 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1597 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1599 cipher
->sesskey(session_key
);
1603 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1604 bombout(("Encryption not successfully enabled"));
1608 logevent("Successfully started encryption");
1614 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1616 if (!ssh_get_line("login as: ",
1617 username
, sizeof(username
), FALSE
)) {
1619 * get_line failed to get a username.
1622 logevent("No username provided. Abandoning session.");
1623 ssh_state
= SSH_STATE_CLOSED
;
1627 c_write_str("login as: ");
1630 crWaitUntil(!ispkt
);
1631 while (inlen
--) switch (c
= *in
++) {
1638 c_write_str("\b \b");
1644 c_write_str("\b \b");
1653 if (((c
>= ' ' && c
<= '~') ||
1654 ((unsigned char)c
>= 160)) && pos
< 40) {
1655 username
[pos
++] = c
;
1661 c_write_str("\r\n");
1662 username
[strcspn(username
, "\n\r")] = '\0';
1665 strncpy(username
, cfg
.username
, 99);
1666 username
[99] = '\0';
1669 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1671 char userlog
[22+sizeof(username
)];
1672 sprintf(userlog
, "Sent username \"%s\"", username
);
1674 if (flags
& FLAG_INTERACTIVE
&&
1675 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1676 strcat(userlog
, "\r\n");
1677 c_write_str(userlog
);
1684 tried_publickey
= 0;
1686 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1687 static char password
[100];
1688 static char prompt
[200];
1691 static int pwpkt_type
;
1693 * Show password prompt, having first obtained it via a TIS
1694 * or CryptoCard exchange if we're doing TIS or CryptoCard
1697 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1698 if (agent_exists()) {
1700 * Attempt RSA authentication using Pageant.
1702 static unsigned char request
[5], *response
, *p
;
1703 static int responselen
;
1704 static int i
, nkeys
;
1705 static int authed
= FALSE
;
1708 logevent("Pageant is running. Requesting keys.");
1710 /* Request the keys held by the agent. */
1711 PUT_32BIT(request
, 1);
1712 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1713 agent_query(request
, 5, &r
, &responselen
);
1714 response
= (unsigned char *)r
;
1715 if (response
&& responselen
>= 5 &&
1716 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
1718 nkeys
= GET_32BIT(p
); p
+= 4;
1719 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1721 for (i
= 0; i
< nkeys
; i
++) {
1722 static struct RSAKey key
;
1723 static Bignum challenge
;
1724 static char *commentp
;
1725 static int commentlen
;
1727 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1730 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1731 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1732 commentlen
= GET_32BIT(p
); p
+= 4;
1733 commentp
= p
; p
+= commentlen
;
1734 send_packet(SSH1_CMSG_AUTH_RSA
,
1735 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1737 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1738 logevent("Key refused");
1741 logevent("Received RSA challenge");
1742 ssh1_read_bignum(pktin
.body
, &challenge
);
1744 char *agentreq
, *q
, *ret
;
1746 len
= 1 + 4; /* message type, bit count */
1747 len
+= ssh1_bignum_length(key
.exponent
);
1748 len
+= ssh1_bignum_length(key
.modulus
);
1749 len
+= ssh1_bignum_length(challenge
);
1750 len
+= 16; /* session id */
1751 len
+= 4; /* response format */
1752 agentreq
= smalloc(4 + len
);
1753 PUT_32BIT(agentreq
, len
);
1755 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1756 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
1758 q
+= ssh1_write_bignum(q
, key
.exponent
);
1759 q
+= ssh1_write_bignum(q
, key
.modulus
);
1760 q
+= ssh1_write_bignum(q
, challenge
);
1761 memcpy(q
, session_id
, 16); q
+= 16;
1762 PUT_32BIT(q
, 1); /* response format */
1763 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1766 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1767 logevent("Sending Pageant's response");
1768 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1769 PKT_DATA
, ret
+5, 16, PKT_END
);
1772 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1773 logevent("Pageant's response accepted");
1774 if (flags
& FLAG_VERBOSE
) {
1775 c_write_str("Authenticated using RSA key \"");
1776 c_write(commentp
, commentlen
);
1777 c_write_str("\" from agent\r\n");
1781 logevent("Pageant's response not accepted");
1783 logevent("Pageant failed to answer challenge");
1787 logevent("No reply received from Pageant");
1790 freebn(key
.exponent
);
1791 freebn(key
.modulus
);
1800 if (*cfg
.keyfile
&& !tried_publickey
)
1801 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1803 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1805 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1806 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1807 logevent("Requested TIS authentication");
1808 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1810 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1811 logevent("TIS authentication declined");
1812 if (flags
& FLAG_INTERACTIVE
)
1813 c_write_str("TIS authentication refused.\r\n");
1815 int challengelen
= ((pktin
.body
[0] << 24) |
1816 (pktin
.body
[1] << 16) |
1817 (pktin
.body
[2] << 8) |
1819 logevent("Received TIS challenge");
1820 if (challengelen
> sizeof(prompt
)-1)
1821 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1822 memcpy(prompt
, pktin
.body
+4, challengelen
);
1823 prompt
[challengelen
] = '\0';
1826 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1828 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1829 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1830 logevent("Requested CryptoCard authentication");
1831 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1833 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1834 logevent("CryptoCard authentication declined");
1835 c_write_str("CryptoCard authentication refused.\r\n");
1837 int challengelen
= ((pktin
.body
[0] << 24) |
1838 (pktin
.body
[1] << 16) |
1839 (pktin
.body
[2] << 8) |
1841 logevent("Received CryptoCard challenge");
1842 if (challengelen
> sizeof(prompt
)-1)
1843 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1844 memcpy(prompt
, pktin
.body
+4, challengelen
);
1845 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1846 sizeof(prompt
)-challengelen
);
1847 prompt
[sizeof(prompt
)-1] = '\0';
1850 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1851 sprintf(prompt
, "%.90s@%.90s's password: ",
1852 username
, savedhost
);
1854 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1855 char *comment
= NULL
;
1856 if (flags
& FLAG_VERBOSE
)
1857 c_write_str("Trying public key authentication.\r\n");
1858 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1859 if (flags
& FLAG_VERBOSE
)
1860 c_write_str("No passphrase required.\r\n");
1863 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1868 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
1870 * get_line failed to get a password (for example
1871 * because one was supplied on the command line
1872 * which has already failed to work). Terminate.
1874 logevent("No more passwords to try");
1875 ssh_state
= SSH_STATE_CLOSED
;
1879 c_write_str(prompt
);
1883 crWaitUntil(!ispkt
);
1884 while (inlen
--) switch (c
= *in
++) {
1901 if (((c
>= ' ' && c
<= '~') ||
1902 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1903 password
[pos
++] = c
;
1907 c_write_str("\r\n");
1911 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1913 * Try public key authentication with the specified
1916 static struct RSAKey pubkey
;
1917 static Bignum challenge
, response
;
1919 static unsigned char buffer
[32];
1921 tried_publickey
= 1;
1922 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1924 c_write_str("Couldn't load public key from ");
1925 c_write_str(cfg
.keyfile
);
1926 c_write_str(".\r\n");
1927 continue; /* go and try password */
1930 c_write_str("Wrong passphrase.\r\n");
1931 tried_publickey
= 0;
1932 continue; /* try again */
1936 * Send a public key attempt.
1938 send_packet(SSH1_CMSG_AUTH_RSA
,
1939 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1942 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1943 c_write_str("Server refused our public key.\r\n");
1944 continue; /* go and try password */
1946 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1947 bombout(("Bizarre response to offer of public key"));
1950 ssh1_read_bignum(pktin
.body
, &challenge
);
1951 response
= rsadecrypt(challenge
, &pubkey
);
1952 freebn(pubkey
.private_exponent
); /* burn the evidence */
1954 for (i
= 0; i
< 32; i
++) {
1955 buffer
[i
] = bignum_byte(response
, 31-i
);
1959 MD5Update(&md5c
, buffer
, 32);
1960 MD5Update(&md5c
, session_id
, 16);
1961 MD5Final(buffer
, &md5c
);
1963 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1964 PKT_DATA
, buffer
, 16, PKT_END
);
1967 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1968 if (flags
& FLAG_VERBOSE
)
1969 c_write_str("Failed to authenticate with our public key.\r\n");
1970 continue; /* go and try password */
1971 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1972 bombout(("Bizarre response to RSA authentication response"));
1976 break; /* we're through! */
1978 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1980 * Defence against traffic analysis: we send a
1981 * whole bunch of packets containing strings of
1982 * different lengths. One of these strings is the
1983 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1984 * The others are all random data in
1985 * SSH1_MSG_IGNORE packets. This way a passive
1986 * listener can't tell which is the password, and
1987 * hence can't deduce the password length.
1989 * Anybody with a password length greater than 16
1990 * bytes is going to have enough entropy in their
1991 * password that a listener won't find it _that_
1992 * much help to know how long it is. So what we'll
1995 * - if password length < 16, we send 15 packets
1996 * containing string lengths 1 through 15
1998 * - otherwise, we let N be the nearest multiple
1999 * of 8 below the password length, and send 8
2000 * packets containing string lengths N through
2001 * N+7. This won't obscure the order of
2002 * magnitude of the password length, but it will
2003 * introduce a bit of extra uncertainty.
2005 * A few servers (the old 1.2.18 through 1.2.22)
2006 * can't deal with SSH1_MSG_IGNORE. For these
2007 * servers, we need an alternative defence. We make
2008 * use of the fact that the password is interpreted
2009 * as a C string: so we can append a NUL, then some
2012 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2017 len
= strlen(password
);
2018 if (len
< sizeof(string
)) {
2020 strcpy(string
, password
);
2021 len
++; /* cover the zero byte */
2022 while (len
< sizeof(string
)) {
2023 string
[len
++] = (char)random_byte();
2028 send_packet(pwpkt_type
, PKT_INT
, len
,
2029 PKT_DATA
, s
, len
, PKT_END
);
2031 int bottom
, top
, pwlen
, i
;
2034 pwlen
= strlen(password
);
2036 bottom
= 0; /* zero length passwords are OK! :-) */
2039 bottom
= pwlen
&~ 7;
2043 assert(pwlen
>= bottom
&& pwlen
<= top
);
2045 randomstr
= smalloc(top
+1);
2047 for (i
= bottom
; i
<= top
; i
++) {
2049 defer_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2051 for (j
= 0; j
< i
; j
++) {
2053 randomstr
[j
] = random_byte();
2054 } while (randomstr
[j
] == '\0');
2056 randomstr
[i
] = '\0';
2057 defer_packet(SSH1_MSG_IGNORE
,
2058 PKT_STR
, randomstr
, PKT_END
);
2061 ssh_pkt_defersend();
2064 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2067 logevent("Sent password");
2068 memset(password
, 0, strlen(password
));
2070 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2071 if (flags
& FLAG_VERBOSE
)
2072 c_write_str("Access denied\r\n");
2073 logevent("Authentication refused");
2074 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2075 logevent("Received disconnect request");
2076 ssh_state
= SSH_STATE_CLOSED
;
2078 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2079 bombout(("Strange packet received, type %d", pktin
.type
));
2084 logevent("Authentication successful");
2089 void sshfwd_close(struct ssh_channel
*c
) {
2090 if (c
&& !c
->closes
) {
2091 if (ssh_version
== 1) {
2092 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
, PKT_END
);
2094 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2095 ssh2_pkt_adduint32(c
->remoteid
);
2099 if (c
->type
== CHAN_X11
) {
2101 logevent("X11 connection terminated");
2106 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
) {
2107 if (ssh_version
== 1) {
2108 send_packet(SSH1_MSG_CHANNEL_DATA
,
2109 PKT_INT
, c
->remoteid
,
2114 ssh2_add_channel_data(c
, buf
, len
);
2119 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
2124 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2127 if (ssh_state
== SSH_STATE_CLOSED
)
2130 if (cfg
.agentfwd
&& agent_exists()) {
2131 logevent("Requesting agent forwarding");
2132 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2133 do { crReturnV
; } while (!ispkt
);
2134 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2135 bombout(("Protocol confusion"));
2137 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2138 logevent("Agent forwarding refused");
2140 logevent("Agent forwarding enabled");
2141 ssh_agentfwd_enabled
= TRUE
;
2145 if (cfg
.x11_forward
) {
2146 char proto
[20], data
[64];
2147 logevent("Requesting X11 forwarding");
2148 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2149 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2150 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2151 PKT_STR
, proto
, PKT_STR
, data
,
2155 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2156 PKT_STR
, proto
, PKT_STR
, data
,
2159 do { crReturnV
; } while (!ispkt
);
2160 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2161 bombout(("Protocol confusion"));
2163 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2164 logevent("X11 forwarding refused");
2166 logevent("X11 forwarding enabled");
2167 ssh_X11_fwd_enabled
= TRUE
;
2172 send_packet(SSH1_CMSG_REQUEST_PTY
,
2173 PKT_STR
, cfg
.termtype
,
2174 PKT_INT
, rows
, PKT_INT
, cols
,
2175 PKT_INT
, 0, PKT_INT
, 0,
2178 ssh_state
= SSH_STATE_INTERMED
;
2179 do { crReturnV
; } while (!ispkt
);
2180 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2181 bombout(("Protocol confusion"));
2183 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2184 c_write_str("Server refused to allocate pty\r\n");
2185 ssh_editing
= ssh_echoing
= 1;
2187 logevent("Allocated pty");
2189 ssh_editing
= ssh_echoing
= 1;
2192 if (cfg
.compression
) {
2193 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2194 do { crReturnV
; } while (!ispkt
);
2195 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2196 bombout(("Protocol confusion"));
2198 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2199 c_write_str("Server refused to compress\r\n");
2201 logevent("Started compression");
2202 ssh1_compressing
= TRUE
;
2203 zlib_compress_init();
2204 zlib_decompress_init();
2207 if (*cfg
.remote_cmd_ptr
)
2208 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
, PKT_END
);
2210 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2211 logevent("Started session");
2213 ssh_state
= SSH_STATE_SESSION
;
2217 ssh_special(TS_EOF
);
2219 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2221 ssh_channels
= newtree234(ssh_channelcmp
);
2225 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2226 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2227 long len
= GET_32BIT(pktin
.body
);
2228 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2230 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2231 ssh_state
= SSH_STATE_CLOSED
;
2232 logevent("Received disconnect request");
2234 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2235 /* Remote side is trying to open a channel to talk to our
2236 * X-Server. Give them back a local channel number. */
2238 struct ssh_channel
*c
, *d
;
2241 logevent("Received X11 connect request");
2242 /* Refuse if X11 forwarding is disabled. */
2243 if (!ssh_X11_fwd_enabled
) {
2244 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2245 PKT_INT
, GET_32BIT(pktin
.body
),
2247 logevent("Rejected X11 connect request");
2249 c
= smalloc(sizeof(struct ssh_channel
));
2251 if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2252 logevent("opening X11 forward connection failed");
2254 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2255 PKT_INT
, GET_32BIT(pktin
.body
),
2258 logevent("opening X11 forward connection succeeded");
2259 for (i
=1, d
= first234(ssh_channels
, &e
); d
; d
= next234(&e
)) {
2261 break; /* found a free number */
2264 c
->remoteid
= GET_32BIT(pktin
.body
);
2267 c
->type
= CHAN_X11
; /* identify channel type */
2268 add234(ssh_channels
, c
);
2269 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2270 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2272 logevent("Opened X11 forward channel");
2275 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2276 /* Remote side is trying to open a channel to talk to our
2277 * agent. Give them back a local channel number. */
2279 struct ssh_channel
*c
;
2282 /* Refuse if agent forwarding is disabled. */
2283 if (!ssh_agentfwd_enabled
) {
2284 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2285 PKT_INT
, GET_32BIT(pktin
.body
),
2289 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
2291 break; /* found a free number */
2294 c
= smalloc(sizeof(struct ssh_channel
));
2295 c
->remoteid
= GET_32BIT(pktin
.body
);
2298 c
->type
= CHAN_AGENT
; /* identify channel type */
2299 c
->u
.a
.lensofar
= 0;
2300 add234(ssh_channels
, c
);
2301 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2302 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2305 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2306 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2307 /* Remote side closes a channel. */
2308 unsigned i
= GET_32BIT(pktin
.body
);
2309 struct ssh_channel
*c
;
2310 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2313 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2314 if (!(c
->closes
& closetype
))
2315 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
2316 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2317 logevent("X11 connection closed");
2318 assert(c
->u
.x11
.s
!= NULL
);
2319 x11_close(c
->u
.x11
.s
);
2322 c
->closes
|= closetype
;
2323 if (c
->closes
== 3) {
2324 del234(ssh_channels
, c
);
2328 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2329 /* Data sent down one of our channels. */
2330 int i
= GET_32BIT(pktin
.body
);
2331 int len
= GET_32BIT(pktin
.body
+4);
2332 unsigned char *p
= pktin
.body
+8;
2333 struct ssh_channel
*c
;
2334 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2338 x11_send(c
->u
.x11
.s
, p
, len
);
2341 /* Data for an agent message. Buffer it. */
2343 if (c
->u
.a
.lensofar
< 4) {
2344 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2345 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
2346 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2348 if (c
->u
.a
.lensofar
== 4) {
2349 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
2350 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2351 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2353 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2354 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
2355 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
2356 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2358 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2359 void *reply
, *sentreply
;
2361 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
2366 /* Fake SSH_AGENT_FAILURE. */
2367 sentreply
= "\0\0\0\1\5";
2370 send_packet(SSH1_MSG_CHANNEL_DATA
,
2371 PKT_INT
, c
->remoteid
,
2373 PKT_DATA
, sentreply
, replylen
,
2377 sfree(c
->u
.a
.message
);
2378 c
->u
.a
.lensofar
= 0;
2384 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2385 /* may be from EXEC_SHELL on some servers */
2386 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2387 /* may be from EXEC_SHELL on some servers
2388 * if no pty is available or in other odd cases. Ignore */
2389 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2390 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2392 bombout(("Strange packet received: type %d", pktin
.type
));
2397 int len
= min(inlen
, 512);
2398 send_packet(SSH1_CMSG_STDIN_DATA
,
2399 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2410 * Utility routine for decoding comma-separated strings in KEXINIT.
2412 static int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
2413 int needlen
= strlen(needle
);
2416 * Is it at the start of the string?
2418 if (haylen
>= needlen
&& /* haystack is long enough */
2419 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2420 (haylen
== needlen
|| haystack
[needlen
] == ',')
2421 /* either , or EOS follows */
2425 * If not, search for the next comma and resume after that.
2426 * If no comma found, terminate.
2428 while (haylen
> 0 && *haystack
!= ',')
2429 haylen
--, haystack
++;
2432 haylen
--, haystack
++; /* skip over comma itself */
2437 * SSH2 key creation method.
2439 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
, char *keyspace
) {
2441 /* First 20 bytes. */
2444 SHA_Bytes(&s
, H
, 20);
2445 SHA_Bytes(&s
, &chr
, 1);
2446 SHA_Bytes(&s
, sessid
, 20);
2447 SHA_Final(&s
, keyspace
);
2448 /* Next 20 bytes. */
2451 SHA_Bytes(&s
, H
, 20);
2452 SHA_Bytes(&s
, keyspace
, 20);
2453 SHA_Final(&s
, keyspace
+20);
2457 * Handle the SSH2 transport layer.
2459 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2461 static int i
, j
, len
, nbits
, pbits
;
2463 static Bignum p
, g
, e
, f
, K
;
2464 static int kex_init_value
, kex_reply_value
;
2465 static const struct ssh_mac
**maclist
;
2467 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2468 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2469 static const struct ssh_mac
*csmac_tobe
= NULL
;
2470 static const struct ssh_mac
*scmac_tobe
= NULL
;
2471 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2472 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2473 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2474 static int hostkeylen
, siglen
;
2475 static void *hkey
; /* actual host key */
2476 static unsigned char exchange_hash
[20];
2477 static unsigned char keyspace
[40];
2478 static const struct ssh2_ciphers
*preferred_cipher
;
2479 static const struct ssh_compress
*preferred_comp
;
2480 static int first_kex
;
2487 * Set up the preferred cipher and compression.
2489 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2490 preferred_cipher
= &ssh2_blowfish
;
2491 } else if (cfg
.cipher
== CIPHER_DES
) {
2492 logevent("Single DES not supported in SSH2; using 3DES");
2493 preferred_cipher
= &ssh2_3des
;
2494 } else if (cfg
.cipher
== CIPHER_3DES
) {
2495 preferred_cipher
= &ssh2_3des
;
2496 } else if (cfg
.cipher
== CIPHER_AES
) {
2497 preferred_cipher
= &ssh2_aes
;
2499 /* Shouldn't happen, but we do want to initialise to _something_. */
2500 preferred_cipher
= &ssh2_3des
;
2502 if (cfg
.compression
)
2503 preferred_comp
= &ssh_zlib
;
2505 preferred_comp
= &ssh_comp_none
;
2508 * Be prepared to work around the buggy MAC problem.
2510 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2511 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2513 maclist
= macs
, nmacs
= lenof(macs
);
2517 * Construct and send our key exchange packet.
2519 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2520 for (i
= 0; i
< 16; i
++)
2521 ssh2_pkt_addbyte((unsigned char)random_byte());
2522 /* List key exchange algorithms. */
2523 ssh2_pkt_addstring_start();
2524 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2525 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2526 if (i
< lenof(kex_algs
)-1)
2527 ssh2_pkt_addstring_str(",");
2529 /* List server host key algorithms. */
2530 ssh2_pkt_addstring_start();
2531 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2532 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2533 if (i
< lenof(hostkey_algs
)-1)
2534 ssh2_pkt_addstring_str(",");
2536 /* List client->server encryption algorithms. */
2537 ssh2_pkt_addstring_start();
2538 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2539 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2540 for (j
= 0; j
< c
->nciphers
; j
++) {
2541 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2542 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2543 ssh2_pkt_addstring_str(",");
2546 /* List server->client encryption algorithms. */
2547 ssh2_pkt_addstring_start();
2548 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2549 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2550 for (j
= 0; j
< c
->nciphers
; j
++) {
2551 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2552 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2553 ssh2_pkt_addstring_str(",");
2556 /* List client->server MAC algorithms. */
2557 ssh2_pkt_addstring_start();
2558 for (i
= 0; i
< nmacs
; i
++) {
2559 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2561 ssh2_pkt_addstring_str(",");
2563 /* List server->client MAC algorithms. */
2564 ssh2_pkt_addstring_start();
2565 for (i
= 0; i
< nmacs
; i
++) {
2566 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2568 ssh2_pkt_addstring_str(",");
2570 /* List client->server compression algorithms. */
2571 ssh2_pkt_addstring_start();
2572 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2573 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2574 ssh2_pkt_addstring_str(c
->name
);
2575 if (i
< lenof(compressions
))
2576 ssh2_pkt_addstring_str(",");
2578 /* List server->client compression algorithms. */
2579 ssh2_pkt_addstring_start();
2580 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2581 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2582 ssh2_pkt_addstring_str(c
->name
);
2583 if (i
< lenof(compressions
))
2584 ssh2_pkt_addstring_str(",");
2586 /* List client->server languages. Empty list. */
2587 ssh2_pkt_addstring_start();
2588 /* List server->client languages. Empty list. */
2589 ssh2_pkt_addstring_start();
2590 /* First KEX packet does _not_ follow, because we're not that brave. */
2591 ssh2_pkt_addbool(FALSE
);
2593 ssh2_pkt_adduint32(0);
2595 exhash
= exhashbase
;
2596 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
2600 if (!ispkt
) crWaitUntil(ispkt
);
2601 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
2604 * Now examine the other side's KEXINIT to see what we're up
2607 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2608 bombout(("expected key exchange packet from server"));
2611 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
2612 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
2613 pktin
.savedpos
+= 16; /* skip garbage cookie */
2614 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2615 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2616 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2621 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2622 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2623 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2624 hostkey
= hostkey_algs
[i
];
2628 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2629 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2630 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2631 for (j
= 0; j
< c
->nciphers
; j
++) {
2632 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2633 cscipher_tobe
= c
->list
[j
];
2640 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2641 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2642 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2643 for (j
= 0; j
< c
->nciphers
; j
++) {
2644 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2645 sccipher_tobe
= c
->list
[j
];
2652 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2653 for (i
= 0; i
< nmacs
; i
++) {
2654 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2655 csmac_tobe
= maclist
[i
];
2659 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2660 for (i
= 0; i
< nmacs
; i
++) {
2661 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2662 scmac_tobe
= maclist
[i
];
2666 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2667 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2668 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2669 if (in_commasep_string(c
->name
, str
, len
)) {
2674 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2675 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2676 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2677 if (in_commasep_string(c
->name
, str
, len
)) {
2684 * Work out the number of bits of key we will need from the key
2685 * exchange. We start with the maximum key length of either
2691 csbits
= cscipher_tobe
->keylen
;
2692 scbits
= sccipher_tobe
->keylen
;
2693 nbits
= (csbits
> scbits ? csbits
: scbits
);
2695 /* The keys only have 160-bit entropy, since they're based on
2696 * a SHA-1 hash. So cap the key size at 160 bits. */
2697 if (nbits
> 160) nbits
= 160;
2700 * If we're doing Diffie-Hellman group exchange, start by
2701 * requesting a group.
2703 if (kex
== &ssh_diffiehellman_gex
) {
2704 logevent("Doing Diffie-Hellman group exchange");
2706 * Work out how big a DH group we will need to allow that
2709 pbits
= 512 << ((nbits
-1) / 64);
2710 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2711 ssh2_pkt_adduint32(pbits
);
2715 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2716 bombout(("expected key exchange group packet from server"));
2719 p
= ssh2_pkt_getmp();
2720 g
= ssh2_pkt_getmp();
2721 dh_setup_group(p
, g
);
2722 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2723 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2726 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2727 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2730 logevent("Doing Diffie-Hellman key exchange");
2732 * Now generate and send e for Diffie-Hellman.
2734 e
= dh_create_e(nbits
*2);
2735 ssh2_pkt_init(kex_init_value
);
2740 if (pktin
.type
!= kex_reply_value
) {
2741 bombout(("expected key exchange reply packet from server"));
2744 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2745 f
= ssh2_pkt_getmp();
2746 ssh2_pkt_getstring(&sigdata
, &siglen
);
2750 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2751 if (kex
== &ssh_diffiehellman_gex
) {
2752 sha_uint32(&exhash
, pbits
);
2753 sha_mpint(&exhash
, p
);
2754 sha_mpint(&exhash
, g
);
2756 sha_mpint(&exhash
, e
);
2757 sha_mpint(&exhash
, f
);
2758 sha_mpint(&exhash
, K
);
2759 SHA_Final(&exhash
, exchange_hash
);
2764 debug(("Exchange hash is:\r\n"));
2765 for (i
= 0; i
< 20; i
++)
2766 debug((" %02x", exchange_hash
[i
]));
2770 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2771 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2772 bombout(("Server failed host key check"));
2777 * Expect SSH2_MSG_NEWKEYS from server.
2780 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2781 bombout(("expected new-keys packet from server"));
2786 * Authenticate remote host: verify host key. (We've already
2787 * checked the signature of the exchange hash.)
2789 keystr
= hostkey
->fmtkey(hkey
);
2790 fingerprint
= hostkey
->fingerprint(hkey
);
2791 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2792 keystr
, fingerprint
);
2793 if (first_kex
) { /* don't bother logging this in rekeys */
2794 logevent("Host key fingerprint is:");
2795 logevent(fingerprint
);
2799 hostkey
->freekey(hkey
);
2802 * Send SSH2_MSG_NEWKEYS.
2804 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2808 * Create and initialise session keys.
2810 cscipher
= cscipher_tobe
;
2811 sccipher
= sccipher_tobe
;
2814 cscomp
= cscomp_tobe
;
2815 sccomp
= sccomp_tobe
;
2816 cscomp
->compress_init();
2817 sccomp
->decompress_init();
2819 * Set IVs after keys. Here we use the exchange hash from the
2820 * _first_ key exchange.
2823 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
2824 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
2825 cscipher
->setcskey(keyspace
);
2826 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
2827 sccipher
->setsckey(keyspace
);
2828 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
2829 cscipher
->setcsiv(keyspace
);
2830 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
2831 sccipher
->setsciv(keyspace
);
2832 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
2833 csmac
->setcskey(keyspace
);
2834 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
2835 scmac
->setsckey(keyspace
);
2838 * If this is the first key exchange phase, we must pass the
2839 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2840 * wants to see it but because it will need time to initialise
2841 * itself before it sees an actual packet. In subsequent key
2842 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2843 * it would only confuse the layer above.
2851 * Now we're encrypting. Begin returning 1 to the protocol main
2852 * function so that other things can run on top of the
2853 * transport. If we ever see a KEXINIT, we must go back to the
2856 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
2859 logevent("Server initiated key re-exchange");
2860 goto begin_key_exchange
;
2866 * Add data to an SSH2 channel output buffer.
2868 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
) {
2869 if (c
->v2
.outbufsize
<
2870 c
->v2
.outbuflen
+ len
) {
2872 c
->v2
.outbuflen
+ len
+ 1024;
2873 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
,
2876 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
,
2878 c
->v2
.outbuflen
+= len
;
2882 * Attempt to send data on an SSH2 channel.
2884 static void ssh2_try_send(struct ssh_channel
*c
) {
2885 while (c
->v2
.remwindow
> 0 &&
2886 c
->v2
.outbuflen
> 0) {
2887 unsigned len
= c
->v2
.remwindow
;
2888 if (len
> c
->v2
.outbuflen
)
2889 len
= c
->v2
.outbuflen
;
2890 if (len
> c
->v2
.remmaxpkt
)
2891 len
= c
->v2
.remmaxpkt
;
2892 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2893 ssh2_pkt_adduint32(c
->remoteid
);
2894 ssh2_pkt_addstring_start();
2895 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
2897 c
->v2
.outbuflen
-= len
;
2898 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+len
,
2900 c
->v2
.remwindow
-= len
;
2905 * Handle the SSH2 userauth and connection layers.
2907 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2909 static unsigned long remote_winsize
;
2910 static unsigned long remote_maxpkt
;
2912 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
, AUTH_PASSWORD
2916 AUTH_TYPE_PUBLICKEY
,
2917 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
2918 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
2921 static int gotit
, need_pw
, can_pubkey
, can_passwd
;
2922 static int tried_pubkey_config
, tried_agent
;
2923 static int we_are_in
;
2924 static char username
[100];
2925 static char pwprompt
[200];
2926 static char password
[100];
2931 * Request userauth protocol, and await a response to it.
2933 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2934 ssh2_pkt_addstring("ssh-userauth");
2936 crWaitUntilV(ispkt
);
2937 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2938 bombout(("Server refused user authentication protocol"));
2943 * We repeat this whole loop, including the username prompt,
2944 * until we manage a successful authentication. If the user
2945 * types the wrong _password_, they are sent back to the
2946 * beginning to try another username. (If they specify a
2947 * username in the config, they are never asked, even if they
2948 * do give a wrong password.)
2950 * I think this best serves the needs of
2952 * - the people who have no configuration, no keys, and just
2953 * want to try repeated (username,password) pairs until they
2954 * type both correctly
2956 * - people who have keys and configuration but occasionally
2957 * need to fall back to passwords
2959 * - people with a key held in Pageant, who might not have
2960 * logged in to a particular machine before; so they want to
2961 * type a username, and then _either_ their key will be
2962 * accepted, _or_ they will type a password. If they mistype
2963 * the username they will want to be able to get back and
2974 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2976 if (!ssh_get_line("login as: ",
2977 username
, sizeof(username
), FALSE
)) {
2979 * get_line failed to get a username.
2982 logevent("No username provided. Abandoning session.");
2983 ssh_state
= SSH_STATE_CLOSED
;
2987 c_write_str("login as: ");
2990 crWaitUntilV(!ispkt
);
2991 while (inlen
--) switch (c
= *in
++) {
2998 c_write_str("\b \b");
3004 c_write_str("\b \b");
3013 if (((c
>= ' ' && c
<= '~') ||
3014 ((unsigned char)c
>= 160)) && pos
< 40) {
3015 username
[pos
++] = c
;
3022 c_write_str("\r\n");
3023 username
[strcspn(username
, "\n\r")] = '\0';
3026 strncpy(username
, cfg
.username
, 99);
3027 username
[99] = '\0';
3028 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3029 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3035 * Send an authentication request using method "none": (a)
3036 * just in case it succeeds, and (b) so that we know what
3037 * authentication methods we can usefully try next.
3039 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3040 ssh2_pkt_addstring(username
);
3041 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3042 ssh2_pkt_addstring("none"); /* method */
3044 type
= AUTH_TYPE_NONE
;
3048 tried_pubkey_config
= FALSE
;
3049 tried_agent
= FALSE
;
3053 * Wait for the result of the last authentication request.
3056 crWaitUntilV(ispkt
);
3057 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3061 * Don't show the banner if we're operating in
3062 * non-verbose non-interactive mode. (It's probably
3063 * a script, which means nobody will read the
3064 * banner _anyway_, and moreover the printing of
3065 * the banner will screw up processing on the
3066 * output of (say) plink.)
3068 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3069 ssh2_pkt_getstring(&banner
, &size
);
3071 c_write_untrusted(banner
, size
);
3073 crWaitUntilV(ispkt
);
3075 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3076 logevent("Access granted");
3081 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3082 bombout(("Strange packet received during authentication: type %d",
3090 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3091 * we can look at the string in it and know what we can
3092 * helpfully try next.
3097 ssh2_pkt_getstring(&methods
, &methlen
);
3098 if (!ssh2_pkt_getbool()) {
3100 * We have received an unequivocal Access
3101 * Denied. This can translate to a variety of
3104 * - if we'd just tried "none" authentication,
3105 * it's not worth printing anything at all
3107 * - if we'd just tried a public key _offer_,
3108 * the message should be "Server refused our
3109 * key" (or no message at all if the key
3110 * came from Pageant)
3112 * - if we'd just tried anything else, the
3113 * message really should be "Access denied".
3115 * Additionally, if we'd just tried password
3116 * authentication, we should break out of this
3117 * whole loop so as to go back to the username
3120 if (type
== AUTH_TYPE_NONE
) {
3122 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3123 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3124 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3125 c_write_str("Server refused our key\r\n");
3126 logevent("Server refused public key");
3128 c_write_str("Access denied\r\n");
3129 logevent("Access denied");
3130 if (type
== AUTH_TYPE_PASSWORD
) {
3136 c_write_str("Further authentication required\r\n");
3137 logevent("Further authentication required");
3140 can_pubkey
= in_commasep_string("publickey", methods
, methlen
);
3141 can_passwd
= in_commasep_string("password", methods
, methlen
);
3146 if (!method
&& can_pubkey
&& agent_exists
&& !tried_agent
) {
3148 * Attempt public-key authentication using Pageant.
3150 static unsigned char request
[5], *response
, *p
;
3151 static int responselen
;
3152 static int i
, nkeys
;
3153 static int authed
= FALSE
;
3158 logevent("Pageant is running. Requesting keys.");
3160 /* Request the keys held by the agent. */
3161 PUT_32BIT(request
, 1);
3162 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3163 agent_query(request
, 5, &r
, &responselen
);
3164 response
= (unsigned char *)r
;
3165 if (response
&& responselen
>= 5 &&
3166 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3168 nkeys
= GET_32BIT(p
); p
+= 4;
3169 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3171 for (i
= 0; i
< nkeys
; i
++) {
3172 static char *pkblob
, *alg
, *commentp
;
3173 static int pklen
, alglen
, commentlen
;
3174 static int siglen
, retlen
, len
;
3175 static char *q
, *agentreq
, *ret
;
3177 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
3179 pklen
= GET_32BIT(p
); p
+= 4;
3180 pkblob
= p
; p
+= pklen
;
3181 alglen
= GET_32BIT(pkblob
);
3183 commentlen
= GET_32BIT(p
); p
+= 4;
3184 commentp
= p
; p
+= commentlen
;
3185 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3186 ssh2_pkt_addstring(username
);
3187 ssh2_pkt_addstring("ssh-connection");/* service requested */
3188 ssh2_pkt_addstring("publickey");/* method */
3189 ssh2_pkt_addbool(FALSE
); /* no signature included */
3190 ssh2_pkt_addstring_start();
3191 ssh2_pkt_addstring_data(alg
, alglen
);
3192 ssh2_pkt_addstring_start();
3193 ssh2_pkt_addstring_data(pkblob
, pklen
);
3196 crWaitUntilV(ispkt
);
3197 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3198 logevent("Key refused");
3202 if (flags
& FLAG_VERBOSE
) {
3203 c_write_str("Authenticating with public key \"");
3204 c_write(commentp
, commentlen
);
3205 c_write_str("\" from agent\r\n");
3209 * Server is willing to accept the key.
3210 * Construct a SIGN_REQUEST.
3212 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3213 ssh2_pkt_addstring(username
);
3214 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3215 ssh2_pkt_addstring("publickey"); /* method */
3216 ssh2_pkt_addbool(TRUE
);
3217 ssh2_pkt_addstring_start();
3218 ssh2_pkt_addstring_data(alg
, alglen
);
3219 ssh2_pkt_addstring_start();
3220 ssh2_pkt_addstring_data(pkblob
, pklen
);
3222 siglen
= pktout
.length
- 5 + 4 + 20;
3223 len
= 1; /* message type */
3224 len
+= 4 + pklen
; /* key blob */
3225 len
+= 4 + siglen
; /* data to sign */
3226 len
+= 4; /* flags */
3227 agentreq
= smalloc(4 + len
);
3228 PUT_32BIT(agentreq
, len
);
3230 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3231 PUT_32BIT(q
, pklen
); q
+= 4;
3232 memcpy(q
, pkblob
, pklen
); q
+= pklen
;
3233 PUT_32BIT(q
, siglen
); q
+= 4;
3234 /* Now the data to be signed... */
3235 PUT_32BIT(q
, 20); q
+= 4;
3236 memcpy(q
, ssh2_session_id
, 20); q
+= 20;
3237 memcpy(q
, pktout
.data
+5, pktout
.length
-5);
3238 q
+= pktout
.length
-5;
3239 /* And finally the (zero) flags word. */
3241 agent_query(agentreq
, len
+4, &ret
, &retlen
);
3244 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3245 logevent("Sending Pageant's response");
3246 ssh2_pkt_addstring_start();
3247 ssh2_pkt_addstring_data(ret
+9, GET_32BIT(ret
+5));
3252 logevent("Pageant failed to answer challenge");
3262 if (!method
&& can_pubkey
&& *cfg
.keyfile
&& !tried_pubkey_config
) {
3263 unsigned char *pub_blob
;
3264 char *algorithm
, *comment
;
3267 tried_pubkey_config
= TRUE
;
3270 * Try the public key supplied in the configuration.
3272 * First, offer the public blob to see if the server is
3273 * willing to accept it.
3275 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3278 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3279 ssh2_pkt_addstring(username
);
3280 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3281 ssh2_pkt_addstring("publickey");/* method */
3282 ssh2_pkt_addbool(FALSE
); /* no signature included */
3283 ssh2_pkt_addstring(algorithm
);
3284 ssh2_pkt_addstring_start();
3285 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3287 logevent("Offered public key"); /* FIXME */
3289 crWaitUntilV(ispkt
);
3290 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3292 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3293 continue; /* key refused; give up on it */
3296 logevent("Offer of public key accepted");
3298 * Actually attempt a serious authentication using
3301 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3302 sprintf(pwprompt
, "Passphrase for key \"%.100s\": ", comment
);
3307 c_write_str("Authenticating with public key \"");
3308 c_write_str(comment
);
3309 c_write_str("\"\r\n");
3310 method
= AUTH_PUBLICKEY_FILE
;
3314 if (!method
&& can_passwd
) {
3315 method
= AUTH_PASSWORD
;
3316 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
, savedhost
);
3322 if (!ssh_get_line(pwprompt
, password
,
3323 sizeof(password
), TRUE
)) {
3325 * get_line failed to get a password (for
3326 * example because one was supplied on the
3327 * command line which has already failed to
3330 logevent("No more passwords to try");
3331 ssh_state
= SSH_STATE_CLOSED
;
3338 c_write_str(pwprompt
);
3343 crWaitUntilV(!ispkt
);
3344 while (inlen
--) switch (c
= *in
++) {
3361 if (((c
>= ' ' && c
<= '~') ||
3362 ((unsigned char)c
>= 160)) && pos
< 40)
3363 password
[pos
++] = c
;
3367 c_write_str("\r\n");
3371 if (method
== AUTH_PUBLICKEY_FILE
) {
3373 * We have our passphrase. Now try the actual authentication.
3375 struct ssh2_userkey
*key
;
3377 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3378 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3379 if (key
== SSH2_WRONG_PASSPHRASE
) {
3380 c_write_str("Wrong passphrase\r\n");
3381 tried_pubkey_config
= FALSE
;
3383 c_write_str("Unable to load private key\r\n");
3384 tried_pubkey_config
= TRUE
;
3386 /* Send a spurious AUTH_NONE to return to the top. */
3387 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3388 ssh2_pkt_addstring(username
);
3389 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3390 ssh2_pkt_addstring("none"); /* method */
3392 type
= AUTH_TYPE_NONE
;
3394 unsigned char *blob
, *sigdata
;
3395 int blob_len
, sigdata_len
;
3398 * We have loaded the private key and the server
3399 * has announced that it's willing to accept it.
3400 * Hallelujah. Generate a signature and send it.
3402 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3403 ssh2_pkt_addstring(username
);
3404 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3405 ssh2_pkt_addstring("publickey"); /* method */
3406 ssh2_pkt_addbool(TRUE
);
3407 ssh2_pkt_addstring(key
->alg
->name
);
3408 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3409 ssh2_pkt_addstring_start();
3410 ssh2_pkt_addstring_data(blob
, blob_len
);
3414 * The data to be signed is:
3418 * followed by everything so far placed in the
3421 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3422 sigdata
= smalloc(sigdata_len
);
3423 PUT_32BIT(sigdata
, 20);
3424 memcpy(sigdata
+4, ssh2_session_id
, 20);
3425 memcpy(sigdata
+24, pktout
.data
+5, pktout
.length
-5);
3426 blob
= key
->alg
->sign(key
->data
, sigdata
, sigdata_len
, &blob_len
);
3427 ssh2_pkt_addstring_start();
3428 ssh2_pkt_addstring_data(blob
, blob_len
);
3433 type
= AUTH_TYPE_PUBLICKEY
;
3435 } else if (method
== AUTH_PASSWORD
) {
3437 * We send the password packet lumped tightly together with
3438 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3439 * string long enough to make the total length of the two
3440 * packets constant. This should ensure that a passive
3441 * listener doing traffic analyis can't work out the length
3444 * For this to work, we need an assumption about the
3445 * maximum length of the password packet. I think 256 is
3446 * pretty conservative. Anyone using a password longer than
3447 * that probably doesn't have much to worry about from
3448 * people who find out how long their password is!
3450 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3451 ssh2_pkt_addstring(username
);
3452 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3453 ssh2_pkt_addstring("password");
3454 ssh2_pkt_addbool(FALSE
);
3455 ssh2_pkt_addstring(password
);
3458 * We'll include a string that's an exact multiple of the
3459 * cipher block size. If the cipher is NULL for some
3460 * reason, we don't do this trick at all because we gain
3466 stringlen
= (256 - deferred_len
);
3467 stringlen
+= cscipher
->blksize
- 1;
3468 stringlen
-= (stringlen
% cscipher
->blksize
);
3471 * Temporarily disable actual compression,
3472 * so we can guarantee to get this string
3473 * exactly the length we want it. The
3474 * compression-disabling routine should
3475 * return an integer indicating how many
3476 * bytes we should adjust our string length
3479 stringlen
-= cscomp
->disable_compression();
3481 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3482 ssh2_pkt_addstring_start();
3483 for (i
= 0; i
< stringlen
; i
++) {
3484 char c
= (char)random_byte();
3485 ssh2_pkt_addstring_data(&c
, 1);
3489 ssh_pkt_defersend();
3490 logevent("Sent password");
3491 type
= AUTH_TYPE_PASSWORD
;
3493 c_write_str("No supported authentication methods left to try!\r\n");
3494 logevent("No supported authentications offered. Disconnecting");
3495 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3496 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3497 ssh2_pkt_addstring("No supported authentication methods available");
3498 ssh2_pkt_addstring("en"); /* language tag */
3500 ssh_state
= SSH_STATE_CLOSED
;
3504 } while (!we_are_in
);
3507 * Now we're authenticated for the connection protocol. The
3508 * connection protocol will automatically have started at this
3509 * point; there's no need to send SERVICE_REQUEST.
3513 * So now create a channel with a session in it.
3515 mainchan
= smalloc(sizeof(struct ssh_channel
));
3516 mainchan
->localid
= 100; /* as good as any */
3517 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3518 ssh2_pkt_addstring("session");
3519 ssh2_pkt_adduint32(mainchan
->localid
);
3520 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3521 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3523 crWaitUntilV(ispkt
);
3524 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3525 bombout(("Server refused to open a session"));
3527 /* FIXME: error data comes back in FAILURE packet */
3529 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3530 bombout(("Server's channel confirmation cited wrong channel"));
3533 mainchan
->remoteid
= ssh2_pkt_getuint32();
3534 mainchan
->type
= CHAN_MAINSESSION
;
3535 mainchan
->closes
= 0;
3536 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3537 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3538 mainchan
->v2
.outbuffer
= NULL
;
3539 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3540 ssh_channels
= newtree234(ssh_channelcmp
);
3541 add234(ssh_channels
, mainchan
);
3542 logevent("Opened channel for session");
3545 * Potentially enable X11 forwarding.
3547 if (cfg
.x11_forward
) {
3548 char proto
[20], data
[64];
3549 logevent("Requesting X11 forwarding");
3550 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3551 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3552 ssh2_pkt_adduint32(mainchan
->remoteid
);
3553 ssh2_pkt_addstring("x11-req");
3554 ssh2_pkt_addbool(1); /* want reply */
3555 ssh2_pkt_addbool(0); /* many connections */
3556 ssh2_pkt_addstring(proto
);
3557 ssh2_pkt_addstring(data
);
3558 ssh2_pkt_adduint32(0); /* screen number */
3562 crWaitUntilV(ispkt
);
3563 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3564 unsigned i
= ssh2_pkt_getuint32();
3565 struct ssh_channel
*c
;
3566 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3568 continue; /* nonexistent channel */
3569 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3571 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3573 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3574 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3575 bombout(("Server got confused by X11 forwarding request"));
3578 logevent("X11 forwarding refused");
3580 logevent("X11 forwarding enabled");
3581 ssh_X11_fwd_enabled
= TRUE
;
3586 * Potentially enable agent forwarding.
3588 if (cfg
.agentfwd
&& agent_exists()) {
3589 logevent("Requesting OpenSSH-style agent forwarding");
3590 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3591 ssh2_pkt_adduint32(mainchan
->remoteid
);
3592 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3593 ssh2_pkt_addbool(1); /* want reply */
3597 crWaitUntilV(ispkt
);
3598 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3599 unsigned i
= ssh2_pkt_getuint32();
3600 struct ssh_channel
*c
;
3601 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3603 continue; /* nonexistent channel */
3604 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3606 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3608 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3609 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3610 bombout(("Server got confused by agent forwarding request"));
3613 logevent("Agent forwarding refused");
3615 logevent("Agent forwarding enabled");
3616 ssh_agentfwd_enabled
= TRUE
;
3621 * Now allocate a pty for the session.
3624 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3625 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3626 ssh2_pkt_addstring("pty-req");
3627 ssh2_pkt_addbool(1); /* want reply */
3628 ssh2_pkt_addstring(cfg
.termtype
);
3629 ssh2_pkt_adduint32(cols
);
3630 ssh2_pkt_adduint32(rows
);
3631 ssh2_pkt_adduint32(0); /* pixel width */
3632 ssh2_pkt_adduint32(0); /* pixel height */
3633 ssh2_pkt_addstring_start();
3634 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3636 ssh_state
= SSH_STATE_INTERMED
;
3639 crWaitUntilV(ispkt
);
3640 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3641 unsigned i
= ssh2_pkt_getuint32();
3642 struct ssh_channel
*c
;
3643 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3645 continue; /* nonexistent channel */
3646 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3648 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3650 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3651 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3652 bombout(("Server got confused by pty request"));
3655 c_write_str("Server refused to allocate pty\r\n");
3656 ssh_editing
= ssh_echoing
= 1;
3658 logevent("Allocated pty");
3661 ssh_editing
= ssh_echoing
= 1;
3665 * Start a shell or a remote command.
3667 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3668 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3669 if (cfg
.ssh_subsys
) {
3670 ssh2_pkt_addstring("subsystem");
3671 ssh2_pkt_addbool(1); /* want reply */
3672 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3673 } else if (*cfg
.remote_cmd_ptr
) {
3674 ssh2_pkt_addstring("exec");
3675 ssh2_pkt_addbool(1); /* want reply */
3676 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3678 ssh2_pkt_addstring("shell");
3679 ssh2_pkt_addbool(1); /* want reply */
3683 crWaitUntilV(ispkt
);
3684 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3685 unsigned i
= ssh2_pkt_getuint32();
3686 struct ssh_channel
*c
;
3687 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3689 continue; /* nonexistent channel */
3690 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3692 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3693 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3694 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3695 bombout(("Server got confused by shell/command request"));
3698 bombout(("Server refused to start a shell/command"));
3701 logevent("Started a shell/command");
3704 ssh_state
= SSH_STATE_SESSION
;
3708 ssh_special(TS_EOF
);
3713 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3716 static int try_send
;
3720 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3721 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3724 unsigned i
= ssh2_pkt_getuint32();
3725 struct ssh_channel
*c
;
3726 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3728 continue; /* nonexistent channel */
3729 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3730 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3731 continue; /* extended but not stderr */
3732 ssh2_pkt_getstring(&data
, &length
);
3735 case CHAN_MAINSESSION
:
3736 from_backend(pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
,
3740 x11_send(c
->u
.x11
.s
, data
, length
);
3743 while (length
> 0) {
3744 if (c
->u
.a
.lensofar
< 4) {
3745 int l
= min(4 - c
->u
.a
.lensofar
, length
);
3746 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, data
, l
);
3747 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3749 if (c
->u
.a
.lensofar
== 4) {
3750 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
3751 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3752 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3754 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
3755 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3757 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, data
, l
);
3758 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3760 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3761 void *reply
, *sentreply
;
3763 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
3768 /* Fake SSH_AGENT_FAILURE. */
3769 sentreply
= "\0\0\0\1\5";
3772 ssh2_add_channel_data(c
, sentreply
, replylen
);
3776 sfree(c
->u
.a
.message
);
3777 c
->u
.a
.lensofar
= 0;
3783 * Enlarge the window again at the remote
3784 * side, just in case it ever runs down and
3785 * they fail to send us any more data.
3787 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3788 ssh2_pkt_adduint32(c
->remoteid
);
3789 ssh2_pkt_adduint32(length
);
3792 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
3793 ssh_state
= SSH_STATE_CLOSED
;
3794 logevent("Received disconnect message");
3796 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
3797 continue; /* exit status et al; ignore (FIXME?) */
3798 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
3799 unsigned i
= ssh2_pkt_getuint32();
3800 struct ssh_channel
*c
;
3802 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3804 continue; /* nonexistent channel */
3806 if (c
->type
== CHAN_X11
) {
3808 * Remote EOF on an X11 channel means we should
3809 * wrap up and close the channel ourselves.
3811 x11_close(c
->u
.x11
.s
);
3813 } else if (c
->type
== CHAN_AGENT
) {
3816 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
3817 unsigned i
= ssh2_pkt_getuint32();
3818 struct ssh_channel
*c
;
3821 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3823 continue; /* nonexistent channel */
3824 if (c
->closes
== 0) {
3825 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3826 ssh2_pkt_adduint32(c
->remoteid
);
3829 /* Do pre-close processing on the channel. */
3831 case CHAN_MAINSESSION
:
3832 break; /* nothing to see here, move along */
3838 del234(ssh_channels
, c
);
3839 sfree(c
->v2
.outbuffer
);
3843 * See if that was the last channel left open.
3845 c
= first234(ssh_channels
, &e
);
3847 logevent("All channels closed. Disconnecting");
3848 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3849 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3850 ssh2_pkt_addstring("All open channels closed");
3851 ssh2_pkt_addstring("en"); /* language tag */
3853 ssh_state
= SSH_STATE_CLOSED
;
3856 continue; /* remote sends close; ignore (FIXME) */
3857 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3858 unsigned i
= ssh2_pkt_getuint32();
3859 struct ssh_channel
*c
;
3860 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3862 continue; /* nonexistent channel */
3863 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3865 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
3869 struct ssh_channel
*c
;
3870 ssh2_pkt_getstring(&type
, &typelen
);
3871 c
= smalloc(sizeof(struct ssh_channel
));
3873 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
3874 if (!ssh_X11_fwd_enabled
)
3875 error
= "X11 forwarding is not enabled";
3876 else if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3877 error
= "Unable to open an X11 connection";
3881 } else if (typelen
== 22 &&
3882 !memcmp(type
, "auth-agent@openssh.com", 3)) {
3883 if (!ssh_agentfwd_enabled
)
3884 error
= "Agent forwarding is not enabled";
3886 c
->type
= CHAN_AGENT
; /* identify channel type */
3887 c
->u
.a
.lensofar
= 0;
3890 error
= "Unsupported channel type requested";
3893 c
->remoteid
= ssh2_pkt_getuint32();
3895 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
3896 ssh2_pkt_adduint32(c
->remoteid
);
3897 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
3898 ssh2_pkt_addstring(error
);
3899 ssh2_pkt_addstring("en"); /* language tag */
3903 struct ssh_channel
*d
;
3907 for (i
=1, d
= first234(ssh_channels
, &e
); d
;
3910 break; /* found a free number */
3915 c
->v2
.remwindow
= ssh2_pkt_getuint32();
3916 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3917 c
->v2
.outbuffer
= NULL
;
3918 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
3919 add234(ssh_channels
, c
);
3920 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
3921 ssh2_pkt_adduint32(c
->remoteid
);
3922 ssh2_pkt_adduint32(c
->localid
);
3923 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3924 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3928 bombout(("Strange packet received: type %d", pktin
.type
));
3933 * We have spare data. Add it to the channel buffer.
3935 ssh2_add_channel_data(mainchan
, in
, inlen
);
3940 struct ssh_channel
*c
;
3942 * Try to send data on all channels if we can.
3944 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
))
3953 * Handle the top-level SSH2 protocol.
3955 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
3957 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
3959 do_ssh2_authconn(in
, inlen
, ispkt
);
3963 * Called to set up the connection.
3965 * Returns an error message, or NULL on success.
3967 static char *ssh_init (char *host
, int port
, char **realhost
) {
3971 if(crypto_startup() == 0)
3972 return "Microsoft high encryption pack not installed!";
3979 p
= connect_to_host(host
, port
, realhost
);
3987 * Called to send data down the Telnet connection.
3989 static void ssh_send (char *buf
, int len
) {
3990 if (s
== NULL
|| ssh_protocol
== NULL
)
3993 ssh_protocol(buf
, len
, 0);
3997 * Called to set the size of the window from SSH's POV.
3999 static void ssh_size(void) {
4000 switch (ssh_state
) {
4001 case SSH_STATE_BEFORE_SIZE
:
4002 case SSH_STATE_PREPACKET
:
4003 case SSH_STATE_CLOSED
:
4004 break; /* do nothing */
4005 case SSH_STATE_INTERMED
:
4006 size_needed
= TRUE
; /* buffer for later */
4008 case SSH_STATE_SESSION
:
4010 if (ssh_version
== 1) {
4011 send_packet(SSH1_CMSG_WINDOW_SIZE
,
4012 PKT_INT
, rows
, PKT_INT
, cols
,
4013 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
4015 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4016 ssh2_pkt_adduint32(mainchan
->remoteid
);
4017 ssh2_pkt_addstring("window-change");
4018 ssh2_pkt_addbool(0);
4019 ssh2_pkt_adduint32(cols
);
4020 ssh2_pkt_adduint32(rows
);
4021 ssh2_pkt_adduint32(0);
4022 ssh2_pkt_adduint32(0);
4031 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4032 * can send an EOF and collect resulting output (e.g. `plink
4035 static void ssh_special (Telnet_Special code
) {
4036 if (code
== TS_EOF
) {
4037 if (ssh_state
!= SSH_STATE_SESSION
) {
4039 * Buffer the EOF in case we are pre-SESSION, so we can
4040 * send it as soon as we reach SESSION.
4046 if (ssh_version
== 1) {
4047 send_packet(SSH1_CMSG_EOF
, PKT_END
);
4049 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4050 ssh2_pkt_adduint32(mainchan
->remoteid
);
4053 logevent("Sent EOF message");
4054 } else if (code
== TS_PING
) {
4055 if (ssh_state
== SSH_STATE_CLOSED
|| ssh_state
== SSH_STATE_PREPACKET
)
4057 if (ssh_version
== 1) {
4058 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
4060 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4061 ssh2_pkt_addstring_start();
4069 static Socket
ssh_socket(void) { return s
; }
4071 static int ssh_sendok(void) { return ssh_send_ok
; }
4073 static int ssh_ldisc(int option
) {
4074 if (option
== LD_ECHO
) return ssh_echoing
;
4075 if (option
== LD_EDIT
) return ssh_editing
;
4079 Backend ssh_backend
= {