18 /* uncomment this for packet level debugging */
19 /* #define DUMP_PACKETS */
21 #define logevent(s) { logevent(s); \
22 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
23 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
25 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
26 (s ? sk_close(s), s = NULL : 0), \
27 connection_fatal msg )
29 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
30 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
31 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
32 #define SSH1_CMSG_USER 4 /* 0x4 */
33 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
34 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
35 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
36 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
37 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
38 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
39 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
40 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
41 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
42 #define SSH1_SMSG_FAILURE 15 /* 0xf */
43 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
44 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
45 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
46 #define SSH1_CMSG_EOF 19 /* 0x13 */
47 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
48 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
49 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
50 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
51 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
52 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
53 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
54 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
55 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
56 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
57 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
58 #define SSH1_MSG_IGNORE 32 /* 0x20 */
59 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
60 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
61 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
62 #define SSH1_MSG_DEBUG 36 /* 0x24 */
63 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
64 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
65 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
66 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
67 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
68 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
69 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
71 #define SSH1_AUTH_TIS 5 /* 0x5 */
72 #define SSH1_AUTH_CCARD 16 /* 0x10 */
74 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
75 /* Mask for protoflags we will echo back to server if seen */
76 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
78 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
79 #define SSH2_MSG_IGNORE 2 /* 0x2 */
80 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
81 #define SSH2_MSG_DEBUG 4 /* 0x4 */
82 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
83 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
84 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
85 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
86 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
87 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
88 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
89 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
91 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
92 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
93 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
94 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
95 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
96 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
97 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
98 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
100 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
101 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
102 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
103 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
104 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
105 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
106 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
107 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
108 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
109 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
110 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
111 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
112 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
113 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons
[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
163 #define GET_32BIT(cp) \
164 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
165 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
166 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
167 ((unsigned long)(unsigned char)(cp)[3]))
169 #define PUT_32BIT(cp, value) { \
170 (cp)[0] = (unsigned char)((value) >> 24); \
171 (cp)[1] = (unsigned char)((value) >> 16); \
172 (cp)[2] = (unsigned char)((value) >> 8); \
173 (cp)[3] = (unsigned char)(value); }
175 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
177 /* Coroutine mechanics for the sillier bits of the code */
178 #define crBegin1 static int crLine = 0;
179 #define crBegin2 switch(crLine) { case 0:;
180 #define crBegin crBegin1; crBegin2;
181 #define crFinish(z) } crLine = 0; return (z)
182 #define crFinishV } crLine = 0; return
183 #define crReturn(z) \
185 crLine=__LINE__; return (z); case __LINE__:;\
189 crLine=__LINE__; return; case __LINE__:;\
191 #define crStop(z) do{ crLine = 0; return (z); }while(0)
192 #define crStopV do{ crLine = 0; return; }while(0)
193 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
194 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
196 extern char *x11_init(Socket
*, char *, void *);
197 extern void x11_close(Socket
);
198 extern int x11_send(Socket
, char *, int);
199 extern void x11_invent_auth(char *, int, char *, int);
200 extern void x11_unthrottle(Socket s
);
201 extern void x11_override_throttle(Socket s
, int enable
);
203 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
204 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
205 extern void pfd_close(Socket s
);
206 extern int pfd_send(Socket s
, char *data
, int len
);
207 extern void pfd_confirm(Socket s
);
208 extern void pfd_unthrottle(Socket s
);
209 extern void pfd_override_throttle(Socket s
, int enable
);
212 * Buffer management constants. There are several of these for
213 * various different purposes:
215 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
216 * on a local data stream before we throttle the whole SSH
217 * connection (in SSH1 only). Throttling the whole connection is
218 * pretty drastic so we set this high in the hope it won't
221 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
222 * on the SSH connection itself before we defensively throttle
223 * _all_ local data streams. This is pretty drastic too (though
224 * thankfully unlikely in SSH2 since the window mechanism should
225 * ensure that the server never has any need to throttle its end
226 * of the connection), so we set this high as well.
228 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
232 #define SSH1_BUFFER_LIMIT 32768
233 #define SSH_MAX_BACKLOG 32768
234 #define OUR_V2_WINSIZE 16384
237 * Ciphers for SSH2. We miss out single-DES because it isn't
238 * supported; also 3DES and Blowfish are both done differently from
239 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
240 * endianness and different-sized keys.)
242 const static struct ssh2_ciphers
*ciphers
[] = {
248 const static struct ssh_kex
*kex_algs
[] = {
249 &ssh_diffiehellman_gex
,
253 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
255 static void nullmac_key(unsigned char *key
)
258 static void nullmac_generate(unsigned char *blk
, int len
,
262 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
266 const static struct ssh_mac ssh_mac_none
= {
267 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
269 const static struct ssh_mac
*macs
[] = {
270 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
272 const static struct ssh_mac
*buggymacs
[] = {
273 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
276 static void ssh_comp_none_init(void)
279 static int ssh_comp_none_block(unsigned char *block
, int len
,
280 unsigned char **outblock
, int *outlen
)
284 static int ssh_comp_none_disable(void)
288 const static struct ssh_compress ssh_comp_none
= {
290 ssh_comp_none_init
, ssh_comp_none_block
,
291 ssh_comp_none_init
, ssh_comp_none_block
,
292 ssh_comp_none_disable
294 extern const struct ssh_compress ssh_zlib
;
295 const static struct ssh_compress
*compressions
[] = {
296 &ssh_zlib
, &ssh_comp_none
299 enum { /* channel types */
304 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
308 * 2-3-4 tree storing channels.
311 unsigned remoteid
, localid
;
315 struct ssh1_data_channel
{
318 struct ssh2_data_channel
{
320 unsigned remwindow
, remmaxpkt
;
325 struct ssh_agent_channel
{
326 unsigned char *message
;
327 unsigned char msglen
[4];
328 int lensofar
, totallen
;
330 struct ssh_x11_channel
{
333 struct ssh_pfd_channel
{
340 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
341 * 2 use this structure in different ways, reflecting SSH 2's
342 * altogether saner approach to port forwarding.
344 * In SSH 1, you arrange a remote forwarding by sending the server
345 * the remote port number, and the local destination host:port.
346 * When a connection comes in, the server sends you back that
347 * host:port pair, and you connect to it. This is a ready-made
348 * security hole if you're not on the ball: a malicious server
349 * could send you back _any_ host:port pair, so if you trustingly
350 * connect to the address it gives you then you've just opened the
351 * entire inside of your corporate network just by connecting
352 * through it to a dodgy SSH server. Hence, we must store a list of
353 * host:port pairs we _are_ trying to forward to, and reject a
354 * connection request from the server if it's not in the list.
356 * In SSH 2, each side of the connection minds its own business and
357 * doesn't send unnecessary information to the other. You arrange a
358 * remote forwarding by sending the server just the remote port
359 * number. When a connection comes in, the server tells you which
360 * of its ports was connected to; and _you_ have to remember what
361 * local host:port pair went with that port number.
363 * Hence: in SSH 1 this structure stores host:port pairs we intend
364 * to allow connections to, and is indexed by those host:port
365 * pairs. In SSH 2 it stores a mapping from source port to
366 * destination host:port pair, and is indexed by source port.
368 struct ssh_rportfwd
{
369 unsigned sport
, dport
;
382 static SHA_State exhash
, exhashbase
;
384 static Socket s
= NULL
;
386 static unsigned char session_key
[32];
387 static int ssh1_compressing
;
388 static int ssh1_remote_protoflags
;
389 static int ssh1_local_protoflags
;
390 static int ssh_agentfwd_enabled
;
391 static int ssh_X11_fwd_enabled
;
392 static int ssh_remote_bugs
;
393 static const struct ssh_cipher
*cipher
= NULL
;
394 static const struct ssh2_cipher
*cscipher
= NULL
;
395 static const struct ssh2_cipher
*sccipher
= NULL
;
396 static const struct ssh_mac
*csmac
= NULL
;
397 static const struct ssh_mac
*scmac
= NULL
;
398 static const struct ssh_compress
*cscomp
= NULL
;
399 static const struct ssh_compress
*sccomp
= NULL
;
400 static const struct ssh_kex
*kex
= NULL
;
401 static const struct ssh_signkey
*hostkey
= NULL
;
402 static unsigned char ssh2_session_id
[20];
403 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
406 static char *savedhost
;
407 static int savedport
;
408 static int ssh_send_ok
;
409 static int ssh_echoing
, ssh_editing
;
411 static tree234
*ssh_channels
; /* indexed by local id */
412 static struct ssh_channel
*mainchan
; /* primary session channel */
414 static tree234
*ssh_rportfwds
;
418 SSH_STATE_BEFORE_SIZE
,
422 } ssh_state
= SSH_STATE_PREPACKET
;
424 static int size_needed
= FALSE
, eof_needed
= FALSE
;
426 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
427 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
428 static unsigned char *deferred_send_data
= NULL
;
429 static int deferred_len
= 0, deferred_size
= 0;
432 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
433 * that fails. This variable is the means by which scp.c can reach
434 * into the SSH code and find out which one it got.
436 int ssh_fallback_cmd
= 0;
438 static int ssh_version
;
439 static int ssh1_throttle_count
;
440 static int ssh_overall_bufsize
;
441 static int ssh_throttled_all
;
442 static int ssh1_stdout_throttling
;
443 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
444 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
445 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
446 static void ssh_size(void);
447 static void ssh_special(Telnet_Special
);
448 static int ssh2_try_send(struct ssh_channel
*c
);
449 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
451 static void ssh_throttle_all(int enable
, int bufsize
);
452 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
453 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
454 static int ssh_sendbuffer(void);
456 static struct rdpkt1_state_tag
{
457 long len
, pad
, biglen
, to_read
;
458 unsigned long realcrc
, gotcrc
;
464 static struct rdpkt2_state_tag
{
465 long len
, pad
, payload
, packetlen
, maclen
;
468 unsigned long incoming_sequence
;
471 static int ssh_channelcmp(void *av
, void *bv
)
473 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
474 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
475 if (a
->localid
< b
->localid
)
477 if (a
->localid
> b
->localid
)
481 static int ssh_channelfind(void *av
, void *bv
)
483 unsigned *a
= (unsigned *) av
;
484 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
492 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
494 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
495 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
497 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
498 return i
< 0 ?
-1 : +1;
499 if (a
->dport
> b
->dport
)
501 if (a
->dport
< b
->dport
)
506 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
508 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
509 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
511 if (a
->sport
> b
->sport
)
513 if (a
->sport
< b
->sport
)
518 static int alloc_channel_id(void)
520 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
521 unsigned low
, high
, mid
;
523 struct ssh_channel
*c
;
526 * First-fit allocation of channel numbers: always pick the
527 * lowest unused one. To do this, binary-search using the
528 * counted B-tree to find the largest channel ID which is in a
529 * contiguous sequence from the beginning. (Precisely
530 * everything in that sequence must have ID equal to its tree
531 * index plus CHANNEL_NUMBER_OFFSET.)
533 tsize
= count234(ssh_channels
);
537 while (high
- low
> 1) {
538 mid
= (high
+ low
) / 2;
539 c
= index234(ssh_channels
, mid
);
540 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
541 low
= mid
; /* this one is fine */
543 high
= mid
; /* this one is past it */
546 * Now low points to either -1, or the tree index of the
547 * largest ID in the initial sequence.
550 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
551 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
553 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
556 static void c_write(char *buf
, int len
)
558 if ((flags
& FLAG_STDERR
)) {
560 for (i
= 0; i
< len
; i
++)
562 fputc(buf
[i
], stderr
);
565 from_backend(1, buf
, len
);
568 static void c_write_untrusted(char *buf
, int len
)
571 for (i
= 0; i
< len
; i
++) {
574 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
579 static void c_write_str(char *buf
)
581 c_write(buf
, strlen(buf
));
585 * Collect incoming data in the incoming packet buffer.
586 * Decipher and verify the packet when it is completely read.
587 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
588 * Update the *data and *datalen variables.
589 * Return the additional nr of bytes needed, or 0 when
590 * a complete packet is available.
592 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
594 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
603 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
604 while ((*datalen
) == 0)
606 st
->len
= (st
->len
<< 8) + **data
;
607 (*data
)++, (*datalen
)--;
611 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
612 st
->len
= 0x300; /* big enough to carry to end */
616 st
->pad
= 8 - (st
->len
% 8);
617 st
->biglen
= st
->len
+ st
->pad
;
618 pktin
.length
= st
->len
- 5;
620 if (pktin
.maxlen
< st
->biglen
) {
621 pktin
.maxlen
= st
->biglen
;
622 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
623 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
625 fatalbox("Out of memory");
628 st
->to_read
= st
->biglen
;
630 while (st
->to_read
> 0) {
631 st
->chunk
= st
->to_read
;
632 while ((*datalen
) == 0)
633 crReturn(st
->to_read
);
634 if (st
->chunk
> (*datalen
))
635 st
->chunk
= (*datalen
);
636 memcpy(st
->p
, *data
, st
->chunk
);
638 *datalen
-= st
->chunk
;
640 st
->to_read
-= st
->chunk
;
644 cipher
->decrypt(pktin
.data
, st
->biglen
);
646 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
647 dmemdump(pktin
.data
, st
->biglen
);
650 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
651 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
652 if (st
->gotcrc
!= st
->realcrc
) {
653 bombout(("Incorrect CRC received on packet"));
657 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
659 if (ssh1_compressing
) {
660 unsigned char *decompblk
;
663 debug(("Packet payload pre-decompression:\n"));
664 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
666 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
667 &decompblk
, &decomplen
);
669 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
670 pktin
.maxlen
= st
->pad
+ decomplen
;
671 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
672 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
674 fatalbox("Out of memory");
677 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
679 pktin
.length
= decomplen
- 1;
681 debug(("Packet payload post-decompression:\n"));
682 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
686 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
687 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
688 pktin
.type
== SSH1_MSG_DEBUG
||
689 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
690 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
691 long strlen
= GET_32BIT(pktin
.body
);
692 if (strlen
+ 4 != pktin
.length
) {
693 bombout(("Received data packet with bogus string length"));
698 pktin
.type
= pktin
.body
[-1];
700 if (pktin
.type
== SSH1_MSG_DEBUG
) {
701 /* log debug message */
703 int strlen
= GET_32BIT(pktin
.body
);
704 strcpy(buf
, "Remote: ");
707 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
708 buf
[8 + strlen
] = '\0';
711 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
716 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
717 /* log reason code in disconnect message */
719 unsigned msglen
= GET_32BIT(pktin
.body
);
721 strcpy(buf
, "Remote sent disconnect: ");
722 nowlen
= strlen(buf
);
723 if (msglen
> sizeof(buf
) - nowlen
- 1)
724 msglen
= sizeof(buf
) - nowlen
- 1;
725 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
726 buf
[nowlen
+ msglen
] = '\0';
733 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
735 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
743 st
->cipherblk
= sccipher
->blksize
;
746 if (st
->cipherblk
< 8)
749 if (pktin
.maxlen
< st
->cipherblk
) {
750 pktin
.maxlen
= st
->cipherblk
;
753 NULL ?
smalloc(st
->cipherblk
+
754 APIEXTRA
) : srealloc(pktin
.data
,
758 fatalbox("Out of memory");
762 * Acquire and decrypt the first block of the packet. This will
763 * contain the length and padding details.
765 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
766 while ((*datalen
) == 0)
767 crReturn(st
->cipherblk
- st
->i
);
768 pktin
.data
[st
->i
] = *(*data
)++;
772 if (!memcmp(pktin
.data
, "Remo", 4)) { /* "Remo"te server has closed ... */
777 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
780 * Now get the length and padding figures.
782 st
->len
= GET_32BIT(pktin
.data
);
783 st
->pad
= pktin
.data
[4];
786 * This enables us to deduce the payload length.
788 st
->payload
= st
->len
- st
->pad
- 1;
790 pktin
.length
= st
->payload
+ 5;
793 * So now we can work out the total packet length.
795 st
->packetlen
= st
->len
+ 4;
796 st
->maclen
= scmac ? scmac
->len
: 0;
799 * Adjust memory allocation if packet is too big.
801 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
802 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
805 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
810 fatalbox("Out of memory");
814 * Read and decrypt the remainder of the packet.
816 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
818 while ((*datalen
) == 0)
819 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
820 pktin
.data
[st
->i
] = *(*data
)++;
823 /* Decrypt everything _except_ the MAC. */
825 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
826 st
->packetlen
- st
->cipherblk
);
829 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
830 dmemdump(pktin
.data
, st
->packetlen
);
837 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
838 st
->incoming_sequence
)) {
839 bombout(("Incorrect MAC received on packet"));
842 st
->incoming_sequence
++; /* whether or not we MACed */
845 * Decompress packet payload.
848 unsigned char *newpayload
;
850 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
851 &newpayload
, &newlen
)) {
852 if (pktin
.maxlen
< newlen
+ 5) {
853 pktin
.maxlen
= newlen
+ 5;
856 NULL ?
smalloc(pktin
.maxlen
+
857 APIEXTRA
) : srealloc(pktin
.data
,
861 fatalbox("Out of memory");
863 pktin
.length
= 5 + newlen
;
864 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
866 debug(("Post-decompression payload:\n"));
867 dmemdump(pktin
.data
+ 5, newlen
);
875 pktin
.type
= pktin
.data
[5];
877 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
878 goto next_packet
; /* FIXME: print DEBUG message */
880 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
881 /* log reason code in disconnect message */
883 int reason
= GET_32BIT(pktin
.data
+ 6);
884 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
886 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
887 sprintf(buf
, "Received disconnect message (%s)",
888 ssh2_disconnect_reasons
[reason
]);
890 sprintf(buf
, "Received disconnect message (unknown type %d)",
894 strcpy(buf
, "Disconnection message text: ");
895 nowlen
= strlen(buf
);
896 if (msglen
> sizeof(buf
) - nowlen
- 1)
897 msglen
= sizeof(buf
) - nowlen
- 1;
898 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
899 buf
[nowlen
+ msglen
] = '\0';
906 static void ssh1_pktout_size(int len
)
910 len
+= 5; /* type and CRC */
914 pktout
.length
= len
- 5;
915 if (pktout
.maxlen
< biglen
) {
916 pktout
.maxlen
= biglen
;
918 /* Allocate enough buffer space for extra block
919 * for MS CryptEncrypt() */
920 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
921 srealloc(pktout
.data
, biglen
+ 12));
923 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
924 srealloc(pktout
.data
, biglen
+ 4));
927 fatalbox("Out of memory");
929 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
932 static void s_wrpkt_start(int type
, int len
)
934 ssh1_pktout_size(len
);
938 static int s_wrpkt_prepare(void)
940 int pad
, len
, biglen
, i
;
943 pktout
.body
[-1] = pktout
.type
;
946 debug(("Packet payload pre-compression:\n"));
947 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
950 if (ssh1_compressing
) {
951 unsigned char *compblk
;
953 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
955 ssh1_pktout_size(complen
- 1);
956 memcpy(pktout
.body
- 1, compblk
, complen
);
959 debug(("Packet payload post-compression:\n"));
960 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
964 len
= pktout
.length
+ 5; /* type and CRC */
968 for (i
= 0; i
< pad
; i
++)
969 pktout
.data
[i
+ 4] = random_byte();
970 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
971 PUT_32BIT(pktout
.data
+ biglen
, crc
);
972 PUT_32BIT(pktout
.data
, len
);
975 debug(("Sending packet len=%d\n", biglen
+ 4));
976 dmemdump(pktout
.data
, biglen
+ 4);
979 cipher
->encrypt(pktout
.data
+ 4, biglen
);
984 static void s_wrpkt(void)
987 len
= s_wrpkt_prepare();
988 backlog
= sk_write(s
, pktout
.data
, len
);
989 if (backlog
> SSH_MAX_BACKLOG
)
990 ssh_throttle_all(1, backlog
);
993 static void s_wrpkt_defer(void)
996 len
= s_wrpkt_prepare();
997 if (deferred_len
+ len
> deferred_size
) {
998 deferred_size
= deferred_len
+ len
+ 128;
999 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1001 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1002 deferred_len
+= len
;
1006 * Construct a packet with the specified contents.
1008 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1010 unsigned char *p
, *argp
, argchar
;
1011 unsigned long argint
;
1012 int pktlen
, argtype
, arglen
;
1016 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1019 (void) va_arg(ap1
, int);
1023 (void) va_arg(ap1
, char);
1027 (void) va_arg(ap1
, unsigned char *);
1028 arglen
= va_arg(ap1
, int);
1032 argp
= va_arg(ap1
, unsigned char *);
1033 arglen
= strlen(argp
);
1034 pktlen
+= 4 + arglen
;
1037 bn
= va_arg(ap1
, Bignum
);
1038 pktlen
+= ssh1_bignum_length(bn
);
1045 s_wrpkt_start(pkttype
, pktlen
);
1048 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1051 argint
= va_arg(ap2
, int);
1052 PUT_32BIT(p
, argint
);
1056 argchar
= va_arg(ap2
, unsigned char);
1061 argp
= va_arg(ap2
, unsigned char *);
1062 arglen
= va_arg(ap2
, int);
1063 memcpy(p
, argp
, arglen
);
1067 argp
= va_arg(ap2
, unsigned char *);
1068 arglen
= strlen(argp
);
1069 PUT_32BIT(p
, arglen
);
1070 memcpy(p
+ 4, argp
, arglen
);
1074 bn
= va_arg(ap2
, Bignum
);
1075 p
+= ssh1_write_bignum(p
, bn
);
1081 static void send_packet(int pkttype
, ...)
1084 va_start(ap1
, pkttype
);
1085 va_start(ap2
, pkttype
);
1086 construct_packet(pkttype
, ap1
, ap2
);
1090 static void defer_packet(int pkttype
, ...)
1093 va_start(ap1
, pkttype
);
1094 va_start(ap2
, pkttype
);
1095 construct_packet(pkttype
, ap1
, ap2
);
1099 static int ssh_versioncmp(char *a
, char *b
)
1102 unsigned long av
, bv
;
1104 av
= strtoul(a
, &ae
, 10);
1105 bv
= strtoul(b
, &be
, 10);
1107 return (av
< bv ?
-1 : +1);
1112 av
= strtoul(ae
, &ae
, 10);
1113 bv
= strtoul(be
, &be
, 10);
1115 return (av
< bv ?
-1 : +1);
1121 * Utility routines for putting an SSH-protocol `string' and
1122 * `uint32' into a SHA state.
1125 static void sha_string(SHA_State
* s
, void *str
, int len
)
1127 unsigned char lenblk
[4];
1128 PUT_32BIT(lenblk
, len
);
1129 SHA_Bytes(s
, lenblk
, 4);
1130 SHA_Bytes(s
, str
, len
);
1133 static void sha_uint32(SHA_State
* s
, unsigned i
)
1135 unsigned char intblk
[4];
1136 PUT_32BIT(intblk
, i
);
1137 SHA_Bytes(s
, intblk
, 4);
1141 * SSH2 packet construction functions.
1143 static void ssh2_pkt_ensure(int length
)
1145 if (pktout
.maxlen
< length
) {
1146 pktout
.maxlen
= length
+ 256;
1149 NULL ?
smalloc(pktout
.maxlen
+
1150 APIEXTRA
) : srealloc(pktout
.data
,
1154 fatalbox("Out of memory");
1157 static void ssh2_pkt_adddata(void *data
, int len
)
1159 pktout
.length
+= len
;
1160 ssh2_pkt_ensure(pktout
.length
);
1161 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1163 static void ssh2_pkt_addbyte(unsigned char byte
)
1165 ssh2_pkt_adddata(&byte
, 1);
1167 static void ssh2_pkt_init(int pkt_type
)
1170 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1172 static void ssh2_pkt_addbool(unsigned char value
)
1174 ssh2_pkt_adddata(&value
, 1);
1176 static void ssh2_pkt_adduint32(unsigned long value
)
1179 PUT_32BIT(x
, value
);
1180 ssh2_pkt_adddata(x
, 4);
1182 static void ssh2_pkt_addstring_start(void)
1184 ssh2_pkt_adduint32(0);
1185 pktout
.savedpos
= pktout
.length
;
1187 static void ssh2_pkt_addstring_str(char *data
)
1189 ssh2_pkt_adddata(data
, strlen(data
));
1190 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1191 pktout
.length
- pktout
.savedpos
);
1193 static void ssh2_pkt_addstring_data(char *data
, int len
)
1195 ssh2_pkt_adddata(data
, len
);
1196 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1197 pktout
.length
- pktout
.savedpos
);
1199 static void ssh2_pkt_addstring(char *data
)
1201 ssh2_pkt_addstring_start();
1202 ssh2_pkt_addstring_str(data
);
1204 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1207 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1210 fatalbox("out of memory");
1212 for (i
= 1; i
<= n
; i
++)
1213 p
[i
] = bignum_byte(b
, n
- i
);
1215 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1217 memmove(p
, p
+ i
, n
+ 1 - i
);
1221 static void ssh2_pkt_addmp(Bignum b
)
1225 p
= ssh2_mpint_fmt(b
, &len
);
1226 ssh2_pkt_addstring_start();
1227 ssh2_pkt_addstring_data(p
, len
);
1232 * Construct an SSH2 final-form packet: compress it, encrypt it,
1233 * put the MAC on it. Final packet, ready to be sent, is stored in
1234 * pktout.data. Total length is returned.
1236 static int ssh2_pkt_construct(void)
1238 int cipherblk
, maclen
, padding
, i
;
1239 static unsigned long outgoing_sequence
= 0;
1242 * Compress packet payload.
1245 debug(("Pre-compression payload:\n"));
1246 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1249 unsigned char *newpayload
;
1251 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1252 &newpayload
, &newlen
)) {
1254 ssh2_pkt_adddata(newpayload
, newlen
);
1260 * Add padding. At least four bytes, and must also bring total
1261 * length (minus MAC) up to a multiple of the block size.
1263 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1264 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1267 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1268 maclen
= csmac ? csmac
->len
: 0;
1269 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1270 pktout
.data
[4] = padding
;
1271 for (i
= 0; i
< padding
; i
++)
1272 pktout
.data
[pktout
.length
+ i
] = random_byte();
1273 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1275 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1277 outgoing_sequence
++; /* whether or not we MACed */
1280 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1281 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1285 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1287 /* Ready-to-send packet starts at pktout.data. We return length. */
1288 return pktout
.length
+ padding
+ maclen
;
1292 * Construct and send an SSH2 packet immediately.
1294 static void ssh2_pkt_send(void)
1298 len
= ssh2_pkt_construct();
1299 backlog
= sk_write(s
, pktout
.data
, len
);
1300 if (backlog
> SSH_MAX_BACKLOG
)
1301 ssh_throttle_all(1, backlog
);
1305 * Construct an SSH2 packet and add it to a deferred data block.
1306 * Useful for sending multiple packets in a single sk_write() call,
1307 * to prevent a traffic-analysing listener from being able to work
1308 * out the length of any particular packet (such as the password
1311 * Note that because SSH2 sequence-numbers its packets, this can
1312 * NOT be used as an m4-style `defer' allowing packets to be
1313 * constructed in one order and sent in another.
1315 static void ssh2_pkt_defer(void)
1317 int len
= ssh2_pkt_construct();
1318 if (deferred_len
+ len
> deferred_size
) {
1319 deferred_size
= deferred_len
+ len
+ 128;
1320 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1322 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1323 deferred_len
+= len
;
1327 * Send the whole deferred data block constructed by
1328 * ssh2_pkt_defer() or SSH1's defer_packet().
1330 static void ssh_pkt_defersend(void)
1333 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1334 deferred_len
= deferred_size
= 0;
1335 sfree(deferred_send_data
);
1336 deferred_send_data
= NULL
;
1337 if (backlog
> SSH_MAX_BACKLOG
)
1338 ssh_throttle_all(1, backlog
);
1342 void bndebug(char *string
, Bignum b
)
1346 p
= ssh2_mpint_fmt(b
, &len
);
1347 debug(("%s", string
));
1348 for (i
= 0; i
< len
; i
++)
1349 debug((" %02x", p
[i
]));
1355 static void sha_mpint(SHA_State
* s
, Bignum b
)
1359 p
= ssh2_mpint_fmt(b
, &len
);
1360 sha_string(s
, p
, len
);
1365 * SSH2 packet decode functions.
1367 static unsigned long ssh2_pkt_getuint32(void)
1369 unsigned long value
;
1370 if (pktin
.length
- pktin
.savedpos
< 4)
1371 return 0; /* arrgh, no way to decline (FIXME?) */
1372 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1373 pktin
.savedpos
+= 4;
1376 static int ssh2_pkt_getbool(void)
1378 unsigned long value
;
1379 if (pktin
.length
- pktin
.savedpos
< 1)
1380 return 0; /* arrgh, no way to decline (FIXME?) */
1381 value
= pktin
.data
[pktin
.savedpos
] != 0;
1385 static void ssh2_pkt_getstring(char **p
, int *length
)
1388 if (pktin
.length
- pktin
.savedpos
< 4)
1390 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1391 pktin
.savedpos
+= 4;
1392 if (pktin
.length
- pktin
.savedpos
< *length
)
1394 *p
= pktin
.data
+ pktin
.savedpos
;
1395 pktin
.savedpos
+= *length
;
1397 static Bignum
ssh2_pkt_getmp(void)
1403 ssh2_pkt_getstring(&p
, &length
);
1407 bombout(("internal error: Can't handle negative mpints"));
1410 b
= bignum_from_bytes(p
, length
);
1415 * Examine the remote side's version string and compare it against
1416 * a list of known buggy implementations.
1418 static void ssh_detect_bugs(char *vstring
)
1420 char *imp
; /* pointer to implementation part */
1422 imp
+= strcspn(imp
, "-");
1425 imp
+= strcspn(imp
, "-");
1429 ssh_remote_bugs
= 0;
1431 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1432 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1433 !strcmp(imp
, "1.2.22")) {
1435 * These versions don't support SSH1_MSG_IGNORE, so we have
1436 * to use a different defence against password length
1439 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1440 logevent("We believe remote version has SSH1 ignore bug");
1443 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1444 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1445 !strncmp(imp
, "2.1 ", 4)) {
1447 * These versions have the HMAC bug.
1449 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1450 logevent("We believe remote version has SSH2 HMAC bug");
1454 static int do_ssh_init(unsigned char c
)
1457 static char version
[10];
1458 static char *vstring
;
1459 static int vstrsize
;
1465 /* Search for the string "SSH-" in the input. */
1468 static const int transS
[] = { 1, 2, 2, 1 };
1469 static const int transH
[] = { 0, 0, 3, 0 };
1470 static const int transminus
[] = { 0, 0, 0, -1 };
1481 crReturn(1); /* get another character */
1484 vstring
= smalloc(16);
1486 strcpy(vstring
, "SSH-");
1490 crReturn(1); /* get another char */
1491 if (vslen
>= vstrsize
- 1) {
1493 vstring
= srealloc(vstring
, vstrsize
);
1495 vstring
[vslen
++] = c
;
1500 } else if (i
< sizeof(version
) - 1)
1502 } else if (c
== '\n')
1506 ssh_agentfwd_enabled
= FALSE
;
1507 rdpkt2_state
.incoming_sequence
= 0;
1510 vlog
= smalloc(20 + vslen
);
1511 sprintf(vlog
, "Server version: %s", vstring
);
1512 ssh_detect_bugs(vstring
);
1513 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1518 * Server version "1.99" means we can choose whether we use v1
1519 * or v2 protocol. Choice is based on cfg.sshprot.
1521 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1523 * This is a v2 server. Begin v2 protocol.
1525 char verstring
[80], vlog
[100];
1526 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1527 SHA_Init(&exhashbase
);
1529 * Hash our version string and their version string.
1531 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1532 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1533 sprintf(vlog
, "We claim version: %s", verstring
);
1535 strcat(verstring
, "\n");
1536 logevent("Using SSH protocol version 2");
1537 sk_write(s
, verstring
, strlen(verstring
));
1538 ssh_protocol
= ssh2_protocol
;
1540 s_rdpkt
= ssh2_rdpkt
;
1543 * This is a v1 server. Begin v1 protocol.
1545 char verstring
[80], vlog
[100];
1546 sprintf(verstring
, "SSH-%s-%s",
1547 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1549 sprintf(vlog
, "We claim version: %s", verstring
);
1551 strcat(verstring
, "\n");
1552 logevent("Using SSH protocol version 1");
1553 sk_write(s
, verstring
, strlen(verstring
));
1554 ssh_protocol
= ssh1_protocol
;
1556 s_rdpkt
= ssh1_rdpkt
;
1558 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1565 static void ssh_gotdata(unsigned char *data
, int datalen
)
1570 * To begin with, feed the characters one by one to the
1571 * protocol initialisation / selection function do_ssh_init().
1572 * When that returns 0, we're done with the initial greeting
1573 * exchange and can move on to packet discipline.
1578 crReturnV
; /* more data please */
1579 ret
= do_ssh_init(*data
);
1587 * We emerge from that loop when the initial negotiation is
1588 * over and we have selected an s_rdpkt function. Now pass
1589 * everything to s_rdpkt, and then pass the resulting packets
1590 * to the proper protocol handler.
1595 while (datalen
> 0) {
1596 if (s_rdpkt(&data
, &datalen
) == 0) {
1597 ssh_protocol(NULL
, 0, 1);
1598 if (ssh_state
== SSH_STATE_CLOSED
) {
1608 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1611 ssh_state
= SSH_STATE_CLOSED
;
1617 /* A socket error has occurred. */
1618 connection_fatal(error_msg
);
1620 /* Otherwise, the remote side closed the connection normally. */
1625 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1627 ssh_gotdata(data
, len
);
1628 if (ssh_state
== SSH_STATE_CLOSED
) {
1638 static void ssh_sent(Plug plug
, int bufsize
)
1641 * If the send backlog on the SSH socket itself clears, we
1642 * should unthrottle the whole world if it was throttled.
1644 if (bufsize
< SSH_MAX_BACKLOG
)
1645 ssh_throttle_all(0, bufsize
);
1649 * Connect to specified host and port.
1650 * Returns an error message, or NULL on success.
1651 * Also places the canonical host name into `realhost'. It must be
1652 * freed by the caller.
1654 static char *connect_to_host(char *host
, int port
, char **realhost
)
1656 static struct plug_function_table fn_table
= {
1661 }, *fn_table_ptr
= &fn_table
;
1670 savedhost
= smalloc(1 + strlen(host
));
1672 fatalbox("Out of memory");
1673 strcpy(savedhost
, host
);
1676 port
= 22; /* default ssh port */
1689 addr
= sk_namelookup(host
, realhost
);
1690 if ((err
= sk_addr_error(addr
)))
1694 *realhost
= strdup(FWhost
);
1700 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1701 if ((err
= sk_socket_error(s
)))
1705 sk_write(s
, "connect ", 8);
1706 sk_write(s
, FWhost
, strlen(FWhost
));
1709 sprintf(buf
, " %d\n", FWport
);
1710 sk_write(s
, buf
, strlen(buf
));
1718 * Throttle or unthrottle the SSH connection.
1720 static void ssh1_throttle(int adjust
)
1722 int old_count
= ssh1_throttle_count
;
1723 ssh1_throttle_count
+= adjust
;
1724 assert(ssh1_throttle_count
>= 0);
1725 if (ssh1_throttle_count
&& !old_count
) {
1726 sk_set_frozen(s
, 1);
1727 } else if (!ssh1_throttle_count
&& old_count
) {
1728 sk_set_frozen(s
, 0);
1733 * Throttle or unthrottle _all_ local data streams (for when sends
1734 * on the SSH connection itself back up).
1736 static void ssh_throttle_all(int enable
, int bufsize
)
1739 struct ssh_channel
*c
;
1741 if (enable
== ssh_throttled_all
)
1743 ssh_throttled_all
= enable
;
1744 ssh_overall_bufsize
= bufsize
;
1747 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1749 case CHAN_MAINSESSION
:
1751 * This is treated separately, outside the switch.
1755 x11_override_throttle(c
->u
.x11
.s
, enable
);
1758 /* Agent channels require no buffer management. */
1761 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1768 * Handle the key exchange and user authentication phases.
1770 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1774 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1775 unsigned char cookie
[8];
1776 struct RSAKey servkey
, hostkey
;
1777 struct MD5Context md5c
;
1778 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1779 static int tried_publickey
;
1780 static unsigned char session_id
[16];
1781 static int cipher_type
;
1782 static char username
[100];
1789 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1790 bombout(("Public key packet not received"));
1794 logevent("Received public keys");
1796 memcpy(cookie
, pktin
.body
, 8);
1798 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1799 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1802 * Log the host key fingerprint.
1806 logevent("Host key fingerprint is:");
1807 strcpy(logmsg
, " ");
1808 hostkey
.comment
= NULL
;
1809 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1810 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1814 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1815 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1816 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1818 ssh1_local_protoflags
=
1819 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1820 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1823 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1824 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1825 MD5Update(&md5c
, pktin
.body
, 8);
1826 MD5Final(session_id
, &md5c
);
1828 for (i
= 0; i
< 32; i
++)
1829 session_key
[i
] = random_byte();
1831 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1833 rsabuf
= smalloc(len
);
1835 fatalbox("Out of memory");
1838 * Verify the host key.
1842 * First format the key into a string.
1844 int len
= rsastr_len(&hostkey
);
1845 char fingerprint
[100];
1846 char *keystr
= smalloc(len
);
1848 fatalbox("Out of memory");
1849 rsastr_fmt(keystr
, &hostkey
);
1850 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1851 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1856 for (i
= 0; i
< 32; i
++) {
1857 rsabuf
[i
] = session_key
[i
];
1859 rsabuf
[i
] ^= session_id
[i
];
1862 if (hostkey
.bytes
> servkey
.bytes
) {
1863 rsaencrypt(rsabuf
, 32, &servkey
);
1864 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1866 rsaencrypt(rsabuf
, 32, &hostkey
);
1867 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1870 logevent("Encrypted session key");
1873 int cipher_chosen
= 0, warn
= 0;
1874 char *cipher_string
= NULL
;
1875 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
1876 int next_cipher
= cfg
.ssh_cipherlist
[i
];
1877 if (next_cipher
== CIPHER_WARN
) {
1878 /* If/when we choose a cipher, warn about it */
1880 } else if (next_cipher
== CIPHER_AES
) {
1881 /* XXX Probably don't need to mention this. */
1882 logevent("AES not supported in SSH1, skipping");
1884 switch (next_cipher
) {
1885 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
1886 cipher_string
= "3DES"; break;
1887 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
1888 cipher_string
= "Blowfish"; break;
1889 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
1890 cipher_string
= "single-DES"; break;
1892 if (supported_ciphers_mask
& (1 << cipher_type
))
1896 if (!cipher_chosen
) {
1897 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
1898 bombout(("Server violates SSH 1 protocol by not "
1899 "supporting 3DES encryption"));
1901 /* shouldn't happen */
1902 bombout(("No supported ciphers found"));
1906 /* Warn about chosen cipher if necessary. */
1908 askcipher(cipher_string
, 0);
1911 switch (cipher_type
) {
1912 case SSH_CIPHER_3DES
:
1913 logevent("Using 3DES encryption");
1915 case SSH_CIPHER_DES
:
1916 logevent("Using single-DES encryption");
1918 case SSH_CIPHER_BLOWFISH
:
1919 logevent("Using Blowfish encryption");
1923 send_packet(SSH1_CMSG_SESSION_KEY
,
1924 PKT_CHAR
, cipher_type
,
1925 PKT_DATA
, cookie
, 8,
1926 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1927 PKT_DATA
, rsabuf
, len
,
1928 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1930 logevent("Trying to enable encryption...");
1934 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1935 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1936 cipher
->sesskey(session_key
);
1940 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1941 bombout(("Encryption not successfully enabled"));
1945 logevent("Successfully started encryption");
1951 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1953 if (!ssh_get_line("login as: ",
1954 username
, sizeof(username
), FALSE
)) {
1956 * get_line failed to get a username.
1959 logevent("No username provided. Abandoning session.");
1960 ssh_state
= SSH_STATE_CLOSED
;
1964 c_write_str("login as: ");
1967 crWaitUntil(!ispkt
);
1969 switch (c
= *in
++) {
1978 c_write_str("\b \b");
1985 c_write_str("\b \b");
1995 if (((c
>= ' ' && c
<= '~') ||
1996 ((unsigned char) c
>= 160))
1997 && pos
< sizeof(username
)-1) {
1998 username
[pos
++] = c
;
2004 c_write_str("\r\n");
2005 username
[strcspn(username
, "\n\r")] = '\0';
2008 strncpy(username
, cfg
.username
, 99);
2009 username
[99] = '\0';
2012 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2014 char userlog
[22 + sizeof(username
)];
2015 sprintf(userlog
, "Sent username \"%s\"", username
);
2017 if (flags
& FLAG_INTERACTIVE
&&
2018 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2019 strcat(userlog
, "\r\n");
2020 c_write_str(userlog
);
2027 tried_publickey
= 0;
2029 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2030 static char password
[100];
2031 static char prompt
[200];
2034 static int pwpkt_type
;
2036 * Show password prompt, having first obtained it via a TIS
2037 * or CryptoCard exchange if we're doing TIS or CryptoCard
2040 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2041 if (agent_exists()) {
2043 * Attempt RSA authentication using Pageant.
2045 static unsigned char request
[5], *response
, *p
;
2046 static int responselen
;
2047 static int i
, nkeys
;
2048 static int authed
= FALSE
;
2051 logevent("Pageant is running. Requesting keys.");
2053 /* Request the keys held by the agent. */
2054 PUT_32BIT(request
, 1);
2055 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2056 agent_query(request
, 5, &r
, &responselen
);
2057 response
= (unsigned char *) r
;
2058 if (response
&& responselen
>= 5 &&
2059 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2061 nkeys
= GET_32BIT(p
);
2065 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2068 for (i
= 0; i
< nkeys
; i
++) {
2069 static struct RSAKey key
;
2070 static Bignum challenge
;
2071 static char *commentp
;
2072 static int commentlen
;
2076 sprintf(buf
, "Trying Pageant key #%d", i
);
2080 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2081 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2082 commentlen
= GET_32BIT(p
);
2086 send_packet(SSH1_CMSG_AUTH_RSA
,
2087 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2089 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2090 logevent("Key refused");
2093 logevent("Received RSA challenge");
2094 ssh1_read_bignum(pktin
.body
, &challenge
);
2096 char *agentreq
, *q
, *ret
;
2099 len
= 1 + 4; /* message type, bit count */
2100 len
+= ssh1_bignum_length(key
.exponent
);
2101 len
+= ssh1_bignum_length(key
.modulus
);
2102 len
+= ssh1_bignum_length(challenge
);
2103 len
+= 16; /* session id */
2104 len
+= 4; /* response format */
2105 agentreq
= smalloc(4 + len
);
2106 PUT_32BIT(agentreq
, len
);
2108 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2109 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2111 q
+= ssh1_write_bignum(q
, key
.exponent
);
2112 q
+= ssh1_write_bignum(q
, key
.modulus
);
2113 q
+= ssh1_write_bignum(q
, challenge
);
2114 memcpy(q
, session_id
, 16);
2116 PUT_32BIT(q
, 1); /* response format */
2117 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2121 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2122 logevent("Sending Pageant's response");
2123 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2124 PKT_DATA
, ret
+ 5, 16,
2128 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2130 ("Pageant's response accepted");
2131 if (flags
& FLAG_VERBOSE
) {
2133 ("Authenticated using RSA key \"");
2134 c_write(commentp
, commentlen
);
2135 c_write_str("\" from agent\r\n");
2140 ("Pageant's response not accepted");
2143 ("Pageant failed to answer challenge");
2147 logevent("No reply received from Pageant");
2150 freebn(key
.exponent
);
2151 freebn(key
.modulus
);
2160 if (*cfg
.keyfile
&& !tried_publickey
)
2161 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2163 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2165 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
))) {
2166 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2167 logevent("Requested TIS authentication");
2168 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2170 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2171 logevent("TIS authentication declined");
2172 if (flags
& FLAG_INTERACTIVE
)
2173 c_write_str("TIS authentication refused.\r\n");
2175 int challengelen
= ((pktin
.body
[0] << 24) |
2176 (pktin
.body
[1] << 16) |
2177 (pktin
.body
[2] << 8) |
2179 logevent("Received TIS challenge");
2180 if (challengelen
> sizeof(prompt
) - 1)
2181 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2182 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2183 prompt
[challengelen
] = '\0';
2186 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2188 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
))) {
2189 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2190 logevent("Requested CryptoCard authentication");
2191 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2193 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2194 logevent("CryptoCard authentication declined");
2195 c_write_str("CryptoCard authentication refused.\r\n");
2197 int challengelen
= ((pktin
.body
[0] << 24) |
2198 (pktin
.body
[1] << 16) |
2199 (pktin
.body
[2] << 8) |
2201 logevent("Received CryptoCard challenge");
2202 if (challengelen
> sizeof(prompt
) - 1)
2203 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2204 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2205 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
2206 sizeof(prompt
) - challengelen
);
2207 prompt
[sizeof(prompt
) - 1] = '\0';
2210 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2211 sprintf(prompt
, "%.90s@%.90s's password: ",
2212 username
, savedhost
);
2214 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2215 char *comment
= NULL
;
2216 if (flags
& FLAG_VERBOSE
)
2217 c_write_str("Trying public key authentication.\r\n");
2218 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2219 if (flags
& FLAG_VERBOSE
)
2220 c_write_str("No passphrase required.\r\n");
2223 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2228 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2230 * get_line failed to get a password (for example
2231 * because one was supplied on the command line
2232 * which has already failed to work). Terminate.
2234 send_packet(SSH1_MSG_DISCONNECT
,
2235 PKT_STR
, "No more passwords available to try",
2237 connection_fatal("Unable to authenticate");
2238 ssh_state
= SSH_STATE_CLOSED
;
2242 c_write_str(prompt
);
2246 crWaitUntil(!ispkt
);
2248 switch (c
= *in
++) {
2269 if (pos
< sizeof(password
)-1)
2270 password
[pos
++] = c
;
2274 c_write_str("\r\n");
2278 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2280 * Try public key authentication with the specified
2283 static struct RSAKey pubkey
;
2284 static Bignum challenge
, response
;
2286 static unsigned char buffer
[32];
2288 tried_publickey
= 1;
2289 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2291 c_write_str("Couldn't load public key from ");
2292 c_write_str(cfg
.keyfile
);
2293 c_write_str(".\r\n");
2294 continue; /* go and try password */
2297 c_write_str("Wrong passphrase.\r\n");
2298 tried_publickey
= 0;
2299 continue; /* try again */
2303 * Send a public key attempt.
2305 send_packet(SSH1_CMSG_AUTH_RSA
,
2306 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2309 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2310 c_write_str("Server refused our public key.\r\n");
2311 continue; /* go and try password */
2313 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2314 bombout(("Bizarre response to offer of public key"));
2317 ssh1_read_bignum(pktin
.body
, &challenge
);
2318 response
= rsadecrypt(challenge
, &pubkey
);
2319 freebn(pubkey
.private_exponent
); /* burn the evidence */
2321 for (i
= 0; i
< 32; i
++) {
2322 buffer
[i
] = bignum_byte(response
, 31 - i
);
2326 MD5Update(&md5c
, buffer
, 32);
2327 MD5Update(&md5c
, session_id
, 16);
2328 MD5Final(buffer
, &md5c
);
2330 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2331 PKT_DATA
, buffer
, 16, PKT_END
);
2334 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2335 if (flags
& FLAG_VERBOSE
)
2337 ("Failed to authenticate with our public key.\r\n");
2338 continue; /* go and try password */
2339 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2341 ("Bizarre response to RSA authentication response"));
2345 break; /* we're through! */
2347 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2349 * Defence against traffic analysis: we send a
2350 * whole bunch of packets containing strings of
2351 * different lengths. One of these strings is the
2352 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2353 * The others are all random data in
2354 * SSH1_MSG_IGNORE packets. This way a passive
2355 * listener can't tell which is the password, and
2356 * hence can't deduce the password length.
2358 * Anybody with a password length greater than 16
2359 * bytes is going to have enough entropy in their
2360 * password that a listener won't find it _that_
2361 * much help to know how long it is. So what we'll
2364 * - if password length < 16, we send 15 packets
2365 * containing string lengths 1 through 15
2367 * - otherwise, we let N be the nearest multiple
2368 * of 8 below the password length, and send 8
2369 * packets containing string lengths N through
2370 * N+7. This won't obscure the order of
2371 * magnitude of the password length, but it will
2372 * introduce a bit of extra uncertainty.
2374 * A few servers (the old 1.2.18 through 1.2.22)
2375 * can't deal with SSH1_MSG_IGNORE. For these
2376 * servers, we need an alternative defence. We make
2377 * use of the fact that the password is interpreted
2378 * as a C string: so we can append a NUL, then some
2381 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2386 len
= strlen(password
);
2387 if (len
< sizeof(string
)) {
2389 strcpy(string
, password
);
2390 len
++; /* cover the zero byte */
2391 while (len
< sizeof(string
)) {
2392 string
[len
++] = (char) random_byte();
2397 send_packet(pwpkt_type
, PKT_INT
, len
,
2398 PKT_DATA
, s
, len
, PKT_END
);
2400 int bottom
, top
, pwlen
, i
;
2403 pwlen
= strlen(password
);
2405 bottom
= 0; /* zero length passwords are OK! :-) */
2408 bottom
= pwlen
& ~7;
2412 assert(pwlen
>= bottom
&& pwlen
<= top
);
2414 randomstr
= smalloc(top
+ 1);
2416 for (i
= bottom
; i
<= top
; i
++) {
2418 defer_packet(pwpkt_type
, PKT_STR
, password
,
2421 for (j
= 0; j
< i
; j
++) {
2423 randomstr
[j
] = random_byte();
2424 } while (randomstr
[j
] == '\0');
2426 randomstr
[i
] = '\0';
2427 defer_packet(SSH1_MSG_IGNORE
,
2428 PKT_STR
, randomstr
, PKT_END
);
2431 ssh_pkt_defersend();
2434 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2437 logevent("Sent password");
2438 memset(password
, 0, strlen(password
));
2440 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2441 if (flags
& FLAG_VERBOSE
)
2442 c_write_str("Access denied\r\n");
2443 logevent("Authentication refused");
2444 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2445 logevent("Received disconnect request");
2446 ssh_state
= SSH_STATE_CLOSED
;
2448 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2449 bombout(("Strange packet received, type %d", pktin
.type
));
2454 logevent("Authentication successful");
2459 void sshfwd_close(struct ssh_channel
*c
)
2461 if (c
&& !c
->closes
) {
2462 if (ssh_version
== 1) {
2463 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2466 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2467 ssh2_pkt_adduint32(c
->remoteid
);
2471 if (c
->type
== CHAN_X11
) {
2473 logevent("Forwarded X11 connection terminated");
2474 } else if (c
->type
== CHAN_SOCKDATA
) {
2476 logevent("Forwarded port closed");
2481 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2483 if (ssh_version
== 1) {
2484 send_packet(SSH1_MSG_CHANNEL_DATA
,
2485 PKT_INT
, c
->remoteid
,
2486 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2488 * In SSH1 we can return 0 here - implying that forwarded
2489 * connections are never individually throttled - because
2490 * the only circumstance that can cause throttling will be
2491 * the whole SSH connection backing up, in which case
2492 * _everything_ will be throttled as a whole.
2496 ssh2_add_channel_data(c
, buf
, len
);
2497 return ssh2_try_send(c
);
2501 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2503 if (ssh_version
== 1) {
2504 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2505 c
->v
.v1
.throttling
= 0;
2509 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2513 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2519 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2522 if (ssh_state
== SSH_STATE_CLOSED
)
2525 if (cfg
.agentfwd
&& agent_exists()) {
2526 logevent("Requesting agent forwarding");
2527 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2531 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2532 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2533 bombout(("Protocol confusion"));
2535 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2536 logevent("Agent forwarding refused");
2538 logevent("Agent forwarding enabled");
2539 ssh_agentfwd_enabled
= TRUE
;
2543 if (cfg
.x11_forward
) {
2544 char proto
[20], data
[64];
2545 logevent("Requesting X11 forwarding");
2546 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2547 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2548 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2549 PKT_STR
, proto
, PKT_STR
, data
,
2550 PKT_INT
, 0, PKT_END
);
2552 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2553 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2558 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2559 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2560 bombout(("Protocol confusion"));
2562 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2563 logevent("X11 forwarding refused");
2565 logevent("X11 forwarding enabled");
2566 ssh_X11_fwd_enabled
= TRUE
;
2574 char sports
[256], dports
[256], host
[256];
2577 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2578 /* Add port forwardings. */
2583 while (*e
&& *e
!= '\t')
2589 while (*e
&& *e
!= ':')
2599 dport
= atoi(dports
);
2600 sport
= atoi(sports
);
2601 if (sport
&& dport
) {
2603 pfd_addforward(host
, dport
, sport
);
2604 sprintf(buf
, "Local port %d forwarding to %s:%d",
2605 sport
, host
, dport
);
2608 struct ssh_rportfwd
*pf
;
2609 pf
= smalloc(sizeof(*pf
));
2610 strcpy(pf
->dhost
, host
);
2612 if (add234(ssh_rportfwds
, pf
) != pf
) {
2614 "Duplicate remote port forwarding to %s:%d",
2619 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2620 sport
, host
, dport
);
2622 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2634 send_packet(SSH1_CMSG_REQUEST_PTY
,
2635 PKT_STR
, cfg
.termtype
,
2636 PKT_INT
, rows
, PKT_INT
, cols
,
2637 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2638 ssh_state
= SSH_STATE_INTERMED
;
2642 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2643 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2644 bombout(("Protocol confusion"));
2646 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2647 c_write_str("Server refused to allocate pty\r\n");
2648 ssh_editing
= ssh_echoing
= 1;
2650 logevent("Allocated pty");
2652 ssh_editing
= ssh_echoing
= 1;
2655 if (cfg
.compression
) {
2656 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2660 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2661 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2662 bombout(("Protocol confusion"));
2664 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2665 c_write_str("Server refused to compress\r\n");
2667 logevent("Started compression");
2668 ssh1_compressing
= TRUE
;
2669 zlib_compress_init();
2670 zlib_decompress_init();
2674 * Start the shell or command.
2676 * Special case: if the first-choice command is an SSH2
2677 * subsystem (hence not usable here) and the second choice
2678 * exists, we fall straight back to that.
2681 char *cmd
= cfg
.remote_cmd_ptr
;
2683 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
2684 cmd
= cfg
.remote_cmd_ptr2
;
2685 ssh_fallback_cmd
= TRUE
;
2688 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2690 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2691 logevent("Started session");
2694 ssh_state
= SSH_STATE_SESSION
;
2698 ssh_special(TS_EOF
);
2700 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2702 ssh_channels
= newtree234(ssh_channelcmp
);
2706 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2707 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2708 long len
= GET_32BIT(pktin
.body
);
2710 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2711 pktin
.body
+ 4, len
);
2712 if (bufsize
> SSH1_BUFFER_LIMIT
) {
2713 ssh1_stdout_throttling
= 1;
2716 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2717 ssh_state
= SSH_STATE_CLOSED
;
2718 logevent("Received disconnect request");
2720 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2721 /* Remote side is trying to open a channel to talk to our
2722 * X-Server. Give them back a local channel number. */
2723 struct ssh_channel
*c
;
2725 logevent("Received X11 connect request");
2726 /* Refuse if X11 forwarding is disabled. */
2727 if (!ssh_X11_fwd_enabled
) {
2728 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2729 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2730 logevent("Rejected X11 connect request");
2732 c
= smalloc(sizeof(struct ssh_channel
));
2734 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2735 logevent("opening X11 forward connection failed");
2737 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2738 PKT_INT
, GET_32BIT(pktin
.body
),
2742 ("opening X11 forward connection succeeded");
2743 c
->remoteid
= GET_32BIT(pktin
.body
);
2744 c
->localid
= alloc_channel_id();
2746 c
->v
.v1
.throttling
= 0;
2747 c
->type
= CHAN_X11
; /* identify channel type */
2748 add234(ssh_channels
, c
);
2749 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2750 PKT_INT
, c
->remoteid
, PKT_INT
,
2751 c
->localid
, PKT_END
);
2752 logevent("Opened X11 forward channel");
2755 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2756 /* Remote side is trying to open a channel to talk to our
2757 * agent. Give them back a local channel number. */
2758 struct ssh_channel
*c
;
2760 /* Refuse if agent forwarding is disabled. */
2761 if (!ssh_agentfwd_enabled
) {
2762 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2763 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2765 c
= smalloc(sizeof(struct ssh_channel
));
2766 c
->remoteid
= GET_32BIT(pktin
.body
);
2767 c
->localid
= alloc_channel_id();
2769 c
->v
.v1
.throttling
= 0;
2770 c
->type
= CHAN_AGENT
; /* identify channel type */
2771 c
->u
.a
.lensofar
= 0;
2772 add234(ssh_channels
, c
);
2773 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2774 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2777 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2778 /* Remote side is trying to open a channel to talk to a
2779 * forwarded port. Give them back a local channel number. */
2780 struct ssh_channel
*c
;
2781 struct ssh_rportfwd pf
;
2783 char host
[256], buf
[1024];
2785 c
= smalloc(sizeof(struct ssh_channel
));
2787 hostsize
= GET_32BIT(pktin
.body
+4);
2788 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2789 if (h
+1 < host
+sizeof(host
))
2794 port
= GET_32BIT(p
);
2796 strcpy(pf
.dhost
, host
);
2799 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2800 sprintf(buf
, "Rejected remote port open request for %s:%d",
2803 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2804 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2806 sprintf(buf
, "Received remote port open request for %s:%d",
2809 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2812 sprintf(buf
, "Port open failed: %s", e
);
2815 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2816 PKT_INT
, GET_32BIT(pktin
.body
),
2819 c
->remoteid
= GET_32BIT(pktin
.body
);
2820 c
->localid
= alloc_channel_id();
2822 c
->v
.v1
.throttling
= 0;
2823 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2824 add234(ssh_channels
, c
);
2825 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2826 PKT_INT
, c
->remoteid
, PKT_INT
,
2827 c
->localid
, PKT_END
);
2828 logevent("Forwarded port opened successfully");
2832 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2833 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2834 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2835 struct ssh_channel
*c
;
2837 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2838 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2839 c
->remoteid
= localid
;
2840 c
->type
= CHAN_SOCKDATA
;
2841 pfd_confirm(c
->u
.pfd
.s
);
2844 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
2845 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2846 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2847 struct ssh_channel
*c
;
2849 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2850 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2851 logevent("Forwarded connection refused by server");
2852 pfd_close(c
->u
.pfd
.s
);
2853 del234(ssh_channels
, c
);
2857 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2858 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2859 /* Remote side closes a channel. */
2860 unsigned i
= GET_32BIT(pktin
.body
);
2861 struct ssh_channel
*c
;
2862 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2866 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2867 if (!(c
->closes
& closetype
))
2868 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2870 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2871 logevent("Forwarded X11 connection terminated");
2872 assert(c
->u
.x11
.s
!= NULL
);
2873 x11_close(c
->u
.x11
.s
);
2876 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
2877 logevent("Forwarded port closed");
2878 assert(c
->u
.pfd
.s
!= NULL
);
2879 pfd_close(c
->u
.pfd
.s
);
2882 c
->closes
|= closetype
;
2883 if (c
->closes
== 3) {
2884 del234(ssh_channels
, c
);
2888 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2889 /* Data sent down one of our channels. */
2890 int i
= GET_32BIT(pktin
.body
);
2891 int len
= GET_32BIT(pktin
.body
+ 4);
2892 unsigned char *p
= pktin
.body
+ 8;
2893 struct ssh_channel
*c
;
2894 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2899 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
2902 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
2905 /* Data for an agent message. Buffer it. */
2907 if (c
->u
.a
.lensofar
< 4) {
2908 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2909 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2913 c
->u
.a
.lensofar
+= l
;
2915 if (c
->u
.a
.lensofar
== 4) {
2917 4 + GET_32BIT(c
->u
.a
.msglen
);
2918 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2919 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2921 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2923 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
2925 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
2929 c
->u
.a
.lensofar
+= l
;
2931 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2932 void *reply
, *sentreply
;
2934 agent_query(c
->u
.a
.message
,
2935 c
->u
.a
.totallen
, &reply
,
2940 /* Fake SSH_AGENT_FAILURE. */
2941 sentreply
= "\0\0\0\1\5";
2944 send_packet(SSH1_MSG_CHANNEL_DATA
,
2945 PKT_INT
, c
->remoteid
,
2947 PKT_DATA
, sentreply
, replylen
,
2951 sfree(c
->u
.a
.message
);
2952 c
->u
.a
.lensofar
= 0;
2955 bufsize
= 0; /* agent channels never back up */
2958 if (bufsize
> SSH1_BUFFER_LIMIT
) {
2959 c
->v
.v1
.throttling
= 1;
2963 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2964 /* may be from EXEC_SHELL on some servers */
2965 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2966 /* may be from EXEC_SHELL on some servers
2967 * if no pty is available or in other odd cases. Ignore */
2968 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2969 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2971 bombout(("Strange packet received: type %d", pktin
.type
));
2976 int len
= min(inlen
, 512);
2977 send_packet(SSH1_CMSG_STDIN_DATA
,
2978 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2989 * Utility routine for decoding comma-separated strings in KEXINIT.
2991 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
2993 int needlen
= strlen(needle
);
2996 * Is it at the start of the string?
2998 if (haylen
>= needlen
&& /* haystack is long enough */
2999 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3000 (haylen
== needlen
|| haystack
[needlen
] == ',')
3001 /* either , or EOS follows */
3005 * If not, search for the next comma and resume after that.
3006 * If no comma found, terminate.
3008 while (haylen
> 0 && *haystack
!= ',')
3009 haylen
--, haystack
++;
3012 haylen
--, haystack
++; /* skip over comma itself */
3017 * SSH2 key creation method.
3019 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
3023 /* First 20 bytes. */
3026 SHA_Bytes(&s
, H
, 20);
3027 SHA_Bytes(&s
, &chr
, 1);
3028 SHA_Bytes(&s
, sessid
, 20);
3029 SHA_Final(&s
, keyspace
);
3030 /* Next 20 bytes. */
3033 SHA_Bytes(&s
, H
, 20);
3034 SHA_Bytes(&s
, keyspace
, 20);
3035 SHA_Final(&s
, keyspace
+ 20);
3039 * Handle the SSH2 transport layer.
3041 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3043 static int i
, j
, len
, nbits
, pbits
, warn
;
3045 static Bignum p
, g
, e
, f
, K
;
3046 static int kex_init_value
, kex_reply_value
;
3047 static const struct ssh_mac
**maclist
;
3049 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3050 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3051 static const struct ssh_mac
*csmac_tobe
= NULL
;
3052 static const struct ssh_mac
*scmac_tobe
= NULL
;
3053 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3054 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3055 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3056 static int hostkeylen
, siglen
;
3057 static void *hkey
; /* actual host key */
3058 static unsigned char exchange_hash
[20];
3059 static unsigned char keyspace
[40];
3060 static int n_preferred_ciphers
;
3061 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3062 static const struct ssh_compress
*preferred_comp
;
3063 static int first_kex
;
3070 * Set up the preferred ciphers. (NULL => warn below here)
3072 n_preferred_ciphers
= 0;
3073 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3074 switch (cfg
.ssh_cipherlist
[i
]) {
3075 case CIPHER_BLOWFISH
:
3076 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3077 n_preferred_ciphers
++;
3080 /* Not supported in SSH2; silently drop */
3083 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3084 n_preferred_ciphers
++;
3087 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3088 n_preferred_ciphers
++;
3091 /* Flag for later. Don't bother if it's the last in
3093 if (i
< CIPHER_MAX
- 1) {
3094 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3095 n_preferred_ciphers
++;
3102 * Set up preferred compression.
3104 if (cfg
.compression
)
3105 preferred_comp
= &ssh_zlib
;
3107 preferred_comp
= &ssh_comp_none
;
3110 * Be prepared to work around the buggy MAC problem.
3112 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3113 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3115 maclist
= macs
, nmacs
= lenof(macs
);
3119 * Construct and send our key exchange packet.
3121 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3122 for (i
= 0; i
< 16; i
++)
3123 ssh2_pkt_addbyte((unsigned char) random_byte());
3124 /* List key exchange algorithms. */
3125 ssh2_pkt_addstring_start();
3126 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3127 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3128 if (i
< lenof(kex_algs
) - 1)
3129 ssh2_pkt_addstring_str(",");
3131 /* List server host key algorithms. */
3132 ssh2_pkt_addstring_start();
3133 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3134 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3135 if (i
< lenof(hostkey_algs
) - 1)
3136 ssh2_pkt_addstring_str(",");
3138 /* List client->server encryption algorithms. */
3139 ssh2_pkt_addstring_start();
3140 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3141 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3142 if (!c
) continue; /* warning flag */
3143 for (j
= 0; j
< c
->nciphers
; j
++) {
3144 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3145 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3146 ssh2_pkt_addstring_str(",");
3149 /* List server->client encryption algorithms. */
3150 ssh2_pkt_addstring_start();
3151 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3152 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3153 if (!c
) continue; /* warning flag */
3154 for (j
= 0; j
< c
->nciphers
; j
++) {
3155 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3156 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3157 ssh2_pkt_addstring_str(",");
3160 /* List client->server MAC algorithms. */
3161 ssh2_pkt_addstring_start();
3162 for (i
= 0; i
< nmacs
; i
++) {
3163 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3165 ssh2_pkt_addstring_str(",");
3167 /* List server->client MAC algorithms. */
3168 ssh2_pkt_addstring_start();
3169 for (i
= 0; i
< nmacs
; i
++) {
3170 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3172 ssh2_pkt_addstring_str(",");
3174 /* List client->server compression algorithms. */
3175 ssh2_pkt_addstring_start();
3176 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3177 const struct ssh_compress
*c
=
3178 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3179 ssh2_pkt_addstring_str(c
->name
);
3180 if (i
< lenof(compressions
))
3181 ssh2_pkt_addstring_str(",");
3183 /* List server->client compression algorithms. */
3184 ssh2_pkt_addstring_start();
3185 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3186 const struct ssh_compress
*c
=
3187 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3188 ssh2_pkt_addstring_str(c
->name
);
3189 if (i
< lenof(compressions
))
3190 ssh2_pkt_addstring_str(",");
3192 /* List client->server languages. Empty list. */
3193 ssh2_pkt_addstring_start();
3194 /* List server->client languages. Empty list. */
3195 ssh2_pkt_addstring_start();
3196 /* First KEX packet does _not_ follow, because we're not that brave. */
3197 ssh2_pkt_addbool(FALSE
);
3199 ssh2_pkt_adduint32(0);
3201 exhash
= exhashbase
;
3202 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3208 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3211 * Now examine the other side's KEXINIT to see what we're up
3214 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3215 bombout(("expected key exchange packet from server"));
3220 cscipher_tobe
= NULL
;
3221 sccipher_tobe
= NULL
;
3226 pktin
.savedpos
+= 16; /* skip garbage cookie */
3227 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3228 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3229 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3234 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3235 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3236 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3237 hostkey
= hostkey_algs
[i
];
3241 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3243 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3244 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3248 for (j
= 0; j
< c
->nciphers
; j
++) {
3249 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3250 cscipher_tobe
= c
->list
[j
];
3255 if (cscipher_tobe
) {
3257 askcipher(cscipher_tobe
->name
, 1);
3261 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3263 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3264 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3268 for (j
= 0; j
< c
->nciphers
; j
++) {
3269 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3270 sccipher_tobe
= c
->list
[j
];
3275 if (sccipher_tobe
) {
3277 askcipher(sccipher_tobe
->name
, 2);
3281 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3282 for (i
= 0; i
< nmacs
; i
++) {
3283 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3284 csmac_tobe
= maclist
[i
];
3288 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3289 for (i
= 0; i
< nmacs
; i
++) {
3290 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3291 scmac_tobe
= maclist
[i
];
3295 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3296 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3297 const struct ssh_compress
*c
=
3298 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3299 if (in_commasep_string(c
->name
, str
, len
)) {
3304 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3305 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3306 const struct ssh_compress
*c
=
3307 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3308 if (in_commasep_string(c
->name
, str
, len
)) {
3315 * Work out the number of bits of key we will need from the key
3316 * exchange. We start with the maximum key length of either
3322 csbits
= cscipher_tobe
->keylen
;
3323 scbits
= sccipher_tobe
->keylen
;
3324 nbits
= (csbits
> scbits ? csbits
: scbits
);
3326 /* The keys only have 160-bit entropy, since they're based on
3327 * a SHA-1 hash. So cap the key size at 160 bits. */
3332 * If we're doing Diffie-Hellman group exchange, start by
3333 * requesting a group.
3335 if (kex
== &ssh_diffiehellman_gex
) {
3336 logevent("Doing Diffie-Hellman group exchange");
3338 * Work out how big a DH group we will need to allow that
3341 pbits
= 512 << ((nbits
- 1) / 64);
3342 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3343 ssh2_pkt_adduint32(pbits
);
3347 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3348 bombout(("expected key exchange group packet from server"));
3351 p
= ssh2_pkt_getmp();
3352 g
= ssh2_pkt_getmp();
3353 dh_setup_group(p
, g
);
3354 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3355 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3358 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3359 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3362 logevent("Doing Diffie-Hellman key exchange");
3364 * Now generate and send e for Diffie-Hellman.
3366 e
= dh_create_e(nbits
* 2);
3367 ssh2_pkt_init(kex_init_value
);
3372 if (pktin
.type
!= kex_reply_value
) {
3373 bombout(("expected key exchange reply packet from server"));
3376 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3377 f
= ssh2_pkt_getmp();
3378 ssh2_pkt_getstring(&sigdata
, &siglen
);
3382 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3383 if (kex
== &ssh_diffiehellman_gex
) {
3384 sha_uint32(&exhash
, pbits
);
3385 sha_mpint(&exhash
, p
);
3386 sha_mpint(&exhash
, g
);
3388 sha_mpint(&exhash
, e
);
3389 sha_mpint(&exhash
, f
);
3390 sha_mpint(&exhash
, K
);
3391 SHA_Final(&exhash
, exchange_hash
);
3396 debug(("Exchange hash is:\n"));
3397 dmemdump(exchange_hash
, 20);
3400 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3402 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3403 bombout(("Server's host key did not match the signature supplied"));
3408 * Expect SSH2_MSG_NEWKEYS from server.
3411 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3412 bombout(("expected new-keys packet from server"));
3417 * Authenticate remote host: verify host key. (We've already
3418 * checked the signature of the exchange hash.)
3420 keystr
= hostkey
->fmtkey(hkey
);
3421 fingerprint
= hostkey
->fingerprint(hkey
);
3422 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3423 keystr
, fingerprint
);
3424 if (first_kex
) { /* don't bother logging this in rekeys */
3425 logevent("Host key fingerprint is:");
3426 logevent(fingerprint
);
3430 hostkey
->freekey(hkey
);
3433 * Send SSH2_MSG_NEWKEYS.
3435 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3439 * Create and initialise session keys.
3441 cscipher
= cscipher_tobe
;
3442 sccipher
= sccipher_tobe
;
3445 cscomp
= cscomp_tobe
;
3446 sccomp
= sccomp_tobe
;
3447 cscomp
->compress_init();
3448 sccomp
->decompress_init();
3450 * Set IVs after keys. Here we use the exchange hash from the
3451 * _first_ key exchange.
3454 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3455 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3456 cscipher
->setcskey(keyspace
);
3457 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3458 sccipher
->setsckey(keyspace
);
3459 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3460 cscipher
->setcsiv(keyspace
);
3461 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3462 sccipher
->setsciv(keyspace
);
3463 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3464 csmac
->setcskey(keyspace
);
3465 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3466 scmac
->setsckey(keyspace
);
3469 * If this is the first key exchange phase, we must pass the
3470 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3471 * wants to see it but because it will need time to initialise
3472 * itself before it sees an actual packet. In subsequent key
3473 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3474 * it would only confuse the layer above.
3482 * Now we're encrypting. Begin returning 1 to the protocol main
3483 * function so that other things can run on top of the
3484 * transport. If we ever see a KEXINIT, we must go back to the
3487 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3490 logevent("Server initiated key re-exchange");
3491 goto begin_key_exchange
;
3497 * Add data to an SSH2 channel output buffer.
3499 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3502 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3506 * Attempt to send data on an SSH2 channel.
3508 static int ssh2_try_send(struct ssh_channel
*c
)
3510 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3513 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3514 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3515 len
= c
->v
.v2
.remwindow
;
3516 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3517 len
= c
->v
.v2
.remmaxpkt
;
3518 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3519 ssh2_pkt_adduint32(c
->remoteid
);
3520 ssh2_pkt_addstring_start();
3521 ssh2_pkt_addstring_data(data
, len
);
3523 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3524 c
->v
.v2
.remwindow
-= len
;
3528 * After having sent as much data as we can, return the amount
3531 return bufchain_size(&c
->v
.v2
.outbuffer
);
3535 * Potentially enlarge the window on an SSH2 channel.
3537 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3539 if (newwin
> c
->v
.v2
.locwindow
) {
3540 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3541 ssh2_pkt_adduint32(c
->remoteid
);
3542 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3544 c
->v
.v2
.locwindow
= newwin
;
3549 * Handle the SSH2 userauth and connection layers.
3551 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3554 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3556 AUTH_KEYBOARD_INTERACTIVE
3560 AUTH_TYPE_PUBLICKEY
,
3561 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3562 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3564 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3565 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3567 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3568 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3569 static int kbd_inter_running
;
3570 static int we_are_in
;
3571 static int num_prompts
, echo
;
3572 static char username
[100];
3573 static char pwprompt
[200];
3574 static char password
[100];
3579 * Request userauth protocol, and await a response to it.
3581 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3582 ssh2_pkt_addstring("ssh-userauth");
3584 crWaitUntilV(ispkt
);
3585 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3586 bombout(("Server refused user authentication protocol"));
3591 * We repeat this whole loop, including the username prompt,
3592 * until we manage a successful authentication. If the user
3593 * types the wrong _password_, they are sent back to the
3594 * beginning to try another username. (If they specify a
3595 * username in the config, they are never asked, even if they
3596 * do give a wrong password.)
3598 * I think this best serves the needs of
3600 * - the people who have no configuration, no keys, and just
3601 * want to try repeated (username,password) pairs until they
3602 * type both correctly
3604 * - people who have keys and configuration but occasionally
3605 * need to fall back to passwords
3607 * - people with a key held in Pageant, who might not have
3608 * logged in to a particular machine before; so they want to
3609 * type a username, and then _either_ their key will be
3610 * accepted, _or_ they will type a password. If they mistype
3611 * the username they will want to be able to get back and
3622 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3624 if (!ssh_get_line("login as: ",
3625 username
, sizeof(username
), FALSE
)) {
3627 * get_line failed to get a username.
3630 logevent("No username provided. Abandoning session.");
3631 ssh_state
= SSH_STATE_CLOSED
;
3635 c_write_str("login as: ");
3638 crWaitUntilV(!ispkt
);
3640 switch (c
= *in
++) {
3649 c_write_str("\b \b");
3656 c_write_str("\b \b");
3666 if (((c
>= ' ' && c
<= '~') ||
3667 ((unsigned char) c
>= 160))
3668 && pos
< sizeof(username
)-1) {
3669 username
[pos
++] = c
;
3676 c_write_str("\r\n");
3677 username
[strcspn(username
, "\n\r")] = '\0';
3680 strncpy(username
, cfg
.username
, 99);
3681 username
[99] = '\0';
3682 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3683 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3689 * Send an authentication request using method "none": (a)
3690 * just in case it succeeds, and (b) so that we know what
3691 * authentication methods we can usefully try next.
3693 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3694 ssh2_pkt_addstring(username
);
3695 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3696 ssh2_pkt_addstring("none"); /* method */
3698 type
= AUTH_TYPE_NONE
;
3702 tried_pubkey_config
= FALSE
;
3703 tried_agent
= FALSE
;
3704 tried_keyb_inter
= FALSE
;
3705 kbd_inter_running
= FALSE
;
3709 * Wait for the result of the last authentication request.
3712 crWaitUntilV(ispkt
);
3713 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3717 * Don't show the banner if we're operating in
3718 * non-verbose non-interactive mode. (It's probably
3719 * a script, which means nobody will read the
3720 * banner _anyway_, and moreover the printing of
3721 * the banner will screw up processing on the
3722 * output of (say) plink.)
3724 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3725 ssh2_pkt_getstring(&banner
, &size
);
3727 c_write_untrusted(banner
, size
);
3729 crWaitUntilV(ispkt
);
3731 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3732 logevent("Access granted");
3737 if (kbd_inter_running
&&
3738 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3740 * This is a further prompt in keyboard-interactive
3741 * authentication. Do nothing.
3743 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3744 bombout(("Strange packet received during authentication: type %d",
3752 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3753 * we can look at the string in it and know what we can
3754 * helpfully try next.
3756 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
3759 ssh2_pkt_getstring(&methods
, &methlen
);
3760 kbd_inter_running
= FALSE
;
3761 if (!ssh2_pkt_getbool()) {
3763 * We have received an unequivocal Access
3764 * Denied. This can translate to a variety of
3767 * - if we'd just tried "none" authentication,
3768 * it's not worth printing anything at all
3770 * - if we'd just tried a public key _offer_,
3771 * the message should be "Server refused our
3772 * key" (or no message at all if the key
3773 * came from Pageant)
3775 * - if we'd just tried anything else, the
3776 * message really should be "Access denied".
3778 * Additionally, if we'd just tried password
3779 * authentication, we should break out of this
3780 * whole loop so as to go back to the username
3783 if (type
== AUTH_TYPE_NONE
) {
3785 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3786 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3787 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3788 c_write_str("Server refused our key\r\n");
3789 logevent("Server refused public key");
3790 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
3791 /* server declined keyboard-interactive; ignore */
3793 c_write_str("Access denied\r\n");
3794 logevent("Access denied");
3795 if (type
== AUTH_TYPE_PASSWORD
) {
3801 c_write_str("Further authentication required\r\n");
3802 logevent("Further authentication required");
3806 in_commasep_string("publickey", methods
, methlen
);
3808 in_commasep_string("password", methods
, methlen
);
3810 in_commasep_string("keyboard-interactive", methods
, methlen
);
3815 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3817 * Attempt public-key authentication using Pageant.
3819 static unsigned char request
[5], *response
, *p
;
3820 static int responselen
;
3821 static int i
, nkeys
;
3822 static int authed
= FALSE
;
3827 logevent("Pageant is running. Requesting keys.");
3829 /* Request the keys held by the agent. */
3830 PUT_32BIT(request
, 1);
3831 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3832 agent_query(request
, 5, &r
, &responselen
);
3833 response
= (unsigned char *) r
;
3834 if (response
&& responselen
>= 5 &&
3835 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3837 nkeys
= GET_32BIT(p
);
3841 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3844 for (i
= 0; i
< nkeys
; i
++) {
3845 static char *pkblob
, *alg
, *commentp
;
3846 static int pklen
, alglen
, commentlen
;
3847 static int siglen
, retlen
, len
;
3848 static char *q
, *agentreq
, *ret
;
3853 sprintf(buf
, "Trying Pageant key #%d", i
);
3856 pklen
= GET_32BIT(p
);
3860 alglen
= GET_32BIT(pkblob
);
3862 commentlen
= GET_32BIT(p
);
3866 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3867 ssh2_pkt_addstring(username
);
3868 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3869 ssh2_pkt_addstring("publickey"); /* method */
3870 ssh2_pkt_addbool(FALSE
); /* no signature included */
3871 ssh2_pkt_addstring_start();
3872 ssh2_pkt_addstring_data(alg
, alglen
);
3873 ssh2_pkt_addstring_start();
3874 ssh2_pkt_addstring_data(pkblob
, pklen
);
3877 crWaitUntilV(ispkt
);
3878 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3879 logevent("Key refused");
3883 if (flags
& FLAG_VERBOSE
) {
3885 ("Authenticating with public key \"");
3886 c_write(commentp
, commentlen
);
3887 c_write_str("\" from agent\r\n");
3891 * Server is willing to accept the key.
3892 * Construct a SIGN_REQUEST.
3894 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3895 ssh2_pkt_addstring(username
);
3896 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3897 ssh2_pkt_addstring("publickey"); /* method */
3898 ssh2_pkt_addbool(TRUE
);
3899 ssh2_pkt_addstring_start();
3900 ssh2_pkt_addstring_data(alg
, alglen
);
3901 ssh2_pkt_addstring_start();
3902 ssh2_pkt_addstring_data(pkblob
, pklen
);
3904 siglen
= pktout
.length
- 5 + 4 + 20;
3905 len
= 1; /* message type */
3906 len
+= 4 + pklen
; /* key blob */
3907 len
+= 4 + siglen
; /* data to sign */
3908 len
+= 4; /* flags */
3909 agentreq
= smalloc(4 + len
);
3910 PUT_32BIT(agentreq
, len
);
3912 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3913 PUT_32BIT(q
, pklen
);
3915 memcpy(q
, pkblob
, pklen
);
3917 PUT_32BIT(q
, siglen
);
3919 /* Now the data to be signed... */
3922 memcpy(q
, ssh2_session_id
, 20);
3924 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
3925 q
+= pktout
.length
- 5;
3926 /* And finally the (zero) flags word. */
3928 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
3932 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3933 logevent("Sending Pageant's response");
3934 ssh2_pkt_addstring_start();
3935 ssh2_pkt_addstring_data(ret
+ 9,
3943 ("Pageant failed to answer challenge");
3953 if (!method
&& can_pubkey
&& *cfg
.keyfile
3954 && !tried_pubkey_config
) {
3955 unsigned char *pub_blob
;
3956 char *algorithm
, *comment
;
3959 tried_pubkey_config
= TRUE
;
3962 * Try the public key supplied in the configuration.
3964 * First, offer the public blob to see if the server is
3965 * willing to accept it.
3967 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3970 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3971 ssh2_pkt_addstring(username
);
3972 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3973 ssh2_pkt_addstring("publickey"); /* method */
3974 ssh2_pkt_addbool(FALSE
); /* no signature included */
3975 ssh2_pkt_addstring(algorithm
);
3976 ssh2_pkt_addstring_start();
3977 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3979 logevent("Offered public key"); /* FIXME */
3981 crWaitUntilV(ispkt
);
3982 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3984 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3985 continue; /* key refused; give up on it */
3988 logevent("Offer of public key accepted");
3990 * Actually attempt a serious authentication using
3993 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3995 "Passphrase for key \"%.100s\": ",
4001 c_write_str("Authenticating with public key \"");
4002 c_write_str(comment
);
4003 c_write_str("\"\r\n");
4004 method
= AUTH_PUBLICKEY_FILE
;
4008 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
4009 method
= AUTH_KEYBOARD_INTERACTIVE
;
4010 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4011 tried_keyb_inter
= TRUE
;
4013 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4014 ssh2_pkt_addstring(username
);
4015 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4016 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4017 ssh2_pkt_addstring(""); /* lang */
4018 ssh2_pkt_addstring("");
4021 crWaitUntilV(ispkt
);
4022 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4023 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4025 logevent("Keyboard-interactive authentication refused");
4026 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4030 kbd_inter_running
= TRUE
;
4033 if (kbd_inter_running
) {
4034 method
= AUTH_KEYBOARD_INTERACTIVE
;
4035 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4036 tried_keyb_inter
= TRUE
;
4038 /* We've got packet with that "interactive" info
4039 dump banners, and set its prompt as ours */
4041 char *name
, *inst
, *lang
, *prompt
;
4042 int name_len
, inst_len
, lang_len
, prompt_len
;
4043 ssh2_pkt_getstring(&name
, &name_len
);
4044 ssh2_pkt_getstring(&inst
, &inst_len
);
4045 ssh2_pkt_getstring(&lang
, &lang_len
);
4047 c_write_untrusted(name
, name_len
);
4049 c_write_untrusted(inst
, inst_len
);
4050 num_prompts
= ssh2_pkt_getuint32();
4052 ssh2_pkt_getstring(&prompt
, &prompt_len
);
4053 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
4056 echo
= ssh2_pkt_getbool();
4060 if (!method
&& can_passwd
) {
4061 method
= AUTH_PASSWORD
;
4062 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4069 if (!ssh_get_line(pwprompt
, password
,
4070 sizeof(password
), TRUE
)) {
4072 * get_line failed to get a password (for
4073 * example because one was supplied on the
4074 * command line which has already failed to
4077 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4078 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4080 ("No more passwords available to try");
4081 ssh2_pkt_addstring("en"); /* language tag */
4083 connection_fatal("Unable to authenticate");
4084 ssh_state
= SSH_STATE_CLOSED
;
4091 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4096 crWaitUntilV(!ispkt
);
4098 switch (c
= *in
++) {
4119 if (pos
< sizeof(password
)-1)
4120 password
[pos
++] = c
;
4124 c_write_str("\r\n");
4128 if (method
== AUTH_PUBLICKEY_FILE
) {
4130 * We have our passphrase. Now try the actual authentication.
4132 struct ssh2_userkey
*key
;
4134 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4135 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4136 if (key
== SSH2_WRONG_PASSPHRASE
) {
4137 c_write_str("Wrong passphrase\r\n");
4138 tried_pubkey_config
= FALSE
;
4140 c_write_str("Unable to load private key\r\n");
4141 tried_pubkey_config
= TRUE
;
4143 /* Send a spurious AUTH_NONE to return to the top. */
4144 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4145 ssh2_pkt_addstring(username
);
4146 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4147 ssh2_pkt_addstring("none"); /* method */
4149 type
= AUTH_TYPE_NONE
;
4151 unsigned char *blob
, *sigdata
;
4152 int blob_len
, sigdata_len
;
4155 * We have loaded the private key and the server
4156 * has announced that it's willing to accept it.
4157 * Hallelujah. Generate a signature and send it.
4159 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4160 ssh2_pkt_addstring(username
);
4161 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4162 ssh2_pkt_addstring("publickey"); /* method */
4163 ssh2_pkt_addbool(TRUE
);
4164 ssh2_pkt_addstring(key
->alg
->name
);
4165 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4166 ssh2_pkt_addstring_start();
4167 ssh2_pkt_addstring_data(blob
, blob_len
);
4171 * The data to be signed is:
4175 * followed by everything so far placed in the
4178 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4179 sigdata
= smalloc(sigdata_len
);
4180 PUT_32BIT(sigdata
, 20);
4181 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4182 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4185 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4187 ssh2_pkt_addstring_start();
4188 ssh2_pkt_addstring_data(blob
, blob_len
);
4193 type
= AUTH_TYPE_PUBLICKEY
;
4195 } else if (method
== AUTH_PASSWORD
) {
4197 * We send the password packet lumped tightly together with
4198 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4199 * string long enough to make the total length of the two
4200 * packets constant. This should ensure that a passive
4201 * listener doing traffic analyis can't work out the length
4204 * For this to work, we need an assumption about the
4205 * maximum length of the password packet. I think 256 is
4206 * pretty conservative. Anyone using a password longer than
4207 * that probably doesn't have much to worry about from
4208 * people who find out how long their password is!
4210 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4211 ssh2_pkt_addstring(username
);
4212 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4213 ssh2_pkt_addstring("password");
4214 ssh2_pkt_addbool(FALSE
);
4215 ssh2_pkt_addstring(password
);
4218 * We'll include a string that's an exact multiple of the
4219 * cipher block size. If the cipher is NULL for some
4220 * reason, we don't do this trick at all because we gain
4226 stringlen
= (256 - deferred_len
);
4227 stringlen
+= cscipher
->blksize
- 1;
4228 stringlen
-= (stringlen
% cscipher
->blksize
);
4231 * Temporarily disable actual compression,
4232 * so we can guarantee to get this string
4233 * exactly the length we want it. The
4234 * compression-disabling routine should
4235 * return an integer indicating how many
4236 * bytes we should adjust our string length
4239 stringlen
-= cscomp
->disable_compression();
4241 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4242 ssh2_pkt_addstring_start();
4243 for (i
= 0; i
< stringlen
; i
++) {
4244 char c
= (char) random_byte();
4245 ssh2_pkt_addstring_data(&c
, 1);
4249 ssh_pkt_defersend();
4250 logevent("Sent password");
4251 type
= AUTH_TYPE_PASSWORD
;
4252 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4253 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4254 ssh2_pkt_adduint32(num_prompts
);
4255 ssh2_pkt_addstring(password
);
4256 memset(password
, 0, sizeof(password
));
4258 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4261 ("No supported authentication methods left to try!\r\n");
4263 ("No supported authentications offered. Disconnecting");
4264 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4265 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4267 ("No supported authentication methods available");
4268 ssh2_pkt_addstring("en"); /* language tag */
4270 ssh_state
= SSH_STATE_CLOSED
;
4274 } while (!we_are_in
);
4277 * Now we're authenticated for the connection protocol. The
4278 * connection protocol will automatically have started at this
4279 * point; there's no need to send SERVICE_REQUEST.
4283 * So now create a channel with a session in it.
4285 ssh_channels
= newtree234(ssh_channelcmp
);
4286 mainchan
= smalloc(sizeof(struct ssh_channel
));
4287 mainchan
->localid
= alloc_channel_id();
4288 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4289 ssh2_pkt_addstring("session");
4290 ssh2_pkt_adduint32(mainchan
->localid
);
4291 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4292 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4293 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4295 crWaitUntilV(ispkt
);
4296 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4297 bombout(("Server refused to open a session"));
4299 /* FIXME: error data comes back in FAILURE packet */
4301 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4302 bombout(("Server's channel confirmation cited wrong channel"));
4305 mainchan
->remoteid
= ssh2_pkt_getuint32();
4306 mainchan
->type
= CHAN_MAINSESSION
;
4307 mainchan
->closes
= 0;
4308 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4309 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4310 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4311 add234(ssh_channels
, mainchan
);
4312 logevent("Opened channel for session");
4315 * Potentially enable X11 forwarding.
4317 if (cfg
.x11_forward
) {
4318 char proto
[20], data
[64];
4319 logevent("Requesting X11 forwarding");
4320 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4321 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4322 ssh2_pkt_adduint32(mainchan
->remoteid
);
4323 ssh2_pkt_addstring("x11-req");
4324 ssh2_pkt_addbool(1); /* want reply */
4325 ssh2_pkt_addbool(0); /* many connections */
4326 ssh2_pkt_addstring(proto
);
4327 ssh2_pkt_addstring(data
);
4328 ssh2_pkt_adduint32(0); /* screen number */
4332 crWaitUntilV(ispkt
);
4333 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4334 unsigned i
= ssh2_pkt_getuint32();
4335 struct ssh_channel
*c
;
4336 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4338 continue; /* nonexistent channel */
4339 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4341 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4343 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4344 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4345 bombout(("Server got confused by X11 forwarding request"));
4348 logevent("X11 forwarding refused");
4350 logevent("X11 forwarding enabled");
4351 ssh_X11_fwd_enabled
= TRUE
;
4356 * Enable port forwardings.
4359 static char *e
; /* preserve across crReturn */
4363 char sports
[256], dports
[256], host
[256];
4366 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4367 /* Add port forwardings. */
4372 while (*e
&& *e
!= '\t')
4378 while (*e
&& *e
!= ':')
4388 dport
= atoi(dports
);
4389 sport
= atoi(sports
);
4390 if (sport
&& dport
) {
4392 pfd_addforward(host
, dport
, sport
);
4393 sprintf(buf
, "Local port %d forwarding to %s:%d",
4394 sport
, host
, dport
);
4397 struct ssh_rportfwd
*pf
;
4398 pf
= smalloc(sizeof(*pf
));
4399 strcpy(pf
->dhost
, host
);
4402 if (add234(ssh_rportfwds
, pf
) != pf
) {
4404 "Duplicate remote port forwarding to %s:%d",
4409 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4410 sport
, host
, dport
);
4412 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4413 ssh2_pkt_addstring("tcpip-forward");
4414 ssh2_pkt_addbool(1);/* want reply */
4415 ssh2_pkt_addstring("127.0.0.1");
4416 ssh2_pkt_adduint32(sport
);
4420 crWaitUntilV(ispkt
);
4421 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4422 unsigned i
= ssh2_pkt_getuint32();
4423 struct ssh_channel
*c
;
4424 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4426 continue;/* nonexistent channel */
4427 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4429 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4431 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4432 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4433 bombout(("Server got confused by port forwarding request"));
4436 logevent("Server refused this port forwarding");
4438 logevent("Remote port forwarding enabled");
4447 * Potentially enable agent forwarding.
4449 if (cfg
.agentfwd
&& agent_exists()) {
4450 logevent("Requesting OpenSSH-style agent forwarding");
4451 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4452 ssh2_pkt_adduint32(mainchan
->remoteid
);
4453 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4454 ssh2_pkt_addbool(1); /* want reply */
4458 crWaitUntilV(ispkt
);
4459 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4460 unsigned i
= ssh2_pkt_getuint32();
4461 struct ssh_channel
*c
;
4462 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4464 continue; /* nonexistent channel */
4465 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4467 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4469 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4470 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4472 ("Server got confused by agent forwarding request"));
4475 logevent("Agent forwarding refused");
4477 logevent("Agent forwarding enabled");
4478 ssh_agentfwd_enabled
= TRUE
;
4483 * Now allocate a pty for the session.
4486 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4487 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4488 ssh2_pkt_addstring("pty-req");
4489 ssh2_pkt_addbool(1); /* want reply */
4490 ssh2_pkt_addstring(cfg
.termtype
);
4491 ssh2_pkt_adduint32(cols
);
4492 ssh2_pkt_adduint32(rows
);
4493 ssh2_pkt_adduint32(0); /* pixel width */
4494 ssh2_pkt_adduint32(0); /* pixel height */
4495 ssh2_pkt_addstring_start();
4496 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4498 ssh_state
= SSH_STATE_INTERMED
;
4501 crWaitUntilV(ispkt
);
4502 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4503 unsigned i
= ssh2_pkt_getuint32();
4504 struct ssh_channel
*c
;
4505 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4507 continue; /* nonexistent channel */
4508 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4510 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4512 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4513 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4514 bombout(("Server got confused by pty request"));
4517 c_write_str("Server refused to allocate pty\r\n");
4518 ssh_editing
= ssh_echoing
= 1;
4520 logevent("Allocated pty");
4523 ssh_editing
= ssh_echoing
= 1;
4527 * Start a shell or a remote command. We may have to attempt
4528 * this twice if the config data has provided a second choice
4535 if (ssh_fallback_cmd
) {
4536 subsys
= cfg
.ssh_subsys2
;
4537 cmd
= cfg
.remote_cmd_ptr2
;
4539 subsys
= cfg
.ssh_subsys
;
4540 cmd
= cfg
.remote_cmd_ptr
;
4543 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4544 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4546 ssh2_pkt_addstring("subsystem");
4547 ssh2_pkt_addbool(1); /* want reply */
4548 ssh2_pkt_addstring(cmd
);
4550 ssh2_pkt_addstring("exec");
4551 ssh2_pkt_addbool(1); /* want reply */
4552 ssh2_pkt_addstring(cmd
);
4554 ssh2_pkt_addstring("shell");
4555 ssh2_pkt_addbool(1); /* want reply */
4559 crWaitUntilV(ispkt
);
4560 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4561 unsigned i
= ssh2_pkt_getuint32();
4562 struct ssh_channel
*c
;
4563 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4565 continue; /* nonexistent channel */
4566 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4568 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4569 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4570 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4571 bombout(("Server got confused by shell/command request"));
4575 * We failed to start the command. If this is the
4576 * fallback command, we really are finished; if it's
4577 * not, and if the fallback command exists, try falling
4578 * back to it before complaining.
4580 if (!ssh_fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
4581 logevent("Primary command failed; attempting fallback");
4582 ssh_fallback_cmd
= TRUE
;
4585 bombout(("Server refused to start a shell/command"));
4588 logevent("Started a shell/command");
4593 ssh_state
= SSH_STATE_SESSION
;
4597 ssh_special(TS_EOF
);
4602 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
4605 static int try_send
;
4609 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4610 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4613 unsigned i
= ssh2_pkt_getuint32();
4614 struct ssh_channel
*c
;
4615 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4617 continue; /* nonexistent channel */
4618 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4619 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4620 continue; /* extended but not stderr */
4621 ssh2_pkt_getstring(&data
, &length
);
4624 c
->v
.v2
.locwindow
-= length
;
4626 case CHAN_MAINSESSION
:
4628 from_backend(pktin
.type
==
4629 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
4633 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
4636 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
4639 while (length
> 0) {
4640 if (c
->u
.a
.lensofar
< 4) {
4641 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4642 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4646 c
->u
.a
.lensofar
+= l
;
4648 if (c
->u
.a
.lensofar
== 4) {
4650 4 + GET_32BIT(c
->u
.a
.msglen
);
4651 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4652 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4654 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4656 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4658 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4662 c
->u
.a
.lensofar
+= l
;
4664 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4665 void *reply
, *sentreply
;
4667 agent_query(c
->u
.a
.message
,
4668 c
->u
.a
.totallen
, &reply
,
4673 /* Fake SSH_AGENT_FAILURE. */
4674 sentreply
= "\0\0\0\1\5";
4677 ssh2_add_channel_data(c
, sentreply
,
4682 sfree(c
->u
.a
.message
);
4683 c
->u
.a
.lensofar
= 0;
4690 * If we are not buffering too much data,
4691 * enlarge the window again at the remote side.
4693 if (bufsize
< OUR_V2_WINSIZE
)
4694 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
4696 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4697 ssh_state
= SSH_STATE_CLOSED
;
4698 logevent("Received disconnect message");
4700 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4701 continue; /* exit status et al; ignore (FIXME?) */
4702 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4703 unsigned i
= ssh2_pkt_getuint32();
4704 struct ssh_channel
*c
;
4706 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4708 continue; /* nonexistent channel */
4710 if (c
->type
== CHAN_X11
) {
4712 * Remote EOF on an X11 channel means we should
4713 * wrap up and close the channel ourselves.
4715 x11_close(c
->u
.x11
.s
);
4717 } else if (c
->type
== CHAN_AGENT
) {
4719 } else if (c
->type
== CHAN_SOCKDATA
) {
4720 pfd_close(c
->u
.pfd
.s
);
4723 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4724 unsigned i
= ssh2_pkt_getuint32();
4725 struct ssh_channel
*c
;
4727 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4729 continue; /* nonexistent channel */
4730 /* Do pre-close processing on the channel. */
4732 case CHAN_MAINSESSION
:
4733 break; /* nothing to see here, move along */
4735 if (c
->u
.x11
.s
!= NULL
)
4736 x11_close(c
->u
.x11
.s
);
4743 if (c
->u
.pfd
.s
!= NULL
)
4744 pfd_close(c
->u
.pfd
.s
);
4748 if (c
->closes
== 0) {
4749 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4750 ssh2_pkt_adduint32(c
->remoteid
);
4753 del234(ssh_channels
, c
);
4754 bufchain_clear(&c
->v
.v2
.outbuffer
);
4758 * See if that was the last channel left open.
4760 if (count234(ssh_channels
) == 0) {
4761 logevent("All channels closed. Disconnecting");
4762 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4763 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4764 ssh2_pkt_addstring("All open channels closed");
4765 ssh2_pkt_addstring("en"); /* language tag */
4767 ssh_state
= SSH_STATE_CLOSED
;
4770 continue; /* remote sends close; ignore (FIXME) */
4771 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4772 unsigned i
= ssh2_pkt_getuint32();
4773 struct ssh_channel
*c
;
4774 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4776 continue; /* nonexistent channel */
4777 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4779 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4780 unsigned i
= ssh2_pkt_getuint32();
4781 struct ssh_channel
*c
;
4782 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4784 continue; /* nonexistent channel */
4785 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4786 continue; /* dunno why they're confirming this */
4787 c
->remoteid
= ssh2_pkt_getuint32();
4788 c
->type
= CHAN_SOCKDATA
;
4790 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4791 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4792 bufchain_init(&c
->v
.v2
.outbuffer
);
4793 pfd_confirm(c
->u
.pfd
.s
);
4794 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
4795 unsigned i
= ssh2_pkt_getuint32();
4796 struct ssh_channel
*c
;
4797 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4799 continue; /* nonexistent channel */
4800 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4801 continue; /* dunno why they're failing this */
4803 logevent("Forwarded connection refused by server");
4805 pfd_close(c
->u
.pfd
.s
);
4807 del234(ssh_channels
, c
);
4809 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4813 struct ssh_channel
*c
;
4814 unsigned remid
, winsize
, pktsize
;
4815 ssh2_pkt_getstring(&type
, &typelen
);
4816 c
= smalloc(sizeof(struct ssh_channel
));
4818 remid
= ssh2_pkt_getuint32();
4819 winsize
= ssh2_pkt_getuint32();
4820 pktsize
= ssh2_pkt_getuint32();
4822 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4823 if (!ssh_X11_fwd_enabled
)
4824 error
= "X11 forwarding is not enabled";
4825 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4827 error
= "Unable to open an X11 connection";
4831 } else if (typelen
== 15 &&
4832 !memcmp(type
, "forwarded-tcpip", 15)) {
4833 struct ssh_rportfwd pf
, *realpf
;
4836 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
4837 pf
.sport
= ssh2_pkt_getuint32();
4838 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
4839 if (realpf
== NULL
) {
4840 error
= "Remote port is not recognised";
4842 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
4845 sprintf(buf
, "Received remote port open request for %s:%d",
4846 realpf
->dhost
, realpf
->dport
);
4849 sprintf(buf
, "Port open failed: %s", e
);
4851 error
= "Port open failed";
4853 logevent("Forwarded port opened successfully");
4854 c
->type
= CHAN_SOCKDATA
;
4857 } else if (typelen
== 22 &&
4858 !memcmp(type
, "auth-agent@openssh.com", 3)) {
4859 if (!ssh_agentfwd_enabled
)
4860 error
= "Agent forwarding is not enabled";
4862 c
->type
= CHAN_AGENT
; /* identify channel type */
4863 c
->u
.a
.lensofar
= 0;
4866 error
= "Unsupported channel type requested";
4869 c
->remoteid
= remid
;
4871 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
4872 ssh2_pkt_adduint32(c
->remoteid
);
4873 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
4874 ssh2_pkt_addstring(error
);
4875 ssh2_pkt_addstring("en"); /* language tag */
4879 c
->localid
= alloc_channel_id();
4881 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4882 c
->v
.v2
.remwindow
= winsize
;
4883 c
->v
.v2
.remmaxpkt
= pktsize
;
4884 bufchain_init(&c
->v
.v2
.outbuffer
);
4885 add234(ssh_channels
, c
);
4886 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
4887 ssh2_pkt_adduint32(c
->remoteid
);
4888 ssh2_pkt_adduint32(c
->localid
);
4889 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
4890 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4894 bombout(("Strange packet received: type %d", pktin
.type
));
4899 * We have spare data. Add it to the channel buffer.
4901 ssh2_add_channel_data(mainchan
, in
, inlen
);
4906 struct ssh_channel
*c
;
4908 * Try to send data on all channels if we can.
4910 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
4911 int bufsize
= ssh2_try_send(c
);
4914 case CHAN_MAINSESSION
:
4915 /* stdin need not receive an unthrottle
4916 * notification since it will be polled */
4919 x11_unthrottle(c
->u
.x11
.s
);
4922 /* agent sockets are request/response and need no
4923 * buffer management */
4926 pfd_unthrottle(c
->u
.pfd
.s
);
4938 * Handle the top-level SSH2 protocol.
4940 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
4942 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
4944 do_ssh2_authconn(in
, inlen
, ispkt
);
4948 * Called to set up the connection.
4950 * Returns an error message, or NULL on success.
4952 static char *ssh_init(char *host
, int port
, char **realhost
)
4957 if (crypto_startup() == 0)
4958 return "Microsoft high encryption pack not installed!";
4964 ssh1_throttle_count
= 0;
4965 ssh_overall_bufsize
= 0;
4966 ssh_fallback_cmd
= 0;
4968 p
= connect_to_host(host
, port
, realhost
);
4976 * Called to send data down the Telnet connection.
4978 static int ssh_send(char *buf
, int len
)
4980 if (s
== NULL
|| ssh_protocol
== NULL
)
4983 ssh_protocol(buf
, len
, 0);
4985 return ssh_sendbuffer();
4989 * Called to query the current amount of buffered stdin data.
4991 static int ssh_sendbuffer(void)
4995 if (s
== NULL
|| ssh_protocol
== NULL
)
4999 * If the SSH socket itself has backed up, add the total backup
5000 * size on that to any individual buffer on the stdin channel.
5003 if (ssh_throttled_all
)
5004 override_value
= ssh_overall_bufsize
;
5006 if (ssh_version
== 1) {
5007 return override_value
;
5008 } else if (ssh_version
== 2) {
5009 if (!mainchan
|| mainchan
->closes
> 0)
5010 return override_value
;
5012 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
5019 * Called to set the size of the window from SSH's POV.
5021 static void ssh_size(void)
5023 switch (ssh_state
) {
5024 case SSH_STATE_BEFORE_SIZE
:
5025 case SSH_STATE_PREPACKET
:
5026 case SSH_STATE_CLOSED
:
5027 break; /* do nothing */
5028 case SSH_STATE_INTERMED
:
5029 size_needed
= TRUE
; /* buffer for later */
5031 case SSH_STATE_SESSION
:
5033 if (ssh_version
== 1) {
5034 send_packet(SSH1_CMSG_WINDOW_SIZE
,
5035 PKT_INT
, rows
, PKT_INT
, cols
,
5036 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5038 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5039 ssh2_pkt_adduint32(mainchan
->remoteid
);
5040 ssh2_pkt_addstring("window-change");
5041 ssh2_pkt_addbool(0);
5042 ssh2_pkt_adduint32(cols
);
5043 ssh2_pkt_adduint32(rows
);
5044 ssh2_pkt_adduint32(0);
5045 ssh2_pkt_adduint32(0);
5054 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5055 * can send an EOF and collect resulting output (e.g. `plink
5058 static void ssh_special(Telnet_Special code
)
5060 if (code
== TS_EOF
) {
5061 if (ssh_state
!= SSH_STATE_SESSION
) {
5063 * Buffer the EOF in case we are pre-SESSION, so we can
5064 * send it as soon as we reach SESSION.
5070 if (ssh_version
== 1) {
5071 send_packet(SSH1_CMSG_EOF
, PKT_END
);
5073 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
5074 ssh2_pkt_adduint32(mainchan
->remoteid
);
5077 logevent("Sent EOF message");
5078 } else if (code
== TS_PING
) {
5079 if (ssh_state
== SSH_STATE_CLOSED
5080 || ssh_state
== SSH_STATE_PREPACKET
) return;
5081 if (ssh_version
== 1) {
5082 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5084 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5085 ssh2_pkt_addstring_start();
5093 void *new_sock_channel(Socket s
)
5095 struct ssh_channel
*c
;
5096 c
= smalloc(sizeof(struct ssh_channel
));
5099 c
->remoteid
= -1; /* to be set when open confirmed */
5100 c
->localid
= alloc_channel_id();
5102 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5104 add234(ssh_channels
, c
);
5110 * This is called when stdout/stderr (the entity to which
5111 * from_backend sends data) manages to clear some backlog.
5113 void ssh_unthrottle(int bufsize
)
5115 if (ssh_version
== 1) {
5116 if (bufsize
< SSH1_BUFFER_LIMIT
) {
5117 ssh1_stdout_throttling
= 0;
5121 if (mainchan
&& mainchan
->closes
== 0)
5122 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5126 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5128 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5131 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5134 if (ssh_version
== 1) {
5135 send_packet(SSH1_MSG_PORT_OPEN
,
5136 PKT_INT
, c
->localid
,
5139 //PKT_STR, <org:orgport>,
5142 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5143 ssh2_pkt_addstring("direct-tcpip");
5144 ssh2_pkt_adduint32(c
->localid
);
5145 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5146 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5147 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5148 ssh2_pkt_addstring(hostname
);
5149 ssh2_pkt_adduint32(port
);
5151 * We make up values for the originator data; partly it's
5152 * too much hassle to keep track, and partly I'm not
5153 * convinced the server should be told details like that
5154 * about my local network configuration.
5156 ssh2_pkt_addstring("client-side-connection");
5157 ssh2_pkt_adduint32(0);
5163 static Socket
ssh_socket(void)
5168 static int ssh_sendok(void)
5173 static int ssh_ldisc(int option
)
5175 if (option
== LD_ECHO
)
5177 if (option
== LD_EDIT
)
5182 Backend ssh_backend
= {