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 SSH2_MSG_DISCONNECT 1 /* 0x1 */
72 #define SSH2_MSG_IGNORE 2 /* 0x2 */
73 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
74 #define SSH2_MSG_DEBUG 4 /* 0x4 */
75 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
76 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
77 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
78 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
79 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
80 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
81 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
82 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
83 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
84 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
85 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
86 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
87 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
88 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
89 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
90 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
91 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
92 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
93 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
94 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
95 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
96 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
97 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
98 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
99 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
100 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
101 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
102 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
103 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
104 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
106 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
107 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
108 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
109 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
110 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
111 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
112 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
113 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
114 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
115 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
116 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
118 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
119 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
120 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
121 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
123 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
126 * Various remote-bug flags.
128 #define BUG_CHOKES_ON_SSH1_IGNORE 1
129 #define BUG_SSH2_HMAC 2
131 #define GET_32BIT(cp) \
132 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
133 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
134 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
135 ((unsigned long)(unsigned char)(cp)[3]))
137 #define PUT_32BIT(cp, value) { \
138 (cp)[0] = (unsigned char)((value) >> 24); \
139 (cp)[1] = (unsigned char)((value) >> 16); \
140 (cp)[2] = (unsigned char)((value) >> 8); \
141 (cp)[3] = (unsigned char)(value); }
143 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
145 /* Coroutine mechanics for the sillier bits of the code */
146 #define crBegin1 static int crLine = 0;
147 #define crBegin2 switch(crLine) { case 0:;
148 #define crBegin crBegin1; crBegin2;
149 #define crFinish(z) } crLine = 0; return (z)
150 #define crFinishV } crLine = 0; return
151 #define crReturn(z) \
153 crLine=__LINE__; return (z); case __LINE__:;\
157 crLine=__LINE__; return; case __LINE__:;\
159 #define crStop(z) do{ crLine = 0; return (z); }while(0)
160 #define crStopV do{ crLine = 0; return; }while(0)
161 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
162 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
164 extern char *x11_init (Socket
*, char *, void *);
165 extern void x11_close (Socket
);
166 extern void x11_send (Socket
, char *, int);
167 extern void x11_invent_auth(char *, int, char *, int);
170 * Ciphers for SSH2. We miss out single-DES because it isn't
171 * supported; also 3DES and Blowfish are both done differently from
172 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
173 * endianness and different-sized keys.)
175 const static struct ssh2_ciphers
*ciphers
[] = {
181 const static struct ssh_kex
*kex_algs
[] = {
182 #ifdef DO_DIFFIE_HELLMAN_GEX
183 &ssh_diffiehellman_gex
,
185 &ssh_diffiehellman
};
187 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
189 static void nullmac_key(unsigned char *key
) { }
190 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
191 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
192 const static struct ssh_mac ssh_mac_none
= {
193 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
195 const static struct ssh_mac
*macs
[] = {
196 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
};
197 const static struct ssh_mac
*buggymacs
[] = {
198 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
};
200 static void ssh_comp_none_init(void) { }
201 static int ssh_comp_none_block(unsigned char *block
, int len
,
202 unsigned char **outblock
, int *outlen
) {
205 static int ssh_comp_none_disable(void) { return 0; }
206 const static struct ssh_compress ssh_comp_none
= {
208 ssh_comp_none_init
, ssh_comp_none_block
,
209 ssh_comp_none_init
, ssh_comp_none_block
,
210 ssh_comp_none_disable
212 extern const struct ssh_compress ssh_zlib
;
213 const static struct ssh_compress
*compressions
[] = {
214 &ssh_zlib
, &ssh_comp_none
};
216 enum { /* channel types */
223 * 2-3-4 tree storing channels.
226 unsigned remoteid
, localid
;
229 struct ssh2_data_channel
{
230 unsigned char *outbuffer
;
231 unsigned outbuflen
, outbufsize
;
232 unsigned remwindow
, remmaxpkt
;
235 struct ssh_agent_channel
{
236 unsigned char *message
;
237 unsigned char msglen
[4];
238 int lensofar
, totallen
;
240 struct ssh_x11_channel
{
255 static SHA_State exhash
, exhashbase
;
257 static Socket s
= NULL
;
259 static unsigned char session_key
[32];
260 static int ssh1_compressing
;
261 static int ssh_agentfwd_enabled
;
262 static int ssh_X11_fwd_enabled
;
263 static int ssh_remote_bugs
;
264 static const struct ssh_cipher
*cipher
= NULL
;
265 static const struct ssh2_cipher
*cscipher
= NULL
;
266 static const struct ssh2_cipher
*sccipher
= NULL
;
267 static const struct ssh_mac
*csmac
= NULL
;
268 static const struct ssh_mac
*scmac
= NULL
;
269 static const struct ssh_compress
*cscomp
= NULL
;
270 static const struct ssh_compress
*sccomp
= NULL
;
271 static const struct ssh_kex
*kex
= NULL
;
272 static const struct ssh_signkey
*hostkey
= NULL
;
273 static unsigned char ssh2_session_id
[20];
274 int (*ssh_get_password
)(const char *prompt
, char *str
, int maxlen
) = NULL
;
276 static char *savedhost
;
277 static int savedport
;
278 static int ssh_send_ok
;
279 static int ssh_echoing
, ssh_editing
;
281 static tree234
*ssh_channels
; /* indexed by local id */
282 static struct ssh_channel
*mainchan
; /* primary session channel */
286 SSH_STATE_BEFORE_SIZE
,
290 } ssh_state
= SSH_STATE_PREPACKET
;
292 static int size_needed
= FALSE
, eof_needed
= FALSE
;
294 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
295 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
296 static unsigned char *deferred_send_data
= NULL
;
297 static int deferred_len
= 0, deferred_size
= 0;
299 static int ssh_version
;
300 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
301 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
302 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
303 static void ssh_size(void);
304 static void ssh_special (Telnet_Special
);
305 static void ssh2_try_send(struct ssh_channel
*c
);
306 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
308 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
310 static struct rdpkt1_state_tag
{
311 long len
, pad
, biglen
, to_read
;
312 unsigned long realcrc
, gotcrc
;
318 static struct rdpkt2_state_tag
{
319 long len
, pad
, payload
, packetlen
, maclen
;
322 unsigned long incoming_sequence
;
325 static int ssh_channelcmp(void *av
, void *bv
) {
326 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
327 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
328 if (a
->localid
< b
->localid
) return -1;
329 if (a
->localid
> b
->localid
) return +1;
332 static int ssh_channelfind(void *av
, void *bv
) {
333 unsigned *a
= (unsigned *)av
;
334 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
335 if (*a
< b
->localid
) return -1;
336 if (*a
> b
->localid
) return +1;
340 static void c_write (char *buf
, int len
) {
341 if ((flags
& FLAG_STDERR
)) {
343 for (i
= 0; i
< len
; i
++)
345 fputc(buf
[i
], stderr
);
348 from_backend(1, buf
, len
);
351 static void c_write_str (char *buf
) {
352 c_write(buf
, strlen(buf
));
356 * Collect incoming data in the incoming packet buffer.
357 * Decipher and verify the packet when it is completely read.
358 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
359 * Update the *data and *datalen variables.
360 * Return the additional nr of bytes needed, or 0 when
361 * a complete packet is available.
363 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
365 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
374 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
375 while ((*datalen
) == 0)
377 st
->len
= (st
->len
<< 8) + **data
;
378 (*data
)++, (*datalen
)--;
382 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
383 st
->len
= 0x300; /* big enough to carry to end */
387 st
->pad
= 8 - (st
->len
% 8);
388 st
->biglen
= st
->len
+ st
->pad
;
389 pktin
.length
= st
->len
- 5;
391 if (pktin
.maxlen
< st
->biglen
) {
392 pktin
.maxlen
= st
->biglen
;
393 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+APIEXTRA
) :
394 srealloc(pktin
.data
, st
->biglen
+APIEXTRA
));
396 fatalbox("Out of memory");
399 st
->to_read
= st
->biglen
;
401 while (st
->to_read
> 0) {
402 st
->chunk
= st
->to_read
;
403 while ((*datalen
) == 0)
404 crReturn(st
->to_read
);
405 if (st
->chunk
> (*datalen
))
406 st
->chunk
= (*datalen
);
407 memcpy(st
->p
, *data
, st
->chunk
);
409 *datalen
-= st
->chunk
;
411 st
->to_read
-= st
->chunk
;
415 cipher
->decrypt(pktin
.data
, st
->biglen
);
417 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
418 for (st
->i
= 0; st
->i
< st
->biglen
; st
->i
++)
419 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
423 st
->realcrc
= crc32(pktin
.data
, st
->biglen
-4);
424 st
->gotcrc
= GET_32BIT(pktin
.data
+st
->biglen
-4);
425 if (st
->gotcrc
!= st
->realcrc
) {
426 bombout(("Incorrect CRC received on packet"));
430 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
432 if (ssh1_compressing
) {
433 unsigned char *decompblk
;
437 debug(("Packet payload pre-decompression:\n"));
438 for (i
= -1; i
< pktin
.length
; i
++)
439 debug((" %02x", (unsigned char)pktin
.body
[i
]));
442 zlib_decompress_block(pktin
.body
-1, pktin
.length
+1,
443 &decompblk
, &decomplen
);
445 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
446 pktin
.maxlen
= st
->pad
+ decomplen
;
447 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
);
448 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
450 fatalbox("Out of memory");
453 memcpy(pktin
.body
-1, decompblk
, decomplen
);
455 pktin
.length
= decomplen
-1;
457 debug(("Packet payload post-decompression:\n"));
458 for (i
= -1; i
< pktin
.length
; i
++)
459 debug((" %02x", (unsigned char)pktin
.body
[i
]));
464 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
465 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
466 pktin
.type
== SSH1_MSG_DEBUG
||
467 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
468 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
469 long strlen
= GET_32BIT(pktin
.body
);
470 if (strlen
+ 4 != pktin
.length
) {
471 bombout(("Received data packet with bogus string length"));
476 pktin
.type
= pktin
.body
[-1];
478 if (pktin
.type
== SSH1_MSG_DEBUG
) {
479 /* log debug message */
481 int strlen
= GET_32BIT(pktin
.body
);
482 strcpy(buf
, "Remote: ");
483 if (strlen
> 70) strlen
= 70;
484 memcpy(buf
+8, pktin
.body
+4, strlen
);
485 buf
[8+strlen
] = '\0';
488 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
496 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
498 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
506 st
->cipherblk
= sccipher
->blksize
;
509 if (st
->cipherblk
< 8)
512 if (pktin
.maxlen
< st
->cipherblk
) {
513 pktin
.maxlen
= st
->cipherblk
;
514 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->cipherblk
+APIEXTRA
) :
515 srealloc(pktin
.data
, st
->cipherblk
+APIEXTRA
));
517 fatalbox("Out of memory");
521 * Acquire and decrypt the first block of the packet. This will
522 * contain the length and padding details.
524 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
525 while ((*datalen
) == 0)
526 crReturn(st
->cipherblk
-st
->i
);
527 pktin
.data
[st
->i
] = *(*data
)++;
531 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
536 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
539 * Now get the length and padding figures.
541 st
->len
= GET_32BIT(pktin
.data
);
542 st
->pad
= pktin
.data
[4];
545 * This enables us to deduce the payload length.
547 st
->payload
= st
->len
- st
->pad
- 1;
549 pktin
.length
= st
->payload
+ 5;
552 * So now we can work out the total packet length.
554 st
->packetlen
= st
->len
+ 4;
555 st
->maclen
= scmac ? scmac
->len
: 0;
558 * Adjust memory allocation if packet is too big.
560 if (pktin
.maxlen
< st
->packetlen
+st
->maclen
) {
561 pktin
.maxlen
= st
->packetlen
+st
->maclen
;
562 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
563 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
565 fatalbox("Out of memory");
569 * Read and decrypt the remainder of the packet.
571 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
; st
->i
++) {
572 while ((*datalen
) == 0)
573 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
574 pktin
.data
[st
->i
] = *(*data
)++;
577 /* Decrypt everything _except_ the MAC. */
579 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
580 st
->packetlen
- st
->cipherblk
);
583 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
584 for (st
->i
= 0; st
->i
< st
->packetlen
; st
->i
++)
585 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
592 if (scmac
&& !scmac
->verify(pktin
.data
, st
->len
+4, st
->incoming_sequence
)) {
593 bombout(("Incorrect MAC received on packet"));
596 st
->incoming_sequence
++; /* whether or not we MACed */
599 * Decompress packet payload.
602 unsigned char *newpayload
;
604 if (sccomp
&& sccomp
->decompress(pktin
.data
+5, pktin
.length
-5,
605 &newpayload
, &newlen
)) {
606 if (pktin
.maxlen
< newlen
+5) {
607 pktin
.maxlen
= newlen
+5;
608 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
609 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
611 fatalbox("Out of memory");
613 pktin
.length
= 5 + newlen
;
614 memcpy(pktin
.data
+5, newpayload
, newlen
);
616 debug(("Post-decompression payload:\r\n"));
617 for (st
->i
= 0; st
->i
< newlen
; st
->i
++)
618 debug((" %02x", (unsigned char)pktin
.data
[5+st
->i
]));
627 pktin
.type
= pktin
.data
[5];
629 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
630 goto next_packet
; /* FIXME: print DEBUG message */
635 static void ssh1_pktout_size(int len
) {
638 len
+= 5; /* type and CRC */
642 pktout
.length
= len
-5;
643 if (pktout
.maxlen
< biglen
) {
644 pktout
.maxlen
= biglen
;
646 /* Allocate enough buffer space for extra block
647 * for MS CryptEncrypt() */
648 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+12) :
649 srealloc(pktout
.data
, biglen
+12));
651 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+4) :
652 srealloc(pktout
.data
, biglen
+4));
655 fatalbox("Out of memory");
657 pktout
.body
= pktout
.data
+4+pad
+1;
660 static void s_wrpkt_start(int type
, int len
) {
661 ssh1_pktout_size(len
);
665 static int s_wrpkt_prepare(void) {
666 int pad
, len
, biglen
, i
;
669 pktout
.body
[-1] = pktout
.type
;
672 debug(("Packet payload pre-compression:\n"));
673 for (i
= -1; i
< pktout
.length
; i
++)
674 debug((" %02x", (unsigned char)pktout
.body
[i
]));
678 if (ssh1_compressing
) {
679 unsigned char *compblk
;
681 zlib_compress_block(pktout
.body
-1, pktout
.length
+1,
683 ssh1_pktout_size(complen
-1);
684 memcpy(pktout
.body
-1, compblk
, complen
);
687 debug(("Packet payload post-compression:\n"));
688 for (i
= -1; i
< pktout
.length
; i
++)
689 debug((" %02x", (unsigned char)pktout
.body
[i
]));
694 len
= pktout
.length
+ 5; /* type and CRC */
698 for (i
=0; i
<pad
; i
++)
699 pktout
.data
[i
+4] = random_byte();
700 crc
= crc32(pktout
.data
+4, biglen
-4);
701 PUT_32BIT(pktout
.data
+biglen
, crc
);
702 PUT_32BIT(pktout
.data
, len
);
705 debug(("Sending packet len=%d\r\n", biglen
+4));
706 for (i
= 0; i
< biglen
+4; i
++)
707 debug((" %02x", (unsigned char)pktout
.data
[i
]));
711 cipher
->encrypt(pktout
.data
+4, biglen
);
716 static void s_wrpkt(void) {
718 len
= s_wrpkt_prepare();
719 sk_write(s
, pktout
.data
, len
);
722 static void s_wrpkt_defer(void) {
724 len
= s_wrpkt_prepare();
725 if (deferred_len
+ len
> deferred_size
) {
726 deferred_size
= deferred_len
+ len
+ 128;
727 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
729 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
734 * Construct a packet with the specified contents.
736 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
738 unsigned char *p
, *argp
, argchar
;
739 unsigned long argint
;
740 int pktlen
, argtype
, arglen
;
744 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
747 (void) va_arg(ap1
, int);
751 (void) va_arg(ap1
, char);
755 (void) va_arg(ap1
, unsigned char *);
756 arglen
= va_arg(ap1
, int);
760 argp
= va_arg(ap1
, unsigned char *);
761 arglen
= strlen(argp
);
762 pktlen
+= 4 + arglen
;
765 bn
= va_arg(ap1
, Bignum
);
766 pktlen
+= ssh1_bignum_length(bn
);
773 s_wrpkt_start(pkttype
, pktlen
);
776 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
779 argint
= va_arg(ap2
, int);
780 PUT_32BIT(p
, argint
);
784 argchar
= va_arg(ap2
, unsigned char);
789 argp
= va_arg(ap2
, unsigned char *);
790 arglen
= va_arg(ap2
, int);
791 memcpy(p
, argp
, arglen
);
795 argp
= va_arg(ap2
, unsigned char *);
796 arglen
= strlen(argp
);
797 PUT_32BIT(p
, arglen
);
798 memcpy(p
+ 4, argp
, arglen
);
802 bn
= va_arg(ap2
, Bignum
);
803 p
+= ssh1_write_bignum(p
, bn
);
809 static void send_packet(int pkttype
, ...) {
811 va_start(ap1
, pkttype
);
812 va_start(ap2
, pkttype
);
813 construct_packet(pkttype
, ap1
, ap2
);
817 static void defer_packet(int pkttype
, ...) {
819 va_start(ap1
, pkttype
);
820 va_start(ap2
, pkttype
);
821 construct_packet(pkttype
, ap1
, ap2
);
825 static int ssh_versioncmp(char *a
, char *b
) {
827 unsigned long av
, bv
;
829 av
= strtoul(a
, &ae
, 10);
830 bv
= strtoul(b
, &be
, 10);
831 if (av
!= bv
) return (av
< bv ?
-1 : +1);
832 if (*ae
== '.') ae
++;
833 if (*be
== '.') be
++;
834 av
= strtoul(ae
, &ae
, 10);
835 bv
= strtoul(be
, &be
, 10);
836 if (av
!= bv
) return (av
< bv ?
-1 : +1);
842 * Utility routines for putting an SSH-protocol `string' and
843 * `uint32' into a SHA state.
846 static void sha_string(SHA_State
*s
, void *str
, int len
) {
847 unsigned char lenblk
[4];
848 PUT_32BIT(lenblk
, len
);
849 SHA_Bytes(s
, lenblk
, 4);
850 SHA_Bytes(s
, str
, len
);
853 static void sha_uint32(SHA_State
*s
, unsigned i
) {
854 unsigned char intblk
[4];
855 PUT_32BIT(intblk
, i
);
856 SHA_Bytes(s
, intblk
, 4);
860 * SSH2 packet construction functions.
862 static void ssh2_pkt_ensure(int length
) {
863 if (pktout
.maxlen
< length
) {
864 pktout
.maxlen
= length
+ 256;
865 pktout
.data
= (pktout
.data
== NULL ?
smalloc(pktout
.maxlen
+APIEXTRA
) :
866 srealloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
868 fatalbox("Out of memory");
871 static void ssh2_pkt_adddata(void *data
, int len
) {
872 pktout
.length
+= len
;
873 ssh2_pkt_ensure(pktout
.length
);
874 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
876 static void ssh2_pkt_addbyte(unsigned char byte
) {
877 ssh2_pkt_adddata(&byte
, 1);
879 static void ssh2_pkt_init(int pkt_type
) {
881 ssh2_pkt_addbyte((unsigned char)pkt_type
);
883 static void ssh2_pkt_addbool(unsigned char value
) {
884 ssh2_pkt_adddata(&value
, 1);
886 static void ssh2_pkt_adduint32(unsigned long value
) {
889 ssh2_pkt_adddata(x
, 4);
891 static void ssh2_pkt_addstring_start(void) {
892 ssh2_pkt_adduint32(0);
893 pktout
.savedpos
= pktout
.length
;
895 static void ssh2_pkt_addstring_str(char *data
) {
896 ssh2_pkt_adddata(data
, strlen(data
));
897 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
898 pktout
.length
- pktout
.savedpos
);
900 static void ssh2_pkt_addstring_data(char *data
, int len
) {
901 ssh2_pkt_adddata(data
, len
);
902 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
903 pktout
.length
- pktout
.savedpos
);
905 static void ssh2_pkt_addstring(char *data
) {
906 ssh2_pkt_addstring_start();
907 ssh2_pkt_addstring_str(data
);
909 static char *ssh2_mpint_fmt(Bignum b
, int *len
) {
911 int i
, n
= (ssh1_bignum_bitcount(b
)+7)/8;
914 fatalbox("out of memory");
916 for (i
= 1; i
<= n
; i
++)
917 p
[i
] = bignum_byte(b
, n
-i
);
919 while (i
<= n
&& p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
921 memmove(p
, p
+i
, n
+1-i
);
925 static void ssh2_pkt_addmp(Bignum b
) {
928 p
= ssh2_mpint_fmt(b
, &len
);
929 ssh2_pkt_addstring_start();
930 ssh2_pkt_addstring_data(p
, len
);
935 * Construct an SSH2 final-form packet: compress it, encrypt it,
936 * put the MAC on it. Final packet, ready to be sent, is stored in
937 * pktout.data. Total length is returned.
939 static int ssh2_pkt_construct(void) {
940 int cipherblk
, maclen
, padding
, i
;
941 static unsigned long outgoing_sequence
= 0;
944 * Compress packet payload.
947 debug(("Pre-compression payload:\r\n"));
948 for (i
= 5; i
< pktout
.length
; i
++)
949 debug((" %02x", (unsigned char)pktout
.data
[i
]));
953 unsigned char *newpayload
;
955 if (cscomp
&& cscomp
->compress(pktout
.data
+5, pktout
.length
-5,
956 &newpayload
, &newlen
)) {
958 ssh2_pkt_adddata(newpayload
, newlen
);
964 * Add padding. At least four bytes, and must also bring total
965 * length (minus MAC) up to a multiple of the block size.
967 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
968 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
970 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
971 maclen
= csmac ? csmac
->len
: 0;
972 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
973 pktout
.data
[4] = padding
;
974 for (i
= 0; i
< padding
; i
++)
975 pktout
.data
[pktout
.length
+ i
] = random_byte();
976 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
978 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
980 outgoing_sequence
++; /* whether or not we MACed */
983 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
984 for (i
= 0; i
< pktout
.length
+padding
; i
++)
985 debug((" %02x", (unsigned char)pktout
.data
[i
]));
990 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
992 /* Ready-to-send packet starts at pktout.data. We return length. */
993 return pktout
.length
+ padding
+ maclen
;
997 * Construct and send an SSH2 packet immediately.
999 static void ssh2_pkt_send(void) {
1000 int len
= ssh2_pkt_construct();
1001 sk_write(s
, pktout
.data
, len
);
1005 * Construct an SSH2 packet and add it to a deferred data block.
1006 * Useful for sending multiple packets in a single sk_write() call,
1007 * to prevent a traffic-analysing listener from being able to work
1008 * out the length of any particular packet (such as the password
1011 * Note that because SSH2 sequence-numbers its packets, this can
1012 * NOT be used as an m4-style `defer' allowing packets to be
1013 * constructed in one order and sent in another.
1015 static void ssh2_pkt_defer(void) {
1016 int len
= ssh2_pkt_construct();
1017 if (deferred_len
+ len
> deferred_size
) {
1018 deferred_size
= deferred_len
+ len
+ 128;
1019 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1021 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
1022 deferred_len
+= len
;
1026 * Send the whole deferred data block constructed by
1027 * ssh2_pkt_defer() or SSH1's defer_packet().
1029 static void ssh_pkt_defersend(void) {
1030 sk_write(s
, deferred_send_data
, deferred_len
);
1031 deferred_len
= deferred_size
= 0;
1032 sfree(deferred_send_data
);
1033 deferred_send_data
= NULL
;
1037 void bndebug(char *string
, Bignum b
) {
1040 p
= ssh2_mpint_fmt(b
, &len
);
1041 debug(("%s", string
));
1042 for (i
= 0; i
< len
; i
++)
1043 debug((" %02x", p
[i
]));
1049 static void sha_mpint(SHA_State
*s
, Bignum b
) {
1052 p
= ssh2_mpint_fmt(b
, &len
);
1053 sha_string(s
, p
, len
);
1058 * SSH2 packet decode functions.
1060 static unsigned long ssh2_pkt_getuint32(void) {
1061 unsigned long value
;
1062 if (pktin
.length
- pktin
.savedpos
< 4)
1063 return 0; /* arrgh, no way to decline (FIXME?) */
1064 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1065 pktin
.savedpos
+= 4;
1068 static int ssh2_pkt_getbool(void) {
1069 unsigned long value
;
1070 if (pktin
.length
- pktin
.savedpos
< 1)
1071 return 0; /* arrgh, no way to decline (FIXME?) */
1072 value
= pktin
.data
[pktin
.savedpos
] != 0;
1076 static void ssh2_pkt_getstring(char **p
, int *length
) {
1078 if (pktin
.length
- pktin
.savedpos
< 4)
1080 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1081 pktin
.savedpos
+= 4;
1082 if (pktin
.length
- pktin
.savedpos
< *length
)
1084 *p
= pktin
.data
+pktin
.savedpos
;
1085 pktin
.savedpos
+= *length
;
1087 static Bignum
ssh2_pkt_getmp(void) {
1092 ssh2_pkt_getstring(&p
, &length
);
1096 bombout(("internal error: Can't handle negative mpints"));
1099 b
= bignum_from_bytes(p
, length
);
1104 * Examine the remote side's version string and compare it against
1105 * a list of known buggy implementations.
1107 static void ssh_detect_bugs(char *vstring
) {
1108 char *imp
; /* pointer to implementation part */
1110 imp
+= strcspn(imp
, "-");
1111 imp
+= strcspn(imp
, "-");
1113 ssh_remote_bugs
= 0;
1115 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1116 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1117 !strcmp(imp
, "1.2.22")) {
1119 * These versions don't support SSH1_MSG_IGNORE, so we have
1120 * to use a different defence against password length
1123 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1124 logevent("We believe remote version has SSH1 ignore bug");
1127 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1128 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1129 !strncmp(imp
, "2.1 ", 4)) {
1131 * These versions have the HMAC bug.
1133 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1134 logevent("We believe remote version has SSH2 HMAC bug");
1138 static int do_ssh_init(unsigned char c
) {
1140 static char version
[10];
1141 static char vstring
[80];
1142 static char vlog
[sizeof(vstring
)+20];
1147 /* Search for the string "SSH-" in the input. */
1150 static const int transS
[] = { 1, 2, 2, 1 };
1151 static const int transH
[] = { 0, 0, 3, 0 };
1152 static const int transminus
[] = { 0, 0, 0, -1 };
1153 if (c
== 'S') i
= transS
[i
];
1154 else if (c
== 'H') i
= transH
[i
];
1155 else if (c
== '-') i
= transminus
[i
];
1159 crReturn(1); /* get another character */
1162 strcpy(vstring
, "SSH-");
1166 crReturn(1); /* get another char */
1167 if (vsp
< vstring
+sizeof(vstring
)-1)
1173 } else if (i
< sizeof(version
)-1)
1180 ssh_agentfwd_enabled
= FALSE
;
1181 rdpkt2_state
.incoming_sequence
= 0;
1184 sprintf(vlog
, "Server version: %s", vstring
);
1185 ssh_detect_bugs(vstring
);
1186 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1190 * Server version "1.99" means we can choose whether we use v1
1191 * or v2 protocol. Choice is based on cfg.sshprot.
1193 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1195 * This is a v2 server. Begin v2 protocol.
1197 char *verstring
= "SSH-2.0-PuTTY";
1198 SHA_Init(&exhashbase
);
1200 * Hash our version string and their version string.
1202 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1203 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1204 sprintf(vstring
, "%s\n", verstring
);
1205 sprintf(vlog
, "We claim version: %s", verstring
);
1207 logevent("Using SSH protocol version 2");
1208 sk_write(s
, vstring
, strlen(vstring
));
1209 ssh_protocol
= ssh2_protocol
;
1211 s_rdpkt
= ssh2_rdpkt
;
1214 * This is a v1 server. Begin v1 protocol.
1216 sprintf(vstring
, "SSH-%s-PuTTY\n",
1217 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1218 sprintf(vlog
, "We claim version: %s", vstring
);
1219 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1221 logevent("Using SSH protocol version 1");
1222 sk_write(s
, vstring
, strlen(vstring
));
1223 ssh_protocol
= ssh1_protocol
;
1225 s_rdpkt
= ssh1_rdpkt
;
1227 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1232 static void ssh_gotdata(unsigned char *data
, int datalen
)
1237 * To begin with, feed the characters one by one to the
1238 * protocol initialisation / selection function do_ssh_init().
1239 * When that returns 0, we're done with the initial greeting
1240 * exchange and can move on to packet discipline.
1245 crReturnV
; /* more data please */
1246 ret
= do_ssh_init(*data
);
1253 * We emerge from that loop when the initial negotiation is
1254 * over and we have selected an s_rdpkt function. Now pass
1255 * everything to s_rdpkt, and then pass the resulting packets
1256 * to the proper protocol handler.
1261 while (datalen
> 0) {
1262 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
1263 ssh_protocol(NULL
, 0, 1);
1264 if (ssh_state
== SSH_STATE_CLOSED
) {
1274 static int ssh_receive(Socket skt
, int urgent
, char *data
, int len
) {
1276 /* A socket error has occurred. */
1277 ssh_state
= SSH_STATE_CLOSED
;
1280 connection_fatal(data
);
1283 /* Connection has closed. */
1284 ssh_state
= SSH_STATE_CLOSED
;
1289 ssh_gotdata (data
, len
);
1290 if (ssh_state
== SSH_STATE_CLOSED
) {
1301 * Connect to specified host and port.
1302 * Returns an error message, or NULL on success.
1303 * Also places the canonical host name into `realhost'.
1305 static char *connect_to_host(char *host
, int port
, char **realhost
)
1314 savedhost
= smalloc(1+strlen(host
));
1316 fatalbox("Out of memory");
1317 strcpy(savedhost
, host
);
1320 port
= 22; /* default ssh port */
1333 addr
= sk_namelookup(host
, realhost
);
1334 if ( (err
= sk_addr_error(addr
)) )
1344 s
= sk_new(addr
, port
, 0, 1, ssh_receive
);
1345 if ( (err
= sk_socket_error(s
)) )
1349 sk_write(s
, "connect ", 8);
1350 sk_write(s
, FWhost
, strlen(FWhost
));
1353 sprintf(buf
, " %d\n", FWport
);
1354 sk_write(s
, buf
, strlen(buf
));
1362 * Handle the key exchange and user authentication phases.
1364 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1367 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1368 unsigned char cookie
[8];
1369 struct RSAKey servkey
, hostkey
;
1370 struct MD5Context md5c
;
1371 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1372 static int tried_publickey
;
1373 static unsigned char session_id
[16];
1375 static char username
[100];
1379 if (!ispkt
) crWaitUntil(ispkt
);
1381 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1382 bombout(("Public key packet not received"));
1386 logevent("Received public keys");
1388 memcpy(cookie
, pktin
.body
, 8);
1390 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1391 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1394 * Log the host key fingerprint.
1398 logevent("Host key fingerprint is:");
1399 strcpy(logmsg
, " ");
1400 hostkey
.comment
= NULL
;
1401 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1406 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1407 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1410 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1411 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1412 MD5Update(&md5c
, pktin
.body
, 8);
1413 MD5Final(session_id
, &md5c
);
1415 for (i
=0; i
<32; i
++)
1416 session_key
[i
] = random_byte();
1418 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1420 rsabuf
= smalloc(len
);
1422 fatalbox("Out of memory");
1425 * Verify the host key.
1429 * First format the key into a string.
1431 int len
= rsastr_len(&hostkey
);
1432 char fingerprint
[100];
1433 char *keystr
= smalloc(len
);
1435 fatalbox("Out of memory");
1436 rsastr_fmt(keystr
, &hostkey
);
1437 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1438 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1442 for (i
=0; i
<32; i
++) {
1443 rsabuf
[i
] = session_key
[i
];
1445 rsabuf
[i
] ^= session_id
[i
];
1448 if (hostkey
.bytes
> servkey
.bytes
) {
1449 rsaencrypt(rsabuf
, 32, &servkey
);
1450 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1452 rsaencrypt(rsabuf
, 32, &hostkey
);
1453 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1456 logevent("Encrypted session key");
1458 switch (cfg
.cipher
) {
1459 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
; break;
1460 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
; break;
1461 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
; break;
1463 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1464 cipher_type
= SSH_CIPHER_3DES
;
1467 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1468 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1469 cipher_type
= SSH_CIPHER_3DES
;
1471 switch (cipher_type
) {
1472 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1473 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1474 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1477 send_packet(SSH1_CMSG_SESSION_KEY
,
1478 PKT_CHAR
, cipher_type
,
1479 PKT_DATA
, cookie
, 8,
1480 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1481 PKT_DATA
, rsabuf
, len
,
1485 logevent("Trying to enable encryption...");
1489 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1490 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1492 cipher
->sesskey(session_key
);
1496 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1497 bombout(("Encryption not successfully enabled"));
1501 logevent("Successfully started encryption");
1507 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1508 c_write_str("login as: ");
1511 crWaitUntil(!ispkt
);
1512 while (inlen
--) switch (c
= *in
++) {
1519 c_write_str("\b \b");
1525 c_write_str("\b \b");
1534 if (((c
>= ' ' && c
<= '~') ||
1535 ((unsigned char)c
>= 160)) && pos
< 40) {
1536 username
[pos
++] = c
;
1542 c_write_str("\r\n");
1543 username
[strcspn(username
, "\n\r")] = '\0';
1545 strncpy(username
, cfg
.username
, 99);
1546 username
[99] = '\0';
1549 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1551 char userlog
[22+sizeof(username
)];
1552 sprintf(userlog
, "Sent username \"%s\"", username
);
1554 if (flags
& FLAG_INTERACTIVE
&&
1555 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1556 strcat(userlog
, "\r\n");
1557 c_write_str(userlog
);
1564 tried_publickey
= 0;
1566 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1567 static char password
[100];
1568 static char prompt
[200];
1571 static int pwpkt_type
;
1573 * Show password prompt, having first obtained it via a TIS
1574 * or CryptoCard exchange if we're doing TIS or CryptoCard
1577 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1578 if (agent_exists()) {
1580 * Attempt RSA authentication using Pageant.
1582 static unsigned char request
[5], *response
, *p
;
1583 static int responselen
;
1584 static int i
, nkeys
;
1585 static int authed
= FALSE
;
1588 logevent("Pageant is running. Requesting keys.");
1590 /* Request the keys held by the agent. */
1591 PUT_32BIT(request
, 1);
1592 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1593 agent_query(request
, 5, &r
, &responselen
);
1594 response
= (unsigned char *)r
;
1597 nkeys
= GET_32BIT(p
); p
+= 4;
1598 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1600 for (i
= 0; i
< nkeys
; i
++) {
1601 static struct RSAKey key
;
1602 static Bignum challenge
;
1603 static char *commentp
;
1604 static int commentlen
;
1606 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1609 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1610 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1611 commentlen
= GET_32BIT(p
); p
+= 4;
1612 commentp
= p
; p
+= commentlen
;
1613 send_packet(SSH1_CMSG_AUTH_RSA
,
1614 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1616 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1617 logevent("Key refused");
1620 logevent("Received RSA challenge");
1621 ssh1_read_bignum(pktin
.body
, &challenge
);
1623 char *agentreq
, *q
, *ret
;
1625 len
= 1 + 4; /* message type, bit count */
1626 len
+= ssh1_bignum_length(key
.exponent
);
1627 len
+= ssh1_bignum_length(key
.modulus
);
1628 len
+= ssh1_bignum_length(challenge
);
1629 len
+= 16; /* session id */
1630 len
+= 4; /* response format */
1631 agentreq
= smalloc(4 + len
);
1632 PUT_32BIT(agentreq
, len
);
1634 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1635 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1637 q
+= ssh1_write_bignum(q
, key
.exponent
);
1638 q
+= ssh1_write_bignum(q
, key
.modulus
);
1639 q
+= ssh1_write_bignum(q
, challenge
);
1640 memcpy(q
, session_id
, 16); q
+= 16;
1641 PUT_32BIT(q
, 1); /* response format */
1642 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1645 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1646 logevent("Sending Pageant's response");
1647 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1648 PKT_DATA
, ret
+5, 16, PKT_END
);
1651 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1652 logevent("Pageant's response accepted");
1653 if (flags
& FLAG_VERBOSE
) {
1654 c_write_str("Authenticated using RSA key \"");
1655 c_write(commentp
, commentlen
);
1656 c_write_str("\" from agent\r\n");
1660 logevent("Pageant's response not accepted");
1662 logevent("Pageant failed to answer challenge");
1666 logevent("No reply received from Pageant");
1669 freebn(key
.exponent
);
1670 freebn(key
.modulus
);
1679 if (*cfg
.keyfile
&& !tried_publickey
)
1680 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1682 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1684 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1685 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1686 logevent("Requested TIS authentication");
1687 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1689 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1690 logevent("TIS authentication declined");
1691 if (flags
& FLAG_INTERACTIVE
)
1692 c_write_str("TIS authentication refused.\r\n");
1694 int challengelen
= ((pktin
.body
[0] << 24) |
1695 (pktin
.body
[1] << 16) |
1696 (pktin
.body
[2] << 8) |
1698 logevent("Received TIS challenge");
1699 if (challengelen
> sizeof(prompt
)-1)
1700 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1701 memcpy(prompt
, pktin
.body
+4, challengelen
);
1702 prompt
[challengelen
] = '\0';
1705 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1707 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1708 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1709 logevent("Requested CryptoCard authentication");
1710 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1712 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1713 logevent("CryptoCard authentication declined");
1714 c_write_str("CryptoCard authentication refused.\r\n");
1716 int challengelen
= ((pktin
.body
[0] << 24) |
1717 (pktin
.body
[1] << 16) |
1718 (pktin
.body
[2] << 8) |
1720 logevent("Received CryptoCard challenge");
1721 if (challengelen
> sizeof(prompt
)-1)
1722 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1723 memcpy(prompt
, pktin
.body
+4, challengelen
);
1724 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1725 sizeof(prompt
)-challengelen
);
1726 prompt
[sizeof(prompt
)-1] = '\0';
1729 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1730 sprintf(prompt
, "%.90s@%.90s's password: ",
1731 username
, savedhost
);
1733 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1734 char *comment
= NULL
;
1735 if (flags
& FLAG_VERBOSE
)
1736 c_write_str("Trying public key authentication.\r\n");
1737 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1738 if (flags
& FLAG_VERBOSE
)
1739 c_write_str("No passphrase required.\r\n");
1742 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1746 if (ssh_get_password
) {
1747 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1749 * get_password failed to get a password (for
1750 * example because one was supplied on the command
1751 * line which has already failed to work).
1754 logevent("No more passwords to try");
1755 ssh_state
= SSH_STATE_CLOSED
;
1759 c_write_str(prompt
);
1763 crWaitUntil(!ispkt
);
1764 while (inlen
--) switch (c
= *in
++) {
1781 if (((c
>= ' ' && c
<= '~') ||
1782 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1783 password
[pos
++] = c
;
1787 c_write_str("\r\n");
1791 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1793 * Try public key authentication with the specified
1796 static struct RSAKey pubkey
;
1797 static Bignum challenge
, response
;
1799 static unsigned char buffer
[32];
1801 tried_publickey
= 1;
1802 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1804 c_write_str("Couldn't load public key from ");
1805 c_write_str(cfg
.keyfile
);
1806 c_write_str(".\r\n");
1807 continue; /* go and try password */
1810 c_write_str("Wrong passphrase.\r\n");
1811 tried_publickey
= 0;
1812 continue; /* try again */
1816 * Send a public key attempt.
1818 send_packet(SSH1_CMSG_AUTH_RSA
,
1819 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1822 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1823 c_write_str("Server refused our public key.\r\n");
1824 continue; /* go and try password */
1826 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1827 bombout(("Bizarre response to offer of public key"));
1830 ssh1_read_bignum(pktin
.body
, &challenge
);
1831 response
= rsadecrypt(challenge
, &pubkey
);
1832 freebn(pubkey
.private_exponent
); /* burn the evidence */
1834 for (i
= 0; i
< 32; i
++) {
1835 buffer
[i
] = bignum_byte(response
, 31-i
);
1839 MD5Update(&md5c
, buffer
, 32);
1840 MD5Update(&md5c
, session_id
, 16);
1841 MD5Final(buffer
, &md5c
);
1843 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1844 PKT_DATA
, buffer
, 16, PKT_END
);
1847 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1848 if (flags
& FLAG_VERBOSE
)
1849 c_write_str("Failed to authenticate with our public key.\r\n");
1850 continue; /* go and try password */
1851 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1852 bombout(("Bizarre response to RSA authentication response"));
1856 break; /* we're through! */
1858 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1860 * Defence against traffic analysis: we send a
1861 * whole bunch of packets containing strings of
1862 * different lengths. One of these strings is the
1863 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1864 * The others are all random data in
1865 * SSH1_MSG_IGNORE packets. This way a passive
1866 * listener can't tell which is the password, and
1867 * hence can't deduce the password length.
1869 * Anybody with a password length greater than 16
1870 * bytes is going to have enough entropy in their
1871 * password that a listener won't find it _that_
1872 * much help to know how long it is. So what we'll
1875 * - if password length < 16, we send 15 packets
1876 * containing string lengths 1 through 15
1878 * - otherwise, we let N be the nearest multiple
1879 * of 8 below the password length, and send 8
1880 * packets containing string lengths N through
1881 * N+7. This won't obscure the order of
1882 * magnitude of the password length, but it will
1883 * introduce a bit of extra uncertainty.
1885 * A few servers (the old 1.2.18 through 1.2.22)
1886 * can't deal with SSH1_MSG_IGNORE. For these
1887 * servers, we need an alternative defence. We make
1888 * use of the fact that the password is interpreted
1889 * as a C string: so we can append a NUL, then some
1892 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
1897 len
= strlen(password
);
1898 if (len
< sizeof(string
)) {
1900 strcpy(string
, password
);
1901 len
++; /* cover the zero byte */
1902 while (len
< sizeof(string
)) {
1903 string
[len
++] = (char)random_byte();
1908 send_packet(pwpkt_type
, PKT_INT
, len
,
1909 PKT_DATA
, s
, len
, PKT_END
);
1911 int bottom
, top
, pwlen
, i
;
1914 pwlen
= strlen(password
);
1919 bottom
= pwlen
&~ 7;
1923 assert(pwlen
>= bottom
&& pwlen
<= top
);
1925 randomstr
= smalloc(top
+1);
1927 for (i
= bottom
; i
<= top
; i
++) {
1929 defer_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1931 for (j
= 0; j
< i
; j
++) {
1933 randomstr
[j
] = random_byte();
1934 } while (randomstr
[j
] == '\0');
1936 randomstr
[i
] = '\0';
1937 defer_packet(SSH1_MSG_IGNORE
,
1938 PKT_STR
, randomstr
, PKT_END
);
1941 ssh_pkt_defersend();
1944 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1947 logevent("Sent password");
1948 memset(password
, 0, strlen(password
));
1950 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1951 if (flags
& FLAG_VERBOSE
)
1952 c_write_str("Access denied\r\n");
1953 logevent("Authentication refused");
1954 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1955 logevent("Received disconnect request");
1956 ssh_state
= SSH_STATE_CLOSED
;
1958 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1959 bombout(("Strange packet received, type %d", pktin
.type
));
1964 logevent("Authentication successful");
1969 void sshfwd_close(struct ssh_channel
*c
) {
1971 if (ssh_version
== 1) {
1972 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
, PKT_END
);
1974 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
1975 ssh2_pkt_adduint32(c
->remoteid
);
1979 if (c
->type
== CHAN_X11
) {
1981 logevent("X11 connection terminated");
1986 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
) {
1987 if (ssh_version
== 1) {
1988 send_packet(SSH1_MSG_CHANNEL_DATA
,
1989 PKT_INT
, c
->remoteid
,
1994 ssh2_add_channel_data(c
, buf
, len
);
1999 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
2004 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2007 if (ssh_state
== SSH_STATE_CLOSED
)
2010 if (cfg
.agentfwd
&& agent_exists()) {
2011 logevent("Requesting agent forwarding");
2012 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2013 do { crReturnV
; } while (!ispkt
);
2014 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2015 bombout(("Protocol confusion"));
2017 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2018 logevent("Agent forwarding refused");
2020 logevent("Agent forwarding enabled");
2021 ssh_agentfwd_enabled
= TRUE
;
2025 if (cfg
.x11_forward
) {
2026 char proto
[20], data
[64];
2027 logevent("Requesting X11 forwarding");
2028 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2029 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2030 PKT_STR
, proto
, PKT_STR
, data
,
2033 do { crReturnV
; } while (!ispkt
);
2034 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2035 bombout(("Protocol confusion"));
2037 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2038 logevent("X11 forwarding refused");
2040 logevent("X11 forwarding enabled");
2041 ssh_X11_fwd_enabled
= TRUE
;
2046 send_packet(SSH1_CMSG_REQUEST_PTY
,
2047 PKT_STR
, cfg
.termtype
,
2048 PKT_INT
, rows
, PKT_INT
, cols
,
2049 PKT_INT
, 0, PKT_INT
, 0,
2052 ssh_state
= SSH_STATE_INTERMED
;
2053 do { crReturnV
; } while (!ispkt
);
2054 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2055 bombout(("Protocol confusion"));
2057 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2058 c_write_str("Server refused to allocate pty\r\n");
2059 ssh_editing
= ssh_echoing
= 1;
2061 logevent("Allocated pty");
2063 ssh_editing
= ssh_echoing
= 1;
2066 if (cfg
.compression
) {
2067 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2068 do { crReturnV
; } while (!ispkt
);
2069 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2070 bombout(("Protocol confusion"));
2072 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2073 c_write_str("Server refused to compress\r\n");
2075 logevent("Started compression");
2076 ssh1_compressing
= TRUE
;
2077 zlib_compress_init();
2078 zlib_decompress_init();
2081 if (*cfg
.remote_cmd
)
2082 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
2084 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2085 logevent("Started session");
2087 ssh_state
= SSH_STATE_SESSION
;
2091 ssh_special(TS_EOF
);
2093 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2095 ssh_channels
= newtree234(ssh_channelcmp
);
2099 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2100 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2101 long len
= GET_32BIT(pktin
.body
);
2102 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2104 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2105 ssh_state
= SSH_STATE_CLOSED
;
2106 logevent("Received disconnect request");
2108 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2109 /* Remote side is trying to open a channel to talk to our
2110 * X-Server. Give them back a local channel number. */
2112 struct ssh_channel
*c
, *d
;
2115 logevent("Received X11 connect request");
2116 /* Refuse if X11 forwarding is disabled. */
2117 if (!ssh_X11_fwd_enabled
) {
2118 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2119 PKT_INT
, GET_32BIT(pktin
.body
),
2121 logevent("Rejected X11 connect request");
2123 c
= smalloc(sizeof(struct ssh_channel
));
2125 if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2126 logevent("opening X11 forward connection failed");
2128 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2129 PKT_INT
, GET_32BIT(pktin
.body
),
2132 logevent("opening X11 forward connection succeeded");
2133 for (i
=1, d
= first234(ssh_channels
, &e
); d
; d
= next234(&e
)) {
2135 break; /* found a free number */
2138 c
->remoteid
= GET_32BIT(pktin
.body
);
2141 c
->type
= CHAN_X11
; /* identify channel type */
2142 add234(ssh_channels
, c
);
2143 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2144 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2146 logevent("Opened X11 forward channel");
2149 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2150 /* Remote side is trying to open a channel to talk to our
2151 * agent. Give them back a local channel number. */
2153 struct ssh_channel
*c
;
2156 /* Refuse if agent forwarding is disabled. */
2157 if (!ssh_agentfwd_enabled
) {
2158 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2159 PKT_INT
, GET_32BIT(pktin
.body
),
2163 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
2165 break; /* found a free number */
2168 c
= smalloc(sizeof(struct ssh_channel
));
2169 c
->remoteid
= GET_32BIT(pktin
.body
);
2172 c
->type
= CHAN_AGENT
; /* identify channel type */
2173 c
->u
.a
.lensofar
= 0;
2174 add234(ssh_channels
, c
);
2175 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2176 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2179 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2180 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2181 /* Remote side closes a channel. */
2182 unsigned i
= GET_32BIT(pktin
.body
);
2183 struct ssh_channel
*c
;
2184 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2187 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2188 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
2189 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2190 logevent("X11 connection closed");
2191 assert(c
->u
.x11
.s
!= NULL
);
2192 x11_close(c
->u
.x11
.s
);
2195 c
->closes
|= closetype
;
2196 if (c
->closes
== 3) {
2197 del234(ssh_channels
, c
);
2201 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2202 /* Data sent down one of our channels. */
2203 int i
= GET_32BIT(pktin
.body
);
2204 int len
= GET_32BIT(pktin
.body
+4);
2205 unsigned char *p
= pktin
.body
+8;
2206 struct ssh_channel
*c
;
2207 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2211 x11_send(c
->u
.x11
.s
, p
, len
);
2214 /* Data for an agent message. Buffer it. */
2216 if (c
->u
.a
.lensofar
< 4) {
2217 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2218 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
2219 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2221 if (c
->u
.a
.lensofar
== 4) {
2222 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
2223 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2224 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2226 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2227 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
2228 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
2229 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2231 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2232 void *reply
, *sentreply
;
2234 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
2239 /* Fake SSH_AGENT_FAILURE. */
2240 sentreply
= "\0\0\0\1\5";
2243 send_packet(SSH1_MSG_CHANNEL_DATA
,
2244 PKT_INT
, c
->remoteid
,
2246 PKT_DATA
, sentreply
, replylen
,
2250 sfree(c
->u
.a
.message
);
2251 c
->u
.a
.lensofar
= 0;
2257 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2258 /* may be from EXEC_SHELL on some servers */
2259 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2260 /* may be from EXEC_SHELL on some servers
2261 * if no pty is available or in other odd cases. Ignore */
2262 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2263 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2265 bombout(("Strange packet received: type %d", pktin
.type
));
2270 int len
= min(inlen
, 512);
2271 send_packet(SSH1_CMSG_STDIN_DATA
,
2272 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2283 * Utility routine for decoding comma-separated strings in KEXINIT.
2285 static int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
2286 int needlen
= strlen(needle
);
2289 * Is it at the start of the string?
2291 if (haylen
>= needlen
&& /* haystack is long enough */
2292 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2293 (haylen
== needlen
|| haystack
[needlen
] == ',')
2294 /* either , or EOS follows */
2298 * If not, search for the next comma and resume after that.
2299 * If no comma found, terminate.
2301 while (haylen
> 0 && *haystack
!= ',')
2302 haylen
--, haystack
++;
2305 haylen
--, haystack
++; /* skip over comma itself */
2310 * SSH2 key creation method.
2312 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
, char *keyspace
) {
2314 /* First 20 bytes. */
2317 SHA_Bytes(&s
, H
, 20);
2318 SHA_Bytes(&s
, &chr
, 1);
2319 SHA_Bytes(&s
, sessid
, 20);
2320 SHA_Final(&s
, keyspace
);
2321 /* Next 20 bytes. */
2324 SHA_Bytes(&s
, H
, 20);
2325 SHA_Bytes(&s
, keyspace
, 20);
2326 SHA_Final(&s
, keyspace
+20);
2330 * Handle the SSH2 transport layer.
2332 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2334 static int i
, j
, len
, nbits
;
2336 static Bignum p
, g
, e
, f
, K
;
2337 static int kex_init_value
, kex_reply_value
;
2338 static const struct ssh_mac
**maclist
;
2340 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2341 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2342 static const struct ssh_mac
*csmac_tobe
= NULL
;
2343 static const struct ssh_mac
*scmac_tobe
= NULL
;
2344 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2345 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2346 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2347 static int hostkeylen
, siglen
;
2348 static void *hkey
; /* actual host key */
2349 static unsigned char exchange_hash
[20];
2350 static unsigned char keyspace
[40];
2351 static const struct ssh2_ciphers
*preferred_cipher
;
2352 static const struct ssh_compress
*preferred_comp
;
2353 static int first_kex
;
2360 * Set up the preferred cipher and compression.
2362 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2363 preferred_cipher
= &ssh2_blowfish
;
2364 } else if (cfg
.cipher
== CIPHER_DES
) {
2365 logevent("Single DES not supported in SSH2; using 3DES");
2366 preferred_cipher
= &ssh2_3des
;
2367 } else if (cfg
.cipher
== CIPHER_3DES
) {
2368 preferred_cipher
= &ssh2_3des
;
2369 } else if (cfg
.cipher
== CIPHER_AES
) {
2370 preferred_cipher
= &ssh2_aes
;
2372 /* Shouldn't happen, but we do want to initialise to _something_. */
2373 preferred_cipher
= &ssh2_3des
;
2375 if (cfg
.compression
)
2376 preferred_comp
= &ssh_zlib
;
2378 preferred_comp
= &ssh_comp_none
;
2381 * Be prepared to work around the buggy MAC problem.
2383 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2384 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2386 maclist
= macs
, nmacs
= lenof(macs
);
2390 * Construct and send our key exchange packet.
2392 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2393 for (i
= 0; i
< 16; i
++)
2394 ssh2_pkt_addbyte((unsigned char)random_byte());
2395 /* List key exchange algorithms. */
2396 ssh2_pkt_addstring_start();
2397 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2398 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2399 if (i
< lenof(kex_algs
)-1)
2400 ssh2_pkt_addstring_str(",");
2402 /* List server host key algorithms. */
2403 ssh2_pkt_addstring_start();
2404 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2405 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2406 if (i
< lenof(hostkey_algs
)-1)
2407 ssh2_pkt_addstring_str(",");
2409 /* List client->server encryption algorithms. */
2410 ssh2_pkt_addstring_start();
2411 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2412 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2413 for (j
= 0; j
< c
->nciphers
; j
++) {
2414 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2415 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2416 ssh2_pkt_addstring_str(",");
2419 /* List server->client encryption algorithms. */
2420 ssh2_pkt_addstring_start();
2421 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2422 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2423 for (j
= 0; j
< c
->nciphers
; j
++) {
2424 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2425 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2426 ssh2_pkt_addstring_str(",");
2429 /* List client->server MAC algorithms. */
2430 ssh2_pkt_addstring_start();
2431 for (i
= 0; i
< nmacs
; i
++) {
2432 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2434 ssh2_pkt_addstring_str(",");
2436 /* List server->client MAC algorithms. */
2437 ssh2_pkt_addstring_start();
2438 for (i
= 0; i
< nmacs
; i
++) {
2439 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2441 ssh2_pkt_addstring_str(",");
2443 /* List client->server compression algorithms. */
2444 ssh2_pkt_addstring_start();
2445 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2446 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2447 ssh2_pkt_addstring_str(c
->name
);
2448 if (i
< lenof(compressions
))
2449 ssh2_pkt_addstring_str(",");
2451 /* List server->client compression algorithms. */
2452 ssh2_pkt_addstring_start();
2453 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2454 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2455 ssh2_pkt_addstring_str(c
->name
);
2456 if (i
< lenof(compressions
))
2457 ssh2_pkt_addstring_str(",");
2459 /* List client->server languages. Empty list. */
2460 ssh2_pkt_addstring_start();
2461 /* List server->client languages. Empty list. */
2462 ssh2_pkt_addstring_start();
2463 /* First KEX packet does _not_ follow, because we're not that brave. */
2464 ssh2_pkt_addbool(FALSE
);
2466 ssh2_pkt_adduint32(0);
2468 exhash
= exhashbase
;
2469 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
2473 if (!ispkt
) crWaitUntil(ispkt
);
2474 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
2477 * Now examine the other side's KEXINIT to see what we're up
2480 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2481 bombout(("expected key exchange packet from server"));
2484 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
2485 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
2486 pktin
.savedpos
+= 16; /* skip garbage cookie */
2487 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2488 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2489 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2494 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2495 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2496 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2497 hostkey
= hostkey_algs
[i
];
2501 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2502 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2503 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2504 for (j
= 0; j
< c
->nciphers
; j
++) {
2505 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2506 cscipher_tobe
= c
->list
[j
];
2513 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2514 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2515 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2516 for (j
= 0; j
< c
->nciphers
; j
++) {
2517 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2518 sccipher_tobe
= c
->list
[j
];
2525 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2526 for (i
= 0; i
< nmacs
; i
++) {
2527 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2528 csmac_tobe
= maclist
[i
];
2532 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2533 for (i
= 0; i
< nmacs
; i
++) {
2534 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2535 scmac_tobe
= maclist
[i
];
2539 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2540 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2541 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2542 if (in_commasep_string(c
->name
, str
, len
)) {
2547 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2548 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2549 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2550 if (in_commasep_string(c
->name
, str
, len
)) {
2557 * If we're doing Diffie-Hellman group exchange, start by
2558 * requesting a group.
2560 if (kex
== &ssh_diffiehellman_gex
) {
2563 logevent("Doing Diffie-Hellman group exchange");
2565 * Work out number of bits. We start with the maximum key
2566 * length of either cipher...
2568 csbits
= cscipher_tobe
->keylen
;
2569 scbits
= sccipher_tobe
->keylen
;
2570 nbits
= (csbits
> scbits ? csbits
: scbits
);
2571 /* The keys only have 160-bit entropy, since they're based on
2572 * a SHA-1 hash. So cap the key size at 160 bits. */
2573 if (nbits
> 160) nbits
= 160;
2575 * ... and then work out how big a DH group we will need to
2576 * allow that much data.
2578 nbits
= 512 << ((nbits
-1) / 64);
2579 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2580 ssh2_pkt_adduint32(nbits
);
2584 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2585 bombout(("expected key exchange group packet from server"));
2588 p
= ssh2_pkt_getmp();
2589 g
= ssh2_pkt_getmp();
2590 dh_setup_group(p
, g
);
2591 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2592 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2595 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2596 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2599 logevent("Doing Diffie-Hellman key exchange");
2601 * Now generate and send e for Diffie-Hellman.
2604 ssh2_pkt_init(kex_init_value
);
2609 if (pktin
.type
!= kex_reply_value
) {
2610 bombout(("expected key exchange reply packet from server"));
2613 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2614 f
= ssh2_pkt_getmp();
2615 ssh2_pkt_getstring(&sigdata
, &siglen
);
2619 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2620 if (kex
== &ssh_diffiehellman_gex
) {
2621 sha_uint32(&exhash
, nbits
);
2622 sha_mpint(&exhash
, p
);
2623 sha_mpint(&exhash
, g
);
2625 sha_mpint(&exhash
, e
);
2626 sha_mpint(&exhash
, f
);
2627 sha_mpint(&exhash
, K
);
2628 SHA_Final(&exhash
, exchange_hash
);
2633 debug(("Exchange hash is:\r\n"));
2634 for (i
= 0; i
< 20; i
++)
2635 debug((" %02x", exchange_hash
[i
]));
2639 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2640 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2641 bombout(("Server failed host key check"));
2646 * Expect SSH2_MSG_NEWKEYS from server.
2649 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2650 bombout(("expected new-keys packet from server"));
2655 * Authenticate remote host: verify host key. (We've already
2656 * checked the signature of the exchange hash.)
2658 keystr
= hostkey
->fmtkey(hkey
);
2659 fingerprint
= hostkey
->fingerprint(hkey
);
2660 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2661 keystr
, fingerprint
);
2662 if (first_kex
) { /* don't bother logging this in rekeys */
2663 logevent("Host key fingerprint is:");
2664 logevent(fingerprint
);
2668 hostkey
->freekey(hkey
);
2671 * Send SSH2_MSG_NEWKEYS.
2673 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2677 * Create and initialise session keys.
2679 cscipher
= cscipher_tobe
;
2680 sccipher
= sccipher_tobe
;
2683 cscomp
= cscomp_tobe
;
2684 sccomp
= sccomp_tobe
;
2685 cscomp
->compress_init();
2686 sccomp
->decompress_init();
2688 * Set IVs after keys. Here we use the exchange hash from the
2689 * _first_ key exchange.
2692 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
2693 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
2694 cscipher
->setcskey(keyspace
);
2695 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
2696 sccipher
->setsckey(keyspace
);
2697 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
2698 cscipher
->setcsiv(keyspace
);
2699 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
2700 sccipher
->setsciv(keyspace
);
2701 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
2702 csmac
->setcskey(keyspace
);
2703 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
2704 scmac
->setsckey(keyspace
);
2707 * If this is the first key exchange phase, we must pass the
2708 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2709 * wants to see it but because it will need time to initialise
2710 * itself before it sees an actual packet. In subsequent key
2711 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2712 * it would only confuse the layer above.
2720 * Now we're encrypting. Begin returning 1 to the protocol main
2721 * function so that other things can run on top of the
2722 * transport. If we ever see a KEXINIT, we must go back to the
2725 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
2728 logevent("Server initiated key re-exchange");
2729 goto begin_key_exchange
;
2735 * Add data to an SSH2 channel output buffer.
2737 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
) {
2738 if (c
->v2
.outbufsize
<
2739 c
->v2
.outbuflen
+ len
) {
2741 c
->v2
.outbuflen
+ len
+ 1024;
2742 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
,
2745 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
,
2747 c
->v2
.outbuflen
+= len
;
2751 * Attempt to send data on an SSH2 channel.
2753 static void ssh2_try_send(struct ssh_channel
*c
) {
2754 while (c
->v2
.remwindow
> 0 &&
2755 c
->v2
.outbuflen
> 0) {
2756 unsigned len
= c
->v2
.remwindow
;
2757 if (len
> c
->v2
.outbuflen
)
2758 len
= c
->v2
.outbuflen
;
2759 if (len
> c
->v2
.remmaxpkt
)
2760 len
= c
->v2
.remmaxpkt
;
2761 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2762 ssh2_pkt_adduint32(c
->remoteid
);
2763 ssh2_pkt_addstring_start();
2764 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
2766 c
->v2
.outbuflen
-= len
;
2767 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+len
,
2769 c
->v2
.remwindow
-= len
;
2774 * Handle the SSH2 userauth and connection layers.
2776 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2778 static unsigned long remote_winsize
;
2779 static unsigned long remote_maxpkt
;
2781 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
, AUTH_PASSWORD
2785 AUTH_TYPE_PUBLICKEY
,
2786 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
2787 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
2790 static int gotit
, need_pw
, can_pubkey
, can_passwd
;
2791 static int tried_pubkey_config
, tried_agent
;
2792 static int we_are_in
;
2793 static char username
[100];
2794 static char pwprompt
[200];
2795 static char password
[100];
2800 * Request userauth protocol, and await a response to it.
2802 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2803 ssh2_pkt_addstring("ssh-userauth");
2805 crWaitUntilV(ispkt
);
2806 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2807 bombout(("Server refused user authentication protocol"));
2812 * We repeat this whole loop, including the username prompt,
2813 * until we manage a successful authentication. If the user
2814 * types the wrong _password_, they are sent back to the
2815 * beginning to try another username. (If they specify a
2816 * username in the config, they are never asked, even if they
2817 * do give a wrong password.)
2819 * I think this best serves the needs of
2821 * - the people who have no configuration, no keys, and just
2822 * want to try repeated (username,password) pairs until they
2823 * type both correctly
2825 * - people who have keys and configuration but occasionally
2826 * need to fall back to passwords
2828 * - people with a key held in Pageant, who might not have
2829 * logged in to a particular machine before; so they want to
2830 * type a username, and then _either_ their key will be
2831 * accepted, _or_ they will type a password. If they mistype
2832 * the username they will want to be able to get back and
2843 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2844 c_write_str("login as: ");
2847 crWaitUntilV(!ispkt
);
2848 while (inlen
--) switch (c
= *in
++) {
2855 c_write_str("\b \b");
2861 c_write_str("\b \b");
2870 if (((c
>= ' ' && c
<= '~') ||
2871 ((unsigned char)c
>= 160)) && pos
< 40) {
2872 username
[pos
++] = c
;
2878 c_write_str("\r\n");
2879 username
[strcspn(username
, "\n\r")] = '\0';
2882 strncpy(username
, cfg
.username
, 99);
2883 username
[99] = '\0';
2884 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2885 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2891 * Send an authentication request using method "none": (a)
2892 * just in case it succeeds, and (b) so that we know what
2893 * authentication methods we can usefully try next.
2895 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2896 ssh2_pkt_addstring(username
);
2897 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2898 ssh2_pkt_addstring("none"); /* method */
2900 type
= AUTH_TYPE_NONE
;
2904 tried_pubkey_config
= FALSE
;
2905 tried_agent
= FALSE
;
2909 * Wait for the result of the last authentication request.
2912 crWaitUntilV(ispkt
);
2913 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
2914 /* FIXME: should support this */
2915 crWaitUntilV(ispkt
);
2917 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
2918 logevent("Access granted");
2923 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
2924 bombout(("Strange packet received during authentication: type %d",
2931 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2932 * we can look at the string in it and know what we can
2933 * helpfully try next.
2938 ssh2_pkt_getstring(&methods
, &methlen
);
2939 if (!ssh2_pkt_getbool()) {
2941 * We have received an unequivocal Access
2942 * Denied. This can translate to a variety of
2945 * - if we'd just tried "none" authentication,
2946 * it's not worth printing anything at all
2948 * - if we'd just tried a public key _offer_,
2949 * the message should be "Server refused our
2950 * key" (or no message at all if the key
2951 * came from Pageant)
2953 * - if we'd just tried anything else, the
2954 * message really should be "Access denied".
2956 * Additionally, if we'd just tried password
2957 * authentication, we should break out of this
2958 * whole loop so as to go back to the username
2961 if (type
== AUTH_TYPE_NONE
) {
2963 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
2964 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
2965 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
2966 c_write_str("Server refused our key\r\n");
2967 logevent("Server refused public key");
2969 c_write_str("Access denied\r\n");
2970 logevent("Access denied");
2971 if (type
== AUTH_TYPE_PASSWORD
) {
2977 c_write_str("Further authentication required\r\n");
2978 logevent("Further authentication required");
2981 can_pubkey
= in_commasep_string("publickey", methods
, methlen
);
2982 can_passwd
= in_commasep_string("password", methods
, methlen
);
2987 if (!method
&& can_pubkey
&& agent_exists
&& !tried_agent
) {
2989 * Attempt public-key authentication using Pageant.
2991 static unsigned char request
[5], *response
, *p
;
2992 static int responselen
;
2993 static int i
, nkeys
;
2994 static int authed
= FALSE
;
2999 logevent("Pageant is running. Requesting keys.");
3001 /* Request the keys held by the agent. */
3002 PUT_32BIT(request
, 1);
3003 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3004 agent_query(request
, 5, &r
, &responselen
);
3005 response
= (unsigned char *)r
;
3008 nkeys
= GET_32BIT(p
); p
+= 4;
3009 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3011 for (i
= 0; i
< nkeys
; i
++) {
3012 static char *pkblob
, *alg
, *commentp
;
3013 static int pklen
, alglen
, commentlen
;
3014 static int siglen
, retlen
, len
;
3015 static char *q
, *agentreq
, *ret
;
3017 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
3019 pklen
= GET_32BIT(p
); p
+= 4;
3020 pkblob
= p
; p
+= pklen
;
3021 alglen
= GET_32BIT(pkblob
);
3023 commentlen
= GET_32BIT(p
); p
+= 4;
3024 commentp
= p
; p
+= commentlen
;
3025 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3026 ssh2_pkt_addstring(username
);
3027 ssh2_pkt_addstring("ssh-connection");/* service requested */
3028 ssh2_pkt_addstring("publickey");/* method */
3029 ssh2_pkt_addbool(FALSE
); /* no signature included */
3030 ssh2_pkt_addstring_start();
3031 ssh2_pkt_addstring_data(alg
, alglen
);
3032 ssh2_pkt_addstring_start();
3033 ssh2_pkt_addstring_data(pkblob
, pklen
);
3036 crWaitUntilV(ispkt
);
3037 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3038 logevent("Key refused");
3042 c_write_str("Authenticating with public key \"");
3043 c_write(commentp
, commentlen
);
3044 c_write_str("\" from agent\r\n");
3047 * Server is willing to accept the key.
3048 * Construct a SIGN_REQUEST.
3050 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3051 ssh2_pkt_addstring(username
);
3052 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3053 ssh2_pkt_addstring("publickey"); /* method */
3054 ssh2_pkt_addbool(TRUE
);
3055 ssh2_pkt_addstring_start();
3056 ssh2_pkt_addstring_data(alg
, alglen
);
3057 ssh2_pkt_addstring_start();
3058 ssh2_pkt_addstring_data(pkblob
, pklen
);
3060 siglen
= pktout
.length
- 5 + 4 + 20;
3061 len
= 1; /* message type */
3062 len
+= 4 + pklen
; /* key blob */
3063 len
+= 4 + siglen
; /* data to sign */
3064 len
+= 4; /* flags */
3065 agentreq
= smalloc(4 + len
);
3066 PUT_32BIT(agentreq
, len
);
3068 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3069 PUT_32BIT(q
, pklen
); q
+= 4;
3070 memcpy(q
, pkblob
, pklen
); q
+= pklen
;
3071 PUT_32BIT(q
, siglen
); q
+= 4;
3072 /* Now the data to be signed... */
3073 PUT_32BIT(q
, 20); q
+= 4;
3074 memcpy(q
, ssh2_session_id
, 20); q
+= 20;
3075 memcpy(q
, pktout
.data
+5, pktout
.length
-5);
3076 q
+= pktout
.length
-5;
3077 /* And finally the (zero) flags word. */
3079 agent_query(agentreq
, len
+4, &ret
, &retlen
);
3082 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3083 logevent("Sending Pageant's response");
3084 ssh2_pkt_addstring_start();
3085 ssh2_pkt_addstring_data(ret
+9, GET_32BIT(ret
+5));
3090 logevent("Pageant failed to answer challenge");
3100 if (!method
&& can_pubkey
&& *cfg
.keyfile
&& !tried_pubkey_config
) {
3101 unsigned char *pub_blob
;
3102 char *algorithm
, *comment
;
3105 tried_pubkey_config
= TRUE
;
3108 * Try the public key supplied in the configuration.
3110 * First, offer the public blob to see if the server is
3111 * willing to accept it.
3113 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3116 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3117 ssh2_pkt_addstring(username
);
3118 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3119 ssh2_pkt_addstring("publickey");/* method */
3120 ssh2_pkt_addbool(FALSE
); /* no signature included */
3121 ssh2_pkt_addstring(algorithm
);
3122 ssh2_pkt_addstring_start();
3123 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3125 logevent("Offered public key"); /* FIXME */
3127 crWaitUntilV(ispkt
);
3128 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3130 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3131 continue; /* key refused; give up on it */
3134 logevent("Offer of public key accepted");
3136 * Actually attempt a serious authentication using
3139 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3140 sprintf(pwprompt
, "Passphrase for key \"%.100s\": ", comment
);
3145 c_write_str("Authenticating with public key \"");
3146 c_write_str(comment
);
3147 c_write_str("\"\r\n");
3148 method
= AUTH_PUBLICKEY_FILE
;
3152 if (!method
&& can_passwd
) {
3153 method
= AUTH_PASSWORD
;
3154 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
, savedhost
);
3159 if (ssh_get_password
) {
3160 if (!ssh_get_password(pwprompt
, password
, sizeof(password
))) {
3162 * get_password failed to get a password (for
3163 * example because one was supplied on the command
3164 * line which has already failed to work).
3167 logevent("No more passwords to try");
3168 ssh_state
= SSH_STATE_CLOSED
;
3175 c_write_str(pwprompt
);
3180 crWaitUntilV(!ispkt
);
3181 while (inlen
--) switch (c
= *in
++) {
3198 if (((c
>= ' ' && c
<= '~') ||
3199 ((unsigned char)c
>= 160)) && pos
< 40)
3200 password
[pos
++] = c
;
3204 c_write_str("\r\n");
3208 if (method
== AUTH_PUBLICKEY_FILE
) {
3210 * We have our passphrase. Now try the actual authentication.
3212 struct ssh2_userkey
*key
;
3214 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3215 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3216 if (key
== SSH2_WRONG_PASSPHRASE
) {
3217 c_write_str("Wrong passphrase\r\n");
3218 tried_pubkey_config
= FALSE
;
3220 c_write_str("Unable to load private key\r\n");
3221 tried_pubkey_config
= TRUE
;
3223 /* Send a spurious AUTH_NONE to return to the top. */
3224 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3225 ssh2_pkt_addstring(username
);
3226 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3227 ssh2_pkt_addstring("none"); /* method */
3229 type
= AUTH_TYPE_NONE
;
3231 unsigned char *blob
, *sigdata
;
3232 int blob_len
, sigdata_len
;
3235 * We have loaded the private key and the server
3236 * has announced that it's willing to accept it.
3237 * Hallelujah. Generate a signature and send it.
3239 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3240 ssh2_pkt_addstring(username
);
3241 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3242 ssh2_pkt_addstring("publickey"); /* method */
3243 ssh2_pkt_addbool(TRUE
);
3244 ssh2_pkt_addstring(key
->alg
->name
);
3245 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3246 ssh2_pkt_addstring_start();
3247 ssh2_pkt_addstring_data(blob
, blob_len
);
3251 * The data to be signed is:
3255 * followed by everything so far placed in the
3258 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3259 sigdata
= smalloc(sigdata_len
);
3260 PUT_32BIT(sigdata
, 20);
3261 memcpy(sigdata
+4, ssh2_session_id
, 20);
3262 memcpy(sigdata
+24, pktout
.data
+5, pktout
.length
-5);
3263 blob
= key
->alg
->sign(key
->data
, sigdata
, sigdata_len
, &blob_len
);
3264 ssh2_pkt_addstring_start();
3265 ssh2_pkt_addstring_data(blob
, blob_len
);
3270 type
= AUTH_TYPE_PUBLICKEY
;
3272 } else if (method
== AUTH_PASSWORD
) {
3274 * We send the password packet lumped tightly together with
3275 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3276 * string long enough to make the total length of the two
3277 * packets constant. This should ensure that a passive
3278 * listener doing traffic analyis can't work out the length
3281 * For this to work, we need an assumption about the
3282 * maximum length of the password packet. I think 256 is
3283 * pretty conservative. Anyone using a password longer than
3284 * that probably doesn't have much to worry about from
3285 * people who find out how long their password is!
3287 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3288 ssh2_pkt_addstring(username
);
3289 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3290 ssh2_pkt_addstring("password");
3291 ssh2_pkt_addbool(FALSE
);
3292 ssh2_pkt_addstring(password
);
3295 * We'll include a string that's an exact multiple of the
3296 * cipher block size. If the cipher is NULL for some
3297 * reason, we don't do this trick at all because we gain
3303 stringlen
= (256 - deferred_len
);
3304 stringlen
+= cscipher
->blksize
- 1;
3305 stringlen
-= (stringlen
% cscipher
->blksize
);
3308 * Temporarily disable actual compression,
3309 * so we can guarantee to get this string
3310 * exactly the length we want it. The
3311 * compression-disabling routine should
3312 * return an integer indicating how many
3313 * bytes we should adjust our string length
3316 stringlen
-= cscomp
->disable_compression();
3318 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3319 ssh2_pkt_addstring_start();
3320 for (i
= 0; i
< stringlen
; i
++) {
3321 char c
= (char)random_byte();
3322 ssh2_pkt_addstring_data(&c
, 1);
3326 ssh_pkt_defersend();
3327 logevent("Sent password");
3328 type
= AUTH_TYPE_PASSWORD
;
3330 c_write_str("No supported authentication methods left to try!\r\n");
3331 logevent("No supported authentications offered. Disconnecting");
3332 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3333 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3334 ssh2_pkt_addstring("No supported authentication methods available");
3335 ssh2_pkt_addstring("en"); /* language tag */
3337 ssh_state
= SSH_STATE_CLOSED
;
3341 } while (!we_are_in
);
3344 * Now we're authenticated for the connection protocol. The
3345 * connection protocol will automatically have started at this
3346 * point; there's no need to send SERVICE_REQUEST.
3350 * So now create a channel with a session in it.
3352 mainchan
= smalloc(sizeof(struct ssh_channel
));
3353 mainchan
->localid
= 100; /* as good as any */
3354 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3355 ssh2_pkt_addstring("session");
3356 ssh2_pkt_adduint32(mainchan
->localid
);
3357 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3358 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3360 crWaitUntilV(ispkt
);
3361 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3362 bombout(("Server refused to open a session"));
3364 /* FIXME: error data comes back in FAILURE packet */
3366 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3367 bombout(("Server's channel confirmation cited wrong channel"));
3370 mainchan
->remoteid
= ssh2_pkt_getuint32();
3371 mainchan
->type
= CHAN_MAINSESSION
;
3372 mainchan
->closes
= 0;
3373 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3374 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3375 mainchan
->v2
.outbuffer
= NULL
;
3376 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3377 ssh_channels
= newtree234(ssh_channelcmp
);
3378 add234(ssh_channels
, mainchan
);
3379 logevent("Opened channel for session");
3382 * Potentially enable X11 forwarding.
3384 if (cfg
.x11_forward
) {
3385 char proto
[20], data
[64];
3386 logevent("Requesting X11 forwarding");
3387 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3388 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3389 ssh2_pkt_adduint32(mainchan
->remoteid
);
3390 ssh2_pkt_addstring("x11-req");
3391 ssh2_pkt_addbool(1); /* want reply */
3392 ssh2_pkt_addbool(0); /* many connections */
3393 ssh2_pkt_addstring(proto
);
3394 ssh2_pkt_addstring(data
);
3395 ssh2_pkt_adduint32(0); /* screen number */
3399 crWaitUntilV(ispkt
);
3400 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3401 unsigned i
= ssh2_pkt_getuint32();
3402 struct ssh_channel
*c
;
3403 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3405 continue; /* nonexistent channel */
3406 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3408 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3410 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3411 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3412 bombout(("Server got confused by X11 forwarding request"));
3415 logevent("X11 forwarding refused");
3417 logevent("X11 forwarding enabled");
3418 ssh_X11_fwd_enabled
= TRUE
;
3423 * Potentially enable agent forwarding.
3425 if (cfg
.agentfwd
&& agent_exists()) {
3426 char proto
[20], data
[64];
3427 logevent("Requesting OpenSSH-style agent forwarding");
3428 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3429 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3430 ssh2_pkt_adduint32(mainchan
->remoteid
);
3431 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3432 ssh2_pkt_addbool(1); /* want reply */
3436 crWaitUntilV(ispkt
);
3437 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3438 unsigned i
= ssh2_pkt_getuint32();
3439 struct ssh_channel
*c
;
3440 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3442 continue; /* nonexistent channel */
3443 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3445 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3447 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3448 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3449 bombout(("Server got confused by agent forwarding request"));
3452 logevent("Agent forwarding refused");
3454 logevent("Agent forwarding enabled");
3455 ssh_agentfwd_enabled
= TRUE
;
3460 * Now allocate a pty for the session.
3463 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3464 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3465 ssh2_pkt_addstring("pty-req");
3466 ssh2_pkt_addbool(1); /* want reply */
3467 ssh2_pkt_addstring(cfg
.termtype
);
3468 ssh2_pkt_adduint32(cols
);
3469 ssh2_pkt_adduint32(rows
);
3470 ssh2_pkt_adduint32(0); /* pixel width */
3471 ssh2_pkt_adduint32(0); /* pixel height */
3472 ssh2_pkt_addstring_start();
3473 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3475 ssh_state
= SSH_STATE_INTERMED
;
3478 crWaitUntilV(ispkt
);
3479 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3480 unsigned i
= ssh2_pkt_getuint32();
3481 struct ssh_channel
*c
;
3482 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3484 continue; /* nonexistent channel */
3485 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3487 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3489 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3490 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3491 bombout(("Server got confused by pty request"));
3494 c_write_str("Server refused to allocate pty\r\n");
3495 ssh_editing
= ssh_echoing
= 1;
3497 logevent("Allocated pty");
3500 ssh_editing
= ssh_echoing
= 1;
3504 * Start a shell or a remote command.
3506 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3507 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3508 if (cfg
.ssh_subsys
) {
3509 ssh2_pkt_addstring("subsystem");
3510 ssh2_pkt_addbool(1); /* want reply */
3511 ssh2_pkt_addstring(cfg
.remote_cmd
);
3512 } else if (*cfg
.remote_cmd
) {
3513 ssh2_pkt_addstring("exec");
3514 ssh2_pkt_addbool(1); /* want reply */
3515 ssh2_pkt_addstring(cfg
.remote_cmd
);
3517 ssh2_pkt_addstring("shell");
3518 ssh2_pkt_addbool(1); /* want reply */
3522 crWaitUntilV(ispkt
);
3523 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3524 unsigned i
= ssh2_pkt_getuint32();
3525 struct ssh_channel
*c
;
3526 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3528 continue; /* nonexistent channel */
3529 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3531 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3532 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3533 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3534 bombout(("Server got confused by shell/command request"));
3537 bombout(("Server refused to start a shell/command"));
3540 logevent("Started a shell/command");
3543 ssh_state
= SSH_STATE_SESSION
;
3547 ssh_special(TS_EOF
);
3552 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3555 static int try_send
;
3559 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3560 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3563 unsigned i
= ssh2_pkt_getuint32();
3564 struct ssh_channel
*c
;
3565 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3567 continue; /* nonexistent channel */
3568 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3569 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3570 continue; /* extended but not stderr */
3571 ssh2_pkt_getstring(&data
, &length
);
3574 case CHAN_MAINSESSION
:
3575 from_backend(pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
,
3579 x11_send(c
->u
.x11
.s
, data
, length
);
3582 while (length
> 0) {
3583 if (c
->u
.a
.lensofar
< 4) {
3584 int l
= min(4 - c
->u
.a
.lensofar
, length
);
3585 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, data
, l
);
3586 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3588 if (c
->u
.a
.lensofar
== 4) {
3589 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
3590 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3591 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3593 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
3594 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3596 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, data
, l
);
3597 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3599 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3600 void *reply
, *sentreply
;
3602 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
3607 /* Fake SSH_AGENT_FAILURE. */
3608 sentreply
= "\0\0\0\1\5";
3611 ssh2_add_channel_data(c
, sentreply
, replylen
);
3615 sfree(c
->u
.a
.message
);
3616 c
->u
.a
.lensofar
= 0;
3622 * Enlarge the window again at the remote
3623 * side, just in case it ever runs down and
3624 * they fail to send us any more data.
3626 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3627 ssh2_pkt_adduint32(c
->remoteid
);
3628 ssh2_pkt_adduint32(length
);
3631 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
3632 ssh_state
= SSH_STATE_CLOSED
;
3633 logevent("Received disconnect message");
3635 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
3636 continue; /* exit status et al; ignore (FIXME?) */
3637 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
3638 unsigned i
= ssh2_pkt_getuint32();
3639 struct ssh_channel
*c
;
3641 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3643 continue; /* nonexistent channel */
3645 if (c
->type
== CHAN_X11
) {
3647 * Remote EOF on an X11 channel means we should
3648 * wrap up and close the channel ourselves.
3650 x11_close(c
->u
.x11
.s
);
3652 } else if (c
->type
== CHAN_AGENT
) {
3655 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
3656 unsigned i
= ssh2_pkt_getuint32();
3657 struct ssh_channel
*c
;
3660 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3662 continue; /* nonexistent channel */
3663 if (c
->closes
== 0) {
3664 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3665 ssh2_pkt_adduint32(c
->remoteid
);
3668 /* Do pre-close processing on the channel. */
3670 case CHAN_MAINSESSION
:
3671 break; /* nothing to see here, move along */
3677 del234(ssh_channels
, c
);
3678 sfree(c
->v2
.outbuffer
);
3682 * See if that was the last channel left open.
3684 c
= first234(ssh_channels
, &e
);
3686 logevent("All channels closed. Disconnecting");
3687 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3688 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3689 ssh2_pkt_addstring("All open channels closed");
3690 ssh2_pkt_addstring("en"); /* language tag */
3692 ssh_state
= SSH_STATE_CLOSED
;
3695 continue; /* remote sends close; ignore (FIXME) */
3696 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3697 unsigned i
= ssh2_pkt_getuint32();
3698 struct ssh_channel
*c
;
3699 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3701 continue; /* nonexistent channel */
3702 mainchan
->v2
.remwindow
+= ssh2_pkt_getuint32();
3704 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
3708 struct ssh_channel
*c
;
3709 ssh2_pkt_getstring(&type
, &typelen
);
3710 c
= smalloc(sizeof(struct ssh_channel
));
3712 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
3713 if (!ssh_X11_fwd_enabled
)
3714 error
= "X11 forwarding is not enabled";
3715 else if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3716 error
= "Unable to open an X11 connection";
3720 } else if (typelen
== 22 &&
3721 !memcmp(type
, "auth-agent@openssh.com", 3)) {
3722 if (!ssh_agentfwd_enabled
)
3723 error
= "Agent forwarding is not enabled";
3725 c
->type
= CHAN_AGENT
; /* identify channel type */
3726 c
->u
.a
.lensofar
= 0;
3729 error
= "Unsupported channel type requested";
3732 c
->remoteid
= ssh2_pkt_getuint32();
3734 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
3735 ssh2_pkt_adduint32(c
->remoteid
);
3736 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
3737 ssh2_pkt_addstring(error
);
3738 ssh2_pkt_addstring("en"); /* language tag */
3742 struct ssh_channel
*d
;
3746 for (i
=1, d
= first234(ssh_channels
, &e
); d
;
3749 break; /* found a free number */
3754 c
->v2
.remwindow
= ssh2_pkt_getuint32();
3755 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3756 c
->v2
.outbuffer
= NULL
;
3757 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
3758 add234(ssh_channels
, c
);
3759 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
3760 ssh2_pkt_adduint32(c
->remoteid
);
3761 ssh2_pkt_adduint32(c
->localid
);
3762 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3763 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3767 bombout(("Strange packet received: type %d", pktin
.type
));
3772 * We have spare data. Add it to the channel buffer.
3774 ssh2_add_channel_data(mainchan
, in
, inlen
);
3779 struct ssh_channel
*c
;
3781 * Try to send data on all channels if we can.
3783 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
))
3792 * Handle the top-level SSH2 protocol.
3794 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
3796 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
3798 do_ssh2_authconn(in
, inlen
, ispkt
);
3802 * Called to set up the connection.
3804 * Returns an error message, or NULL on success.
3806 static char *ssh_init (char *host
, int port
, char **realhost
) {
3810 if(crypto_startup() == 0)
3811 return "Microsoft high encryption pack not installed!";
3818 p
= connect_to_host(host
, port
, realhost
);
3826 * Called to send data down the Telnet connection.
3828 static void ssh_send (char *buf
, int len
) {
3829 if (s
== NULL
|| ssh_protocol
== NULL
)
3832 ssh_protocol(buf
, len
, 0);
3836 * Called to set the size of the window from SSH's POV.
3838 static void ssh_size(void) {
3839 switch (ssh_state
) {
3840 case SSH_STATE_BEFORE_SIZE
:
3841 case SSH_STATE_PREPACKET
:
3842 case SSH_STATE_CLOSED
:
3843 break; /* do nothing */
3844 case SSH_STATE_INTERMED
:
3845 size_needed
= TRUE
; /* buffer for later */
3847 case SSH_STATE_SESSION
:
3849 if (ssh_version
== 1) {
3850 send_packet(SSH1_CMSG_WINDOW_SIZE
,
3851 PKT_INT
, rows
, PKT_INT
, cols
,
3852 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
3854 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3855 ssh2_pkt_adduint32(mainchan
->remoteid
);
3856 ssh2_pkt_addstring("window-change");
3857 ssh2_pkt_addbool(0);
3858 ssh2_pkt_adduint32(cols
);
3859 ssh2_pkt_adduint32(rows
);
3860 ssh2_pkt_adduint32(0);
3861 ssh2_pkt_adduint32(0);
3870 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3871 * can send an EOF and collect resulting output (e.g. `plink
3874 static void ssh_special (Telnet_Special code
) {
3875 if (code
== TS_EOF
) {
3876 if (ssh_state
!= SSH_STATE_SESSION
) {
3878 * Buffer the EOF in case we are pre-SESSION, so we can
3879 * send it as soon as we reach SESSION.
3885 if (ssh_version
== 1) {
3886 send_packet(SSH1_CMSG_EOF
, PKT_END
);
3888 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
3889 ssh2_pkt_adduint32(mainchan
->remoteid
);
3892 logevent("Sent EOF message");
3893 } else if (code
== TS_PING
) {
3894 if (ssh_state
== SSH_STATE_CLOSED
|| ssh_state
== SSH_STATE_PREPACKET
)
3896 if (ssh_version
== 1) {
3897 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
3899 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3900 ssh2_pkt_addstring_start();
3908 static Socket
ssh_socket(void) { return s
; }
3910 static int ssh_sendok(void) { return ssh_send_ok
; }
3912 static int ssh_ldisc(int option
) {
3913 if (option
== LD_ECHO
) return ssh_echoing
;
3914 if (option
== LD_EDIT
) return ssh_editing
;
3918 Backend ssh_backend
= {