18 /* uncomment this for packet level debugging */
19 /* #define DUMP_PACKETS */
21 #define logevent(s) { logevent(s); \
22 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
23 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
25 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
26 (s ? sk_close(s), s = NULL : 0), \
27 connection_fatal msg )
29 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
30 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
31 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
32 #define SSH1_CMSG_USER 4 /* 0x4 */
33 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
34 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
35 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
36 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
37 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
38 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
39 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
40 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
41 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
42 #define SSH1_SMSG_FAILURE 15 /* 0xf */
43 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
44 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
45 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
46 #define SSH1_CMSG_EOF 19 /* 0x13 */
47 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
48 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
49 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
50 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
51 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
52 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
53 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
54 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
55 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
56 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
57 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
58 #define SSH1_MSG_IGNORE 32 /* 0x20 */
59 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
60 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
61 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
62 #define SSH1_MSG_DEBUG 36 /* 0x24 */
63 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
64 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
65 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
66 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
67 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
68 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
69 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
71 #define SSH1_AUTH_TIS 5 /* 0x5 */
72 #define SSH1_AUTH_CCARD 16 /* 0x10 */
74 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
75 /* Mask for protoflags we will echo back to server if seen */
76 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
78 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
79 #define SSH2_MSG_IGNORE 2 /* 0x2 */
80 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
81 #define SSH2_MSG_DEBUG 4 /* 0x4 */
82 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
83 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
84 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
85 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
86 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
87 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
88 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
89 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
91 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
92 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
93 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
94 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
95 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
96 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
97 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
98 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
100 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
101 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
102 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
103 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
104 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
105 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
106 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
107 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
108 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
109 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
110 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
111 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
112 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
113 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons
[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
163 #define GET_32BIT(cp) \
164 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
165 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
166 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
167 ((unsigned long)(unsigned char)(cp)[3]))
169 #define PUT_32BIT(cp, value) { \
170 (cp)[0] = (unsigned char)((value) >> 24); \
171 (cp)[1] = (unsigned char)((value) >> 16); \
172 (cp)[2] = (unsigned char)((value) >> 8); \
173 (cp)[3] = (unsigned char)(value); }
175 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
177 /* Coroutine mechanics for the sillier bits of the code */
178 #define crBegin1 static int crLine = 0;
179 #define crBegin2 switch(crLine) { case 0:;
180 #define crBegin crBegin1; crBegin2;
181 #define crFinish(z) } crLine = 0; return (z)
182 #define crFinishV } crLine = 0; return
183 #define crReturn(z) \
185 crLine=__LINE__; return (z); case __LINE__:;\
189 crLine=__LINE__; return; case __LINE__:;\
191 #define crStop(z) do{ crLine = 0; return (z); }while(0)
192 #define crStopV do{ crLine = 0; return; }while(0)
193 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
194 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
196 extern char *x11_init(Socket
*, char *, void *);
197 extern void x11_close(Socket
);
198 extern int x11_send(Socket
, char *, int);
199 extern void x11_invent_auth(char *, int, char *, int);
200 extern void x11_unthrottle(Socket s
);
201 extern void x11_override_throttle(Socket s
, int enable
);
203 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
204 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
205 extern void pfd_close(Socket s
);
206 extern int pfd_send(Socket s
, char *data
, int len
);
207 extern void pfd_confirm(Socket s
);
208 extern void pfd_unthrottle(Socket s
);
209 extern void pfd_override_throttle(Socket s
, int enable
);
212 * Buffer management constants. There are several of these for
213 * various different purposes:
215 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
216 * on a local data stream before we throttle the whole SSH
217 * connection (in SSH1 only). Throttling the whole connection is
218 * pretty drastic so we set this high in the hope it won't
221 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
222 * on the SSH connection itself before we defensively throttle
223 * _all_ local data streams. This is pretty drastic too (though
224 * thankfully unlikely in SSH2 since the window mechanism should
225 * ensure that the server never has any need to throttle its end
226 * of the connection), so we set this high as well.
228 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
232 #define SSH1_BUFFER_LIMIT 32768
233 #define SSH_MAX_BACKLOG 32768
234 #define OUR_V2_WINSIZE 16384
237 * Ciphers for SSH2. We miss out single-DES because it isn't
238 * supported; also 3DES and Blowfish are both done differently from
239 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
240 * endianness and different-sized keys.)
242 const static struct ssh2_ciphers
*ciphers
[] = {
248 const static struct ssh_kex
*kex_algs
[] = {
249 &ssh_diffiehellman_gex
,
253 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
255 static void nullmac_key(unsigned char *key
)
258 static void nullmac_generate(unsigned char *blk
, int len
,
262 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
266 const static struct ssh_mac ssh_mac_none
= {
267 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
269 const static struct ssh_mac
*macs
[] = {
270 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
272 const static struct ssh_mac
*buggymacs
[] = {
273 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
276 static void ssh_comp_none_init(void)
279 static int ssh_comp_none_block(unsigned char *block
, int len
,
280 unsigned char **outblock
, int *outlen
)
284 static int ssh_comp_none_disable(void)
288 const static struct ssh_compress ssh_comp_none
= {
290 ssh_comp_none_init
, ssh_comp_none_block
,
291 ssh_comp_none_init
, ssh_comp_none_block
,
292 ssh_comp_none_disable
294 extern const struct ssh_compress ssh_zlib
;
295 const static struct ssh_compress
*compressions
[] = {
296 &ssh_zlib
, &ssh_comp_none
299 enum { /* channel types */
304 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
308 * 2-3-4 tree storing channels.
311 unsigned remoteid
, localid
;
315 struct ssh1_data_channel
{
318 struct ssh2_data_channel
{
320 unsigned remwindow
, remmaxpkt
;
325 struct ssh_agent_channel
{
326 unsigned char *message
;
327 unsigned char msglen
[4];
328 int lensofar
, totallen
;
330 struct ssh_x11_channel
{
333 struct ssh_pfd_channel
{
340 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
341 * 2 use this structure in different ways, reflecting SSH 2's
342 * altogether saner approach to port forwarding.
344 * In SSH 1, you arrange a remote forwarding by sending the server
345 * the remote port number, and the local destination host:port.
346 * When a connection comes in, the server sends you back that
347 * host:port pair, and you connect to it. This is a ready-made
348 * security hole if you're not on the ball: a malicious server
349 * could send you back _any_ host:port pair, so if you trustingly
350 * connect to the address it gives you then you've just opened the
351 * entire inside of your corporate network just by connecting
352 * through it to a dodgy SSH server. Hence, we must store a list of
353 * host:port pairs we _are_ trying to forward to, and reject a
354 * connection request from the server if it's not in the list.
356 * In SSH 2, each side of the connection minds its own business and
357 * doesn't send unnecessary information to the other. You arrange a
358 * remote forwarding by sending the server just the remote port
359 * number. When a connection comes in, the server tells you which
360 * of its ports was connected to; and _you_ have to remember what
361 * local host:port pair went with that port number.
363 * Hence: in SSH 1 this structure stores host:port pairs we intend
364 * to allow connections to, and is indexed by those host:port
365 * pairs. In SSH 2 it stores a mapping from source port to
366 * destination host:port pair, and is indexed by source port.
368 struct ssh_rportfwd
{
369 unsigned sport
, dport
;
382 static SHA_State exhash
, exhashbase
;
384 static Socket s
= NULL
;
386 static unsigned char session_key
[32];
387 static int ssh1_compressing
;
388 static int ssh1_remote_protoflags
;
389 static int ssh1_local_protoflags
;
390 static int ssh_agentfwd_enabled
;
391 static int ssh_X11_fwd_enabled
;
392 static int ssh_remote_bugs
;
393 static const struct ssh_cipher
*cipher
= NULL
;
394 static const struct ssh2_cipher
*cscipher
= NULL
;
395 static const struct ssh2_cipher
*sccipher
= NULL
;
396 static const struct ssh_mac
*csmac
= NULL
;
397 static const struct ssh_mac
*scmac
= NULL
;
398 static const struct ssh_compress
*cscomp
= NULL
;
399 static const struct ssh_compress
*sccomp
= NULL
;
400 static const struct ssh_kex
*kex
= NULL
;
401 static const struct ssh_signkey
*hostkey
= NULL
;
402 static unsigned char ssh2_session_id
[20];
403 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
406 static char *savedhost
;
407 static int savedport
;
408 static int ssh_send_ok
;
409 static int ssh_echoing
, ssh_editing
;
411 static tree234
*ssh_channels
; /* indexed by local id */
412 static struct ssh_channel
*mainchan
; /* primary session channel */
414 static tree234
*ssh_rportfwds
;
418 SSH_STATE_BEFORE_SIZE
,
422 } ssh_state
= SSH_STATE_PREPACKET
;
424 static int size_needed
= FALSE
, eof_needed
= FALSE
;
426 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
427 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
428 static unsigned char *deferred_send_data
= NULL
;
429 static int deferred_len
= 0, deferred_size
= 0;
431 static int ssh_version
;
432 static int ssh1_throttle_count
;
433 static int ssh_overall_bufsize
;
434 static int ssh_throttled_all
;
435 static int ssh1_stdout_throttling
;
436 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
437 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
438 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
439 static void ssh_size(void);
440 static void ssh_special(Telnet_Special
);
441 static int ssh2_try_send(struct ssh_channel
*c
);
442 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
444 static void ssh_throttle_all(int enable
, int bufsize
);
445 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
446 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
447 static int ssh_sendbuffer(void);
449 static struct rdpkt1_state_tag
{
450 long len
, pad
, biglen
, to_read
;
451 unsigned long realcrc
, gotcrc
;
457 static struct rdpkt2_state_tag
{
458 long len
, pad
, payload
, packetlen
, maclen
;
461 unsigned long incoming_sequence
;
464 static int ssh_channelcmp(void *av
, void *bv
)
466 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
467 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
468 if (a
->localid
< b
->localid
)
470 if (a
->localid
> b
->localid
)
474 static int ssh_channelfind(void *av
, void *bv
)
476 unsigned *a
= (unsigned *) av
;
477 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
485 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
487 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
488 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
490 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
491 return i
< 0 ?
-1 : +1;
492 if (a
->dport
> b
->dport
)
494 if (a
->dport
< b
->dport
)
499 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
501 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
502 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
504 if (a
->sport
> b
->sport
)
506 if (a
->sport
< b
->sport
)
511 static int alloc_channel_id(void)
513 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
514 unsigned low
, high
, mid
;
516 struct ssh_channel
*c
;
519 * First-fit allocation of channel numbers: always pick the
520 * lowest unused one. To do this, binary-search using the
521 * counted B-tree to find the largest channel ID which is in a
522 * contiguous sequence from the beginning. (Precisely
523 * everything in that sequence must have ID equal to its tree
524 * index plus CHANNEL_NUMBER_OFFSET.)
526 tsize
= count234(ssh_channels
);
530 while (high
- low
> 1) {
531 mid
= (high
+ low
) / 2;
532 c
= index234(ssh_channels
, mid
);
533 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
534 low
= mid
; /* this one is fine */
536 high
= mid
; /* this one is past it */
539 * Now low points to either -1, or the tree index of the
540 * largest ID in the initial sequence.
543 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
544 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
546 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
549 static void c_write(char *buf
, int len
)
551 if ((flags
& FLAG_STDERR
)) {
553 for (i
= 0; i
< len
; i
++)
555 fputc(buf
[i
], stderr
);
558 from_backend(1, buf
, len
);
561 static void c_write_untrusted(char *buf
, int len
)
564 for (i
= 0; i
< len
; i
++) {
567 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
572 static void c_write_str(char *buf
)
574 c_write(buf
, strlen(buf
));
578 * Collect incoming data in the incoming packet buffer.
579 * Decipher and verify the packet when it is completely read.
580 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
581 * Update the *data and *datalen variables.
582 * Return the additional nr of bytes needed, or 0 when
583 * a complete packet is available.
585 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
587 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
596 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
597 while ((*datalen
) == 0)
599 st
->len
= (st
->len
<< 8) + **data
;
600 (*data
)++, (*datalen
)--;
604 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
605 st
->len
= 0x300; /* big enough to carry to end */
609 st
->pad
= 8 - (st
->len
% 8);
610 st
->biglen
= st
->len
+ st
->pad
;
611 pktin
.length
= st
->len
- 5;
613 if (pktin
.maxlen
< st
->biglen
) {
614 pktin
.maxlen
= st
->biglen
;
615 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
616 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
618 fatalbox("Out of memory");
621 st
->to_read
= st
->biglen
;
623 while (st
->to_read
> 0) {
624 st
->chunk
= st
->to_read
;
625 while ((*datalen
) == 0)
626 crReturn(st
->to_read
);
627 if (st
->chunk
> (*datalen
))
628 st
->chunk
= (*datalen
);
629 memcpy(st
->p
, *data
, st
->chunk
);
631 *datalen
-= st
->chunk
;
633 st
->to_read
-= st
->chunk
;
637 cipher
->decrypt(pktin
.data
, st
->biglen
);
639 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
640 dmemdump(pktin
.data
, st
->biglen
);
643 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
644 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
645 if (st
->gotcrc
!= st
->realcrc
) {
646 bombout(("Incorrect CRC received on packet"));
650 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
652 if (ssh1_compressing
) {
653 unsigned char *decompblk
;
656 debug(("Packet payload pre-decompression:\n"));
657 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
659 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
660 &decompblk
, &decomplen
);
662 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
663 pktin
.maxlen
= st
->pad
+ decomplen
;
664 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
665 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
667 fatalbox("Out of memory");
670 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
672 pktin
.length
= decomplen
- 1;
674 debug(("Packet payload post-decompression:\n"));
675 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
679 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
680 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
681 pktin
.type
== SSH1_MSG_DEBUG
||
682 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
683 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
684 long strlen
= GET_32BIT(pktin
.body
);
685 if (strlen
+ 4 != pktin
.length
) {
686 bombout(("Received data packet with bogus string length"));
691 pktin
.type
= pktin
.body
[-1];
693 if (pktin
.type
== SSH1_MSG_DEBUG
) {
694 /* log debug message */
696 int strlen
= GET_32BIT(pktin
.body
);
697 strcpy(buf
, "Remote: ");
700 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
701 buf
[8 + strlen
] = '\0';
704 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
709 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
710 /* log reason code in disconnect message */
712 unsigned msglen
= GET_32BIT(pktin
.body
);
714 strcpy(buf
, "Remote sent disconnect: ");
715 nowlen
= strlen(buf
);
716 if (msglen
> sizeof(buf
) - nowlen
- 1)
717 msglen
= sizeof(buf
) - nowlen
- 1;
718 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
719 buf
[nowlen
+ msglen
] = '\0';
726 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
728 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
736 st
->cipherblk
= sccipher
->blksize
;
739 if (st
->cipherblk
< 8)
742 if (pktin
.maxlen
< st
->cipherblk
) {
743 pktin
.maxlen
= st
->cipherblk
;
746 NULL ?
smalloc(st
->cipherblk
+
747 APIEXTRA
) : srealloc(pktin
.data
,
751 fatalbox("Out of memory");
755 * Acquire and decrypt the first block of the packet. This will
756 * contain the length and padding details.
758 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
759 while ((*datalen
) == 0)
760 crReturn(st
->cipherblk
- st
->i
);
761 pktin
.data
[st
->i
] = *(*data
)++;
765 if (!memcmp(pktin
.data
, "Remo", 4)) { /* "Remo"te server has closed ... */
770 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
773 * Now get the length and padding figures.
775 st
->len
= GET_32BIT(pktin
.data
);
776 st
->pad
= pktin
.data
[4];
779 * This enables us to deduce the payload length.
781 st
->payload
= st
->len
- st
->pad
- 1;
783 pktin
.length
= st
->payload
+ 5;
786 * So now we can work out the total packet length.
788 st
->packetlen
= st
->len
+ 4;
789 st
->maclen
= scmac ? scmac
->len
: 0;
792 * Adjust memory allocation if packet is too big.
794 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
795 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
798 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
803 fatalbox("Out of memory");
807 * Read and decrypt the remainder of the packet.
809 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
811 while ((*datalen
) == 0)
812 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
813 pktin
.data
[st
->i
] = *(*data
)++;
816 /* Decrypt everything _except_ the MAC. */
818 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
819 st
->packetlen
- st
->cipherblk
);
822 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
823 dmemdump(pktin
.data
, st
->packetlen
);
830 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
831 st
->incoming_sequence
)) {
832 bombout(("Incorrect MAC received on packet"));
835 st
->incoming_sequence
++; /* whether or not we MACed */
838 * Decompress packet payload.
841 unsigned char *newpayload
;
843 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
844 &newpayload
, &newlen
)) {
845 if (pktin
.maxlen
< newlen
+ 5) {
846 pktin
.maxlen
= newlen
+ 5;
849 NULL ?
smalloc(pktin
.maxlen
+
850 APIEXTRA
) : srealloc(pktin
.data
,
854 fatalbox("Out of memory");
856 pktin
.length
= 5 + newlen
;
857 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
859 debug(("Post-decompression payload:\n"));
860 dmemdump(pktin
.data
+ 5, newlen
);
868 pktin
.type
= pktin
.data
[5];
870 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
871 goto next_packet
; /* FIXME: print DEBUG message */
873 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
874 /* log reason code in disconnect message */
876 int reason
= GET_32BIT(pktin
.data
+ 6);
877 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
879 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
880 sprintf(buf
, "Received disconnect message (%s)",
881 ssh2_disconnect_reasons
[reason
]);
883 sprintf(buf
, "Received disconnect message (unknown type %d)",
887 strcpy(buf
, "Disconnection message text: ");
888 nowlen
= strlen(buf
);
889 if (msglen
> sizeof(buf
) - nowlen
- 1)
890 msglen
= sizeof(buf
) - nowlen
- 1;
891 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
892 buf
[nowlen
+ msglen
] = '\0';
899 static void ssh1_pktout_size(int len
)
903 len
+= 5; /* type and CRC */
907 pktout
.length
= len
- 5;
908 if (pktout
.maxlen
< biglen
) {
909 pktout
.maxlen
= biglen
;
911 /* Allocate enough buffer space for extra block
912 * for MS CryptEncrypt() */
913 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
914 srealloc(pktout
.data
, biglen
+ 12));
916 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
917 srealloc(pktout
.data
, biglen
+ 4));
920 fatalbox("Out of memory");
922 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
925 static void s_wrpkt_start(int type
, int len
)
927 ssh1_pktout_size(len
);
931 static int s_wrpkt_prepare(void)
933 int pad
, len
, biglen
, i
;
936 pktout
.body
[-1] = pktout
.type
;
939 debug(("Packet payload pre-compression:\n"));
940 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
943 if (ssh1_compressing
) {
944 unsigned char *compblk
;
946 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
948 ssh1_pktout_size(complen
- 1);
949 memcpy(pktout
.body
- 1, compblk
, complen
);
952 debug(("Packet payload post-compression:\n"));
953 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
957 len
= pktout
.length
+ 5; /* type and CRC */
961 for (i
= 0; i
< pad
; i
++)
962 pktout
.data
[i
+ 4] = random_byte();
963 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
964 PUT_32BIT(pktout
.data
+ biglen
, crc
);
965 PUT_32BIT(pktout
.data
, len
);
968 debug(("Sending packet len=%d\n", biglen
+ 4));
969 dmemdump(pktout
.data
, biglen
+ 4);
972 cipher
->encrypt(pktout
.data
+ 4, biglen
);
977 static void s_wrpkt(void)
980 len
= s_wrpkt_prepare();
981 backlog
= sk_write(s
, pktout
.data
, len
);
982 if (backlog
> SSH_MAX_BACKLOG
)
983 ssh_throttle_all(1, backlog
);
986 static void s_wrpkt_defer(void)
989 len
= s_wrpkt_prepare();
990 if (deferred_len
+ len
> deferred_size
) {
991 deferred_size
= deferred_len
+ len
+ 128;
992 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
994 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
999 * Construct a packet with the specified contents.
1001 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1003 unsigned char *p
, *argp
, argchar
;
1004 unsigned long argint
;
1005 int pktlen
, argtype
, arglen
;
1009 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1012 (void) va_arg(ap1
, int);
1016 (void) va_arg(ap1
, char);
1020 (void) va_arg(ap1
, unsigned char *);
1021 arglen
= va_arg(ap1
, int);
1025 argp
= va_arg(ap1
, unsigned char *);
1026 arglen
= strlen(argp
);
1027 pktlen
+= 4 + arglen
;
1030 bn
= va_arg(ap1
, Bignum
);
1031 pktlen
+= ssh1_bignum_length(bn
);
1038 s_wrpkt_start(pkttype
, pktlen
);
1041 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1044 argint
= va_arg(ap2
, int);
1045 PUT_32BIT(p
, argint
);
1049 argchar
= va_arg(ap2
, unsigned char);
1054 argp
= va_arg(ap2
, unsigned char *);
1055 arglen
= va_arg(ap2
, int);
1056 memcpy(p
, argp
, arglen
);
1060 argp
= va_arg(ap2
, unsigned char *);
1061 arglen
= strlen(argp
);
1062 PUT_32BIT(p
, arglen
);
1063 memcpy(p
+ 4, argp
, arglen
);
1067 bn
= va_arg(ap2
, Bignum
);
1068 p
+= ssh1_write_bignum(p
, bn
);
1074 static void send_packet(int pkttype
, ...)
1077 va_start(ap1
, pkttype
);
1078 va_start(ap2
, pkttype
);
1079 construct_packet(pkttype
, ap1
, ap2
);
1083 static void defer_packet(int pkttype
, ...)
1086 va_start(ap1
, pkttype
);
1087 va_start(ap2
, pkttype
);
1088 construct_packet(pkttype
, ap1
, ap2
);
1092 static int ssh_versioncmp(char *a
, char *b
)
1095 unsigned long av
, bv
;
1097 av
= strtoul(a
, &ae
, 10);
1098 bv
= strtoul(b
, &be
, 10);
1100 return (av
< bv ?
-1 : +1);
1105 av
= strtoul(ae
, &ae
, 10);
1106 bv
= strtoul(be
, &be
, 10);
1108 return (av
< bv ?
-1 : +1);
1114 * Utility routines for putting an SSH-protocol `string' and
1115 * `uint32' into a SHA state.
1118 static void sha_string(SHA_State
* s
, void *str
, int len
)
1120 unsigned char lenblk
[4];
1121 PUT_32BIT(lenblk
, len
);
1122 SHA_Bytes(s
, lenblk
, 4);
1123 SHA_Bytes(s
, str
, len
);
1126 static void sha_uint32(SHA_State
* s
, unsigned i
)
1128 unsigned char intblk
[4];
1129 PUT_32BIT(intblk
, i
);
1130 SHA_Bytes(s
, intblk
, 4);
1134 * SSH2 packet construction functions.
1136 static void ssh2_pkt_ensure(int length
)
1138 if (pktout
.maxlen
< length
) {
1139 pktout
.maxlen
= length
+ 256;
1142 NULL ?
smalloc(pktout
.maxlen
+
1143 APIEXTRA
) : srealloc(pktout
.data
,
1147 fatalbox("Out of memory");
1150 static void ssh2_pkt_adddata(void *data
, int len
)
1152 pktout
.length
+= len
;
1153 ssh2_pkt_ensure(pktout
.length
);
1154 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1156 static void ssh2_pkt_addbyte(unsigned char byte
)
1158 ssh2_pkt_adddata(&byte
, 1);
1160 static void ssh2_pkt_init(int pkt_type
)
1163 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1165 static void ssh2_pkt_addbool(unsigned char value
)
1167 ssh2_pkt_adddata(&value
, 1);
1169 static void ssh2_pkt_adduint32(unsigned long value
)
1172 PUT_32BIT(x
, value
);
1173 ssh2_pkt_adddata(x
, 4);
1175 static void ssh2_pkt_addstring_start(void)
1177 ssh2_pkt_adduint32(0);
1178 pktout
.savedpos
= pktout
.length
;
1180 static void ssh2_pkt_addstring_str(char *data
)
1182 ssh2_pkt_adddata(data
, strlen(data
));
1183 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1184 pktout
.length
- pktout
.savedpos
);
1186 static void ssh2_pkt_addstring_data(char *data
, int len
)
1188 ssh2_pkt_adddata(data
, len
);
1189 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1190 pktout
.length
- pktout
.savedpos
);
1192 static void ssh2_pkt_addstring(char *data
)
1194 ssh2_pkt_addstring_start();
1195 ssh2_pkt_addstring_str(data
);
1197 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1200 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1203 fatalbox("out of memory");
1205 for (i
= 1; i
<= n
; i
++)
1206 p
[i
] = bignum_byte(b
, n
- i
);
1208 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1210 memmove(p
, p
+ i
, n
+ 1 - i
);
1214 static void ssh2_pkt_addmp(Bignum b
)
1218 p
= ssh2_mpint_fmt(b
, &len
);
1219 ssh2_pkt_addstring_start();
1220 ssh2_pkt_addstring_data(p
, len
);
1225 * Construct an SSH2 final-form packet: compress it, encrypt it,
1226 * put the MAC on it. Final packet, ready to be sent, is stored in
1227 * pktout.data. Total length is returned.
1229 static int ssh2_pkt_construct(void)
1231 int cipherblk
, maclen
, padding
, i
;
1232 static unsigned long outgoing_sequence
= 0;
1235 * Compress packet payload.
1238 debug(("Pre-compression payload:\n"));
1239 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1242 unsigned char *newpayload
;
1244 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1245 &newpayload
, &newlen
)) {
1247 ssh2_pkt_adddata(newpayload
, newlen
);
1253 * Add padding. At least four bytes, and must also bring total
1254 * length (minus MAC) up to a multiple of the block size.
1256 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1257 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1260 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1261 maclen
= csmac ? csmac
->len
: 0;
1262 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1263 pktout
.data
[4] = padding
;
1264 for (i
= 0; i
< padding
; i
++)
1265 pktout
.data
[pktout
.length
+ i
] = random_byte();
1266 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1268 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1270 outgoing_sequence
++; /* whether or not we MACed */
1273 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1274 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1278 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1280 /* Ready-to-send packet starts at pktout.data. We return length. */
1281 return pktout
.length
+ padding
+ maclen
;
1285 * Construct and send an SSH2 packet immediately.
1287 static void ssh2_pkt_send(void)
1291 len
= ssh2_pkt_construct();
1292 backlog
= sk_write(s
, pktout
.data
, len
);
1293 if (backlog
> SSH_MAX_BACKLOG
)
1294 ssh_throttle_all(1, backlog
);
1298 * Construct an SSH2 packet and add it to a deferred data block.
1299 * Useful for sending multiple packets in a single sk_write() call,
1300 * to prevent a traffic-analysing listener from being able to work
1301 * out the length of any particular packet (such as the password
1304 * Note that because SSH2 sequence-numbers its packets, this can
1305 * NOT be used as an m4-style `defer' allowing packets to be
1306 * constructed in one order and sent in another.
1308 static void ssh2_pkt_defer(void)
1310 int len
= ssh2_pkt_construct();
1311 if (deferred_len
+ len
> deferred_size
) {
1312 deferred_size
= deferred_len
+ len
+ 128;
1313 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1315 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1316 deferred_len
+= len
;
1320 * Send the whole deferred data block constructed by
1321 * ssh2_pkt_defer() or SSH1's defer_packet().
1323 static void ssh_pkt_defersend(void)
1326 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1327 deferred_len
= deferred_size
= 0;
1328 sfree(deferred_send_data
);
1329 deferred_send_data
= NULL
;
1330 if (backlog
> SSH_MAX_BACKLOG
)
1331 ssh_throttle_all(1, backlog
);
1335 void bndebug(char *string
, Bignum b
)
1339 p
= ssh2_mpint_fmt(b
, &len
);
1340 debug(("%s", string
));
1341 for (i
= 0; i
< len
; i
++)
1342 debug((" %02x", p
[i
]));
1348 static void sha_mpint(SHA_State
* s
, Bignum b
)
1352 p
= ssh2_mpint_fmt(b
, &len
);
1353 sha_string(s
, p
, len
);
1358 * SSH2 packet decode functions.
1360 static unsigned long ssh2_pkt_getuint32(void)
1362 unsigned long value
;
1363 if (pktin
.length
- pktin
.savedpos
< 4)
1364 return 0; /* arrgh, no way to decline (FIXME?) */
1365 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1366 pktin
.savedpos
+= 4;
1369 static int ssh2_pkt_getbool(void)
1371 unsigned long value
;
1372 if (pktin
.length
- pktin
.savedpos
< 1)
1373 return 0; /* arrgh, no way to decline (FIXME?) */
1374 value
= pktin
.data
[pktin
.savedpos
] != 0;
1378 static void ssh2_pkt_getstring(char **p
, int *length
)
1381 if (pktin
.length
- pktin
.savedpos
< 4)
1383 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1384 pktin
.savedpos
+= 4;
1385 if (pktin
.length
- pktin
.savedpos
< *length
)
1387 *p
= pktin
.data
+ pktin
.savedpos
;
1388 pktin
.savedpos
+= *length
;
1390 static Bignum
ssh2_pkt_getmp(void)
1396 ssh2_pkt_getstring(&p
, &length
);
1400 bombout(("internal error: Can't handle negative mpints"));
1403 b
= bignum_from_bytes(p
, length
);
1408 * Examine the remote side's version string and compare it against
1409 * a list of known buggy implementations.
1411 static void ssh_detect_bugs(char *vstring
)
1413 char *imp
; /* pointer to implementation part */
1415 imp
+= strcspn(imp
, "-");
1418 imp
+= strcspn(imp
, "-");
1422 ssh_remote_bugs
= 0;
1424 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1425 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1426 !strcmp(imp
, "1.2.22")) {
1428 * These versions don't support SSH1_MSG_IGNORE, so we have
1429 * to use a different defence against password length
1432 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1433 logevent("We believe remote version has SSH1 ignore bug");
1436 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1437 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1438 !strncmp(imp
, "2.1 ", 4)) {
1440 * These versions have the HMAC bug.
1442 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1443 logevent("We believe remote version has SSH2 HMAC bug");
1447 static int do_ssh_init(unsigned char c
)
1450 static char version
[10];
1451 static char *vstring
;
1452 static int vstrsize
;
1458 /* Search for the string "SSH-" in the input. */
1461 static const int transS
[] = { 1, 2, 2, 1 };
1462 static const int transH
[] = { 0, 0, 3, 0 };
1463 static const int transminus
[] = { 0, 0, 0, -1 };
1474 crReturn(1); /* get another character */
1477 vstring
= smalloc(16);
1479 strcpy(vstring
, "SSH-");
1483 crReturn(1); /* get another char */
1484 if (vslen
>= vstrsize
- 1) {
1486 vstring
= srealloc(vstring
, vstrsize
);
1488 vstring
[vslen
++] = c
;
1493 } else if (i
< sizeof(version
) - 1)
1495 } else if (c
== '\n')
1499 ssh_agentfwd_enabled
= FALSE
;
1500 rdpkt2_state
.incoming_sequence
= 0;
1503 vlog
= smalloc(20 + vslen
);
1504 sprintf(vlog
, "Server version: %s", vstring
);
1505 ssh_detect_bugs(vstring
);
1506 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1511 * Server version "1.99" means we can choose whether we use v1
1512 * or v2 protocol. Choice is based on cfg.sshprot.
1514 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1516 * This is a v2 server. Begin v2 protocol.
1518 char verstring
[80], vlog
[100];
1519 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1520 SHA_Init(&exhashbase
);
1522 * Hash our version string and their version string.
1524 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1525 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1526 sprintf(vlog
, "We claim version: %s", verstring
);
1528 strcat(verstring
, "\n");
1529 logevent("Using SSH protocol version 2");
1530 sk_write(s
, verstring
, strlen(verstring
));
1531 ssh_protocol
= ssh2_protocol
;
1533 s_rdpkt
= ssh2_rdpkt
;
1536 * This is a v1 server. Begin v1 protocol.
1538 char verstring
[80], vlog
[100];
1539 sprintf(verstring
, "SSH-%s-%s",
1540 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1542 sprintf(vlog
, "We claim version: %s", verstring
);
1544 strcat(verstring
, "\n");
1545 logevent("Using SSH protocol version 1");
1546 sk_write(s
, verstring
, strlen(verstring
));
1547 ssh_protocol
= ssh1_protocol
;
1549 s_rdpkt
= ssh1_rdpkt
;
1551 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1558 static void ssh_gotdata(unsigned char *data
, int datalen
)
1563 * To begin with, feed the characters one by one to the
1564 * protocol initialisation / selection function do_ssh_init().
1565 * When that returns 0, we're done with the initial greeting
1566 * exchange and can move on to packet discipline.
1571 crReturnV
; /* more data please */
1572 ret
= do_ssh_init(*data
);
1580 * We emerge from that loop when the initial negotiation is
1581 * over and we have selected an s_rdpkt function. Now pass
1582 * everything to s_rdpkt, and then pass the resulting packets
1583 * to the proper protocol handler.
1588 while (datalen
> 0) {
1589 if (s_rdpkt(&data
, &datalen
) == 0) {
1590 ssh_protocol(NULL
, 0, 1);
1591 if (ssh_state
== SSH_STATE_CLOSED
) {
1601 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1604 ssh_state
= SSH_STATE_CLOSED
;
1610 /* A socket error has occurred. */
1611 connection_fatal(error_msg
);
1613 /* Otherwise, the remote side closed the connection normally. */
1618 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1620 ssh_gotdata(data
, len
);
1621 if (ssh_state
== SSH_STATE_CLOSED
) {
1631 static void ssh_sent(Plug plug
, int bufsize
)
1634 * If the send backlog on the SSH socket itself clears, we
1635 * should unthrottle the whole world if it was throttled.
1637 if (bufsize
< SSH_MAX_BACKLOG
)
1638 ssh_throttle_all(0, bufsize
);
1642 * Connect to specified host and port.
1643 * Returns an error message, or NULL on success.
1644 * Also places the canonical host name into `realhost'. It must be
1645 * freed by the caller.
1647 static char *connect_to_host(char *host
, int port
, char **realhost
)
1649 static struct plug_function_table fn_table
= {
1654 }, *fn_table_ptr
= &fn_table
;
1663 savedhost
= smalloc(1 + strlen(host
));
1665 fatalbox("Out of memory");
1666 strcpy(savedhost
, host
);
1669 port
= 22; /* default ssh port */
1682 addr
= sk_namelookup(host
, realhost
);
1683 if ((err
= sk_addr_error(addr
)))
1687 *realhost
= strdup(FWhost
);
1693 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1694 if ((err
= sk_socket_error(s
)))
1698 sk_write(s
, "connect ", 8);
1699 sk_write(s
, FWhost
, strlen(FWhost
));
1702 sprintf(buf
, " %d\n", FWport
);
1703 sk_write(s
, buf
, strlen(buf
));
1711 * Throttle or unthrottle the SSH connection.
1713 static void ssh1_throttle(int adjust
)
1715 int old_count
= ssh1_throttle_count
;
1716 ssh1_throttle_count
+= adjust
;
1717 assert(ssh1_throttle_count
>= 0);
1718 if (ssh1_throttle_count
&& !old_count
) {
1719 sk_set_frozen(s
, 1);
1720 } else if (!ssh1_throttle_count
&& old_count
) {
1721 sk_set_frozen(s
, 0);
1726 * Throttle or unthrottle _all_ local data streams (for when sends
1727 * on the SSH connection itself back up).
1729 static void ssh_throttle_all(int enable
, int bufsize
)
1732 struct ssh_channel
*c
;
1734 if (enable
== ssh_throttled_all
)
1736 ssh_throttled_all
= enable
;
1737 ssh_overall_bufsize
= bufsize
;
1740 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1742 case CHAN_MAINSESSION
:
1744 * This is treated separately, outside the switch.
1748 x11_override_throttle(c
->u
.x11
.s
, enable
);
1751 /* Agent channels require no buffer management. */
1754 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1761 * Handle the key exchange and user authentication phases.
1763 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1767 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1768 unsigned char cookie
[8];
1769 struct RSAKey servkey
, hostkey
;
1770 struct MD5Context md5c
;
1771 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1772 static int tried_publickey
;
1773 static unsigned char session_id
[16];
1774 static int cipher_type
;
1775 static char username
[100];
1782 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1783 bombout(("Public key packet not received"));
1787 logevent("Received public keys");
1789 memcpy(cookie
, pktin
.body
, 8);
1791 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1792 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1795 * Log the host key fingerprint.
1799 logevent("Host key fingerprint is:");
1800 strcpy(logmsg
, " ");
1801 hostkey
.comment
= NULL
;
1802 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1803 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1807 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1808 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1809 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1811 ssh1_local_protoflags
=
1812 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1813 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1816 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1817 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1818 MD5Update(&md5c
, pktin
.body
, 8);
1819 MD5Final(session_id
, &md5c
);
1821 for (i
= 0; i
< 32; i
++)
1822 session_key
[i
] = random_byte();
1824 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1826 rsabuf
= smalloc(len
);
1828 fatalbox("Out of memory");
1831 * Verify the host key.
1835 * First format the key into a string.
1837 int len
= rsastr_len(&hostkey
);
1838 char fingerprint
[100];
1839 char *keystr
= smalloc(len
);
1841 fatalbox("Out of memory");
1842 rsastr_fmt(keystr
, &hostkey
);
1843 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1844 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1849 for (i
= 0; i
< 32; i
++) {
1850 rsabuf
[i
] = session_key
[i
];
1852 rsabuf
[i
] ^= session_id
[i
];
1855 if (hostkey
.bytes
> servkey
.bytes
) {
1856 rsaencrypt(rsabuf
, 32, &servkey
);
1857 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1859 rsaencrypt(rsabuf
, 32, &hostkey
);
1860 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1863 logevent("Encrypted session key");
1865 switch (cfg
.cipher
) {
1866 case CIPHER_BLOWFISH
:
1867 cipher_type
= SSH_CIPHER_BLOWFISH
;
1870 cipher_type
= SSH_CIPHER_DES
;
1873 cipher_type
= SSH_CIPHER_3DES
;
1876 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1877 cipher_type
= SSH_CIPHER_3DES
;
1880 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1882 ("Selected cipher not supported, falling back to 3DES\r\n");
1883 cipher_type
= SSH_CIPHER_3DES
;
1884 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1885 bombout(("Server violates SSH 1 protocol by "
1886 "not supporting 3DES encryption"));
1890 switch (cipher_type
) {
1891 case SSH_CIPHER_3DES
:
1892 logevent("Using 3DES encryption");
1894 case SSH_CIPHER_DES
:
1895 logevent("Using single-DES encryption");
1897 case SSH_CIPHER_BLOWFISH
:
1898 logevent("Using Blowfish encryption");
1902 send_packet(SSH1_CMSG_SESSION_KEY
,
1903 PKT_CHAR
, cipher_type
,
1904 PKT_DATA
, cookie
, 8,
1905 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1906 PKT_DATA
, rsabuf
, len
,
1907 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1909 logevent("Trying to enable encryption...");
1913 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1914 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1915 cipher
->sesskey(session_key
);
1919 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1920 bombout(("Encryption not successfully enabled"));
1924 logevent("Successfully started encryption");
1930 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1932 if (!ssh_get_line("login as: ",
1933 username
, sizeof(username
), FALSE
)) {
1935 * get_line failed to get a username.
1938 logevent("No username provided. Abandoning session.");
1939 ssh_state
= SSH_STATE_CLOSED
;
1943 c_write_str("login as: ");
1946 crWaitUntil(!ispkt
);
1948 switch (c
= *in
++) {
1957 c_write_str("\b \b");
1964 c_write_str("\b \b");
1974 if (((c
>= ' ' && c
<= '~') ||
1975 ((unsigned char) c
>= 160))
1976 && pos
< sizeof(username
)-1) {
1977 username
[pos
++] = c
;
1983 c_write_str("\r\n");
1984 username
[strcspn(username
, "\n\r")] = '\0';
1987 strncpy(username
, cfg
.username
, 99);
1988 username
[99] = '\0';
1991 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1993 char userlog
[22 + sizeof(username
)];
1994 sprintf(userlog
, "Sent username \"%s\"", username
);
1996 if (flags
& FLAG_INTERACTIVE
&&
1997 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1998 strcat(userlog
, "\r\n");
1999 c_write_str(userlog
);
2006 tried_publickey
= 0;
2008 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2009 static char password
[100];
2010 static char prompt
[200];
2013 static int pwpkt_type
;
2015 * Show password prompt, having first obtained it via a TIS
2016 * or CryptoCard exchange if we're doing TIS or CryptoCard
2019 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2020 if (agent_exists()) {
2022 * Attempt RSA authentication using Pageant.
2024 static unsigned char request
[5], *response
, *p
;
2025 static int responselen
;
2026 static int i
, nkeys
;
2027 static int authed
= FALSE
;
2030 logevent("Pageant is running. Requesting keys.");
2032 /* Request the keys held by the agent. */
2033 PUT_32BIT(request
, 1);
2034 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2035 agent_query(request
, 5, &r
, &responselen
);
2036 response
= (unsigned char *) r
;
2037 if (response
&& responselen
>= 5 &&
2038 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2040 nkeys
= GET_32BIT(p
);
2044 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2047 for (i
= 0; i
< nkeys
; i
++) {
2048 static struct RSAKey key
;
2049 static Bignum challenge
;
2050 static char *commentp
;
2051 static int commentlen
;
2055 sprintf(buf
, "Trying Pageant key #%d", i
);
2059 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2060 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2061 commentlen
= GET_32BIT(p
);
2065 send_packet(SSH1_CMSG_AUTH_RSA
,
2066 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2068 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2069 logevent("Key refused");
2072 logevent("Received RSA challenge");
2073 ssh1_read_bignum(pktin
.body
, &challenge
);
2075 char *agentreq
, *q
, *ret
;
2078 len
= 1 + 4; /* message type, bit count */
2079 len
+= ssh1_bignum_length(key
.exponent
);
2080 len
+= ssh1_bignum_length(key
.modulus
);
2081 len
+= ssh1_bignum_length(challenge
);
2082 len
+= 16; /* session id */
2083 len
+= 4; /* response format */
2084 agentreq
= smalloc(4 + len
);
2085 PUT_32BIT(agentreq
, len
);
2087 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2088 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2090 q
+= ssh1_write_bignum(q
, key
.exponent
);
2091 q
+= ssh1_write_bignum(q
, key
.modulus
);
2092 q
+= ssh1_write_bignum(q
, challenge
);
2093 memcpy(q
, session_id
, 16);
2095 PUT_32BIT(q
, 1); /* response format */
2096 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2100 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2101 logevent("Sending Pageant's response");
2102 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2103 PKT_DATA
, ret
+ 5, 16,
2107 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2109 ("Pageant's response accepted");
2110 if (flags
& FLAG_VERBOSE
) {
2112 ("Authenticated using RSA key \"");
2113 c_write(commentp
, commentlen
);
2114 c_write_str("\" from agent\r\n");
2119 ("Pageant's response not accepted");
2122 ("Pageant failed to answer challenge");
2126 logevent("No reply received from Pageant");
2129 freebn(key
.exponent
);
2130 freebn(key
.modulus
);
2139 if (*cfg
.keyfile
&& !tried_publickey
)
2140 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2142 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2144 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
))) {
2145 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2146 logevent("Requested TIS authentication");
2147 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2149 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2150 logevent("TIS authentication declined");
2151 if (flags
& FLAG_INTERACTIVE
)
2152 c_write_str("TIS authentication refused.\r\n");
2154 int challengelen
= ((pktin
.body
[0] << 24) |
2155 (pktin
.body
[1] << 16) |
2156 (pktin
.body
[2] << 8) |
2158 logevent("Received TIS challenge");
2159 if (challengelen
> sizeof(prompt
) - 1)
2160 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2161 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2162 prompt
[challengelen
] = '\0';
2165 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2167 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
))) {
2168 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2169 logevent("Requested CryptoCard authentication");
2170 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2172 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2173 logevent("CryptoCard authentication declined");
2174 c_write_str("CryptoCard authentication refused.\r\n");
2176 int challengelen
= ((pktin
.body
[0] << 24) |
2177 (pktin
.body
[1] << 16) |
2178 (pktin
.body
[2] << 8) |
2180 logevent("Received CryptoCard challenge");
2181 if (challengelen
> sizeof(prompt
) - 1)
2182 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2183 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2184 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
2185 sizeof(prompt
) - challengelen
);
2186 prompt
[sizeof(prompt
) - 1] = '\0';
2189 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2190 sprintf(prompt
, "%.90s@%.90s's password: ",
2191 username
, savedhost
);
2193 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2194 char *comment
= NULL
;
2195 if (flags
& FLAG_VERBOSE
)
2196 c_write_str("Trying public key authentication.\r\n");
2197 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2198 if (flags
& FLAG_VERBOSE
)
2199 c_write_str("No passphrase required.\r\n");
2202 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2207 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2209 * get_line failed to get a password (for example
2210 * because one was supplied on the command line
2211 * which has already failed to work). Terminate.
2213 send_packet(SSH1_MSG_DISCONNECT
,
2214 PKT_STR
, "No more passwords available to try",
2216 connection_fatal("Unable to authenticate");
2217 ssh_state
= SSH_STATE_CLOSED
;
2221 c_write_str(prompt
);
2225 crWaitUntil(!ispkt
);
2227 switch (c
= *in
++) {
2248 if (pos
< sizeof(password
)-1)
2249 password
[pos
++] = c
;
2253 c_write_str("\r\n");
2257 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2259 * Try public key authentication with the specified
2262 static struct RSAKey pubkey
;
2263 static Bignum challenge
, response
;
2265 static unsigned char buffer
[32];
2267 tried_publickey
= 1;
2268 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2270 c_write_str("Couldn't load public key from ");
2271 c_write_str(cfg
.keyfile
);
2272 c_write_str(".\r\n");
2273 continue; /* go and try password */
2276 c_write_str("Wrong passphrase.\r\n");
2277 tried_publickey
= 0;
2278 continue; /* try again */
2282 * Send a public key attempt.
2284 send_packet(SSH1_CMSG_AUTH_RSA
,
2285 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2288 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2289 c_write_str("Server refused our public key.\r\n");
2290 continue; /* go and try password */
2292 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2293 bombout(("Bizarre response to offer of public key"));
2296 ssh1_read_bignum(pktin
.body
, &challenge
);
2297 response
= rsadecrypt(challenge
, &pubkey
);
2298 freebn(pubkey
.private_exponent
); /* burn the evidence */
2300 for (i
= 0; i
< 32; i
++) {
2301 buffer
[i
] = bignum_byte(response
, 31 - i
);
2305 MD5Update(&md5c
, buffer
, 32);
2306 MD5Update(&md5c
, session_id
, 16);
2307 MD5Final(buffer
, &md5c
);
2309 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2310 PKT_DATA
, buffer
, 16, PKT_END
);
2313 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2314 if (flags
& FLAG_VERBOSE
)
2316 ("Failed to authenticate with our public key.\r\n");
2317 continue; /* go and try password */
2318 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2320 ("Bizarre response to RSA authentication response"));
2324 break; /* we're through! */
2326 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2328 * Defence against traffic analysis: we send a
2329 * whole bunch of packets containing strings of
2330 * different lengths. One of these strings is the
2331 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2332 * The others are all random data in
2333 * SSH1_MSG_IGNORE packets. This way a passive
2334 * listener can't tell which is the password, and
2335 * hence can't deduce the password length.
2337 * Anybody with a password length greater than 16
2338 * bytes is going to have enough entropy in their
2339 * password that a listener won't find it _that_
2340 * much help to know how long it is. So what we'll
2343 * - if password length < 16, we send 15 packets
2344 * containing string lengths 1 through 15
2346 * - otherwise, we let N be the nearest multiple
2347 * of 8 below the password length, and send 8
2348 * packets containing string lengths N through
2349 * N+7. This won't obscure the order of
2350 * magnitude of the password length, but it will
2351 * introduce a bit of extra uncertainty.
2353 * A few servers (the old 1.2.18 through 1.2.22)
2354 * can't deal with SSH1_MSG_IGNORE. For these
2355 * servers, we need an alternative defence. We make
2356 * use of the fact that the password is interpreted
2357 * as a C string: so we can append a NUL, then some
2360 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2365 len
= strlen(password
);
2366 if (len
< sizeof(string
)) {
2368 strcpy(string
, password
);
2369 len
++; /* cover the zero byte */
2370 while (len
< sizeof(string
)) {
2371 string
[len
++] = (char) random_byte();
2376 send_packet(pwpkt_type
, PKT_INT
, len
,
2377 PKT_DATA
, s
, len
, PKT_END
);
2379 int bottom
, top
, pwlen
, i
;
2382 pwlen
= strlen(password
);
2384 bottom
= 0; /* zero length passwords are OK! :-) */
2387 bottom
= pwlen
& ~7;
2391 assert(pwlen
>= bottom
&& pwlen
<= top
);
2393 randomstr
= smalloc(top
+ 1);
2395 for (i
= bottom
; i
<= top
; i
++) {
2397 defer_packet(pwpkt_type
, PKT_STR
, password
,
2400 for (j
= 0; j
< i
; j
++) {
2402 randomstr
[j
] = random_byte();
2403 } while (randomstr
[j
] == '\0');
2405 randomstr
[i
] = '\0';
2406 defer_packet(SSH1_MSG_IGNORE
,
2407 PKT_STR
, randomstr
, PKT_END
);
2410 ssh_pkt_defersend();
2413 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2416 logevent("Sent password");
2417 memset(password
, 0, strlen(password
));
2419 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2420 if (flags
& FLAG_VERBOSE
)
2421 c_write_str("Access denied\r\n");
2422 logevent("Authentication refused");
2423 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2424 logevent("Received disconnect request");
2425 ssh_state
= SSH_STATE_CLOSED
;
2427 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2428 bombout(("Strange packet received, type %d", pktin
.type
));
2433 logevent("Authentication successful");
2438 void sshfwd_close(struct ssh_channel
*c
)
2440 if (c
&& !c
->closes
) {
2441 if (ssh_version
== 1) {
2442 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2445 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2446 ssh2_pkt_adduint32(c
->remoteid
);
2450 if (c
->type
== CHAN_X11
) {
2452 logevent("Forwarded X11 connection terminated");
2453 } else if (c
->type
== CHAN_SOCKDATA
) {
2455 logevent("Forwarded port closed");
2460 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2462 if (ssh_version
== 1) {
2463 send_packet(SSH1_MSG_CHANNEL_DATA
,
2464 PKT_INT
, c
->remoteid
,
2465 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2467 * In SSH1 we can return 0 here - implying that forwarded
2468 * connections are never individually throttled - because
2469 * the only circumstance that can cause throttling will be
2470 * the whole SSH connection backing up, in which case
2471 * _everything_ will be throttled as a whole.
2475 ssh2_add_channel_data(c
, buf
, len
);
2476 return ssh2_try_send(c
);
2480 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2482 if (ssh_version
== 1) {
2483 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2484 c
->v
.v1
.throttling
= 0;
2488 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2492 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2498 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2501 if (ssh_state
== SSH_STATE_CLOSED
)
2504 if (cfg
.agentfwd
&& agent_exists()) {
2505 logevent("Requesting agent forwarding");
2506 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2510 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2511 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2512 bombout(("Protocol confusion"));
2514 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2515 logevent("Agent forwarding refused");
2517 logevent("Agent forwarding enabled");
2518 ssh_agentfwd_enabled
= TRUE
;
2522 if (cfg
.x11_forward
) {
2523 char proto
[20], data
[64];
2524 logevent("Requesting X11 forwarding");
2525 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2526 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2527 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2528 PKT_STR
, proto
, PKT_STR
, data
,
2529 PKT_INT
, 0, PKT_END
);
2531 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2532 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2537 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2538 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2539 bombout(("Protocol confusion"));
2541 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2542 logevent("X11 forwarding refused");
2544 logevent("X11 forwarding enabled");
2545 ssh_X11_fwd_enabled
= TRUE
;
2553 char sports
[256], dports
[256], host
[256];
2556 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2557 /* Add port forwardings. */
2562 while (*e
&& *e
!= '\t')
2568 while (*e
&& *e
!= ':')
2578 dport
= atoi(dports
);
2579 sport
= atoi(sports
);
2580 if (sport
&& dport
) {
2582 pfd_addforward(host
, dport
, sport
);
2583 sprintf(buf
, "Local port %d forwarding to %s:%d",
2584 sport
, host
, dport
);
2587 struct ssh_rportfwd
*pf
;
2588 pf
= smalloc(sizeof(*pf
));
2589 strcpy(pf
->dhost
, host
);
2591 if (add234(ssh_rportfwds
, pf
) != pf
) {
2593 "Duplicate remote port forwarding to %s:%d",
2598 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2599 sport
, host
, dport
);
2601 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2613 send_packet(SSH1_CMSG_REQUEST_PTY
,
2614 PKT_STR
, cfg
.termtype
,
2615 PKT_INT
, rows
, PKT_INT
, cols
,
2616 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2617 ssh_state
= SSH_STATE_INTERMED
;
2621 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2622 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2623 bombout(("Protocol confusion"));
2625 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2626 c_write_str("Server refused to allocate pty\r\n");
2627 ssh_editing
= ssh_echoing
= 1;
2629 logevent("Allocated pty");
2631 ssh_editing
= ssh_echoing
= 1;
2634 if (cfg
.compression
) {
2635 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2639 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2640 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2641 bombout(("Protocol confusion"));
2643 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2644 c_write_str("Server refused to compress\r\n");
2646 logevent("Started compression");
2647 ssh1_compressing
= TRUE
;
2648 zlib_compress_init();
2649 zlib_decompress_init();
2652 if (*cfg
.remote_cmd_ptr
)
2653 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
,
2656 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2657 logevent("Started session");
2659 ssh_state
= SSH_STATE_SESSION
;
2663 ssh_special(TS_EOF
);
2665 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2667 ssh_channels
= newtree234(ssh_channelcmp
);
2671 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2672 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2673 long len
= GET_32BIT(pktin
.body
);
2675 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2676 pktin
.body
+ 4, len
);
2677 if (bufsize
> SSH1_BUFFER_LIMIT
) {
2678 ssh1_stdout_throttling
= 1;
2681 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2682 ssh_state
= SSH_STATE_CLOSED
;
2683 logevent("Received disconnect request");
2685 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2686 /* Remote side is trying to open a channel to talk to our
2687 * X-Server. Give them back a local channel number. */
2688 struct ssh_channel
*c
;
2690 logevent("Received X11 connect request");
2691 /* Refuse if X11 forwarding is disabled. */
2692 if (!ssh_X11_fwd_enabled
) {
2693 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2694 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2695 logevent("Rejected X11 connect request");
2697 c
= smalloc(sizeof(struct ssh_channel
));
2699 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2700 logevent("opening X11 forward connection failed");
2702 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2703 PKT_INT
, GET_32BIT(pktin
.body
),
2707 ("opening X11 forward connection succeeded");
2708 c
->remoteid
= GET_32BIT(pktin
.body
);
2709 c
->localid
= alloc_channel_id();
2711 c
->v
.v1
.throttling
= 0;
2712 c
->type
= CHAN_X11
; /* identify channel type */
2713 add234(ssh_channels
, c
);
2714 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2715 PKT_INT
, c
->remoteid
, PKT_INT
,
2716 c
->localid
, PKT_END
);
2717 logevent("Opened X11 forward channel");
2720 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2721 /* Remote side is trying to open a channel to talk to our
2722 * agent. Give them back a local channel number. */
2723 struct ssh_channel
*c
;
2725 /* Refuse if agent forwarding is disabled. */
2726 if (!ssh_agentfwd_enabled
) {
2727 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2728 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2730 c
= smalloc(sizeof(struct ssh_channel
));
2731 c
->remoteid
= GET_32BIT(pktin
.body
);
2732 c
->localid
= alloc_channel_id();
2734 c
->v
.v1
.throttling
= 0;
2735 c
->type
= CHAN_AGENT
; /* identify channel type */
2736 c
->u
.a
.lensofar
= 0;
2737 add234(ssh_channels
, c
);
2738 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2739 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2742 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2743 /* Remote side is trying to open a channel to talk to a
2744 * forwarded port. Give them back a local channel number. */
2745 struct ssh_channel
*c
;
2746 struct ssh_rportfwd pf
;
2748 char host
[256], buf
[1024];
2750 c
= smalloc(sizeof(struct ssh_channel
));
2752 hostsize
= GET_32BIT(pktin
.body
+4);
2753 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2754 if (h
+1 < host
+sizeof(host
))
2759 port
= GET_32BIT(p
);
2761 strcpy(pf
.dhost
, host
);
2764 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2765 sprintf(buf
, "Rejected remote port open request for %s:%d",
2768 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2769 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2771 sprintf(buf
, "Received remote port open request for %s:%d",
2774 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2777 sprintf(buf
, "Port open failed: %s", e
);
2780 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2781 PKT_INT
, GET_32BIT(pktin
.body
),
2784 c
->remoteid
= GET_32BIT(pktin
.body
);
2785 c
->localid
= alloc_channel_id();
2787 c
->v
.v1
.throttling
= 0;
2788 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2789 add234(ssh_channels
, c
);
2790 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2791 PKT_INT
, c
->remoteid
, PKT_INT
,
2792 c
->localid
, PKT_END
);
2793 logevent("Forwarded port opened successfully");
2797 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2798 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2799 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2800 struct ssh_channel
*c
;
2802 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2803 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2804 c
->remoteid
= localid
;
2805 c
->type
= CHAN_SOCKDATA
;
2806 pfd_confirm(c
->u
.pfd
.s
);
2809 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2810 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2811 /* Remote side closes a channel. */
2812 unsigned i
= GET_32BIT(pktin
.body
);
2813 struct ssh_channel
*c
;
2814 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2818 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2819 if (!(c
->closes
& closetype
))
2820 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2822 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2823 logevent("Forwarded X11 connection terminated");
2824 assert(c
->u
.x11
.s
!= NULL
);
2825 x11_close(c
->u
.x11
.s
);
2828 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
2829 logevent("Forwarded port closed");
2830 assert(c
->u
.pfd
.s
!= NULL
);
2831 pfd_close(c
->u
.pfd
.s
);
2834 c
->closes
|= closetype
;
2835 if (c
->closes
== 3) {
2836 del234(ssh_channels
, c
);
2840 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2841 /* Data sent down one of our channels. */
2842 int i
= GET_32BIT(pktin
.body
);
2843 int len
= GET_32BIT(pktin
.body
+ 4);
2844 unsigned char *p
= pktin
.body
+ 8;
2845 struct ssh_channel
*c
;
2846 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2851 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
2854 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
2857 /* Data for an agent message. Buffer it. */
2859 if (c
->u
.a
.lensofar
< 4) {
2860 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2861 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2865 c
->u
.a
.lensofar
+= l
;
2867 if (c
->u
.a
.lensofar
== 4) {
2869 4 + GET_32BIT(c
->u
.a
.msglen
);
2870 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2871 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2873 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2875 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
2877 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
2881 c
->u
.a
.lensofar
+= l
;
2883 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2884 void *reply
, *sentreply
;
2886 agent_query(c
->u
.a
.message
,
2887 c
->u
.a
.totallen
, &reply
,
2892 /* Fake SSH_AGENT_FAILURE. */
2893 sentreply
= "\0\0\0\1\5";
2896 send_packet(SSH1_MSG_CHANNEL_DATA
,
2897 PKT_INT
, c
->remoteid
,
2899 PKT_DATA
, sentreply
, replylen
,
2903 sfree(c
->u
.a
.message
);
2904 c
->u
.a
.lensofar
= 0;
2907 bufsize
= 0; /* agent channels never back up */
2910 if (bufsize
> SSH1_BUFFER_LIMIT
) {
2911 c
->v
.v1
.throttling
= 1;
2915 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2916 /* may be from EXEC_SHELL on some servers */
2917 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2918 /* may be from EXEC_SHELL on some servers
2919 * if no pty is available or in other odd cases. Ignore */
2920 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2921 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2923 bombout(("Strange packet received: type %d", pktin
.type
));
2928 int len
= min(inlen
, 512);
2929 send_packet(SSH1_CMSG_STDIN_DATA
,
2930 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2941 * Utility routine for decoding comma-separated strings in KEXINIT.
2943 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
2945 int needlen
= strlen(needle
);
2948 * Is it at the start of the string?
2950 if (haylen
>= needlen
&& /* haystack is long enough */
2951 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2952 (haylen
== needlen
|| haystack
[needlen
] == ',')
2953 /* either , or EOS follows */
2957 * If not, search for the next comma and resume after that.
2958 * If no comma found, terminate.
2960 while (haylen
> 0 && *haystack
!= ',')
2961 haylen
--, haystack
++;
2964 haylen
--, haystack
++; /* skip over comma itself */
2969 * SSH2 key creation method.
2971 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
2975 /* First 20 bytes. */
2978 SHA_Bytes(&s
, H
, 20);
2979 SHA_Bytes(&s
, &chr
, 1);
2980 SHA_Bytes(&s
, sessid
, 20);
2981 SHA_Final(&s
, keyspace
);
2982 /* Next 20 bytes. */
2985 SHA_Bytes(&s
, H
, 20);
2986 SHA_Bytes(&s
, keyspace
, 20);
2987 SHA_Final(&s
, keyspace
+ 20);
2991 * Handle the SSH2 transport layer.
2993 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2995 static int i
, j
, len
, nbits
, pbits
;
2997 static Bignum p
, g
, e
, f
, K
;
2998 static int kex_init_value
, kex_reply_value
;
2999 static const struct ssh_mac
**maclist
;
3001 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3002 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3003 static const struct ssh_mac
*csmac_tobe
= NULL
;
3004 static const struct ssh_mac
*scmac_tobe
= NULL
;
3005 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3006 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3007 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3008 static int hostkeylen
, siglen
;
3009 static void *hkey
; /* actual host key */
3010 static unsigned char exchange_hash
[20];
3011 static unsigned char keyspace
[40];
3012 static const struct ssh2_ciphers
*preferred_cipher
;
3013 static const struct ssh_compress
*preferred_comp
;
3014 static int first_kex
;
3021 * Set up the preferred cipher and compression.
3023 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
3024 preferred_cipher
= &ssh2_blowfish
;
3025 } else if (cfg
.cipher
== CIPHER_DES
) {
3026 logevent("Single DES not supported in SSH2; using 3DES");
3027 preferred_cipher
= &ssh2_3des
;
3028 } else if (cfg
.cipher
== CIPHER_3DES
) {
3029 preferred_cipher
= &ssh2_3des
;
3030 } else if (cfg
.cipher
== CIPHER_AES
) {
3031 preferred_cipher
= &ssh2_aes
;
3033 /* Shouldn't happen, but we do want to initialise to _something_. */
3034 preferred_cipher
= &ssh2_3des
;
3036 if (cfg
.compression
)
3037 preferred_comp
= &ssh_zlib
;
3039 preferred_comp
= &ssh_comp_none
;
3042 * Be prepared to work around the buggy MAC problem.
3044 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3045 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3047 maclist
= macs
, nmacs
= lenof(macs
);
3051 * Construct and send our key exchange packet.
3053 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3054 for (i
= 0; i
< 16; i
++)
3055 ssh2_pkt_addbyte((unsigned char) random_byte());
3056 /* List key exchange algorithms. */
3057 ssh2_pkt_addstring_start();
3058 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3059 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3060 if (i
< lenof(kex_algs
) - 1)
3061 ssh2_pkt_addstring_str(",");
3063 /* List server host key algorithms. */
3064 ssh2_pkt_addstring_start();
3065 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3066 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3067 if (i
< lenof(hostkey_algs
) - 1)
3068 ssh2_pkt_addstring_str(",");
3070 /* List client->server encryption algorithms. */
3071 ssh2_pkt_addstring_start();
3072 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
3073 const struct ssh2_ciphers
*c
=
3074 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
3075 for (j
= 0; j
< c
->nciphers
; j
++) {
3076 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3077 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
3078 ssh2_pkt_addstring_str(",");
3081 /* List server->client encryption algorithms. */
3082 ssh2_pkt_addstring_start();
3083 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
3084 const struct ssh2_ciphers
*c
=
3085 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
3086 for (j
= 0; j
< c
->nciphers
; j
++) {
3087 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3088 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
3089 ssh2_pkt_addstring_str(",");
3092 /* List client->server MAC algorithms. */
3093 ssh2_pkt_addstring_start();
3094 for (i
= 0; i
< nmacs
; i
++) {
3095 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3097 ssh2_pkt_addstring_str(",");
3099 /* List server->client MAC algorithms. */
3100 ssh2_pkt_addstring_start();
3101 for (i
= 0; i
< nmacs
; i
++) {
3102 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3104 ssh2_pkt_addstring_str(",");
3106 /* List client->server compression algorithms. */
3107 ssh2_pkt_addstring_start();
3108 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3109 const struct ssh_compress
*c
=
3110 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3111 ssh2_pkt_addstring_str(c
->name
);
3112 if (i
< lenof(compressions
))
3113 ssh2_pkt_addstring_str(",");
3115 /* List server->client compression algorithms. */
3116 ssh2_pkt_addstring_start();
3117 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3118 const struct ssh_compress
*c
=
3119 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3120 ssh2_pkt_addstring_str(c
->name
);
3121 if (i
< lenof(compressions
))
3122 ssh2_pkt_addstring_str(",");
3124 /* List client->server languages. Empty list. */
3125 ssh2_pkt_addstring_start();
3126 /* List server->client languages. Empty list. */
3127 ssh2_pkt_addstring_start();
3128 /* First KEX packet does _not_ follow, because we're not that brave. */
3129 ssh2_pkt_addbool(FALSE
);
3131 ssh2_pkt_adduint32(0);
3133 exhash
= exhashbase
;
3134 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3140 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3143 * Now examine the other side's KEXINIT to see what we're up
3146 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3147 bombout(("expected key exchange packet from server"));
3152 cscipher_tobe
= NULL
;
3153 sccipher_tobe
= NULL
;
3158 pktin
.savedpos
+= 16; /* skip garbage cookie */
3159 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3160 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3161 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3166 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3167 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3168 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3169 hostkey
= hostkey_algs
[i
];
3173 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3174 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
3175 const struct ssh2_ciphers
*c
=
3176 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
3177 for (j
= 0; j
< c
->nciphers
; j
++) {
3178 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3179 cscipher_tobe
= c
->list
[j
];
3186 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3187 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
3188 const struct ssh2_ciphers
*c
=
3189 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
3190 for (j
= 0; j
< c
->nciphers
; j
++) {
3191 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3192 sccipher_tobe
= c
->list
[j
];
3199 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3200 for (i
= 0; i
< nmacs
; i
++) {
3201 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3202 csmac_tobe
= maclist
[i
];
3206 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3207 for (i
= 0; i
< nmacs
; i
++) {
3208 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3209 scmac_tobe
= maclist
[i
];
3213 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3214 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3215 const struct ssh_compress
*c
=
3216 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3217 if (in_commasep_string(c
->name
, str
, len
)) {
3222 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3223 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3224 const struct ssh_compress
*c
=
3225 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3226 if (in_commasep_string(c
->name
, str
, len
)) {
3233 * Work out the number of bits of key we will need from the key
3234 * exchange. We start with the maximum key length of either
3240 csbits
= cscipher_tobe
->keylen
;
3241 scbits
= sccipher_tobe
->keylen
;
3242 nbits
= (csbits
> scbits ? csbits
: scbits
);
3244 /* The keys only have 160-bit entropy, since they're based on
3245 * a SHA-1 hash. So cap the key size at 160 bits. */
3250 * If we're doing Diffie-Hellman group exchange, start by
3251 * requesting a group.
3253 if (kex
== &ssh_diffiehellman_gex
) {
3254 logevent("Doing Diffie-Hellman group exchange");
3256 * Work out how big a DH group we will need to allow that
3259 pbits
= 512 << ((nbits
- 1) / 64);
3260 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3261 ssh2_pkt_adduint32(pbits
);
3265 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3266 bombout(("expected key exchange group packet from server"));
3269 p
= ssh2_pkt_getmp();
3270 g
= ssh2_pkt_getmp();
3271 dh_setup_group(p
, g
);
3272 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3273 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3276 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3277 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3280 logevent("Doing Diffie-Hellman key exchange");
3282 * Now generate and send e for Diffie-Hellman.
3284 e
= dh_create_e(nbits
* 2);
3285 ssh2_pkt_init(kex_init_value
);
3290 if (pktin
.type
!= kex_reply_value
) {
3291 bombout(("expected key exchange reply packet from server"));
3294 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3295 f
= ssh2_pkt_getmp();
3296 ssh2_pkt_getstring(&sigdata
, &siglen
);
3300 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3301 if (kex
== &ssh_diffiehellman_gex
) {
3302 sha_uint32(&exhash
, pbits
);
3303 sha_mpint(&exhash
, p
);
3304 sha_mpint(&exhash
, g
);
3306 sha_mpint(&exhash
, e
);
3307 sha_mpint(&exhash
, f
);
3308 sha_mpint(&exhash
, K
);
3309 SHA_Final(&exhash
, exchange_hash
);
3314 debug(("Exchange hash is:\n"));
3315 dmemdump(exchange_hash
, 20);
3318 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3320 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3321 bombout(("Server's host key did not match the signature supplied"));
3326 * Expect SSH2_MSG_NEWKEYS from server.
3329 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3330 bombout(("expected new-keys packet from server"));
3335 * Authenticate remote host: verify host key. (We've already
3336 * checked the signature of the exchange hash.)
3338 keystr
= hostkey
->fmtkey(hkey
);
3339 fingerprint
= hostkey
->fingerprint(hkey
);
3340 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3341 keystr
, fingerprint
);
3342 if (first_kex
) { /* don't bother logging this in rekeys */
3343 logevent("Host key fingerprint is:");
3344 logevent(fingerprint
);
3348 hostkey
->freekey(hkey
);
3351 * Send SSH2_MSG_NEWKEYS.
3353 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3357 * Create and initialise session keys.
3359 cscipher
= cscipher_tobe
;
3360 sccipher
= sccipher_tobe
;
3363 cscomp
= cscomp_tobe
;
3364 sccomp
= sccomp_tobe
;
3365 cscomp
->compress_init();
3366 sccomp
->decompress_init();
3368 * Set IVs after keys. Here we use the exchange hash from the
3369 * _first_ key exchange.
3372 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3373 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3374 cscipher
->setcskey(keyspace
);
3375 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3376 sccipher
->setsckey(keyspace
);
3377 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3378 cscipher
->setcsiv(keyspace
);
3379 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3380 sccipher
->setsciv(keyspace
);
3381 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3382 csmac
->setcskey(keyspace
);
3383 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3384 scmac
->setsckey(keyspace
);
3387 * If this is the first key exchange phase, we must pass the
3388 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3389 * wants to see it but because it will need time to initialise
3390 * itself before it sees an actual packet. In subsequent key
3391 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3392 * it would only confuse the layer above.
3400 * Now we're encrypting. Begin returning 1 to the protocol main
3401 * function so that other things can run on top of the
3402 * transport. If we ever see a KEXINIT, we must go back to the
3405 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3408 logevent("Server initiated key re-exchange");
3409 goto begin_key_exchange
;
3415 * Add data to an SSH2 channel output buffer.
3417 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3420 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3424 * Attempt to send data on an SSH2 channel.
3426 static int ssh2_try_send(struct ssh_channel
*c
)
3428 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3431 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3432 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3433 len
= c
->v
.v2
.remwindow
;
3434 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3435 len
= c
->v
.v2
.remmaxpkt
;
3436 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3437 ssh2_pkt_adduint32(c
->remoteid
);
3438 ssh2_pkt_addstring_start();
3439 ssh2_pkt_addstring_data(data
, len
);
3441 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3442 c
->v
.v2
.remwindow
-= len
;
3446 * After having sent as much data as we can, return the amount
3449 return bufchain_size(&c
->v
.v2
.outbuffer
);
3453 * Potentially enlarge the window on an SSH2 channel.
3455 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3457 if (newwin
> c
->v
.v2
.locwindow
) {
3458 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3459 ssh2_pkt_adduint32(c
->remoteid
);
3460 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3462 c
->v
.v2
.locwindow
= newwin
;
3467 * Handle the SSH2 userauth and connection layers.
3469 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3472 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3474 AUTH_KEYBOARD_INTERACTIVE
3478 AUTH_TYPE_PUBLICKEY
,
3479 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3480 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3482 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3483 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3485 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3486 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3487 static int kbd_inter_running
;
3488 static int we_are_in
;
3489 static int num_prompts
, echo
;
3490 static char username
[100];
3491 static char pwprompt
[200];
3492 static char password
[100];
3497 * Request userauth protocol, and await a response to it.
3499 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3500 ssh2_pkt_addstring("ssh-userauth");
3502 crWaitUntilV(ispkt
);
3503 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3504 bombout(("Server refused user authentication protocol"));
3509 * We repeat this whole loop, including the username prompt,
3510 * until we manage a successful authentication. If the user
3511 * types the wrong _password_, they are sent back to the
3512 * beginning to try another username. (If they specify a
3513 * username in the config, they are never asked, even if they
3514 * do give a wrong password.)
3516 * I think this best serves the needs of
3518 * - the people who have no configuration, no keys, and just
3519 * want to try repeated (username,password) pairs until they
3520 * type both correctly
3522 * - people who have keys and configuration but occasionally
3523 * need to fall back to passwords
3525 * - people with a key held in Pageant, who might not have
3526 * logged in to a particular machine before; so they want to
3527 * type a username, and then _either_ their key will be
3528 * accepted, _or_ they will type a password. If they mistype
3529 * the username they will want to be able to get back and
3540 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3542 if (!ssh_get_line("login as: ",
3543 username
, sizeof(username
), FALSE
)) {
3545 * get_line failed to get a username.
3548 logevent("No username provided. Abandoning session.");
3549 ssh_state
= SSH_STATE_CLOSED
;
3553 c_write_str("login as: ");
3556 crWaitUntilV(!ispkt
);
3558 switch (c
= *in
++) {
3567 c_write_str("\b \b");
3574 c_write_str("\b \b");
3584 if (((c
>= ' ' && c
<= '~') ||
3585 ((unsigned char) c
>= 160))
3586 && pos
< sizeof(username
)-1) {
3587 username
[pos
++] = c
;
3594 c_write_str("\r\n");
3595 username
[strcspn(username
, "\n\r")] = '\0';
3598 strncpy(username
, cfg
.username
, 99);
3599 username
[99] = '\0';
3600 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3601 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3607 * Send an authentication request using method "none": (a)
3608 * just in case it succeeds, and (b) so that we know what
3609 * authentication methods we can usefully try next.
3611 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3612 ssh2_pkt_addstring(username
);
3613 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3614 ssh2_pkt_addstring("none"); /* method */
3616 type
= AUTH_TYPE_NONE
;
3620 tried_pubkey_config
= FALSE
;
3621 tried_agent
= FALSE
;
3622 tried_keyb_inter
= FALSE
;
3623 kbd_inter_running
= FALSE
;
3627 * Wait for the result of the last authentication request.
3630 crWaitUntilV(ispkt
);
3631 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3635 * Don't show the banner if we're operating in
3636 * non-verbose non-interactive mode. (It's probably
3637 * a script, which means nobody will read the
3638 * banner _anyway_, and moreover the printing of
3639 * the banner will screw up processing on the
3640 * output of (say) plink.)
3642 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3643 ssh2_pkt_getstring(&banner
, &size
);
3645 c_write_untrusted(banner
, size
);
3647 crWaitUntilV(ispkt
);
3649 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3650 logevent("Access granted");
3655 if (kbd_inter_running
&&
3656 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3658 * This is a further prompt in keyboard-interactive
3659 * authentication. Do nothing.
3661 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3662 bombout(("Strange packet received during authentication: type %d",
3670 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3671 * we can look at the string in it and know what we can
3672 * helpfully try next.
3674 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
3677 ssh2_pkt_getstring(&methods
, &methlen
);
3678 kbd_inter_running
= FALSE
;
3679 if (!ssh2_pkt_getbool()) {
3681 * We have received an unequivocal Access
3682 * Denied. This can translate to a variety of
3685 * - if we'd just tried "none" authentication,
3686 * it's not worth printing anything at all
3688 * - if we'd just tried a public key _offer_,
3689 * the message should be "Server refused our
3690 * key" (or no message at all if the key
3691 * came from Pageant)
3693 * - if we'd just tried anything else, the
3694 * message really should be "Access denied".
3696 * Additionally, if we'd just tried password
3697 * authentication, we should break out of this
3698 * whole loop so as to go back to the username
3701 if (type
== AUTH_TYPE_NONE
) {
3703 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3704 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3705 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3706 c_write_str("Server refused our key\r\n");
3707 logevent("Server refused public key");
3708 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
3709 /* server declined keyboard-interactive; ignore */
3711 c_write_str("Access denied\r\n");
3712 logevent("Access denied");
3713 if (type
== AUTH_TYPE_PASSWORD
) {
3719 c_write_str("Further authentication required\r\n");
3720 logevent("Further authentication required");
3724 in_commasep_string("publickey", methods
, methlen
);
3726 in_commasep_string("password", methods
, methlen
);
3728 in_commasep_string("password", methods
, methlen
);
3730 in_commasep_string("keyboard-interactive", methods
, methlen
);
3735 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
3736 method
= AUTH_KEYBOARD_INTERACTIVE
;
3737 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3738 tried_keyb_inter
= TRUE
;
3740 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3741 ssh2_pkt_addstring(username
);
3742 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3743 ssh2_pkt_addstring("keyboard-interactive"); /* method */
3744 ssh2_pkt_addstring(""); /* lang */
3745 ssh2_pkt_addstring("");
3748 crWaitUntilV(ispkt
);
3749 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3750 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
3752 logevent("Keyboard-interactive authentication refused");
3753 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
3757 kbd_inter_running
= TRUE
;
3760 if (kbd_inter_running
) {
3761 method
= AUTH_KEYBOARD_INTERACTIVE
;
3762 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3763 tried_keyb_inter
= TRUE
;
3765 /* We've got packet with that "interactive" info
3766 dump banners, and set its prompt as ours */
3768 char *name
, *inst
, *lang
, *prompt
;
3769 int name_len
, inst_len
, lang_len
, prompt_len
;
3770 ssh2_pkt_getstring(&name
, &name_len
);
3771 ssh2_pkt_getstring(&inst
, &inst_len
);
3772 ssh2_pkt_getstring(&lang
, &lang_len
);
3774 c_write_untrusted(name
, name_len
);
3776 c_write_untrusted(inst
, inst_len
);
3777 num_prompts
= ssh2_pkt_getuint32();
3779 ssh2_pkt_getstring(&prompt
, &prompt_len
);
3780 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
3783 echo
= ssh2_pkt_getbool();
3787 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3789 * Attempt public-key authentication using Pageant.
3791 static unsigned char request
[5], *response
, *p
;
3792 static int responselen
;
3793 static int i
, nkeys
;
3794 static int authed
= FALSE
;
3799 logevent("Pageant is running. Requesting keys.");
3801 /* Request the keys held by the agent. */
3802 PUT_32BIT(request
, 1);
3803 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3804 agent_query(request
, 5, &r
, &responselen
);
3805 response
= (unsigned char *) r
;
3806 if (response
&& responselen
>= 5 &&
3807 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3809 nkeys
= GET_32BIT(p
);
3813 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3816 for (i
= 0; i
< nkeys
; i
++) {
3817 static char *pkblob
, *alg
, *commentp
;
3818 static int pklen
, alglen
, commentlen
;
3819 static int siglen
, retlen
, len
;
3820 static char *q
, *agentreq
, *ret
;
3825 sprintf(buf
, "Trying Pageant key #%d", i
);
3828 pklen
= GET_32BIT(p
);
3832 alglen
= GET_32BIT(pkblob
);
3834 commentlen
= GET_32BIT(p
);
3838 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3839 ssh2_pkt_addstring(username
);
3840 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3841 ssh2_pkt_addstring("publickey"); /* method */
3842 ssh2_pkt_addbool(FALSE
); /* no signature included */
3843 ssh2_pkt_addstring_start();
3844 ssh2_pkt_addstring_data(alg
, alglen
);
3845 ssh2_pkt_addstring_start();
3846 ssh2_pkt_addstring_data(pkblob
, pklen
);
3849 crWaitUntilV(ispkt
);
3850 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3851 logevent("Key refused");
3855 if (flags
& FLAG_VERBOSE
) {
3857 ("Authenticating with public key \"");
3858 c_write(commentp
, commentlen
);
3859 c_write_str("\" from agent\r\n");
3863 * Server is willing to accept the key.
3864 * Construct a SIGN_REQUEST.
3866 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3867 ssh2_pkt_addstring(username
);
3868 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3869 ssh2_pkt_addstring("publickey"); /* method */
3870 ssh2_pkt_addbool(TRUE
);
3871 ssh2_pkt_addstring_start();
3872 ssh2_pkt_addstring_data(alg
, alglen
);
3873 ssh2_pkt_addstring_start();
3874 ssh2_pkt_addstring_data(pkblob
, pklen
);
3876 siglen
= pktout
.length
- 5 + 4 + 20;
3877 len
= 1; /* message type */
3878 len
+= 4 + pklen
; /* key blob */
3879 len
+= 4 + siglen
; /* data to sign */
3880 len
+= 4; /* flags */
3881 agentreq
= smalloc(4 + len
);
3882 PUT_32BIT(agentreq
, len
);
3884 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3885 PUT_32BIT(q
, pklen
);
3887 memcpy(q
, pkblob
, pklen
);
3889 PUT_32BIT(q
, siglen
);
3891 /* Now the data to be signed... */
3894 memcpy(q
, ssh2_session_id
, 20);
3896 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
3897 q
+= pktout
.length
- 5;
3898 /* And finally the (zero) flags word. */
3900 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
3904 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3905 logevent("Sending Pageant's response");
3906 ssh2_pkt_addstring_start();
3907 ssh2_pkt_addstring_data(ret
+ 9,
3915 ("Pageant failed to answer challenge");
3925 if (!method
&& can_pubkey
&& *cfg
.keyfile
3926 && !tried_pubkey_config
) {
3927 unsigned char *pub_blob
;
3928 char *algorithm
, *comment
;
3931 tried_pubkey_config
= TRUE
;
3934 * Try the public key supplied in the configuration.
3936 * First, offer the public blob to see if the server is
3937 * willing to accept it.
3939 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
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(algorithm
);
3948 ssh2_pkt_addstring_start();
3949 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3951 logevent("Offered public key"); /* FIXME */
3953 crWaitUntilV(ispkt
);
3954 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3956 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3957 continue; /* key refused; give up on it */
3960 logevent("Offer of public key accepted");
3962 * Actually attempt a serious authentication using
3965 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3967 "Passphrase for key \"%.100s\": ",
3973 c_write_str("Authenticating with public key \"");
3974 c_write_str(comment
);
3975 c_write_str("\"\r\n");
3976 method
= AUTH_PUBLICKEY_FILE
;
3980 if (!method
&& can_passwd
) {
3981 method
= AUTH_PASSWORD
;
3982 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
3989 if (!ssh_get_line(pwprompt
, password
,
3990 sizeof(password
), TRUE
)) {
3992 * get_line failed to get a password (for
3993 * example because one was supplied on the
3994 * command line which has already failed to
3997 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3998 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4000 ("No more passwords available to try");
4001 ssh2_pkt_addstring("en"); /* language tag */
4003 connection_fatal("Unable to authenticate");
4004 ssh_state
= SSH_STATE_CLOSED
;
4011 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4016 crWaitUntilV(!ispkt
);
4018 switch (c
= *in
++) {
4039 if (pos
< sizeof(password
)-1)
4040 password
[pos
++] = c
;
4044 c_write_str("\r\n");
4048 if (method
== AUTH_PUBLICKEY_FILE
) {
4050 * We have our passphrase. Now try the actual authentication.
4052 struct ssh2_userkey
*key
;
4054 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4055 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4056 if (key
== SSH2_WRONG_PASSPHRASE
) {
4057 c_write_str("Wrong passphrase\r\n");
4058 tried_pubkey_config
= FALSE
;
4060 c_write_str("Unable to load private key\r\n");
4061 tried_pubkey_config
= TRUE
;
4063 /* Send a spurious AUTH_NONE to return to the top. */
4064 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4065 ssh2_pkt_addstring(username
);
4066 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4067 ssh2_pkt_addstring("none"); /* method */
4069 type
= AUTH_TYPE_NONE
;
4071 unsigned char *blob
, *sigdata
;
4072 int blob_len
, sigdata_len
;
4075 * We have loaded the private key and the server
4076 * has announced that it's willing to accept it.
4077 * Hallelujah. Generate a signature and send it.
4079 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4080 ssh2_pkt_addstring(username
);
4081 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4082 ssh2_pkt_addstring("publickey"); /* method */
4083 ssh2_pkt_addbool(TRUE
);
4084 ssh2_pkt_addstring(key
->alg
->name
);
4085 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4086 ssh2_pkt_addstring_start();
4087 ssh2_pkt_addstring_data(blob
, blob_len
);
4091 * The data to be signed is:
4095 * followed by everything so far placed in the
4098 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4099 sigdata
= smalloc(sigdata_len
);
4100 PUT_32BIT(sigdata
, 20);
4101 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4102 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4105 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4107 ssh2_pkt_addstring_start();
4108 ssh2_pkt_addstring_data(blob
, blob_len
);
4113 type
= AUTH_TYPE_PUBLICKEY
;
4115 } else if (method
== AUTH_PASSWORD
) {
4117 * We send the password packet lumped tightly together with
4118 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4119 * string long enough to make the total length of the two
4120 * packets constant. This should ensure that a passive
4121 * listener doing traffic analyis can't work out the length
4124 * For this to work, we need an assumption about the
4125 * maximum length of the password packet. I think 256 is
4126 * pretty conservative. Anyone using a password longer than
4127 * that probably doesn't have much to worry about from
4128 * people who find out how long their password is!
4130 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4131 ssh2_pkt_addstring(username
);
4132 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4133 ssh2_pkt_addstring("password");
4134 ssh2_pkt_addbool(FALSE
);
4135 ssh2_pkt_addstring(password
);
4138 * We'll include a string that's an exact multiple of the
4139 * cipher block size. If the cipher is NULL for some
4140 * reason, we don't do this trick at all because we gain
4146 stringlen
= (256 - deferred_len
);
4147 stringlen
+= cscipher
->blksize
- 1;
4148 stringlen
-= (stringlen
% cscipher
->blksize
);
4151 * Temporarily disable actual compression,
4152 * so we can guarantee to get this string
4153 * exactly the length we want it. The
4154 * compression-disabling routine should
4155 * return an integer indicating how many
4156 * bytes we should adjust our string length
4159 stringlen
-= cscomp
->disable_compression();
4161 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4162 ssh2_pkt_addstring_start();
4163 for (i
= 0; i
< stringlen
; i
++) {
4164 char c
= (char) random_byte();
4165 ssh2_pkt_addstring_data(&c
, 1);
4169 ssh_pkt_defersend();
4170 logevent("Sent password");
4171 type
= AUTH_TYPE_PASSWORD
;
4172 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4173 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4174 ssh2_pkt_adduint32(num_prompts
);
4175 ssh2_pkt_addstring(password
);
4176 memset(password
, 0, sizeof(password
));
4178 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4181 ("No supported authentication methods left to try!\r\n");
4183 ("No supported authentications offered. Disconnecting");
4184 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4185 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4187 ("No supported authentication methods available");
4188 ssh2_pkt_addstring("en"); /* language tag */
4190 ssh_state
= SSH_STATE_CLOSED
;
4194 } while (!we_are_in
);
4197 * Now we're authenticated for the connection protocol. The
4198 * connection protocol will automatically have started at this
4199 * point; there's no need to send SERVICE_REQUEST.
4203 * So now create a channel with a session in it.
4205 ssh_channels
= newtree234(ssh_channelcmp
);
4206 mainchan
= smalloc(sizeof(struct ssh_channel
));
4207 mainchan
->localid
= alloc_channel_id();
4208 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4209 ssh2_pkt_addstring("session");
4210 ssh2_pkt_adduint32(mainchan
->localid
);
4211 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4212 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4213 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4215 crWaitUntilV(ispkt
);
4216 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4217 bombout(("Server refused to open a session"));
4219 /* FIXME: error data comes back in FAILURE packet */
4221 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4222 bombout(("Server's channel confirmation cited wrong channel"));
4225 mainchan
->remoteid
= ssh2_pkt_getuint32();
4226 mainchan
->type
= CHAN_MAINSESSION
;
4227 mainchan
->closes
= 0;
4228 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4229 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4230 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4231 add234(ssh_channels
, mainchan
);
4232 logevent("Opened channel for session");
4235 * Potentially enable X11 forwarding.
4237 if (cfg
.x11_forward
) {
4238 char proto
[20], data
[64];
4239 logevent("Requesting X11 forwarding");
4240 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4241 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4242 ssh2_pkt_adduint32(mainchan
->remoteid
);
4243 ssh2_pkt_addstring("x11-req");
4244 ssh2_pkt_addbool(1); /* want reply */
4245 ssh2_pkt_addbool(0); /* many connections */
4246 ssh2_pkt_addstring(proto
);
4247 ssh2_pkt_addstring(data
);
4248 ssh2_pkt_adduint32(0); /* screen number */
4252 crWaitUntilV(ispkt
);
4253 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4254 unsigned i
= ssh2_pkt_getuint32();
4255 struct ssh_channel
*c
;
4256 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4258 continue; /* nonexistent channel */
4259 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4261 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4263 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4264 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4265 bombout(("Server got confused by X11 forwarding request"));
4268 logevent("X11 forwarding refused");
4270 logevent("X11 forwarding enabled");
4271 ssh_X11_fwd_enabled
= TRUE
;
4276 * Enable port forwardings.
4279 static char *e
; /* preserve across crReturn */
4283 char sports
[256], dports
[256], host
[256];
4286 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4287 /* Add port forwardings. */
4292 while (*e
&& *e
!= '\t')
4298 while (*e
&& *e
!= ':')
4308 dport
= atoi(dports
);
4309 sport
= atoi(sports
);
4310 if (sport
&& dport
) {
4312 pfd_addforward(host
, dport
, sport
);
4313 sprintf(buf
, "Local port %d forwarding to %s:%d",
4314 sport
, host
, dport
);
4317 struct ssh_rportfwd
*pf
;
4318 pf
= smalloc(sizeof(*pf
));
4319 strcpy(pf
->dhost
, host
);
4322 if (add234(ssh_rportfwds
, pf
) != pf
) {
4324 "Duplicate remote port forwarding to %s:%d",
4329 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4330 sport
, host
, dport
);
4332 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4333 ssh2_pkt_addstring("tcpip-forward");
4334 ssh2_pkt_addbool(1);/* want reply */
4335 ssh2_pkt_addstring("127.0.0.1");
4336 ssh2_pkt_adduint32(sport
);
4340 crWaitUntilV(ispkt
);
4341 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4342 unsigned i
= ssh2_pkt_getuint32();
4343 struct ssh_channel
*c
;
4344 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4346 continue;/* nonexistent channel */
4347 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4349 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4351 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4352 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4353 bombout(("Server got confused by port forwarding request"));
4356 logevent("Server refused this port forwarding");
4358 logevent("Remote port forwarding enabled");
4367 * Potentially enable agent forwarding.
4369 if (cfg
.agentfwd
&& agent_exists()) {
4370 logevent("Requesting OpenSSH-style agent forwarding");
4371 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4372 ssh2_pkt_adduint32(mainchan
->remoteid
);
4373 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4374 ssh2_pkt_addbool(1); /* want reply */
4378 crWaitUntilV(ispkt
);
4379 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4380 unsigned i
= ssh2_pkt_getuint32();
4381 struct ssh_channel
*c
;
4382 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4384 continue; /* nonexistent channel */
4385 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4387 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4389 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4390 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4392 ("Server got confused by agent forwarding request"));
4395 logevent("Agent forwarding refused");
4397 logevent("Agent forwarding enabled");
4398 ssh_agentfwd_enabled
= TRUE
;
4403 * Now allocate a pty for the session.
4406 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4407 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4408 ssh2_pkt_addstring("pty-req");
4409 ssh2_pkt_addbool(1); /* want reply */
4410 ssh2_pkt_addstring(cfg
.termtype
);
4411 ssh2_pkt_adduint32(cols
);
4412 ssh2_pkt_adduint32(rows
);
4413 ssh2_pkt_adduint32(0); /* pixel width */
4414 ssh2_pkt_adduint32(0); /* pixel height */
4415 ssh2_pkt_addstring_start();
4416 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4418 ssh_state
= SSH_STATE_INTERMED
;
4421 crWaitUntilV(ispkt
);
4422 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4423 unsigned i
= ssh2_pkt_getuint32();
4424 struct ssh_channel
*c
;
4425 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4427 continue; /* nonexistent channel */
4428 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4430 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4432 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4433 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4434 bombout(("Server got confused by pty request"));
4437 c_write_str("Server refused to allocate pty\r\n");
4438 ssh_editing
= ssh_echoing
= 1;
4440 logevent("Allocated pty");
4443 ssh_editing
= ssh_echoing
= 1;
4447 * Start a shell or a remote command.
4449 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4450 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4451 if (cfg
.ssh_subsys
) {
4452 ssh2_pkt_addstring("subsystem");
4453 ssh2_pkt_addbool(1); /* want reply */
4454 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4455 } else if (*cfg
.remote_cmd_ptr
) {
4456 ssh2_pkt_addstring("exec");
4457 ssh2_pkt_addbool(1); /* want reply */
4458 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4460 ssh2_pkt_addstring("shell");
4461 ssh2_pkt_addbool(1); /* want reply */
4465 crWaitUntilV(ispkt
);
4466 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4467 unsigned i
= ssh2_pkt_getuint32();
4468 struct ssh_channel
*c
;
4469 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4471 continue; /* nonexistent channel */
4472 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4474 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4475 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4476 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4477 bombout(("Server got confused by shell/command request"));
4480 bombout(("Server refused to start a shell/command"));
4483 logevent("Started a shell/command");
4486 ssh_state
= SSH_STATE_SESSION
;
4490 ssh_special(TS_EOF
);
4495 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
4498 static int try_send
;
4502 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4503 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4506 unsigned i
= ssh2_pkt_getuint32();
4507 struct ssh_channel
*c
;
4508 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4510 continue; /* nonexistent channel */
4511 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4512 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4513 continue; /* extended but not stderr */
4514 ssh2_pkt_getstring(&data
, &length
);
4517 c
->v
.v2
.locwindow
-= length
;
4519 case CHAN_MAINSESSION
:
4521 from_backend(pktin
.type
==
4522 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
4526 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
4529 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
4532 while (length
> 0) {
4533 if (c
->u
.a
.lensofar
< 4) {
4534 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4535 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4539 c
->u
.a
.lensofar
+= l
;
4541 if (c
->u
.a
.lensofar
== 4) {
4543 4 + GET_32BIT(c
->u
.a
.msglen
);
4544 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4545 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4547 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4549 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4551 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4555 c
->u
.a
.lensofar
+= l
;
4557 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4558 void *reply
, *sentreply
;
4560 agent_query(c
->u
.a
.message
,
4561 c
->u
.a
.totallen
, &reply
,
4566 /* Fake SSH_AGENT_FAILURE. */
4567 sentreply
= "\0\0\0\1\5";
4570 ssh2_add_channel_data(c
, sentreply
,
4575 sfree(c
->u
.a
.message
);
4576 c
->u
.a
.lensofar
= 0;
4583 * If we are not buffering too much data,
4584 * enlarge the window again at the remote side.
4586 if (bufsize
< OUR_V2_WINSIZE
)
4587 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
4589 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4590 ssh_state
= SSH_STATE_CLOSED
;
4591 logevent("Received disconnect message");
4593 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4594 continue; /* exit status et al; ignore (FIXME?) */
4595 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4596 unsigned i
= ssh2_pkt_getuint32();
4597 struct ssh_channel
*c
;
4599 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4601 continue; /* nonexistent channel */
4603 if (c
->type
== CHAN_X11
) {
4605 * Remote EOF on an X11 channel means we should
4606 * wrap up and close the channel ourselves.
4608 x11_close(c
->u
.x11
.s
);
4610 } else if (c
->type
== CHAN_AGENT
) {
4612 } else if (c
->type
== CHAN_SOCKDATA
) {
4613 pfd_close(c
->u
.pfd
.s
);
4616 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4617 unsigned i
= ssh2_pkt_getuint32();
4618 struct ssh_channel
*c
;
4620 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4622 continue; /* nonexistent channel */
4623 if (c
->closes
== 0) {
4624 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4625 ssh2_pkt_adduint32(c
->remoteid
);
4628 /* Do pre-close processing on the channel. */
4630 case CHAN_MAINSESSION
:
4631 break; /* nothing to see here, move along */
4639 del234(ssh_channels
, c
);
4640 bufchain_clear(&c
->v
.v2
.outbuffer
);
4644 * See if that was the last channel left open.
4646 if (count234(ssh_channels
) == 0) {
4647 logevent("All channels closed. Disconnecting");
4648 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4649 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4650 ssh2_pkt_addstring("All open channels closed");
4651 ssh2_pkt_addstring("en"); /* language tag */
4653 ssh_state
= SSH_STATE_CLOSED
;
4656 continue; /* remote sends close; ignore (FIXME) */
4657 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4658 unsigned i
= ssh2_pkt_getuint32();
4659 struct ssh_channel
*c
;
4660 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4662 continue; /* nonexistent channel */
4663 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4665 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4666 unsigned i
= ssh2_pkt_getuint32();
4667 struct ssh_channel
*c
;
4668 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4670 continue; /* nonexistent channel */
4671 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4672 continue; /* dunno why they're confirming this */
4673 c
->remoteid
= ssh2_pkt_getuint32();
4674 c
->type
= CHAN_SOCKDATA
;
4676 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4677 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4678 bufchain_init(&c
->v
.v2
.outbuffer
);
4679 pfd_confirm(c
->u
.pfd
.s
);
4680 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4684 struct ssh_channel
*c
;
4685 unsigned remid
, winsize
, pktsize
;
4686 ssh2_pkt_getstring(&type
, &typelen
);
4687 c
= smalloc(sizeof(struct ssh_channel
));
4689 remid
= ssh2_pkt_getuint32();
4690 winsize
= ssh2_pkt_getuint32();
4691 pktsize
= ssh2_pkt_getuint32();
4693 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4694 if (!ssh_X11_fwd_enabled
)
4695 error
= "X11 forwarding is not enabled";
4696 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4698 error
= "Unable to open an X11 connection";
4702 } else if (typelen
== 15 &&
4703 !memcmp(type
, "forwarded-tcpip", 15)) {
4704 struct ssh_rportfwd pf
, *realpf
;
4707 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
4708 pf
.sport
= ssh2_pkt_getuint32();
4709 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
4710 if (realpf
== NULL
) {
4711 error
= "Remote port is not recognised";
4713 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
4716 sprintf(buf
, "Received remote port open request for %s:%d",
4717 realpf
->dhost
, realpf
->dport
);
4720 sprintf(buf
, "Port open failed: %s", e
);
4722 error
= "Port open failed";
4724 logevent("Forwarded port opened successfully");
4725 c
->type
= CHAN_SOCKDATA
;
4728 } else if (typelen
== 22 &&
4729 !memcmp(type
, "auth-agent@openssh.com", 3)) {
4730 if (!ssh_agentfwd_enabled
)
4731 error
= "Agent forwarding is not enabled";
4733 c
->type
= CHAN_AGENT
; /* identify channel type */
4734 c
->u
.a
.lensofar
= 0;
4737 error
= "Unsupported channel type requested";
4740 c
->remoteid
= remid
;
4742 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
4743 ssh2_pkt_adduint32(c
->remoteid
);
4744 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
4745 ssh2_pkt_addstring(error
);
4746 ssh2_pkt_addstring("en"); /* language tag */
4750 c
->localid
= alloc_channel_id();
4752 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4753 c
->v
.v2
.remwindow
= winsize
;
4754 c
->v
.v2
.remmaxpkt
= pktsize
;
4755 bufchain_init(&c
->v
.v2
.outbuffer
);
4756 add234(ssh_channels
, c
);
4757 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
4758 ssh2_pkt_adduint32(c
->remoteid
);
4759 ssh2_pkt_adduint32(c
->localid
);
4760 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
4761 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4765 bombout(("Strange packet received: type %d", pktin
.type
));
4770 * We have spare data. Add it to the channel buffer.
4772 ssh2_add_channel_data(mainchan
, in
, inlen
);
4777 struct ssh_channel
*c
;
4779 * Try to send data on all channels if we can.
4781 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
4782 int bufsize
= ssh2_try_send(c
);
4785 case CHAN_MAINSESSION
:
4786 /* stdin need not receive an unthrottle
4787 * notification since it will be polled */
4790 x11_unthrottle(c
->u
.x11
.s
);
4793 /* agent sockets are request/response and need no
4794 * buffer management */
4797 pfd_unthrottle(c
->u
.pfd
.s
);
4809 * Handle the top-level SSH2 protocol.
4811 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
4813 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
4815 do_ssh2_authconn(in
, inlen
, ispkt
);
4819 * Called to set up the connection.
4821 * Returns an error message, or NULL on success.
4823 static char *ssh_init(char *host
, int port
, char **realhost
)
4828 if (crypto_startup() == 0)
4829 return "Microsoft high encryption pack not installed!";
4835 ssh1_throttle_count
= 0;
4836 ssh_overall_bufsize
= 0;
4838 p
= connect_to_host(host
, port
, realhost
);
4846 * Called to send data down the Telnet connection.
4848 static int ssh_send(char *buf
, int len
)
4850 if (s
== NULL
|| ssh_protocol
== NULL
)
4853 ssh_protocol(buf
, len
, 0);
4855 return ssh_sendbuffer();
4859 * Called to query the current amount of buffered stdin data.
4861 static int ssh_sendbuffer(void)
4865 if (s
== NULL
|| ssh_protocol
== NULL
)
4869 * If the SSH socket itself has backed up, add the total backup
4870 * size on that to any individual buffer on the stdin channel.
4873 if (ssh_throttled_all
)
4874 override_value
= ssh_overall_bufsize
;
4876 if (ssh_version
== 1) {
4877 return override_value
;
4878 } else if (ssh_version
== 2) {
4879 if (!mainchan
|| mainchan
->closes
> 0)
4880 return override_value
;
4882 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
4889 * Called to set the size of the window from SSH's POV.
4891 static void ssh_size(void)
4893 switch (ssh_state
) {
4894 case SSH_STATE_BEFORE_SIZE
:
4895 case SSH_STATE_PREPACKET
:
4896 case SSH_STATE_CLOSED
:
4897 break; /* do nothing */
4898 case SSH_STATE_INTERMED
:
4899 size_needed
= TRUE
; /* buffer for later */
4901 case SSH_STATE_SESSION
:
4903 if (ssh_version
== 1) {
4904 send_packet(SSH1_CMSG_WINDOW_SIZE
,
4905 PKT_INT
, rows
, PKT_INT
, cols
,
4906 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
4908 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4909 ssh2_pkt_adduint32(mainchan
->remoteid
);
4910 ssh2_pkt_addstring("window-change");
4911 ssh2_pkt_addbool(0);
4912 ssh2_pkt_adduint32(cols
);
4913 ssh2_pkt_adduint32(rows
);
4914 ssh2_pkt_adduint32(0);
4915 ssh2_pkt_adduint32(0);
4924 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4925 * can send an EOF and collect resulting output (e.g. `plink
4928 static void ssh_special(Telnet_Special code
)
4930 if (code
== TS_EOF
) {
4931 if (ssh_state
!= SSH_STATE_SESSION
) {
4933 * Buffer the EOF in case we are pre-SESSION, so we can
4934 * send it as soon as we reach SESSION.
4940 if (ssh_version
== 1) {
4941 send_packet(SSH1_CMSG_EOF
, PKT_END
);
4943 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4944 ssh2_pkt_adduint32(mainchan
->remoteid
);
4947 logevent("Sent EOF message");
4948 } else if (code
== TS_PING
) {
4949 if (ssh_state
== SSH_STATE_CLOSED
4950 || ssh_state
== SSH_STATE_PREPACKET
) return;
4951 if (ssh_version
== 1) {
4952 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
4954 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4955 ssh2_pkt_addstring_start();
4963 void *new_sock_channel(Socket s
)
4965 struct ssh_channel
*c
;
4966 c
= smalloc(sizeof(struct ssh_channel
));
4969 c
->remoteid
= -1; /* to be set when open confirmed */
4970 c
->localid
= alloc_channel_id();
4972 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
4974 add234(ssh_channels
, c
);
4980 * This is called when stdout/stderr (the entity to which
4981 * from_backend sends data) manages to clear some backlog.
4983 void ssh_unthrottle(int bufsize
)
4985 if (ssh_version
== 1) {
4986 if (bufsize
< SSH1_BUFFER_LIMIT
) {
4987 ssh1_stdout_throttling
= 0;
4991 if (mainchan
&& mainchan
->closes
== 0)
4992 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
4996 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
4998 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5001 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5004 if (ssh_version
== 1) {
5005 send_packet(SSH1_MSG_PORT_OPEN
,
5006 PKT_INT
, c
->localid
,
5009 //PKT_STR, <org:orgport>,
5012 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5013 ssh2_pkt_addstring("direct-tcpip");
5014 ssh2_pkt_adduint32(c
->localid
);
5015 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5016 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5017 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5018 ssh2_pkt_addstring(hostname
);
5019 ssh2_pkt_adduint32(port
);
5021 * We make up values for the originator data; partly it's
5022 * too much hassle to keep track, and partly I'm not
5023 * convinced the server should be told details like that
5024 * about my local network configuration.
5026 ssh2_pkt_addstring("client-side-connection");
5027 ssh2_pkt_adduint32(0);
5033 static Socket
ssh_socket(void)
5038 static int ssh_sendok(void)
5043 static int ssh_ldisc(int option
)
5045 if (option
== LD_ECHO
)
5047 if (option
== LD_EDIT
)
5052 Backend ssh_backend
= {