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
;
946 debug(("Packet payload pre-compression:\n"));
947 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
950 if (ssh1_compressing
) {
951 unsigned char *compblk
;
953 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
955 ssh1_pktout_size(complen
- 1);
956 memcpy(pktout
.body
- 1, compblk
, complen
);
959 debug(("Packet payload post-compression:\n"));
960 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
964 len
= pktout
.length
+ 5; /* type and CRC */
968 for (i
= 0; i
< pad
; i
++)
969 pktout
.data
[i
+ 4] = random_byte();
970 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
971 PUT_32BIT(pktout
.data
+ biglen
, crc
);
972 PUT_32BIT(pktout
.data
, len
);
975 debug(("Sending packet len=%d\n", biglen
+ 4));
976 dmemdump(pktout
.data
, biglen
+ 4);
979 cipher
->encrypt(pktout
.data
+ 4, biglen
);
984 static void s_wrpkt(void)
987 len
= s_wrpkt_prepare();
988 backlog
= sk_write(s
, pktout
.data
, len
);
989 if (backlog
> SSH_MAX_BACKLOG
)
990 ssh_throttle_all(1, backlog
);
993 static void s_wrpkt_defer(void)
996 len
= s_wrpkt_prepare();
997 if (deferred_len
+ len
> deferred_size
) {
998 deferred_size
= deferred_len
+ len
+ 128;
999 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1001 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1002 deferred_len
+= len
;
1006 * Construct a packet with the specified contents.
1008 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1010 unsigned char *p
, *argp
, argchar
;
1011 unsigned long argint
;
1012 int pktlen
, argtype
, arglen
;
1016 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1019 (void) va_arg(ap1
, int);
1023 (void) va_arg(ap1
, char);
1027 (void) va_arg(ap1
, unsigned char *);
1028 arglen
= va_arg(ap1
, int);
1032 argp
= va_arg(ap1
, unsigned char *);
1033 arglen
= strlen(argp
);
1034 pktlen
+= 4 + arglen
;
1037 bn
= va_arg(ap1
, Bignum
);
1038 pktlen
+= ssh1_bignum_length(bn
);
1045 s_wrpkt_start(pkttype
, pktlen
);
1048 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1051 argint
= va_arg(ap2
, int);
1052 PUT_32BIT(p
, argint
);
1056 argchar
= va_arg(ap2
, unsigned char);
1061 argp
= va_arg(ap2
, unsigned char *);
1062 arglen
= va_arg(ap2
, int);
1063 memcpy(p
, argp
, arglen
);
1067 argp
= va_arg(ap2
, unsigned char *);
1068 arglen
= strlen(argp
);
1069 PUT_32BIT(p
, arglen
);
1070 memcpy(p
+ 4, argp
, arglen
);
1074 bn
= va_arg(ap2
, Bignum
);
1075 p
+= ssh1_write_bignum(p
, bn
);
1081 static void send_packet(int pkttype
, ...)
1084 va_start(ap1
, pkttype
);
1085 va_start(ap2
, pkttype
);
1086 construct_packet(pkttype
, ap1
, ap2
);
1090 static void defer_packet(int pkttype
, ...)
1093 va_start(ap1
, pkttype
);
1094 va_start(ap2
, pkttype
);
1095 construct_packet(pkttype
, ap1
, ap2
);
1099 static int ssh_versioncmp(char *a
, char *b
)
1102 unsigned long av
, bv
;
1104 av
= strtoul(a
, &ae
, 10);
1105 bv
= strtoul(b
, &be
, 10);
1107 return (av
< bv ?
-1 : +1);
1112 av
= strtoul(ae
, &ae
, 10);
1113 bv
= strtoul(be
, &be
, 10);
1115 return (av
< bv ?
-1 : +1);
1121 * Utility routines for putting an SSH-protocol `string' and
1122 * `uint32' into a SHA state.
1125 static void sha_string(SHA_State
* s
, void *str
, int len
)
1127 unsigned char lenblk
[4];
1128 PUT_32BIT(lenblk
, len
);
1129 SHA_Bytes(s
, lenblk
, 4);
1130 SHA_Bytes(s
, str
, len
);
1133 static void sha_uint32(SHA_State
* s
, unsigned i
)
1135 unsigned char intblk
[4];
1136 PUT_32BIT(intblk
, i
);
1137 SHA_Bytes(s
, intblk
, 4);
1141 * SSH2 packet construction functions.
1143 static void ssh2_pkt_ensure(int length
)
1145 if (pktout
.maxlen
< length
) {
1146 pktout
.maxlen
= length
+ 256;
1149 NULL ?
smalloc(pktout
.maxlen
+
1150 APIEXTRA
) : srealloc(pktout
.data
,
1154 fatalbox("Out of memory");
1157 static void ssh2_pkt_adddata(void *data
, int len
)
1159 pktout
.length
+= len
;
1160 ssh2_pkt_ensure(pktout
.length
);
1161 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1163 static void ssh2_pkt_addbyte(unsigned char byte
)
1165 ssh2_pkt_adddata(&byte
, 1);
1167 static void ssh2_pkt_init(int pkt_type
)
1170 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1172 static void ssh2_pkt_addbool(unsigned char value
)
1174 ssh2_pkt_adddata(&value
, 1);
1176 static void ssh2_pkt_adduint32(unsigned long value
)
1179 PUT_32BIT(x
, value
);
1180 ssh2_pkt_adddata(x
, 4);
1182 static void ssh2_pkt_addstring_start(void)
1184 ssh2_pkt_adduint32(0);
1185 pktout
.savedpos
= pktout
.length
;
1187 static void ssh2_pkt_addstring_str(char *data
)
1189 ssh2_pkt_adddata(data
, strlen(data
));
1190 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1191 pktout
.length
- pktout
.savedpos
);
1193 static void ssh2_pkt_addstring_data(char *data
, int len
)
1195 ssh2_pkt_adddata(data
, len
);
1196 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1197 pktout
.length
- pktout
.savedpos
);
1199 static void ssh2_pkt_addstring(char *data
)
1201 ssh2_pkt_addstring_start();
1202 ssh2_pkt_addstring_str(data
);
1204 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1207 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1210 fatalbox("out of memory");
1212 for (i
= 1; i
<= n
; i
++)
1213 p
[i
] = bignum_byte(b
, n
- i
);
1215 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1217 memmove(p
, p
+ i
, n
+ 1 - i
);
1221 static void ssh2_pkt_addmp(Bignum b
)
1225 p
= ssh2_mpint_fmt(b
, &len
);
1226 ssh2_pkt_addstring_start();
1227 ssh2_pkt_addstring_data(p
, len
);
1232 * Construct an SSH2 final-form packet: compress it, encrypt it,
1233 * put the MAC on it. Final packet, ready to be sent, is stored in
1234 * pktout.data. Total length is returned.
1236 static int ssh2_pkt_construct(void)
1238 int cipherblk
, maclen
, padding
, i
;
1239 static unsigned long outgoing_sequence
= 0;
1242 * Compress packet payload.
1245 debug(("Pre-compression payload:\n"));
1246 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1249 unsigned char *newpayload
;
1251 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1252 &newpayload
, &newlen
)) {
1254 ssh2_pkt_adddata(newpayload
, newlen
);
1260 * Add padding. At least four bytes, and must also bring total
1261 * length (minus MAC) up to a multiple of the block size.
1263 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1264 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1267 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1268 maclen
= csmac ? csmac
->len
: 0;
1269 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1270 pktout
.data
[4] = padding
;
1271 for (i
= 0; i
< padding
; i
++)
1272 pktout
.data
[pktout
.length
+ i
] = random_byte();
1273 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1275 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1277 outgoing_sequence
++; /* whether or not we MACed */
1280 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1281 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1285 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1287 /* Ready-to-send packet starts at pktout.data. We return length. */
1288 return pktout
.length
+ padding
+ maclen
;
1292 * Construct and send an SSH2 packet immediately.
1294 static void ssh2_pkt_send(void)
1298 len
= ssh2_pkt_construct();
1299 backlog
= sk_write(s
, pktout
.data
, len
);
1300 if (backlog
> SSH_MAX_BACKLOG
)
1301 ssh_throttle_all(1, backlog
);
1305 * Construct an SSH2 packet and add it to a deferred data block.
1306 * Useful for sending multiple packets in a single sk_write() call,
1307 * to prevent a traffic-analysing listener from being able to work
1308 * out the length of any particular packet (such as the password
1311 * Note that because SSH2 sequence-numbers its packets, this can
1312 * NOT be used as an m4-style `defer' allowing packets to be
1313 * constructed in one order and sent in another.
1315 static void ssh2_pkt_defer(void)
1317 int len
= ssh2_pkt_construct();
1318 if (deferred_len
+ len
> deferred_size
) {
1319 deferred_size
= deferred_len
+ len
+ 128;
1320 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1322 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1323 deferred_len
+= len
;
1327 * Send the whole deferred data block constructed by
1328 * ssh2_pkt_defer() or SSH1's defer_packet().
1330 static void ssh_pkt_defersend(void)
1333 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1334 deferred_len
= deferred_size
= 0;
1335 sfree(deferred_send_data
);
1336 deferred_send_data
= NULL
;
1337 if (backlog
> SSH_MAX_BACKLOG
)
1338 ssh_throttle_all(1, backlog
);
1342 void bndebug(char *string
, Bignum b
)
1346 p
= ssh2_mpint_fmt(b
, &len
);
1347 debug(("%s", string
));
1348 for (i
= 0; i
< len
; i
++)
1349 debug((" %02x", p
[i
]));
1355 static void sha_mpint(SHA_State
* s
, Bignum b
)
1359 p
= ssh2_mpint_fmt(b
, &len
);
1360 sha_string(s
, p
, len
);
1365 * SSH2 packet decode functions.
1367 static unsigned long ssh2_pkt_getuint32(void)
1369 unsigned long value
;
1370 if (pktin
.length
- pktin
.savedpos
< 4)
1371 return 0; /* arrgh, no way to decline (FIXME?) */
1372 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1373 pktin
.savedpos
+= 4;
1376 static int ssh2_pkt_getbool(void)
1378 unsigned long value
;
1379 if (pktin
.length
- pktin
.savedpos
< 1)
1380 return 0; /* arrgh, no way to decline (FIXME?) */
1381 value
= pktin
.data
[pktin
.savedpos
] != 0;
1385 static void ssh2_pkt_getstring(char **p
, int *length
)
1388 if (pktin
.length
- pktin
.savedpos
< 4)
1390 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1391 pktin
.savedpos
+= 4;
1392 if (pktin
.length
- pktin
.savedpos
< *length
)
1394 *p
= pktin
.data
+ pktin
.savedpos
;
1395 pktin
.savedpos
+= *length
;
1397 static Bignum
ssh2_pkt_getmp(void)
1403 ssh2_pkt_getstring(&p
, &length
);
1407 bombout(("internal error: Can't handle negative mpints"));
1410 b
= bignum_from_bytes(p
, length
);
1415 * Examine the remote side's version string and compare it against
1416 * a list of known buggy implementations.
1418 static void ssh_detect_bugs(char *vstring
)
1420 char *imp
; /* pointer to implementation part */
1422 imp
+= strcspn(imp
, "-");
1424 imp
+= strcspn(imp
, "-");
1427 ssh_remote_bugs
= 0;
1429 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1430 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1431 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")) {
1433 * These versions don't support SSH1_MSG_IGNORE, so we have
1434 * to use a different defence against password length
1437 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1438 logevent("We believe remote version has SSH1 ignore bug");
1441 if (!strcmp(imp
, "Cisco-1.25")) {
1443 * These versions need a plain password sent; they can't
1444 * handle having a null and a random length of data after
1447 ssh_remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1448 logevent("We believe remote version needs a plain SSH1 password");
1451 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1452 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1453 !strncmp(imp
, "2.1 ", 4)) {
1455 * These versions have the HMAC bug.
1457 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1458 logevent("We believe remote version has SSH2 HMAC bug");
1462 static int do_ssh_init(unsigned char c
)
1465 static char version
[10];
1466 static char *vstring
;
1467 static int vstrsize
;
1473 /* Search for the string "SSH-" in the input. */
1476 static const int transS
[] = { 1, 2, 2, 1 };
1477 static const int transH
[] = { 0, 0, 3, 0 };
1478 static const int transminus
[] = { 0, 0, 0, -1 };
1489 crReturn(1); /* get another character */
1493 vstring
= smalloc(vstrsize
);
1494 strcpy(vstring
, "SSH-");
1498 crReturn(1); /* get another char */
1499 if (vslen
>= vstrsize
- 1) {
1501 vstring
= srealloc(vstring
, vstrsize
);
1503 vstring
[vslen
++] = c
;
1508 } else if (i
< sizeof(version
) - 1)
1510 } else if (c
== '\n')
1514 ssh_agentfwd_enabled
= FALSE
;
1515 rdpkt2_state
.incoming_sequence
= 0;
1518 vlog
= smalloc(20 + vslen
);
1519 vstring
[strcspn (vstring
, "\r\n")] = '\0'; /* remove end-of-line chars */
1520 sprintf(vlog
, "Server version: %s", vstring
);
1522 ssh_detect_bugs(vstring
);
1526 * Server version "1.99" means we can choose whether we use v1
1527 * or v2 protocol. Choice is based on cfg.sshprot.
1529 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1531 * This is a v2 server. Begin v2 protocol.
1533 char verstring
[80], vlog
[100];
1534 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1535 SHA_Init(&exhashbase
);
1537 * Hash our version string and their version string.
1539 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1540 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1541 sprintf(vlog
, "We claim version: %s", verstring
);
1543 strcat(verstring
, "\n");
1544 logevent("Using SSH protocol version 2");
1545 sk_write(s
, verstring
, strlen(verstring
));
1546 ssh_protocol
= ssh2_protocol
;
1548 s_rdpkt
= ssh2_rdpkt
;
1551 * This is a v1 server. Begin v1 protocol.
1553 char verstring
[80], vlog
[100];
1554 sprintf(verstring
, "SSH-%s-%s",
1555 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1557 sprintf(vlog
, "We claim version: %s", verstring
);
1559 strcat(verstring
, "\n");
1560 logevent("Using SSH protocol version 1");
1561 sk_write(s
, verstring
, strlen(verstring
));
1562 ssh_protocol
= ssh1_protocol
;
1564 s_rdpkt
= ssh1_rdpkt
;
1566 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1573 static void ssh_gotdata(unsigned char *data
, int datalen
)
1578 * To begin with, feed the characters one by one to the
1579 * protocol initialisation / selection function do_ssh_init().
1580 * When that returns 0, we're done with the initial greeting
1581 * exchange and can move on to packet discipline.
1586 crReturnV
; /* more data please */
1587 ret
= do_ssh_init(*data
);
1595 * We emerge from that loop when the initial negotiation is
1596 * over and we have selected an s_rdpkt function. Now pass
1597 * everything to s_rdpkt, and then pass the resulting packets
1598 * to the proper protocol handler.
1603 while (datalen
> 0) {
1604 if (s_rdpkt(&data
, &datalen
) == 0) {
1605 if (ssh_state
== SSH_STATE_CLOSED
) {
1608 ssh_protocol(NULL
, 0, 1);
1609 if (ssh_state
== SSH_STATE_CLOSED
) {
1619 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1622 ssh_state
= SSH_STATE_CLOSED
;
1628 /* A socket error has occurred. */
1629 connection_fatal(error_msg
);
1631 /* Otherwise, the remote side closed the connection normally. */
1636 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1638 ssh_gotdata(data
, len
);
1639 if (ssh_state
== SSH_STATE_CLOSED
) {
1649 static void ssh_sent(Plug plug
, int bufsize
)
1652 * If the send backlog on the SSH socket itself clears, we
1653 * should unthrottle the whole world if it was throttled.
1655 if (bufsize
< SSH_MAX_BACKLOG
)
1656 ssh_throttle_all(0, bufsize
);
1660 * Connect to specified host and port.
1661 * Returns an error message, or NULL on success.
1662 * Also places the canonical host name into `realhost'. It must be
1663 * freed by the caller.
1665 static char *connect_to_host(char *host
, int port
, char **realhost
)
1667 static struct plug_function_table fn_table
= {
1672 }, *fn_table_ptr
= &fn_table
;
1681 savedhost
= smalloc(1 + strlen(host
));
1683 fatalbox("Out of memory");
1684 strcpy(savedhost
, host
);
1687 port
= 22; /* default ssh port */
1702 sprintf(buf
, "Looking up host \"%.170s\"", host
);
1705 addr
= sk_namelookup(host
, realhost
);
1706 if ((err
= sk_addr_error(addr
)))
1710 *realhost
= strdup(FWhost
);
1717 char buf
[200], addrbuf
[100];
1718 sk_getaddr(addr
, addrbuf
, 100);
1719 sprintf(buf
, "Connecting to %.100s port %d", addrbuf
, port
);
1722 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1723 if ((err
= sk_socket_error(s
)))
1727 sk_write(s
, "connect ", 8);
1728 sk_write(s
, FWhost
, strlen(FWhost
));
1731 sprintf(buf
, " %d\n", FWport
);
1732 sk_write(s
, buf
, strlen(buf
));
1740 * Throttle or unthrottle the SSH connection.
1742 static void ssh1_throttle(int adjust
)
1744 int old_count
= ssh1_throttle_count
;
1745 ssh1_throttle_count
+= adjust
;
1746 assert(ssh1_throttle_count
>= 0);
1747 if (ssh1_throttle_count
&& !old_count
) {
1748 sk_set_frozen(s
, 1);
1749 } else if (!ssh1_throttle_count
&& old_count
) {
1750 sk_set_frozen(s
, 0);
1755 * Throttle or unthrottle _all_ local data streams (for when sends
1756 * on the SSH connection itself back up).
1758 static void ssh_throttle_all(int enable
, int bufsize
)
1761 struct ssh_channel
*c
;
1763 if (enable
== ssh_throttled_all
)
1765 ssh_throttled_all
= enable
;
1766 ssh_overall_bufsize
= bufsize
;
1769 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1771 case CHAN_MAINSESSION
:
1773 * This is treated separately, outside the switch.
1777 x11_override_throttle(c
->u
.x11
.s
, enable
);
1780 /* Agent channels require no buffer management. */
1783 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1790 * Handle the key exchange and user authentication phases.
1792 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1796 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1797 unsigned char cookie
[8];
1798 struct RSAKey servkey
, hostkey
;
1799 struct MD5Context md5c
;
1800 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1801 static int tried_publickey
;
1802 static int tis_auth_refused
, ccard_auth_refused
;
1803 static unsigned char session_id
[16];
1804 static int cipher_type
;
1805 static char username
[100];
1812 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1813 bombout(("Public key packet not received"));
1817 logevent("Received public keys");
1819 memcpy(cookie
, pktin
.body
, 8);
1821 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1822 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1825 * Log the host key fingerprint.
1829 logevent("Host key fingerprint is:");
1830 strcpy(logmsg
, " ");
1831 hostkey
.comment
= NULL
;
1832 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1833 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1837 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1838 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1839 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1841 ssh1_local_protoflags
=
1842 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1843 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1846 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1847 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1848 MD5Update(&md5c
, pktin
.body
, 8);
1849 MD5Final(session_id
, &md5c
);
1851 for (i
= 0; i
< 32; i
++)
1852 session_key
[i
] = random_byte();
1854 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1856 rsabuf
= smalloc(len
);
1858 fatalbox("Out of memory");
1861 * Verify the host key.
1865 * First format the key into a string.
1867 int len
= rsastr_len(&hostkey
);
1868 char fingerprint
[100];
1869 char *keystr
= smalloc(len
);
1871 fatalbox("Out of memory");
1872 rsastr_fmt(keystr
, &hostkey
);
1873 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1874 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1879 for (i
= 0; i
< 32; i
++) {
1880 rsabuf
[i
] = session_key
[i
];
1882 rsabuf
[i
] ^= session_id
[i
];
1885 if (hostkey
.bytes
> servkey
.bytes
) {
1886 rsaencrypt(rsabuf
, 32, &servkey
);
1887 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1889 rsaencrypt(rsabuf
, 32, &hostkey
);
1890 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1893 logevent("Encrypted session key");
1896 int cipher_chosen
= 0, warn
= 0;
1897 char *cipher_string
= NULL
;
1898 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
1899 int next_cipher
= cfg
.ssh_cipherlist
[i
];
1900 if (next_cipher
== CIPHER_WARN
) {
1901 /* If/when we choose a cipher, warn about it */
1903 } else if (next_cipher
== CIPHER_AES
) {
1904 /* XXX Probably don't need to mention this. */
1905 logevent("AES not supported in SSH1, skipping");
1907 switch (next_cipher
) {
1908 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
1909 cipher_string
= "3DES"; break;
1910 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
1911 cipher_string
= "Blowfish"; break;
1912 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
1913 cipher_string
= "single-DES"; break;
1915 if (supported_ciphers_mask
& (1 << cipher_type
))
1919 if (!cipher_chosen
) {
1920 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
1921 bombout(("Server violates SSH 1 protocol by not "
1922 "supporting 3DES encryption"));
1924 /* shouldn't happen */
1925 bombout(("No supported ciphers found"));
1929 /* Warn about chosen cipher if necessary. */
1931 askcipher(cipher_string
, 0);
1934 switch (cipher_type
) {
1935 case SSH_CIPHER_3DES
:
1936 logevent("Using 3DES encryption");
1938 case SSH_CIPHER_DES
:
1939 logevent("Using single-DES encryption");
1941 case SSH_CIPHER_BLOWFISH
:
1942 logevent("Using Blowfish encryption");
1946 send_packet(SSH1_CMSG_SESSION_KEY
,
1947 PKT_CHAR
, cipher_type
,
1948 PKT_DATA
, cookie
, 8,
1949 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1950 PKT_DATA
, rsabuf
, len
,
1951 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1953 logevent("Trying to enable encryption...");
1957 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1958 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1959 cipher
->sesskey(session_key
);
1963 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1964 bombout(("Encryption not successfully enabled"));
1968 logevent("Successfully started encryption");
1974 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1976 if (!ssh_get_line("login as: ",
1977 username
, sizeof(username
), FALSE
)) {
1979 * get_line failed to get a username.
1982 logevent("No username provided. Abandoning session.");
1983 ssh_state
= SSH_STATE_CLOSED
;
1987 c_write_str("login as: ");
1990 crWaitUntil(!ispkt
);
1992 switch (c
= *in
++) {
2001 c_write_str("\b \b");
2008 c_write_str("\b \b");
2018 if (((c
>= ' ' && c
<= '~') ||
2019 ((unsigned char) c
>= 160))
2020 && pos
< sizeof(username
)-1) {
2021 username
[pos
++] = c
;
2027 c_write_str("\r\n");
2028 username
[strcspn(username
, "\n\r")] = '\0';
2031 strncpy(username
, cfg
.username
, 99);
2032 username
[99] = '\0';
2035 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2037 char userlog
[22 + sizeof(username
)];
2038 sprintf(userlog
, "Sent username \"%s\"", username
);
2040 if (flags
& FLAG_INTERACTIVE
&&
2041 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2042 strcat(userlog
, "\r\n");
2043 c_write_str(userlog
);
2050 tried_publickey
= 0;
2051 tis_auth_refused
= ccard_auth_refused
= 0;
2053 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2054 static char password
[100];
2055 static char prompt
[200];
2058 static int pwpkt_type
;
2059 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2061 if (agent_exists()) {
2063 * Attempt RSA authentication using Pageant.
2065 static unsigned char request
[5], *response
, *p
;
2066 static int responselen
;
2067 static int i
, nkeys
;
2068 static int authed
= FALSE
;
2071 logevent("Pageant is running. Requesting keys.");
2073 /* Request the keys held by the agent. */
2074 PUT_32BIT(request
, 1);
2075 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2076 agent_query(request
, 5, &r
, &responselen
);
2077 response
= (unsigned char *) r
;
2078 if (response
&& responselen
>= 5 &&
2079 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2081 nkeys
= GET_32BIT(p
);
2085 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2088 for (i
= 0; i
< nkeys
; i
++) {
2089 static struct RSAKey key
;
2090 static Bignum challenge
;
2091 static char *commentp
;
2092 static int commentlen
;
2096 sprintf(buf
, "Trying Pageant key #%d", i
);
2100 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2101 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2102 commentlen
= GET_32BIT(p
);
2106 send_packet(SSH1_CMSG_AUTH_RSA
,
2107 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2109 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2110 logevent("Key refused");
2113 logevent("Received RSA challenge");
2114 ssh1_read_bignum(pktin
.body
, &challenge
);
2116 char *agentreq
, *q
, *ret
;
2119 len
= 1 + 4; /* message type, bit count */
2120 len
+= ssh1_bignum_length(key
.exponent
);
2121 len
+= ssh1_bignum_length(key
.modulus
);
2122 len
+= ssh1_bignum_length(challenge
);
2123 len
+= 16; /* session id */
2124 len
+= 4; /* response format */
2125 agentreq
= smalloc(4 + len
);
2126 PUT_32BIT(agentreq
, len
);
2128 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2129 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2131 q
+= ssh1_write_bignum(q
, key
.exponent
);
2132 q
+= ssh1_write_bignum(q
, key
.modulus
);
2133 q
+= ssh1_write_bignum(q
, challenge
);
2134 memcpy(q
, session_id
, 16);
2136 PUT_32BIT(q
, 1); /* response format */
2137 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2141 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2142 logevent("Sending Pageant's response");
2143 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2144 PKT_DATA
, ret
+ 5, 16,
2148 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2150 ("Pageant's response accepted");
2151 if (flags
& FLAG_VERBOSE
) {
2153 ("Authenticated using RSA key \"");
2154 c_write(commentp
, commentlen
);
2155 c_write_str("\" from agent\r\n");
2160 ("Pageant's response not accepted");
2163 ("Pageant failed to answer challenge");
2167 logevent("No reply received from Pageant");
2170 freebn(key
.exponent
);
2171 freebn(key
.modulus
);
2180 if (*cfg
.keyfile
&& !tried_publickey
)
2181 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2183 if (cfg
.try_tis_auth
&&
2184 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2185 !tis_auth_refused
) {
2186 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2187 logevent("Requested TIS authentication");
2188 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2190 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2191 logevent("TIS authentication declined");
2192 if (flags
& FLAG_INTERACTIVE
)
2193 c_write_str("TIS authentication refused.\r\n");
2194 tis_auth_refused
= 1;
2197 int challengelen
= ((pktin
.body
[0] << 24) |
2198 (pktin
.body
[1] << 16) |
2199 (pktin
.body
[2] << 8) |
2201 logevent("Received TIS challenge");
2202 if (challengelen
> sizeof(prompt
) - 1)
2203 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2204 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2205 /* Prompt heuristic comes from OpenSSH */
2206 strncpy(prompt
+ challengelen
,
2207 memchr(prompt
, '\n', challengelen
) ?
2208 "": "\r\nResponse: ",
2209 (sizeof prompt
) - challengelen
);
2210 prompt
[(sizeof prompt
) - 1] = '\0';
2213 if (cfg
.try_tis_auth
&&
2214 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2215 !ccard_auth_refused
) {
2216 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2217 logevent("Requested CryptoCard authentication");
2218 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2220 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2221 logevent("CryptoCard authentication declined");
2222 c_write_str("CryptoCard authentication refused.\r\n");
2223 ccard_auth_refused
= 1;
2226 int challengelen
= ((pktin
.body
[0] << 24) |
2227 (pktin
.body
[1] << 16) |
2228 (pktin
.body
[2] << 8) |
2230 logevent("Received CryptoCard challenge");
2231 if (challengelen
> sizeof(prompt
) - 1)
2232 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2233 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2234 strncpy(prompt
+ challengelen
,
2235 memchr(prompt
, '\n', challengelen
) ?
2236 "" : "\r\nResponse: ",
2237 sizeof(prompt
) - challengelen
);
2238 prompt
[sizeof(prompt
) - 1] = '\0';
2241 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2242 sprintf(prompt
, "%.90s@%.90s's password: ",
2243 username
, savedhost
);
2245 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2246 char *comment
= NULL
;
2247 if (flags
& FLAG_VERBOSE
)
2248 c_write_str("Trying public key authentication.\r\n");
2249 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2250 if (flags
& FLAG_VERBOSE
)
2251 c_write_str("No passphrase required.\r\n");
2254 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2259 * Show password prompt, having first obtained it via a TIS
2260 * or CryptoCard exchange if we're doing TIS or CryptoCard
2264 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2266 * get_line failed to get a password (for example
2267 * because one was supplied on the command line
2268 * which has already failed to work). Terminate.
2270 send_packet(SSH1_MSG_DISCONNECT
,
2271 PKT_STR
, "No more passwords available to try",
2273 connection_fatal("Unable to authenticate");
2274 ssh_state
= SSH_STATE_CLOSED
;
2278 /* Prompt may have come from server. We've munged it a bit, so
2279 * we know it to be zero-terminated at least once. */
2280 c_write_untrusted(prompt
, strlen(prompt
));
2284 crWaitUntil(!ispkt
);
2286 switch (c
= *in
++) {
2307 if (pos
< sizeof(password
)-1)
2308 password
[pos
++] = c
;
2312 c_write_str("\r\n");
2316 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2318 * Try public key authentication with the specified
2321 static struct RSAKey pubkey
;
2322 static Bignum challenge
, response
;
2324 static unsigned char buffer
[32];
2326 tried_publickey
= 1;
2327 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2329 c_write_str("Couldn't load private key from ");
2330 c_write_str(cfg
.keyfile
);
2331 c_write_str(".\r\n");
2332 continue; /* go and try password */
2335 c_write_str("Wrong passphrase.\r\n");
2336 tried_publickey
= 0;
2337 continue; /* try again */
2341 * Send a public key attempt.
2343 send_packet(SSH1_CMSG_AUTH_RSA
,
2344 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2347 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2348 c_write_str("Server refused our public key.\r\n");
2349 continue; /* go and try password */
2351 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2352 bombout(("Bizarre response to offer of public key"));
2355 ssh1_read_bignum(pktin
.body
, &challenge
);
2356 response
= rsadecrypt(challenge
, &pubkey
);
2357 freebn(pubkey
.private_exponent
); /* burn the evidence */
2359 for (i
= 0; i
< 32; i
++) {
2360 buffer
[i
] = bignum_byte(response
, 31 - i
);
2364 MD5Update(&md5c
, buffer
, 32);
2365 MD5Update(&md5c
, session_id
, 16);
2366 MD5Final(buffer
, &md5c
);
2368 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2369 PKT_DATA
, buffer
, 16, PKT_END
);
2372 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2373 if (flags
& FLAG_VERBOSE
)
2375 ("Failed to authenticate with our public key.\r\n");
2376 continue; /* go and try password */
2377 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2379 ("Bizarre response to RSA authentication response"));
2383 break; /* we're through! */
2385 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2387 * Defence against traffic analysis: we send a
2388 * whole bunch of packets containing strings of
2389 * different lengths. One of these strings is the
2390 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2391 * The others are all random data in
2392 * SSH1_MSG_IGNORE packets. This way a passive
2393 * listener can't tell which is the password, and
2394 * hence can't deduce the password length.
2396 * Anybody with a password length greater than 16
2397 * bytes is going to have enough entropy in their
2398 * password that a listener won't find it _that_
2399 * much help to know how long it is. So what we'll
2402 * - if password length < 16, we send 15 packets
2403 * containing string lengths 1 through 15
2405 * - otherwise, we let N be the nearest multiple
2406 * of 8 below the password length, and send 8
2407 * packets containing string lengths N through
2408 * N+7. This won't obscure the order of
2409 * magnitude of the password length, but it will
2410 * introduce a bit of extra uncertainty.
2412 * A few servers (the old 1.2.18 through 1.2.22)
2413 * can't deal with SSH1_MSG_IGNORE. For these
2414 * servers, we need an alternative defence. We make
2415 * use of the fact that the password is interpreted
2416 * as a C string: so we can append a NUL, then some
2419 * One server (a Cisco one) can deal with neither
2420 * SSH1_MSG_IGNORE _nor_ a padded password string.
2421 * For this server we are left with no defences
2422 * against password length sniffing.
2424 if (!(ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2426 * The server can deal with SSH1_MSG_IGNORE, so
2427 * we can use the primary defence.
2429 int bottom
, top
, pwlen
, i
;
2432 pwlen
= strlen(password
);
2434 bottom
= 0; /* zero length passwords are OK! :-) */
2437 bottom
= pwlen
& ~7;
2441 assert(pwlen
>= bottom
&& pwlen
<= top
);
2443 randomstr
= smalloc(top
+ 1);
2445 for (i
= bottom
; i
<= top
; i
++) {
2447 defer_packet(pwpkt_type
, PKT_STR
, password
,
2450 for (j
= 0; j
< i
; j
++) {
2452 randomstr
[j
] = random_byte();
2453 } while (randomstr
[j
] == '\0');
2455 randomstr
[i
] = '\0';
2456 defer_packet(SSH1_MSG_IGNORE
,
2457 PKT_STR
, randomstr
, PKT_END
);
2460 logevent("Sending password with camouflage packets");
2461 ssh_pkt_defersend();
2463 else if (!(ssh_remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2465 * The server can't deal with SSH1_MSG_IGNORE
2466 * but can deal with padded passwords, so we
2467 * can use the secondary defence.
2473 len
= strlen(password
);
2474 if (len
< sizeof(string
)) {
2476 strcpy(string
, password
);
2477 len
++; /* cover the zero byte */
2478 while (len
< sizeof(string
)) {
2479 string
[len
++] = (char) random_byte();
2484 logevent("Sending length-padded password");
2485 send_packet(pwpkt_type
, PKT_INT
, len
,
2486 PKT_DATA
, s
, len
, PKT_END
);
2489 * The server has _both_
2490 * BUG_CHOKES_ON_SSH1_IGNORE and
2491 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2492 * therefore nothing we can do.
2495 len
= strlen(password
);
2496 logevent("Sending unpadded password");
2497 send_packet(pwpkt_type
, PKT_INT
, len
,
2498 PKT_DATA
, password
, len
, PKT_END
);
2501 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2504 logevent("Sent password");
2505 memset(password
, 0, strlen(password
));
2507 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2508 if (flags
& FLAG_VERBOSE
)
2509 c_write_str("Access denied\r\n");
2510 logevent("Authentication refused");
2511 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2512 logevent("Received disconnect request");
2513 ssh_state
= SSH_STATE_CLOSED
;
2515 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2516 bombout(("Strange packet received, type %d", pktin
.type
));
2521 logevent("Authentication successful");
2526 void sshfwd_close(struct ssh_channel
*c
)
2528 if (c
&& !c
->closes
) {
2529 if (ssh_version
== 1) {
2530 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2533 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2534 ssh2_pkt_adduint32(c
->remoteid
);
2538 if (c
->type
== CHAN_X11
) {
2540 logevent("Forwarded X11 connection terminated");
2541 } else if (c
->type
== CHAN_SOCKDATA
) {
2543 logevent("Forwarded port closed");
2548 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2550 if (ssh_version
== 1) {
2551 send_packet(SSH1_MSG_CHANNEL_DATA
,
2552 PKT_INT
, c
->remoteid
,
2553 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2555 * In SSH1 we can return 0 here - implying that forwarded
2556 * connections are never individually throttled - because
2557 * the only circumstance that can cause throttling will be
2558 * the whole SSH connection backing up, in which case
2559 * _everything_ will be throttled as a whole.
2563 ssh2_add_channel_data(c
, buf
, len
);
2564 return ssh2_try_send(c
);
2568 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2570 if (ssh_version
== 1) {
2571 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2572 c
->v
.v1
.throttling
= 0;
2576 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2580 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2586 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2589 if (ssh_state
== SSH_STATE_CLOSED
)
2592 if (cfg
.agentfwd
&& agent_exists()) {
2593 logevent("Requesting agent forwarding");
2594 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2598 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2599 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2600 bombout(("Protocol confusion"));
2602 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2603 logevent("Agent forwarding refused");
2605 logevent("Agent forwarding enabled");
2606 ssh_agentfwd_enabled
= TRUE
;
2610 if (cfg
.x11_forward
) {
2611 char proto
[20], data
[64];
2612 logevent("Requesting X11 forwarding");
2613 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2614 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2615 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2616 PKT_STR
, proto
, PKT_STR
, data
,
2617 PKT_INT
, 0, PKT_END
);
2619 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2620 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2625 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2626 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2627 bombout(("Protocol confusion"));
2629 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2630 logevent("X11 forwarding refused");
2632 logevent("X11 forwarding enabled");
2633 ssh_X11_fwd_enabled
= TRUE
;
2641 char sports
[256], dports
[256], host
[256];
2644 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2645 /* Add port forwardings. */
2650 while (*e
&& *e
!= '\t')
2656 while (*e
&& *e
!= ':')
2666 dport
= atoi(dports
);
2667 sport
= atoi(sports
);
2668 if (sport
&& dport
) {
2670 pfd_addforward(host
, dport
, sport
);
2671 sprintf(buf
, "Local port %d forwarding to %s:%d",
2672 sport
, host
, dport
);
2675 struct ssh_rportfwd
*pf
;
2676 pf
= smalloc(sizeof(*pf
));
2677 strcpy(pf
->dhost
, host
);
2679 if (add234(ssh_rportfwds
, pf
) != pf
) {
2681 "Duplicate remote port forwarding to %s:%d",
2686 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2687 sport
, host
, dport
);
2689 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2701 send_packet(SSH1_CMSG_REQUEST_PTY
,
2702 PKT_STR
, cfg
.termtype
,
2703 PKT_INT
, rows
, PKT_INT
, cols
,
2704 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2705 ssh_state
= SSH_STATE_INTERMED
;
2709 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2710 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2711 bombout(("Protocol confusion"));
2713 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2714 c_write_str("Server refused to allocate pty\r\n");
2715 ssh_editing
= ssh_echoing
= 1;
2717 logevent("Allocated pty");
2719 ssh_editing
= ssh_echoing
= 1;
2722 if (cfg
.compression
) {
2723 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2727 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2728 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2729 bombout(("Protocol confusion"));
2731 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2732 c_write_str("Server refused to compress\r\n");
2734 logevent("Started compression");
2735 ssh1_compressing
= TRUE
;
2736 zlib_compress_init();
2737 zlib_decompress_init();
2741 * Start the shell or command.
2743 * Special case: if the first-choice command is an SSH2
2744 * subsystem (hence not usable here) and the second choice
2745 * exists, we fall straight back to that.
2748 char *cmd
= cfg
.remote_cmd_ptr
;
2750 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
2751 cmd
= cfg
.remote_cmd_ptr2
;
2752 ssh_fallback_cmd
= TRUE
;
2755 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2757 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2758 logevent("Started session");
2761 ssh_state
= SSH_STATE_SESSION
;
2765 ssh_special(TS_EOF
);
2767 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
2769 ssh_channels
= newtree234(ssh_channelcmp
);
2773 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2774 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2775 long len
= GET_32BIT(pktin
.body
);
2777 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2778 pktin
.body
+ 4, len
);
2779 if (!ssh1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
2780 ssh1_stdout_throttling
= 1;
2783 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2784 ssh_state
= SSH_STATE_CLOSED
;
2785 logevent("Received disconnect request");
2787 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2788 /* Remote side is trying to open a channel to talk to our
2789 * X-Server. Give them back a local channel number. */
2790 struct ssh_channel
*c
;
2792 logevent("Received X11 connect request");
2793 /* Refuse if X11 forwarding is disabled. */
2794 if (!ssh_X11_fwd_enabled
) {
2795 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2796 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2797 logevent("Rejected X11 connect request");
2799 c
= smalloc(sizeof(struct ssh_channel
));
2801 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2802 logevent("opening X11 forward connection failed");
2804 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2805 PKT_INT
, GET_32BIT(pktin
.body
),
2809 ("opening X11 forward connection succeeded");
2810 c
->remoteid
= GET_32BIT(pktin
.body
);
2811 c
->localid
= alloc_channel_id();
2813 c
->v
.v1
.throttling
= 0;
2814 c
->type
= CHAN_X11
; /* identify channel type */
2815 add234(ssh_channels
, c
);
2816 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2817 PKT_INT
, c
->remoteid
, PKT_INT
,
2818 c
->localid
, PKT_END
);
2819 logevent("Opened X11 forward channel");
2822 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2823 /* Remote side is trying to open a channel to talk to our
2824 * agent. Give them back a local channel number. */
2825 struct ssh_channel
*c
;
2827 /* Refuse if agent forwarding is disabled. */
2828 if (!ssh_agentfwd_enabled
) {
2829 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2830 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2832 c
= smalloc(sizeof(struct ssh_channel
));
2833 c
->remoteid
= GET_32BIT(pktin
.body
);
2834 c
->localid
= alloc_channel_id();
2836 c
->v
.v1
.throttling
= 0;
2837 c
->type
= CHAN_AGENT
; /* identify channel type */
2838 c
->u
.a
.lensofar
= 0;
2839 add234(ssh_channels
, c
);
2840 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2841 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2844 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2845 /* Remote side is trying to open a channel to talk to a
2846 * forwarded port. Give them back a local channel number. */
2847 struct ssh_channel
*c
;
2848 struct ssh_rportfwd pf
;
2850 char host
[256], buf
[1024];
2852 c
= smalloc(sizeof(struct ssh_channel
));
2854 hostsize
= GET_32BIT(pktin
.body
+4);
2855 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2856 if (h
+1 < host
+sizeof(host
))
2861 port
= GET_32BIT(p
);
2863 strcpy(pf
.dhost
, host
);
2866 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2867 sprintf(buf
, "Rejected remote port open request for %s:%d",
2870 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2871 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2873 sprintf(buf
, "Received remote port open request for %s:%d",
2876 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2879 sprintf(buf
, "Port open failed: %s", e
);
2882 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2883 PKT_INT
, GET_32BIT(pktin
.body
),
2886 c
->remoteid
= GET_32BIT(pktin
.body
);
2887 c
->localid
= alloc_channel_id();
2889 c
->v
.v1
.throttling
= 0;
2890 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2891 add234(ssh_channels
, c
);
2892 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2893 PKT_INT
, c
->remoteid
, PKT_INT
,
2894 c
->localid
, PKT_END
);
2895 logevent("Forwarded port opened successfully");
2899 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2900 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2901 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2902 struct ssh_channel
*c
;
2904 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2905 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2906 c
->remoteid
= localid
;
2907 c
->type
= CHAN_SOCKDATA
;
2908 pfd_confirm(c
->u
.pfd
.s
);
2911 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
2912 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2913 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2914 struct ssh_channel
*c
;
2916 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2917 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2918 logevent("Forwarded connection refused by server");
2919 pfd_close(c
->u
.pfd
.s
);
2920 del234(ssh_channels
, c
);
2924 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2925 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2926 /* Remote side closes a channel. */
2927 unsigned i
= GET_32BIT(pktin
.body
);
2928 struct ssh_channel
*c
;
2929 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2933 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2934 if (!(c
->closes
& closetype
))
2935 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2937 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2938 logevent("Forwarded X11 connection terminated");
2939 assert(c
->u
.x11
.s
!= NULL
);
2940 x11_close(c
->u
.x11
.s
);
2943 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
2944 logevent("Forwarded port closed");
2945 assert(c
->u
.pfd
.s
!= NULL
);
2946 pfd_close(c
->u
.pfd
.s
);
2949 c
->closes
|= closetype
;
2950 if (c
->closes
== 3) {
2951 del234(ssh_channels
, c
);
2955 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2956 /* Data sent down one of our channels. */
2957 int i
= GET_32BIT(pktin
.body
);
2958 int len
= GET_32BIT(pktin
.body
+ 4);
2959 unsigned char *p
= pktin
.body
+ 8;
2960 struct ssh_channel
*c
;
2961 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2966 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
2969 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
2972 /* Data for an agent message. Buffer it. */
2974 if (c
->u
.a
.lensofar
< 4) {
2975 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2976 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2980 c
->u
.a
.lensofar
+= l
;
2982 if (c
->u
.a
.lensofar
== 4) {
2984 4 + GET_32BIT(c
->u
.a
.msglen
);
2985 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2986 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2988 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2990 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
2992 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
2996 c
->u
.a
.lensofar
+= l
;
2998 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2999 void *reply
, *sentreply
;
3001 agent_query(c
->u
.a
.message
,
3002 c
->u
.a
.totallen
, &reply
,
3007 /* Fake SSH_AGENT_FAILURE. */
3008 sentreply
= "\0\0\0\1\5";
3011 send_packet(SSH1_MSG_CHANNEL_DATA
,
3012 PKT_INT
, c
->remoteid
,
3014 PKT_DATA
, sentreply
, replylen
,
3018 sfree(c
->u
.a
.message
);
3019 c
->u
.a
.lensofar
= 0;
3022 bufsize
= 0; /* agent channels never back up */
3025 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3026 c
->v
.v1
.throttling
= 1;
3030 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
3031 /* may be from EXEC_SHELL on some servers */
3032 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3033 /* may be from EXEC_SHELL on some servers
3034 * if no pty is available or in other odd cases. Ignore */
3035 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3036 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3038 * In case `helpful' firewalls or proxies tack
3039 * extra human-readable text on the end of the
3040 * session which we might mistake for another
3041 * encrypted packet, we close the session once
3042 * we've sent EXIT_CONFIRMATION.
3044 ssh_state
= SSH_STATE_CLOSED
;
3047 bombout(("Strange packet received: type %d", pktin
.type
));
3052 int len
= min(inlen
, 512);
3053 send_packet(SSH1_CMSG_STDIN_DATA
,
3054 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3065 * Utility routine for decoding comma-separated strings in KEXINIT.
3067 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3069 int needlen
= strlen(needle
);
3072 * Is it at the start of the string?
3074 if (haylen
>= needlen
&& /* haystack is long enough */
3075 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3076 (haylen
== needlen
|| haystack
[needlen
] == ',')
3077 /* either , or EOS follows */
3081 * If not, search for the next comma and resume after that.
3082 * If no comma found, terminate.
3084 while (haylen
> 0 && *haystack
!= ',')
3085 haylen
--, haystack
++;
3088 haylen
--, haystack
++; /* skip over comma itself */
3093 * SSH2 key creation method.
3095 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
3099 /* First 20 bytes. */
3102 SHA_Bytes(&s
, H
, 20);
3103 SHA_Bytes(&s
, &chr
, 1);
3104 SHA_Bytes(&s
, sessid
, 20);
3105 SHA_Final(&s
, keyspace
);
3106 /* Next 20 bytes. */
3109 SHA_Bytes(&s
, H
, 20);
3110 SHA_Bytes(&s
, keyspace
, 20);
3111 SHA_Final(&s
, keyspace
+ 20);
3115 * Handle the SSH2 transport layer.
3117 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3119 static int i
, j
, len
, nbits
, pbits
, warn
;
3121 static Bignum p
, g
, e
, f
, K
;
3122 static int kex_init_value
, kex_reply_value
;
3123 static const struct ssh_mac
**maclist
;
3125 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3126 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3127 static const struct ssh_mac
*csmac_tobe
= NULL
;
3128 static const struct ssh_mac
*scmac_tobe
= NULL
;
3129 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3130 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3131 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3132 static int hostkeylen
, siglen
;
3133 static void *hkey
; /* actual host key */
3134 static unsigned char exchange_hash
[20];
3135 static unsigned char keyspace
[40];
3136 static int n_preferred_ciphers
;
3137 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3138 static const struct ssh_compress
*preferred_comp
;
3139 static int first_kex
;
3146 * Set up the preferred ciphers. (NULL => warn below here)
3148 n_preferred_ciphers
= 0;
3149 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3150 switch (cfg
.ssh_cipherlist
[i
]) {
3151 case CIPHER_BLOWFISH
:
3152 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3153 n_preferred_ciphers
++;
3156 /* Not supported in SSH2; silently drop */
3159 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3160 n_preferred_ciphers
++;
3163 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3164 n_preferred_ciphers
++;
3167 /* Flag for later. Don't bother if it's the last in
3169 if (i
< CIPHER_MAX
- 1) {
3170 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3171 n_preferred_ciphers
++;
3178 * Set up preferred compression.
3180 if (cfg
.compression
)
3181 preferred_comp
= &ssh_zlib
;
3183 preferred_comp
= &ssh_comp_none
;
3186 * Be prepared to work around the buggy MAC problem.
3188 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3189 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3191 maclist
= macs
, nmacs
= lenof(macs
);
3195 * Construct and send our key exchange packet.
3197 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3198 for (i
= 0; i
< 16; i
++)
3199 ssh2_pkt_addbyte((unsigned char) random_byte());
3200 /* List key exchange algorithms. */
3201 ssh2_pkt_addstring_start();
3202 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3203 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3204 if (i
< lenof(kex_algs
) - 1)
3205 ssh2_pkt_addstring_str(",");
3207 /* List server host key algorithms. */
3208 ssh2_pkt_addstring_start();
3209 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3210 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3211 if (i
< lenof(hostkey_algs
) - 1)
3212 ssh2_pkt_addstring_str(",");
3214 /* List client->server encryption algorithms. */
3215 ssh2_pkt_addstring_start();
3216 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3217 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3218 if (!c
) continue; /* warning flag */
3219 for (j
= 0; j
< c
->nciphers
; j
++) {
3220 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3221 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3222 ssh2_pkt_addstring_str(",");
3225 /* List server->client encryption algorithms. */
3226 ssh2_pkt_addstring_start();
3227 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3228 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3229 if (!c
) continue; /* warning flag */
3230 for (j
= 0; j
< c
->nciphers
; j
++) {
3231 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3232 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3233 ssh2_pkt_addstring_str(",");
3236 /* List client->server MAC algorithms. */
3237 ssh2_pkt_addstring_start();
3238 for (i
= 0; i
< nmacs
; i
++) {
3239 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3241 ssh2_pkt_addstring_str(",");
3243 /* List server->client MAC algorithms. */
3244 ssh2_pkt_addstring_start();
3245 for (i
= 0; i
< nmacs
; i
++) {
3246 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3248 ssh2_pkt_addstring_str(",");
3250 /* List client->server compression algorithms. */
3251 ssh2_pkt_addstring_start();
3252 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3253 const struct ssh_compress
*c
=
3254 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3255 ssh2_pkt_addstring_str(c
->name
);
3256 if (i
< lenof(compressions
))
3257 ssh2_pkt_addstring_str(",");
3259 /* List server->client compression algorithms. */
3260 ssh2_pkt_addstring_start();
3261 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3262 const struct ssh_compress
*c
=
3263 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3264 ssh2_pkt_addstring_str(c
->name
);
3265 if (i
< lenof(compressions
))
3266 ssh2_pkt_addstring_str(",");
3268 /* List client->server languages. Empty list. */
3269 ssh2_pkt_addstring_start();
3270 /* List server->client languages. Empty list. */
3271 ssh2_pkt_addstring_start();
3272 /* First KEX packet does _not_ follow, because we're not that brave. */
3273 ssh2_pkt_addbool(FALSE
);
3275 ssh2_pkt_adduint32(0);
3277 exhash
= exhashbase
;
3278 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3284 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3287 * Now examine the other side's KEXINIT to see what we're up
3290 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3291 bombout(("expected key exchange packet from server"));
3296 cscipher_tobe
= NULL
;
3297 sccipher_tobe
= NULL
;
3302 pktin
.savedpos
+= 16; /* skip garbage cookie */
3303 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3304 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3305 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3310 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3311 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3312 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3313 hostkey
= hostkey_algs
[i
];
3317 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3319 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3320 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3324 for (j
= 0; j
< c
->nciphers
; j
++) {
3325 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3326 cscipher_tobe
= c
->list
[j
];
3331 if (cscipher_tobe
) {
3333 askcipher(cscipher_tobe
->name
, 1);
3337 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3339 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3340 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3344 for (j
= 0; j
< c
->nciphers
; j
++) {
3345 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3346 sccipher_tobe
= c
->list
[j
];
3351 if (sccipher_tobe
) {
3353 askcipher(sccipher_tobe
->name
, 2);
3357 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3358 for (i
= 0; i
< nmacs
; i
++) {
3359 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3360 csmac_tobe
= maclist
[i
];
3364 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3365 for (i
= 0; i
< nmacs
; i
++) {
3366 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3367 scmac_tobe
= maclist
[i
];
3371 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3372 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3373 const struct ssh_compress
*c
=
3374 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3375 if (in_commasep_string(c
->name
, str
, len
)) {
3380 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3381 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3382 const struct ssh_compress
*c
=
3383 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3384 if (in_commasep_string(c
->name
, str
, len
)) {
3391 * Work out the number of bits of key we will need from the key
3392 * exchange. We start with the maximum key length of either
3398 csbits
= cscipher_tobe
->keylen
;
3399 scbits
= sccipher_tobe
->keylen
;
3400 nbits
= (csbits
> scbits ? csbits
: scbits
);
3402 /* The keys only have 160-bit entropy, since they're based on
3403 * a SHA-1 hash. So cap the key size at 160 bits. */
3408 * If we're doing Diffie-Hellman group exchange, start by
3409 * requesting a group.
3411 if (kex
== &ssh_diffiehellman_gex
) {
3412 logevent("Doing Diffie-Hellman group exchange");
3414 * Work out how big a DH group we will need to allow that
3417 pbits
= 512 << ((nbits
- 1) / 64);
3418 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3419 ssh2_pkt_adduint32(pbits
);
3423 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3424 bombout(("expected key exchange group packet from server"));
3427 p
= ssh2_pkt_getmp();
3428 g
= ssh2_pkt_getmp();
3429 dh_setup_group(p
, g
);
3430 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3431 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3434 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3435 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3438 logevent("Doing Diffie-Hellman key exchange");
3440 * Now generate and send e for Diffie-Hellman.
3442 e
= dh_create_e(nbits
* 2);
3443 ssh2_pkt_init(kex_init_value
);
3448 if (pktin
.type
!= kex_reply_value
) {
3449 bombout(("expected key exchange reply packet from server"));
3452 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3453 f
= ssh2_pkt_getmp();
3454 ssh2_pkt_getstring(&sigdata
, &siglen
);
3458 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3459 if (kex
== &ssh_diffiehellman_gex
) {
3460 sha_uint32(&exhash
, pbits
);
3461 sha_mpint(&exhash
, p
);
3462 sha_mpint(&exhash
, g
);
3464 sha_mpint(&exhash
, e
);
3465 sha_mpint(&exhash
, f
);
3466 sha_mpint(&exhash
, K
);
3467 SHA_Final(&exhash
, exchange_hash
);
3472 debug(("Exchange hash is:\n"));
3473 dmemdump(exchange_hash
, 20);
3476 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3478 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3479 bombout(("Server's host key did not match the signature supplied"));
3484 * Expect SSH2_MSG_NEWKEYS from server.
3487 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3488 bombout(("expected new-keys packet from server"));
3493 * Authenticate remote host: verify host key. (We've already
3494 * checked the signature of the exchange hash.)
3496 keystr
= hostkey
->fmtkey(hkey
);
3497 fingerprint
= hostkey
->fingerprint(hkey
);
3498 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3499 keystr
, fingerprint
);
3500 if (first_kex
) { /* don't bother logging this in rekeys */
3501 logevent("Host key fingerprint is:");
3502 logevent(fingerprint
);
3506 hostkey
->freekey(hkey
);
3509 * Send SSH2_MSG_NEWKEYS.
3511 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3515 * Create and initialise session keys.
3517 cscipher
= cscipher_tobe
;
3518 sccipher
= sccipher_tobe
;
3521 cscomp
= cscomp_tobe
;
3522 sccomp
= sccomp_tobe
;
3523 cscomp
->compress_init();
3524 sccomp
->decompress_init();
3526 * Set IVs after keys. Here we use the exchange hash from the
3527 * _first_ key exchange.
3530 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3531 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3532 cscipher
->setcskey(keyspace
);
3533 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3534 sccipher
->setsckey(keyspace
);
3535 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3536 cscipher
->setcsiv(keyspace
);
3537 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3538 sccipher
->setsciv(keyspace
);
3539 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3540 csmac
->setcskey(keyspace
);
3541 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3542 scmac
->setsckey(keyspace
);
3545 * If this is the first key exchange phase, we must pass the
3546 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3547 * wants to see it but because it will need time to initialise
3548 * itself before it sees an actual packet. In subsequent key
3549 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3550 * it would only confuse the layer above.
3558 * Now we're encrypting. Begin returning 1 to the protocol main
3559 * function so that other things can run on top of the
3560 * transport. If we ever see a KEXINIT, we must go back to the
3563 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3566 logevent("Server initiated key re-exchange");
3567 goto begin_key_exchange
;
3573 * Add data to an SSH2 channel output buffer.
3575 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3578 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3582 * Attempt to send data on an SSH2 channel.
3584 static int ssh2_try_send(struct ssh_channel
*c
)
3586 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3589 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3590 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3591 len
= c
->v
.v2
.remwindow
;
3592 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3593 len
= c
->v
.v2
.remmaxpkt
;
3594 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3595 ssh2_pkt_adduint32(c
->remoteid
);
3596 ssh2_pkt_addstring_start();
3597 ssh2_pkt_addstring_data(data
, len
);
3599 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3600 c
->v
.v2
.remwindow
-= len
;
3604 * After having sent as much data as we can, return the amount
3607 return bufchain_size(&c
->v
.v2
.outbuffer
);
3611 * Potentially enlarge the window on an SSH2 channel.
3613 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3615 if (newwin
> c
->v
.v2
.locwindow
) {
3616 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3617 ssh2_pkt_adduint32(c
->remoteid
);
3618 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3620 c
->v
.v2
.locwindow
= newwin
;
3625 * Handle the SSH2 userauth and connection layers.
3627 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3630 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3632 AUTH_KEYBOARD_INTERACTIVE
3636 AUTH_TYPE_PUBLICKEY
,
3637 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3638 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3640 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3641 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3643 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3644 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3645 static int kbd_inter_running
;
3646 static int we_are_in
;
3647 static int num_prompts
, echo
;
3648 static char username
[100];
3649 static char pwprompt
[200];
3650 static char password
[100];
3655 * Request userauth protocol, and await a response to it.
3657 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3658 ssh2_pkt_addstring("ssh-userauth");
3660 crWaitUntilV(ispkt
);
3661 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3662 bombout(("Server refused user authentication protocol"));
3667 * We repeat this whole loop, including the username prompt,
3668 * until we manage a successful authentication. If the user
3669 * types the wrong _password_, they are sent back to the
3670 * beginning to try another username. (If they specify a
3671 * username in the config, they are never asked, even if they
3672 * do give a wrong password.)
3674 * I think this best serves the needs of
3676 * - the people who have no configuration, no keys, and just
3677 * want to try repeated (username,password) pairs until they
3678 * type both correctly
3680 * - people who have keys and configuration but occasionally
3681 * need to fall back to passwords
3683 * - people with a key held in Pageant, who might not have
3684 * logged in to a particular machine before; so they want to
3685 * type a username, and then _either_ their key will be
3686 * accepted, _or_ they will type a password. If they mistype
3687 * the username they will want to be able to get back and
3698 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3700 if (!ssh_get_line("login as: ",
3701 username
, sizeof(username
), FALSE
)) {
3703 * get_line failed to get a username.
3706 logevent("No username provided. Abandoning session.");
3707 ssh_state
= SSH_STATE_CLOSED
;
3711 c_write_str("login as: ");
3714 crWaitUntilV(!ispkt
);
3716 switch (c
= *in
++) {
3725 c_write_str("\b \b");
3732 c_write_str("\b \b");
3742 if (((c
>= ' ' && c
<= '~') ||
3743 ((unsigned char) c
>= 160))
3744 && pos
< sizeof(username
)-1) {
3745 username
[pos
++] = c
;
3752 c_write_str("\r\n");
3753 username
[strcspn(username
, "\n\r")] = '\0';
3756 strncpy(username
, cfg
.username
, 99);
3757 username
[99] = '\0';
3758 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3759 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3765 * Send an authentication request using method "none": (a)
3766 * just in case it succeeds, and (b) so that we know what
3767 * authentication methods we can usefully try next.
3769 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3770 ssh2_pkt_addstring(username
);
3771 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3772 ssh2_pkt_addstring("none"); /* method */
3774 type
= AUTH_TYPE_NONE
;
3778 tried_pubkey_config
= FALSE
;
3779 tried_agent
= FALSE
;
3780 tried_keyb_inter
= FALSE
;
3781 kbd_inter_running
= FALSE
;
3785 * Wait for the result of the last authentication request.
3788 crWaitUntilV(ispkt
);
3789 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3793 * Don't show the banner if we're operating in
3794 * non-verbose non-interactive mode. (It's probably
3795 * a script, which means nobody will read the
3796 * banner _anyway_, and moreover the printing of
3797 * the banner will screw up processing on the
3798 * output of (say) plink.)
3800 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3801 ssh2_pkt_getstring(&banner
, &size
);
3803 c_write_untrusted(banner
, size
);
3805 crWaitUntilV(ispkt
);
3807 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3808 logevent("Access granted");
3813 if (kbd_inter_running
&&
3814 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3816 * This is a further prompt in keyboard-interactive
3817 * authentication. Do nothing.
3819 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3820 bombout(("Strange packet received during authentication: type %d",
3828 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3829 * we can look at the string in it and know what we can
3830 * helpfully try next.
3832 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
3835 ssh2_pkt_getstring(&methods
, &methlen
);
3836 kbd_inter_running
= FALSE
;
3837 if (!ssh2_pkt_getbool()) {
3839 * We have received an unequivocal Access
3840 * Denied. This can translate to a variety of
3843 * - if we'd just tried "none" authentication,
3844 * it's not worth printing anything at all
3846 * - if we'd just tried a public key _offer_,
3847 * the message should be "Server refused our
3848 * key" (or no message at all if the key
3849 * came from Pageant)
3851 * - if we'd just tried anything else, the
3852 * message really should be "Access denied".
3854 * Additionally, if we'd just tried password
3855 * authentication, we should break out of this
3856 * whole loop so as to go back to the username
3859 if (type
== AUTH_TYPE_NONE
) {
3861 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3862 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3863 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3864 c_write_str("Server refused our key\r\n");
3865 logevent("Server refused public key");
3866 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
3867 /* server declined keyboard-interactive; ignore */
3869 c_write_str("Access denied\r\n");
3870 logevent("Access denied");
3871 if (type
== AUTH_TYPE_PASSWORD
) {
3877 c_write_str("Further authentication required\r\n");
3878 logevent("Further authentication required");
3882 in_commasep_string("publickey", methods
, methlen
);
3884 in_commasep_string("password", methods
, methlen
);
3886 in_commasep_string("keyboard-interactive", methods
, methlen
);
3891 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3893 * Attempt public-key authentication using Pageant.
3895 static unsigned char request
[5], *response
, *p
;
3896 static int responselen
;
3897 static int i
, nkeys
;
3898 static int authed
= FALSE
;
3903 logevent("Pageant is running. Requesting keys.");
3905 /* Request the keys held by the agent. */
3906 PUT_32BIT(request
, 1);
3907 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3908 agent_query(request
, 5, &r
, &responselen
);
3909 response
= (unsigned char *) r
;
3910 if (response
&& responselen
>= 5 &&
3911 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3913 nkeys
= GET_32BIT(p
);
3917 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3920 for (i
= 0; i
< nkeys
; i
++) {
3921 static char *pkblob
, *alg
, *commentp
;
3922 static int pklen
, alglen
, commentlen
;
3923 static int siglen
, retlen
, len
;
3924 static char *q
, *agentreq
, *ret
;
3929 sprintf(buf
, "Trying Pageant key #%d", i
);
3932 pklen
= GET_32BIT(p
);
3936 alglen
= GET_32BIT(pkblob
);
3938 commentlen
= GET_32BIT(p
);
3942 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3943 ssh2_pkt_addstring(username
);
3944 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3945 ssh2_pkt_addstring("publickey"); /* method */
3946 ssh2_pkt_addbool(FALSE
); /* no signature included */
3947 ssh2_pkt_addstring_start();
3948 ssh2_pkt_addstring_data(alg
, alglen
);
3949 ssh2_pkt_addstring_start();
3950 ssh2_pkt_addstring_data(pkblob
, pklen
);
3953 crWaitUntilV(ispkt
);
3954 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3955 logevent("Key refused");
3959 if (flags
& FLAG_VERBOSE
) {
3961 ("Authenticating with public key \"");
3962 c_write(commentp
, commentlen
);
3963 c_write_str("\" from agent\r\n");
3967 * Server is willing to accept the key.
3968 * Construct a SIGN_REQUEST.
3970 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3971 ssh2_pkt_addstring(username
);
3972 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3973 ssh2_pkt_addstring("publickey"); /* method */
3974 ssh2_pkt_addbool(TRUE
);
3975 ssh2_pkt_addstring_start();
3976 ssh2_pkt_addstring_data(alg
, alglen
);
3977 ssh2_pkt_addstring_start();
3978 ssh2_pkt_addstring_data(pkblob
, pklen
);
3980 siglen
= pktout
.length
- 5 + 4 + 20;
3981 len
= 1; /* message type */
3982 len
+= 4 + pklen
; /* key blob */
3983 len
+= 4 + siglen
; /* data to sign */
3984 len
+= 4; /* flags */
3985 agentreq
= smalloc(4 + len
);
3986 PUT_32BIT(agentreq
, len
);
3988 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3989 PUT_32BIT(q
, pklen
);
3991 memcpy(q
, pkblob
, pklen
);
3993 PUT_32BIT(q
, siglen
);
3995 /* Now the data to be signed... */
3998 memcpy(q
, ssh2_session_id
, 20);
4000 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
4001 q
+= pktout
.length
- 5;
4002 /* And finally the (zero) flags word. */
4004 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
4008 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4009 logevent("Sending Pageant's response");
4010 ssh2_pkt_addstring_start();
4011 ssh2_pkt_addstring_data(ret
+ 9,
4019 ("Pageant failed to answer challenge");
4029 if (!method
&& can_pubkey
&& *cfg
.keyfile
4030 && !tried_pubkey_config
) {
4031 unsigned char *pub_blob
;
4032 char *algorithm
, *comment
;
4035 tried_pubkey_config
= TRUE
;
4038 * Try the public key supplied in the configuration.
4040 * First, offer the public blob to see if the server is
4041 * willing to accept it.
4043 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
4046 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4047 ssh2_pkt_addstring(username
);
4048 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4049 ssh2_pkt_addstring("publickey"); /* method */
4050 ssh2_pkt_addbool(FALSE
); /* no signature included */
4051 ssh2_pkt_addstring(algorithm
);
4052 ssh2_pkt_addstring_start();
4053 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
4055 logevent("Offered public key"); /* FIXME */
4057 crWaitUntilV(ispkt
);
4058 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4060 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4061 continue; /* key refused; give up on it */
4064 logevent("Offer of public key accepted");
4066 * Actually attempt a serious authentication using
4069 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4071 "Passphrase for key \"%.100s\": ",
4077 c_write_str("Authenticating with public key \"");
4078 c_write_str(comment
);
4079 c_write_str("\"\r\n");
4080 method
= AUTH_PUBLICKEY_FILE
;
4084 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
4085 method
= AUTH_KEYBOARD_INTERACTIVE
;
4086 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4087 tried_keyb_inter
= TRUE
;
4089 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4090 ssh2_pkt_addstring(username
);
4091 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4092 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4093 ssh2_pkt_addstring(""); /* lang */
4094 ssh2_pkt_addstring("");
4097 crWaitUntilV(ispkt
);
4098 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4099 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4101 logevent("Keyboard-interactive authentication refused");
4102 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4106 kbd_inter_running
= TRUE
;
4109 if (kbd_inter_running
) {
4110 method
= AUTH_KEYBOARD_INTERACTIVE
;
4111 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4112 tried_keyb_inter
= TRUE
;
4114 /* We've got packet with that "interactive" info
4115 dump banners, and set its prompt as ours */
4117 char *name
, *inst
, *lang
, *prompt
;
4118 int name_len
, inst_len
, lang_len
, prompt_len
;
4119 ssh2_pkt_getstring(&name
, &name_len
);
4120 ssh2_pkt_getstring(&inst
, &inst_len
);
4121 ssh2_pkt_getstring(&lang
, &lang_len
);
4123 c_write_untrusted(name
, name_len
);
4125 c_write_untrusted(inst
, inst_len
);
4126 num_prompts
= ssh2_pkt_getuint32();
4128 ssh2_pkt_getstring(&prompt
, &prompt_len
);
4129 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
4132 echo
= ssh2_pkt_getbool();
4136 if (!method
&& can_passwd
) {
4137 method
= AUTH_PASSWORD
;
4138 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4145 if (!ssh_get_line(pwprompt
, password
,
4146 sizeof(password
), TRUE
)) {
4148 * get_line failed to get a password (for
4149 * example because one was supplied on the
4150 * command line which has already failed to
4153 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4154 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4156 ("No more passwords available to try");
4157 ssh2_pkt_addstring("en"); /* language tag */
4159 connection_fatal("Unable to authenticate");
4160 ssh_state
= SSH_STATE_CLOSED
;
4167 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4172 crWaitUntilV(!ispkt
);
4174 switch (c
= *in
++) {
4195 if (pos
< sizeof(password
)-1)
4196 password
[pos
++] = c
;
4200 c_write_str("\r\n");
4204 if (method
== AUTH_PUBLICKEY_FILE
) {
4206 * We have our passphrase. Now try the actual authentication.
4208 struct ssh2_userkey
*key
;
4210 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4211 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4212 if (key
== SSH2_WRONG_PASSPHRASE
) {
4213 c_write_str("Wrong passphrase\r\n");
4214 tried_pubkey_config
= FALSE
;
4216 c_write_str("Unable to load private key\r\n");
4217 tried_pubkey_config
= TRUE
;
4219 /* Send a spurious AUTH_NONE to return to the top. */
4220 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4221 ssh2_pkt_addstring(username
);
4222 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4223 ssh2_pkt_addstring("none"); /* method */
4225 type
= AUTH_TYPE_NONE
;
4227 unsigned char *blob
, *sigdata
;
4228 int blob_len
, sigdata_len
;
4231 * We have loaded the private key and the server
4232 * has announced that it's willing to accept it.
4233 * Hallelujah. Generate a signature and send it.
4235 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4236 ssh2_pkt_addstring(username
);
4237 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4238 ssh2_pkt_addstring("publickey"); /* method */
4239 ssh2_pkt_addbool(TRUE
);
4240 ssh2_pkt_addstring(key
->alg
->name
);
4241 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4242 ssh2_pkt_addstring_start();
4243 ssh2_pkt_addstring_data(blob
, blob_len
);
4247 * The data to be signed is:
4251 * followed by everything so far placed in the
4254 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4255 sigdata
= smalloc(sigdata_len
);
4256 PUT_32BIT(sigdata
, 20);
4257 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4258 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4261 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4263 ssh2_pkt_addstring_start();
4264 ssh2_pkt_addstring_data(blob
, blob_len
);
4269 type
= AUTH_TYPE_PUBLICKEY
;
4271 } else if (method
== AUTH_PASSWORD
) {
4273 * We send the password packet lumped tightly together with
4274 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4275 * string long enough to make the total length of the two
4276 * packets constant. This should ensure that a passive
4277 * listener doing traffic analyis can't work out the length
4280 * For this to work, we need an assumption about the
4281 * maximum length of the password packet. I think 256 is
4282 * pretty conservative. Anyone using a password longer than
4283 * that probably doesn't have much to worry about from
4284 * people who find out how long their password is!
4286 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4287 ssh2_pkt_addstring(username
);
4288 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4289 ssh2_pkt_addstring("password");
4290 ssh2_pkt_addbool(FALSE
);
4291 ssh2_pkt_addstring(password
);
4294 * We'll include a string that's an exact multiple of the
4295 * cipher block size. If the cipher is NULL for some
4296 * reason, we don't do this trick at all because we gain
4302 stringlen
= (256 - deferred_len
);
4303 stringlen
+= cscipher
->blksize
- 1;
4304 stringlen
-= (stringlen
% cscipher
->blksize
);
4307 * Temporarily disable actual compression,
4308 * so we can guarantee to get this string
4309 * exactly the length we want it. The
4310 * compression-disabling routine should
4311 * return an integer indicating how many
4312 * bytes we should adjust our string length
4315 stringlen
-= cscomp
->disable_compression();
4317 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4318 ssh2_pkt_addstring_start();
4319 for (i
= 0; i
< stringlen
; i
++) {
4320 char c
= (char) random_byte();
4321 ssh2_pkt_addstring_data(&c
, 1);
4325 ssh_pkt_defersend();
4326 logevent("Sent password");
4327 type
= AUTH_TYPE_PASSWORD
;
4328 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4329 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4330 ssh2_pkt_adduint32(num_prompts
);
4331 ssh2_pkt_addstring(password
);
4332 memset(password
, 0, sizeof(password
));
4334 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4337 ("No supported authentication methods left to try!\r\n");
4339 ("No supported authentications offered. Disconnecting");
4340 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4341 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4343 ("No supported authentication methods available");
4344 ssh2_pkt_addstring("en"); /* language tag */
4346 ssh_state
= SSH_STATE_CLOSED
;
4350 } while (!we_are_in
);
4353 * Now we're authenticated for the connection protocol. The
4354 * connection protocol will automatically have started at this
4355 * point; there's no need to send SERVICE_REQUEST.
4359 * So now create a channel with a session in it.
4361 ssh_channels
= newtree234(ssh_channelcmp
);
4362 mainchan
= smalloc(sizeof(struct ssh_channel
));
4363 mainchan
->localid
= alloc_channel_id();
4364 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4365 ssh2_pkt_addstring("session");
4366 ssh2_pkt_adduint32(mainchan
->localid
);
4367 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4368 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4369 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4371 crWaitUntilV(ispkt
);
4372 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4373 bombout(("Server refused to open a session"));
4375 /* FIXME: error data comes back in FAILURE packet */
4377 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4378 bombout(("Server's channel confirmation cited wrong channel"));
4381 mainchan
->remoteid
= ssh2_pkt_getuint32();
4382 mainchan
->type
= CHAN_MAINSESSION
;
4383 mainchan
->closes
= 0;
4384 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4385 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4386 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4387 add234(ssh_channels
, mainchan
);
4388 logevent("Opened channel for session");
4391 * Potentially enable X11 forwarding.
4393 if (cfg
.x11_forward
) {
4394 char proto
[20], data
[64];
4395 logevent("Requesting X11 forwarding");
4396 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4397 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4398 ssh2_pkt_adduint32(mainchan
->remoteid
);
4399 ssh2_pkt_addstring("x11-req");
4400 ssh2_pkt_addbool(1); /* want reply */
4401 ssh2_pkt_addbool(0); /* many connections */
4402 ssh2_pkt_addstring(proto
);
4403 ssh2_pkt_addstring(data
);
4404 ssh2_pkt_adduint32(0); /* screen number */
4408 crWaitUntilV(ispkt
);
4409 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4410 unsigned i
= ssh2_pkt_getuint32();
4411 struct ssh_channel
*c
;
4412 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4414 continue; /* nonexistent channel */
4415 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4417 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4419 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4420 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4421 bombout(("Unexpected response to X11 forwarding request:"
4422 " packet type %d", pktin
.type
));
4425 logevent("X11 forwarding refused");
4427 logevent("X11 forwarding enabled");
4428 ssh_X11_fwd_enabled
= TRUE
;
4433 * Enable port forwardings.
4436 static char *e
; /* preserve across crReturn */
4440 char sports
[256], dports
[256], host
[256];
4443 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4444 /* Add port forwardings. */
4449 while (*e
&& *e
!= '\t')
4455 while (*e
&& *e
!= ':')
4465 dport
= atoi(dports
);
4466 sport
= atoi(sports
);
4467 if (sport
&& dport
) {
4469 pfd_addforward(host
, dport
, sport
);
4470 sprintf(buf
, "Local port %d forwarding to %s:%d",
4471 sport
, host
, dport
);
4474 struct ssh_rportfwd
*pf
;
4475 pf
= smalloc(sizeof(*pf
));
4476 strcpy(pf
->dhost
, host
);
4479 if (add234(ssh_rportfwds
, pf
) != pf
) {
4481 "Duplicate remote port forwarding to %s:%d",
4486 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4487 sport
, host
, dport
);
4489 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4490 ssh2_pkt_addstring("tcpip-forward");
4491 ssh2_pkt_addbool(1);/* want reply */
4492 ssh2_pkt_addstring("127.0.0.1");
4493 ssh2_pkt_adduint32(sport
);
4497 crWaitUntilV(ispkt
);
4498 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4499 unsigned i
= ssh2_pkt_getuint32();
4500 struct ssh_channel
*c
;
4501 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4503 continue;/* nonexistent channel */
4504 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4506 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4508 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4509 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4510 bombout(("Unexpected response to port "
4511 "forwarding request: packet type %d",
4515 logevent("Server refused this port forwarding");
4517 logevent("Remote port forwarding enabled");
4526 * Potentially enable agent forwarding.
4528 if (cfg
.agentfwd
&& agent_exists()) {
4529 logevent("Requesting OpenSSH-style agent forwarding");
4530 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4531 ssh2_pkt_adduint32(mainchan
->remoteid
);
4532 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4533 ssh2_pkt_addbool(1); /* want reply */
4537 crWaitUntilV(ispkt
);
4538 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4539 unsigned i
= ssh2_pkt_getuint32();
4540 struct ssh_channel
*c
;
4541 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4543 continue; /* nonexistent channel */
4544 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4546 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4548 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4549 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4550 bombout(("Unexpected response to agent forwarding request:"
4551 " packet type %d", pktin
.type
));
4554 logevent("Agent forwarding refused");
4556 logevent("Agent forwarding enabled");
4557 ssh_agentfwd_enabled
= TRUE
;
4562 * Now allocate a pty for the session.
4565 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4566 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4567 ssh2_pkt_addstring("pty-req");
4568 ssh2_pkt_addbool(1); /* want reply */
4569 ssh2_pkt_addstring(cfg
.termtype
);
4570 ssh2_pkt_adduint32(cols
);
4571 ssh2_pkt_adduint32(rows
);
4572 ssh2_pkt_adduint32(0); /* pixel width */
4573 ssh2_pkt_adduint32(0); /* pixel height */
4574 ssh2_pkt_addstring_start();
4575 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4577 ssh_state
= SSH_STATE_INTERMED
;
4580 crWaitUntilV(ispkt
);
4581 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4582 unsigned i
= ssh2_pkt_getuint32();
4583 struct ssh_channel
*c
;
4584 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4586 continue; /* nonexistent channel */
4587 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4589 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4591 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4592 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4593 bombout(("Unexpected response to pty request:"
4594 " packet type %d", pktin
.type
));
4597 c_write_str("Server refused to allocate pty\r\n");
4598 ssh_editing
= ssh_echoing
= 1;
4600 logevent("Allocated pty");
4603 ssh_editing
= ssh_echoing
= 1;
4607 * Start a shell or a remote command. We may have to attempt
4608 * this twice if the config data has provided a second choice
4615 if (ssh_fallback_cmd
) {
4616 subsys
= cfg
.ssh_subsys2
;
4617 cmd
= cfg
.remote_cmd_ptr2
;
4619 subsys
= cfg
.ssh_subsys
;
4620 cmd
= cfg
.remote_cmd_ptr
;
4623 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4624 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4626 ssh2_pkt_addstring("subsystem");
4627 ssh2_pkt_addbool(1); /* want reply */
4628 ssh2_pkt_addstring(cmd
);
4630 ssh2_pkt_addstring("exec");
4631 ssh2_pkt_addbool(1); /* want reply */
4632 ssh2_pkt_addstring(cmd
);
4634 ssh2_pkt_addstring("shell");
4635 ssh2_pkt_addbool(1); /* want reply */
4639 crWaitUntilV(ispkt
);
4640 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4641 unsigned i
= ssh2_pkt_getuint32();
4642 struct ssh_channel
*c
;
4643 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4645 continue; /* nonexistent channel */
4646 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4648 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4649 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4650 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4651 bombout(("Unexpected response to shell/command request:"
4652 " packet type %d", pktin
.type
));
4656 * We failed to start the command. If this is the
4657 * fallback command, we really are finished; if it's
4658 * not, and if the fallback command exists, try falling
4659 * back to it before complaining.
4661 if (!ssh_fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
4662 logevent("Primary command failed; attempting fallback");
4663 ssh_fallback_cmd
= TRUE
;
4666 bombout(("Server refused to start a shell/command"));
4669 logevent("Started a shell/command");
4674 ssh_state
= SSH_STATE_SESSION
;
4678 ssh_special(TS_EOF
);
4683 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
4686 static int try_send
;
4690 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4691 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4694 unsigned i
= ssh2_pkt_getuint32();
4695 struct ssh_channel
*c
;
4696 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4698 continue; /* nonexistent channel */
4699 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4700 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4701 continue; /* extended but not stderr */
4702 ssh2_pkt_getstring(&data
, &length
);
4705 c
->v
.v2
.locwindow
-= length
;
4707 case CHAN_MAINSESSION
:
4709 from_backend(pktin
.type
==
4710 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
4714 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
4717 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
4720 while (length
> 0) {
4721 if (c
->u
.a
.lensofar
< 4) {
4722 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4723 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4727 c
->u
.a
.lensofar
+= l
;
4729 if (c
->u
.a
.lensofar
== 4) {
4731 4 + GET_32BIT(c
->u
.a
.msglen
);
4732 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4733 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4735 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4737 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4739 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4743 c
->u
.a
.lensofar
+= l
;
4745 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4746 void *reply
, *sentreply
;
4748 agent_query(c
->u
.a
.message
,
4749 c
->u
.a
.totallen
, &reply
,
4754 /* Fake SSH_AGENT_FAILURE. */
4755 sentreply
= "\0\0\0\1\5";
4758 ssh2_add_channel_data(c
, sentreply
,
4763 sfree(c
->u
.a
.message
);
4764 c
->u
.a
.lensofar
= 0;
4771 * If we are not buffering too much data,
4772 * enlarge the window again at the remote side.
4774 if (bufsize
< OUR_V2_WINSIZE
)
4775 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
4777 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4778 ssh_state
= SSH_STATE_CLOSED
;
4779 logevent("Received disconnect message");
4781 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4782 continue; /* exit status et al; ignore (FIXME?) */
4783 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4784 unsigned i
= ssh2_pkt_getuint32();
4785 struct ssh_channel
*c
;
4787 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4789 continue; /* nonexistent channel */
4791 if (c
->type
== CHAN_X11
) {
4793 * Remote EOF on an X11 channel means we should
4794 * wrap up and close the channel ourselves.
4796 x11_close(c
->u
.x11
.s
);
4798 } else if (c
->type
== CHAN_AGENT
) {
4800 } else if (c
->type
== CHAN_SOCKDATA
) {
4801 pfd_close(c
->u
.pfd
.s
);
4804 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4805 unsigned i
= ssh2_pkt_getuint32();
4806 struct ssh_channel
*c
;
4808 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4810 continue; /* nonexistent channel */
4811 /* Do pre-close processing on the channel. */
4813 case CHAN_MAINSESSION
:
4814 break; /* nothing to see here, move along */
4816 if (c
->u
.x11
.s
!= NULL
)
4817 x11_close(c
->u
.x11
.s
);
4824 if (c
->u
.pfd
.s
!= NULL
)
4825 pfd_close(c
->u
.pfd
.s
);
4829 if (c
->closes
== 0) {
4830 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4831 ssh2_pkt_adduint32(c
->remoteid
);
4834 del234(ssh_channels
, c
);
4835 bufchain_clear(&c
->v
.v2
.outbuffer
);
4839 * See if that was the last channel left open.
4841 if (count234(ssh_channels
) == 0) {
4842 logevent("All channels closed. Disconnecting");
4843 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4844 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4845 ssh2_pkt_addstring("All open channels closed");
4846 ssh2_pkt_addstring("en"); /* language tag */
4848 ssh_state
= SSH_STATE_CLOSED
;
4851 continue; /* remote sends close; ignore (FIXME) */
4852 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4853 unsigned i
= ssh2_pkt_getuint32();
4854 struct ssh_channel
*c
;
4855 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4857 continue; /* nonexistent channel */
4858 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4860 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4861 unsigned i
= ssh2_pkt_getuint32();
4862 struct ssh_channel
*c
;
4863 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4865 continue; /* nonexistent channel */
4866 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4867 continue; /* dunno why they're confirming this */
4868 c
->remoteid
= ssh2_pkt_getuint32();
4869 c
->type
= CHAN_SOCKDATA
;
4871 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4872 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4873 bufchain_init(&c
->v
.v2
.outbuffer
);
4874 pfd_confirm(c
->u
.pfd
.s
);
4875 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
4876 unsigned i
= ssh2_pkt_getuint32();
4877 struct ssh_channel
*c
;
4878 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4880 continue; /* nonexistent channel */
4881 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4882 continue; /* dunno why they're failing this */
4884 logevent("Forwarded connection refused by server");
4886 pfd_close(c
->u
.pfd
.s
);
4888 del234(ssh_channels
, c
);
4890 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4894 struct ssh_channel
*c
;
4895 unsigned remid
, winsize
, pktsize
;
4896 ssh2_pkt_getstring(&type
, &typelen
);
4897 c
= smalloc(sizeof(struct ssh_channel
));
4899 remid
= ssh2_pkt_getuint32();
4900 winsize
= ssh2_pkt_getuint32();
4901 pktsize
= ssh2_pkt_getuint32();
4903 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4904 if (!ssh_X11_fwd_enabled
)
4905 error
= "X11 forwarding is not enabled";
4906 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4908 error
= "Unable to open an X11 connection";
4912 } else if (typelen
== 15 &&
4913 !memcmp(type
, "forwarded-tcpip", 15)) {
4914 struct ssh_rportfwd pf
, *realpf
;
4917 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
4918 pf
.sport
= ssh2_pkt_getuint32();
4919 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
4920 if (realpf
== NULL
) {
4921 error
= "Remote port is not recognised";
4923 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
4926 sprintf(buf
, "Received remote port open request for %s:%d",
4927 realpf
->dhost
, realpf
->dport
);
4930 sprintf(buf
, "Port open failed: %s", e
);
4932 error
= "Port open failed";
4934 logevent("Forwarded port opened successfully");
4935 c
->type
= CHAN_SOCKDATA
;
4938 } else if (typelen
== 22 &&
4939 !memcmp(type
, "auth-agent@openssh.com", 3)) {
4940 if (!ssh_agentfwd_enabled
)
4941 error
= "Agent forwarding is not enabled";
4943 c
->type
= CHAN_AGENT
; /* identify channel type */
4944 c
->u
.a
.lensofar
= 0;
4947 error
= "Unsupported channel type requested";
4950 c
->remoteid
= remid
;
4952 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
4953 ssh2_pkt_adduint32(c
->remoteid
);
4954 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
4955 ssh2_pkt_addstring(error
);
4956 ssh2_pkt_addstring("en"); /* language tag */
4960 c
->localid
= alloc_channel_id();
4962 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4963 c
->v
.v2
.remwindow
= winsize
;
4964 c
->v
.v2
.remmaxpkt
= pktsize
;
4965 bufchain_init(&c
->v
.v2
.outbuffer
);
4966 add234(ssh_channels
, c
);
4967 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
4968 ssh2_pkt_adduint32(c
->remoteid
);
4969 ssh2_pkt_adduint32(c
->localid
);
4970 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
4971 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4975 bombout(("Strange packet received: type %d", pktin
.type
));
4980 * We have spare data. Add it to the channel buffer.
4982 ssh2_add_channel_data(mainchan
, in
, inlen
);
4987 struct ssh_channel
*c
;
4989 * Try to send data on all channels if we can.
4991 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
4992 int bufsize
= ssh2_try_send(c
);
4995 case CHAN_MAINSESSION
:
4996 /* stdin need not receive an unthrottle
4997 * notification since it will be polled */
5000 x11_unthrottle(c
->u
.x11
.s
);
5003 /* agent sockets are request/response and need no
5004 * buffer management */
5007 pfd_unthrottle(c
->u
.pfd
.s
);
5019 * Handle the top-level SSH2 protocol.
5021 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
5023 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
5025 do_ssh2_authconn(in
, inlen
, ispkt
);
5029 * Called to set up the connection.
5031 * Returns an error message, or NULL on success.
5033 static char *ssh_init(char *host
, int port
, char **realhost
)
5038 if (crypto_startup() == 0)
5039 return "Microsoft high encryption pack not installed!";
5045 ssh1_throttle_count
= 0;
5046 ssh_overall_bufsize
= 0;
5047 ssh_fallback_cmd
= 0;
5049 p
= connect_to_host(host
, port
, realhost
);
5057 * Called to send data down the Telnet connection.
5059 static int ssh_send(char *buf
, int len
)
5061 if (s
== NULL
|| ssh_protocol
== NULL
)
5064 ssh_protocol(buf
, len
, 0);
5066 return ssh_sendbuffer();
5070 * Called to query the current amount of buffered stdin data.
5072 static int ssh_sendbuffer(void)
5076 if (s
== NULL
|| ssh_protocol
== NULL
)
5080 * If the SSH socket itself has backed up, add the total backup
5081 * size on that to any individual buffer on the stdin channel.
5084 if (ssh_throttled_all
)
5085 override_value
= ssh_overall_bufsize
;
5087 if (ssh_version
== 1) {
5088 return override_value
;
5089 } else if (ssh_version
== 2) {
5090 if (!mainchan
|| mainchan
->closes
> 0)
5091 return override_value
;
5093 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
5100 * Called to set the size of the window from SSH's POV.
5102 static void ssh_size(void)
5104 switch (ssh_state
) {
5105 case SSH_STATE_BEFORE_SIZE
:
5106 case SSH_STATE_PREPACKET
:
5107 case SSH_STATE_CLOSED
:
5108 break; /* do nothing */
5109 case SSH_STATE_INTERMED
:
5110 size_needed
= TRUE
; /* buffer for later */
5112 case SSH_STATE_SESSION
:
5114 if (ssh_version
== 1) {
5115 send_packet(SSH1_CMSG_WINDOW_SIZE
,
5116 PKT_INT
, rows
, PKT_INT
, cols
,
5117 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5119 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5120 ssh2_pkt_adduint32(mainchan
->remoteid
);
5121 ssh2_pkt_addstring("window-change");
5122 ssh2_pkt_addbool(0);
5123 ssh2_pkt_adduint32(cols
);
5124 ssh2_pkt_adduint32(rows
);
5125 ssh2_pkt_adduint32(0);
5126 ssh2_pkt_adduint32(0);
5135 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5136 * can send an EOF and collect resulting output (e.g. `plink
5139 static void ssh_special(Telnet_Special code
)
5141 if (code
== TS_EOF
) {
5142 if (ssh_state
!= SSH_STATE_SESSION
) {
5144 * Buffer the EOF in case we are pre-SESSION, so we can
5145 * send it as soon as we reach SESSION.
5151 if (ssh_version
== 1) {
5152 send_packet(SSH1_CMSG_EOF
, PKT_END
);
5154 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
5155 ssh2_pkt_adduint32(mainchan
->remoteid
);
5158 logevent("Sent EOF message");
5159 } else if (code
== TS_PING
) {
5160 if (ssh_state
== SSH_STATE_CLOSED
5161 || ssh_state
== SSH_STATE_PREPACKET
) return;
5162 if (ssh_version
== 1) {
5163 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5165 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5166 ssh2_pkt_addstring_start();
5174 void *new_sock_channel(Socket s
)
5176 struct ssh_channel
*c
;
5177 c
= smalloc(sizeof(struct ssh_channel
));
5180 c
->remoteid
= -1; /* to be set when open confirmed */
5181 c
->localid
= alloc_channel_id();
5183 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5185 add234(ssh_channels
, c
);
5191 * This is called when stdout/stderr (the entity to which
5192 * from_backend sends data) manages to clear some backlog.
5194 void ssh_unthrottle(int bufsize
)
5196 if (ssh_version
== 1) {
5197 if (ssh1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
5198 ssh1_stdout_throttling
= 0;
5202 if (mainchan
&& mainchan
->closes
== 0)
5203 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5207 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5209 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5212 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5215 if (ssh_version
== 1) {
5216 send_packet(SSH1_MSG_PORT_OPEN
,
5217 PKT_INT
, c
->localid
,
5220 //PKT_STR, <org:orgport>,
5223 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5224 ssh2_pkt_addstring("direct-tcpip");
5225 ssh2_pkt_adduint32(c
->localid
);
5226 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5227 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5228 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5229 ssh2_pkt_addstring(hostname
);
5230 ssh2_pkt_adduint32(port
);
5232 * We make up values for the originator data; partly it's
5233 * too much hassle to keep track, and partly I'm not
5234 * convinced the server should be told details like that
5235 * about my local network configuration.
5237 ssh2_pkt_addstring("client-side-connection");
5238 ssh2_pkt_adduint32(0);
5244 static Socket
ssh_socket(void)
5249 static int ssh_sendok(void)
5254 static int ssh_ldisc(int option
)
5256 if (option
== LD_ECHO
)
5258 if (option
== LD_EDIT
)
5263 Backend ssh_backend
= {