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
162 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
165 #define GET_32BIT(cp) \
166 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
167 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
168 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
169 ((unsigned long)(unsigned char)(cp)[3]))
171 #define PUT_32BIT(cp, value) { \
172 (cp)[0] = (unsigned char)((value) >> 24); \
173 (cp)[1] = (unsigned char)((value) >> 16); \
174 (cp)[2] = (unsigned char)((value) >> 8); \
175 (cp)[3] = (unsigned char)(value); }
177 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
179 /* Coroutine mechanics for the sillier bits of the code */
180 #define crBegin1 static int crLine = 0;
181 #define crBegin2 switch(crLine) { case 0:;
182 #define crBegin crBegin1; crBegin2;
183 #define crFinish(z) } crLine = 0; return (z)
184 #define crFinishV } crLine = 0; return
185 #define crReturn(z) \
187 crLine=__LINE__; return (z); case __LINE__:;\
191 crLine=__LINE__; return; case __LINE__:;\
193 #define crStop(z) do{ crLine = 0; return (z); }while(0)
194 #define crStopV do{ crLine = 0; return; }while(0)
195 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
196 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
198 extern char *x11_init(Socket
*, char *, void *);
199 extern void x11_close(Socket
);
200 extern int x11_send(Socket
, char *, int);
201 extern void x11_invent_auth(char *, int, char *, int);
202 extern void x11_unthrottle(Socket s
);
203 extern void x11_override_throttle(Socket s
, int enable
);
205 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
206 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
207 extern void pfd_close(Socket s
);
208 extern int pfd_send(Socket s
, char *data
, int len
);
209 extern void pfd_confirm(Socket s
);
210 extern void pfd_unthrottle(Socket s
);
211 extern void pfd_override_throttle(Socket s
, int enable
);
214 * Buffer management constants. There are several of these for
215 * various different purposes:
217 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
218 * on a local data stream before we throttle the whole SSH
219 * connection (in SSH1 only). Throttling the whole connection is
220 * pretty drastic so we set this high in the hope it won't
223 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
224 * on the SSH connection itself before we defensively throttle
225 * _all_ local data streams. This is pretty drastic too (though
226 * thankfully unlikely in SSH2 since the window mechanism should
227 * ensure that the server never has any need to throttle its end
228 * of the connection), so we set this high as well.
230 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
234 #define SSH1_BUFFER_LIMIT 32768
235 #define SSH_MAX_BACKLOG 32768
236 #define OUR_V2_WINSIZE 16384
239 * Ciphers for SSH2. We miss out single-DES because it isn't
240 * supported; also 3DES and Blowfish are both done differently from
241 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
242 * endianness and different-sized keys.)
244 const static struct ssh2_ciphers
*ciphers
[] = {
250 const static struct ssh_kex
*kex_algs
[] = {
251 &ssh_diffiehellman_gex
,
255 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
257 static void nullmac_key(unsigned char *key
)
260 static void nullmac_generate(unsigned char *blk
, int len
,
264 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
268 const static struct ssh_mac ssh_mac_none
= {
269 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
271 const static struct ssh_mac
*macs
[] = {
272 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
274 const static struct ssh_mac
*buggymacs
[] = {
275 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
278 static void ssh_comp_none_init(void)
281 static int ssh_comp_none_block(unsigned char *block
, int len
,
282 unsigned char **outblock
, int *outlen
)
286 static int ssh_comp_none_disable(void)
290 const static struct ssh_compress ssh_comp_none
= {
292 ssh_comp_none_init
, ssh_comp_none_block
,
293 ssh_comp_none_init
, ssh_comp_none_block
,
294 ssh_comp_none_disable
296 extern const struct ssh_compress ssh_zlib
;
297 const static struct ssh_compress
*compressions
[] = {
298 &ssh_zlib
, &ssh_comp_none
301 enum { /* channel types */
306 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
310 * 2-3-4 tree storing channels.
313 unsigned remoteid
, localid
;
317 struct ssh1_data_channel
{
320 struct ssh2_data_channel
{
322 unsigned remwindow
, remmaxpkt
;
327 struct ssh_agent_channel
{
328 unsigned char *message
;
329 unsigned char msglen
[4];
330 int lensofar
, totallen
;
332 struct ssh_x11_channel
{
335 struct ssh_pfd_channel
{
342 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
343 * 2 use this structure in different ways, reflecting SSH 2's
344 * altogether saner approach to port forwarding.
346 * In SSH 1, you arrange a remote forwarding by sending the server
347 * the remote port number, and the local destination host:port.
348 * When a connection comes in, the server sends you back that
349 * host:port pair, and you connect to it. This is a ready-made
350 * security hole if you're not on the ball: a malicious server
351 * could send you back _any_ host:port pair, so if you trustingly
352 * connect to the address it gives you then you've just opened the
353 * entire inside of your corporate network just by connecting
354 * through it to a dodgy SSH server. Hence, we must store a list of
355 * host:port pairs we _are_ trying to forward to, and reject a
356 * connection request from the server if it's not in the list.
358 * In SSH 2, each side of the connection minds its own business and
359 * doesn't send unnecessary information to the other. You arrange a
360 * remote forwarding by sending the server just the remote port
361 * number. When a connection comes in, the server tells you which
362 * of its ports was connected to; and _you_ have to remember what
363 * local host:port pair went with that port number.
365 * Hence: in SSH 1 this structure stores host:port pairs we intend
366 * to allow connections to, and is indexed by those host:port
367 * pairs. In SSH 2 it stores a mapping from source port to
368 * destination host:port pair, and is indexed by source port.
370 struct ssh_rportfwd
{
371 unsigned sport
, dport
;
384 static SHA_State exhash
, exhashbase
;
386 static Socket s
= NULL
;
388 static unsigned char session_key
[32];
389 static int ssh1_compressing
;
390 static int ssh1_remote_protoflags
;
391 static int ssh1_local_protoflags
;
392 static int ssh_agentfwd_enabled
;
393 static int ssh_X11_fwd_enabled
;
394 static int ssh_remote_bugs
;
395 static const struct ssh_cipher
*cipher
= NULL
;
396 static const struct ssh2_cipher
*cscipher
= NULL
;
397 static const struct ssh2_cipher
*sccipher
= NULL
;
398 static const struct ssh_mac
*csmac
= NULL
;
399 static const struct ssh_mac
*scmac
= NULL
;
400 static const struct ssh_compress
*cscomp
= NULL
;
401 static const struct ssh_compress
*sccomp
= NULL
;
402 static const struct ssh_kex
*kex
= NULL
;
403 static const struct ssh_signkey
*hostkey
= NULL
;
404 static unsigned char ssh2_session_id
[20];
405 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
408 static char *savedhost
;
409 static int savedport
;
410 static int ssh_send_ok
;
411 static int ssh_echoing
, ssh_editing
;
413 static tree234
*ssh_channels
; /* indexed by local id */
414 static struct ssh_channel
*mainchan
; /* primary session channel */
416 static tree234
*ssh_rportfwds
;
420 SSH_STATE_BEFORE_SIZE
,
424 } ssh_state
= SSH_STATE_PREPACKET
;
426 static int size_needed
= FALSE
, eof_needed
= FALSE
;
428 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
429 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
430 static unsigned char *deferred_send_data
= NULL
;
431 static int deferred_len
= 0, deferred_size
= 0;
434 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
435 * that fails. This variable is the means by which scp.c can reach
436 * into the SSH code and find out which one it got.
438 int ssh_fallback_cmd
= 0;
440 static int ssh_version
;
441 static int ssh1_throttle_count
;
442 static int ssh_overall_bufsize
;
443 static int ssh_throttled_all
;
444 static int ssh1_stdout_throttling
;
445 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
446 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
447 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
448 static void ssh_size(void);
449 static void ssh_special(Telnet_Special
);
450 static int ssh2_try_send(struct ssh_channel
*c
);
451 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
453 static void ssh_throttle_all(int enable
, int bufsize
);
454 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
455 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
456 static int ssh_sendbuffer(void);
458 static struct rdpkt1_state_tag
{
459 long len
, pad
, biglen
, to_read
;
460 unsigned long realcrc
, gotcrc
;
466 static struct rdpkt2_state_tag
{
467 long len
, pad
, payload
, packetlen
, maclen
;
470 unsigned long incoming_sequence
;
473 static int ssh_channelcmp(void *av
, void *bv
)
475 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
476 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
477 if (a
->localid
< b
->localid
)
479 if (a
->localid
> b
->localid
)
483 static int ssh_channelfind(void *av
, void *bv
)
485 unsigned *a
= (unsigned *) av
;
486 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
494 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
496 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
497 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
499 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
500 return i
< 0 ?
-1 : +1;
501 if (a
->dport
> b
->dport
)
503 if (a
->dport
< b
->dport
)
508 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
510 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
511 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
513 if (a
->sport
> b
->sport
)
515 if (a
->sport
< b
->sport
)
520 static int alloc_channel_id(void)
522 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
523 unsigned low
, high
, mid
;
525 struct ssh_channel
*c
;
528 * First-fit allocation of channel numbers: always pick the
529 * lowest unused one. To do this, binary-search using the
530 * counted B-tree to find the largest channel ID which is in a
531 * contiguous sequence from the beginning. (Precisely
532 * everything in that sequence must have ID equal to its tree
533 * index plus CHANNEL_NUMBER_OFFSET.)
535 tsize
= count234(ssh_channels
);
539 while (high
- low
> 1) {
540 mid
= (high
+ low
) / 2;
541 c
= index234(ssh_channels
, mid
);
542 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
543 low
= mid
; /* this one is fine */
545 high
= mid
; /* this one is past it */
548 * Now low points to either -1, or the tree index of the
549 * largest ID in the initial sequence.
552 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
553 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
555 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
558 static void c_write(char *buf
, int len
)
560 if ((flags
& FLAG_STDERR
)) {
562 for (i
= 0; i
< len
; i
++)
564 fputc(buf
[i
], stderr
);
567 from_backend(1, buf
, len
);
570 static void c_write_untrusted(char *buf
, int len
)
573 for (i
= 0; i
< len
; i
++) {
576 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
581 static void c_write_str(char *buf
)
583 c_write(buf
, strlen(buf
));
587 * Collect incoming data in the incoming packet buffer.
588 * Decipher and verify the packet when it is completely read.
589 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
590 * Update the *data and *datalen variables.
591 * Return the additional nr of bytes needed, or 0 when
592 * a complete packet is available.
594 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
596 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
605 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
606 while ((*datalen
) == 0)
608 st
->len
= (st
->len
<< 8) + **data
;
609 (*data
)++, (*datalen
)--;
612 st
->pad
= 8 - (st
->len
% 8);
613 st
->biglen
= st
->len
+ st
->pad
;
614 pktin
.length
= st
->len
- 5;
616 if (pktin
.maxlen
< st
->biglen
) {
617 pktin
.maxlen
= st
->biglen
;
618 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
619 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
621 fatalbox("Out of memory");
624 st
->to_read
= st
->biglen
;
626 while (st
->to_read
> 0) {
627 st
->chunk
= st
->to_read
;
628 while ((*datalen
) == 0)
629 crReturn(st
->to_read
);
630 if (st
->chunk
> (*datalen
))
631 st
->chunk
= (*datalen
);
632 memcpy(st
->p
, *data
, st
->chunk
);
634 *datalen
-= st
->chunk
;
636 st
->to_read
-= st
->chunk
;
640 cipher
->decrypt(pktin
.data
, st
->biglen
);
642 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
643 dmemdump(pktin
.data
, st
->biglen
);
646 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
647 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
648 if (st
->gotcrc
!= st
->realcrc
) {
649 bombout(("Incorrect CRC received on packet"));
653 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
655 if (ssh1_compressing
) {
656 unsigned char *decompblk
;
659 debug(("Packet payload pre-decompression:\n"));
660 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
662 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
663 &decompblk
, &decomplen
);
665 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
666 pktin
.maxlen
= st
->pad
+ decomplen
;
667 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
668 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
670 fatalbox("Out of memory");
673 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
675 pktin
.length
= decomplen
- 1;
677 debug(("Packet payload post-decompression:\n"));
678 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
682 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
683 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
684 pktin
.type
== SSH1_MSG_DEBUG
||
685 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
686 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
687 long strlen
= GET_32BIT(pktin
.body
);
688 if (strlen
+ 4 != pktin
.length
) {
689 bombout(("Received data packet with bogus string length"));
694 pktin
.type
= pktin
.body
[-1];
696 if (pktin
.type
== SSH1_MSG_DEBUG
) {
697 /* log debug message */
699 int strlen
= GET_32BIT(pktin
.body
);
700 strcpy(buf
, "Remote: ");
703 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
704 buf
[8 + strlen
] = '\0';
707 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
712 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
713 /* log reason code in disconnect message */
715 unsigned msglen
= GET_32BIT(pktin
.body
);
717 strcpy(buf
, "Remote sent disconnect: ");
718 nowlen
= strlen(buf
);
719 if (msglen
> sizeof(buf
) - nowlen
- 1)
720 msglen
= sizeof(buf
) - nowlen
- 1;
721 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
722 buf
[nowlen
+ msglen
] = '\0';
724 bombout(("Server sent disconnect message:\n\"%s\"", buf
+nowlen
));
731 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
733 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
741 st
->cipherblk
= sccipher
->blksize
;
744 if (st
->cipherblk
< 8)
747 if (pktin
.maxlen
< st
->cipherblk
) {
748 pktin
.maxlen
= st
->cipherblk
;
751 NULL ?
smalloc(st
->cipherblk
+
752 APIEXTRA
) : srealloc(pktin
.data
,
756 fatalbox("Out of memory");
760 * Acquire and decrypt the first block of the packet. This will
761 * contain the length and padding details.
763 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
764 while ((*datalen
) == 0)
765 crReturn(st
->cipherblk
- st
->i
);
766 pktin
.data
[st
->i
] = *(*data
)++;
771 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
774 * Now get the length and padding figures.
776 st
->len
= GET_32BIT(pktin
.data
);
777 st
->pad
= pktin
.data
[4];
780 * This enables us to deduce the payload length.
782 st
->payload
= st
->len
- st
->pad
- 1;
784 pktin
.length
= st
->payload
+ 5;
787 * So now we can work out the total packet length.
789 st
->packetlen
= st
->len
+ 4;
790 st
->maclen
= scmac ? scmac
->len
: 0;
793 * Adjust memory allocation if packet is too big.
795 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
796 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
799 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
804 fatalbox("Out of memory");
808 * Read and decrypt the remainder of the packet.
810 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
812 while ((*datalen
) == 0)
813 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
814 pktin
.data
[st
->i
] = *(*data
)++;
817 /* Decrypt everything _except_ the MAC. */
819 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
820 st
->packetlen
- st
->cipherblk
);
823 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
824 dmemdump(pktin
.data
, st
->packetlen
);
831 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
832 st
->incoming_sequence
)) {
833 bombout(("Incorrect MAC received on packet"));
836 st
->incoming_sequence
++; /* whether or not we MACed */
839 * Decompress packet payload.
842 unsigned char *newpayload
;
844 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
845 &newpayload
, &newlen
)) {
846 if (pktin
.maxlen
< newlen
+ 5) {
847 pktin
.maxlen
= newlen
+ 5;
850 NULL ?
smalloc(pktin
.maxlen
+
851 APIEXTRA
) : srealloc(pktin
.data
,
855 fatalbox("Out of memory");
857 pktin
.length
= 5 + newlen
;
858 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
860 debug(("Post-decompression payload:\n"));
861 dmemdump(pktin
.data
+ 5, newlen
);
869 pktin
.type
= pktin
.data
[5];
871 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
872 goto next_packet
; /* FIXME: print DEBUG message */
874 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
875 /* log reason code in disconnect message */
877 int reason
= GET_32BIT(pktin
.data
+ 6);
878 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
880 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
881 sprintf(buf
, "Received disconnect message (%s)",
882 ssh2_disconnect_reasons
[reason
]);
884 sprintf(buf
, "Received disconnect message (unknown type %d)",
888 strcpy(buf
, "Disconnection message text: ");
889 nowlen
= strlen(buf
);
890 if (msglen
> sizeof(buf
) - nowlen
- 1)
891 msglen
= sizeof(buf
) - nowlen
- 1;
892 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
893 buf
[nowlen
+ msglen
] = '\0';
895 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
897 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
898 ssh2_disconnect_reasons
[reason
] : "unknown",
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
;
945 if (ssh1_compressing
) {
946 unsigned char *compblk
;
949 debug(("Packet payload pre-compression:\n"));
950 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
952 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
954 ssh1_pktout_size(complen
- 1);
955 memcpy(pktout
.body
- 1, compblk
, complen
);
959 len
= pktout
.length
+ 5; /* type and CRC */
963 for (i
= 0; i
< pad
; i
++)
964 pktout
.data
[i
+ 4] = random_byte();
965 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
966 PUT_32BIT(pktout
.data
+ biglen
, crc
);
967 PUT_32BIT(pktout
.data
, len
);
970 debug(("Sending packet len=%d\n", biglen
+ 4));
971 dmemdump(pktout
.data
, biglen
+ 4);
974 cipher
->encrypt(pktout
.data
+ 4, biglen
);
979 static void s_wrpkt(void)
982 len
= s_wrpkt_prepare();
983 backlog
= sk_write(s
, pktout
.data
, len
);
984 if (backlog
> SSH_MAX_BACKLOG
)
985 ssh_throttle_all(1, backlog
);
988 static void s_wrpkt_defer(void)
991 len
= s_wrpkt_prepare();
992 if (deferred_len
+ len
> deferred_size
) {
993 deferred_size
= deferred_len
+ len
+ 128;
994 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
996 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1001 * Construct a packet with the specified contents.
1003 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1005 unsigned char *p
, *argp
, argchar
;
1006 unsigned long argint
;
1007 int pktlen
, argtype
, arglen
;
1011 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1014 (void) va_arg(ap1
, int);
1018 (void) va_arg(ap1
, char);
1022 (void) va_arg(ap1
, unsigned char *);
1023 arglen
= va_arg(ap1
, int);
1027 argp
= va_arg(ap1
, unsigned char *);
1028 arglen
= strlen(argp
);
1029 pktlen
+= 4 + arglen
;
1032 bn
= va_arg(ap1
, Bignum
);
1033 pktlen
+= ssh1_bignum_length(bn
);
1040 s_wrpkt_start(pkttype
, pktlen
);
1043 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1046 argint
= va_arg(ap2
, int);
1047 PUT_32BIT(p
, argint
);
1051 argchar
= va_arg(ap2
, unsigned char);
1056 argp
= va_arg(ap2
, unsigned char *);
1057 arglen
= va_arg(ap2
, int);
1058 memcpy(p
, argp
, arglen
);
1062 argp
= va_arg(ap2
, unsigned char *);
1063 arglen
= strlen(argp
);
1064 PUT_32BIT(p
, arglen
);
1065 memcpy(p
+ 4, argp
, arglen
);
1069 bn
= va_arg(ap2
, Bignum
);
1070 p
+= ssh1_write_bignum(p
, bn
);
1076 static void send_packet(int pkttype
, ...)
1079 va_start(ap1
, pkttype
);
1080 va_start(ap2
, pkttype
);
1081 construct_packet(pkttype
, ap1
, ap2
);
1085 static void defer_packet(int pkttype
, ...)
1088 va_start(ap1
, pkttype
);
1089 va_start(ap2
, pkttype
);
1090 construct_packet(pkttype
, ap1
, ap2
);
1094 static int ssh_versioncmp(char *a
, char *b
)
1097 unsigned long av
, bv
;
1099 av
= strtoul(a
, &ae
, 10);
1100 bv
= strtoul(b
, &be
, 10);
1102 return (av
< bv ?
-1 : +1);
1107 av
= strtoul(ae
, &ae
, 10);
1108 bv
= strtoul(be
, &be
, 10);
1110 return (av
< bv ?
-1 : +1);
1116 * Utility routines for putting an SSH-protocol `string' and
1117 * `uint32' into a SHA state.
1120 static void sha_string(SHA_State
* s
, void *str
, int len
)
1122 unsigned char lenblk
[4];
1123 PUT_32BIT(lenblk
, len
);
1124 SHA_Bytes(s
, lenblk
, 4);
1125 SHA_Bytes(s
, str
, len
);
1128 static void sha_uint32(SHA_State
* s
, unsigned i
)
1130 unsigned char intblk
[4];
1131 PUT_32BIT(intblk
, i
);
1132 SHA_Bytes(s
, intblk
, 4);
1136 * SSH2 packet construction functions.
1138 static void ssh2_pkt_ensure(int length
)
1140 if (pktout
.maxlen
< length
) {
1141 pktout
.maxlen
= length
+ 256;
1144 NULL ?
smalloc(pktout
.maxlen
+
1145 APIEXTRA
) : srealloc(pktout
.data
,
1149 fatalbox("Out of memory");
1152 static void ssh2_pkt_adddata(void *data
, int len
)
1154 pktout
.length
+= len
;
1155 ssh2_pkt_ensure(pktout
.length
);
1156 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1158 static void ssh2_pkt_addbyte(unsigned char byte
)
1160 ssh2_pkt_adddata(&byte
, 1);
1162 static void ssh2_pkt_init(int pkt_type
)
1165 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1167 static void ssh2_pkt_addbool(unsigned char value
)
1169 ssh2_pkt_adddata(&value
, 1);
1171 static void ssh2_pkt_adduint32(unsigned long value
)
1174 PUT_32BIT(x
, value
);
1175 ssh2_pkt_adddata(x
, 4);
1177 static void ssh2_pkt_addstring_start(void)
1179 ssh2_pkt_adduint32(0);
1180 pktout
.savedpos
= pktout
.length
;
1182 static void ssh2_pkt_addstring_str(char *data
)
1184 ssh2_pkt_adddata(data
, strlen(data
));
1185 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1186 pktout
.length
- pktout
.savedpos
);
1188 static void ssh2_pkt_addstring_data(char *data
, int len
)
1190 ssh2_pkt_adddata(data
, len
);
1191 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1192 pktout
.length
- pktout
.savedpos
);
1194 static void ssh2_pkt_addstring(char *data
)
1196 ssh2_pkt_addstring_start();
1197 ssh2_pkt_addstring_str(data
);
1199 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1202 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1205 fatalbox("out of memory");
1207 for (i
= 1; i
<= n
; i
++)
1208 p
[i
] = bignum_byte(b
, n
- i
);
1210 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1212 memmove(p
, p
+ i
, n
+ 1 - i
);
1216 static void ssh2_pkt_addmp(Bignum b
)
1220 p
= ssh2_mpint_fmt(b
, &len
);
1221 ssh2_pkt_addstring_start();
1222 ssh2_pkt_addstring_data(p
, len
);
1227 * Construct an SSH2 final-form packet: compress it, encrypt it,
1228 * put the MAC on it. Final packet, ready to be sent, is stored in
1229 * pktout.data. Total length is returned.
1231 static int ssh2_pkt_construct(void)
1233 int cipherblk
, maclen
, padding
, i
;
1234 static unsigned long outgoing_sequence
= 0;
1237 * Compress packet payload.
1240 unsigned char *newpayload
;
1243 if (cscomp
&& cscomp
!= &ssh_comp_none
) {
1244 debug(("Pre-compression payload:\n"));
1245 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1248 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1249 &newpayload
, &newlen
)) {
1251 ssh2_pkt_adddata(newpayload
, newlen
);
1257 * Add padding. At least four bytes, and must also bring total
1258 * length (minus MAC) up to a multiple of the block size.
1260 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1261 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1264 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1265 maclen
= csmac ? csmac
->len
: 0;
1266 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1267 pktout
.data
[4] = padding
;
1268 for (i
= 0; i
< padding
; i
++)
1269 pktout
.data
[pktout
.length
+ i
] = random_byte();
1270 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1272 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1274 outgoing_sequence
++; /* whether or not we MACed */
1277 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1278 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1282 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1284 /* Ready-to-send packet starts at pktout.data. We return length. */
1285 return pktout
.length
+ padding
+ maclen
;
1289 * Construct and send an SSH2 packet immediately.
1291 static void ssh2_pkt_send(void)
1295 len
= ssh2_pkt_construct();
1296 backlog
= sk_write(s
, pktout
.data
, len
);
1297 if (backlog
> SSH_MAX_BACKLOG
)
1298 ssh_throttle_all(1, backlog
);
1302 * Construct an SSH2 packet and add it to a deferred data block.
1303 * Useful for sending multiple packets in a single sk_write() call,
1304 * to prevent a traffic-analysing listener from being able to work
1305 * out the length of any particular packet (such as the password
1308 * Note that because SSH2 sequence-numbers its packets, this can
1309 * NOT be used as an m4-style `defer' allowing packets to be
1310 * constructed in one order and sent in another.
1312 static void ssh2_pkt_defer(void)
1314 int len
= ssh2_pkt_construct();
1315 if (deferred_len
+ len
> deferred_size
) {
1316 deferred_size
= deferred_len
+ len
+ 128;
1317 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1319 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1320 deferred_len
+= len
;
1324 * Send the whole deferred data block constructed by
1325 * ssh2_pkt_defer() or SSH1's defer_packet().
1327 static void ssh_pkt_defersend(void)
1330 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1331 deferred_len
= deferred_size
= 0;
1332 sfree(deferred_send_data
);
1333 deferred_send_data
= NULL
;
1334 if (backlog
> SSH_MAX_BACKLOG
)
1335 ssh_throttle_all(1, backlog
);
1339 void bndebug(char *string
, Bignum b
)
1343 p
= ssh2_mpint_fmt(b
, &len
);
1344 debug(("%s", string
));
1345 for (i
= 0; i
< len
; i
++)
1346 debug((" %02x", p
[i
]));
1352 static void sha_mpint(SHA_State
* s
, Bignum b
)
1356 p
= ssh2_mpint_fmt(b
, &len
);
1357 sha_string(s
, p
, len
);
1362 * SSH2 packet decode functions.
1364 static unsigned long ssh2_pkt_getuint32(void)
1366 unsigned long value
;
1367 if (pktin
.length
- pktin
.savedpos
< 4)
1368 return 0; /* arrgh, no way to decline (FIXME?) */
1369 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1370 pktin
.savedpos
+= 4;
1373 static int ssh2_pkt_getbool(void)
1375 unsigned long value
;
1376 if (pktin
.length
- pktin
.savedpos
< 1)
1377 return 0; /* arrgh, no way to decline (FIXME?) */
1378 value
= pktin
.data
[pktin
.savedpos
] != 0;
1382 static void ssh2_pkt_getstring(char **p
, int *length
)
1385 if (pktin
.length
- pktin
.savedpos
< 4)
1387 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1388 pktin
.savedpos
+= 4;
1389 if (pktin
.length
- pktin
.savedpos
< *length
)
1391 *p
= pktin
.data
+ pktin
.savedpos
;
1392 pktin
.savedpos
+= *length
;
1394 static Bignum
ssh2_pkt_getmp(void)
1400 ssh2_pkt_getstring(&p
, &length
);
1404 bombout(("internal error: Can't handle negative mpints"));
1407 b
= bignum_from_bytes(p
, length
);
1412 * Examine the remote side's version string and compare it against
1413 * a list of known buggy implementations.
1415 static void ssh_detect_bugs(char *vstring
)
1417 char *imp
; /* pointer to implementation part */
1419 imp
+= strcspn(imp
, "-");
1421 imp
+= strcspn(imp
, "-");
1424 ssh_remote_bugs
= 0;
1426 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1427 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1428 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")) {
1430 * These versions don't support SSH1_MSG_IGNORE, so we have
1431 * to use a different defence against password length
1434 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1435 logevent("We believe remote version has SSH1 ignore bug");
1438 if (!strcmp(imp
, "Cisco-1.25")) {
1440 * These versions need a plain password sent; they can't
1441 * handle having a null and a random length of data after
1444 ssh_remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1445 logevent("We believe remote version needs a plain SSH1 password");
1448 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1449 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1450 !strncmp(imp
, "2.1 ", 4)) {
1452 * These versions have the HMAC bug.
1454 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1455 logevent("We believe remote version has SSH2 HMAC bug");
1459 static int do_ssh_init(unsigned char c
)
1462 static char version
[10];
1463 static char *vstring
;
1464 static int vstrsize
;
1470 /* Search for the string "SSH-" in the input. */
1473 static const int transS
[] = { 1, 2, 2, 1 };
1474 static const int transH
[] = { 0, 0, 3, 0 };
1475 static const int transminus
[] = { 0, 0, 0, -1 };
1486 crReturn(1); /* get another character */
1490 vstring
= smalloc(vstrsize
);
1491 strcpy(vstring
, "SSH-");
1495 crReturn(1); /* get another char */
1496 if (vslen
>= vstrsize
- 1) {
1498 vstring
= srealloc(vstring
, vstrsize
);
1500 vstring
[vslen
++] = c
;
1505 } else if (i
< sizeof(version
) - 1)
1507 } else if (c
== '\n')
1511 ssh_agentfwd_enabled
= FALSE
;
1512 rdpkt2_state
.incoming_sequence
= 0;
1515 vlog
= smalloc(20 + vslen
);
1516 vstring
[strcspn (vstring
, "\r\n")] = '\0'; /* remove end-of-line chars */
1517 sprintf(vlog
, "Server version: %s", vstring
);
1519 ssh_detect_bugs(vstring
);
1523 * Server version "1.99" means we can choose whether we use v1
1524 * or v2 protocol. Choice is based on cfg.sshprot.
1526 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1528 * This is a v2 server. Begin v2 protocol.
1530 char verstring
[80], vlog
[100];
1531 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1532 SHA_Init(&exhashbase
);
1534 * Hash our version string and their version string.
1536 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1537 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1538 sprintf(vlog
, "We claim version: %s", verstring
);
1540 strcat(verstring
, "\n");
1541 logevent("Using SSH protocol version 2");
1542 sk_write(s
, verstring
, strlen(verstring
));
1543 ssh_protocol
= ssh2_protocol
;
1545 s_rdpkt
= ssh2_rdpkt
;
1548 * This is a v1 server. Begin v1 protocol.
1550 char verstring
[80], vlog
[100];
1551 sprintf(verstring
, "SSH-%s-%s",
1552 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1554 sprintf(vlog
, "We claim version: %s", verstring
);
1556 strcat(verstring
, "\n");
1557 logevent("Using SSH protocol version 1");
1558 sk_write(s
, verstring
, strlen(verstring
));
1559 ssh_protocol
= ssh1_protocol
;
1561 s_rdpkt
= ssh1_rdpkt
;
1563 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1570 static void ssh_gotdata(unsigned char *data
, int datalen
)
1575 * To begin with, feed the characters one by one to the
1576 * protocol initialisation / selection function do_ssh_init().
1577 * When that returns 0, we're done with the initial greeting
1578 * exchange and can move on to packet discipline.
1583 crReturnV
; /* more data please */
1584 ret
= do_ssh_init(*data
);
1592 * We emerge from that loop when the initial negotiation is
1593 * over and we have selected an s_rdpkt function. Now pass
1594 * everything to s_rdpkt, and then pass the resulting packets
1595 * to the proper protocol handler.
1600 while (datalen
> 0) {
1601 if (s_rdpkt(&data
, &datalen
) == 0) {
1602 if (ssh_state
== SSH_STATE_CLOSED
) {
1605 ssh_protocol(NULL
, 0, 1);
1606 if (ssh_state
== SSH_STATE_CLOSED
) {
1616 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1619 ssh_state
= SSH_STATE_CLOSED
;
1625 /* A socket error has occurred. */
1626 connection_fatal(error_msg
);
1628 /* Otherwise, the remote side closed the connection normally. */
1633 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1635 ssh_gotdata(data
, len
);
1636 if (ssh_state
== SSH_STATE_CLOSED
) {
1646 static void ssh_sent(Plug plug
, int bufsize
)
1649 * If the send backlog on the SSH socket itself clears, we
1650 * should unthrottle the whole world if it was throttled.
1652 if (bufsize
< SSH_MAX_BACKLOG
)
1653 ssh_throttle_all(0, bufsize
);
1657 * Connect to specified host and port.
1658 * Returns an error message, or NULL on success.
1659 * Also places the canonical host name into `realhost'. It must be
1660 * freed by the caller.
1662 static char *connect_to_host(char *host
, int port
, char **realhost
)
1664 static struct plug_function_table fn_table
= {
1669 }, *fn_table_ptr
= &fn_table
;
1678 savedhost
= smalloc(1 + strlen(host
));
1680 fatalbox("Out of memory");
1681 strcpy(savedhost
, host
);
1684 port
= 22; /* default ssh port */
1699 sprintf(buf
, "Looking up host \"%.170s\"", host
);
1702 addr
= sk_namelookup(host
, realhost
);
1703 if ((err
= sk_addr_error(addr
)))
1707 *realhost
= strdup(FWhost
);
1714 char buf
[200], addrbuf
[100];
1715 sk_getaddr(addr
, addrbuf
, 100);
1716 sprintf(buf
, "Connecting to %.100s port %d", addrbuf
, port
);
1719 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1720 if ((err
= sk_socket_error(s
)))
1724 sk_write(s
, "connect ", 8);
1725 sk_write(s
, FWhost
, strlen(FWhost
));
1728 sprintf(buf
, " %d\n", FWport
);
1729 sk_write(s
, buf
, strlen(buf
));
1737 * Throttle or unthrottle the SSH connection.
1739 static void ssh1_throttle(int adjust
)
1741 int old_count
= ssh1_throttle_count
;
1742 ssh1_throttle_count
+= adjust
;
1743 assert(ssh1_throttle_count
>= 0);
1744 if (ssh1_throttle_count
&& !old_count
) {
1745 sk_set_frozen(s
, 1);
1746 } else if (!ssh1_throttle_count
&& old_count
) {
1747 sk_set_frozen(s
, 0);
1752 * Throttle or unthrottle _all_ local data streams (for when sends
1753 * on the SSH connection itself back up).
1755 static void ssh_throttle_all(int enable
, int bufsize
)
1758 struct ssh_channel
*c
;
1760 if (enable
== ssh_throttled_all
)
1762 ssh_throttled_all
= enable
;
1763 ssh_overall_bufsize
= bufsize
;
1766 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1768 case CHAN_MAINSESSION
:
1770 * This is treated separately, outside the switch.
1774 x11_override_throttle(c
->u
.x11
.s
, enable
);
1777 /* Agent channels require no buffer management. */
1780 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1787 * Handle the key exchange and user authentication phases.
1789 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1793 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1794 unsigned char cookie
[8];
1795 struct RSAKey servkey
, hostkey
;
1796 struct MD5Context md5c
;
1797 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1798 static int tried_publickey
;
1799 static int tis_auth_refused
, ccard_auth_refused
;
1800 static unsigned char session_id
[16];
1801 static int cipher_type
;
1802 static char username
[100];
1809 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1810 bombout(("Public key packet not received"));
1814 logevent("Received public keys");
1816 memcpy(cookie
, pktin
.body
, 8);
1818 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1819 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1822 * Log the host key fingerprint.
1826 logevent("Host key fingerprint is:");
1827 strcpy(logmsg
, " ");
1828 hostkey
.comment
= NULL
;
1829 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1830 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1834 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1835 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1836 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1838 ssh1_local_protoflags
=
1839 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1840 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1843 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1844 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1845 MD5Update(&md5c
, pktin
.body
, 8);
1846 MD5Final(session_id
, &md5c
);
1848 for (i
= 0; i
< 32; i
++)
1849 session_key
[i
] = random_byte();
1851 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1853 rsabuf
= smalloc(len
);
1855 fatalbox("Out of memory");
1858 * Verify the host key.
1862 * First format the key into a string.
1864 int len
= rsastr_len(&hostkey
);
1865 char fingerprint
[100];
1866 char *keystr
= smalloc(len
);
1868 fatalbox("Out of memory");
1869 rsastr_fmt(keystr
, &hostkey
);
1870 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1871 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1876 for (i
= 0; i
< 32; i
++) {
1877 rsabuf
[i
] = session_key
[i
];
1879 rsabuf
[i
] ^= session_id
[i
];
1882 if (hostkey
.bytes
> servkey
.bytes
) {
1883 rsaencrypt(rsabuf
, 32, &servkey
);
1884 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1886 rsaencrypt(rsabuf
, 32, &hostkey
);
1887 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1890 logevent("Encrypted session key");
1893 int cipher_chosen
= 0, warn
= 0;
1894 char *cipher_string
= NULL
;
1895 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
1896 int next_cipher
= cfg
.ssh_cipherlist
[i
];
1897 if (next_cipher
== CIPHER_WARN
) {
1898 /* If/when we choose a cipher, warn about it */
1900 } else if (next_cipher
== CIPHER_AES
) {
1901 /* XXX Probably don't need to mention this. */
1902 logevent("AES not supported in SSH1, skipping");
1904 switch (next_cipher
) {
1905 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
1906 cipher_string
= "3DES"; break;
1907 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
1908 cipher_string
= "Blowfish"; break;
1909 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
1910 cipher_string
= "single-DES"; break;
1912 if (supported_ciphers_mask
& (1 << cipher_type
))
1916 if (!cipher_chosen
) {
1917 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
1918 bombout(("Server violates SSH 1 protocol by not "
1919 "supporting 3DES encryption"));
1921 /* shouldn't happen */
1922 bombout(("No supported ciphers found"));
1926 /* Warn about chosen cipher if necessary. */
1928 askcipher(cipher_string
, 0);
1931 switch (cipher_type
) {
1932 case SSH_CIPHER_3DES
:
1933 logevent("Using 3DES encryption");
1935 case SSH_CIPHER_DES
:
1936 logevent("Using single-DES encryption");
1938 case SSH_CIPHER_BLOWFISH
:
1939 logevent("Using Blowfish encryption");
1943 send_packet(SSH1_CMSG_SESSION_KEY
,
1944 PKT_CHAR
, cipher_type
,
1945 PKT_DATA
, cookie
, 8,
1946 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1947 PKT_DATA
, rsabuf
, len
,
1948 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1950 logevent("Trying to enable encryption...");
1954 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1955 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1956 cipher
->sesskey(session_key
);
1960 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1961 bombout(("Encryption not successfully enabled"));
1965 logevent("Successfully started encryption");
1971 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1973 if (!ssh_get_line("login as: ",
1974 username
, sizeof(username
), FALSE
)) {
1976 * get_line failed to get a username.
1979 logevent("No username provided. Abandoning session.");
1980 ssh_state
= SSH_STATE_CLOSED
;
1984 c_write_str("login as: ");
1987 crWaitUntil(!ispkt
);
1989 switch (c
= *in
++) {
1998 c_write_str("\b \b");
2005 c_write_str("\b \b");
2015 if (((c
>= ' ' && c
<= '~') ||
2016 ((unsigned char) c
>= 160))
2017 && pos
< sizeof(username
)-1) {
2018 username
[pos
++] = c
;
2024 c_write_str("\r\n");
2025 username
[strcspn(username
, "\n\r")] = '\0';
2028 strncpy(username
, cfg
.username
, 99);
2029 username
[99] = '\0';
2032 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2034 char userlog
[22 + sizeof(username
)];
2035 sprintf(userlog
, "Sent username \"%s\"", username
);
2037 if (flags
& FLAG_INTERACTIVE
&&
2038 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2039 strcat(userlog
, "\r\n");
2040 c_write_str(userlog
);
2047 tried_publickey
= 0;
2048 tis_auth_refused
= ccard_auth_refused
= 0;
2050 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2051 static char password
[100];
2052 static char prompt
[200];
2055 static int pwpkt_type
;
2056 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2058 if (agent_exists()) {
2060 * Attempt RSA authentication using Pageant.
2062 static unsigned char request
[5], *response
, *p
;
2063 static int responselen
;
2064 static int i
, nkeys
;
2065 static int authed
= FALSE
;
2068 logevent("Pageant is running. Requesting keys.");
2070 /* Request the keys held by the agent. */
2071 PUT_32BIT(request
, 1);
2072 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2073 agent_query(request
, 5, &r
, &responselen
);
2074 response
= (unsigned char *) r
;
2075 if (response
&& responselen
>= 5 &&
2076 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2078 nkeys
= GET_32BIT(p
);
2082 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2085 for (i
= 0; i
< nkeys
; i
++) {
2086 static struct RSAKey key
;
2087 static Bignum challenge
;
2088 static char *commentp
;
2089 static int commentlen
;
2093 sprintf(buf
, "Trying Pageant key #%d", i
);
2097 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2098 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2099 commentlen
= GET_32BIT(p
);
2103 send_packet(SSH1_CMSG_AUTH_RSA
,
2104 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2106 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2107 logevent("Key refused");
2110 logevent("Received RSA challenge");
2111 ssh1_read_bignum(pktin
.body
, &challenge
);
2113 char *agentreq
, *q
, *ret
;
2116 len
= 1 + 4; /* message type, bit count */
2117 len
+= ssh1_bignum_length(key
.exponent
);
2118 len
+= ssh1_bignum_length(key
.modulus
);
2119 len
+= ssh1_bignum_length(challenge
);
2120 len
+= 16; /* session id */
2121 len
+= 4; /* response format */
2122 agentreq
= smalloc(4 + len
);
2123 PUT_32BIT(agentreq
, len
);
2125 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2126 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2128 q
+= ssh1_write_bignum(q
, key
.exponent
);
2129 q
+= ssh1_write_bignum(q
, key
.modulus
);
2130 q
+= ssh1_write_bignum(q
, challenge
);
2131 memcpy(q
, session_id
, 16);
2133 PUT_32BIT(q
, 1); /* response format */
2134 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2138 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2139 logevent("Sending Pageant's response");
2140 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2141 PKT_DATA
, ret
+ 5, 16,
2145 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2147 ("Pageant's response accepted");
2148 if (flags
& FLAG_VERBOSE
) {
2150 ("Authenticated using RSA key \"");
2151 c_write(commentp
, commentlen
);
2152 c_write_str("\" from agent\r\n");
2157 ("Pageant's response not accepted");
2160 ("Pageant failed to answer challenge");
2164 logevent("No reply received from Pageant");
2167 freebn(key
.exponent
);
2168 freebn(key
.modulus
);
2177 if (*cfg
.keyfile
&& !tried_publickey
)
2178 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2180 if (cfg
.try_tis_auth
&&
2181 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2182 !tis_auth_refused
) {
2183 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2184 logevent("Requested TIS authentication");
2185 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2187 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2188 logevent("TIS authentication declined");
2189 if (flags
& FLAG_INTERACTIVE
)
2190 c_write_str("TIS authentication refused.\r\n");
2191 tis_auth_refused
= 1;
2194 int challengelen
= ((pktin
.body
[0] << 24) |
2195 (pktin
.body
[1] << 16) |
2196 (pktin
.body
[2] << 8) |
2198 logevent("Received TIS challenge");
2199 if (challengelen
> sizeof(prompt
) - 1)
2200 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2201 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2202 /* Prompt heuristic comes from OpenSSH */
2203 strncpy(prompt
+ challengelen
,
2204 memchr(prompt
, '\n', challengelen
) ?
2205 "": "\r\nResponse: ",
2206 (sizeof prompt
) - challengelen
);
2207 prompt
[(sizeof prompt
) - 1] = '\0';
2210 if (cfg
.try_tis_auth
&&
2211 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2212 !ccard_auth_refused
) {
2213 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2214 logevent("Requested CryptoCard authentication");
2215 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2217 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2218 logevent("CryptoCard authentication declined");
2219 c_write_str("CryptoCard authentication refused.\r\n");
2220 ccard_auth_refused
= 1;
2223 int challengelen
= ((pktin
.body
[0] << 24) |
2224 (pktin
.body
[1] << 16) |
2225 (pktin
.body
[2] << 8) |
2227 logevent("Received CryptoCard challenge");
2228 if (challengelen
> sizeof(prompt
) - 1)
2229 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2230 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2231 strncpy(prompt
+ challengelen
,
2232 memchr(prompt
, '\n', challengelen
) ?
2233 "" : "\r\nResponse: ",
2234 sizeof(prompt
) - challengelen
);
2235 prompt
[sizeof(prompt
) - 1] = '\0';
2238 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2239 sprintf(prompt
, "%.90s@%.90s's password: ",
2240 username
, savedhost
);
2242 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2243 char *comment
= NULL
;
2244 if (flags
& FLAG_VERBOSE
)
2245 c_write_str("Trying public key authentication.\r\n");
2246 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2247 if (flags
& FLAG_VERBOSE
)
2248 c_write_str("No passphrase required.\r\n");
2251 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2256 * Show password prompt, having first obtained it via a TIS
2257 * or CryptoCard exchange if we're doing TIS or CryptoCard
2261 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2263 * get_line failed to get a password (for example
2264 * because one was supplied on the command line
2265 * which has already failed to work). Terminate.
2267 send_packet(SSH1_MSG_DISCONNECT
,
2268 PKT_STR
, "No more passwords available to try",
2270 connection_fatal("Unable to authenticate");
2271 ssh_state
= SSH_STATE_CLOSED
;
2275 /* Prompt may have come from server. We've munged it a bit, so
2276 * we know it to be zero-terminated at least once. */
2277 c_write_untrusted(prompt
, strlen(prompt
));
2281 crWaitUntil(!ispkt
);
2283 switch (c
= *in
++) {
2304 if (pos
< sizeof(password
)-1)
2305 password
[pos
++] = c
;
2309 c_write_str("\r\n");
2313 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2315 * Try public key authentication with the specified
2318 static struct RSAKey pubkey
;
2319 static Bignum challenge
, response
;
2321 static unsigned char buffer
[32];
2323 tried_publickey
= 1;
2324 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2326 c_write_str("Couldn't load private key from ");
2327 c_write_str(cfg
.keyfile
);
2328 c_write_str(".\r\n");
2329 continue; /* go and try password */
2332 c_write_str("Wrong passphrase.\r\n");
2333 tried_publickey
= 0;
2334 continue; /* try again */
2338 * Send a public key attempt.
2340 send_packet(SSH1_CMSG_AUTH_RSA
,
2341 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2344 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2345 c_write_str("Server refused our public key.\r\n");
2346 continue; /* go and try password */
2348 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2349 bombout(("Bizarre response to offer of public key"));
2352 ssh1_read_bignum(pktin
.body
, &challenge
);
2353 response
= rsadecrypt(challenge
, &pubkey
);
2354 freebn(pubkey
.private_exponent
); /* burn the evidence */
2356 for (i
= 0; i
< 32; i
++) {
2357 buffer
[i
] = bignum_byte(response
, 31 - i
);
2361 MD5Update(&md5c
, buffer
, 32);
2362 MD5Update(&md5c
, session_id
, 16);
2363 MD5Final(buffer
, &md5c
);
2365 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2366 PKT_DATA
, buffer
, 16, PKT_END
);
2369 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2370 if (flags
& FLAG_VERBOSE
)
2372 ("Failed to authenticate with our public key.\r\n");
2373 continue; /* go and try password */
2374 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2376 ("Bizarre response to RSA authentication response"));
2380 break; /* we're through! */
2382 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2384 * Defence against traffic analysis: we send a
2385 * whole bunch of packets containing strings of
2386 * different lengths. One of these strings is the
2387 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2388 * The others are all random data in
2389 * SSH1_MSG_IGNORE packets. This way a passive
2390 * listener can't tell which is the password, and
2391 * hence can't deduce the password length.
2393 * Anybody with a password length greater than 16
2394 * bytes is going to have enough entropy in their
2395 * password that a listener won't find it _that_
2396 * much help to know how long it is. So what we'll
2399 * - if password length < 16, we send 15 packets
2400 * containing string lengths 1 through 15
2402 * - otherwise, we let N be the nearest multiple
2403 * of 8 below the password length, and send 8
2404 * packets containing string lengths N through
2405 * N+7. This won't obscure the order of
2406 * magnitude of the password length, but it will
2407 * introduce a bit of extra uncertainty.
2409 * A few servers (the old 1.2.18 through 1.2.22)
2410 * can't deal with SSH1_MSG_IGNORE. For these
2411 * servers, we need an alternative defence. We make
2412 * use of the fact that the password is interpreted
2413 * as a C string: so we can append a NUL, then some
2416 * One server (a Cisco one) can deal with neither
2417 * SSH1_MSG_IGNORE _nor_ a padded password string.
2418 * For this server we are left with no defences
2419 * against password length sniffing.
2421 if (!(ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2423 * The server can deal with SSH1_MSG_IGNORE, so
2424 * we can use the primary defence.
2426 int bottom
, top
, pwlen
, i
;
2429 pwlen
= strlen(password
);
2431 bottom
= 0; /* zero length passwords are OK! :-) */
2434 bottom
= pwlen
& ~7;
2438 assert(pwlen
>= bottom
&& pwlen
<= top
);
2440 randomstr
= smalloc(top
+ 1);
2442 for (i
= bottom
; i
<= top
; i
++) {
2444 defer_packet(pwpkt_type
, PKT_STR
, password
,
2447 for (j
= 0; j
< i
; j
++) {
2449 randomstr
[j
] = random_byte();
2450 } while (randomstr
[j
] == '\0');
2452 randomstr
[i
] = '\0';
2453 defer_packet(SSH1_MSG_IGNORE
,
2454 PKT_STR
, randomstr
, PKT_END
);
2457 logevent("Sending password with camouflage packets");
2458 ssh_pkt_defersend();
2460 else if (!(ssh_remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2462 * The server can't deal with SSH1_MSG_IGNORE
2463 * but can deal with padded passwords, so we
2464 * can use the secondary defence.
2470 len
= strlen(password
);
2471 if (len
< sizeof(string
)) {
2473 strcpy(string
, password
);
2474 len
++; /* cover the zero byte */
2475 while (len
< sizeof(string
)) {
2476 string
[len
++] = (char) random_byte();
2481 logevent("Sending length-padded password");
2482 send_packet(pwpkt_type
, PKT_INT
, len
,
2483 PKT_DATA
, s
, len
, PKT_END
);
2486 * The server has _both_
2487 * BUG_CHOKES_ON_SSH1_IGNORE and
2488 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2489 * therefore nothing we can do.
2492 len
= strlen(password
);
2493 logevent("Sending unpadded password");
2494 send_packet(pwpkt_type
, PKT_INT
, len
,
2495 PKT_DATA
, password
, len
, PKT_END
);
2498 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2501 logevent("Sent password");
2502 memset(password
, 0, strlen(password
));
2504 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2505 if (flags
& FLAG_VERBOSE
)
2506 c_write_str("Access denied\r\n");
2507 logevent("Authentication refused");
2508 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2509 logevent("Received disconnect request");
2510 ssh_state
= SSH_STATE_CLOSED
;
2512 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2513 bombout(("Strange packet received, type %d", pktin
.type
));
2518 logevent("Authentication successful");
2523 void sshfwd_close(struct ssh_channel
*c
)
2525 if (c
&& !c
->closes
) {
2527 * If the channel's remoteid is -1, we have sent
2528 * CHANNEL_OPEN for this channel, but it hasn't even been
2529 * acknowledged by the server. So we must set a close flag
2530 * on it now, and then when the server acks the channel
2531 * open, we can close it then.
2533 if (c
->remoteid
!= -1) {
2534 if (ssh_version
== 1) {
2535 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2538 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2539 ssh2_pkt_adduint32(c
->remoteid
);
2544 if (c
->type
== CHAN_X11
) {
2546 logevent("Forwarded X11 connection terminated");
2547 } else if (c
->type
== CHAN_SOCKDATA
||
2548 c
->type
== CHAN_SOCKDATA_DORMANT
) {
2550 logevent("Forwarded port closed");
2555 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2557 if (ssh_version
== 1) {
2558 send_packet(SSH1_MSG_CHANNEL_DATA
,
2559 PKT_INT
, c
->remoteid
,
2560 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2562 * In SSH1 we can return 0 here - implying that forwarded
2563 * connections are never individually throttled - because
2564 * the only circumstance that can cause throttling will be
2565 * the whole SSH connection backing up, in which case
2566 * _everything_ will be throttled as a whole.
2570 ssh2_add_channel_data(c
, buf
, len
);
2571 return ssh2_try_send(c
);
2575 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2577 if (ssh_version
== 1) {
2578 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2579 c
->v
.v1
.throttling
= 0;
2583 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2587 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2593 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2596 if (ssh_state
== SSH_STATE_CLOSED
)
2599 if (cfg
.agentfwd
&& agent_exists()) {
2600 logevent("Requesting agent forwarding");
2601 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2605 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2606 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2607 bombout(("Protocol confusion"));
2609 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2610 logevent("Agent forwarding refused");
2612 logevent("Agent forwarding enabled");
2613 ssh_agentfwd_enabled
= TRUE
;
2617 if (cfg
.x11_forward
) {
2618 char proto
[20], data
[64];
2619 logevent("Requesting X11 forwarding");
2620 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2621 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2622 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2623 PKT_STR
, proto
, PKT_STR
, data
,
2624 PKT_INT
, 0, PKT_END
);
2626 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2627 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2632 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2633 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2634 bombout(("Protocol confusion"));
2636 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2637 logevent("X11 forwarding refused");
2639 logevent("X11 forwarding enabled");
2640 ssh_X11_fwd_enabled
= TRUE
;
2648 char sports
[256], dports
[256], host
[256];
2651 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2652 /* Add port forwardings. */
2657 while (*e
&& *e
!= '\t')
2663 while (*e
&& *e
!= ':')
2673 dport
= atoi(dports
);
2674 sport
= atoi(sports
);
2675 if (sport
&& dport
) {
2677 pfd_addforward(host
, dport
, sport
);
2678 sprintf(buf
, "Local port %d forwarding to %s:%d",
2679 sport
, host
, dport
);
2682 struct ssh_rportfwd
*pf
;
2683 pf
= smalloc(sizeof(*pf
));
2684 strcpy(pf
->dhost
, host
);
2686 if (add234(ssh_rportfwds
, pf
) != pf
) {
2688 "Duplicate remote port forwarding to %s:%d",
2693 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2694 sport
, host
, dport
);
2696 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2708 send_packet(SSH1_CMSG_REQUEST_PTY
,
2709 PKT_STR
, cfg
.termtype
,
2710 PKT_INT
, rows
, PKT_INT
, cols
,
2711 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2712 ssh_state
= SSH_STATE_INTERMED
;
2716 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2717 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2718 bombout(("Protocol confusion"));
2720 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2721 c_write_str("Server refused to allocate pty\r\n");
2722 ssh_editing
= ssh_echoing
= 1;
2724 logevent("Allocated pty");
2726 ssh_editing
= ssh_echoing
= 1;
2729 if (cfg
.compression
) {
2730 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2734 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2735 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2736 bombout(("Protocol confusion"));
2738 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2739 c_write_str("Server refused to compress\r\n");
2741 logevent("Started compression");
2742 ssh1_compressing
= TRUE
;
2743 zlib_compress_init();
2744 zlib_decompress_init();
2748 * Start the shell or command.
2750 * Special case: if the first-choice command is an SSH2
2751 * subsystem (hence not usable here) and the second choice
2752 * exists, we fall straight back to that.
2755 char *cmd
= cfg
.remote_cmd_ptr
;
2757 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
2758 cmd
= cfg
.remote_cmd_ptr2
;
2759 ssh_fallback_cmd
= TRUE
;
2762 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2764 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2765 logevent("Started session");
2768 ssh_state
= SSH_STATE_SESSION
;
2772 ssh_special(TS_EOF
);
2774 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
2776 ssh_channels
= newtree234(ssh_channelcmp
);
2780 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2781 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2782 long len
= GET_32BIT(pktin
.body
);
2784 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2785 pktin
.body
+ 4, len
);
2786 if (!ssh1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
2787 ssh1_stdout_throttling
= 1;
2790 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2791 ssh_state
= SSH_STATE_CLOSED
;
2792 logevent("Received disconnect request");
2794 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2795 /* Remote side is trying to open a channel to talk to our
2796 * X-Server. Give them back a local channel number. */
2797 struct ssh_channel
*c
;
2799 logevent("Received X11 connect request");
2800 /* Refuse if X11 forwarding is disabled. */
2801 if (!ssh_X11_fwd_enabled
) {
2802 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2803 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2804 logevent("Rejected X11 connect request");
2806 c
= smalloc(sizeof(struct ssh_channel
));
2808 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2809 logevent("opening X11 forward connection failed");
2811 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2812 PKT_INT
, GET_32BIT(pktin
.body
),
2816 ("opening X11 forward connection succeeded");
2817 c
->remoteid
= GET_32BIT(pktin
.body
);
2818 c
->localid
= alloc_channel_id();
2820 c
->v
.v1
.throttling
= 0;
2821 c
->type
= CHAN_X11
; /* identify channel type */
2822 add234(ssh_channels
, c
);
2823 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2824 PKT_INT
, c
->remoteid
, PKT_INT
,
2825 c
->localid
, PKT_END
);
2826 logevent("Opened X11 forward channel");
2829 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2830 /* Remote side is trying to open a channel to talk to our
2831 * agent. Give them back a local channel number. */
2832 struct ssh_channel
*c
;
2834 /* Refuse if agent forwarding is disabled. */
2835 if (!ssh_agentfwd_enabled
) {
2836 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2837 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2839 c
= smalloc(sizeof(struct ssh_channel
));
2840 c
->remoteid
= GET_32BIT(pktin
.body
);
2841 c
->localid
= alloc_channel_id();
2843 c
->v
.v1
.throttling
= 0;
2844 c
->type
= CHAN_AGENT
; /* identify channel type */
2845 c
->u
.a
.lensofar
= 0;
2846 add234(ssh_channels
, c
);
2847 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2848 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2851 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2852 /* Remote side is trying to open a channel to talk to a
2853 * forwarded port. Give them back a local channel number. */
2854 struct ssh_channel
*c
;
2855 struct ssh_rportfwd pf
;
2857 char host
[256], buf
[1024];
2859 c
= smalloc(sizeof(struct ssh_channel
));
2861 hostsize
= GET_32BIT(pktin
.body
+4);
2862 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2863 if (h
+1 < host
+sizeof(host
))
2868 port
= GET_32BIT(p
);
2870 strcpy(pf
.dhost
, host
);
2873 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2874 sprintf(buf
, "Rejected remote port open request for %s:%d",
2877 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2878 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2880 sprintf(buf
, "Received remote port open request for %s:%d",
2883 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2886 sprintf(buf
, "Port open failed: %s", e
);
2889 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2890 PKT_INT
, GET_32BIT(pktin
.body
),
2893 c
->remoteid
= GET_32BIT(pktin
.body
);
2894 c
->localid
= alloc_channel_id();
2896 c
->v
.v1
.throttling
= 0;
2897 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2898 add234(ssh_channels
, c
);
2899 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2900 PKT_INT
, c
->remoteid
, PKT_INT
,
2901 c
->localid
, PKT_END
);
2902 logevent("Forwarded port opened successfully");
2906 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2907 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2908 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2909 struct ssh_channel
*c
;
2911 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2912 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2913 c
->remoteid
= localid
;
2914 c
->type
= CHAN_SOCKDATA
;
2915 c
->v
.v1
.throttling
= 0;
2916 pfd_confirm(c
->u
.pfd
.s
);
2919 if (c
&& c
->closes
) {
2921 * We have a pending close on this channel,
2922 * which we decided on before the server acked
2923 * the channel open. So now we know the
2924 * remoteid, we can close it again.
2926 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2930 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
2931 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2932 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2933 struct ssh_channel
*c
;
2935 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2936 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2937 logevent("Forwarded connection refused by server");
2938 pfd_close(c
->u
.pfd
.s
);
2939 del234(ssh_channels
, c
);
2943 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2944 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2945 /* Remote side closes a channel. */
2946 unsigned i
= GET_32BIT(pktin
.body
);
2947 struct ssh_channel
*c
;
2948 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2952 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2953 if (!(c
->closes
& closetype
))
2954 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2956 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2957 logevent("Forwarded X11 connection terminated");
2958 assert(c
->u
.x11
.s
!= NULL
);
2959 x11_close(c
->u
.x11
.s
);
2962 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
2963 logevent("Forwarded port closed");
2964 assert(c
->u
.pfd
.s
!= NULL
);
2965 pfd_close(c
->u
.pfd
.s
);
2968 c
->closes
|= closetype
;
2969 if (c
->closes
== 3) {
2970 del234(ssh_channels
, c
);
2974 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2975 /* Data sent down one of our channels. */
2976 int i
= GET_32BIT(pktin
.body
);
2977 int len
= GET_32BIT(pktin
.body
+ 4);
2978 unsigned char *p
= pktin
.body
+ 8;
2979 struct ssh_channel
*c
;
2980 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2985 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
2988 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
2991 /* Data for an agent message. Buffer it. */
2993 if (c
->u
.a
.lensofar
< 4) {
2994 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2995 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2999 c
->u
.a
.lensofar
+= l
;
3001 if (c
->u
.a
.lensofar
== 4) {
3003 4 + GET_32BIT(c
->u
.a
.msglen
);
3004 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3005 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3007 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3009 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3011 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3015 c
->u
.a
.lensofar
+= l
;
3017 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3018 void *reply
, *sentreply
;
3020 agent_query(c
->u
.a
.message
,
3021 c
->u
.a
.totallen
, &reply
,
3026 /* Fake SSH_AGENT_FAILURE. */
3027 sentreply
= "\0\0\0\1\5";
3030 send_packet(SSH1_MSG_CHANNEL_DATA
,
3031 PKT_INT
, c
->remoteid
,
3033 PKT_DATA
, sentreply
, replylen
,
3037 sfree(c
->u
.a
.message
);
3038 c
->u
.a
.lensofar
= 0;
3041 bufsize
= 0; /* agent channels never back up */
3044 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3045 c
->v
.v1
.throttling
= 1;
3049 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
3050 /* may be from EXEC_SHELL on some servers */
3051 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3052 /* may be from EXEC_SHELL on some servers
3053 * if no pty is available or in other odd cases. Ignore */
3054 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3055 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3057 * In case `helpful' firewalls or proxies tack
3058 * extra human-readable text on the end of the
3059 * session which we might mistake for another
3060 * encrypted packet, we close the session once
3061 * we've sent EXIT_CONFIRMATION.
3063 ssh_state
= SSH_STATE_CLOSED
;
3066 bombout(("Strange packet received: type %d", pktin
.type
));
3071 int len
= min(inlen
, 512);
3072 send_packet(SSH1_CMSG_STDIN_DATA
,
3073 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3084 * Utility routine for decoding comma-separated strings in KEXINIT.
3086 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3088 int needlen
= strlen(needle
);
3091 * Is it at the start of the string?
3093 if (haylen
>= needlen
&& /* haystack is long enough */
3094 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3095 (haylen
== needlen
|| haystack
[needlen
] == ',')
3096 /* either , or EOS follows */
3100 * If not, search for the next comma and resume after that.
3101 * If no comma found, terminate.
3103 while (haylen
> 0 && *haystack
!= ',')
3104 haylen
--, haystack
++;
3107 haylen
--, haystack
++; /* skip over comma itself */
3112 * SSH2 key creation method.
3114 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
3118 /* First 20 bytes. */
3121 SHA_Bytes(&s
, H
, 20);
3122 SHA_Bytes(&s
, &chr
, 1);
3123 SHA_Bytes(&s
, sessid
, 20);
3124 SHA_Final(&s
, keyspace
);
3125 /* Next 20 bytes. */
3128 SHA_Bytes(&s
, H
, 20);
3129 SHA_Bytes(&s
, keyspace
, 20);
3130 SHA_Final(&s
, keyspace
+ 20);
3134 * Handle the SSH2 transport layer.
3136 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3138 static int i
, j
, len
, nbits
, pbits
, warn
;
3140 static Bignum p
, g
, e
, f
, K
;
3141 static int kex_init_value
, kex_reply_value
;
3142 static const struct ssh_mac
**maclist
;
3144 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3145 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3146 static const struct ssh_mac
*csmac_tobe
= NULL
;
3147 static const struct ssh_mac
*scmac_tobe
= NULL
;
3148 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3149 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3150 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3151 static int hostkeylen
, siglen
;
3152 static void *hkey
; /* actual host key */
3153 static unsigned char exchange_hash
[20];
3154 static unsigned char keyspace
[40];
3155 static int n_preferred_ciphers
;
3156 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3157 static const struct ssh_compress
*preferred_comp
;
3158 static int first_kex
;
3165 * Set up the preferred ciphers. (NULL => warn below here)
3167 n_preferred_ciphers
= 0;
3168 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3169 switch (cfg
.ssh_cipherlist
[i
]) {
3170 case CIPHER_BLOWFISH
:
3171 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3172 n_preferred_ciphers
++;
3175 /* Not supported in SSH2; silently drop */
3178 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3179 n_preferred_ciphers
++;
3182 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3183 n_preferred_ciphers
++;
3186 /* Flag for later. Don't bother if it's the last in
3188 if (i
< CIPHER_MAX
- 1) {
3189 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3190 n_preferred_ciphers
++;
3197 * Set up preferred compression.
3199 if (cfg
.compression
)
3200 preferred_comp
= &ssh_zlib
;
3202 preferred_comp
= &ssh_comp_none
;
3205 * Be prepared to work around the buggy MAC problem.
3207 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3208 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3210 maclist
= macs
, nmacs
= lenof(macs
);
3214 * Construct and send our key exchange packet.
3216 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3217 for (i
= 0; i
< 16; i
++)
3218 ssh2_pkt_addbyte((unsigned char) random_byte());
3219 /* List key exchange algorithms. */
3220 ssh2_pkt_addstring_start();
3221 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3222 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3223 if (i
< lenof(kex_algs
) - 1)
3224 ssh2_pkt_addstring_str(",");
3226 /* List server host key algorithms. */
3227 ssh2_pkt_addstring_start();
3228 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3229 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3230 if (i
< lenof(hostkey_algs
) - 1)
3231 ssh2_pkt_addstring_str(",");
3233 /* List client->server encryption algorithms. */
3234 ssh2_pkt_addstring_start();
3235 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3236 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3237 if (!c
) continue; /* warning flag */
3238 for (j
= 0; j
< c
->nciphers
; j
++) {
3239 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3240 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3241 ssh2_pkt_addstring_str(",");
3244 /* List server->client encryption algorithms. */
3245 ssh2_pkt_addstring_start();
3246 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3247 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3248 if (!c
) continue; /* warning flag */
3249 for (j
= 0; j
< c
->nciphers
; j
++) {
3250 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3251 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3252 ssh2_pkt_addstring_str(",");
3255 /* List client->server MAC algorithms. */
3256 ssh2_pkt_addstring_start();
3257 for (i
= 0; i
< nmacs
; i
++) {
3258 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3260 ssh2_pkt_addstring_str(",");
3262 /* List server->client MAC algorithms. */
3263 ssh2_pkt_addstring_start();
3264 for (i
= 0; i
< nmacs
; i
++) {
3265 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3267 ssh2_pkt_addstring_str(",");
3269 /* List client->server compression algorithms. */
3270 ssh2_pkt_addstring_start();
3271 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3272 const struct ssh_compress
*c
=
3273 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3274 ssh2_pkt_addstring_str(c
->name
);
3275 if (i
< lenof(compressions
))
3276 ssh2_pkt_addstring_str(",");
3278 /* List server->client compression algorithms. */
3279 ssh2_pkt_addstring_start();
3280 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3281 const struct ssh_compress
*c
=
3282 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3283 ssh2_pkt_addstring_str(c
->name
);
3284 if (i
< lenof(compressions
))
3285 ssh2_pkt_addstring_str(",");
3287 /* List client->server languages. Empty list. */
3288 ssh2_pkt_addstring_start();
3289 /* List server->client languages. Empty list. */
3290 ssh2_pkt_addstring_start();
3291 /* First KEX packet does _not_ follow, because we're not that brave. */
3292 ssh2_pkt_addbool(FALSE
);
3294 ssh2_pkt_adduint32(0);
3296 exhash
= exhashbase
;
3297 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3303 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3306 * Now examine the other side's KEXINIT to see what we're up
3309 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3310 bombout(("expected key exchange packet from server"));
3315 cscipher_tobe
= NULL
;
3316 sccipher_tobe
= NULL
;
3321 pktin
.savedpos
+= 16; /* skip garbage cookie */
3322 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3323 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3324 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3329 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3330 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3331 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3332 hostkey
= hostkey_algs
[i
];
3336 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3338 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3339 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3343 for (j
= 0; j
< c
->nciphers
; j
++) {
3344 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3345 cscipher_tobe
= c
->list
[j
];
3350 if (cscipher_tobe
) {
3352 askcipher(cscipher_tobe
->name
, 1);
3356 if (!cscipher_tobe
) {
3357 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str
));
3361 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3363 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3364 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3368 for (j
= 0; j
< c
->nciphers
; j
++) {
3369 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3370 sccipher_tobe
= c
->list
[j
];
3375 if (sccipher_tobe
) {
3377 askcipher(sccipher_tobe
->name
, 2);
3381 if (!sccipher_tobe
) {
3382 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str
));
3386 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3387 for (i
= 0; i
< nmacs
; i
++) {
3388 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3389 csmac_tobe
= maclist
[i
];
3393 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3394 for (i
= 0; i
< nmacs
; i
++) {
3395 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3396 scmac_tobe
= maclist
[i
];
3400 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3401 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3402 const struct ssh_compress
*c
=
3403 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3404 if (in_commasep_string(c
->name
, str
, len
)) {
3409 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3410 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3411 const struct ssh_compress
*c
=
3412 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3413 if (in_commasep_string(c
->name
, str
, len
)) {
3420 * Work out the number of bits of key we will need from the key
3421 * exchange. We start with the maximum key length of either
3427 csbits
= cscipher_tobe
->keylen
;
3428 scbits
= sccipher_tobe
->keylen
;
3429 nbits
= (csbits
> scbits ? csbits
: scbits
);
3431 /* The keys only have 160-bit entropy, since they're based on
3432 * a SHA-1 hash. So cap the key size at 160 bits. */
3437 * If we're doing Diffie-Hellman group exchange, start by
3438 * requesting a group.
3440 if (kex
== &ssh_diffiehellman_gex
) {
3441 logevent("Doing Diffie-Hellman group exchange");
3443 * Work out how big a DH group we will need to allow that
3446 pbits
= 512 << ((nbits
- 1) / 64);
3447 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3448 ssh2_pkt_adduint32(pbits
);
3452 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3453 bombout(("expected key exchange group packet from server"));
3456 p
= ssh2_pkt_getmp();
3457 g
= ssh2_pkt_getmp();
3458 dh_setup_group(p
, g
);
3459 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3460 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3463 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3464 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3467 logevent("Doing Diffie-Hellman key exchange");
3469 * Now generate and send e for Diffie-Hellman.
3471 e
= dh_create_e(nbits
* 2);
3472 ssh2_pkt_init(kex_init_value
);
3477 if (pktin
.type
!= kex_reply_value
) {
3478 bombout(("expected key exchange reply packet from server"));
3481 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3482 f
= ssh2_pkt_getmp();
3483 ssh2_pkt_getstring(&sigdata
, &siglen
);
3487 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3488 if (kex
== &ssh_diffiehellman_gex
) {
3489 sha_uint32(&exhash
, pbits
);
3490 sha_mpint(&exhash
, p
);
3491 sha_mpint(&exhash
, g
);
3493 sha_mpint(&exhash
, e
);
3494 sha_mpint(&exhash
, f
);
3495 sha_mpint(&exhash
, K
);
3496 SHA_Final(&exhash
, exchange_hash
);
3501 debug(("Exchange hash is:\n"));
3502 dmemdump(exchange_hash
, 20);
3505 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3507 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3508 bombout(("Server's host key did not match the signature supplied"));
3513 * Authenticate remote host: verify host key. (We've already
3514 * checked the signature of the exchange hash.)
3516 keystr
= hostkey
->fmtkey(hkey
);
3517 fingerprint
= hostkey
->fingerprint(hkey
);
3518 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3519 keystr
, fingerprint
);
3520 if (first_kex
) { /* don't bother logging this in rekeys */
3521 logevent("Host key fingerprint is:");
3522 logevent(fingerprint
);
3526 hostkey
->freekey(hkey
);
3529 * Send SSH2_MSG_NEWKEYS.
3531 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3535 * Expect SSH2_MSG_NEWKEYS from server.
3538 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3539 bombout(("expected new-keys packet from server"));
3544 * Create and initialise session keys.
3546 cscipher
= cscipher_tobe
;
3547 sccipher
= sccipher_tobe
;
3550 cscomp
= cscomp_tobe
;
3551 sccomp
= sccomp_tobe
;
3552 cscomp
->compress_init();
3553 sccomp
->decompress_init();
3555 * Set IVs after keys. Here we use the exchange hash from the
3556 * _first_ key exchange.
3559 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3560 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3561 cscipher
->setcskey(keyspace
);
3562 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3563 sccipher
->setsckey(keyspace
);
3564 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3565 cscipher
->setcsiv(keyspace
);
3566 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3567 sccipher
->setsciv(keyspace
);
3568 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3569 csmac
->setcskey(keyspace
);
3570 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3571 scmac
->setsckey(keyspace
);
3574 * If this is the first key exchange phase, we must pass the
3575 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3576 * wants to see it but because it will need time to initialise
3577 * itself before it sees an actual packet. In subsequent key
3578 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3579 * it would only confuse the layer above.
3587 * Now we're encrypting. Begin returning 1 to the protocol main
3588 * function so that other things can run on top of the
3589 * transport. If we ever see a KEXINIT, we must go back to the
3592 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3595 logevent("Server initiated key re-exchange");
3596 goto begin_key_exchange
;
3602 * Add data to an SSH2 channel output buffer.
3604 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3607 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3611 * Attempt to send data on an SSH2 channel.
3613 static int ssh2_try_send(struct ssh_channel
*c
)
3615 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3618 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3619 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3620 len
= c
->v
.v2
.remwindow
;
3621 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3622 len
= c
->v
.v2
.remmaxpkt
;
3623 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3624 ssh2_pkt_adduint32(c
->remoteid
);
3625 ssh2_pkt_addstring_start();
3626 ssh2_pkt_addstring_data(data
, len
);
3628 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3629 c
->v
.v2
.remwindow
-= len
;
3633 * After having sent as much data as we can, return the amount
3636 return bufchain_size(&c
->v
.v2
.outbuffer
);
3640 * Potentially enlarge the window on an SSH2 channel.
3642 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3644 if (newwin
> c
->v
.v2
.locwindow
) {
3645 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3646 ssh2_pkt_adduint32(c
->remoteid
);
3647 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3649 c
->v
.v2
.locwindow
= newwin
;
3654 * Handle the SSH2 userauth and connection layers.
3656 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3659 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3661 AUTH_KEYBOARD_INTERACTIVE
3665 AUTH_TYPE_PUBLICKEY
,
3666 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3667 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3669 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3670 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3672 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3673 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3674 static int kbd_inter_running
;
3675 static int we_are_in
;
3676 static int num_prompts
, echo
;
3677 static char username
[100];
3678 static char pwprompt
[200];
3679 static char password
[100];
3684 * Request userauth protocol, and await a response to it.
3686 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3687 ssh2_pkt_addstring("ssh-userauth");
3689 crWaitUntilV(ispkt
);
3690 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3691 bombout(("Server refused user authentication protocol"));
3696 * We repeat this whole loop, including the username prompt,
3697 * until we manage a successful authentication. If the user
3698 * types the wrong _password_, they are sent back to the
3699 * beginning to try another username. (If they specify a
3700 * username in the config, they are never asked, even if they
3701 * do give a wrong password.)
3703 * I think this best serves the needs of
3705 * - the people who have no configuration, no keys, and just
3706 * want to try repeated (username,password) pairs until they
3707 * type both correctly
3709 * - people who have keys and configuration but occasionally
3710 * need to fall back to passwords
3712 * - people with a key held in Pageant, who might not have
3713 * logged in to a particular machine before; so they want to
3714 * type a username, and then _either_ their key will be
3715 * accepted, _or_ they will type a password. If they mistype
3716 * the username they will want to be able to get back and
3727 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3729 if (!ssh_get_line("login as: ",
3730 username
, sizeof(username
), FALSE
)) {
3732 * get_line failed to get a username.
3735 logevent("No username provided. Abandoning session.");
3736 ssh_state
= SSH_STATE_CLOSED
;
3740 c_write_str("login as: ");
3743 crWaitUntilV(!ispkt
);
3745 switch (c
= *in
++) {
3754 c_write_str("\b \b");
3761 c_write_str("\b \b");
3771 if (((c
>= ' ' && c
<= '~') ||
3772 ((unsigned char) c
>= 160))
3773 && pos
< sizeof(username
)-1) {
3774 username
[pos
++] = c
;
3781 c_write_str("\r\n");
3782 username
[strcspn(username
, "\n\r")] = '\0';
3785 strncpy(username
, cfg
.username
, 99);
3786 username
[99] = '\0';
3787 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3788 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3794 * Send an authentication request using method "none": (a)
3795 * just in case it succeeds, and (b) so that we know what
3796 * authentication methods we can usefully try next.
3798 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3799 ssh2_pkt_addstring(username
);
3800 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3801 ssh2_pkt_addstring("none"); /* method */
3803 type
= AUTH_TYPE_NONE
;
3807 tried_pubkey_config
= FALSE
;
3808 tried_agent
= FALSE
;
3809 tried_keyb_inter
= FALSE
;
3810 kbd_inter_running
= FALSE
;
3814 * Wait for the result of the last authentication request.
3817 crWaitUntilV(ispkt
);
3818 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3822 * Don't show the banner if we're operating in
3823 * non-verbose non-interactive mode. (It's probably
3824 * a script, which means nobody will read the
3825 * banner _anyway_, and moreover the printing of
3826 * the banner will screw up processing on the
3827 * output of (say) plink.)
3829 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3830 ssh2_pkt_getstring(&banner
, &size
);
3832 c_write_untrusted(banner
, size
);
3834 crWaitUntilV(ispkt
);
3836 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3837 logevent("Access granted");
3842 if (kbd_inter_running
&&
3843 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3845 * This is a further prompt in keyboard-interactive
3846 * authentication. Do nothing.
3848 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3849 bombout(("Strange packet received during authentication: type %d",
3857 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3858 * we can look at the string in it and know what we can
3859 * helpfully try next.
3861 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
3864 ssh2_pkt_getstring(&methods
, &methlen
);
3865 kbd_inter_running
= FALSE
;
3866 if (!ssh2_pkt_getbool()) {
3868 * We have received an unequivocal Access
3869 * Denied. This can translate to a variety of
3872 * - if we'd just tried "none" authentication,
3873 * it's not worth printing anything at all
3875 * - if we'd just tried a public key _offer_,
3876 * the message should be "Server refused our
3877 * key" (or no message at all if the key
3878 * came from Pageant)
3880 * - if we'd just tried anything else, the
3881 * message really should be "Access denied".
3883 * Additionally, if we'd just tried password
3884 * authentication, we should break out of this
3885 * whole loop so as to go back to the username
3888 if (type
== AUTH_TYPE_NONE
) {
3890 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3891 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3892 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3893 c_write_str("Server refused our key\r\n");
3894 logevent("Server refused public key");
3895 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
3896 /* server declined keyboard-interactive; ignore */
3898 c_write_str("Access denied\r\n");
3899 logevent("Access denied");
3900 if (type
== AUTH_TYPE_PASSWORD
) {
3906 c_write_str("Further authentication required\r\n");
3907 logevent("Further authentication required");
3911 in_commasep_string("publickey", methods
, methlen
);
3913 in_commasep_string("password", methods
, methlen
);
3915 in_commasep_string("keyboard-interactive", methods
, methlen
);
3920 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3922 * Attempt public-key authentication using Pageant.
3924 static unsigned char request
[5], *response
, *p
;
3925 static int responselen
;
3926 static int i
, nkeys
;
3927 static int authed
= FALSE
;
3932 logevent("Pageant is running. Requesting keys.");
3934 /* Request the keys held by the agent. */
3935 PUT_32BIT(request
, 1);
3936 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3937 agent_query(request
, 5, &r
, &responselen
);
3938 response
= (unsigned char *) r
;
3939 if (response
&& responselen
>= 5 &&
3940 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3942 nkeys
= GET_32BIT(p
);
3946 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3949 for (i
= 0; i
< nkeys
; i
++) {
3950 static char *pkblob
, *alg
, *commentp
;
3951 static int pklen
, alglen
, commentlen
;
3952 static int siglen
, retlen
, len
;
3953 static char *q
, *agentreq
, *ret
;
3958 sprintf(buf
, "Trying Pageant key #%d", i
);
3961 pklen
= GET_32BIT(p
);
3965 alglen
= GET_32BIT(pkblob
);
3967 commentlen
= GET_32BIT(p
);
3971 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3972 ssh2_pkt_addstring(username
);
3973 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3974 ssh2_pkt_addstring("publickey"); /* method */
3975 ssh2_pkt_addbool(FALSE
); /* no signature included */
3976 ssh2_pkt_addstring_start();
3977 ssh2_pkt_addstring_data(alg
, alglen
);
3978 ssh2_pkt_addstring_start();
3979 ssh2_pkt_addstring_data(pkblob
, pklen
);
3982 crWaitUntilV(ispkt
);
3983 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3984 logevent("Key refused");
3988 if (flags
& FLAG_VERBOSE
) {
3990 ("Authenticating with public key \"");
3991 c_write(commentp
, commentlen
);
3992 c_write_str("\" from agent\r\n");
3996 * Server is willing to accept the key.
3997 * Construct a SIGN_REQUEST.
3999 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4000 ssh2_pkt_addstring(username
);
4001 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4002 ssh2_pkt_addstring("publickey"); /* method */
4003 ssh2_pkt_addbool(TRUE
);
4004 ssh2_pkt_addstring_start();
4005 ssh2_pkt_addstring_data(alg
, alglen
);
4006 ssh2_pkt_addstring_start();
4007 ssh2_pkt_addstring_data(pkblob
, pklen
);
4009 siglen
= pktout
.length
- 5 + 4 + 20;
4010 len
= 1; /* message type */
4011 len
+= 4 + pklen
; /* key blob */
4012 len
+= 4 + siglen
; /* data to sign */
4013 len
+= 4; /* flags */
4014 agentreq
= smalloc(4 + len
);
4015 PUT_32BIT(agentreq
, len
);
4017 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
4018 PUT_32BIT(q
, pklen
);
4020 memcpy(q
, pkblob
, pklen
);
4022 PUT_32BIT(q
, siglen
);
4024 /* Now the data to be signed... */
4027 memcpy(q
, ssh2_session_id
, 20);
4029 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
4030 q
+= pktout
.length
- 5;
4031 /* And finally the (zero) flags word. */
4033 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
4037 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4038 logevent("Sending Pageant's response");
4039 ssh2_pkt_addstring_start();
4040 ssh2_pkt_addstring_data(ret
+ 9,
4048 ("Pageant failed to answer challenge");
4058 if (!method
&& can_pubkey
&& *cfg
.keyfile
4059 && !tried_pubkey_config
) {
4060 unsigned char *pub_blob
;
4061 char *algorithm
, *comment
;
4064 tried_pubkey_config
= TRUE
;
4067 * Try the public key supplied in the configuration.
4069 * First, offer the public blob to see if the server is
4070 * willing to accept it.
4072 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
4075 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4076 ssh2_pkt_addstring(username
);
4077 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4078 ssh2_pkt_addstring("publickey"); /* method */
4079 ssh2_pkt_addbool(FALSE
); /* no signature included */
4080 ssh2_pkt_addstring(algorithm
);
4081 ssh2_pkt_addstring_start();
4082 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
4084 logevent("Offered public key"); /* FIXME */
4086 crWaitUntilV(ispkt
);
4087 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4089 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4090 continue; /* key refused; give up on it */
4093 logevent("Offer of public key accepted");
4095 * Actually attempt a serious authentication using
4098 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4100 "Passphrase for key \"%.100s\": ",
4106 c_write_str("Authenticating with public key \"");
4107 c_write_str(comment
);
4108 c_write_str("\"\r\n");
4109 method
= AUTH_PUBLICKEY_FILE
;
4113 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
4114 method
= AUTH_KEYBOARD_INTERACTIVE
;
4115 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4116 tried_keyb_inter
= TRUE
;
4118 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4119 ssh2_pkt_addstring(username
);
4120 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4121 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4122 ssh2_pkt_addstring(""); /* lang */
4123 ssh2_pkt_addstring("");
4126 crWaitUntilV(ispkt
);
4127 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4128 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4130 logevent("Keyboard-interactive authentication refused");
4131 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4135 kbd_inter_running
= TRUE
;
4138 if (kbd_inter_running
) {
4139 method
= AUTH_KEYBOARD_INTERACTIVE
;
4140 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4141 tried_keyb_inter
= TRUE
;
4143 /* We've got packet with that "interactive" info
4144 dump banners, and set its prompt as ours */
4146 char *name
, *inst
, *lang
, *prompt
;
4147 int name_len
, inst_len
, lang_len
, prompt_len
;
4148 ssh2_pkt_getstring(&name
, &name_len
);
4149 ssh2_pkt_getstring(&inst
, &inst_len
);
4150 ssh2_pkt_getstring(&lang
, &lang_len
);
4152 c_write_untrusted(name
, name_len
);
4154 c_write_untrusted(inst
, inst_len
);
4155 num_prompts
= ssh2_pkt_getuint32();
4157 ssh2_pkt_getstring(&prompt
, &prompt_len
);
4158 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
4161 echo
= ssh2_pkt_getbool();
4165 if (!method
&& can_passwd
) {
4166 method
= AUTH_PASSWORD
;
4167 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4174 if (!ssh_get_line(pwprompt
, password
,
4175 sizeof(password
), TRUE
)) {
4177 * get_line failed to get a password (for
4178 * example because one was supplied on the
4179 * command line which has already failed to
4182 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4183 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4185 ("No more passwords available to try");
4186 ssh2_pkt_addstring("en"); /* language tag */
4188 connection_fatal("Unable to authenticate");
4189 ssh_state
= SSH_STATE_CLOSED
;
4196 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4201 crWaitUntilV(!ispkt
);
4203 switch (c
= *in
++) {
4224 if (pos
< sizeof(password
)-1)
4225 password
[pos
++] = c
;
4229 c_write_str("\r\n");
4233 if (method
== AUTH_PUBLICKEY_FILE
) {
4235 * We have our passphrase. Now try the actual authentication.
4237 struct ssh2_userkey
*key
;
4239 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4240 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4241 if (key
== SSH2_WRONG_PASSPHRASE
) {
4242 c_write_str("Wrong passphrase\r\n");
4243 tried_pubkey_config
= FALSE
;
4245 c_write_str("Unable to load private key\r\n");
4246 tried_pubkey_config
= TRUE
;
4248 /* Send a spurious AUTH_NONE to return to the top. */
4249 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4250 ssh2_pkt_addstring(username
);
4251 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4252 ssh2_pkt_addstring("none"); /* method */
4254 type
= AUTH_TYPE_NONE
;
4256 unsigned char *blob
, *sigdata
;
4257 int blob_len
, sigdata_len
;
4260 * We have loaded the private key and the server
4261 * has announced that it's willing to accept it.
4262 * Hallelujah. Generate a signature and send it.
4264 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4265 ssh2_pkt_addstring(username
);
4266 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4267 ssh2_pkt_addstring("publickey"); /* method */
4268 ssh2_pkt_addbool(TRUE
);
4269 ssh2_pkt_addstring(key
->alg
->name
);
4270 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4271 ssh2_pkt_addstring_start();
4272 ssh2_pkt_addstring_data(blob
, blob_len
);
4276 * The data to be signed is:
4280 * followed by everything so far placed in the
4283 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4284 sigdata
= smalloc(sigdata_len
);
4285 PUT_32BIT(sigdata
, 20);
4286 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4287 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4290 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4292 ssh2_pkt_addstring_start();
4293 ssh2_pkt_addstring_data(blob
, blob_len
);
4298 type
= AUTH_TYPE_PUBLICKEY
;
4300 } else if (method
== AUTH_PASSWORD
) {
4302 * We send the password packet lumped tightly together with
4303 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4304 * string long enough to make the total length of the two
4305 * packets constant. This should ensure that a passive
4306 * listener doing traffic analyis can't work out the length
4309 * For this to work, we need an assumption about the
4310 * maximum length of the password packet. I think 256 is
4311 * pretty conservative. Anyone using a password longer than
4312 * that probably doesn't have much to worry about from
4313 * people who find out how long their password is!
4315 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4316 ssh2_pkt_addstring(username
);
4317 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4318 ssh2_pkt_addstring("password");
4319 ssh2_pkt_addbool(FALSE
);
4320 ssh2_pkt_addstring(password
);
4323 * We'll include a string that's an exact multiple of the
4324 * cipher block size. If the cipher is NULL for some
4325 * reason, we don't do this trick at all because we gain
4331 stringlen
= (256 - deferred_len
);
4332 stringlen
+= cscipher
->blksize
- 1;
4333 stringlen
-= (stringlen
% cscipher
->blksize
);
4336 * Temporarily disable actual compression,
4337 * so we can guarantee to get this string
4338 * exactly the length we want it. The
4339 * compression-disabling routine should
4340 * return an integer indicating how many
4341 * bytes we should adjust our string length
4344 stringlen
-= cscomp
->disable_compression();
4346 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4347 ssh2_pkt_addstring_start();
4348 for (i
= 0; i
< stringlen
; i
++) {
4349 char c
= (char) random_byte();
4350 ssh2_pkt_addstring_data(&c
, 1);
4354 ssh_pkt_defersend();
4355 logevent("Sent password");
4356 type
= AUTH_TYPE_PASSWORD
;
4357 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4358 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4359 ssh2_pkt_adduint32(num_prompts
);
4360 ssh2_pkt_addstring(password
);
4361 memset(password
, 0, sizeof(password
));
4363 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4366 ("No supported authentication methods left to try!\r\n");
4368 ("No supported authentications offered. Disconnecting");
4369 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4370 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4372 ("No supported authentication methods available");
4373 ssh2_pkt_addstring("en"); /* language tag */
4375 ssh_state
= SSH_STATE_CLOSED
;
4379 } while (!we_are_in
);
4382 * Now we're authenticated for the connection protocol. The
4383 * connection protocol will automatically have started at this
4384 * point; there's no need to send SERVICE_REQUEST.
4388 * So now create a channel with a session in it.
4390 ssh_channels
= newtree234(ssh_channelcmp
);
4391 mainchan
= smalloc(sizeof(struct ssh_channel
));
4392 mainchan
->localid
= alloc_channel_id();
4393 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4394 ssh2_pkt_addstring("session");
4395 ssh2_pkt_adduint32(mainchan
->localid
);
4396 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4397 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4398 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4400 crWaitUntilV(ispkt
);
4401 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4402 bombout(("Server refused to open a session"));
4404 /* FIXME: error data comes back in FAILURE packet */
4406 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4407 bombout(("Server's channel confirmation cited wrong channel"));
4410 mainchan
->remoteid
= ssh2_pkt_getuint32();
4411 mainchan
->type
= CHAN_MAINSESSION
;
4412 mainchan
->closes
= 0;
4413 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4414 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4415 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4416 add234(ssh_channels
, mainchan
);
4417 logevent("Opened channel for session");
4420 * Potentially enable X11 forwarding.
4422 if (cfg
.x11_forward
) {
4423 char proto
[20], data
[64];
4424 logevent("Requesting X11 forwarding");
4425 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4426 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4427 ssh2_pkt_adduint32(mainchan
->remoteid
);
4428 ssh2_pkt_addstring("x11-req");
4429 ssh2_pkt_addbool(1); /* want reply */
4430 ssh2_pkt_addbool(0); /* many connections */
4431 ssh2_pkt_addstring(proto
);
4432 ssh2_pkt_addstring(data
);
4433 ssh2_pkt_adduint32(0); /* screen number */
4437 crWaitUntilV(ispkt
);
4438 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4439 unsigned i
= ssh2_pkt_getuint32();
4440 struct ssh_channel
*c
;
4441 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4443 continue; /* nonexistent channel */
4444 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4446 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4448 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4449 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4450 bombout(("Unexpected response to X11 forwarding request:"
4451 " packet type %d", pktin
.type
));
4454 logevent("X11 forwarding refused");
4456 logevent("X11 forwarding enabled");
4457 ssh_X11_fwd_enabled
= TRUE
;
4462 * Enable port forwardings.
4465 static char *e
; /* preserve across crReturn */
4469 char sports
[256], dports
[256], host
[256];
4472 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4473 /* Add port forwardings. */
4478 while (*e
&& *e
!= '\t')
4484 while (*e
&& *e
!= ':')
4494 dport
= atoi(dports
);
4495 sport
= atoi(sports
);
4496 if (sport
&& dport
) {
4498 pfd_addforward(host
, dport
, sport
);
4499 sprintf(buf
, "Local port %d forwarding to %s:%d",
4500 sport
, host
, dport
);
4503 struct ssh_rportfwd
*pf
;
4504 pf
= smalloc(sizeof(*pf
));
4505 strcpy(pf
->dhost
, host
);
4508 if (add234(ssh_rportfwds
, pf
) != pf
) {
4510 "Duplicate remote port forwarding to %s:%d",
4515 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4516 sport
, host
, dport
);
4518 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4519 ssh2_pkt_addstring("tcpip-forward");
4520 ssh2_pkt_addbool(1);/* want reply */
4521 ssh2_pkt_addstring("127.0.0.1");
4522 ssh2_pkt_adduint32(sport
);
4526 crWaitUntilV(ispkt
);
4527 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4528 unsigned i
= ssh2_pkt_getuint32();
4529 struct ssh_channel
*c
;
4530 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4532 continue;/* nonexistent channel */
4533 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4535 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4537 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4538 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4539 bombout(("Unexpected response to port "
4540 "forwarding request: packet type %d",
4544 logevent("Server refused this port forwarding");
4546 logevent("Remote port forwarding enabled");
4555 * Potentially enable agent forwarding.
4557 if (cfg
.agentfwd
&& agent_exists()) {
4558 logevent("Requesting OpenSSH-style agent forwarding");
4559 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4560 ssh2_pkt_adduint32(mainchan
->remoteid
);
4561 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4562 ssh2_pkt_addbool(1); /* want reply */
4566 crWaitUntilV(ispkt
);
4567 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4568 unsigned i
= ssh2_pkt_getuint32();
4569 struct ssh_channel
*c
;
4570 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4572 continue; /* nonexistent channel */
4573 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4575 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4577 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4578 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4579 bombout(("Unexpected response to agent forwarding request:"
4580 " packet type %d", pktin
.type
));
4583 logevent("Agent forwarding refused");
4585 logevent("Agent forwarding enabled");
4586 ssh_agentfwd_enabled
= TRUE
;
4591 * Now allocate a pty for the session.
4594 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4595 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4596 ssh2_pkt_addstring("pty-req");
4597 ssh2_pkt_addbool(1); /* want reply */
4598 ssh2_pkt_addstring(cfg
.termtype
);
4599 ssh2_pkt_adduint32(cols
);
4600 ssh2_pkt_adduint32(rows
);
4601 ssh2_pkt_adduint32(0); /* pixel width */
4602 ssh2_pkt_adduint32(0); /* pixel height */
4603 ssh2_pkt_addstring_start();
4604 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4606 ssh_state
= SSH_STATE_INTERMED
;
4609 crWaitUntilV(ispkt
);
4610 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4611 unsigned i
= ssh2_pkt_getuint32();
4612 struct ssh_channel
*c
;
4613 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4615 continue; /* nonexistent channel */
4616 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4618 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4620 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4621 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4622 bombout(("Unexpected response to pty request:"
4623 " packet type %d", pktin
.type
));
4626 c_write_str("Server refused to allocate pty\r\n");
4627 ssh_editing
= ssh_echoing
= 1;
4629 logevent("Allocated pty");
4632 ssh_editing
= ssh_echoing
= 1;
4636 * Start a shell or a remote command. We may have to attempt
4637 * this twice if the config data has provided a second choice
4644 if (ssh_fallback_cmd
) {
4645 subsys
= cfg
.ssh_subsys2
;
4646 cmd
= cfg
.remote_cmd_ptr2
;
4648 subsys
= cfg
.ssh_subsys
;
4649 cmd
= cfg
.remote_cmd_ptr
;
4652 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4653 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4655 ssh2_pkt_addstring("subsystem");
4656 ssh2_pkt_addbool(1); /* want reply */
4657 ssh2_pkt_addstring(cmd
);
4659 ssh2_pkt_addstring("exec");
4660 ssh2_pkt_addbool(1); /* want reply */
4661 ssh2_pkt_addstring(cmd
);
4663 ssh2_pkt_addstring("shell");
4664 ssh2_pkt_addbool(1); /* want reply */
4668 crWaitUntilV(ispkt
);
4669 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4670 unsigned i
= ssh2_pkt_getuint32();
4671 struct ssh_channel
*c
;
4672 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4674 continue; /* nonexistent channel */
4675 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4677 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4678 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4679 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4680 bombout(("Unexpected response to shell/command request:"
4681 " packet type %d", pktin
.type
));
4685 * We failed to start the command. If this is the
4686 * fallback command, we really are finished; if it's
4687 * not, and if the fallback command exists, try falling
4688 * back to it before complaining.
4690 if (!ssh_fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
4691 logevent("Primary command failed; attempting fallback");
4692 ssh_fallback_cmd
= TRUE
;
4695 bombout(("Server refused to start a shell/command"));
4698 logevent("Started a shell/command");
4703 ssh_state
= SSH_STATE_SESSION
;
4707 ssh_special(TS_EOF
);
4712 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
4715 static int try_send
;
4719 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4720 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4723 unsigned i
= ssh2_pkt_getuint32();
4724 struct ssh_channel
*c
;
4725 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4727 continue; /* nonexistent channel */
4728 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4729 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4730 continue; /* extended but not stderr */
4731 ssh2_pkt_getstring(&data
, &length
);
4734 c
->v
.v2
.locwindow
-= length
;
4736 case CHAN_MAINSESSION
:
4738 from_backend(pktin
.type
==
4739 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
4743 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
4746 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
4749 while (length
> 0) {
4750 if (c
->u
.a
.lensofar
< 4) {
4751 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4752 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4756 c
->u
.a
.lensofar
+= l
;
4758 if (c
->u
.a
.lensofar
== 4) {
4760 4 + GET_32BIT(c
->u
.a
.msglen
);
4761 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4762 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4764 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4766 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4768 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4772 c
->u
.a
.lensofar
+= l
;
4774 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4775 void *reply
, *sentreply
;
4777 agent_query(c
->u
.a
.message
,
4778 c
->u
.a
.totallen
, &reply
,
4783 /* Fake SSH_AGENT_FAILURE. */
4784 sentreply
= "\0\0\0\1\5";
4787 ssh2_add_channel_data(c
, sentreply
,
4792 sfree(c
->u
.a
.message
);
4793 c
->u
.a
.lensofar
= 0;
4800 * If we are not buffering too much data,
4801 * enlarge the window again at the remote side.
4803 if (bufsize
< OUR_V2_WINSIZE
)
4804 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
4806 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4807 ssh_state
= SSH_STATE_CLOSED
;
4808 logevent("Received disconnect message");
4810 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4811 unsigned i
= ssh2_pkt_getuint32();
4812 struct ssh_channel
*c
;
4814 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4816 continue; /* nonexistent channel */
4818 if (c
->type
== CHAN_X11
) {
4820 * Remote EOF on an X11 channel means we should
4821 * wrap up and close the channel ourselves.
4823 x11_close(c
->u
.x11
.s
);
4825 } else if (c
->type
== CHAN_AGENT
) {
4827 } else if (c
->type
== CHAN_SOCKDATA
) {
4828 pfd_close(c
->u
.pfd
.s
);
4831 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4832 unsigned i
= ssh2_pkt_getuint32();
4833 struct ssh_channel
*c
;
4835 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4837 continue; /* nonexistent channel */
4838 /* Do pre-close processing on the channel. */
4840 case CHAN_MAINSESSION
:
4841 break; /* nothing to see here, move along */
4843 if (c
->u
.x11
.s
!= NULL
)
4844 x11_close(c
->u
.x11
.s
);
4851 if (c
->u
.pfd
.s
!= NULL
)
4852 pfd_close(c
->u
.pfd
.s
);
4856 if (c
->closes
== 0) {
4857 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4858 ssh2_pkt_adduint32(c
->remoteid
);
4861 del234(ssh_channels
, c
);
4862 bufchain_clear(&c
->v
.v2
.outbuffer
);
4866 * See if that was the last channel left open.
4868 if (count234(ssh_channels
) == 0) {
4869 logevent("All channels closed. Disconnecting");
4870 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4871 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4872 ssh2_pkt_addstring("All open channels closed");
4873 ssh2_pkt_addstring("en"); /* language tag */
4875 ssh_state
= SSH_STATE_CLOSED
;
4878 continue; /* remote sends close; ignore (FIXME) */
4879 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4880 unsigned i
= ssh2_pkt_getuint32();
4881 struct ssh_channel
*c
;
4882 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4884 continue; /* nonexistent channel */
4885 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4887 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4888 unsigned i
= ssh2_pkt_getuint32();
4889 struct ssh_channel
*c
;
4890 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4892 continue; /* nonexistent channel */
4893 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4894 continue; /* dunno why they're confirming this */
4895 c
->remoteid
= ssh2_pkt_getuint32();
4896 c
->type
= CHAN_SOCKDATA
;
4897 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4898 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4899 bufchain_init(&c
->v
.v2
.outbuffer
);
4901 pfd_confirm(c
->u
.pfd
.s
);
4904 * We have a pending close on this channel,
4905 * which we decided on before the server acked
4906 * the channel open. So now we know the
4907 * remoteid, we can close it again.
4909 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4910 ssh2_pkt_adduint32(c
->remoteid
);
4913 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
4914 unsigned i
= ssh2_pkt_getuint32();
4915 struct ssh_channel
*c
;
4916 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4918 continue; /* nonexistent channel */
4919 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4920 continue; /* dunno why they're failing this */
4922 logevent("Forwarded connection refused by server");
4924 pfd_close(c
->u
.pfd
.s
);
4926 del234(ssh_channels
, c
);
4928 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4931 int typelen
, want_reply
;
4932 struct ssh_channel
*c
;
4934 localid
= ssh2_pkt_getuint32();
4935 ssh2_pkt_getstring(&type
, &typelen
);
4936 want_reply
= ssh2_pkt_getbool();
4939 * First, check that the channel exists. Otherwise,
4940 * we can instantly disconnect with a rude message.
4942 c
= find234(ssh_channels
, &localid
, ssh_channelfind
);
4945 sprintf(buf
, "Received channel request for nonexistent"
4946 " channel %d", localid
);
4948 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4949 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4950 ssh2_pkt_addstring(buf
);
4951 ssh2_pkt_addstring("en"); /* language tag */
4953 connection_fatal(buf
);
4954 ssh_state
= SSH_STATE_CLOSED
;
4959 * We don't recognise any form of channel request,
4960 * so we now either ignore the request or respond
4961 * with CHANNEL_FAILURE, depending on want_reply.
4964 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE
);
4965 ssh2_pkt_adduint32(c
->remoteid
);
4968 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4972 struct ssh_channel
*c
;
4973 unsigned remid
, winsize
, pktsize
;
4974 ssh2_pkt_getstring(&type
, &typelen
);
4975 c
= smalloc(sizeof(struct ssh_channel
));
4977 remid
= ssh2_pkt_getuint32();
4978 winsize
= ssh2_pkt_getuint32();
4979 pktsize
= ssh2_pkt_getuint32();
4981 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4982 if (!ssh_X11_fwd_enabled
)
4983 error
= "X11 forwarding is not enabled";
4984 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4986 error
= "Unable to open an X11 connection";
4990 } else if (typelen
== 15 &&
4991 !memcmp(type
, "forwarded-tcpip", 15)) {
4992 struct ssh_rportfwd pf
, *realpf
;
4995 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
4996 pf
.sport
= ssh2_pkt_getuint32();
4997 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
4998 if (realpf
== NULL
) {
4999 error
= "Remote port is not recognised";
5001 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
5004 sprintf(buf
, "Received remote port open request for %s:%d",
5005 realpf
->dhost
, realpf
->dport
);
5008 sprintf(buf
, "Port open failed: %s", e
);
5010 error
= "Port open failed";
5012 logevent("Forwarded port opened successfully");
5013 c
->type
= CHAN_SOCKDATA
;
5016 } else if (typelen
== 22 &&
5017 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5018 if (!ssh_agentfwd_enabled
)
5019 error
= "Agent forwarding is not enabled";
5021 c
->type
= CHAN_AGENT
; /* identify channel type */
5022 c
->u
.a
.lensofar
= 0;
5025 error
= "Unsupported channel type requested";
5028 c
->remoteid
= remid
;
5030 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5031 ssh2_pkt_adduint32(c
->remoteid
);
5032 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
5033 ssh2_pkt_addstring(error
);
5034 ssh2_pkt_addstring("en"); /* language tag */
5038 c
->localid
= alloc_channel_id();
5040 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5041 c
->v
.v2
.remwindow
= winsize
;
5042 c
->v
.v2
.remmaxpkt
= pktsize
;
5043 bufchain_init(&c
->v
.v2
.outbuffer
);
5044 add234(ssh_channels
, c
);
5045 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5046 ssh2_pkt_adduint32(c
->remoteid
);
5047 ssh2_pkt_adduint32(c
->localid
);
5048 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
5049 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5053 bombout(("Strange packet received: type %d", pktin
.type
));
5058 * We have spare data. Add it to the channel buffer.
5060 ssh2_add_channel_data(mainchan
, in
, inlen
);
5065 struct ssh_channel
*c
;
5067 * Try to send data on all channels if we can.
5069 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
5070 int bufsize
= ssh2_try_send(c
);
5073 case CHAN_MAINSESSION
:
5074 /* stdin need not receive an unthrottle
5075 * notification since it will be polled */
5078 x11_unthrottle(c
->u
.x11
.s
);
5081 /* agent sockets are request/response and need no
5082 * buffer management */
5085 pfd_unthrottle(c
->u
.pfd
.s
);
5097 * Handle the top-level SSH2 protocol.
5099 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
5101 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
5103 do_ssh2_authconn(in
, inlen
, ispkt
);
5107 * Called to set up the connection.
5109 * Returns an error message, or NULL on success.
5111 static char *ssh_init(char *host
, int port
, char **realhost
)
5116 if (crypto_startup() == 0)
5117 return "Microsoft high encryption pack not installed!";
5123 ssh1_throttle_count
= 0;
5124 ssh_overall_bufsize
= 0;
5125 ssh_fallback_cmd
= 0;
5127 p
= connect_to_host(host
, port
, realhost
);
5135 * Called to send data down the Telnet connection.
5137 static int ssh_send(char *buf
, int len
)
5139 if (s
== NULL
|| ssh_protocol
== NULL
)
5142 ssh_protocol(buf
, len
, 0);
5144 return ssh_sendbuffer();
5148 * Called to query the current amount of buffered stdin data.
5150 static int ssh_sendbuffer(void)
5154 if (s
== NULL
|| ssh_protocol
== NULL
)
5158 * If the SSH socket itself has backed up, add the total backup
5159 * size on that to any individual buffer on the stdin channel.
5162 if (ssh_throttled_all
)
5163 override_value
= ssh_overall_bufsize
;
5165 if (ssh_version
== 1) {
5166 return override_value
;
5167 } else if (ssh_version
== 2) {
5168 if (!mainchan
|| mainchan
->closes
> 0)
5169 return override_value
;
5171 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
5178 * Called to set the size of the window from SSH's POV.
5180 static void ssh_size(void)
5182 switch (ssh_state
) {
5183 case SSH_STATE_BEFORE_SIZE
:
5184 case SSH_STATE_PREPACKET
:
5185 case SSH_STATE_CLOSED
:
5186 break; /* do nothing */
5187 case SSH_STATE_INTERMED
:
5188 size_needed
= TRUE
; /* buffer for later */
5190 case SSH_STATE_SESSION
:
5192 if (ssh_version
== 1) {
5193 send_packet(SSH1_CMSG_WINDOW_SIZE
,
5194 PKT_INT
, rows
, PKT_INT
, cols
,
5195 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5197 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5198 ssh2_pkt_adduint32(mainchan
->remoteid
);
5199 ssh2_pkt_addstring("window-change");
5200 ssh2_pkt_addbool(0);
5201 ssh2_pkt_adduint32(cols
);
5202 ssh2_pkt_adduint32(rows
);
5203 ssh2_pkt_adduint32(0);
5204 ssh2_pkt_adduint32(0);
5213 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5214 * can send an EOF and collect resulting output (e.g. `plink
5217 static void ssh_special(Telnet_Special code
)
5219 if (code
== TS_EOF
) {
5220 if (ssh_state
!= SSH_STATE_SESSION
) {
5222 * Buffer the EOF in case we are pre-SESSION, so we can
5223 * send it as soon as we reach SESSION.
5229 if (ssh_version
== 1) {
5230 send_packet(SSH1_CMSG_EOF
, PKT_END
);
5232 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
5233 ssh2_pkt_adduint32(mainchan
->remoteid
);
5236 logevent("Sent EOF message");
5237 } else if (code
== TS_PING
) {
5238 if (ssh_state
== SSH_STATE_CLOSED
5239 || ssh_state
== SSH_STATE_PREPACKET
) return;
5240 if (ssh_version
== 1) {
5241 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5243 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5244 ssh2_pkt_addstring_start();
5252 void *new_sock_channel(Socket s
)
5254 struct ssh_channel
*c
;
5255 c
= smalloc(sizeof(struct ssh_channel
));
5258 c
->remoteid
= -1; /* to be set when open confirmed */
5259 c
->localid
= alloc_channel_id();
5261 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5263 add234(ssh_channels
, c
);
5269 * This is called when stdout/stderr (the entity to which
5270 * from_backend sends data) manages to clear some backlog.
5272 void ssh_unthrottle(int bufsize
)
5274 if (ssh_version
== 1) {
5275 if (ssh1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
5276 ssh1_stdout_throttling
= 0;
5280 if (mainchan
&& mainchan
->closes
== 0)
5281 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5285 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5287 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5290 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5293 if (ssh_version
== 1) {
5294 send_packet(SSH1_MSG_PORT_OPEN
,
5295 PKT_INT
, c
->localid
,
5298 //PKT_STR, <org:orgport>,
5301 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5302 ssh2_pkt_addstring("direct-tcpip");
5303 ssh2_pkt_adduint32(c
->localid
);
5304 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5305 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5306 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5307 ssh2_pkt_addstring(hostname
);
5308 ssh2_pkt_adduint32(port
);
5310 * We make up values for the originator data; partly it's
5311 * too much hassle to keep track, and partly I'm not
5312 * convinced the server should be told details like that
5313 * about my local network configuration.
5315 ssh2_pkt_addstring("client-side-connection");
5316 ssh2_pkt_adduint32(0);
5322 static Socket
ssh_socket(void)
5327 static int ssh_sendok(void)
5332 static int ssh_ldisc(int option
)
5334 if (option
== LD_ECHO
)
5336 if (option
== LD_EDIT
)
5341 Backend ssh_backend
= {