18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 fprintf(stderr, "%s\n", s); }
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
23 (s ? sk_close(s), s = NULL : 0), \
24 connection_fatal msg )
26 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
29 #define SSH1_CMSG_USER 4 /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
38 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
39 #define SSH1_SMSG_FAILURE 15 /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
43 #define SSH1_CMSG_EOF 19 /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
55 #define SSH1_MSG_IGNORE 32 /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
68 #define SSH1_AUTH_TIS 5 /* 0x5 */
69 #define SSH1_AUTH_CCARD 16 /* 0x10 */
71 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
72 #define SSH2_MSG_IGNORE 2 /* 0x2 */
73 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
74 #define SSH2_MSG_DEBUG 4 /* 0x4 */
75 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
76 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
77 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
78 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
79 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
80 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
81 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
82 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
83 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
84 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
85 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
86 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
87 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
88 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
89 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
90 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
91 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
92 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
93 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
94 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
95 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
96 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
97 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
98 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
99 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
100 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
101 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
102 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
103 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
104 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
106 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
107 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
108 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
109 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
110 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
111 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
112 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
113 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
114 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
115 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
116 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
118 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
119 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
120 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
121 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
123 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
126 * Various remote-bug flags.
128 #define BUG_CHOKES_ON_SSH1_IGNORE 1
129 #define BUG_SSH2_HMAC 2
131 #define GET_32BIT(cp) \
132 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
133 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
134 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
135 ((unsigned long)(unsigned char)(cp)[3]))
137 #define PUT_32BIT(cp, value) { \
138 (cp)[0] = (unsigned char)((value) >> 24); \
139 (cp)[1] = (unsigned char)((value) >> 16); \
140 (cp)[2] = (unsigned char)((value) >> 8); \
141 (cp)[3] = (unsigned char)(value); }
143 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
145 /* Coroutine mechanics for the sillier bits of the code */
146 #define crBegin1 static int crLine = 0;
147 #define crBegin2 switch(crLine) { case 0:;
148 #define crBegin crBegin1; crBegin2;
149 #define crFinish(z) } crLine = 0; return (z)
150 #define crFinishV } crLine = 0; return
151 #define crReturn(z) \
153 crLine=__LINE__; return (z); case __LINE__:;\
157 crLine=__LINE__; return; case __LINE__:;\
159 #define crStop(z) do{ crLine = 0; return (z); }while(0)
160 #define crStopV do{ crLine = 0; return; }while(0)
161 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
162 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
164 extern char *x11_init (Socket
*, char *, void *);
165 extern void x11_close (Socket
);
166 extern void x11_send (Socket
, char *, int);
167 extern void x11_invent_auth(char *, int, char *, int);
170 * Ciphers for SSH2. We miss out single-DES because it isn't
171 * supported; also 3DES and Blowfish are both done differently from
172 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
173 * endianness and different-sized keys.)
175 const static struct ssh2_ciphers
*ciphers
[] = {
181 const static struct ssh_kex
*kex_algs
[] = {
182 &ssh_diffiehellman_gex
,
183 &ssh_diffiehellman
};
185 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
187 static void nullmac_key(unsigned char *key
) { }
188 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
189 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
190 const static struct ssh_mac ssh_mac_none
= {
191 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
193 const static struct ssh_mac
*macs
[] = {
194 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
};
195 const static struct ssh_mac
*buggymacs
[] = {
196 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
};
198 static void ssh_comp_none_init(void) { }
199 static int ssh_comp_none_block(unsigned char *block
, int len
,
200 unsigned char **outblock
, int *outlen
) {
203 static int ssh_comp_none_disable(void) { return 0; }
204 const static struct ssh_compress ssh_comp_none
= {
206 ssh_comp_none_init
, ssh_comp_none_block
,
207 ssh_comp_none_init
, ssh_comp_none_block
,
208 ssh_comp_none_disable
210 extern const struct ssh_compress ssh_zlib
;
211 const static struct ssh_compress
*compressions
[] = {
212 &ssh_zlib
, &ssh_comp_none
};
214 enum { /* channel types */
221 * 2-3-4 tree storing channels.
224 unsigned remoteid
, localid
;
227 struct ssh2_data_channel
{
228 unsigned char *outbuffer
;
229 unsigned outbuflen
, outbufsize
;
230 unsigned remwindow
, remmaxpkt
;
233 struct ssh_agent_channel
{
234 unsigned char *message
;
235 unsigned char msglen
[4];
236 int lensofar
, totallen
;
238 struct ssh_x11_channel
{
253 static SHA_State exhash
, exhashbase
;
255 static Socket s
= NULL
;
257 static unsigned char session_key
[32];
258 static int ssh1_compressing
;
259 static int ssh_agentfwd_enabled
;
260 static int ssh_X11_fwd_enabled
;
261 static int ssh_remote_bugs
;
262 static const struct ssh_cipher
*cipher
= NULL
;
263 static const struct ssh2_cipher
*cscipher
= NULL
;
264 static const struct ssh2_cipher
*sccipher
= NULL
;
265 static const struct ssh_mac
*csmac
= NULL
;
266 static const struct ssh_mac
*scmac
= NULL
;
267 static const struct ssh_compress
*cscomp
= NULL
;
268 static const struct ssh_compress
*sccomp
= NULL
;
269 static const struct ssh_kex
*kex
= NULL
;
270 static const struct ssh_signkey
*hostkey
= NULL
;
271 static unsigned char ssh2_session_id
[20];
272 int (*ssh_get_line
)(const char *prompt
, char *str
, int maxlen
,
275 static char *savedhost
;
276 static int savedport
;
277 static int ssh_send_ok
;
278 static int ssh_echoing
, ssh_editing
;
280 static tree234
*ssh_channels
; /* indexed by local id */
281 static struct ssh_channel
*mainchan
; /* primary session channel */
285 SSH_STATE_BEFORE_SIZE
,
289 } ssh_state
= SSH_STATE_PREPACKET
;
291 static int size_needed
= FALSE
, eof_needed
= FALSE
;
293 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
294 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
295 static unsigned char *deferred_send_data
= NULL
;
296 static int deferred_len
= 0, deferred_size
= 0;
298 static int ssh_version
;
299 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
300 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
301 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
302 static void ssh_size(void);
303 static void ssh_special (Telnet_Special
);
304 static void ssh2_try_send(struct ssh_channel
*c
);
305 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
307 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
309 static struct rdpkt1_state_tag
{
310 long len
, pad
, biglen
, to_read
;
311 unsigned long realcrc
, gotcrc
;
317 static struct rdpkt2_state_tag
{
318 long len
, pad
, payload
, packetlen
, maclen
;
321 unsigned long incoming_sequence
;
324 static int ssh_channelcmp(void *av
, void *bv
) {
325 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
326 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
327 if (a
->localid
< b
->localid
) return -1;
328 if (a
->localid
> b
->localid
) return +1;
331 static int ssh_channelfind(void *av
, void *bv
) {
332 unsigned *a
= (unsigned *)av
;
333 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
334 if (*a
< b
->localid
) return -1;
335 if (*a
> b
->localid
) return +1;
339 static void c_write (char *buf
, int len
) {
340 if ((flags
& FLAG_STDERR
)) {
342 for (i
= 0; i
< len
; i
++)
344 fputc(buf
[i
], stderr
);
347 from_backend(1, buf
, len
);
350 static void c_write_untrusted(char *buf
, int len
) {
352 for (i
= 0; i
< len
; i
++) {
355 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
360 static void c_write_str (char *buf
) {
361 c_write(buf
, strlen(buf
));
365 * Collect incoming data in the incoming packet buffer.
366 * Decipher and verify the packet when it is completely read.
367 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
368 * Update the *data and *datalen variables.
369 * Return the additional nr of bytes needed, or 0 when
370 * a complete packet is available.
372 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
374 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
383 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
384 while ((*datalen
) == 0)
386 st
->len
= (st
->len
<< 8) + **data
;
387 (*data
)++, (*datalen
)--;
391 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
392 st
->len
= 0x300; /* big enough to carry to end */
396 st
->pad
= 8 - (st
->len
% 8);
397 st
->biglen
= st
->len
+ st
->pad
;
398 pktin
.length
= st
->len
- 5;
400 if (pktin
.maxlen
< st
->biglen
) {
401 pktin
.maxlen
= st
->biglen
;
402 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+APIEXTRA
) :
403 srealloc(pktin
.data
, st
->biglen
+APIEXTRA
));
405 fatalbox("Out of memory");
408 st
->to_read
= st
->biglen
;
410 while (st
->to_read
> 0) {
411 st
->chunk
= st
->to_read
;
412 while ((*datalen
) == 0)
413 crReturn(st
->to_read
);
414 if (st
->chunk
> (*datalen
))
415 st
->chunk
= (*datalen
);
416 memcpy(st
->p
, *data
, st
->chunk
);
418 *datalen
-= st
->chunk
;
420 st
->to_read
-= st
->chunk
;
424 cipher
->decrypt(pktin
.data
, st
->biglen
);
426 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
427 for (st
->i
= 0; st
->i
< st
->biglen
; st
->i
++)
428 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
432 st
->realcrc
= crc32(pktin
.data
, st
->biglen
-4);
433 st
->gotcrc
= GET_32BIT(pktin
.data
+st
->biglen
-4);
434 if (st
->gotcrc
!= st
->realcrc
) {
435 bombout(("Incorrect CRC received on packet"));
439 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
441 if (ssh1_compressing
) {
442 unsigned char *decompblk
;
446 debug(("Packet payload pre-decompression:\n"));
447 for (i
= -1; i
< pktin
.length
; i
++)
448 debug((" %02x", (unsigned char)pktin
.body
[i
]));
451 zlib_decompress_block(pktin
.body
-1, pktin
.length
+1,
452 &decompblk
, &decomplen
);
454 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
455 pktin
.maxlen
= st
->pad
+ decomplen
;
456 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
);
457 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
459 fatalbox("Out of memory");
462 memcpy(pktin
.body
-1, decompblk
, decomplen
);
464 pktin
.length
= decomplen
-1;
466 debug(("Packet payload post-decompression:\n"));
467 for (i
= -1; i
< pktin
.length
; i
++)
468 debug((" %02x", (unsigned char)pktin
.body
[i
]));
473 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
474 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
475 pktin
.type
== SSH1_MSG_DEBUG
||
476 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
477 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
478 long strlen
= GET_32BIT(pktin
.body
);
479 if (strlen
+ 4 != pktin
.length
) {
480 bombout(("Received data packet with bogus string length"));
485 pktin
.type
= pktin
.body
[-1];
487 if (pktin
.type
== SSH1_MSG_DEBUG
) {
488 /* log debug message */
490 int strlen
= GET_32BIT(pktin
.body
);
491 strcpy(buf
, "Remote: ");
492 if (strlen
> 70) strlen
= 70;
493 memcpy(buf
+8, pktin
.body
+4, strlen
);
494 buf
[8+strlen
] = '\0';
497 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
505 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
507 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
515 st
->cipherblk
= sccipher
->blksize
;
518 if (st
->cipherblk
< 8)
521 if (pktin
.maxlen
< st
->cipherblk
) {
522 pktin
.maxlen
= st
->cipherblk
;
523 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->cipherblk
+APIEXTRA
) :
524 srealloc(pktin
.data
, st
->cipherblk
+APIEXTRA
));
526 fatalbox("Out of memory");
530 * Acquire and decrypt the first block of the packet. This will
531 * contain the length and padding details.
533 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
534 while ((*datalen
) == 0)
535 crReturn(st
->cipherblk
-st
->i
);
536 pktin
.data
[st
->i
] = *(*data
)++;
540 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
545 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
548 * Now get the length and padding figures.
550 st
->len
= GET_32BIT(pktin
.data
);
551 st
->pad
= pktin
.data
[4];
554 * This enables us to deduce the payload length.
556 st
->payload
= st
->len
- st
->pad
- 1;
558 pktin
.length
= st
->payload
+ 5;
561 * So now we can work out the total packet length.
563 st
->packetlen
= st
->len
+ 4;
564 st
->maclen
= scmac ? scmac
->len
: 0;
567 * Adjust memory allocation if packet is too big.
569 if (pktin
.maxlen
< st
->packetlen
+st
->maclen
) {
570 pktin
.maxlen
= st
->packetlen
+st
->maclen
;
571 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
572 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
574 fatalbox("Out of memory");
578 * Read and decrypt the remainder of the packet.
580 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
; st
->i
++) {
581 while ((*datalen
) == 0)
582 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
583 pktin
.data
[st
->i
] = *(*data
)++;
586 /* Decrypt everything _except_ the MAC. */
588 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
589 st
->packetlen
- st
->cipherblk
);
592 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
593 for (st
->i
= 0; st
->i
< st
->packetlen
; st
->i
++)
594 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
601 if (scmac
&& !scmac
->verify(pktin
.data
, st
->len
+4, st
->incoming_sequence
)) {
602 bombout(("Incorrect MAC received on packet"));
605 st
->incoming_sequence
++; /* whether or not we MACed */
608 * Decompress packet payload.
611 unsigned char *newpayload
;
613 if (sccomp
&& sccomp
->decompress(pktin
.data
+5, pktin
.length
-5,
614 &newpayload
, &newlen
)) {
615 if (pktin
.maxlen
< newlen
+5) {
616 pktin
.maxlen
= newlen
+5;
617 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
618 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
620 fatalbox("Out of memory");
622 pktin
.length
= 5 + newlen
;
623 memcpy(pktin
.data
+5, newpayload
, newlen
);
625 debug(("Post-decompression payload:\r\n"));
626 for (st
->i
= 0; st
->i
< newlen
; st
->i
++)
627 debug((" %02x", (unsigned char)pktin
.data
[5+st
->i
]));
636 pktin
.type
= pktin
.data
[5];
638 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
639 goto next_packet
; /* FIXME: print DEBUG message */
644 static void ssh1_pktout_size(int len
) {
647 len
+= 5; /* type and CRC */
651 pktout
.length
= len
-5;
652 if (pktout
.maxlen
< biglen
) {
653 pktout
.maxlen
= biglen
;
655 /* Allocate enough buffer space for extra block
656 * for MS CryptEncrypt() */
657 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+12) :
658 srealloc(pktout
.data
, biglen
+12));
660 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+4) :
661 srealloc(pktout
.data
, biglen
+4));
664 fatalbox("Out of memory");
666 pktout
.body
= pktout
.data
+4+pad
+1;
669 static void s_wrpkt_start(int type
, int len
) {
670 ssh1_pktout_size(len
);
674 static int s_wrpkt_prepare(void) {
675 int pad
, len
, biglen
, i
;
678 pktout
.body
[-1] = pktout
.type
;
681 debug(("Packet payload pre-compression:\n"));
682 for (i
= -1; i
< pktout
.length
; i
++)
683 debug((" %02x", (unsigned char)pktout
.body
[i
]));
687 if (ssh1_compressing
) {
688 unsigned char *compblk
;
690 zlib_compress_block(pktout
.body
-1, pktout
.length
+1,
692 ssh1_pktout_size(complen
-1);
693 memcpy(pktout
.body
-1, compblk
, complen
);
696 debug(("Packet payload post-compression:\n"));
697 for (i
= -1; i
< pktout
.length
; i
++)
698 debug((" %02x", (unsigned char)pktout
.body
[i
]));
703 len
= pktout
.length
+ 5; /* type and CRC */
707 for (i
=0; i
<pad
; i
++)
708 pktout
.data
[i
+4] = random_byte();
709 crc
= crc32(pktout
.data
+4, biglen
-4);
710 PUT_32BIT(pktout
.data
+biglen
, crc
);
711 PUT_32BIT(pktout
.data
, len
);
714 debug(("Sending packet len=%d\r\n", biglen
+4));
715 for (i
= 0; i
< biglen
+4; i
++)
716 debug((" %02x", (unsigned char)pktout
.data
[i
]));
720 cipher
->encrypt(pktout
.data
+4, biglen
);
725 static void s_wrpkt(void) {
727 len
= s_wrpkt_prepare();
728 sk_write(s
, pktout
.data
, len
);
731 static void s_wrpkt_defer(void) {
733 len
= s_wrpkt_prepare();
734 if (deferred_len
+ len
> deferred_size
) {
735 deferred_size
= deferred_len
+ len
+ 128;
736 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
738 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
743 * Construct a packet with the specified contents.
745 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
747 unsigned char *p
, *argp
, argchar
;
748 unsigned long argint
;
749 int pktlen
, argtype
, arglen
;
753 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
756 (void) va_arg(ap1
, int);
760 (void) va_arg(ap1
, char);
764 (void) va_arg(ap1
, unsigned char *);
765 arglen
= va_arg(ap1
, int);
769 argp
= va_arg(ap1
, unsigned char *);
770 arglen
= strlen(argp
);
771 pktlen
+= 4 + arglen
;
774 bn
= va_arg(ap1
, Bignum
);
775 pktlen
+= ssh1_bignum_length(bn
);
782 s_wrpkt_start(pkttype
, pktlen
);
785 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
788 argint
= va_arg(ap2
, int);
789 PUT_32BIT(p
, argint
);
793 argchar
= va_arg(ap2
, unsigned char);
798 argp
= va_arg(ap2
, unsigned char *);
799 arglen
= va_arg(ap2
, int);
800 memcpy(p
, argp
, arglen
);
804 argp
= va_arg(ap2
, unsigned char *);
805 arglen
= strlen(argp
);
806 PUT_32BIT(p
, arglen
);
807 memcpy(p
+ 4, argp
, arglen
);
811 bn
= va_arg(ap2
, Bignum
);
812 p
+= ssh1_write_bignum(p
, bn
);
818 static void send_packet(int pkttype
, ...) {
820 va_start(ap1
, pkttype
);
821 va_start(ap2
, pkttype
);
822 construct_packet(pkttype
, ap1
, ap2
);
826 static void defer_packet(int pkttype
, ...) {
828 va_start(ap1
, pkttype
);
829 va_start(ap2
, pkttype
);
830 construct_packet(pkttype
, ap1
, ap2
);
834 static int ssh_versioncmp(char *a
, char *b
) {
836 unsigned long av
, bv
;
838 av
= strtoul(a
, &ae
, 10);
839 bv
= strtoul(b
, &be
, 10);
840 if (av
!= bv
) return (av
< bv ?
-1 : +1);
841 if (*ae
== '.') ae
++;
842 if (*be
== '.') be
++;
843 av
= strtoul(ae
, &ae
, 10);
844 bv
= strtoul(be
, &be
, 10);
845 if (av
!= bv
) return (av
< bv ?
-1 : +1);
851 * Utility routines for putting an SSH-protocol `string' and
852 * `uint32' into a SHA state.
855 static void sha_string(SHA_State
*s
, void *str
, int len
) {
856 unsigned char lenblk
[4];
857 PUT_32BIT(lenblk
, len
);
858 SHA_Bytes(s
, lenblk
, 4);
859 SHA_Bytes(s
, str
, len
);
862 static void sha_uint32(SHA_State
*s
, unsigned i
) {
863 unsigned char intblk
[4];
864 PUT_32BIT(intblk
, i
);
865 SHA_Bytes(s
, intblk
, 4);
869 * SSH2 packet construction functions.
871 static void ssh2_pkt_ensure(int length
) {
872 if (pktout
.maxlen
< length
) {
873 pktout
.maxlen
= length
+ 256;
874 pktout
.data
= (pktout
.data
== NULL ?
smalloc(pktout
.maxlen
+APIEXTRA
) :
875 srealloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
877 fatalbox("Out of memory");
880 static void ssh2_pkt_adddata(void *data
, int len
) {
881 pktout
.length
+= len
;
882 ssh2_pkt_ensure(pktout
.length
);
883 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
885 static void ssh2_pkt_addbyte(unsigned char byte
) {
886 ssh2_pkt_adddata(&byte
, 1);
888 static void ssh2_pkt_init(int pkt_type
) {
890 ssh2_pkt_addbyte((unsigned char)pkt_type
);
892 static void ssh2_pkt_addbool(unsigned char value
) {
893 ssh2_pkt_adddata(&value
, 1);
895 static void ssh2_pkt_adduint32(unsigned long value
) {
898 ssh2_pkt_adddata(x
, 4);
900 static void ssh2_pkt_addstring_start(void) {
901 ssh2_pkt_adduint32(0);
902 pktout
.savedpos
= pktout
.length
;
904 static void ssh2_pkt_addstring_str(char *data
) {
905 ssh2_pkt_adddata(data
, strlen(data
));
906 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
907 pktout
.length
- pktout
.savedpos
);
909 static void ssh2_pkt_addstring_data(char *data
, int len
) {
910 ssh2_pkt_adddata(data
, len
);
911 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
912 pktout
.length
- pktout
.savedpos
);
914 static void ssh2_pkt_addstring(char *data
) {
915 ssh2_pkt_addstring_start();
916 ssh2_pkt_addstring_str(data
);
918 static char *ssh2_mpint_fmt(Bignum b
, int *len
) {
920 int i
, n
= (ssh1_bignum_bitcount(b
)+7)/8;
923 fatalbox("out of memory");
925 for (i
= 1; i
<= n
; i
++)
926 p
[i
] = bignum_byte(b
, n
-i
);
928 while (i
<= n
&& p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
930 memmove(p
, p
+i
, n
+1-i
);
934 static void ssh2_pkt_addmp(Bignum b
) {
937 p
= ssh2_mpint_fmt(b
, &len
);
938 ssh2_pkt_addstring_start();
939 ssh2_pkt_addstring_data(p
, len
);
944 * Construct an SSH2 final-form packet: compress it, encrypt it,
945 * put the MAC on it. Final packet, ready to be sent, is stored in
946 * pktout.data. Total length is returned.
948 static int ssh2_pkt_construct(void) {
949 int cipherblk
, maclen
, padding
, i
;
950 static unsigned long outgoing_sequence
= 0;
953 * Compress packet payload.
956 debug(("Pre-compression payload:\r\n"));
957 for (i
= 5; i
< pktout
.length
; i
++)
958 debug((" %02x", (unsigned char)pktout
.data
[i
]));
962 unsigned char *newpayload
;
964 if (cscomp
&& cscomp
->compress(pktout
.data
+5, pktout
.length
-5,
965 &newpayload
, &newlen
)) {
967 ssh2_pkt_adddata(newpayload
, newlen
);
973 * Add padding. At least four bytes, and must also bring total
974 * length (minus MAC) up to a multiple of the block size.
976 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
977 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
979 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
980 maclen
= csmac ? csmac
->len
: 0;
981 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
982 pktout
.data
[4] = padding
;
983 for (i
= 0; i
< padding
; i
++)
984 pktout
.data
[pktout
.length
+ i
] = random_byte();
985 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
987 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
989 outgoing_sequence
++; /* whether or not we MACed */
992 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
993 for (i
= 0; i
< pktout
.length
+padding
; i
++)
994 debug((" %02x", (unsigned char)pktout
.data
[i
]));
999 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1001 /* Ready-to-send packet starts at pktout.data. We return length. */
1002 return pktout
.length
+ padding
+ maclen
;
1006 * Construct and send an SSH2 packet immediately.
1008 static void ssh2_pkt_send(void) {
1009 int len
= ssh2_pkt_construct();
1010 sk_write(s
, pktout
.data
, len
);
1014 * Construct an SSH2 packet and add it to a deferred data block.
1015 * Useful for sending multiple packets in a single sk_write() call,
1016 * to prevent a traffic-analysing listener from being able to work
1017 * out the length of any particular packet (such as the password
1020 * Note that because SSH2 sequence-numbers its packets, this can
1021 * NOT be used as an m4-style `defer' allowing packets to be
1022 * constructed in one order and sent in another.
1024 static void ssh2_pkt_defer(void) {
1025 int len
= ssh2_pkt_construct();
1026 if (deferred_len
+ len
> deferred_size
) {
1027 deferred_size
= deferred_len
+ len
+ 128;
1028 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1030 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
1031 deferred_len
+= len
;
1035 * Send the whole deferred data block constructed by
1036 * ssh2_pkt_defer() or SSH1's defer_packet().
1038 static void ssh_pkt_defersend(void) {
1039 sk_write(s
, deferred_send_data
, deferred_len
);
1040 deferred_len
= deferred_size
= 0;
1041 sfree(deferred_send_data
);
1042 deferred_send_data
= NULL
;
1046 void bndebug(char *string
, Bignum b
) {
1049 p
= ssh2_mpint_fmt(b
, &len
);
1050 debug(("%s", string
));
1051 for (i
= 0; i
< len
; i
++)
1052 debug((" %02x", p
[i
]));
1058 static void sha_mpint(SHA_State
*s
, Bignum b
) {
1061 p
= ssh2_mpint_fmt(b
, &len
);
1062 sha_string(s
, p
, len
);
1067 * SSH2 packet decode functions.
1069 static unsigned long ssh2_pkt_getuint32(void) {
1070 unsigned long value
;
1071 if (pktin
.length
- pktin
.savedpos
< 4)
1072 return 0; /* arrgh, no way to decline (FIXME?) */
1073 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1074 pktin
.savedpos
+= 4;
1077 static int ssh2_pkt_getbool(void) {
1078 unsigned long value
;
1079 if (pktin
.length
- pktin
.savedpos
< 1)
1080 return 0; /* arrgh, no way to decline (FIXME?) */
1081 value
= pktin
.data
[pktin
.savedpos
] != 0;
1085 static void ssh2_pkt_getstring(char **p
, int *length
) {
1087 if (pktin
.length
- pktin
.savedpos
< 4)
1089 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1090 pktin
.savedpos
+= 4;
1091 if (pktin
.length
- pktin
.savedpos
< *length
)
1093 *p
= pktin
.data
+pktin
.savedpos
;
1094 pktin
.savedpos
+= *length
;
1096 static Bignum
ssh2_pkt_getmp(void) {
1101 ssh2_pkt_getstring(&p
, &length
);
1105 bombout(("internal error: Can't handle negative mpints"));
1108 b
= bignum_from_bytes(p
, length
);
1113 * Examine the remote side's version string and compare it against
1114 * a list of known buggy implementations.
1116 static void ssh_detect_bugs(char *vstring
) {
1117 char *imp
; /* pointer to implementation part */
1119 imp
+= strcspn(imp
, "-");
1120 imp
+= strcspn(imp
, "-");
1122 ssh_remote_bugs
= 0;
1124 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1125 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1126 !strcmp(imp
, "1.2.22")) {
1128 * These versions don't support SSH1_MSG_IGNORE, so we have
1129 * to use a different defence against password length
1132 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1133 logevent("We believe remote version has SSH1 ignore bug");
1136 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1137 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1138 !strncmp(imp
, "2.1 ", 4)) {
1140 * These versions have the HMAC bug.
1142 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1143 logevent("We believe remote version has SSH2 HMAC bug");
1147 static int do_ssh_init(unsigned char c
) {
1149 static char version
[10];
1150 static char vstring
[80];
1151 static char vlog
[sizeof(vstring
)+20];
1156 /* Search for the string "SSH-" in the input. */
1159 static const int transS
[] = { 1, 2, 2, 1 };
1160 static const int transH
[] = { 0, 0, 3, 0 };
1161 static const int transminus
[] = { 0, 0, 0, -1 };
1162 if (c
== 'S') i
= transS
[i
];
1163 else if (c
== 'H') i
= transH
[i
];
1164 else if (c
== '-') i
= transminus
[i
];
1168 crReturn(1); /* get another character */
1171 strcpy(vstring
, "SSH-");
1175 crReturn(1); /* get another char */
1176 if (vsp
< vstring
+sizeof(vstring
)-1)
1182 } else if (i
< sizeof(version
)-1)
1189 ssh_agentfwd_enabled
= FALSE
;
1190 rdpkt2_state
.incoming_sequence
= 0;
1193 sprintf(vlog
, "Server version: %s", vstring
);
1194 ssh_detect_bugs(vstring
);
1195 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1199 * Server version "1.99" means we can choose whether we use v1
1200 * or v2 protocol. Choice is based on cfg.sshprot.
1202 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1204 * This is a v2 server. Begin v2 protocol.
1207 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1208 SHA_Init(&exhashbase
);
1210 * Hash our version string and their version string.
1212 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1213 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1214 sprintf(vstring
, "%s\n", verstring
);
1215 sprintf(vlog
, "We claim version: %s", verstring
);
1217 logevent("Using SSH protocol version 2");
1218 sk_write(s
, vstring
, strlen(vstring
));
1219 ssh_protocol
= ssh2_protocol
;
1221 s_rdpkt
= ssh2_rdpkt
;
1224 * This is a v1 server. Begin v1 protocol.
1226 sprintf(vstring
, "SSH-%s-%s\n",
1227 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1229 sprintf(vlog
, "We claim version: %s", vstring
);
1230 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1232 logevent("Using SSH protocol version 1");
1233 sk_write(s
, vstring
, strlen(vstring
));
1234 ssh_protocol
= ssh1_protocol
;
1236 s_rdpkt
= ssh1_rdpkt
;
1238 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1243 static void ssh_gotdata(unsigned char *data
, int datalen
)
1248 * To begin with, feed the characters one by one to the
1249 * protocol initialisation / selection function do_ssh_init().
1250 * When that returns 0, we're done with the initial greeting
1251 * exchange and can move on to packet discipline.
1256 crReturnV
; /* more data please */
1257 ret
= do_ssh_init(*data
);
1264 * We emerge from that loop when the initial negotiation is
1265 * over and we have selected an s_rdpkt function. Now pass
1266 * everything to s_rdpkt, and then pass the resulting packets
1267 * to the proper protocol handler.
1272 while (datalen
> 0) {
1273 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
1274 ssh_protocol(NULL
, 0, 1);
1275 if (ssh_state
== SSH_STATE_CLOSED
) {
1285 static int ssh_closing (Plug plug
, char *error_msg
, int error_code
, int calling_back
) {
1286 ssh_state
= SSH_STATE_CLOSED
;
1290 /* A socket error has occurred. */
1291 connection_fatal (error_msg
);
1293 /* Otherwise, the remote side closed the connection normally. */
1298 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
) {
1299 ssh_gotdata (data
, len
);
1300 if (ssh_state
== SSH_STATE_CLOSED
) {
1311 * Connect to specified host and port.
1312 * Returns an error message, or NULL on success.
1313 * Also places the canonical host name into `realhost'.
1315 static char *connect_to_host(char *host
, int port
, char **realhost
)
1317 static struct plug_function_table fn_table
= {
1320 }, *fn_table_ptr
= &fn_table
;
1329 savedhost
= smalloc(1+strlen(host
));
1331 fatalbox("Out of memory");
1332 strcpy(savedhost
, host
);
1335 port
= 22; /* default ssh port */
1348 addr
= sk_namelookup(host
, realhost
);
1349 if ( (err
= sk_addr_error(addr
)) )
1359 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1360 if ( (err
= sk_socket_error(s
)) )
1364 sk_write(s
, "connect ", 8);
1365 sk_write(s
, FWhost
, strlen(FWhost
));
1368 sprintf(buf
, " %d\n", FWport
);
1369 sk_write(s
, buf
, strlen(buf
));
1377 * Handle the key exchange and user authentication phases.
1379 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1382 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1383 unsigned char cookie
[8];
1384 struct RSAKey servkey
, hostkey
;
1385 struct MD5Context md5c
;
1386 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1387 static int tried_publickey
;
1388 static unsigned char session_id
[16];
1390 static char username
[100];
1394 if (!ispkt
) crWaitUntil(ispkt
);
1396 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1397 bombout(("Public key packet not received"));
1401 logevent("Received public keys");
1403 memcpy(cookie
, pktin
.body
, 8);
1405 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1406 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1409 * Log the host key fingerprint.
1413 logevent("Host key fingerprint is:");
1414 strcpy(logmsg
, " ");
1415 hostkey
.comment
= NULL
;
1416 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1421 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1422 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1425 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1426 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1427 MD5Update(&md5c
, pktin
.body
, 8);
1428 MD5Final(session_id
, &md5c
);
1430 for (i
=0; i
<32; i
++)
1431 session_key
[i
] = random_byte();
1433 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1435 rsabuf
= smalloc(len
);
1437 fatalbox("Out of memory");
1440 * Verify the host key.
1444 * First format the key into a string.
1446 int len
= rsastr_len(&hostkey
);
1447 char fingerprint
[100];
1448 char *keystr
= smalloc(len
);
1450 fatalbox("Out of memory");
1451 rsastr_fmt(keystr
, &hostkey
);
1452 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1453 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1457 for (i
=0; i
<32; i
++) {
1458 rsabuf
[i
] = session_key
[i
];
1460 rsabuf
[i
] ^= session_id
[i
];
1463 if (hostkey
.bytes
> servkey
.bytes
) {
1464 rsaencrypt(rsabuf
, 32, &servkey
);
1465 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1467 rsaencrypt(rsabuf
, 32, &hostkey
);
1468 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1471 logevent("Encrypted session key");
1473 switch (cfg
.cipher
) {
1474 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
; break;
1475 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
; break;
1476 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
; break;
1478 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1479 cipher_type
= SSH_CIPHER_3DES
;
1482 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1483 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1484 cipher_type
= SSH_CIPHER_3DES
;
1486 switch (cipher_type
) {
1487 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1488 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1489 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1492 send_packet(SSH1_CMSG_SESSION_KEY
,
1493 PKT_CHAR
, cipher_type
,
1494 PKT_DATA
, cookie
, 8,
1495 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1496 PKT_DATA
, rsabuf
, len
,
1500 logevent("Trying to enable encryption...");
1504 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1505 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1507 cipher
->sesskey(session_key
);
1511 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1512 bombout(("Encryption not successfully enabled"));
1516 logevent("Successfully started encryption");
1522 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1524 if (!ssh_get_line("login as: ",
1525 username
, sizeof(username
), FALSE
)) {
1527 * get_line failed to get a username.
1530 logevent("No username provided. Abandoning session.");
1531 ssh_state
= SSH_STATE_CLOSED
;
1535 c_write_str("login as: ");
1538 crWaitUntil(!ispkt
);
1539 while (inlen
--) switch (c
= *in
++) {
1546 c_write_str("\b \b");
1552 c_write_str("\b \b");
1561 if (((c
>= ' ' && c
<= '~') ||
1562 ((unsigned char)c
>= 160)) && pos
< 40) {
1563 username
[pos
++] = c
;
1569 c_write_str("\r\n");
1570 username
[strcspn(username
, "\n\r")] = '\0';
1573 strncpy(username
, cfg
.username
, 99);
1574 username
[99] = '\0';
1577 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1579 char userlog
[22+sizeof(username
)];
1580 sprintf(userlog
, "Sent username \"%s\"", username
);
1582 if (flags
& FLAG_INTERACTIVE
&&
1583 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1584 strcat(userlog
, "\r\n");
1585 c_write_str(userlog
);
1592 tried_publickey
= 0;
1594 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1595 static char password
[100];
1596 static char prompt
[200];
1599 static int pwpkt_type
;
1601 * Show password prompt, having first obtained it via a TIS
1602 * or CryptoCard exchange if we're doing TIS or CryptoCard
1605 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1606 if (agent_exists()) {
1608 * Attempt RSA authentication using Pageant.
1610 static unsigned char request
[5], *response
, *p
;
1611 static int responselen
;
1612 static int i
, nkeys
;
1613 static int authed
= FALSE
;
1616 logevent("Pageant is running. Requesting keys.");
1618 /* Request the keys held by the agent. */
1619 PUT_32BIT(request
, 1);
1620 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1621 agent_query(request
, 5, &r
, &responselen
);
1622 response
= (unsigned char *)r
;
1623 if (response
&& responselen
>= 5 &&
1624 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
1626 nkeys
= GET_32BIT(p
); p
+= 4;
1627 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1629 for (i
= 0; i
< nkeys
; i
++) {
1630 static struct RSAKey key
;
1631 static Bignum challenge
;
1632 static char *commentp
;
1633 static int commentlen
;
1635 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1638 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1639 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1640 commentlen
= GET_32BIT(p
); p
+= 4;
1641 commentp
= p
; p
+= commentlen
;
1642 send_packet(SSH1_CMSG_AUTH_RSA
,
1643 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1645 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1646 logevent("Key refused");
1649 logevent("Received RSA challenge");
1650 ssh1_read_bignum(pktin
.body
, &challenge
);
1652 char *agentreq
, *q
, *ret
;
1654 len
= 1 + 4; /* message type, bit count */
1655 len
+= ssh1_bignum_length(key
.exponent
);
1656 len
+= ssh1_bignum_length(key
.modulus
);
1657 len
+= ssh1_bignum_length(challenge
);
1658 len
+= 16; /* session id */
1659 len
+= 4; /* response format */
1660 agentreq
= smalloc(4 + len
);
1661 PUT_32BIT(agentreq
, len
);
1663 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1664 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1666 q
+= ssh1_write_bignum(q
, key
.exponent
);
1667 q
+= ssh1_write_bignum(q
, key
.modulus
);
1668 q
+= ssh1_write_bignum(q
, challenge
);
1669 memcpy(q
, session_id
, 16); q
+= 16;
1670 PUT_32BIT(q
, 1); /* response format */
1671 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1674 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1675 logevent("Sending Pageant's response");
1676 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1677 PKT_DATA
, ret
+5, 16, PKT_END
);
1680 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1681 logevent("Pageant's response accepted");
1682 if (flags
& FLAG_VERBOSE
) {
1683 c_write_str("Authenticated using RSA key \"");
1684 c_write(commentp
, commentlen
);
1685 c_write_str("\" from agent\r\n");
1689 logevent("Pageant's response not accepted");
1691 logevent("Pageant failed to answer challenge");
1695 logevent("No reply received from Pageant");
1698 freebn(key
.exponent
);
1699 freebn(key
.modulus
);
1708 if (*cfg
.keyfile
&& !tried_publickey
)
1709 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1711 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1713 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1714 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1715 logevent("Requested TIS authentication");
1716 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1718 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1719 logevent("TIS authentication declined");
1720 if (flags
& FLAG_INTERACTIVE
)
1721 c_write_str("TIS authentication refused.\r\n");
1723 int challengelen
= ((pktin
.body
[0] << 24) |
1724 (pktin
.body
[1] << 16) |
1725 (pktin
.body
[2] << 8) |
1727 logevent("Received TIS challenge");
1728 if (challengelen
> sizeof(prompt
)-1)
1729 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1730 memcpy(prompt
, pktin
.body
+4, challengelen
);
1731 prompt
[challengelen
] = '\0';
1734 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1736 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1737 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1738 logevent("Requested CryptoCard authentication");
1739 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1741 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1742 logevent("CryptoCard authentication declined");
1743 c_write_str("CryptoCard authentication refused.\r\n");
1745 int challengelen
= ((pktin
.body
[0] << 24) |
1746 (pktin
.body
[1] << 16) |
1747 (pktin
.body
[2] << 8) |
1749 logevent("Received CryptoCard challenge");
1750 if (challengelen
> sizeof(prompt
)-1)
1751 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1752 memcpy(prompt
, pktin
.body
+4, challengelen
);
1753 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1754 sizeof(prompt
)-challengelen
);
1755 prompt
[sizeof(prompt
)-1] = '\0';
1758 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1759 sprintf(prompt
, "%.90s@%.90s's password: ",
1760 username
, savedhost
);
1762 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1763 char *comment
= NULL
;
1764 if (flags
& FLAG_VERBOSE
)
1765 c_write_str("Trying public key authentication.\r\n");
1766 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1767 if (flags
& FLAG_VERBOSE
)
1768 c_write_str("No passphrase required.\r\n");
1771 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1776 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
1778 * get_line failed to get a password (for example
1779 * because one was supplied on the command line
1780 * which has already failed to work). Terminate.
1782 logevent("No more passwords to try");
1783 ssh_state
= SSH_STATE_CLOSED
;
1787 c_write_str(prompt
);
1791 crWaitUntil(!ispkt
);
1792 while (inlen
--) switch (c
= *in
++) {
1809 if (((c
>= ' ' && c
<= '~') ||
1810 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1811 password
[pos
++] = c
;
1815 c_write_str("\r\n");
1819 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1821 * Try public key authentication with the specified
1824 static struct RSAKey pubkey
;
1825 static Bignum challenge
, response
;
1827 static unsigned char buffer
[32];
1829 tried_publickey
= 1;
1830 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1832 c_write_str("Couldn't load public key from ");
1833 c_write_str(cfg
.keyfile
);
1834 c_write_str(".\r\n");
1835 continue; /* go and try password */
1838 c_write_str("Wrong passphrase.\r\n");
1839 tried_publickey
= 0;
1840 continue; /* try again */
1844 * Send a public key attempt.
1846 send_packet(SSH1_CMSG_AUTH_RSA
,
1847 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1850 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1851 c_write_str("Server refused our public key.\r\n");
1852 continue; /* go and try password */
1854 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1855 bombout(("Bizarre response to offer of public key"));
1858 ssh1_read_bignum(pktin
.body
, &challenge
);
1859 response
= rsadecrypt(challenge
, &pubkey
);
1860 freebn(pubkey
.private_exponent
); /* burn the evidence */
1862 for (i
= 0; i
< 32; i
++) {
1863 buffer
[i
] = bignum_byte(response
, 31-i
);
1867 MD5Update(&md5c
, buffer
, 32);
1868 MD5Update(&md5c
, session_id
, 16);
1869 MD5Final(buffer
, &md5c
);
1871 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1872 PKT_DATA
, buffer
, 16, PKT_END
);
1875 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1876 if (flags
& FLAG_VERBOSE
)
1877 c_write_str("Failed to authenticate with our public key.\r\n");
1878 continue; /* go and try password */
1879 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1880 bombout(("Bizarre response to RSA authentication response"));
1884 break; /* we're through! */
1886 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1888 * Defence against traffic analysis: we send a
1889 * whole bunch of packets containing strings of
1890 * different lengths. One of these strings is the
1891 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1892 * The others are all random data in
1893 * SSH1_MSG_IGNORE packets. This way a passive
1894 * listener can't tell which is the password, and
1895 * hence can't deduce the password length.
1897 * Anybody with a password length greater than 16
1898 * bytes is going to have enough entropy in their
1899 * password that a listener won't find it _that_
1900 * much help to know how long it is. So what we'll
1903 * - if password length < 16, we send 15 packets
1904 * containing string lengths 1 through 15
1906 * - otherwise, we let N be the nearest multiple
1907 * of 8 below the password length, and send 8
1908 * packets containing string lengths N through
1909 * N+7. This won't obscure the order of
1910 * magnitude of the password length, but it will
1911 * introduce a bit of extra uncertainty.
1913 * A few servers (the old 1.2.18 through 1.2.22)
1914 * can't deal with SSH1_MSG_IGNORE. For these
1915 * servers, we need an alternative defence. We make
1916 * use of the fact that the password is interpreted
1917 * as a C string: so we can append a NUL, then some
1920 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
1925 len
= strlen(password
);
1926 if (len
< sizeof(string
)) {
1928 strcpy(string
, password
);
1929 len
++; /* cover the zero byte */
1930 while (len
< sizeof(string
)) {
1931 string
[len
++] = (char)random_byte();
1936 send_packet(pwpkt_type
, PKT_INT
, len
,
1937 PKT_DATA
, s
, len
, PKT_END
);
1939 int bottom
, top
, pwlen
, i
;
1942 pwlen
= strlen(password
);
1944 bottom
= 0; /* zero length passwords are OK! :-) */
1947 bottom
= pwlen
&~ 7;
1951 assert(pwlen
>= bottom
&& pwlen
<= top
);
1953 randomstr
= smalloc(top
+1);
1955 for (i
= bottom
; i
<= top
; i
++) {
1957 defer_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1959 for (j
= 0; j
< i
; j
++) {
1961 randomstr
[j
] = random_byte();
1962 } while (randomstr
[j
] == '\0');
1964 randomstr
[i
] = '\0';
1965 defer_packet(SSH1_MSG_IGNORE
,
1966 PKT_STR
, randomstr
, PKT_END
);
1969 ssh_pkt_defersend();
1972 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1975 logevent("Sent password");
1976 memset(password
, 0, strlen(password
));
1978 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1979 if (flags
& FLAG_VERBOSE
)
1980 c_write_str("Access denied\r\n");
1981 logevent("Authentication refused");
1982 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1983 logevent("Received disconnect request");
1984 ssh_state
= SSH_STATE_CLOSED
;
1986 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1987 bombout(("Strange packet received, type %d", pktin
.type
));
1992 logevent("Authentication successful");
1997 void sshfwd_close(struct ssh_channel
*c
) {
1998 if (c
&& !c
->closes
) {
1999 if (ssh_version
== 1) {
2000 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
, PKT_END
);
2002 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2003 ssh2_pkt_adduint32(c
->remoteid
);
2007 if (c
->type
== CHAN_X11
) {
2009 logevent("X11 connection terminated");
2014 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
) {
2015 if (ssh_version
== 1) {
2016 send_packet(SSH1_MSG_CHANNEL_DATA
,
2017 PKT_INT
, c
->remoteid
,
2022 ssh2_add_channel_data(c
, buf
, len
);
2027 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
2032 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2035 if (ssh_state
== SSH_STATE_CLOSED
)
2038 if (cfg
.agentfwd
&& agent_exists()) {
2039 logevent("Requesting agent forwarding");
2040 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2041 do { crReturnV
; } while (!ispkt
);
2042 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2043 bombout(("Protocol confusion"));
2045 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2046 logevent("Agent forwarding refused");
2048 logevent("Agent forwarding enabled");
2049 ssh_agentfwd_enabled
= TRUE
;
2053 if (cfg
.x11_forward
) {
2054 char proto
[20], data
[64];
2055 logevent("Requesting X11 forwarding");
2056 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2057 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2058 PKT_STR
, proto
, PKT_STR
, data
,
2061 do { crReturnV
; } while (!ispkt
);
2062 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2063 bombout(("Protocol confusion"));
2065 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2066 logevent("X11 forwarding refused");
2068 logevent("X11 forwarding enabled");
2069 ssh_X11_fwd_enabled
= TRUE
;
2074 send_packet(SSH1_CMSG_REQUEST_PTY
,
2075 PKT_STR
, cfg
.termtype
,
2076 PKT_INT
, rows
, PKT_INT
, cols
,
2077 PKT_INT
, 0, PKT_INT
, 0,
2080 ssh_state
= SSH_STATE_INTERMED
;
2081 do { crReturnV
; } while (!ispkt
);
2082 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2083 bombout(("Protocol confusion"));
2085 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2086 c_write_str("Server refused to allocate pty\r\n");
2087 ssh_editing
= ssh_echoing
= 1;
2089 logevent("Allocated pty");
2091 ssh_editing
= ssh_echoing
= 1;
2094 if (cfg
.compression
) {
2095 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2096 do { crReturnV
; } while (!ispkt
);
2097 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2098 bombout(("Protocol confusion"));
2100 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2101 c_write_str("Server refused to compress\r\n");
2103 logevent("Started compression");
2104 ssh1_compressing
= TRUE
;
2105 zlib_compress_init();
2106 zlib_decompress_init();
2109 if (*cfg
.remote_cmd
)
2110 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
2112 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2113 logevent("Started session");
2115 ssh_state
= SSH_STATE_SESSION
;
2119 ssh_special(TS_EOF
);
2121 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2123 ssh_channels
= newtree234(ssh_channelcmp
);
2127 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2128 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2129 long len
= GET_32BIT(pktin
.body
);
2130 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2132 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2133 ssh_state
= SSH_STATE_CLOSED
;
2134 logevent("Received disconnect request");
2136 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2137 /* Remote side is trying to open a channel to talk to our
2138 * X-Server. Give them back a local channel number. */
2140 struct ssh_channel
*c
, *d
;
2143 logevent("Received X11 connect request");
2144 /* Refuse if X11 forwarding is disabled. */
2145 if (!ssh_X11_fwd_enabled
) {
2146 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2147 PKT_INT
, GET_32BIT(pktin
.body
),
2149 logevent("Rejected X11 connect request");
2151 c
= smalloc(sizeof(struct ssh_channel
));
2153 if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2154 logevent("opening X11 forward connection failed");
2156 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2157 PKT_INT
, GET_32BIT(pktin
.body
),
2160 logevent("opening X11 forward connection succeeded");
2161 for (i
=1, d
= first234(ssh_channels
, &e
); d
; d
= next234(&e
)) {
2163 break; /* found a free number */
2166 c
->remoteid
= GET_32BIT(pktin
.body
);
2169 c
->type
= CHAN_X11
; /* identify channel type */
2170 add234(ssh_channels
, c
);
2171 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2172 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2174 logevent("Opened X11 forward channel");
2177 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2178 /* Remote side is trying to open a channel to talk to our
2179 * agent. Give them back a local channel number. */
2181 struct ssh_channel
*c
;
2184 /* Refuse if agent forwarding is disabled. */
2185 if (!ssh_agentfwd_enabled
) {
2186 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2187 PKT_INT
, GET_32BIT(pktin
.body
),
2191 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
2193 break; /* found a free number */
2196 c
= smalloc(sizeof(struct ssh_channel
));
2197 c
->remoteid
= GET_32BIT(pktin
.body
);
2200 c
->type
= CHAN_AGENT
; /* identify channel type */
2201 c
->u
.a
.lensofar
= 0;
2202 add234(ssh_channels
, c
);
2203 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2204 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2207 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2208 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2209 /* Remote side closes a channel. */
2210 unsigned i
= GET_32BIT(pktin
.body
);
2211 struct ssh_channel
*c
;
2212 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2215 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2216 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
2217 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2218 logevent("X11 connection closed");
2219 assert(c
->u
.x11
.s
!= NULL
);
2220 x11_close(c
->u
.x11
.s
);
2223 c
->closes
|= closetype
;
2224 if (c
->closes
== 3) {
2225 del234(ssh_channels
, c
);
2229 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2230 /* Data sent down one of our channels. */
2231 int i
= GET_32BIT(pktin
.body
);
2232 int len
= GET_32BIT(pktin
.body
+4);
2233 unsigned char *p
= pktin
.body
+8;
2234 struct ssh_channel
*c
;
2235 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2239 x11_send(c
->u
.x11
.s
, p
, len
);
2242 /* Data for an agent message. Buffer it. */
2244 if (c
->u
.a
.lensofar
< 4) {
2245 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2246 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
2247 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2249 if (c
->u
.a
.lensofar
== 4) {
2250 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
2251 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2252 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2254 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2255 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
2256 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
2257 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2259 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2260 void *reply
, *sentreply
;
2262 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
2267 /* Fake SSH_AGENT_FAILURE. */
2268 sentreply
= "\0\0\0\1\5";
2271 send_packet(SSH1_MSG_CHANNEL_DATA
,
2272 PKT_INT
, c
->remoteid
,
2274 PKT_DATA
, sentreply
, replylen
,
2278 sfree(c
->u
.a
.message
);
2279 c
->u
.a
.lensofar
= 0;
2285 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2286 /* may be from EXEC_SHELL on some servers */
2287 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2288 /* may be from EXEC_SHELL on some servers
2289 * if no pty is available or in other odd cases. Ignore */
2290 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2291 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2293 bombout(("Strange packet received: type %d", pktin
.type
));
2298 int len
= min(inlen
, 512);
2299 send_packet(SSH1_CMSG_STDIN_DATA
,
2300 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2311 * Utility routine for decoding comma-separated strings in KEXINIT.
2313 static int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
2314 int needlen
= strlen(needle
);
2317 * Is it at the start of the string?
2319 if (haylen
>= needlen
&& /* haystack is long enough */
2320 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2321 (haylen
== needlen
|| haystack
[needlen
] == ',')
2322 /* either , or EOS follows */
2326 * If not, search for the next comma and resume after that.
2327 * If no comma found, terminate.
2329 while (haylen
> 0 && *haystack
!= ',')
2330 haylen
--, haystack
++;
2333 haylen
--, haystack
++; /* skip over comma itself */
2338 * SSH2 key creation method.
2340 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
, char *keyspace
) {
2342 /* First 20 bytes. */
2345 SHA_Bytes(&s
, H
, 20);
2346 SHA_Bytes(&s
, &chr
, 1);
2347 SHA_Bytes(&s
, sessid
, 20);
2348 SHA_Final(&s
, keyspace
);
2349 /* Next 20 bytes. */
2352 SHA_Bytes(&s
, H
, 20);
2353 SHA_Bytes(&s
, keyspace
, 20);
2354 SHA_Final(&s
, keyspace
+20);
2358 * Handle the SSH2 transport layer.
2360 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2362 static int i
, j
, len
, nbits
, pbits
;
2364 static Bignum p
, g
, e
, f
, K
;
2365 static int kex_init_value
, kex_reply_value
;
2366 static const struct ssh_mac
**maclist
;
2368 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2369 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2370 static const struct ssh_mac
*csmac_tobe
= NULL
;
2371 static const struct ssh_mac
*scmac_tobe
= NULL
;
2372 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2373 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2374 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2375 static int hostkeylen
, siglen
;
2376 static void *hkey
; /* actual host key */
2377 static unsigned char exchange_hash
[20];
2378 static unsigned char keyspace
[40];
2379 static const struct ssh2_ciphers
*preferred_cipher
;
2380 static const struct ssh_compress
*preferred_comp
;
2381 static int first_kex
;
2388 * Set up the preferred cipher and compression.
2390 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2391 preferred_cipher
= &ssh2_blowfish
;
2392 } else if (cfg
.cipher
== CIPHER_DES
) {
2393 logevent("Single DES not supported in SSH2; using 3DES");
2394 preferred_cipher
= &ssh2_3des
;
2395 } else if (cfg
.cipher
== CIPHER_3DES
) {
2396 preferred_cipher
= &ssh2_3des
;
2397 } else if (cfg
.cipher
== CIPHER_AES
) {
2398 preferred_cipher
= &ssh2_aes
;
2400 /* Shouldn't happen, but we do want to initialise to _something_. */
2401 preferred_cipher
= &ssh2_3des
;
2403 if (cfg
.compression
)
2404 preferred_comp
= &ssh_zlib
;
2406 preferred_comp
= &ssh_comp_none
;
2409 * Be prepared to work around the buggy MAC problem.
2411 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2412 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2414 maclist
= macs
, nmacs
= lenof(macs
);
2418 * Construct and send our key exchange packet.
2420 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2421 for (i
= 0; i
< 16; i
++)
2422 ssh2_pkt_addbyte((unsigned char)random_byte());
2423 /* List key exchange algorithms. */
2424 ssh2_pkt_addstring_start();
2425 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2426 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2427 if (i
< lenof(kex_algs
)-1)
2428 ssh2_pkt_addstring_str(",");
2430 /* List server host key algorithms. */
2431 ssh2_pkt_addstring_start();
2432 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2433 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2434 if (i
< lenof(hostkey_algs
)-1)
2435 ssh2_pkt_addstring_str(",");
2437 /* List client->server encryption algorithms. */
2438 ssh2_pkt_addstring_start();
2439 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2440 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2441 for (j
= 0; j
< c
->nciphers
; j
++) {
2442 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2443 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2444 ssh2_pkt_addstring_str(",");
2447 /* List server->client encryption algorithms. */
2448 ssh2_pkt_addstring_start();
2449 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2450 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2451 for (j
= 0; j
< c
->nciphers
; j
++) {
2452 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2453 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2454 ssh2_pkt_addstring_str(",");
2457 /* List client->server MAC algorithms. */
2458 ssh2_pkt_addstring_start();
2459 for (i
= 0; i
< nmacs
; i
++) {
2460 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2462 ssh2_pkt_addstring_str(",");
2464 /* List server->client MAC algorithms. */
2465 ssh2_pkt_addstring_start();
2466 for (i
= 0; i
< nmacs
; i
++) {
2467 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2469 ssh2_pkt_addstring_str(",");
2471 /* List client->server compression algorithms. */
2472 ssh2_pkt_addstring_start();
2473 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2474 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2475 ssh2_pkt_addstring_str(c
->name
);
2476 if (i
< lenof(compressions
))
2477 ssh2_pkt_addstring_str(",");
2479 /* List server->client compression algorithms. */
2480 ssh2_pkt_addstring_start();
2481 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2482 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2483 ssh2_pkt_addstring_str(c
->name
);
2484 if (i
< lenof(compressions
))
2485 ssh2_pkt_addstring_str(",");
2487 /* List client->server languages. Empty list. */
2488 ssh2_pkt_addstring_start();
2489 /* List server->client languages. Empty list. */
2490 ssh2_pkt_addstring_start();
2491 /* First KEX packet does _not_ follow, because we're not that brave. */
2492 ssh2_pkt_addbool(FALSE
);
2494 ssh2_pkt_adduint32(0);
2496 exhash
= exhashbase
;
2497 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
2501 if (!ispkt
) crWaitUntil(ispkt
);
2502 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
2505 * Now examine the other side's KEXINIT to see what we're up
2508 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2509 bombout(("expected key exchange packet from server"));
2512 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
2513 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
2514 pktin
.savedpos
+= 16; /* skip garbage cookie */
2515 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2516 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2517 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2522 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2523 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2524 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2525 hostkey
= hostkey_algs
[i
];
2529 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2530 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2531 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2532 for (j
= 0; j
< c
->nciphers
; j
++) {
2533 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2534 cscipher_tobe
= c
->list
[j
];
2541 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2542 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2543 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2544 for (j
= 0; j
< c
->nciphers
; j
++) {
2545 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2546 sccipher_tobe
= c
->list
[j
];
2553 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2554 for (i
= 0; i
< nmacs
; i
++) {
2555 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2556 csmac_tobe
= maclist
[i
];
2560 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2561 for (i
= 0; i
< nmacs
; i
++) {
2562 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2563 scmac_tobe
= maclist
[i
];
2567 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2568 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2569 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2570 if (in_commasep_string(c
->name
, str
, len
)) {
2575 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2576 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2577 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2578 if (in_commasep_string(c
->name
, str
, len
)) {
2585 * Work out the number of bits of key we will need from the key
2586 * exchange. We start with the maximum key length of either
2592 csbits
= cscipher_tobe
->keylen
;
2593 scbits
= sccipher_tobe
->keylen
;
2594 nbits
= (csbits
> scbits ? csbits
: scbits
);
2596 /* The keys only have 160-bit entropy, since they're based on
2597 * a SHA-1 hash. So cap the key size at 160 bits. */
2598 if (nbits
> 160) nbits
= 160;
2601 * If we're doing Diffie-Hellman group exchange, start by
2602 * requesting a group.
2604 if (kex
== &ssh_diffiehellman_gex
) {
2605 logevent("Doing Diffie-Hellman group exchange");
2607 * Work out how big a DH group we will need to allow that
2610 pbits
= 512 << ((nbits
-1) / 64);
2611 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2612 ssh2_pkt_adduint32(pbits
);
2616 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2617 bombout(("expected key exchange group packet from server"));
2620 p
= ssh2_pkt_getmp();
2621 g
= ssh2_pkt_getmp();
2622 dh_setup_group(p
, g
);
2623 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2624 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2627 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2628 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2631 logevent("Doing Diffie-Hellman key exchange");
2633 * Now generate and send e for Diffie-Hellman.
2635 e
= dh_create_e(nbits
*2);
2636 ssh2_pkt_init(kex_init_value
);
2641 if (pktin
.type
!= kex_reply_value
) {
2642 bombout(("expected key exchange reply packet from server"));
2645 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2646 f
= ssh2_pkt_getmp();
2647 ssh2_pkt_getstring(&sigdata
, &siglen
);
2651 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2652 if (kex
== &ssh_diffiehellman_gex
) {
2653 sha_uint32(&exhash
, pbits
);
2654 sha_mpint(&exhash
, p
);
2655 sha_mpint(&exhash
, g
);
2657 sha_mpint(&exhash
, e
);
2658 sha_mpint(&exhash
, f
);
2659 sha_mpint(&exhash
, K
);
2660 SHA_Final(&exhash
, exchange_hash
);
2665 debug(("Exchange hash is:\r\n"));
2666 for (i
= 0; i
< 20; i
++)
2667 debug((" %02x", exchange_hash
[i
]));
2671 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2672 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2673 bombout(("Server failed host key check"));
2678 * Expect SSH2_MSG_NEWKEYS from server.
2681 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2682 bombout(("expected new-keys packet from server"));
2687 * Authenticate remote host: verify host key. (We've already
2688 * checked the signature of the exchange hash.)
2690 keystr
= hostkey
->fmtkey(hkey
);
2691 fingerprint
= hostkey
->fingerprint(hkey
);
2692 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2693 keystr
, fingerprint
);
2694 if (first_kex
) { /* don't bother logging this in rekeys */
2695 logevent("Host key fingerprint is:");
2696 logevent(fingerprint
);
2700 hostkey
->freekey(hkey
);
2703 * Send SSH2_MSG_NEWKEYS.
2705 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2709 * Create and initialise session keys.
2711 cscipher
= cscipher_tobe
;
2712 sccipher
= sccipher_tobe
;
2715 cscomp
= cscomp_tobe
;
2716 sccomp
= sccomp_tobe
;
2717 cscomp
->compress_init();
2718 sccomp
->decompress_init();
2720 * Set IVs after keys. Here we use the exchange hash from the
2721 * _first_ key exchange.
2724 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
2725 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
2726 cscipher
->setcskey(keyspace
);
2727 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
2728 sccipher
->setsckey(keyspace
);
2729 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
2730 cscipher
->setcsiv(keyspace
);
2731 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
2732 sccipher
->setsciv(keyspace
);
2733 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
2734 csmac
->setcskey(keyspace
);
2735 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
2736 scmac
->setsckey(keyspace
);
2739 * If this is the first key exchange phase, we must pass the
2740 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2741 * wants to see it but because it will need time to initialise
2742 * itself before it sees an actual packet. In subsequent key
2743 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2744 * it would only confuse the layer above.
2752 * Now we're encrypting. Begin returning 1 to the protocol main
2753 * function so that other things can run on top of the
2754 * transport. If we ever see a KEXINIT, we must go back to the
2757 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
2760 logevent("Server initiated key re-exchange");
2761 goto begin_key_exchange
;
2767 * Add data to an SSH2 channel output buffer.
2769 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
) {
2770 if (c
->v2
.outbufsize
<
2771 c
->v2
.outbuflen
+ len
) {
2773 c
->v2
.outbuflen
+ len
+ 1024;
2774 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
,
2777 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
,
2779 c
->v2
.outbuflen
+= len
;
2783 * Attempt to send data on an SSH2 channel.
2785 static void ssh2_try_send(struct ssh_channel
*c
) {
2786 while (c
->v2
.remwindow
> 0 &&
2787 c
->v2
.outbuflen
> 0) {
2788 unsigned len
= c
->v2
.remwindow
;
2789 if (len
> c
->v2
.outbuflen
)
2790 len
= c
->v2
.outbuflen
;
2791 if (len
> c
->v2
.remmaxpkt
)
2792 len
= c
->v2
.remmaxpkt
;
2793 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2794 ssh2_pkt_adduint32(c
->remoteid
);
2795 ssh2_pkt_addstring_start();
2796 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
2798 c
->v2
.outbuflen
-= len
;
2799 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+len
,
2801 c
->v2
.remwindow
-= len
;
2806 * Handle the SSH2 userauth and connection layers.
2808 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2810 static unsigned long remote_winsize
;
2811 static unsigned long remote_maxpkt
;
2813 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
, AUTH_PASSWORD
2817 AUTH_TYPE_PUBLICKEY
,
2818 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
2819 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
2822 static int gotit
, need_pw
, can_pubkey
, can_passwd
;
2823 static int tried_pubkey_config
, tried_agent
;
2824 static int we_are_in
;
2825 static char username
[100];
2826 static char pwprompt
[200];
2827 static char password
[100];
2832 * Request userauth protocol, and await a response to it.
2834 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2835 ssh2_pkt_addstring("ssh-userauth");
2837 crWaitUntilV(ispkt
);
2838 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2839 bombout(("Server refused user authentication protocol"));
2844 * We repeat this whole loop, including the username prompt,
2845 * until we manage a successful authentication. If the user
2846 * types the wrong _password_, they are sent back to the
2847 * beginning to try another username. (If they specify a
2848 * username in the config, they are never asked, even if they
2849 * do give a wrong password.)
2851 * I think this best serves the needs of
2853 * - the people who have no configuration, no keys, and just
2854 * want to try repeated (username,password) pairs until they
2855 * type both correctly
2857 * - people who have keys and configuration but occasionally
2858 * need to fall back to passwords
2860 * - people with a key held in Pageant, who might not have
2861 * logged in to a particular machine before; so they want to
2862 * type a username, and then _either_ their key will be
2863 * accepted, _or_ they will type a password. If they mistype
2864 * the username they will want to be able to get back and
2875 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2877 if (!ssh_get_line("login as: ",
2878 username
, sizeof(username
), FALSE
)) {
2880 * get_line failed to get a username.
2883 logevent("No username provided. Abandoning session.");
2884 ssh_state
= SSH_STATE_CLOSED
;
2888 c_write_str("login as: ");
2891 crWaitUntilV(!ispkt
);
2892 while (inlen
--) switch (c
= *in
++) {
2899 c_write_str("\b \b");
2905 c_write_str("\b \b");
2914 if (((c
>= ' ' && c
<= '~') ||
2915 ((unsigned char)c
>= 160)) && pos
< 40) {
2916 username
[pos
++] = c
;
2923 c_write_str("\r\n");
2924 username
[strcspn(username
, "\n\r")] = '\0';
2927 strncpy(username
, cfg
.username
, 99);
2928 username
[99] = '\0';
2929 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2930 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2936 * Send an authentication request using method "none": (a)
2937 * just in case it succeeds, and (b) so that we know what
2938 * authentication methods we can usefully try next.
2940 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2941 ssh2_pkt_addstring(username
);
2942 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2943 ssh2_pkt_addstring("none"); /* method */
2945 type
= AUTH_TYPE_NONE
;
2949 tried_pubkey_config
= FALSE
;
2950 tried_agent
= FALSE
;
2954 * Wait for the result of the last authentication request.
2957 crWaitUntilV(ispkt
);
2958 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
2961 ssh2_pkt_getstring(&banner
, &size
);
2963 c_write_untrusted(banner
, size
);
2964 crWaitUntilV(ispkt
);
2966 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
2967 logevent("Access granted");
2972 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
2973 bombout(("Strange packet received during authentication: type %d",
2980 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2981 * we can look at the string in it and know what we can
2982 * helpfully try next.
2987 ssh2_pkt_getstring(&methods
, &methlen
);
2988 if (!ssh2_pkt_getbool()) {
2990 * We have received an unequivocal Access
2991 * Denied. This can translate to a variety of
2994 * - if we'd just tried "none" authentication,
2995 * it's not worth printing anything at all
2997 * - if we'd just tried a public key _offer_,
2998 * the message should be "Server refused our
2999 * key" (or no message at all if the key
3000 * came from Pageant)
3002 * - if we'd just tried anything else, the
3003 * message really should be "Access denied".
3005 * Additionally, if we'd just tried password
3006 * authentication, we should break out of this
3007 * whole loop so as to go back to the username
3010 if (type
== AUTH_TYPE_NONE
) {
3012 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3013 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3014 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3015 c_write_str("Server refused our key\r\n");
3016 logevent("Server refused public key");
3018 c_write_str("Access denied\r\n");
3019 logevent("Access denied");
3020 if (type
== AUTH_TYPE_PASSWORD
) {
3026 c_write_str("Further authentication required\r\n");
3027 logevent("Further authentication required");
3030 can_pubkey
= in_commasep_string("publickey", methods
, methlen
);
3031 can_passwd
= in_commasep_string("password", methods
, methlen
);
3036 if (!method
&& can_pubkey
&& agent_exists
&& !tried_agent
) {
3038 * Attempt public-key authentication using Pageant.
3040 static unsigned char request
[5], *response
, *p
;
3041 static int responselen
;
3042 static int i
, nkeys
;
3043 static int authed
= FALSE
;
3048 logevent("Pageant is running. Requesting keys.");
3050 /* Request the keys held by the agent. */
3051 PUT_32BIT(request
, 1);
3052 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3053 agent_query(request
, 5, &r
, &responselen
);
3054 response
= (unsigned char *)r
;
3055 if (response
&& responselen
>= 5 &&
3056 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3058 nkeys
= GET_32BIT(p
); p
+= 4;
3059 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3061 for (i
= 0; i
< nkeys
; i
++) {
3062 static char *pkblob
, *alg
, *commentp
;
3063 static int pklen
, alglen
, commentlen
;
3064 static int siglen
, retlen
, len
;
3065 static char *q
, *agentreq
, *ret
;
3067 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
3069 pklen
= GET_32BIT(p
); p
+= 4;
3070 pkblob
= p
; p
+= pklen
;
3071 alglen
= GET_32BIT(pkblob
);
3073 commentlen
= GET_32BIT(p
); p
+= 4;
3074 commentp
= p
; p
+= commentlen
;
3075 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3076 ssh2_pkt_addstring(username
);
3077 ssh2_pkt_addstring("ssh-connection");/* service requested */
3078 ssh2_pkt_addstring("publickey");/* method */
3079 ssh2_pkt_addbool(FALSE
); /* no signature included */
3080 ssh2_pkt_addstring_start();
3081 ssh2_pkt_addstring_data(alg
, alglen
);
3082 ssh2_pkt_addstring_start();
3083 ssh2_pkt_addstring_data(pkblob
, pklen
);
3086 crWaitUntilV(ispkt
);
3087 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3088 logevent("Key refused");
3092 c_write_str("Authenticating with public key \"");
3093 c_write(commentp
, commentlen
);
3094 c_write_str("\" from agent\r\n");
3097 * Server is willing to accept the key.
3098 * Construct a SIGN_REQUEST.
3100 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3101 ssh2_pkt_addstring(username
);
3102 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3103 ssh2_pkt_addstring("publickey"); /* method */
3104 ssh2_pkt_addbool(TRUE
);
3105 ssh2_pkt_addstring_start();
3106 ssh2_pkt_addstring_data(alg
, alglen
);
3107 ssh2_pkt_addstring_start();
3108 ssh2_pkt_addstring_data(pkblob
, pklen
);
3110 siglen
= pktout
.length
- 5 + 4 + 20;
3111 len
= 1; /* message type */
3112 len
+= 4 + pklen
; /* key blob */
3113 len
+= 4 + siglen
; /* data to sign */
3114 len
+= 4; /* flags */
3115 agentreq
= smalloc(4 + len
);
3116 PUT_32BIT(agentreq
, len
);
3118 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3119 PUT_32BIT(q
, pklen
); q
+= 4;
3120 memcpy(q
, pkblob
, pklen
); q
+= pklen
;
3121 PUT_32BIT(q
, siglen
); q
+= 4;
3122 /* Now the data to be signed... */
3123 PUT_32BIT(q
, 20); q
+= 4;
3124 memcpy(q
, ssh2_session_id
, 20); q
+= 20;
3125 memcpy(q
, pktout
.data
+5, pktout
.length
-5);
3126 q
+= pktout
.length
-5;
3127 /* And finally the (zero) flags word. */
3129 agent_query(agentreq
, len
+4, &ret
, &retlen
);
3132 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3133 logevent("Sending Pageant's response");
3134 ssh2_pkt_addstring_start();
3135 ssh2_pkt_addstring_data(ret
+9, GET_32BIT(ret
+5));
3140 logevent("Pageant failed to answer challenge");
3150 if (!method
&& can_pubkey
&& *cfg
.keyfile
&& !tried_pubkey_config
) {
3151 unsigned char *pub_blob
;
3152 char *algorithm
, *comment
;
3155 tried_pubkey_config
= TRUE
;
3158 * Try the public key supplied in the configuration.
3160 * First, offer the public blob to see if the server is
3161 * willing to accept it.
3163 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3166 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3167 ssh2_pkt_addstring(username
);
3168 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3169 ssh2_pkt_addstring("publickey");/* method */
3170 ssh2_pkt_addbool(FALSE
); /* no signature included */
3171 ssh2_pkt_addstring(algorithm
);
3172 ssh2_pkt_addstring_start();
3173 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3175 logevent("Offered public key"); /* FIXME */
3177 crWaitUntilV(ispkt
);
3178 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3180 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3181 continue; /* key refused; give up on it */
3184 logevent("Offer of public key accepted");
3186 * Actually attempt a serious authentication using
3189 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3190 sprintf(pwprompt
, "Passphrase for key \"%.100s\": ", comment
);
3195 c_write_str("Authenticating with public key \"");
3196 c_write_str(comment
);
3197 c_write_str("\"\r\n");
3198 method
= AUTH_PUBLICKEY_FILE
;
3202 if (!method
&& can_passwd
) {
3203 method
= AUTH_PASSWORD
;
3204 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
, savedhost
);
3210 if (!ssh_get_line(pwprompt
, password
,
3211 sizeof(password
), TRUE
)) {
3213 * get_line failed to get a password (for
3214 * example because one was supplied on the
3215 * command line which has already failed to
3218 logevent("No more passwords to try");
3219 ssh_state
= SSH_STATE_CLOSED
;
3226 c_write_str(pwprompt
);
3231 crWaitUntilV(!ispkt
);
3232 while (inlen
--) switch (c
= *in
++) {
3249 if (((c
>= ' ' && c
<= '~') ||
3250 ((unsigned char)c
>= 160)) && pos
< 40)
3251 password
[pos
++] = c
;
3255 c_write_str("\r\n");
3259 if (method
== AUTH_PUBLICKEY_FILE
) {
3261 * We have our passphrase. Now try the actual authentication.
3263 struct ssh2_userkey
*key
;
3265 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3266 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3267 if (key
== SSH2_WRONG_PASSPHRASE
) {
3268 c_write_str("Wrong passphrase\r\n");
3269 tried_pubkey_config
= FALSE
;
3271 c_write_str("Unable to load private key\r\n");
3272 tried_pubkey_config
= TRUE
;
3274 /* Send a spurious AUTH_NONE to return to the top. */
3275 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3276 ssh2_pkt_addstring(username
);
3277 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3278 ssh2_pkt_addstring("none"); /* method */
3280 type
= AUTH_TYPE_NONE
;
3282 unsigned char *blob
, *sigdata
;
3283 int blob_len
, sigdata_len
;
3286 * We have loaded the private key and the server
3287 * has announced that it's willing to accept it.
3288 * Hallelujah. Generate a signature and send it.
3290 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3291 ssh2_pkt_addstring(username
);
3292 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3293 ssh2_pkt_addstring("publickey"); /* method */
3294 ssh2_pkt_addbool(TRUE
);
3295 ssh2_pkt_addstring(key
->alg
->name
);
3296 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3297 ssh2_pkt_addstring_start();
3298 ssh2_pkt_addstring_data(blob
, blob_len
);
3302 * The data to be signed is:
3306 * followed by everything so far placed in the
3309 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3310 sigdata
= smalloc(sigdata_len
);
3311 PUT_32BIT(sigdata
, 20);
3312 memcpy(sigdata
+4, ssh2_session_id
, 20);
3313 memcpy(sigdata
+24, pktout
.data
+5, pktout
.length
-5);
3314 blob
= key
->alg
->sign(key
->data
, sigdata
, sigdata_len
, &blob_len
);
3315 ssh2_pkt_addstring_start();
3316 ssh2_pkt_addstring_data(blob
, blob_len
);
3321 type
= AUTH_TYPE_PUBLICKEY
;
3323 } else if (method
== AUTH_PASSWORD
) {
3325 * We send the password packet lumped tightly together with
3326 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3327 * string long enough to make the total length of the two
3328 * packets constant. This should ensure that a passive
3329 * listener doing traffic analyis can't work out the length
3332 * For this to work, we need an assumption about the
3333 * maximum length of the password packet. I think 256 is
3334 * pretty conservative. Anyone using a password longer than
3335 * that probably doesn't have much to worry about from
3336 * people who find out how long their password is!
3338 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3339 ssh2_pkt_addstring(username
);
3340 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3341 ssh2_pkt_addstring("password");
3342 ssh2_pkt_addbool(FALSE
);
3343 ssh2_pkt_addstring(password
);
3346 * We'll include a string that's an exact multiple of the
3347 * cipher block size. If the cipher is NULL for some
3348 * reason, we don't do this trick at all because we gain
3354 stringlen
= (256 - deferred_len
);
3355 stringlen
+= cscipher
->blksize
- 1;
3356 stringlen
-= (stringlen
% cscipher
->blksize
);
3359 * Temporarily disable actual compression,
3360 * so we can guarantee to get this string
3361 * exactly the length we want it. The
3362 * compression-disabling routine should
3363 * return an integer indicating how many
3364 * bytes we should adjust our string length
3367 stringlen
-= cscomp
->disable_compression();
3369 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3370 ssh2_pkt_addstring_start();
3371 for (i
= 0; i
< stringlen
; i
++) {
3372 char c
= (char)random_byte();
3373 ssh2_pkt_addstring_data(&c
, 1);
3377 ssh_pkt_defersend();
3378 logevent("Sent password");
3379 type
= AUTH_TYPE_PASSWORD
;
3381 c_write_str("No supported authentication methods left to try!\r\n");
3382 logevent("No supported authentications offered. Disconnecting");
3383 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3384 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3385 ssh2_pkt_addstring("No supported authentication methods available");
3386 ssh2_pkt_addstring("en"); /* language tag */
3388 ssh_state
= SSH_STATE_CLOSED
;
3392 } while (!we_are_in
);
3395 * Now we're authenticated for the connection protocol. The
3396 * connection protocol will automatically have started at this
3397 * point; there's no need to send SERVICE_REQUEST.
3401 * So now create a channel with a session in it.
3403 mainchan
= smalloc(sizeof(struct ssh_channel
));
3404 mainchan
->localid
= 100; /* as good as any */
3405 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3406 ssh2_pkt_addstring("session");
3407 ssh2_pkt_adduint32(mainchan
->localid
);
3408 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3409 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3411 crWaitUntilV(ispkt
);
3412 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3413 bombout(("Server refused to open a session"));
3415 /* FIXME: error data comes back in FAILURE packet */
3417 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3418 bombout(("Server's channel confirmation cited wrong channel"));
3421 mainchan
->remoteid
= ssh2_pkt_getuint32();
3422 mainchan
->type
= CHAN_MAINSESSION
;
3423 mainchan
->closes
= 0;
3424 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3425 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3426 mainchan
->v2
.outbuffer
= NULL
;
3427 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3428 ssh_channels
= newtree234(ssh_channelcmp
);
3429 add234(ssh_channels
, mainchan
);
3430 logevent("Opened channel for session");
3433 * Potentially enable X11 forwarding.
3435 if (cfg
.x11_forward
) {
3436 char proto
[20], data
[64];
3437 logevent("Requesting X11 forwarding");
3438 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3439 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3440 ssh2_pkt_adduint32(mainchan
->remoteid
);
3441 ssh2_pkt_addstring("x11-req");
3442 ssh2_pkt_addbool(1); /* want reply */
3443 ssh2_pkt_addbool(0); /* many connections */
3444 ssh2_pkt_addstring(proto
);
3445 ssh2_pkt_addstring(data
);
3446 ssh2_pkt_adduint32(0); /* screen number */
3450 crWaitUntilV(ispkt
);
3451 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3452 unsigned i
= ssh2_pkt_getuint32();
3453 struct ssh_channel
*c
;
3454 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3456 continue; /* nonexistent channel */
3457 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3459 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3461 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3462 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3463 bombout(("Server got confused by X11 forwarding request"));
3466 logevent("X11 forwarding refused");
3468 logevent("X11 forwarding enabled");
3469 ssh_X11_fwd_enabled
= TRUE
;
3474 * Potentially enable agent forwarding.
3476 if (cfg
.agentfwd
&& agent_exists()) {
3477 logevent("Requesting OpenSSH-style agent forwarding");
3478 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3479 ssh2_pkt_adduint32(mainchan
->remoteid
);
3480 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3481 ssh2_pkt_addbool(1); /* want reply */
3485 crWaitUntilV(ispkt
);
3486 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3487 unsigned i
= ssh2_pkt_getuint32();
3488 struct ssh_channel
*c
;
3489 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3491 continue; /* nonexistent channel */
3492 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3494 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3496 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3497 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3498 bombout(("Server got confused by agent forwarding request"));
3501 logevent("Agent forwarding refused");
3503 logevent("Agent forwarding enabled");
3504 ssh_agentfwd_enabled
= TRUE
;
3509 * Now allocate a pty for the session.
3512 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3513 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3514 ssh2_pkt_addstring("pty-req");
3515 ssh2_pkt_addbool(1); /* want reply */
3516 ssh2_pkt_addstring(cfg
.termtype
);
3517 ssh2_pkt_adduint32(cols
);
3518 ssh2_pkt_adduint32(rows
);
3519 ssh2_pkt_adduint32(0); /* pixel width */
3520 ssh2_pkt_adduint32(0); /* pixel height */
3521 ssh2_pkt_addstring_start();
3522 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3524 ssh_state
= SSH_STATE_INTERMED
;
3527 crWaitUntilV(ispkt
);
3528 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3529 unsigned i
= ssh2_pkt_getuint32();
3530 struct ssh_channel
*c
;
3531 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3533 continue; /* nonexistent channel */
3534 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3536 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3538 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3539 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3540 bombout(("Server got confused by pty request"));
3543 c_write_str("Server refused to allocate pty\r\n");
3544 ssh_editing
= ssh_echoing
= 1;
3546 logevent("Allocated pty");
3549 ssh_editing
= ssh_echoing
= 1;
3553 * Start a shell or a remote command.
3555 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3556 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3557 if (cfg
.ssh_subsys
) {
3558 ssh2_pkt_addstring("subsystem");
3559 ssh2_pkt_addbool(1); /* want reply */
3560 ssh2_pkt_addstring(cfg
.remote_cmd
);
3561 } else if (*cfg
.remote_cmd
) {
3562 ssh2_pkt_addstring("exec");
3563 ssh2_pkt_addbool(1); /* want reply */
3564 ssh2_pkt_addstring(cfg
.remote_cmd
);
3566 ssh2_pkt_addstring("shell");
3567 ssh2_pkt_addbool(1); /* want reply */
3571 crWaitUntilV(ispkt
);
3572 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3573 unsigned i
= ssh2_pkt_getuint32();
3574 struct ssh_channel
*c
;
3575 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3577 continue; /* nonexistent channel */
3578 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3580 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3581 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3582 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3583 bombout(("Server got confused by shell/command request"));
3586 bombout(("Server refused to start a shell/command"));
3589 logevent("Started a shell/command");
3592 ssh_state
= SSH_STATE_SESSION
;
3596 ssh_special(TS_EOF
);
3601 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3604 static int try_send
;
3608 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3609 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3612 unsigned i
= ssh2_pkt_getuint32();
3613 struct ssh_channel
*c
;
3614 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3616 continue; /* nonexistent channel */
3617 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3618 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3619 continue; /* extended but not stderr */
3620 ssh2_pkt_getstring(&data
, &length
);
3623 case CHAN_MAINSESSION
:
3624 from_backend(pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
,
3628 x11_send(c
->u
.x11
.s
, data
, length
);
3631 while (length
> 0) {
3632 if (c
->u
.a
.lensofar
< 4) {
3633 int l
= min(4 - c
->u
.a
.lensofar
, length
);
3634 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, data
, l
);
3635 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3637 if (c
->u
.a
.lensofar
== 4) {
3638 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
3639 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3640 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3642 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
3643 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3645 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, data
, l
);
3646 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3648 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3649 void *reply
, *sentreply
;
3651 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
3656 /* Fake SSH_AGENT_FAILURE. */
3657 sentreply
= "\0\0\0\1\5";
3660 ssh2_add_channel_data(c
, sentreply
, replylen
);
3664 sfree(c
->u
.a
.message
);
3665 c
->u
.a
.lensofar
= 0;
3671 * Enlarge the window again at the remote
3672 * side, just in case it ever runs down and
3673 * they fail to send us any more data.
3675 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3676 ssh2_pkt_adduint32(c
->remoteid
);
3677 ssh2_pkt_adduint32(length
);
3680 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
3681 ssh_state
= SSH_STATE_CLOSED
;
3682 logevent("Received disconnect message");
3684 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
3685 continue; /* exit status et al; ignore (FIXME?) */
3686 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
3687 unsigned i
= ssh2_pkt_getuint32();
3688 struct ssh_channel
*c
;
3690 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3692 continue; /* nonexistent channel */
3694 if (c
->type
== CHAN_X11
) {
3696 * Remote EOF on an X11 channel means we should
3697 * wrap up and close the channel ourselves.
3699 x11_close(c
->u
.x11
.s
);
3701 } else if (c
->type
== CHAN_AGENT
) {
3704 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
3705 unsigned i
= ssh2_pkt_getuint32();
3706 struct ssh_channel
*c
;
3709 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3711 continue; /* nonexistent channel */
3712 if (c
->closes
== 0) {
3713 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3714 ssh2_pkt_adduint32(c
->remoteid
);
3717 /* Do pre-close processing on the channel. */
3719 case CHAN_MAINSESSION
:
3720 break; /* nothing to see here, move along */
3726 del234(ssh_channels
, c
);
3727 sfree(c
->v2
.outbuffer
);
3731 * See if that was the last channel left open.
3733 c
= first234(ssh_channels
, &e
);
3735 logevent("All channels closed. Disconnecting");
3736 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3737 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3738 ssh2_pkt_addstring("All open channels closed");
3739 ssh2_pkt_addstring("en"); /* language tag */
3741 ssh_state
= SSH_STATE_CLOSED
;
3744 continue; /* remote sends close; ignore (FIXME) */
3745 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3746 unsigned i
= ssh2_pkt_getuint32();
3747 struct ssh_channel
*c
;
3748 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3750 continue; /* nonexistent channel */
3751 mainchan
->v2
.remwindow
+= ssh2_pkt_getuint32();
3753 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
3757 struct ssh_channel
*c
;
3758 ssh2_pkt_getstring(&type
, &typelen
);
3759 c
= smalloc(sizeof(struct ssh_channel
));
3761 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
3762 if (!ssh_X11_fwd_enabled
)
3763 error
= "X11 forwarding is not enabled";
3764 else if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3765 error
= "Unable to open an X11 connection";
3769 } else if (typelen
== 22 &&
3770 !memcmp(type
, "auth-agent@openssh.com", 3)) {
3771 if (!ssh_agentfwd_enabled
)
3772 error
= "Agent forwarding is not enabled";
3774 c
->type
= CHAN_AGENT
; /* identify channel type */
3775 c
->u
.a
.lensofar
= 0;
3778 error
= "Unsupported channel type requested";
3781 c
->remoteid
= ssh2_pkt_getuint32();
3783 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
3784 ssh2_pkt_adduint32(c
->remoteid
);
3785 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
3786 ssh2_pkt_addstring(error
);
3787 ssh2_pkt_addstring("en"); /* language tag */
3791 struct ssh_channel
*d
;
3795 for (i
=1, d
= first234(ssh_channels
, &e
); d
;
3798 break; /* found a free number */
3803 c
->v2
.remwindow
= ssh2_pkt_getuint32();
3804 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3805 c
->v2
.outbuffer
= NULL
;
3806 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
3807 add234(ssh_channels
, c
);
3808 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
3809 ssh2_pkt_adduint32(c
->remoteid
);
3810 ssh2_pkt_adduint32(c
->localid
);
3811 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3812 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3816 bombout(("Strange packet received: type %d", pktin
.type
));
3821 * We have spare data. Add it to the channel buffer.
3823 ssh2_add_channel_data(mainchan
, in
, inlen
);
3828 struct ssh_channel
*c
;
3830 * Try to send data on all channels if we can.
3832 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
))
3841 * Handle the top-level SSH2 protocol.
3843 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
3845 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
3847 do_ssh2_authconn(in
, inlen
, ispkt
);
3851 * Called to set up the connection.
3853 * Returns an error message, or NULL on success.
3855 static char *ssh_init (char *host
, int port
, char **realhost
) {
3859 if(crypto_startup() == 0)
3860 return "Microsoft high encryption pack not installed!";
3867 p
= connect_to_host(host
, port
, realhost
);
3875 * Called to send data down the Telnet connection.
3877 static void ssh_send (char *buf
, int len
) {
3878 if (s
== NULL
|| ssh_protocol
== NULL
)
3881 ssh_protocol(buf
, len
, 0);
3885 * Called to set the size of the window from SSH's POV.
3887 static void ssh_size(void) {
3888 switch (ssh_state
) {
3889 case SSH_STATE_BEFORE_SIZE
:
3890 case SSH_STATE_PREPACKET
:
3891 case SSH_STATE_CLOSED
:
3892 break; /* do nothing */
3893 case SSH_STATE_INTERMED
:
3894 size_needed
= TRUE
; /* buffer for later */
3896 case SSH_STATE_SESSION
:
3898 if (ssh_version
== 1) {
3899 send_packet(SSH1_CMSG_WINDOW_SIZE
,
3900 PKT_INT
, rows
, PKT_INT
, cols
,
3901 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
3903 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3904 ssh2_pkt_adduint32(mainchan
->remoteid
);
3905 ssh2_pkt_addstring("window-change");
3906 ssh2_pkt_addbool(0);
3907 ssh2_pkt_adduint32(cols
);
3908 ssh2_pkt_adduint32(rows
);
3909 ssh2_pkt_adduint32(0);
3910 ssh2_pkt_adduint32(0);
3919 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3920 * can send an EOF and collect resulting output (e.g. `plink
3923 static void ssh_special (Telnet_Special code
) {
3924 if (code
== TS_EOF
) {
3925 if (ssh_state
!= SSH_STATE_SESSION
) {
3927 * Buffer the EOF in case we are pre-SESSION, so we can
3928 * send it as soon as we reach SESSION.
3934 if (ssh_version
== 1) {
3935 send_packet(SSH1_CMSG_EOF
, PKT_END
);
3937 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
3938 ssh2_pkt_adduint32(mainchan
->remoteid
);
3941 logevent("Sent EOF message");
3942 } else if (code
== TS_PING
) {
3943 if (ssh_state
== SSH_STATE_CLOSED
|| ssh_state
== SSH_STATE_PREPACKET
)
3945 if (ssh_version
== 1) {
3946 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
3948 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3949 ssh2_pkt_addstring_start();
3957 static Socket
ssh_socket(void) { return s
; }
3959 static int ssh_sendok(void) { return ssh_send_ok
; }
3961 static int ssh_ldisc(int option
) {
3962 if (option
== LD_ECHO
) return ssh_echoing
;
3963 if (option
== LD_EDIT
) return ssh_editing
;
3967 Backend ssh_backend
= {