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
);
352 * Collect incoming data in the incoming packet buffer.
353 * Decipher and verify the packet when it is completely read.
354 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
355 * Update the *data and *datalen variables.
356 * Return the additional nr of bytes needed, or 0 when
357 * a complete packet is available.
359 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
361 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
370 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
371 while ((*datalen
) == 0)
373 st
->len
= (st
->len
<< 8) + **data
;
374 (*data
)++, (*datalen
)--;
378 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
379 st
->len
= 0x300; /* big enough to carry to end */
383 st
->pad
= 8 - (st
->len
% 8);
384 st
->biglen
= st
->len
+ st
->pad
;
385 pktin
.length
= st
->len
- 5;
387 if (pktin
.maxlen
< st
->biglen
) {
388 pktin
.maxlen
= st
->biglen
;
389 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+APIEXTRA
) :
390 srealloc(pktin
.data
, st
->biglen
+APIEXTRA
));
392 fatalbox("Out of memory");
395 st
->to_read
= st
->biglen
;
397 while (st
->to_read
> 0) {
398 st
->chunk
= st
->to_read
;
399 while ((*datalen
) == 0)
400 crReturn(st
->to_read
);
401 if (st
->chunk
> (*datalen
))
402 st
->chunk
= (*datalen
);
403 memcpy(st
->p
, *data
, st
->chunk
);
405 *datalen
-= st
->chunk
;
407 st
->to_read
-= st
->chunk
;
411 cipher
->decrypt(pktin
.data
, st
->biglen
);
413 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
414 for (st
->i
= 0; st
->i
< st
->biglen
; st
->i
++)
415 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
419 st
->realcrc
= crc32(pktin
.data
, st
->biglen
-4);
420 st
->gotcrc
= GET_32BIT(pktin
.data
+st
->biglen
-4);
421 if (st
->gotcrc
!= st
->realcrc
) {
422 bombout(("Incorrect CRC received on packet"));
426 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
428 if (ssh1_compressing
) {
429 unsigned char *decompblk
;
433 debug(("Packet payload pre-decompression:\n"));
434 for (i
= -1; i
< pktin
.length
; i
++)
435 debug((" %02x", (unsigned char)pktin
.body
[i
]));
438 zlib_decompress_block(pktin
.body
-1, pktin
.length
+1,
439 &decompblk
, &decomplen
);
441 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
442 pktin
.maxlen
= st
->pad
+ decomplen
;
443 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
);
444 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
446 fatalbox("Out of memory");
449 memcpy(pktin
.body
-1, decompblk
, decomplen
);
451 pktin
.length
= decomplen
-1;
453 debug(("Packet payload post-decompression:\n"));
454 for (i
= -1; i
< pktin
.length
; i
++)
455 debug((" %02x", (unsigned char)pktin
.body
[i
]));
460 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
461 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
462 pktin
.type
== SSH1_MSG_DEBUG
||
463 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
464 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
465 long strlen
= GET_32BIT(pktin
.body
);
466 if (strlen
+ 4 != pktin
.length
) {
467 bombout(("Received data packet with bogus string length"));
472 pktin
.type
= pktin
.body
[-1];
474 if (pktin
.type
== SSH1_MSG_DEBUG
) {
475 /* log debug message */
477 int strlen
= GET_32BIT(pktin
.body
);
478 strcpy(buf
, "Remote: ");
479 if (strlen
> 70) strlen
= 70;
480 memcpy(buf
+8, pktin
.body
+4, strlen
);
481 buf
[8+strlen
] = '\0';
484 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
492 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
494 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
502 st
->cipherblk
= sccipher
->blksize
;
505 if (st
->cipherblk
< 8)
508 if (pktin
.maxlen
< st
->cipherblk
) {
509 pktin
.maxlen
= st
->cipherblk
;
510 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->cipherblk
+APIEXTRA
) :
511 srealloc(pktin
.data
, st
->cipherblk
+APIEXTRA
));
513 fatalbox("Out of memory");
517 * Acquire and decrypt the first block of the packet. This will
518 * contain the length and padding details.
520 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
521 while ((*datalen
) == 0)
522 crReturn(st
->cipherblk
-st
->i
);
523 pktin
.data
[st
->i
] = *(*data
)++;
527 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
532 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
535 * Now get the length and padding figures.
537 st
->len
= GET_32BIT(pktin
.data
);
538 st
->pad
= pktin
.data
[4];
541 * This enables us to deduce the payload length.
543 st
->payload
= st
->len
- st
->pad
- 1;
545 pktin
.length
= st
->payload
+ 5;
548 * So now we can work out the total packet length.
550 st
->packetlen
= st
->len
+ 4;
551 st
->maclen
= scmac ? scmac
->len
: 0;
554 * Adjust memory allocation if packet is too big.
556 if (pktin
.maxlen
< st
->packetlen
+st
->maclen
) {
557 pktin
.maxlen
= st
->packetlen
+st
->maclen
;
558 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
559 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
561 fatalbox("Out of memory");
565 * Read and decrypt the remainder of the packet.
567 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
; st
->i
++) {
568 while ((*datalen
) == 0)
569 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
570 pktin
.data
[st
->i
] = *(*data
)++;
573 /* Decrypt everything _except_ the MAC. */
575 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
576 st
->packetlen
- st
->cipherblk
);
579 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
580 for (st
->i
= 0; st
->i
< st
->packetlen
; st
->i
++)
581 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
588 if (scmac
&& !scmac
->verify(pktin
.data
, st
->len
+4, st
->incoming_sequence
)) {
589 bombout(("Incorrect MAC received on packet"));
592 st
->incoming_sequence
++; /* whether or not we MACed */
595 * Decompress packet payload.
598 unsigned char *newpayload
;
600 if (sccomp
&& sccomp
->decompress(pktin
.data
+5, pktin
.length
-5,
601 &newpayload
, &newlen
)) {
602 if (pktin
.maxlen
< newlen
+5) {
603 pktin
.maxlen
= newlen
+5;
604 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
605 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
607 fatalbox("Out of memory");
609 pktin
.length
= 5 + newlen
;
610 memcpy(pktin
.data
+5, newpayload
, newlen
);
612 debug(("Post-decompression payload:\r\n"));
613 for (st
->i
= 0; st
->i
< newlen
; st
->i
++)
614 debug((" %02x", (unsigned char)pktin
.data
[5+st
->i
]));
623 pktin
.type
= pktin
.data
[5];
625 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
626 goto next_packet
; /* FIXME: print DEBUG message */
631 static void ssh1_pktout_size(int len
) {
634 len
+= 5; /* type and CRC */
638 pktout
.length
= len
-5;
639 if (pktout
.maxlen
< biglen
) {
640 pktout
.maxlen
= biglen
;
642 /* Allocate enough buffer space for extra block
643 * for MS CryptEncrypt() */
644 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+12) :
645 srealloc(pktout
.data
, biglen
+12));
647 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+4) :
648 srealloc(pktout
.data
, biglen
+4));
651 fatalbox("Out of memory");
653 pktout
.body
= pktout
.data
+4+pad
+1;
656 static void s_wrpkt_start(int type
, int len
) {
657 ssh1_pktout_size(len
);
661 static void s_wrpkt(void) {
662 int pad
, len
, biglen
, i
;
665 pktout
.body
[-1] = pktout
.type
;
667 if (ssh1_compressing
) {
668 unsigned char *compblk
;
671 debug(("Packet payload pre-compression:\n"));
672 for (i
= -1; i
< pktout
.length
; i
++)
673 debug((" %02x", (unsigned char)pktout
.body
[i
]));
676 zlib_compress_block(pktout
.body
-1, pktout
.length
+1,
678 ssh1_pktout_size(complen
-1);
679 memcpy(pktout
.body
-1, compblk
, complen
);
682 debug(("Packet payload post-compression:\n"));
683 for (i
= -1; i
< pktout
.length
; i
++)
684 debug((" %02x", (unsigned char)pktout
.body
[i
]));
689 len
= pktout
.length
+ 5; /* type and CRC */
693 for (i
=0; i
<pad
; i
++)
694 pktout
.data
[i
+4] = random_byte();
695 crc
= crc32(pktout
.data
+4, biglen
-4);
696 PUT_32BIT(pktout
.data
+biglen
, crc
);
697 PUT_32BIT(pktout
.data
, len
);
700 debug(("Sending packet len=%d\r\n", biglen
+4));
701 for (i
= 0; i
< biglen
+4; i
++)
702 debug((" %02x", (unsigned char)pktout
.data
[i
]));
706 cipher
->encrypt(pktout
.data
+4, biglen
);
708 sk_write(s
, pktout
.data
, biglen
+4);
712 * Construct a packet with the specified contents and
713 * send it to the server.
715 static void send_packet(int pkttype
, ...)
718 unsigned char *p
, *argp
, argchar
;
719 unsigned long argint
;
720 int pktlen
, argtype
, arglen
;
724 va_start(args
, pkttype
);
725 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
728 (void) va_arg(args
, int);
732 (void) va_arg(args
, char);
736 (void) va_arg(args
, unsigned char *);
737 arglen
= va_arg(args
, int);
741 argp
= va_arg(args
, unsigned char *);
742 arglen
= strlen(argp
);
743 pktlen
+= 4 + arglen
;
746 bn
= va_arg(args
, Bignum
);
747 pktlen
+= ssh1_bignum_length(bn
);
755 s_wrpkt_start(pkttype
, pktlen
);
758 va_start(args
, pkttype
);
759 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
762 argint
= va_arg(args
, int);
763 PUT_32BIT(p
, argint
);
767 argchar
= va_arg(args
, unsigned char);
772 argp
= va_arg(args
, unsigned char *);
773 arglen
= va_arg(args
, int);
774 memcpy(p
, argp
, arglen
);
778 argp
= va_arg(args
, unsigned char *);
779 arglen
= strlen(argp
);
780 PUT_32BIT(p
, arglen
);
781 memcpy(p
+ 4, argp
, arglen
);
785 bn
= va_arg(args
, Bignum
);
786 p
+= ssh1_write_bignum(p
, bn
);
795 static int ssh_versioncmp(char *a
, char *b
) {
797 unsigned long av
, bv
;
799 av
= strtoul(a
, &ae
, 10);
800 bv
= strtoul(b
, &be
, 10);
801 if (av
!= bv
) return (av
< bv ?
-1 : +1);
802 if (*ae
== '.') ae
++;
803 if (*be
== '.') be
++;
804 av
= strtoul(ae
, &ae
, 10);
805 bv
= strtoul(be
, &be
, 10);
806 if (av
!= bv
) return (av
< bv ?
-1 : +1);
812 * Utility routines for putting an SSH-protocol `string' and
813 * `uint32' into a SHA state.
816 static void sha_string(SHA_State
*s
, void *str
, int len
) {
817 unsigned char lenblk
[4];
818 PUT_32BIT(lenblk
, len
);
819 SHA_Bytes(s
, lenblk
, 4);
820 SHA_Bytes(s
, str
, len
);
823 static void sha_uint32(SHA_State
*s
, unsigned i
) {
824 unsigned char intblk
[4];
825 PUT_32BIT(intblk
, i
);
826 SHA_Bytes(s
, intblk
, 4);
830 * SSH2 packet construction functions.
832 static void ssh2_pkt_ensure(int length
) {
833 if (pktout
.maxlen
< length
) {
834 pktout
.maxlen
= length
+ 256;
835 pktout
.data
= (pktout
.data
== NULL ?
smalloc(pktout
.maxlen
+APIEXTRA
) :
836 srealloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
838 fatalbox("Out of memory");
841 static void ssh2_pkt_adddata(void *data
, int len
) {
842 pktout
.length
+= len
;
843 ssh2_pkt_ensure(pktout
.length
);
844 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
846 static void ssh2_pkt_addbyte(unsigned char byte
) {
847 ssh2_pkt_adddata(&byte
, 1);
849 static void ssh2_pkt_init(int pkt_type
) {
851 ssh2_pkt_addbyte((unsigned char)pkt_type
);
853 static void ssh2_pkt_addbool(unsigned char value
) {
854 ssh2_pkt_adddata(&value
, 1);
856 static void ssh2_pkt_adduint32(unsigned long value
) {
859 ssh2_pkt_adddata(x
, 4);
861 static void ssh2_pkt_addstring_start(void) {
862 ssh2_pkt_adduint32(0);
863 pktout
.savedpos
= pktout
.length
;
865 static void ssh2_pkt_addstring_str(char *data
) {
866 ssh2_pkt_adddata(data
, strlen(data
));
867 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
868 pktout
.length
- pktout
.savedpos
);
870 static void ssh2_pkt_addstring_data(char *data
, int len
) {
871 ssh2_pkt_adddata(data
, len
);
872 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
873 pktout
.length
- pktout
.savedpos
);
875 static void ssh2_pkt_addstring(char *data
) {
876 ssh2_pkt_addstring_start();
877 ssh2_pkt_addstring_str(data
);
879 static char *ssh2_mpint_fmt(Bignum b
, int *len
) {
881 int i
, n
= (ssh1_bignum_bitcount(b
)+7)/8;
884 fatalbox("out of memory");
886 for (i
= 1; i
<= n
; i
++)
887 p
[i
] = bignum_byte(b
, n
-i
);
889 while (i
<= n
&& p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
891 memmove(p
, p
+i
, n
+1-i
);
895 static void ssh2_pkt_addmp(Bignum b
) {
898 p
= ssh2_mpint_fmt(b
, &len
);
899 ssh2_pkt_addstring_start();
900 ssh2_pkt_addstring_data(p
, len
);
905 * Construct an SSH2 final-form packet: compress it, encrypt it,
906 * put the MAC on it. Final packet, ready to be sent, is stored in
907 * pktout.data. Total length is returned.
909 static int ssh2_pkt_construct(void) {
910 int cipherblk
, maclen
, padding
, i
;
911 static unsigned long outgoing_sequence
= 0;
914 * Compress packet payload.
917 debug(("Pre-compression payload:\r\n"));
918 for (i
= 5; i
< pktout
.length
; i
++)
919 debug((" %02x", (unsigned char)pktout
.data
[i
]));
923 unsigned char *newpayload
;
925 if (cscomp
&& cscomp
->compress(pktout
.data
+5, pktout
.length
-5,
926 &newpayload
, &newlen
)) {
928 ssh2_pkt_adddata(newpayload
, newlen
);
934 * Add padding. At least four bytes, and must also bring total
935 * length (minus MAC) up to a multiple of the block size.
937 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
938 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
940 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
941 maclen
= csmac ? csmac
->len
: 0;
942 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
943 pktout
.data
[4] = padding
;
944 for (i
= 0; i
< padding
; i
++)
945 pktout
.data
[pktout
.length
+ i
] = random_byte();
946 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
948 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
950 outgoing_sequence
++; /* whether or not we MACed */
953 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
954 for (i
= 0; i
< pktout
.length
+padding
; i
++)
955 debug((" %02x", (unsigned char)pktout
.data
[i
]));
960 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
962 /* Ready-to-send packet starts at pktout.data. We return length. */
963 return pktout
.length
+ padding
+ maclen
;
967 * Construct and send an SSH2 packet immediately.
969 static void ssh2_pkt_send(void) {
970 int len
= ssh2_pkt_construct();
971 sk_write(s
, pktout
.data
, len
);
975 * Construct an SSH2 packet and add it to a deferred data block.
976 * Useful for sending multiple packets in a single sk_write() call,
977 * to prevent a traffic-analysing listener from being able to work
978 * out the length of any particular packet (such as the password
981 * Note that because SSH2 sequence-numbers its packets, this can
982 * NOT be used as an m4-style `defer' allowing packets to be
983 * constructed in one order and sent in another.
985 static void ssh2_pkt_defer(void) {
986 int len
= ssh2_pkt_construct();
987 if (deferred_len
+ len
> deferred_size
) {
988 deferred_size
= deferred_len
+ len
+ 128;
989 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
991 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
996 * Send the whole deferred data block constructed by
999 static void ssh2_pkt_defersend(void) {
1000 sk_write(s
, deferred_send_data
, deferred_len
);
1001 deferred_len
= deferred_size
= 0;
1002 sfree(deferred_send_data
);
1003 deferred_send_data
= NULL
;
1007 void bndebug(char *string
, Bignum b
) {
1010 p
= ssh2_mpint_fmt(b
, &len
);
1011 debug(("%s", string
));
1012 for (i
= 0; i
< len
; i
++)
1013 debug((" %02x", p
[i
]));
1019 static void sha_mpint(SHA_State
*s
, Bignum b
) {
1022 p
= ssh2_mpint_fmt(b
, &len
);
1023 sha_string(s
, p
, len
);
1028 * SSH2 packet decode functions.
1030 static unsigned long ssh2_pkt_getuint32(void) {
1031 unsigned long value
;
1032 if (pktin
.length
- pktin
.savedpos
< 4)
1033 return 0; /* arrgh, no way to decline (FIXME?) */
1034 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1035 pktin
.savedpos
+= 4;
1038 static int ssh2_pkt_getbool(void) {
1039 unsigned long value
;
1040 if (pktin
.length
- pktin
.savedpos
< 1)
1041 return 0; /* arrgh, no way to decline (FIXME?) */
1042 value
= pktin
.data
[pktin
.savedpos
] != 0;
1046 static void ssh2_pkt_getstring(char **p
, int *length
) {
1048 if (pktin
.length
- pktin
.savedpos
< 4)
1050 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1051 pktin
.savedpos
+= 4;
1052 if (pktin
.length
- pktin
.savedpos
< *length
)
1054 *p
= pktin
.data
+pktin
.savedpos
;
1055 pktin
.savedpos
+= *length
;
1057 static Bignum
ssh2_pkt_getmp(void) {
1062 ssh2_pkt_getstring(&p
, &length
);
1066 bombout(("internal error: Can't handle negative mpints"));
1069 b
= bignum_from_bytes(p
, length
);
1073 static int do_ssh_init(unsigned char c
) {
1075 static char version
[10];
1076 static char vstring
[80];
1077 static char vlog
[sizeof(vstring
)+20];
1082 /* Search for the string "SSH-" in the input. */
1085 static const int transS
[] = { 1, 2, 2, 1 };
1086 static const int transH
[] = { 0, 0, 3, 0 };
1087 static const int transminus
[] = { 0, 0, 0, -1 };
1088 if (c
== 'S') i
= transS
[i
];
1089 else if (c
== 'H') i
= transH
[i
];
1090 else if (c
== '-') i
= transminus
[i
];
1094 crReturn(1); /* get another character */
1097 strcpy(vstring
, "SSH-");
1101 crReturn(1); /* get another char */
1102 if (vsp
< vstring
+sizeof(vstring
)-1)
1108 } else if (i
< sizeof(version
)-1)
1115 ssh_agentfwd_enabled
= FALSE
;
1116 rdpkt2_state
.incoming_sequence
= 0;
1119 sprintf(vlog
, "Server version: %s", vstring
);
1120 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1124 * Server version "1.99" means we can choose whether we use v1
1125 * or v2 protocol. Choice is based on cfg.sshprot.
1127 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1129 * This is a v2 server. Begin v2 protocol.
1131 char *verstring
= "SSH-2.0-PuTTY";
1132 SHA_Init(&exhashbase
);
1134 * Hash our version string and their version string.
1136 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1137 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1138 sprintf(vstring
, "%s\n", verstring
);
1139 sprintf(vlog
, "We claim version: %s", verstring
);
1141 logevent("Using SSH protocol version 2");
1142 sk_write(s
, vstring
, strlen(vstring
));
1143 ssh_protocol
= ssh2_protocol
;
1145 s_rdpkt
= ssh2_rdpkt
;
1148 * This is a v1 server. Begin v1 protocol.
1150 sprintf(vstring
, "SSH-%s-PuTTY\n",
1151 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1152 sprintf(vlog
, "We claim version: %s", vstring
);
1153 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1155 logevent("Using SSH protocol version 1");
1156 sk_write(s
, vstring
, strlen(vstring
));
1157 ssh_protocol
= ssh1_protocol
;
1159 s_rdpkt
= ssh1_rdpkt
;
1161 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1166 static void ssh_gotdata(unsigned char *data
, int datalen
)
1171 * To begin with, feed the characters one by one to the
1172 * protocol initialisation / selection function do_ssh_init().
1173 * When that returns 0, we're done with the initial greeting
1174 * exchange and can move on to packet discipline.
1179 crReturnV
; /* more data please */
1180 ret
= do_ssh_init(*data
);
1187 * We emerge from that loop when the initial negotiation is
1188 * over and we have selected an s_rdpkt function. Now pass
1189 * everything to s_rdpkt, and then pass the resulting packets
1190 * to the proper protocol handler.
1195 while (datalen
> 0) {
1196 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
1197 ssh_protocol(NULL
, 0, 1);
1198 if (ssh_state
== SSH_STATE_CLOSED
) {
1208 static int ssh_receive(Socket skt
, int urgent
, char *data
, int len
) {
1210 /* A socket error has occurred. */
1211 ssh_state
= SSH_STATE_CLOSED
;
1214 connection_fatal(data
);
1217 /* Connection has closed. */
1218 ssh_state
= SSH_STATE_CLOSED
;
1223 ssh_gotdata (data
, len
);
1224 if (ssh_state
== SSH_STATE_CLOSED
) {
1235 * Connect to specified host and port.
1236 * Returns an error message, or NULL on success.
1237 * Also places the canonical host name into `realhost'.
1239 static char *connect_to_host(char *host
, int port
, char **realhost
)
1248 savedhost
= smalloc(1+strlen(host
));
1250 fatalbox("Out of memory");
1251 strcpy(savedhost
, host
);
1254 port
= 22; /* default ssh port */
1267 addr
= sk_namelookup(host
, realhost
);
1268 if ( (err
= sk_addr_error(addr
)) )
1278 s
= sk_new(addr
, port
, 0, 1, ssh_receive
);
1279 if ( (err
= sk_socket_error(s
)) )
1283 sk_write(s
, "connect ", 8);
1284 sk_write(s
, FWhost
, strlen(FWhost
));
1287 sprintf(buf
, " %d\n", FWport
);
1288 sk_write(s
, buf
, strlen(buf
));
1296 * Handle the key exchange and user authentication phases.
1298 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1301 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1302 unsigned char cookie
[8];
1303 struct RSAKey servkey
, hostkey
;
1304 struct MD5Context md5c
;
1305 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1306 static int tried_publickey
;
1307 static unsigned char session_id
[16];
1309 static char username
[100];
1313 if (!ispkt
) crWaitUntil(ispkt
);
1315 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1316 bombout(("Public key packet not received"));
1320 logevent("Received public keys");
1322 memcpy(cookie
, pktin
.body
, 8);
1324 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1325 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1328 * Log the host key fingerprint.
1332 logevent("Host key fingerprint is:");
1333 strcpy(logmsg
, " ");
1334 hostkey
.comment
= NULL
;
1335 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1340 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1341 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1344 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1345 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1346 MD5Update(&md5c
, pktin
.body
, 8);
1347 MD5Final(session_id
, &md5c
);
1349 for (i
=0; i
<32; i
++)
1350 session_key
[i
] = random_byte();
1352 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1354 rsabuf
= smalloc(len
);
1356 fatalbox("Out of memory");
1359 * Verify the host key.
1363 * First format the key into a string.
1365 int len
= rsastr_len(&hostkey
);
1366 char fingerprint
[100];
1367 char *keystr
= smalloc(len
);
1369 fatalbox("Out of memory");
1370 rsastr_fmt(keystr
, &hostkey
);
1371 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1372 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1376 for (i
=0; i
<32; i
++) {
1377 rsabuf
[i
] = session_key
[i
];
1379 rsabuf
[i
] ^= session_id
[i
];
1382 if (hostkey
.bytes
> servkey
.bytes
) {
1383 rsaencrypt(rsabuf
, 32, &servkey
);
1384 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1386 rsaencrypt(rsabuf
, 32, &hostkey
);
1387 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1390 logevent("Encrypted session key");
1392 switch (cfg
.cipher
) {
1393 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
; break;
1394 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
; break;
1395 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
; break;
1397 c_write("AES not supported in SSH1, falling back to 3DES\r\n", 49);
1398 cipher_type
= SSH_CIPHER_3DES
;
1401 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1402 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1403 cipher_type
= SSH_CIPHER_3DES
;
1405 switch (cipher_type
) {
1406 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1407 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1408 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1411 send_packet(SSH1_CMSG_SESSION_KEY
,
1412 PKT_CHAR
, cipher_type
,
1413 PKT_DATA
, cookie
, 8,
1414 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1415 PKT_DATA
, rsabuf
, len
,
1419 logevent("Trying to enable encryption...");
1423 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1424 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1426 cipher
->sesskey(session_key
);
1430 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1431 bombout(("Encryption not successfully enabled"));
1435 logevent("Successfully started encryption");
1441 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1442 c_write("login as: ", 10);
1445 crWaitUntil(!ispkt
);
1446 while (inlen
--) switch (c
= *in
++) {
1453 c_write("\b \b", 3);
1459 c_write("\b \b", 3);
1468 if (((c
>= ' ' && c
<= '~') ||
1469 ((unsigned char)c
>= 160)) && pos
< 40) {
1470 username
[pos
++] = c
;
1477 username
[strcspn(username
, "\n\r")] = '\0';
1479 strncpy(username
, cfg
.username
, 99);
1480 username
[99] = '\0';
1483 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1485 char userlog
[22+sizeof(username
)];
1486 sprintf(userlog
, "Sent username \"%s\"", username
);
1488 if (flags
& FLAG_INTERACTIVE
&&
1489 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1490 strcat(userlog
, "\r\n");
1491 c_write(userlog
, strlen(userlog
));
1498 tried_publickey
= 0;
1500 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1501 static char password
[100];
1502 static char prompt
[200];
1505 static int pwpkt_type
;
1507 * Show password prompt, having first obtained it via a TIS
1508 * or CryptoCard exchange if we're doing TIS or CryptoCard
1511 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1512 if (agent_exists()) {
1514 * Attempt RSA authentication using Pageant.
1516 static unsigned char request
[5], *response
, *p
;
1517 static int responselen
;
1518 static int i
, nkeys
;
1519 static int authed
= FALSE
;
1522 logevent("Pageant is running. Requesting keys.");
1524 /* Request the keys held by the agent. */
1525 PUT_32BIT(request
, 1);
1526 request
[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES
;
1527 agent_query(request
, 5, &r
, &responselen
);
1528 response
= (unsigned char *)r
;
1531 nkeys
= GET_32BIT(p
); p
+= 4;
1532 { char buf
[64]; sprintf(buf
, "Pageant has %d keys", nkeys
);
1534 for (i
= 0; i
< nkeys
; i
++) {
1535 static struct RSAKey key
;
1536 static Bignum challenge
;
1537 static char *commentp
;
1538 static int commentlen
;
1540 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1543 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1544 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1545 commentlen
= GET_32BIT(p
); p
+= 4;
1546 commentp
= p
; p
+= commentlen
;
1547 send_packet(SSH1_CMSG_AUTH_RSA
,
1548 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1550 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1551 logevent("Key refused");
1554 logevent("Received RSA challenge");
1555 ssh1_read_bignum(pktin
.body
, &challenge
);
1557 char *agentreq
, *q
, *ret
;
1559 len
= 1 + 4; /* message type, bit count */
1560 len
+= ssh1_bignum_length(key
.exponent
);
1561 len
+= ssh1_bignum_length(key
.modulus
);
1562 len
+= ssh1_bignum_length(challenge
);
1563 len
+= 16; /* session id */
1564 len
+= 4; /* response format */
1565 agentreq
= smalloc(4 + len
);
1566 PUT_32BIT(agentreq
, len
);
1568 *q
++ = SSH_AGENTC_RSA_CHALLENGE
;
1569 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1571 q
+= ssh1_write_bignum(q
, key
.exponent
);
1572 q
+= ssh1_write_bignum(q
, key
.modulus
);
1573 q
+= ssh1_write_bignum(q
, challenge
);
1574 memcpy(q
, session_id
, 16); q
+= 16;
1575 PUT_32BIT(q
, 1); /* response format */
1576 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1579 if (ret
[4] == SSH_AGENT_RSA_RESPONSE
) {
1580 logevent("Sending Pageant's response");
1581 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1582 PKT_DATA
, ret
+5, 16, PKT_END
);
1585 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1586 logevent("Pageant's response accepted");
1587 if (flags
& FLAG_VERBOSE
) {
1588 c_write("Authenticated using RSA key \"",
1590 c_write(commentp
, commentlen
);
1591 c_write("\" from agent\r\n", 14);
1595 logevent("Pageant's response not accepted");
1597 logevent("Pageant failed to answer challenge");
1601 logevent("No reply received from Pageant");
1604 freebn(key
.exponent
);
1605 freebn(key
.modulus
);
1614 if (*cfg
.keyfile
&& !tried_publickey
)
1615 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1617 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1619 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1620 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1621 logevent("Requested TIS authentication");
1622 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1624 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1625 logevent("TIS authentication declined");
1626 if (flags
& FLAG_INTERACTIVE
)
1627 c_write("TIS authentication refused.\r\n", 29);
1629 int challengelen
= ((pktin
.body
[0] << 24) |
1630 (pktin
.body
[1] << 16) |
1631 (pktin
.body
[2] << 8) |
1633 logevent("Received TIS challenge");
1634 if (challengelen
> sizeof(prompt
)-1)
1635 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1636 memcpy(prompt
, pktin
.body
+4, challengelen
);
1637 prompt
[challengelen
] = '\0';
1640 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1642 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1643 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1644 logevent("Requested CryptoCard authentication");
1645 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1647 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1648 logevent("CryptoCard authentication declined");
1649 c_write("CryptoCard authentication refused.\r\n", 29);
1651 int challengelen
= ((pktin
.body
[0] << 24) |
1652 (pktin
.body
[1] << 16) |
1653 (pktin
.body
[2] << 8) |
1655 logevent("Received CryptoCard challenge");
1656 if (challengelen
> sizeof(prompt
)-1)
1657 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1658 memcpy(prompt
, pktin
.body
+4, challengelen
);
1659 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1660 sizeof(prompt
)-challengelen
);
1661 prompt
[sizeof(prompt
)-1] = '\0';
1664 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1665 sprintf(prompt
, "%.90s@%.90s's password: ",
1666 username
, savedhost
);
1668 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1669 char *comment
= NULL
;
1670 if (flags
& FLAG_VERBOSE
)
1671 c_write("Trying public key authentication.\r\n", 35);
1672 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1673 if (flags
& FLAG_VERBOSE
)
1674 c_write("No passphrase required.\r\n", 25);
1677 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1681 if (ssh_get_password
) {
1682 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1684 * get_password failed to get a password (for
1685 * example because one was supplied on the command
1686 * line which has already failed to work).
1689 logevent("No more passwords to try");
1690 ssh_state
= SSH_STATE_CLOSED
;
1694 c_write(prompt
, strlen(prompt
));
1698 crWaitUntil(!ispkt
);
1699 while (inlen
--) switch (c
= *in
++) {
1716 if (((c
>= ' ' && c
<= '~') ||
1717 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1718 password
[pos
++] = c
;
1726 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1728 * Try public key authentication with the specified
1731 static struct RSAKey pubkey
;
1732 static Bignum challenge
, response
;
1734 static unsigned char buffer
[32];
1736 tried_publickey
= 1;
1737 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1739 c_write("Couldn't load public key from ", 30);
1740 c_write(cfg
.keyfile
, strlen(cfg
.keyfile
));
1741 c_write(".\r\n", 3);
1742 continue; /* go and try password */
1745 c_write("Wrong passphrase.\r\n", 19);
1746 tried_publickey
= 0;
1747 continue; /* try again */
1751 * Send a public key attempt.
1753 send_packet(SSH1_CMSG_AUTH_RSA
,
1754 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1757 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1758 c_write("Server refused our public key.\r\n", 32);
1759 continue; /* go and try password */
1761 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1762 bombout(("Bizarre response to offer of public key"));
1765 ssh1_read_bignum(pktin
.body
, &challenge
);
1766 response
= rsadecrypt(challenge
, &pubkey
);
1767 freebn(pubkey
.private_exponent
); /* burn the evidence */
1769 for (i
= 0; i
< 32; i
++) {
1770 buffer
[i
] = bignum_byte(response
, 31-i
);
1774 MD5Update(&md5c
, buffer
, 32);
1775 MD5Update(&md5c
, session_id
, 16);
1776 MD5Final(buffer
, &md5c
);
1778 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1779 PKT_DATA
, buffer
, 16, PKT_END
);
1782 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1783 if (flags
& FLAG_VERBOSE
)
1784 c_write("Failed to authenticate with our public key.\r\n",
1786 continue; /* go and try password */
1787 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1788 bombout(("Bizarre response to RSA authentication response"));
1792 break; /* we're through! */
1794 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1796 logevent("Sent password");
1797 memset(password
, 0, strlen(password
));
1799 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1800 if (flags
& FLAG_VERBOSE
)
1801 c_write("Access denied\r\n", 15);
1802 logevent("Authentication refused");
1803 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1804 logevent("Received disconnect request");
1805 ssh_state
= SSH_STATE_CLOSED
;
1807 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1808 bombout(("Strange packet received, type %d", pktin
.type
));
1813 logevent("Authentication successful");
1818 void sshfwd_close(struct ssh_channel
*c
) {
1820 if (ssh_version
== 1) {
1821 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
, PKT_END
);
1823 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
1824 ssh2_pkt_adduint32(c
->remoteid
);
1828 if (c
->type
== CHAN_X11
) {
1830 logevent("X11 connection terminated");
1835 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
) {
1836 if (ssh_version
== 1) {
1837 send_packet(SSH1_MSG_CHANNEL_DATA
,
1838 PKT_INT
, c
->remoteid
,
1843 ssh2_add_channel_data(c
, buf
, len
);
1848 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1853 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1856 if (ssh_state
== SSH_STATE_CLOSED
)
1859 if (cfg
.agentfwd
&& agent_exists()) {
1860 logevent("Requesting agent forwarding");
1861 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
1862 do { crReturnV
; } while (!ispkt
);
1863 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1864 bombout(("Protocol confusion"));
1866 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1867 logevent("Agent forwarding refused");
1869 logevent("Agent forwarding enabled");
1870 ssh_agentfwd_enabled
= TRUE
;
1874 if (cfg
.x11_forward
) {
1875 char proto
[20], data
[64];
1876 logevent("Requesting X11 forwarding");
1877 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
1878 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
1879 PKT_STR
, proto
, PKT_STR
, data
,
1882 do { crReturnV
; } while (!ispkt
);
1883 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1884 bombout(("Protocol confusion"));
1886 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1887 logevent("X11 forwarding refused");
1889 logevent("X11 forwarding enabled");
1890 ssh_X11_fwd_enabled
= TRUE
;
1895 send_packet(SSH1_CMSG_REQUEST_PTY
,
1896 PKT_STR
, cfg
.termtype
,
1897 PKT_INT
, rows
, PKT_INT
, cols
,
1898 PKT_INT
, 0, PKT_INT
, 0,
1901 ssh_state
= SSH_STATE_INTERMED
;
1902 do { crReturnV
; } while (!ispkt
);
1903 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1904 bombout(("Protocol confusion"));
1906 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1907 c_write("Server refused to allocate pty\r\n", 32);
1908 ssh_editing
= ssh_echoing
= 1;
1910 logevent("Allocated pty");
1912 ssh_editing
= ssh_echoing
= 1;
1915 if (cfg
.compression
) {
1916 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
1917 do { crReturnV
; } while (!ispkt
);
1918 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1919 bombout(("Protocol confusion"));
1921 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1922 c_write("Server refused to compress\r\n", 32);
1924 logevent("Started compression");
1925 ssh1_compressing
= TRUE
;
1926 zlib_compress_init();
1927 zlib_decompress_init();
1930 if (*cfg
.remote_cmd
)
1931 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1933 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1934 logevent("Started session");
1936 ssh_state
= SSH_STATE_SESSION
;
1940 ssh_special(TS_EOF
);
1942 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
1944 ssh_channels
= newtree234(ssh_channelcmp
);
1948 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1949 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1950 long len
= GET_32BIT(pktin
.body
);
1951 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
1953 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1954 ssh_state
= SSH_STATE_CLOSED
;
1955 logevent("Received disconnect request");
1957 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
1958 /* Remote side is trying to open a channel to talk to our
1959 * X-Server. Give them back a local channel number. */
1961 struct ssh_channel
*c
, *d
;
1964 logevent("Received X11 connect request");
1965 /* Refuse if X11 forwarding is disabled. */
1966 if (!ssh_X11_fwd_enabled
) {
1967 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
1968 PKT_INT
, GET_32BIT(pktin
.body
),
1970 logevent("Rejected X11 connect request");
1972 c
= smalloc(sizeof(struct ssh_channel
));
1974 if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
1975 logevent("opening X11 forward connection failed");
1977 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
1978 PKT_INT
, GET_32BIT(pktin
.body
),
1981 logevent("opening X11 forward connection succeeded");
1982 for (i
=1, d
= first234(ssh_channels
, &e
); d
; d
= next234(&e
)) {
1984 break; /* found a free number */
1987 c
->remoteid
= GET_32BIT(pktin
.body
);
1990 c
->type
= CHAN_X11
; /* identify channel type */
1991 add234(ssh_channels
, c
);
1992 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
1993 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
1995 logevent("Opened X11 forward channel");
1998 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
1999 /* Remote side is trying to open a channel to talk to our
2000 * agent. Give them back a local channel number. */
2002 struct ssh_channel
*c
;
2005 /* Refuse if agent forwarding is disabled. */
2006 if (!ssh_agentfwd_enabled
) {
2007 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2008 PKT_INT
, GET_32BIT(pktin
.body
),
2012 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
2014 break; /* found a free number */
2017 c
= smalloc(sizeof(struct ssh_channel
));
2018 c
->remoteid
= GET_32BIT(pktin
.body
);
2021 c
->type
= CHAN_AGENT
; /* identify channel type */
2022 c
->u
.a
.lensofar
= 0;
2023 add234(ssh_channels
, c
);
2024 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2025 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2028 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2029 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2030 /* Remote side closes a channel. */
2031 unsigned i
= GET_32BIT(pktin
.body
);
2032 struct ssh_channel
*c
;
2033 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2036 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2037 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
2038 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2039 logevent("X11 connection closed");
2040 assert(c
->u
.x11
.s
!= NULL
);
2041 x11_close(c
->u
.x11
.s
);
2044 c
->closes
|= closetype
;
2045 if (c
->closes
== 3) {
2046 del234(ssh_channels
, c
);
2050 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2051 /* Data sent down one of our channels. */
2052 int i
= GET_32BIT(pktin
.body
);
2053 int len
= GET_32BIT(pktin
.body
+4);
2054 unsigned char *p
= pktin
.body
+8;
2055 struct ssh_channel
*c
;
2056 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2060 x11_send(c
->u
.x11
.s
, p
, len
);
2063 /* Data for an agent message. Buffer it. */
2065 if (c
->u
.a
.lensofar
< 4) {
2066 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2067 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
2068 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2070 if (c
->u
.a
.lensofar
== 4) {
2071 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
2072 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2073 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2075 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2076 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
2077 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
2078 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2080 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2081 void *reply
, *sentreply
;
2083 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
2088 /* Fake SSH_AGENT_FAILURE. */
2089 sentreply
= "\0\0\0\1\5";
2092 send_packet(SSH1_MSG_CHANNEL_DATA
,
2093 PKT_INT
, c
->remoteid
,
2095 PKT_DATA
, sentreply
, replylen
,
2099 sfree(c
->u
.a
.message
);
2100 c
->u
.a
.lensofar
= 0;
2106 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2107 /* may be from EXEC_SHELL on some servers */
2108 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2109 /* may be from EXEC_SHELL on some servers
2110 * if no pty is available or in other odd cases. Ignore */
2111 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2112 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2114 bombout(("Strange packet received: type %d", pktin
.type
));
2119 int len
= min(inlen
, 512);
2120 send_packet(SSH1_CMSG_STDIN_DATA
,
2121 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2132 * Utility routine for decoding comma-separated strings in KEXINIT.
2134 static int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
2135 int needlen
= strlen(needle
);
2138 * Is it at the start of the string?
2140 if (haylen
>= needlen
&& /* haystack is long enough */
2141 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2142 (haylen
== needlen
|| haystack
[needlen
] == ',')
2143 /* either , or EOS follows */
2147 * If not, search for the next comma and resume after that.
2148 * If no comma found, terminate.
2150 while (haylen
> 0 && *haystack
!= ',')
2151 haylen
--, haystack
++;
2154 haylen
--, haystack
++; /* skip over comma itself */
2159 * SSH2 key creation method.
2161 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
, char *keyspace
) {
2163 /* First 20 bytes. */
2166 SHA_Bytes(&s
, H
, 20);
2167 SHA_Bytes(&s
, &chr
, 1);
2168 SHA_Bytes(&s
, sessid
, 20);
2169 SHA_Final(&s
, keyspace
);
2170 /* Next 20 bytes. */
2173 SHA_Bytes(&s
, H
, 20);
2174 SHA_Bytes(&s
, keyspace
, 20);
2175 SHA_Final(&s
, keyspace
+20);
2179 * Handle the SSH2 transport layer.
2181 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2183 static int i
, j
, len
, nbits
;
2185 static Bignum p
, g
, e
, f
, K
;
2186 static int kex_init_value
, kex_reply_value
;
2187 static const struct ssh_mac
**maclist
;
2189 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2190 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2191 static const struct ssh_mac
*csmac_tobe
= NULL
;
2192 static const struct ssh_mac
*scmac_tobe
= NULL
;
2193 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2194 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2195 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2196 static int hostkeylen
, siglen
;
2197 static void *hkey
; /* actual host key */
2198 static unsigned char exchange_hash
[20];
2199 static unsigned char keyspace
[40];
2200 static const struct ssh2_ciphers
*preferred_cipher
;
2201 static const struct ssh_compress
*preferred_comp
;
2202 static int first_kex
;
2209 * Set up the preferred cipher and compression.
2211 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2212 preferred_cipher
= &ssh2_blowfish
;
2213 } else if (cfg
.cipher
== CIPHER_DES
) {
2214 logevent("Single DES not supported in SSH2; using 3DES");
2215 preferred_cipher
= &ssh2_3des
;
2216 } else if (cfg
.cipher
== CIPHER_3DES
) {
2217 preferred_cipher
= &ssh2_3des
;
2218 } else if (cfg
.cipher
== CIPHER_AES
) {
2219 preferred_cipher
= &ssh2_aes
;
2221 /* Shouldn't happen, but we do want to initialise to _something_. */
2222 preferred_cipher
= &ssh2_3des
;
2224 if (cfg
.compression
)
2225 preferred_comp
= &ssh_zlib
;
2227 preferred_comp
= &ssh_comp_none
;
2230 * Be prepared to work around the buggy MAC problem.
2233 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2235 maclist
= macs
, nmacs
= lenof(macs
);
2239 * Construct and send our key exchange packet.
2241 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2242 for (i
= 0; i
< 16; i
++)
2243 ssh2_pkt_addbyte((unsigned char)random_byte());
2244 /* List key exchange algorithms. */
2245 ssh2_pkt_addstring_start();
2246 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2247 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2248 if (i
< lenof(kex_algs
)-1)
2249 ssh2_pkt_addstring_str(",");
2251 /* List server host key algorithms. */
2252 ssh2_pkt_addstring_start();
2253 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2254 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2255 if (i
< lenof(hostkey_algs
)-1)
2256 ssh2_pkt_addstring_str(",");
2258 /* List client->server encryption algorithms. */
2259 ssh2_pkt_addstring_start();
2260 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2261 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2262 for (j
= 0; j
< c
->nciphers
; j
++) {
2263 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2264 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2265 ssh2_pkt_addstring_str(",");
2268 /* List server->client encryption algorithms. */
2269 ssh2_pkt_addstring_start();
2270 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2271 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2272 for (j
= 0; j
< c
->nciphers
; j
++) {
2273 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2274 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2275 ssh2_pkt_addstring_str(",");
2278 /* List client->server MAC algorithms. */
2279 ssh2_pkt_addstring_start();
2280 for (i
= 0; i
< nmacs
; i
++) {
2281 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2283 ssh2_pkt_addstring_str(",");
2285 /* List server->client MAC algorithms. */
2286 ssh2_pkt_addstring_start();
2287 for (i
= 0; i
< nmacs
; i
++) {
2288 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2290 ssh2_pkt_addstring_str(",");
2292 /* List client->server compression algorithms. */
2293 ssh2_pkt_addstring_start();
2294 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2295 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2296 ssh2_pkt_addstring_str(c
->name
);
2297 if (i
< lenof(compressions
))
2298 ssh2_pkt_addstring_str(",");
2300 /* List server->client compression algorithms. */
2301 ssh2_pkt_addstring_start();
2302 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2303 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2304 ssh2_pkt_addstring_str(c
->name
);
2305 if (i
< lenof(compressions
))
2306 ssh2_pkt_addstring_str(",");
2308 /* List client->server languages. Empty list. */
2309 ssh2_pkt_addstring_start();
2310 /* List server->client languages. Empty list. */
2311 ssh2_pkt_addstring_start();
2312 /* First KEX packet does _not_ follow, because we're not that brave. */
2313 ssh2_pkt_addbool(FALSE
);
2315 ssh2_pkt_adduint32(0);
2317 exhash
= exhashbase
;
2318 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
2322 if (!ispkt
) crWaitUntil(ispkt
);
2323 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
2326 * Now examine the other side's KEXINIT to see what we're up
2329 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2330 bombout(("expected key exchange packet from server"));
2333 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
2334 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
2335 pktin
.savedpos
+= 16; /* skip garbage cookie */
2336 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2337 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2338 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2343 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2344 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2345 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2346 hostkey
= hostkey_algs
[i
];
2350 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2351 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2352 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2353 for (j
= 0; j
< c
->nciphers
; j
++) {
2354 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2355 cscipher_tobe
= c
->list
[j
];
2362 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2363 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2364 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2365 for (j
= 0; j
< c
->nciphers
; j
++) {
2366 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2367 sccipher_tobe
= c
->list
[j
];
2374 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2375 for (i
= 0; i
< nmacs
; i
++) {
2376 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2377 csmac_tobe
= maclist
[i
];
2381 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2382 for (i
= 0; i
< nmacs
; i
++) {
2383 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2384 scmac_tobe
= maclist
[i
];
2388 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2389 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2390 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2391 if (in_commasep_string(c
->name
, str
, len
)) {
2396 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2397 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2398 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2399 if (in_commasep_string(c
->name
, str
, len
)) {
2406 * If we're doing Diffie-Hellman group exchange, start by
2407 * requesting a group.
2409 if (kex
== &ssh_diffiehellman_gex
) {
2412 logevent("Doing Diffie-Hellman group exchange");
2414 * Work out number of bits. We start with the maximum key
2415 * length of either cipher...
2417 csbits
= cscipher_tobe
->keylen
;
2418 scbits
= sccipher_tobe
->keylen
;
2419 nbits
= (csbits
> scbits ? csbits
: scbits
);
2420 /* The keys only have 160-bit entropy, since they're based on
2421 * a SHA-1 hash. So cap the key size at 160 bits. */
2422 if (nbits
> 160) nbits
= 160;
2424 * ... and then work out how big a DH group we will need to
2425 * allow that much data.
2427 nbits
= 512 << ((nbits
-1) / 64);
2428 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2429 ssh2_pkt_adduint32(nbits
);
2433 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2434 bombout(("expected key exchange group packet from server"));
2437 p
= ssh2_pkt_getmp();
2438 g
= ssh2_pkt_getmp();
2439 dh_setup_group(p
, g
);
2440 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2441 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2444 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2445 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2448 logevent("Doing Diffie-Hellman key exchange");
2450 * Now generate and send e for Diffie-Hellman.
2453 ssh2_pkt_init(kex_init_value
);
2458 if (pktin
.type
!= kex_reply_value
) {
2459 bombout(("expected key exchange reply packet from server"));
2462 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2463 f
= ssh2_pkt_getmp();
2464 ssh2_pkt_getstring(&sigdata
, &siglen
);
2468 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2469 if (kex
== &ssh_diffiehellman_gex
) {
2470 sha_uint32(&exhash
, nbits
);
2471 sha_mpint(&exhash
, p
);
2472 sha_mpint(&exhash
, g
);
2474 sha_mpint(&exhash
, e
);
2475 sha_mpint(&exhash
, f
);
2476 sha_mpint(&exhash
, K
);
2477 SHA_Final(&exhash
, exchange_hash
);
2482 debug(("Exchange hash is:\r\n"));
2483 for (i
= 0; i
< 20; i
++)
2484 debug((" %02x", exchange_hash
[i
]));
2488 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2489 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2490 bombout(("Server failed host key check"));
2495 * Expect SSH2_MSG_NEWKEYS from server.
2498 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2499 bombout(("expected new-keys packet from server"));
2504 * Authenticate remote host: verify host key. (We've already
2505 * checked the signature of the exchange hash.)
2507 keystr
= hostkey
->fmtkey(hkey
);
2508 fingerprint
= hostkey
->fingerprint(hkey
);
2509 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2510 keystr
, fingerprint
);
2511 if (first_kex
) { /* don't bother logging this in rekeys */
2512 logevent("Host key fingerprint is:");
2513 logevent(fingerprint
);
2517 hostkey
->freekey(hkey
);
2520 * Send SSH2_MSG_NEWKEYS.
2522 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2526 * Create and initialise session keys.
2528 cscipher
= cscipher_tobe
;
2529 sccipher
= sccipher_tobe
;
2532 cscomp
= cscomp_tobe
;
2533 sccomp
= sccomp_tobe
;
2534 cscomp
->compress_init();
2535 sccomp
->decompress_init();
2537 * Set IVs after keys. Here we use the exchange hash from the
2538 * _first_ key exchange.
2541 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
2542 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
2543 cscipher
->setcskey(keyspace
);
2544 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
2545 sccipher
->setsckey(keyspace
);
2546 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
2547 cscipher
->setcsiv(keyspace
);
2548 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
2549 sccipher
->setsciv(keyspace
);
2550 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
2551 csmac
->setcskey(keyspace
);
2552 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
2553 scmac
->setsckey(keyspace
);
2556 * If this is the first key exchange phase, we must pass the
2557 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2558 * wants to see it but because it will need time to initialise
2559 * itself before it sees an actual packet. In subsequent key
2560 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2561 * it would only confuse the layer above.
2569 * Now we're encrypting. Begin returning 1 to the protocol main
2570 * function so that other things can run on top of the
2571 * transport. If we ever see a KEXINIT, we must go back to the
2574 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
2577 logevent("Server initiated key re-exchange");
2578 goto begin_key_exchange
;
2584 * Add data to an SSH2 channel output buffer.
2586 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
) {
2587 if (c
->v2
.outbufsize
<
2588 c
->v2
.outbuflen
+ len
) {
2590 c
->v2
.outbuflen
+ len
+ 1024;
2591 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
,
2594 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
,
2596 c
->v2
.outbuflen
+= len
;
2600 * Attempt to send data on an SSH2 channel.
2602 static void ssh2_try_send(struct ssh_channel
*c
) {
2603 while (c
->v2
.remwindow
> 0 &&
2604 c
->v2
.outbuflen
> 0) {
2605 unsigned len
= c
->v2
.remwindow
;
2606 if (len
> c
->v2
.outbuflen
)
2607 len
= c
->v2
.outbuflen
;
2608 if (len
> c
->v2
.remmaxpkt
)
2609 len
= c
->v2
.remmaxpkt
;
2610 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2611 ssh2_pkt_adduint32(c
->remoteid
);
2612 ssh2_pkt_addstring_start();
2613 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
2615 c
->v2
.outbuflen
-= len
;
2616 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+len
,
2618 c
->v2
.remwindow
-= len
;
2623 * Handle the SSH2 userauth and connection layers.
2625 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2627 static unsigned long remote_winsize
;
2628 static unsigned long remote_maxpkt
;
2630 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
, AUTH_PASSWORD
2632 static int gotit
, need_pw
, can_pubkey
, can_passwd
, tried_pubkey_config
;
2633 static char username
[100];
2634 static char pwprompt
[200];
2635 static char password
[100];
2640 * Request userauth protocol, and await a response to it.
2642 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2643 ssh2_pkt_addstring("ssh-userauth");
2645 crWaitUntilV(ispkt
);
2646 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2647 bombout(("Server refused user authentication protocol"));
2658 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2659 c_write("login as: ", 10);
2662 crWaitUntilV(!ispkt
);
2663 while (inlen
--) switch (c
= *in
++) {
2670 c_write("\b \b", 3);
2676 c_write("\b \b", 3);
2685 if (((c
>= ' ' && c
<= '~') ||
2686 ((unsigned char)c
>= 160)) && pos
< 40) {
2687 username
[pos
++] = c
;
2694 username
[strcspn(username
, "\n\r")] = '\0';
2697 strncpy(username
, cfg
.username
, 99);
2698 username
[99] = '\0';
2699 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2700 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2701 c_write(stuff
, strlen(stuff
));
2707 * Send an authentication request using method "none": (a)
2708 * just in case it succeeds, and (b) so that we know what
2709 * authentication methods we can usefully try next.
2711 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2712 ssh2_pkt_addstring(username
);
2713 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2714 ssh2_pkt_addstring("none"); /* method */
2716 logevent("Attempting null authentication");
2721 * Wait for the result of the last authentication request.
2724 crWaitUntilV(ispkt
);
2725 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
2726 /* FIXME: should support this */
2727 crWaitUntilV(ispkt
);
2729 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
2730 logevent("Access granted");
2734 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
2735 bombout(("Strange packet received during authentication: type %d",
2742 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2743 * we can look at the string in it and know what we can
2744 * helpfully try next.
2749 ssh2_pkt_getstring(&methods
, &methlen
);
2750 if (!ssh2_pkt_getbool()) {
2752 * FIXME: these messages are often inappropriate.
2754 c_write("Access denied\r\n", 15);
2755 logevent("Access denied");
2757 c_write("Authentication partially successful\r\n", 37);
2758 logevent("Authentication partially successful");
2761 can_pubkey
= in_commasep_string("publickey", methods
, methlen
);
2762 can_passwd
= in_commasep_string("password", methods
, methlen
);
2767 if (!method
&& can_pubkey
&& *cfg
.keyfile
&& !tried_pubkey_config
) {
2768 unsigned char *pub_blob
;
2769 char *algorithm
, *comment
;
2772 tried_pubkey_config
= TRUE
;
2775 * Try the public key supplied in the configuration.
2777 * First, offer the public blob to see if the server is
2778 * willing to accept it.
2780 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
2783 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2784 ssh2_pkt_addstring(username
);
2785 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2786 ssh2_pkt_addstring("publickey");/* method */
2787 ssh2_pkt_addbool(FALSE
); /* no signature included */
2788 ssh2_pkt_addstring(algorithm
);
2789 ssh2_pkt_addstring_start();
2790 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
2792 logevent("Offered public key"); /* FIXME */
2794 crWaitUntilV(ispkt
);
2795 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
2797 continue; /* key refused; give up on it */
2800 logevent("Offer of public key accepted");
2802 * Actually attempt a serious authentication using
2805 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
2806 sprintf(pwprompt
, "Passphrase for key \"%.100s\": ", comment
);
2811 method
= AUTH_PUBLICKEY_FILE
;
2815 if (!method
&& can_passwd
) {
2816 method
= AUTH_PASSWORD
;
2817 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
, savedhost
);
2822 if (ssh_get_password
) {
2823 if (!ssh_get_password(pwprompt
, password
, sizeof(password
))) {
2825 * get_password failed to get a password (for
2826 * example because one was supplied on the command
2827 * line which has already failed to work).
2830 logevent("No more passwords to try");
2831 ssh_state
= SSH_STATE_CLOSED
;
2838 c_write(pwprompt
, strlen(pwprompt
));
2843 crWaitUntilV(!ispkt
);
2844 while (inlen
--) switch (c
= *in
++) {
2861 if (((c
>= ' ' && c
<= '~') ||
2862 ((unsigned char)c
>= 160)) && pos
< 40)
2863 password
[pos
++] = c
;
2871 if (method
== AUTH_PUBLICKEY_FILE
) {
2873 * We have our passphrase. Now try the actual authentication.
2875 struct ssh2_userkey
*key
;
2877 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
2878 if (key
== SSH2_WRONG_PASSPHRASE
) {
2879 c_write("Wrong passphrase\r\n", 18);
2880 tried_pubkey_config
= FALSE
;
2881 /* Send a spurious AUTH_NONE to return to the top. */
2882 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2883 ssh2_pkt_addstring(username
);
2884 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2885 ssh2_pkt_addstring("none"); /* method */
2887 } else if (key
== NULL
) {
2888 c_write("Unable to load private key\r\n",28);
2889 tried_pubkey_config
= TRUE
;
2890 /* Send a spurious AUTH_NONE to return to the top. */
2891 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2892 ssh2_pkt_addstring(username
);
2893 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2894 ssh2_pkt_addstring("none"); /* method */
2897 unsigned char *blob
, *sigdata
;
2898 int blob_len
, sigdata_len
;
2901 * We have loaded the private key and the server
2902 * has announced that it's willing to accept it.
2903 * Hallelujah. Generate a signature and send it.
2905 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2906 ssh2_pkt_addstring(username
);
2907 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2908 ssh2_pkt_addstring("publickey"); /* method */
2909 ssh2_pkt_addbool(TRUE
);
2910 ssh2_pkt_addstring(key
->alg
->name
);
2911 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
2912 ssh2_pkt_addstring_start();
2913 ssh2_pkt_addstring_data(blob
, blob_len
);
2917 * The data to be signed is:
2921 * followed by everything so far placed in the
2924 sigdata_len
= pktout
.length
- 5 + 4 + 20;
2925 sigdata
= smalloc(sigdata_len
);
2926 PUT_32BIT(sigdata
, 20);
2927 memcpy(sigdata
+4, ssh2_session_id
, 20);
2928 memcpy(sigdata
+24, pktout
.data
+5, pktout
.length
-5);
2929 blob
= key
->alg
->sign(key
->data
, sigdata
, sigdata_len
, &blob_len
);
2930 ssh2_pkt_addstring_start();
2931 ssh2_pkt_addstring_data(blob
, blob_len
);
2937 } else if (method
== AUTH_PASSWORD
) {
2939 * We send the password packet lumped tightly together with
2940 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
2941 * string long enough to make the total length of the two
2942 * packets constant. This should ensure that a passive
2943 * listener doing traffic analyis can't work out the length
2946 * For this to work, we need an assumption about the
2947 * maximum length of the password packet. I think 256 is
2948 * pretty conservative. Anyone using a password longer than
2949 * that probably doesn't have much to worry about from
2950 * people who find out how long their password is!
2952 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2953 ssh2_pkt_addstring(username
);
2954 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2955 ssh2_pkt_addstring("password");
2956 ssh2_pkt_addbool(FALSE
);
2957 ssh2_pkt_addstring(password
);
2960 * We'll include a string that's an exact multiple of the
2961 * cipher block size. If the cipher is NULL for some
2962 * reason, we don't do this trick at all because we gain
2967 ssh2_pkt_init(SSH2_MSG_IGNORE
);
2968 ssh2_pkt_addstring_start();
2969 for (i
= deferred_len
; i
<= 256; i
+= cscipher
->blksize
) {
2970 for (j
= 0; j
< cscipher
->blksize
; j
++) {
2971 char c
= (char)random_byte();
2972 ssh2_pkt_addstring_data(&c
, 1);
2977 ssh2_pkt_defersend();
2979 c_write("No supported authentication methods left to try!\r\n", 50);
2980 logevent("No supported authentications offered. Disconnecting");
2981 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2982 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
2983 ssh2_pkt_addstring("No supported authentication methods available");
2984 ssh2_pkt_addstring("en"); /* language tag */
2986 ssh_state
= SSH_STATE_CLOSED
;
2992 * Now we're authenticated for the connection protocol. The
2993 * connection protocol will automatically have started at this
2994 * point; there's no need to send SERVICE_REQUEST.
2998 * So now create a channel with a session in it.
3000 mainchan
= smalloc(sizeof(struct ssh_channel
));
3001 mainchan
->localid
= 100; /* as good as any */
3002 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3003 ssh2_pkt_addstring("session");
3004 ssh2_pkt_adduint32(mainchan
->localid
);
3005 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3006 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3008 crWaitUntilV(ispkt
);
3009 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3010 bombout(("Server refused to open a session"));
3012 /* FIXME: error data comes back in FAILURE packet */
3014 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3015 bombout(("Server's channel confirmation cited wrong channel"));
3018 mainchan
->remoteid
= ssh2_pkt_getuint32();
3019 mainchan
->type
= CHAN_MAINSESSION
;
3020 mainchan
->closes
= 0;
3021 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3022 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3023 mainchan
->v2
.outbuffer
= NULL
;
3024 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3025 ssh_channels
= newtree234(ssh_channelcmp
);
3026 add234(ssh_channels
, mainchan
);
3027 logevent("Opened channel for session");
3030 * Potentially enable X11 forwarding.
3032 if (cfg
.x11_forward
) {
3033 char proto
[20], data
[64];
3034 logevent("Requesting X11 forwarding");
3035 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3036 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3037 ssh2_pkt_adduint32(mainchan
->remoteid
);
3038 ssh2_pkt_addstring("x11-req");
3039 ssh2_pkt_addbool(1); /* want reply */
3040 ssh2_pkt_addbool(0); /* many connections */
3041 ssh2_pkt_addstring(proto
);
3042 ssh2_pkt_addstring(data
);
3043 ssh2_pkt_adduint32(0); /* screen number */
3047 crWaitUntilV(ispkt
);
3048 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3049 unsigned i
= ssh2_pkt_getuint32();
3050 struct ssh_channel
*c
;
3051 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3053 continue; /* nonexistent channel */
3054 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3056 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3058 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3059 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3060 bombout(("Server got confused by X11 forwarding request"));
3063 logevent("X11 forwarding refused");
3065 logevent("X11 forwarding enabled");
3066 ssh_X11_fwd_enabled
= TRUE
;
3071 * Now allocate a pty for the session.
3074 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3075 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3076 ssh2_pkt_addstring("pty-req");
3077 ssh2_pkt_addbool(1); /* want reply */
3078 ssh2_pkt_addstring(cfg
.termtype
);
3079 ssh2_pkt_adduint32(cols
);
3080 ssh2_pkt_adduint32(rows
);
3081 ssh2_pkt_adduint32(0); /* pixel width */
3082 ssh2_pkt_adduint32(0); /* pixel height */
3083 ssh2_pkt_addstring_start();
3084 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3086 ssh_state
= SSH_STATE_INTERMED
;
3089 crWaitUntilV(ispkt
);
3090 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3091 unsigned i
= ssh2_pkt_getuint32();
3092 struct ssh_channel
*c
;
3093 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3095 continue; /* nonexistent channel */
3096 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3098 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3100 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3101 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3102 bombout(("Server got confused by pty request"));
3105 c_write("Server refused to allocate pty\r\n", 32);
3106 ssh_editing
= ssh_echoing
= 1;
3108 logevent("Allocated pty");
3111 ssh_editing
= ssh_echoing
= 1;
3115 * Start a shell or a remote command.
3117 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3118 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3119 if (cfg
.ssh_subsys
) {
3120 ssh2_pkt_addstring("subsystem");
3121 ssh2_pkt_addbool(1); /* want reply */
3122 ssh2_pkt_addstring(cfg
.remote_cmd
);
3123 } else if (*cfg
.remote_cmd
) {
3124 ssh2_pkt_addstring("exec");
3125 ssh2_pkt_addbool(1); /* want reply */
3126 ssh2_pkt_addstring(cfg
.remote_cmd
);
3128 ssh2_pkt_addstring("shell");
3129 ssh2_pkt_addbool(1); /* want reply */
3133 crWaitUntilV(ispkt
);
3134 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3135 unsigned i
= ssh2_pkt_getuint32();
3136 struct ssh_channel
*c
;
3137 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3139 continue; /* nonexistent channel */
3140 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3142 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3143 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3144 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3145 bombout(("Server got confused by shell/command request"));
3148 bombout(("Server refused to start a shell/command"));
3151 logevent("Started a shell/command");
3154 ssh_state
= SSH_STATE_SESSION
;
3158 ssh_special(TS_EOF
);
3163 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3166 static int try_send
;
3170 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3171 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3174 unsigned i
= ssh2_pkt_getuint32();
3175 struct ssh_channel
*c
;
3176 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3178 continue; /* nonexistent channel */
3179 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3180 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3181 continue; /* extended but not stderr */
3182 ssh2_pkt_getstring(&data
, &length
);
3185 case CHAN_MAINSESSION
:
3186 from_backend(pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
,
3190 x11_send(c
->u
.x11
.s
, data
, length
);
3194 * Enlarge the window again at the remote
3195 * side, just in case it ever runs down and
3196 * they fail to send us any more data.
3198 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3199 ssh2_pkt_adduint32(c
->remoteid
);
3200 ssh2_pkt_adduint32(length
);
3203 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
3204 ssh_state
= SSH_STATE_CLOSED
;
3205 logevent("Received disconnect message");
3207 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
3208 continue; /* exit status et al; ignore (FIXME?) */
3209 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
3210 unsigned i
= ssh2_pkt_getuint32();
3211 struct ssh_channel
*c
;
3213 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3215 continue; /* nonexistent channel */
3217 if (c
->type
== CHAN_X11
) {
3219 * Remote EOF on an X11 channel means we should
3220 * wrap up and close the channel ourselves.
3222 x11_close(c
->u
.x11
.s
);
3225 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
3226 unsigned i
= ssh2_pkt_getuint32();
3227 struct ssh_channel
*c
;
3230 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3232 continue; /* nonexistent channel */
3233 if (c
->closes
== 0) {
3234 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3235 ssh2_pkt_adduint32(c
->remoteid
);
3238 /* Do pre-close processing on the channel. */
3240 case CHAN_MAINSESSION
:
3241 break; /* nothing to see here, move along */
3245 del234(ssh_channels
, c
);
3246 sfree(c
->v2
.outbuffer
);
3250 * See if that was the last channel left open.
3252 c
= first234(ssh_channels
, &e
);
3254 logevent("All channels closed. Disconnecting");
3255 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3256 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3257 ssh2_pkt_addstring("All open channels closed");
3258 ssh2_pkt_addstring("en"); /* language tag */
3260 ssh_state
= SSH_STATE_CLOSED
;
3263 continue; /* remote sends close; ignore (FIXME) */
3264 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3265 unsigned i
= ssh2_pkt_getuint32();
3266 struct ssh_channel
*c
;
3267 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3269 continue; /* nonexistent channel */
3270 mainchan
->v2
.remwindow
+= ssh2_pkt_getuint32();
3272 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
3276 struct ssh_channel
*c
;
3277 ssh2_pkt_getstring(&type
, &typelen
);
3278 c
= smalloc(sizeof(struct ssh_channel
));
3280 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
3281 if (!ssh_X11_fwd_enabled
)
3282 error
= "X11 forwarding is not enabled";
3283 else if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3284 error
= "Unable to open an X11 connection";
3289 error
= "Unsupported channel type requested";
3292 c
->remoteid
= ssh2_pkt_getuint32();
3294 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
3295 ssh2_pkt_adduint32(c
->remoteid
);
3296 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
3297 ssh2_pkt_addstring(error
);
3298 ssh2_pkt_addstring("en"); /* language tag */
3302 struct ssh_channel
*d
;
3306 for (i
=1, d
= first234(ssh_channels
, &e
); d
;
3309 break; /* found a free number */
3314 c
->v2
.remwindow
= ssh2_pkt_getuint32();
3315 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3316 c
->v2
.outbuffer
= NULL
;
3317 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
3318 add234(ssh_channels
, c
);
3319 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
3320 ssh2_pkt_adduint32(c
->remoteid
);
3321 ssh2_pkt_adduint32(c
->localid
);
3322 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3323 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3327 bombout(("Strange packet received: type %d", pktin
.type
));
3332 * We have spare data. Add it to the channel buffer.
3334 ssh2_add_channel_data(mainchan
, in
, inlen
);
3339 struct ssh_channel
*c
;
3341 * Try to send data on all channels if we can.
3343 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
))
3352 * Handle the top-level SSH2 protocol.
3354 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
3356 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
3358 do_ssh2_authconn(in
, inlen
, ispkt
);
3362 * Called to set up the connection.
3364 * Returns an error message, or NULL on success.
3366 static char *ssh_init (char *host
, int port
, char **realhost
) {
3370 if(crypto_startup() == 0)
3371 return "Microsoft high encryption pack not installed!";
3378 p
= connect_to_host(host
, port
, realhost
);
3386 * Called to send data down the Telnet connection.
3388 static void ssh_send (char *buf
, int len
) {
3389 if (s
== NULL
|| ssh_protocol
== NULL
)
3392 ssh_protocol(buf
, len
, 0);
3396 * Called to set the size of the window from SSH's POV.
3398 static void ssh_size(void) {
3399 switch (ssh_state
) {
3400 case SSH_STATE_BEFORE_SIZE
:
3401 case SSH_STATE_PREPACKET
:
3402 case SSH_STATE_CLOSED
:
3403 break; /* do nothing */
3404 case SSH_STATE_INTERMED
:
3405 size_needed
= TRUE
; /* buffer for later */
3407 case SSH_STATE_SESSION
:
3409 if (ssh_version
== 1) {
3410 send_packet(SSH1_CMSG_WINDOW_SIZE
,
3411 PKT_INT
, rows
, PKT_INT
, cols
,
3412 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
3414 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3415 ssh2_pkt_adduint32(mainchan
->remoteid
);
3416 ssh2_pkt_addstring("window-change");
3417 ssh2_pkt_addbool(0);
3418 ssh2_pkt_adduint32(cols
);
3419 ssh2_pkt_adduint32(rows
);
3420 ssh2_pkt_adduint32(0);
3421 ssh2_pkt_adduint32(0);
3430 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3431 * can send an EOF and collect resulting output (e.g. `plink
3434 static void ssh_special (Telnet_Special code
) {
3435 if (code
== TS_EOF
) {
3436 if (ssh_state
!= SSH_STATE_SESSION
) {
3438 * Buffer the EOF in case we are pre-SESSION, so we can
3439 * send it as soon as we reach SESSION.
3445 if (ssh_version
== 1) {
3446 send_packet(SSH1_CMSG_EOF
, PKT_END
);
3448 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
3449 ssh2_pkt_adduint32(mainchan
->remoteid
);
3452 logevent("Sent EOF message");
3453 } else if (code
== TS_PING
) {
3454 if (ssh_state
== SSH_STATE_CLOSED
|| ssh_state
== SSH_STATE_PREPACKET
)
3456 if (ssh_version
== 1) {
3457 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
3459 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3460 ssh2_pkt_addstring_start();
3468 static Socket
ssh_socket(void) { return s
; }
3470 static int ssh_sendok(void) { return ssh_send_ok
; }
3472 static int ssh_ldisc(int option
) {
3473 if (option
== LD_ECHO
) return ssh_echoing
;
3474 if (option
== LD_EDIT
) return ssh_editing
;
3478 Backend ssh_backend
= {