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 SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 /* 0x1 */
72 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 /* 0x2 */
73 #define SSH_AGENTC_RSA_CHALLENGE 3 /* 0x3 */
74 #define SSH_AGENT_RSA_RESPONSE 4 /* 0x4 */
75 #define SSH_AGENT_FAILURE 5 /* 0x5 */
76 #define SSH_AGENT_SUCCESS 6 /* 0x6 */
77 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 /* 0x7 */
78 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 /* 0x8 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
91 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
92 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
93 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
94 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
95 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
96 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
97 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
98 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
100 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
101 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
102 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
103 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
104 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
105 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
106 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
107 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
108 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
109 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
110 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
111 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
112 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
113 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
127 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
128 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
129 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
130 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
132 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
134 #define GET_32BIT(cp) \
135 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
136 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
137 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
138 ((unsigned long)(unsigned char)(cp)[3]))
140 #define PUT_32BIT(cp, value) { \
141 (cp)[0] = (unsigned char)((value) >> 24); \
142 (cp)[1] = (unsigned char)((value) >> 16); \
143 (cp)[2] = (unsigned char)((value) >> 8); \
144 (cp)[3] = (unsigned char)(value); }
146 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
148 /* Coroutine mechanics for the sillier bits of the code */
149 #define crBegin1 static int crLine = 0;
150 #define crBegin2 switch(crLine) { case 0:;
151 #define crBegin crBegin1; crBegin2;
152 #define crFinish(z) } crLine = 0; return (z)
153 #define crFinishV } crLine = 0; return
154 #define crReturn(z) \
156 crLine=__LINE__; return (z); case __LINE__:;\
160 crLine=__LINE__; return; case __LINE__:;\
162 #define crStop(z) do{ crLine = 0; return (z); }while(0)
163 #define crStopV do{ crLine = 0; return; }while(0)
164 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
165 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
167 extern char *x11_init (Socket
*, char *, void *);
168 extern void x11_close (Socket
);
169 extern void x11_send (Socket
, char *, int);
170 extern void x11_invent_auth(char *, int, char *, int);
173 * Ciphers for SSH2. We miss out single-DES because it isn't
174 * supported; also 3DES and Blowfish are both done differently from
175 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
176 * endianness and different-sized keys.)
178 const static struct ssh2_ciphers
*ciphers
[] = {
184 const static struct ssh_kex
*kex_algs
[] = {
185 #ifdef DO_DIFFIE_HELLMAN_GEX
186 &ssh_diffiehellman_gex
,
188 &ssh_diffiehellman
};
190 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
192 static void nullmac_key(unsigned char *key
) { }
193 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
194 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
195 const static struct ssh_mac ssh_mac_none
= {
196 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
198 const static struct ssh_mac
*macs
[] = {
199 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
};
200 const static struct ssh_mac
*buggymacs
[] = {
201 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
};
203 static void ssh_comp_none_init(void) { }
204 static int ssh_comp_none_block(unsigned char *block
, int len
,
205 unsigned char **outblock
, int *outlen
) {
208 const static struct ssh_compress ssh_comp_none
= {
210 ssh_comp_none_init
, ssh_comp_none_block
,
211 ssh_comp_none_init
, ssh_comp_none_block
213 extern const struct ssh_compress ssh_zlib
;
214 const static struct ssh_compress
*compressions
[] = {
215 &ssh_zlib
, &ssh_comp_none
};
217 enum { /* channel types */
224 * 2-3-4 tree storing channels.
227 unsigned remoteid
, localid
;
230 struct ssh2_data_channel
{
231 unsigned char *outbuffer
;
232 unsigned outbuflen
, outbufsize
;
233 unsigned remwindow
, remmaxpkt
;
236 struct ssh_agent_channel
{
237 unsigned char *message
;
238 unsigned char msglen
[4];
239 int lensofar
, totallen
;
241 struct ssh_x11_channel
{
256 static SHA_State exhash
, exhashbase
;
258 static Socket s
= NULL
;
260 static unsigned char session_key
[32];
261 static int ssh1_compressing
;
262 static int ssh_agentfwd_enabled
;
263 static int ssh_X11_fwd_enabled
;
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 void s_wrpkt(void) {
666 int pad
, len
, biglen
, i
;
669 pktout
.body
[-1] = pktout
.type
;
671 if (ssh1_compressing
) {
672 unsigned char *compblk
;
675 debug(("Packet payload pre-compression:\n"));
676 for (i
= -1; i
< pktout
.length
; i
++)
677 debug((" %02x", (unsigned char)pktout
.body
[i
]));
680 zlib_compress_block(pktout
.body
-1, pktout
.length
+1,
682 ssh1_pktout_size(complen
-1);
683 memcpy(pktout
.body
-1, compblk
, complen
);
686 debug(("Packet payload post-compression:\n"));
687 for (i
= -1; i
< pktout
.length
; i
++)
688 debug((" %02x", (unsigned char)pktout
.body
[i
]));
693 len
= pktout
.length
+ 5; /* type and CRC */
697 for (i
=0; i
<pad
; i
++)
698 pktout
.data
[i
+4] = random_byte();
699 crc
= crc32(pktout
.data
+4, biglen
-4);
700 PUT_32BIT(pktout
.data
+biglen
, crc
);
701 PUT_32BIT(pktout
.data
, len
);
704 debug(("Sending packet len=%d\r\n", biglen
+4));
705 for (i
= 0; i
< biglen
+4; i
++)
706 debug((" %02x", (unsigned char)pktout
.data
[i
]));
710 cipher
->encrypt(pktout
.data
+4, biglen
);
712 sk_write(s
, pktout
.data
, biglen
+4);
716 * Construct a packet with the specified contents and
717 * send it to the server.
719 static void send_packet(int pkttype
, ...)
722 unsigned char *p
, *argp
, argchar
;
723 unsigned long argint
;
724 int pktlen
, argtype
, arglen
;
728 va_start(args
, pkttype
);
729 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
732 (void) va_arg(args
, int);
736 (void) va_arg(args
, char);
740 (void) va_arg(args
, unsigned char *);
741 arglen
= va_arg(args
, int);
745 argp
= va_arg(args
, unsigned char *);
746 arglen
= strlen(argp
);
747 pktlen
+= 4 + arglen
;
750 bn
= va_arg(args
, Bignum
);
751 pktlen
+= ssh1_bignum_length(bn
);
759 s_wrpkt_start(pkttype
, pktlen
);
762 va_start(args
, pkttype
);
763 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
766 argint
= va_arg(args
, int);
767 PUT_32BIT(p
, argint
);
771 argchar
= va_arg(args
, unsigned char);
776 argp
= va_arg(args
, unsigned char *);
777 arglen
= va_arg(args
, int);
778 memcpy(p
, argp
, arglen
);
782 argp
= va_arg(args
, unsigned char *);
783 arglen
= strlen(argp
);
784 PUT_32BIT(p
, arglen
);
785 memcpy(p
+ 4, argp
, arglen
);
789 bn
= va_arg(args
, Bignum
);
790 p
+= ssh1_write_bignum(p
, bn
);
799 static int ssh_versioncmp(char *a
, char *b
) {
801 unsigned long av
, bv
;
803 av
= strtoul(a
, &ae
, 10);
804 bv
= strtoul(b
, &be
, 10);
805 if (av
!= bv
) return (av
< bv ?
-1 : +1);
806 if (*ae
== '.') ae
++;
807 if (*be
== '.') be
++;
808 av
= strtoul(ae
, &ae
, 10);
809 bv
= strtoul(be
, &be
, 10);
810 if (av
!= bv
) return (av
< bv ?
-1 : +1);
816 * Utility routines for putting an SSH-protocol `string' and
817 * `uint32' into a SHA state.
820 static void sha_string(SHA_State
*s
, void *str
, int len
) {
821 unsigned char lenblk
[4];
822 PUT_32BIT(lenblk
, len
);
823 SHA_Bytes(s
, lenblk
, 4);
824 SHA_Bytes(s
, str
, len
);
827 static void sha_uint32(SHA_State
*s
, unsigned i
) {
828 unsigned char intblk
[4];
829 PUT_32BIT(intblk
, i
);
830 SHA_Bytes(s
, intblk
, 4);
834 * SSH2 packet construction functions.
836 static void ssh2_pkt_ensure(int length
) {
837 if (pktout
.maxlen
< length
) {
838 pktout
.maxlen
= length
+ 256;
839 pktout
.data
= (pktout
.data
== NULL ?
smalloc(pktout
.maxlen
+APIEXTRA
) :
840 srealloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
842 fatalbox("Out of memory");
845 static void ssh2_pkt_adddata(void *data
, int len
) {
846 pktout
.length
+= len
;
847 ssh2_pkt_ensure(pktout
.length
);
848 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
850 static void ssh2_pkt_addbyte(unsigned char byte
) {
851 ssh2_pkt_adddata(&byte
, 1);
853 static void ssh2_pkt_init(int pkt_type
) {
855 ssh2_pkt_addbyte((unsigned char)pkt_type
);
857 static void ssh2_pkt_addbool(unsigned char value
) {
858 ssh2_pkt_adddata(&value
, 1);
860 static void ssh2_pkt_adduint32(unsigned long value
) {
863 ssh2_pkt_adddata(x
, 4);
865 static void ssh2_pkt_addstring_start(void) {
866 ssh2_pkt_adduint32(0);
867 pktout
.savedpos
= pktout
.length
;
869 static void ssh2_pkt_addstring_str(char *data
) {
870 ssh2_pkt_adddata(data
, strlen(data
));
871 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
872 pktout
.length
- pktout
.savedpos
);
874 static void ssh2_pkt_addstring_data(char *data
, int len
) {
875 ssh2_pkt_adddata(data
, len
);
876 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
877 pktout
.length
- pktout
.savedpos
);
879 static void ssh2_pkt_addstring(char *data
) {
880 ssh2_pkt_addstring_start();
881 ssh2_pkt_addstring_str(data
);
883 static char *ssh2_mpint_fmt(Bignum b
, int *len
) {
885 int i
, n
= (ssh1_bignum_bitcount(b
)+7)/8;
888 fatalbox("out of memory");
890 for (i
= 1; i
<= n
; i
++)
891 p
[i
] = bignum_byte(b
, n
-i
);
893 while (i
<= n
&& p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
895 memmove(p
, p
+i
, n
+1-i
);
899 static void ssh2_pkt_addmp(Bignum b
) {
902 p
= ssh2_mpint_fmt(b
, &len
);
903 ssh2_pkt_addstring_start();
904 ssh2_pkt_addstring_data(p
, len
);
909 * Construct an SSH2 final-form packet: compress it, encrypt it,
910 * put the MAC on it. Final packet, ready to be sent, is stored in
911 * pktout.data. Total length is returned.
913 static int ssh2_pkt_construct(void) {
914 int cipherblk
, maclen
, padding
, i
;
915 static unsigned long outgoing_sequence
= 0;
918 * Compress packet payload.
921 debug(("Pre-compression payload:\r\n"));
922 for (i
= 5; i
< pktout
.length
; i
++)
923 debug((" %02x", (unsigned char)pktout
.data
[i
]));
927 unsigned char *newpayload
;
929 if (cscomp
&& cscomp
->compress(pktout
.data
+5, pktout
.length
-5,
930 &newpayload
, &newlen
)) {
932 ssh2_pkt_adddata(newpayload
, newlen
);
938 * Add padding. At least four bytes, and must also bring total
939 * length (minus MAC) up to a multiple of the block size.
941 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
942 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
944 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
945 maclen
= csmac ? csmac
->len
: 0;
946 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
947 pktout
.data
[4] = padding
;
948 for (i
= 0; i
< padding
; i
++)
949 pktout
.data
[pktout
.length
+ i
] = random_byte();
950 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
952 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
954 outgoing_sequence
++; /* whether or not we MACed */
957 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
958 for (i
= 0; i
< pktout
.length
+padding
; i
++)
959 debug((" %02x", (unsigned char)pktout
.data
[i
]));
964 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
966 /* Ready-to-send packet starts at pktout.data. We return length. */
967 return pktout
.length
+ padding
+ maclen
;
971 * Construct and send an SSH2 packet immediately.
973 static void ssh2_pkt_send(void) {
974 int len
= ssh2_pkt_construct();
975 sk_write(s
, pktout
.data
, len
);
979 * Construct an SSH2 packet and add it to a deferred data block.
980 * Useful for sending multiple packets in a single sk_write() call,
981 * to prevent a traffic-analysing listener from being able to work
982 * out the length of any particular packet (such as the password
985 * Note that because SSH2 sequence-numbers its packets, this can
986 * NOT be used as an m4-style `defer' allowing packets to be
987 * constructed in one order and sent in another.
989 static void ssh2_pkt_defer(void) {
990 int len
= ssh2_pkt_construct();
991 if (deferred_len
+ len
> deferred_size
) {
992 deferred_size
= deferred_len
+ len
+ 128;
993 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
995 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
1000 * Send the whole deferred data block constructed by
1003 static void ssh2_pkt_defersend(void) {
1004 sk_write(s
, deferred_send_data
, deferred_len
);
1005 deferred_len
= deferred_size
= 0;
1006 sfree(deferred_send_data
);
1007 deferred_send_data
= NULL
;
1011 void bndebug(char *string
, Bignum b
) {
1014 p
= ssh2_mpint_fmt(b
, &len
);
1015 debug(("%s", string
));
1016 for (i
= 0; i
< len
; i
++)
1017 debug((" %02x", p
[i
]));
1023 static void sha_mpint(SHA_State
*s
, Bignum b
) {
1026 p
= ssh2_mpint_fmt(b
, &len
);
1027 sha_string(s
, p
, len
);
1032 * SSH2 packet decode functions.
1034 static unsigned long ssh2_pkt_getuint32(void) {
1035 unsigned long value
;
1036 if (pktin
.length
- pktin
.savedpos
< 4)
1037 return 0; /* arrgh, no way to decline (FIXME?) */
1038 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1039 pktin
.savedpos
+= 4;
1042 static int ssh2_pkt_getbool(void) {
1043 unsigned long value
;
1044 if (pktin
.length
- pktin
.savedpos
< 1)
1045 return 0; /* arrgh, no way to decline (FIXME?) */
1046 value
= pktin
.data
[pktin
.savedpos
] != 0;
1050 static void ssh2_pkt_getstring(char **p
, int *length
) {
1052 if (pktin
.length
- pktin
.savedpos
< 4)
1054 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1055 pktin
.savedpos
+= 4;
1056 if (pktin
.length
- pktin
.savedpos
< *length
)
1058 *p
= pktin
.data
+pktin
.savedpos
;
1059 pktin
.savedpos
+= *length
;
1061 static Bignum
ssh2_pkt_getmp(void) {
1066 ssh2_pkt_getstring(&p
, &length
);
1070 bombout(("internal error: Can't handle negative mpints"));
1073 b
= bignum_from_bytes(p
, length
);
1077 static int do_ssh_init(unsigned char c
) {
1079 static char version
[10];
1080 static char vstring
[80];
1081 static char vlog
[sizeof(vstring
)+20];
1086 /* Search for the string "SSH-" in the input. */
1089 static const int transS
[] = { 1, 2, 2, 1 };
1090 static const int transH
[] = { 0, 0, 3, 0 };
1091 static const int transminus
[] = { 0, 0, 0, -1 };
1092 if (c
== 'S') i
= transS
[i
];
1093 else if (c
== 'H') i
= transH
[i
];
1094 else if (c
== '-') i
= transminus
[i
];
1098 crReturn(1); /* get another character */
1101 strcpy(vstring
, "SSH-");
1105 crReturn(1); /* get another char */
1106 if (vsp
< vstring
+sizeof(vstring
)-1)
1112 } else if (i
< sizeof(version
)-1)
1119 ssh_agentfwd_enabled
= FALSE
;
1120 rdpkt2_state
.incoming_sequence
= 0;
1123 sprintf(vlog
, "Server version: %s", vstring
);
1124 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1128 * Server version "1.99" means we can choose whether we use v1
1129 * or v2 protocol. Choice is based on cfg.sshprot.
1131 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1133 * This is a v2 server. Begin v2 protocol.
1135 char *verstring
= "SSH-2.0-PuTTY";
1136 SHA_Init(&exhashbase
);
1138 * Hash our version string and their version string.
1140 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1141 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1142 sprintf(vstring
, "%s\n", verstring
);
1143 sprintf(vlog
, "We claim version: %s", verstring
);
1145 logevent("Using SSH protocol version 2");
1146 sk_write(s
, vstring
, strlen(vstring
));
1147 ssh_protocol
= ssh2_protocol
;
1149 s_rdpkt
= ssh2_rdpkt
;
1152 * This is a v1 server. Begin v1 protocol.
1154 sprintf(vstring
, "SSH-%s-PuTTY\n",
1155 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1156 sprintf(vlog
, "We claim version: %s", vstring
);
1157 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1159 logevent("Using SSH protocol version 1");
1160 sk_write(s
, vstring
, strlen(vstring
));
1161 ssh_protocol
= ssh1_protocol
;
1163 s_rdpkt
= ssh1_rdpkt
;
1165 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1170 static void ssh_gotdata(unsigned char *data
, int datalen
)
1175 * To begin with, feed the characters one by one to the
1176 * protocol initialisation / selection function do_ssh_init().
1177 * When that returns 0, we're done with the initial greeting
1178 * exchange and can move on to packet discipline.
1183 crReturnV
; /* more data please */
1184 ret
= do_ssh_init(*data
);
1191 * We emerge from that loop when the initial negotiation is
1192 * over and we have selected an s_rdpkt function. Now pass
1193 * everything to s_rdpkt, and then pass the resulting packets
1194 * to the proper protocol handler.
1199 while (datalen
> 0) {
1200 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
1201 ssh_protocol(NULL
, 0, 1);
1202 if (ssh_state
== SSH_STATE_CLOSED
) {
1212 static int ssh_receive(Socket skt
, int urgent
, char *data
, int len
) {
1214 /* A socket error has occurred. */
1215 ssh_state
= SSH_STATE_CLOSED
;
1218 connection_fatal(data
);
1221 /* Connection has closed. */
1222 ssh_state
= SSH_STATE_CLOSED
;
1227 ssh_gotdata (data
, len
);
1228 if (ssh_state
== SSH_STATE_CLOSED
) {
1239 * Connect to specified host and port.
1240 * Returns an error message, or NULL on success.
1241 * Also places the canonical host name into `realhost'.
1243 static char *connect_to_host(char *host
, int port
, char **realhost
)
1252 savedhost
= smalloc(1+strlen(host
));
1254 fatalbox("Out of memory");
1255 strcpy(savedhost
, host
);
1258 port
= 22; /* default ssh port */
1271 addr
= sk_namelookup(host
, realhost
);
1272 if ( (err
= sk_addr_error(addr
)) )
1282 s
= sk_new(addr
, port
, 0, 1, ssh_receive
);
1283 if ( (err
= sk_socket_error(s
)) )
1287 sk_write(s
, "connect ", 8);
1288 sk_write(s
, FWhost
, strlen(FWhost
));
1291 sprintf(buf
, " %d\n", FWport
);
1292 sk_write(s
, buf
, strlen(buf
));
1300 * Handle the key exchange and user authentication phases.
1302 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1305 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1306 unsigned char cookie
[8];
1307 struct RSAKey servkey
, hostkey
;
1308 struct MD5Context md5c
;
1309 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1310 static int tried_publickey
;
1311 static unsigned char session_id
[16];
1313 static char username
[100];
1317 if (!ispkt
) crWaitUntil(ispkt
);
1319 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1320 bombout(("Public key packet not received"));
1324 logevent("Received public keys");
1326 memcpy(cookie
, pktin
.body
, 8);
1328 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1329 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1332 * Log the host key fingerprint.
1336 logevent("Host key fingerprint is:");
1337 strcpy(logmsg
, " ");
1338 hostkey
.comment
= NULL
;
1339 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1344 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1345 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1348 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1349 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1350 MD5Update(&md5c
, pktin
.body
, 8);
1351 MD5Final(session_id
, &md5c
);
1353 for (i
=0; i
<32; i
++)
1354 session_key
[i
] = random_byte();
1356 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1358 rsabuf
= smalloc(len
);
1360 fatalbox("Out of memory");
1363 * Verify the host key.
1367 * First format the key into a string.
1369 int len
= rsastr_len(&hostkey
);
1370 char fingerprint
[100];
1371 char *keystr
= smalloc(len
);
1373 fatalbox("Out of memory");
1374 rsastr_fmt(keystr
, &hostkey
);
1375 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1376 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1380 for (i
=0; i
<32; i
++) {
1381 rsabuf
[i
] = session_key
[i
];
1383 rsabuf
[i
] ^= session_id
[i
];
1386 if (hostkey
.bytes
> servkey
.bytes
) {
1387 rsaencrypt(rsabuf
, 32, &servkey
);
1388 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1390 rsaencrypt(rsabuf
, 32, &hostkey
);
1391 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1394 logevent("Encrypted session key");
1396 switch (cfg
.cipher
) {
1397 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
; break;
1398 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
; break;
1399 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
; break;
1401 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1402 cipher_type
= SSH_CIPHER_3DES
;
1405 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1406 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1407 cipher_type
= SSH_CIPHER_3DES
;
1409 switch (cipher_type
) {
1410 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1411 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1412 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1415 send_packet(SSH1_CMSG_SESSION_KEY
,
1416 PKT_CHAR
, cipher_type
,
1417 PKT_DATA
, cookie
, 8,
1418 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1419 PKT_DATA
, rsabuf
, len
,
1423 logevent("Trying to enable encryption...");
1427 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1428 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1430 cipher
->sesskey(session_key
);
1434 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1435 bombout(("Encryption not successfully enabled"));
1439 logevent("Successfully started encryption");
1445 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1446 c_write_str("login as: ");
1449 crWaitUntil(!ispkt
);
1450 while (inlen
--) switch (c
= *in
++) {
1457 c_write_str("\b \b");
1463 c_write_str("\b \b");
1472 if (((c
>= ' ' && c
<= '~') ||
1473 ((unsigned char)c
>= 160)) && pos
< 40) {
1474 username
[pos
++] = c
;
1480 c_write_str("\r\n");
1481 username
[strcspn(username
, "\n\r")] = '\0';
1483 strncpy(username
, cfg
.username
, 99);
1484 username
[99] = '\0';
1487 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1489 char userlog
[22+sizeof(username
)];
1490 sprintf(userlog
, "Sent username \"%s\"", username
);
1492 if (flags
& FLAG_INTERACTIVE
&&
1493 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1494 strcat(userlog
, "\r\n");
1495 c_write_str(userlog
);
1502 tried_publickey
= 0;
1504 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1505 static char password
[100];
1506 static char prompt
[200];
1509 static int pwpkt_type
;
1511 * Show password prompt, having first obtained it via a TIS
1512 * or CryptoCard exchange if we're doing TIS or CryptoCard
1515 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1516 if (agent_exists()) {
1518 * Attempt RSA authentication using Pageant.
1520 static unsigned char request
[5], *response
, *p
;
1521 static int responselen
;
1522 static int i
, nkeys
;
1523 static int authed
= FALSE
;
1526 logevent("Pageant is running. Requesting keys.");
1528 /* Request the keys held by the agent. */
1529 PUT_32BIT(request
, 1);
1530 request
[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES
;
1531 agent_query(request
, 5, &r
, &responselen
);
1532 response
= (unsigned char *)r
;
1535 nkeys
= GET_32BIT(p
); p
+= 4;
1536 { char buf
[64]; sprintf(buf
, "Pageant has %d keys", nkeys
);
1538 for (i
= 0; i
< nkeys
; i
++) {
1539 static struct RSAKey key
;
1540 static Bignum challenge
;
1541 static char *commentp
;
1542 static int commentlen
;
1544 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1547 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1548 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1549 commentlen
= GET_32BIT(p
); p
+= 4;
1550 commentp
= p
; p
+= commentlen
;
1551 send_packet(SSH1_CMSG_AUTH_RSA
,
1552 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1554 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1555 logevent("Key refused");
1558 logevent("Received RSA challenge");
1559 ssh1_read_bignum(pktin
.body
, &challenge
);
1561 char *agentreq
, *q
, *ret
;
1563 len
= 1 + 4; /* message type, bit count */
1564 len
+= ssh1_bignum_length(key
.exponent
);
1565 len
+= ssh1_bignum_length(key
.modulus
);
1566 len
+= ssh1_bignum_length(challenge
);
1567 len
+= 16; /* session id */
1568 len
+= 4; /* response format */
1569 agentreq
= smalloc(4 + len
);
1570 PUT_32BIT(agentreq
, len
);
1572 *q
++ = SSH_AGENTC_RSA_CHALLENGE
;
1573 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1575 q
+= ssh1_write_bignum(q
, key
.exponent
);
1576 q
+= ssh1_write_bignum(q
, key
.modulus
);
1577 q
+= ssh1_write_bignum(q
, challenge
);
1578 memcpy(q
, session_id
, 16); q
+= 16;
1579 PUT_32BIT(q
, 1); /* response format */
1580 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1583 if (ret
[4] == SSH_AGENT_RSA_RESPONSE
) {
1584 logevent("Sending Pageant's response");
1585 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1586 PKT_DATA
, ret
+5, 16, PKT_END
);
1589 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1590 logevent("Pageant's response accepted");
1591 if (flags
& FLAG_VERBOSE
) {
1592 c_write_str("Authenticated using RSA key \"");
1593 c_write(commentp
, commentlen
);
1594 c_write_str("\" from agent\r\n");
1598 logevent("Pageant's response not accepted");
1600 logevent("Pageant failed to answer challenge");
1604 logevent("No reply received from Pageant");
1607 freebn(key
.exponent
);
1608 freebn(key
.modulus
);
1617 if (*cfg
.keyfile
&& !tried_publickey
)
1618 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1620 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1622 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1623 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1624 logevent("Requested TIS authentication");
1625 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1627 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1628 logevent("TIS authentication declined");
1629 if (flags
& FLAG_INTERACTIVE
)
1630 c_write_str("TIS authentication refused.\r\n");
1632 int challengelen
= ((pktin
.body
[0] << 24) |
1633 (pktin
.body
[1] << 16) |
1634 (pktin
.body
[2] << 8) |
1636 logevent("Received TIS challenge");
1637 if (challengelen
> sizeof(prompt
)-1)
1638 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1639 memcpy(prompt
, pktin
.body
+4, challengelen
);
1640 prompt
[challengelen
] = '\0';
1643 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1645 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1646 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1647 logevent("Requested CryptoCard authentication");
1648 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1650 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1651 logevent("CryptoCard authentication declined");
1652 c_write_str("CryptoCard authentication refused.\r\n");
1654 int challengelen
= ((pktin
.body
[0] << 24) |
1655 (pktin
.body
[1] << 16) |
1656 (pktin
.body
[2] << 8) |
1658 logevent("Received CryptoCard challenge");
1659 if (challengelen
> sizeof(prompt
)-1)
1660 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1661 memcpy(prompt
, pktin
.body
+4, challengelen
);
1662 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1663 sizeof(prompt
)-challengelen
);
1664 prompt
[sizeof(prompt
)-1] = '\0';
1667 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1668 sprintf(prompt
, "%.90s@%.90s's password: ",
1669 username
, savedhost
);
1671 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1672 char *comment
= NULL
;
1673 if (flags
& FLAG_VERBOSE
)
1674 c_write_str("Trying public key authentication.\r\n");
1675 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1676 if (flags
& FLAG_VERBOSE
)
1677 c_write_str("No passphrase required.\r\n");
1680 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1684 if (ssh_get_password
) {
1685 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1687 * get_password failed to get a password (for
1688 * example because one was supplied on the command
1689 * line which has already failed to work).
1692 logevent("No more passwords to try");
1693 ssh_state
= SSH_STATE_CLOSED
;
1697 c_write_str(prompt
);
1701 crWaitUntil(!ispkt
);
1702 while (inlen
--) switch (c
= *in
++) {
1719 if (((c
>= ' ' && c
<= '~') ||
1720 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1721 password
[pos
++] = c
;
1725 c_write_str("\r\n");
1729 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1731 * Try public key authentication with the specified
1734 static struct RSAKey pubkey
;
1735 static Bignum challenge
, response
;
1737 static unsigned char buffer
[32];
1739 tried_publickey
= 1;
1740 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1742 c_write_str("Couldn't load public key from ");
1743 c_write_str(cfg
.keyfile
);
1744 c_write_str(".\r\n");
1745 continue; /* go and try password */
1748 c_write_str("Wrong passphrase.\r\n");
1749 tried_publickey
= 0;
1750 continue; /* try again */
1754 * Send a public key attempt.
1756 send_packet(SSH1_CMSG_AUTH_RSA
,
1757 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1760 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1761 c_write_str("Server refused our public key.\r\n");
1762 continue; /* go and try password */
1764 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1765 bombout(("Bizarre response to offer of public key"));
1768 ssh1_read_bignum(pktin
.body
, &challenge
);
1769 response
= rsadecrypt(challenge
, &pubkey
);
1770 freebn(pubkey
.private_exponent
); /* burn the evidence */
1772 for (i
= 0; i
< 32; i
++) {
1773 buffer
[i
] = bignum_byte(response
, 31-i
);
1777 MD5Update(&md5c
, buffer
, 32);
1778 MD5Update(&md5c
, session_id
, 16);
1779 MD5Final(buffer
, &md5c
);
1781 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1782 PKT_DATA
, buffer
, 16, PKT_END
);
1785 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1786 if (flags
& FLAG_VERBOSE
)
1787 c_write_str("Failed to authenticate with our public key.\r\n");
1788 continue; /* go and try password */
1789 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1790 bombout(("Bizarre response to RSA authentication response"));
1794 break; /* we're through! */
1796 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1798 logevent("Sent password");
1799 memset(password
, 0, strlen(password
));
1801 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1802 if (flags
& FLAG_VERBOSE
)
1803 c_write_str("Access denied\r\n");
1804 logevent("Authentication refused");
1805 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1806 logevent("Received disconnect request");
1807 ssh_state
= SSH_STATE_CLOSED
;
1809 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1810 bombout(("Strange packet received, type %d", pktin
.type
));
1815 logevent("Authentication successful");
1820 void sshfwd_close(struct ssh_channel
*c
) {
1822 if (ssh_version
== 1) {
1823 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
, PKT_END
);
1825 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
1826 ssh2_pkt_adduint32(c
->remoteid
);
1830 if (c
->type
== CHAN_X11
) {
1832 logevent("X11 connection terminated");
1837 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
) {
1838 if (ssh_version
== 1) {
1839 send_packet(SSH1_MSG_CHANNEL_DATA
,
1840 PKT_INT
, c
->remoteid
,
1845 ssh2_add_channel_data(c
, buf
, len
);
1850 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1855 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1858 if (ssh_state
== SSH_STATE_CLOSED
)
1861 if (cfg
.agentfwd
&& agent_exists()) {
1862 logevent("Requesting agent forwarding");
1863 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
1864 do { crReturnV
; } while (!ispkt
);
1865 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1866 bombout(("Protocol confusion"));
1868 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1869 logevent("Agent forwarding refused");
1871 logevent("Agent forwarding enabled");
1872 ssh_agentfwd_enabled
= TRUE
;
1876 if (cfg
.x11_forward
) {
1877 char proto
[20], data
[64];
1878 logevent("Requesting X11 forwarding");
1879 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
1880 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
1881 PKT_STR
, proto
, PKT_STR
, data
,
1884 do { crReturnV
; } while (!ispkt
);
1885 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1886 bombout(("Protocol confusion"));
1888 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1889 logevent("X11 forwarding refused");
1891 logevent("X11 forwarding enabled");
1892 ssh_X11_fwd_enabled
= TRUE
;
1897 send_packet(SSH1_CMSG_REQUEST_PTY
,
1898 PKT_STR
, cfg
.termtype
,
1899 PKT_INT
, rows
, PKT_INT
, cols
,
1900 PKT_INT
, 0, PKT_INT
, 0,
1903 ssh_state
= SSH_STATE_INTERMED
;
1904 do { crReturnV
; } while (!ispkt
);
1905 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1906 bombout(("Protocol confusion"));
1908 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1909 c_write_str("Server refused to allocate pty\r\n");
1910 ssh_editing
= ssh_echoing
= 1;
1912 logevent("Allocated pty");
1914 ssh_editing
= ssh_echoing
= 1;
1917 if (cfg
.compression
) {
1918 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
1919 do { crReturnV
; } while (!ispkt
);
1920 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1921 bombout(("Protocol confusion"));
1923 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1924 c_write_str("Server refused to compress\r\n");
1926 logevent("Started compression");
1927 ssh1_compressing
= TRUE
;
1928 zlib_compress_init();
1929 zlib_decompress_init();
1932 if (*cfg
.remote_cmd
)
1933 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1935 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1936 logevent("Started session");
1938 ssh_state
= SSH_STATE_SESSION
;
1942 ssh_special(TS_EOF
);
1944 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
1946 ssh_channels
= newtree234(ssh_channelcmp
);
1950 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1951 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1952 long len
= GET_32BIT(pktin
.body
);
1953 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
1955 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1956 ssh_state
= SSH_STATE_CLOSED
;
1957 logevent("Received disconnect request");
1959 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
1960 /* Remote side is trying to open a channel to talk to our
1961 * X-Server. Give them back a local channel number. */
1963 struct ssh_channel
*c
, *d
;
1966 logevent("Received X11 connect request");
1967 /* Refuse if X11 forwarding is disabled. */
1968 if (!ssh_X11_fwd_enabled
) {
1969 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
1970 PKT_INT
, GET_32BIT(pktin
.body
),
1972 logevent("Rejected X11 connect request");
1974 c
= smalloc(sizeof(struct ssh_channel
));
1976 if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
1977 logevent("opening X11 forward connection failed");
1979 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
1980 PKT_INT
, GET_32BIT(pktin
.body
),
1983 logevent("opening X11 forward connection succeeded");
1984 for (i
=1, d
= first234(ssh_channels
, &e
); d
; d
= next234(&e
)) {
1986 break; /* found a free number */
1989 c
->remoteid
= GET_32BIT(pktin
.body
);
1992 c
->type
= CHAN_X11
; /* identify channel type */
1993 add234(ssh_channels
, c
);
1994 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
1995 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
1997 logevent("Opened X11 forward channel");
2000 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2001 /* Remote side is trying to open a channel to talk to our
2002 * agent. Give them back a local channel number. */
2004 struct ssh_channel
*c
;
2007 /* Refuse if agent forwarding is disabled. */
2008 if (!ssh_agentfwd_enabled
) {
2009 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2010 PKT_INT
, GET_32BIT(pktin
.body
),
2014 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
2016 break; /* found a free number */
2019 c
= smalloc(sizeof(struct ssh_channel
));
2020 c
->remoteid
= GET_32BIT(pktin
.body
);
2023 c
->type
= CHAN_AGENT
; /* identify channel type */
2024 c
->u
.a
.lensofar
= 0;
2025 add234(ssh_channels
, c
);
2026 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2027 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2030 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2031 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2032 /* Remote side closes a channel. */
2033 unsigned i
= GET_32BIT(pktin
.body
);
2034 struct ssh_channel
*c
;
2035 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2038 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2039 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
2040 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2041 logevent("X11 connection closed");
2042 assert(c
->u
.x11
.s
!= NULL
);
2043 x11_close(c
->u
.x11
.s
);
2046 c
->closes
|= closetype
;
2047 if (c
->closes
== 3) {
2048 del234(ssh_channels
, c
);
2052 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2053 /* Data sent down one of our channels. */
2054 int i
= GET_32BIT(pktin
.body
);
2055 int len
= GET_32BIT(pktin
.body
+4);
2056 unsigned char *p
= pktin
.body
+8;
2057 struct ssh_channel
*c
;
2058 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2062 x11_send(c
->u
.x11
.s
, p
, len
);
2065 /* Data for an agent message. Buffer it. */
2067 if (c
->u
.a
.lensofar
< 4) {
2068 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2069 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
2070 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2072 if (c
->u
.a
.lensofar
== 4) {
2073 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
2074 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2075 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2077 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2078 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
2079 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
2080 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2082 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2083 void *reply
, *sentreply
;
2085 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
2090 /* Fake SSH_AGENT_FAILURE. */
2091 sentreply
= "\0\0\0\1\5";
2094 send_packet(SSH1_MSG_CHANNEL_DATA
,
2095 PKT_INT
, c
->remoteid
,
2097 PKT_DATA
, sentreply
, replylen
,
2101 sfree(c
->u
.a
.message
);
2102 c
->u
.a
.lensofar
= 0;
2108 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2109 /* may be from EXEC_SHELL on some servers */
2110 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2111 /* may be from EXEC_SHELL on some servers
2112 * if no pty is available or in other odd cases. Ignore */
2113 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2114 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2116 bombout(("Strange packet received: type %d", pktin
.type
));
2121 int len
= min(inlen
, 512);
2122 send_packet(SSH1_CMSG_STDIN_DATA
,
2123 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2134 * Utility routine for decoding comma-separated strings in KEXINIT.
2136 static int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
2137 int needlen
= strlen(needle
);
2140 * Is it at the start of the string?
2142 if (haylen
>= needlen
&& /* haystack is long enough */
2143 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2144 (haylen
== needlen
|| haystack
[needlen
] == ',')
2145 /* either , or EOS follows */
2149 * If not, search for the next comma and resume after that.
2150 * If no comma found, terminate.
2152 while (haylen
> 0 && *haystack
!= ',')
2153 haylen
--, haystack
++;
2156 haylen
--, haystack
++; /* skip over comma itself */
2161 * SSH2 key creation method.
2163 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
, char *keyspace
) {
2165 /* First 20 bytes. */
2168 SHA_Bytes(&s
, H
, 20);
2169 SHA_Bytes(&s
, &chr
, 1);
2170 SHA_Bytes(&s
, sessid
, 20);
2171 SHA_Final(&s
, keyspace
);
2172 /* Next 20 bytes. */
2175 SHA_Bytes(&s
, H
, 20);
2176 SHA_Bytes(&s
, keyspace
, 20);
2177 SHA_Final(&s
, keyspace
+20);
2181 * Handle the SSH2 transport layer.
2183 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2185 static int i
, j
, len
, nbits
;
2187 static Bignum p
, g
, e
, f
, K
;
2188 static int kex_init_value
, kex_reply_value
;
2189 static const struct ssh_mac
**maclist
;
2191 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2192 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2193 static const struct ssh_mac
*csmac_tobe
= NULL
;
2194 static const struct ssh_mac
*scmac_tobe
= NULL
;
2195 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2196 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2197 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2198 static int hostkeylen
, siglen
;
2199 static void *hkey
; /* actual host key */
2200 static unsigned char exchange_hash
[20];
2201 static unsigned char keyspace
[40];
2202 static const struct ssh2_ciphers
*preferred_cipher
;
2203 static const struct ssh_compress
*preferred_comp
;
2204 static int first_kex
;
2211 * Set up the preferred cipher and compression.
2213 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2214 preferred_cipher
= &ssh2_blowfish
;
2215 } else if (cfg
.cipher
== CIPHER_DES
) {
2216 logevent("Single DES not supported in SSH2; using 3DES");
2217 preferred_cipher
= &ssh2_3des
;
2218 } else if (cfg
.cipher
== CIPHER_3DES
) {
2219 preferred_cipher
= &ssh2_3des
;
2220 } else if (cfg
.cipher
== CIPHER_AES
) {
2221 preferred_cipher
= &ssh2_aes
;
2223 /* Shouldn't happen, but we do want to initialise to _something_. */
2224 preferred_cipher
= &ssh2_3des
;
2226 if (cfg
.compression
)
2227 preferred_comp
= &ssh_zlib
;
2229 preferred_comp
= &ssh_comp_none
;
2232 * Be prepared to work around the buggy MAC problem.
2235 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2237 maclist
= macs
, nmacs
= lenof(macs
);
2241 * Construct and send our key exchange packet.
2243 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2244 for (i
= 0; i
< 16; i
++)
2245 ssh2_pkt_addbyte((unsigned char)random_byte());
2246 /* List key exchange algorithms. */
2247 ssh2_pkt_addstring_start();
2248 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2249 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2250 if (i
< lenof(kex_algs
)-1)
2251 ssh2_pkt_addstring_str(",");
2253 /* List server host key algorithms. */
2254 ssh2_pkt_addstring_start();
2255 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2256 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2257 if (i
< lenof(hostkey_algs
)-1)
2258 ssh2_pkt_addstring_str(",");
2260 /* List client->server encryption algorithms. */
2261 ssh2_pkt_addstring_start();
2262 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2263 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2264 for (j
= 0; j
< c
->nciphers
; j
++) {
2265 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2266 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2267 ssh2_pkt_addstring_str(",");
2270 /* List server->client encryption algorithms. */
2271 ssh2_pkt_addstring_start();
2272 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2273 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2274 for (j
= 0; j
< c
->nciphers
; j
++) {
2275 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2276 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2277 ssh2_pkt_addstring_str(",");
2280 /* List client->server MAC algorithms. */
2281 ssh2_pkt_addstring_start();
2282 for (i
= 0; i
< nmacs
; i
++) {
2283 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2285 ssh2_pkt_addstring_str(",");
2287 /* List server->client MAC algorithms. */
2288 ssh2_pkt_addstring_start();
2289 for (i
= 0; i
< nmacs
; i
++) {
2290 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2292 ssh2_pkt_addstring_str(",");
2294 /* List client->server compression algorithms. */
2295 ssh2_pkt_addstring_start();
2296 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2297 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2298 ssh2_pkt_addstring_str(c
->name
);
2299 if (i
< lenof(compressions
))
2300 ssh2_pkt_addstring_str(",");
2302 /* List server->client compression algorithms. */
2303 ssh2_pkt_addstring_start();
2304 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2305 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2306 ssh2_pkt_addstring_str(c
->name
);
2307 if (i
< lenof(compressions
))
2308 ssh2_pkt_addstring_str(",");
2310 /* List client->server languages. Empty list. */
2311 ssh2_pkt_addstring_start();
2312 /* List server->client languages. Empty list. */
2313 ssh2_pkt_addstring_start();
2314 /* First KEX packet does _not_ follow, because we're not that brave. */
2315 ssh2_pkt_addbool(FALSE
);
2317 ssh2_pkt_adduint32(0);
2319 exhash
= exhashbase
;
2320 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
2324 if (!ispkt
) crWaitUntil(ispkt
);
2325 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
2328 * Now examine the other side's KEXINIT to see what we're up
2331 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2332 bombout(("expected key exchange packet from server"));
2335 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
2336 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
2337 pktin
.savedpos
+= 16; /* skip garbage cookie */
2338 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2339 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2340 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2345 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2346 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2347 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2348 hostkey
= hostkey_algs
[i
];
2352 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2353 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2354 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2355 for (j
= 0; j
< c
->nciphers
; j
++) {
2356 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2357 cscipher_tobe
= c
->list
[j
];
2364 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2365 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2366 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2367 for (j
= 0; j
< c
->nciphers
; j
++) {
2368 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2369 sccipher_tobe
= c
->list
[j
];
2376 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2377 for (i
= 0; i
< nmacs
; i
++) {
2378 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2379 csmac_tobe
= maclist
[i
];
2383 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2384 for (i
= 0; i
< nmacs
; i
++) {
2385 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2386 scmac_tobe
= maclist
[i
];
2390 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2391 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2392 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2393 if (in_commasep_string(c
->name
, str
, len
)) {
2398 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2399 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2400 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2401 if (in_commasep_string(c
->name
, str
, len
)) {
2408 * If we're doing Diffie-Hellman group exchange, start by
2409 * requesting a group.
2411 if (kex
== &ssh_diffiehellman_gex
) {
2414 logevent("Doing Diffie-Hellman group exchange");
2416 * Work out number of bits. We start with the maximum key
2417 * length of either cipher...
2419 csbits
= cscipher_tobe
->keylen
;
2420 scbits
= sccipher_tobe
->keylen
;
2421 nbits
= (csbits
> scbits ? csbits
: scbits
);
2422 /* The keys only have 160-bit entropy, since they're based on
2423 * a SHA-1 hash. So cap the key size at 160 bits. */
2424 if (nbits
> 160) nbits
= 160;
2426 * ... and then work out how big a DH group we will need to
2427 * allow that much data.
2429 nbits
= 512 << ((nbits
-1) / 64);
2430 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2431 ssh2_pkt_adduint32(nbits
);
2435 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2436 bombout(("expected key exchange group packet from server"));
2439 p
= ssh2_pkt_getmp();
2440 g
= ssh2_pkt_getmp();
2441 dh_setup_group(p
, g
);
2442 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2443 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2446 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2447 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2450 logevent("Doing Diffie-Hellman key exchange");
2452 * Now generate and send e for Diffie-Hellman.
2455 ssh2_pkt_init(kex_init_value
);
2460 if (pktin
.type
!= kex_reply_value
) {
2461 bombout(("expected key exchange reply packet from server"));
2464 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2465 f
= ssh2_pkt_getmp();
2466 ssh2_pkt_getstring(&sigdata
, &siglen
);
2470 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2471 if (kex
== &ssh_diffiehellman_gex
) {
2472 sha_uint32(&exhash
, nbits
);
2473 sha_mpint(&exhash
, p
);
2474 sha_mpint(&exhash
, g
);
2476 sha_mpint(&exhash
, e
);
2477 sha_mpint(&exhash
, f
);
2478 sha_mpint(&exhash
, K
);
2479 SHA_Final(&exhash
, exchange_hash
);
2484 debug(("Exchange hash is:\r\n"));
2485 for (i
= 0; i
< 20; i
++)
2486 debug((" %02x", exchange_hash
[i
]));
2490 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2491 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2492 bombout(("Server failed host key check"));
2497 * Expect SSH2_MSG_NEWKEYS from server.
2500 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2501 bombout(("expected new-keys packet from server"));
2506 * Authenticate remote host: verify host key. (We've already
2507 * checked the signature of the exchange hash.)
2509 keystr
= hostkey
->fmtkey(hkey
);
2510 fingerprint
= hostkey
->fingerprint(hkey
);
2511 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2512 keystr
, fingerprint
);
2513 if (first_kex
) { /* don't bother logging this in rekeys */
2514 logevent("Host key fingerprint is:");
2515 logevent(fingerprint
);
2519 hostkey
->freekey(hkey
);
2522 * Send SSH2_MSG_NEWKEYS.
2524 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2528 * Create and initialise session keys.
2530 cscipher
= cscipher_tobe
;
2531 sccipher
= sccipher_tobe
;
2534 cscomp
= cscomp_tobe
;
2535 sccomp
= sccomp_tobe
;
2536 cscomp
->compress_init();
2537 sccomp
->decompress_init();
2539 * Set IVs after keys. Here we use the exchange hash from the
2540 * _first_ key exchange.
2543 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
2544 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
2545 cscipher
->setcskey(keyspace
);
2546 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
2547 sccipher
->setsckey(keyspace
);
2548 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
2549 cscipher
->setcsiv(keyspace
);
2550 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
2551 sccipher
->setsciv(keyspace
);
2552 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
2553 csmac
->setcskey(keyspace
);
2554 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
2555 scmac
->setsckey(keyspace
);
2558 * If this is the first key exchange phase, we must pass the
2559 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2560 * wants to see it but because it will need time to initialise
2561 * itself before it sees an actual packet. In subsequent key
2562 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2563 * it would only confuse the layer above.
2571 * Now we're encrypting. Begin returning 1 to the protocol main
2572 * function so that other things can run on top of the
2573 * transport. If we ever see a KEXINIT, we must go back to the
2576 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
2579 logevent("Server initiated key re-exchange");
2580 goto begin_key_exchange
;
2586 * Add data to an SSH2 channel output buffer.
2588 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
) {
2589 if (c
->v2
.outbufsize
<
2590 c
->v2
.outbuflen
+ len
) {
2592 c
->v2
.outbuflen
+ len
+ 1024;
2593 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
,
2596 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
,
2598 c
->v2
.outbuflen
+= len
;
2602 * Attempt to send data on an SSH2 channel.
2604 static void ssh2_try_send(struct ssh_channel
*c
) {
2605 while (c
->v2
.remwindow
> 0 &&
2606 c
->v2
.outbuflen
> 0) {
2607 unsigned len
= c
->v2
.remwindow
;
2608 if (len
> c
->v2
.outbuflen
)
2609 len
= c
->v2
.outbuflen
;
2610 if (len
> c
->v2
.remmaxpkt
)
2611 len
= c
->v2
.remmaxpkt
;
2612 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2613 ssh2_pkt_adduint32(c
->remoteid
);
2614 ssh2_pkt_addstring_start();
2615 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
2617 c
->v2
.outbuflen
-= len
;
2618 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+len
,
2620 c
->v2
.remwindow
-= len
;
2625 * Handle the SSH2 userauth and connection layers.
2627 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2629 static unsigned long remote_winsize
;
2630 static unsigned long remote_maxpkt
;
2632 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
, AUTH_PASSWORD
2636 AUTH_TYPE_PUBLICKEY
,
2637 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
2638 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
2641 static int gotit
, need_pw
, can_pubkey
, can_passwd
, tried_pubkey_config
;
2642 static int we_are_in
;
2643 static char username
[100];
2644 static char pwprompt
[200];
2645 static char password
[100];
2650 * Request userauth protocol, and await a response to it.
2652 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2653 ssh2_pkt_addstring("ssh-userauth");
2655 crWaitUntilV(ispkt
);
2656 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2657 bombout(("Server refused user authentication protocol"));
2662 * We repeat this whole loop, including the username prompt,
2663 * until we manage a successful authentication. If the user
2664 * types the wrong _password_, they are sent back to the
2665 * beginning to try another username. (If they specify a
2666 * username in the config, they are never asked, even if they
2667 * do give a wrong password.)
2669 * I think this best serves the needs of
2671 * - the people who have no configuration, no keys, and just
2672 * want to try repeated (username,password) pairs until they
2673 * type both correctly
2675 * - people who have keys and configuration but occasionally
2676 * need to fall back to passwords
2678 * - people with a key held in Pageant, who might not have
2679 * logged in to a particular machine before; so they want to
2680 * type a username, and then _either_ their key will be
2681 * accepted, _or_ they will type a password. If they mistype
2682 * the username they will want to be able to get back and
2693 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2694 c_write_str("login as: ");
2697 crWaitUntilV(!ispkt
);
2698 while (inlen
--) switch (c
= *in
++) {
2705 c_write_str("\b \b");
2711 c_write_str("\b \b");
2720 if (((c
>= ' ' && c
<= '~') ||
2721 ((unsigned char)c
>= 160)) && pos
< 40) {
2722 username
[pos
++] = c
;
2728 c_write_str("\r\n");
2729 username
[strcspn(username
, "\n\r")] = '\0';
2732 strncpy(username
, cfg
.username
, 99);
2733 username
[99] = '\0';
2734 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2735 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2741 * Send an authentication request using method "none": (a)
2742 * just in case it succeeds, and (b) so that we know what
2743 * authentication methods we can usefully try next.
2745 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2746 ssh2_pkt_addstring(username
);
2747 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2748 ssh2_pkt_addstring("none"); /* method */
2750 type
= AUTH_TYPE_NONE
;
2754 tried_pubkey_config
= FALSE
;
2758 * Wait for the result of the last authentication request.
2761 crWaitUntilV(ispkt
);
2762 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
2763 /* FIXME: should support this */
2764 crWaitUntilV(ispkt
);
2766 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
2767 logevent("Access granted");
2772 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
2773 bombout(("Strange packet received during authentication: type %d",
2780 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2781 * we can look at the string in it and know what we can
2782 * helpfully try next.
2787 ssh2_pkt_getstring(&methods
, &methlen
);
2788 if (!ssh2_pkt_getbool()) {
2790 * We have received an unequivocal Access
2791 * Denied. This can translate to a variety of
2794 * - if we'd just tried "none" authentication,
2795 * it's not worth printing anything at all
2797 * - if we'd just tried a public key _offer_,
2798 * the message should be "Server refused our
2799 * key" (or no message at all if the key
2800 * came from Pageant)
2802 * - if we'd just tried anything else, the
2803 * message really should be "Access denied".
2805 * Additionally, if we'd just tried password
2806 * authentication, we should break out of this
2807 * whole loop so as to go back to the username
2810 if (type
== AUTH_TYPE_NONE
) {
2812 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
2813 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
2814 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
2815 c_write_str("Server refused our key\r\n");
2816 logevent("Server refused public key");
2818 c_write_str("Access denied\r\n");
2819 logevent("Access denied");
2820 if (type
== AUTH_TYPE_PASSWORD
) {
2826 c_write_str("Further authentication required\r\n");
2827 logevent("Further authentication required");
2830 can_pubkey
= in_commasep_string("publickey", methods
, methlen
);
2831 can_passwd
= in_commasep_string("password", methods
, methlen
);
2836 if (!method
&& can_pubkey
&& *cfg
.keyfile
&& !tried_pubkey_config
) {
2837 unsigned char *pub_blob
;
2838 char *algorithm
, *comment
;
2841 tried_pubkey_config
= TRUE
;
2844 * Try the public key supplied in the configuration.
2846 * First, offer the public blob to see if the server is
2847 * willing to accept it.
2849 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
2852 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2853 ssh2_pkt_addstring(username
);
2854 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2855 ssh2_pkt_addstring("publickey");/* method */
2856 ssh2_pkt_addbool(FALSE
); /* no signature included */
2857 ssh2_pkt_addstring(algorithm
);
2858 ssh2_pkt_addstring_start();
2859 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
2861 logevent("Offered public key"); /* FIXME */
2863 crWaitUntilV(ispkt
);
2864 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
2866 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
2867 continue; /* key refused; give up on it */
2870 logevent("Offer of public key accepted");
2872 * Actually attempt a serious authentication using
2875 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
2876 sprintf(pwprompt
, "Passphrase for key \"%.100s\": ", comment
);
2881 c_write_str("Authenticating with public key \"");
2882 c_write_str(comment
);
2883 c_write_str("\"\r\n");
2884 method
= AUTH_PUBLICKEY_FILE
;
2888 if (!method
&& can_passwd
) {
2889 method
= AUTH_PASSWORD
;
2890 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
, savedhost
);
2895 if (ssh_get_password
) {
2896 if (!ssh_get_password(pwprompt
, password
, sizeof(password
))) {
2898 * get_password failed to get a password (for
2899 * example because one was supplied on the command
2900 * line which has already failed to work).
2903 logevent("No more passwords to try");
2904 ssh_state
= SSH_STATE_CLOSED
;
2911 c_write_str(pwprompt
);
2916 crWaitUntilV(!ispkt
);
2917 while (inlen
--) switch (c
= *in
++) {
2934 if (((c
>= ' ' && c
<= '~') ||
2935 ((unsigned char)c
>= 160)) && pos
< 40)
2936 password
[pos
++] = c
;
2940 c_write_str("\r\n");
2944 if (method
== AUTH_PUBLICKEY_FILE
) {
2946 * We have our passphrase. Now try the actual authentication.
2948 struct ssh2_userkey
*key
;
2950 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
2951 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
2952 if (key
== SSH2_WRONG_PASSPHRASE
) {
2953 c_write_str("Wrong passphrase\r\n");
2954 tried_pubkey_config
= FALSE
;
2956 c_write_str("Unable to load private key\r\n");
2957 tried_pubkey_config
= TRUE
;
2959 /* Send a spurious AUTH_NONE to return to the top. */
2960 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2961 ssh2_pkt_addstring(username
);
2962 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2963 ssh2_pkt_addstring("none"); /* method */
2965 type
= AUTH_TYPE_NONE
;
2967 unsigned char *blob
, *sigdata
;
2968 int blob_len
, sigdata_len
;
2971 * We have loaded the private key and the server
2972 * has announced that it's willing to accept it.
2973 * Hallelujah. Generate a signature and send it.
2975 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2976 ssh2_pkt_addstring(username
);
2977 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2978 ssh2_pkt_addstring("publickey"); /* method */
2979 ssh2_pkt_addbool(TRUE
);
2980 ssh2_pkt_addstring(key
->alg
->name
);
2981 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
2982 ssh2_pkt_addstring_start();
2983 ssh2_pkt_addstring_data(blob
, blob_len
);
2987 * The data to be signed is:
2991 * followed by everything so far placed in the
2994 sigdata_len
= pktout
.length
- 5 + 4 + 20;
2995 sigdata
= smalloc(sigdata_len
);
2996 PUT_32BIT(sigdata
, 20);
2997 memcpy(sigdata
+4, ssh2_session_id
, 20);
2998 memcpy(sigdata
+24, pktout
.data
+5, pktout
.length
-5);
2999 blob
= key
->alg
->sign(key
->data
, sigdata
, sigdata_len
, &blob_len
);
3000 ssh2_pkt_addstring_start();
3001 ssh2_pkt_addstring_data(blob
, blob_len
);
3006 type
= AUTH_TYPE_PUBLICKEY
;
3008 } else if (method
== AUTH_PASSWORD
) {
3010 * We send the password packet lumped tightly together with
3011 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3012 * string long enough to make the total length of the two
3013 * packets constant. This should ensure that a passive
3014 * listener doing traffic analyis can't work out the length
3017 * For this to work, we need an assumption about the
3018 * maximum length of the password packet. I think 256 is
3019 * pretty conservative. Anyone using a password longer than
3020 * that probably doesn't have much to worry about from
3021 * people who find out how long their password is!
3023 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3024 ssh2_pkt_addstring(username
);
3025 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3026 ssh2_pkt_addstring("password");
3027 ssh2_pkt_addbool(FALSE
);
3028 ssh2_pkt_addstring(password
);
3031 * We'll include a string that's an exact multiple of the
3032 * cipher block size. If the cipher is NULL for some
3033 * reason, we don't do this trick at all because we gain
3038 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3039 ssh2_pkt_addstring_start();
3040 for (i
= deferred_len
; i
<= 256; i
+= cscipher
->blksize
) {
3041 for (j
= 0; j
< cscipher
->blksize
; j
++) {
3042 char c
= (char)random_byte();
3043 ssh2_pkt_addstring_data(&c
, 1);
3048 ssh2_pkt_defersend();
3049 type
= AUTH_TYPE_PASSWORD
;
3051 c_write_str("No supported authentication methods left to try!\r\n");
3052 logevent("No supported authentications offered. Disconnecting");
3053 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3054 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3055 ssh2_pkt_addstring("No supported authentication methods available");
3056 ssh2_pkt_addstring("en"); /* language tag */
3058 ssh_state
= SSH_STATE_CLOSED
;
3062 } while (!we_are_in
);
3065 * Now we're authenticated for the connection protocol. The
3066 * connection protocol will automatically have started at this
3067 * point; there's no need to send SERVICE_REQUEST.
3071 * So now create a channel with a session in it.
3073 mainchan
= smalloc(sizeof(struct ssh_channel
));
3074 mainchan
->localid
= 100; /* as good as any */
3075 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3076 ssh2_pkt_addstring("session");
3077 ssh2_pkt_adduint32(mainchan
->localid
);
3078 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3079 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3081 crWaitUntilV(ispkt
);
3082 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3083 bombout(("Server refused to open a session"));
3085 /* FIXME: error data comes back in FAILURE packet */
3087 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3088 bombout(("Server's channel confirmation cited wrong channel"));
3091 mainchan
->remoteid
= ssh2_pkt_getuint32();
3092 mainchan
->type
= CHAN_MAINSESSION
;
3093 mainchan
->closes
= 0;
3094 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3095 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3096 mainchan
->v2
.outbuffer
= NULL
;
3097 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3098 ssh_channels
= newtree234(ssh_channelcmp
);
3099 add234(ssh_channels
, mainchan
);
3100 logevent("Opened channel for session");
3103 * Potentially enable X11 forwarding.
3105 if (cfg
.x11_forward
) {
3106 char proto
[20], data
[64];
3107 logevent("Requesting X11 forwarding");
3108 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3109 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3110 ssh2_pkt_adduint32(mainchan
->remoteid
);
3111 ssh2_pkt_addstring("x11-req");
3112 ssh2_pkt_addbool(1); /* want reply */
3113 ssh2_pkt_addbool(0); /* many connections */
3114 ssh2_pkt_addstring(proto
);
3115 ssh2_pkt_addstring(data
);
3116 ssh2_pkt_adduint32(0); /* screen number */
3120 crWaitUntilV(ispkt
);
3121 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3122 unsigned i
= ssh2_pkt_getuint32();
3123 struct ssh_channel
*c
;
3124 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3126 continue; /* nonexistent channel */
3127 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3129 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3131 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3132 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3133 bombout(("Server got confused by X11 forwarding request"));
3136 logevent("X11 forwarding refused");
3138 logevent("X11 forwarding enabled");
3139 ssh_X11_fwd_enabled
= TRUE
;
3144 * Now allocate a pty for the session.
3147 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3148 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3149 ssh2_pkt_addstring("pty-req");
3150 ssh2_pkt_addbool(1); /* want reply */
3151 ssh2_pkt_addstring(cfg
.termtype
);
3152 ssh2_pkt_adduint32(cols
);
3153 ssh2_pkt_adduint32(rows
);
3154 ssh2_pkt_adduint32(0); /* pixel width */
3155 ssh2_pkt_adduint32(0); /* pixel height */
3156 ssh2_pkt_addstring_start();
3157 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3159 ssh_state
= SSH_STATE_INTERMED
;
3162 crWaitUntilV(ispkt
);
3163 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3164 unsigned i
= ssh2_pkt_getuint32();
3165 struct ssh_channel
*c
;
3166 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3168 continue; /* nonexistent channel */
3169 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3171 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3173 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3174 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3175 bombout(("Server got confused by pty request"));
3178 c_write_str("Server refused to allocate pty\r\n");
3179 ssh_editing
= ssh_echoing
= 1;
3181 logevent("Allocated pty");
3184 ssh_editing
= ssh_echoing
= 1;
3188 * Start a shell or a remote command.
3190 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3191 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3192 if (cfg
.ssh_subsys
) {
3193 ssh2_pkt_addstring("subsystem");
3194 ssh2_pkt_addbool(1); /* want reply */
3195 ssh2_pkt_addstring(cfg
.remote_cmd
);
3196 } else if (*cfg
.remote_cmd
) {
3197 ssh2_pkt_addstring("exec");
3198 ssh2_pkt_addbool(1); /* want reply */
3199 ssh2_pkt_addstring(cfg
.remote_cmd
);
3201 ssh2_pkt_addstring("shell");
3202 ssh2_pkt_addbool(1); /* want reply */
3206 crWaitUntilV(ispkt
);
3207 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3208 unsigned i
= ssh2_pkt_getuint32();
3209 struct ssh_channel
*c
;
3210 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3212 continue; /* nonexistent channel */
3213 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3215 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3216 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3217 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3218 bombout(("Server got confused by shell/command request"));
3221 bombout(("Server refused to start a shell/command"));
3224 logevent("Started a shell/command");
3227 ssh_state
= SSH_STATE_SESSION
;
3231 ssh_special(TS_EOF
);
3236 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3239 static int try_send
;
3243 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3244 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3247 unsigned i
= ssh2_pkt_getuint32();
3248 struct ssh_channel
*c
;
3249 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3251 continue; /* nonexistent channel */
3252 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3253 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3254 continue; /* extended but not stderr */
3255 ssh2_pkt_getstring(&data
, &length
);
3258 case CHAN_MAINSESSION
:
3259 from_backend(pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
,
3263 x11_send(c
->u
.x11
.s
, data
, length
);
3267 * Enlarge the window again at the remote
3268 * side, just in case it ever runs down and
3269 * they fail to send us any more data.
3271 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3272 ssh2_pkt_adduint32(c
->remoteid
);
3273 ssh2_pkt_adduint32(length
);
3276 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
3277 ssh_state
= SSH_STATE_CLOSED
;
3278 logevent("Received disconnect message");
3280 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
3281 continue; /* exit status et al; ignore (FIXME?) */
3282 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
3283 unsigned i
= ssh2_pkt_getuint32();
3284 struct ssh_channel
*c
;
3286 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3288 continue; /* nonexistent channel */
3290 if (c
->type
== CHAN_X11
) {
3292 * Remote EOF on an X11 channel means we should
3293 * wrap up and close the channel ourselves.
3295 x11_close(c
->u
.x11
.s
);
3298 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
3299 unsigned i
= ssh2_pkt_getuint32();
3300 struct ssh_channel
*c
;
3303 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3305 continue; /* nonexistent channel */
3306 if (c
->closes
== 0) {
3307 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3308 ssh2_pkt_adduint32(c
->remoteid
);
3311 /* Do pre-close processing on the channel. */
3313 case CHAN_MAINSESSION
:
3314 break; /* nothing to see here, move along */
3318 del234(ssh_channels
, c
);
3319 sfree(c
->v2
.outbuffer
);
3323 * See if that was the last channel left open.
3325 c
= first234(ssh_channels
, &e
);
3327 logevent("All channels closed. Disconnecting");
3328 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3329 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3330 ssh2_pkt_addstring("All open channels closed");
3331 ssh2_pkt_addstring("en"); /* language tag */
3333 ssh_state
= SSH_STATE_CLOSED
;
3336 continue; /* remote sends close; ignore (FIXME) */
3337 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3338 unsigned i
= ssh2_pkt_getuint32();
3339 struct ssh_channel
*c
;
3340 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3342 continue; /* nonexistent channel */
3343 mainchan
->v2
.remwindow
+= ssh2_pkt_getuint32();
3345 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
3349 struct ssh_channel
*c
;
3350 ssh2_pkt_getstring(&type
, &typelen
);
3351 c
= smalloc(sizeof(struct ssh_channel
));
3353 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
3354 if (!ssh_X11_fwd_enabled
)
3355 error
= "X11 forwarding is not enabled";
3356 else if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3357 error
= "Unable to open an X11 connection";
3362 error
= "Unsupported channel type requested";
3365 c
->remoteid
= ssh2_pkt_getuint32();
3367 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
3368 ssh2_pkt_adduint32(c
->remoteid
);
3369 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
3370 ssh2_pkt_addstring(error
);
3371 ssh2_pkt_addstring("en"); /* language tag */
3375 struct ssh_channel
*d
;
3379 for (i
=1, d
= first234(ssh_channels
, &e
); d
;
3382 break; /* found a free number */
3387 c
->v2
.remwindow
= ssh2_pkt_getuint32();
3388 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3389 c
->v2
.outbuffer
= NULL
;
3390 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
3391 add234(ssh_channels
, c
);
3392 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
3393 ssh2_pkt_adduint32(c
->remoteid
);
3394 ssh2_pkt_adduint32(c
->localid
);
3395 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3396 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3400 bombout(("Strange packet received: type %d", pktin
.type
));
3405 * We have spare data. Add it to the channel buffer.
3407 ssh2_add_channel_data(mainchan
, in
, inlen
);
3412 struct ssh_channel
*c
;
3414 * Try to send data on all channels if we can.
3416 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
))
3425 * Handle the top-level SSH2 protocol.
3427 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
3429 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
3431 do_ssh2_authconn(in
, inlen
, ispkt
);
3435 * Called to set up the connection.
3437 * Returns an error message, or NULL on success.
3439 static char *ssh_init (char *host
, int port
, char **realhost
) {
3443 if(crypto_startup() == 0)
3444 return "Microsoft high encryption pack not installed!";
3451 p
= connect_to_host(host
, port
, realhost
);
3459 * Called to send data down the Telnet connection.
3461 static void ssh_send (char *buf
, int len
) {
3462 if (s
== NULL
|| ssh_protocol
== NULL
)
3465 ssh_protocol(buf
, len
, 0);
3469 * Called to set the size of the window from SSH's POV.
3471 static void ssh_size(void) {
3472 switch (ssh_state
) {
3473 case SSH_STATE_BEFORE_SIZE
:
3474 case SSH_STATE_PREPACKET
:
3475 case SSH_STATE_CLOSED
:
3476 break; /* do nothing */
3477 case SSH_STATE_INTERMED
:
3478 size_needed
= TRUE
; /* buffer for later */
3480 case SSH_STATE_SESSION
:
3482 if (ssh_version
== 1) {
3483 send_packet(SSH1_CMSG_WINDOW_SIZE
,
3484 PKT_INT
, rows
, PKT_INT
, cols
,
3485 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
3487 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3488 ssh2_pkt_adduint32(mainchan
->remoteid
);
3489 ssh2_pkt_addstring("window-change");
3490 ssh2_pkt_addbool(0);
3491 ssh2_pkt_adduint32(cols
);
3492 ssh2_pkt_adduint32(rows
);
3493 ssh2_pkt_adduint32(0);
3494 ssh2_pkt_adduint32(0);
3503 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3504 * can send an EOF and collect resulting output (e.g. `plink
3507 static void ssh_special (Telnet_Special code
) {
3508 if (code
== TS_EOF
) {
3509 if (ssh_state
!= SSH_STATE_SESSION
) {
3511 * Buffer the EOF in case we are pre-SESSION, so we can
3512 * send it as soon as we reach SESSION.
3518 if (ssh_version
== 1) {
3519 send_packet(SSH1_CMSG_EOF
, PKT_END
);
3521 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
3522 ssh2_pkt_adduint32(mainchan
->remoteid
);
3525 logevent("Sent EOF message");
3526 } else if (code
== TS_PING
) {
3527 if (ssh_state
== SSH_STATE_CLOSED
|| ssh_state
== SSH_STATE_PREPACKET
)
3529 if (ssh_version
== 1) {
3530 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
3532 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3533 ssh2_pkt_addstring_start();
3541 static Socket
ssh_socket(void) { return s
; }
3543 static int ssh_sendok(void) { return ssh_send_ok
; }
3545 static int ssh_ldisc(int option
) {
3546 if (option
== LD_ECHO
) return ssh_echoing
;
3547 if (option
== LD_EDIT
) return ssh_editing
;
3551 Backend ssh_backend
= {