17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_PUBLICKEY 0x0010
110 #define SSH2_PKTCTX_PASSWORD 0x0020
111 #define SSH2_PKTCTX_KBDINTER 0x0040
112 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
114 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
130 static const char *const ssh2_disconnect_reasons
[] = {
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
149 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
154 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
157 * Various remote-bug flags.
159 #define BUG_CHOKES_ON_SSH1_IGNORE 1
160 #define BUG_SSH2_HMAC 2
161 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
162 #define BUG_CHOKES_ON_RSA 8
163 #define BUG_SSH2_RSA_PADDING 16
164 #define BUG_SSH2_DERIVEKEY 32
165 /* 64 was BUG_SSH2_DH_GEX, now spare */
166 #define BUG_SSH2_PK_SESSIONID 128
168 #define translate(x) if (type == x) return #x
169 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
170 static char *ssh1_pkt_type(int type
)
172 translate(SSH1_MSG_DISCONNECT
);
173 translate(SSH1_SMSG_PUBLIC_KEY
);
174 translate(SSH1_CMSG_SESSION_KEY
);
175 translate(SSH1_CMSG_USER
);
176 translate(SSH1_CMSG_AUTH_RSA
);
177 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
178 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
179 translate(SSH1_CMSG_AUTH_PASSWORD
);
180 translate(SSH1_CMSG_REQUEST_PTY
);
181 translate(SSH1_CMSG_WINDOW_SIZE
);
182 translate(SSH1_CMSG_EXEC_SHELL
);
183 translate(SSH1_CMSG_EXEC_CMD
);
184 translate(SSH1_SMSG_SUCCESS
);
185 translate(SSH1_SMSG_FAILURE
);
186 translate(SSH1_CMSG_STDIN_DATA
);
187 translate(SSH1_SMSG_STDOUT_DATA
);
188 translate(SSH1_SMSG_STDERR_DATA
);
189 translate(SSH1_CMSG_EOF
);
190 translate(SSH1_SMSG_EXIT_STATUS
);
191 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
192 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
193 translate(SSH1_MSG_CHANNEL_DATA
);
194 translate(SSH1_MSG_CHANNEL_CLOSE
);
195 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
196 translate(SSH1_SMSG_X11_OPEN
);
197 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
198 translate(SSH1_MSG_PORT_OPEN
);
199 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
200 translate(SSH1_SMSG_AGENT_OPEN
);
201 translate(SSH1_MSG_IGNORE
);
202 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
203 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
204 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
205 translate(SSH1_MSG_DEBUG
);
206 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
207 translate(SSH1_CMSG_AUTH_TIS
);
208 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
209 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
210 translate(SSH1_CMSG_AUTH_CCARD
);
211 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
212 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
215 static char *ssh2_pkt_type(int pkt_ctx
, int type
)
217 translate(SSH2_MSG_DISCONNECT
);
218 translate(SSH2_MSG_IGNORE
);
219 translate(SSH2_MSG_UNIMPLEMENTED
);
220 translate(SSH2_MSG_DEBUG
);
221 translate(SSH2_MSG_SERVICE_REQUEST
);
222 translate(SSH2_MSG_SERVICE_ACCEPT
);
223 translate(SSH2_MSG_KEXINIT
);
224 translate(SSH2_MSG_NEWKEYS
);
225 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP
);
226 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP
);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
231 translate(SSH2_MSG_USERAUTH_REQUEST
);
232 translate(SSH2_MSG_USERAUTH_FAILURE
);
233 translate(SSH2_MSG_USERAUTH_SUCCESS
);
234 translate(SSH2_MSG_USERAUTH_BANNER
);
235 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
239 translate(SSH2_MSG_GLOBAL_REQUEST
);
240 translate(SSH2_MSG_REQUEST_SUCCESS
);
241 translate(SSH2_MSG_REQUEST_FAILURE
);
242 translate(SSH2_MSG_CHANNEL_OPEN
);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
246 translate(SSH2_MSG_CHANNEL_DATA
);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
248 translate(SSH2_MSG_CHANNEL_EOF
);
249 translate(SSH2_MSG_CHANNEL_CLOSE
);
250 translate(SSH2_MSG_CHANNEL_REQUEST
);
251 translate(SSH2_MSG_CHANNEL_SUCCESS
);
252 translate(SSH2_MSG_CHANNEL_FAILURE
);
258 #define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
264 #define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
270 /* Enumeration values for fields in SSH-1 packets */
272 PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
,
273 /* These values are for communicating relevant semantics of
274 * fields to the packet logging code. */
275 PKTT_OTHER
, PKTT_PASSWORD
, PKTT_DATA
279 * Coroutine mechanics for the sillier bits of the code. If these
280 * macros look impenetrable to you, you might find it helpful to
283 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
285 * which explains the theory behind these macros.
287 * In particular, if you are getting `case expression not constant'
288 * errors when building with MS Visual Studio, this is because MS's
289 * Edit and Continue debugging feature causes their compiler to
290 * violate ANSI C. To disable Edit and Continue debugging:
292 * - right-click ssh.c in the FileView
294 * - select the C/C++ tab and the General category
295 * - under `Debug info:', select anything _other_ than `Program
296 * Database for Edit and Continue'.
298 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
301 if (!ssh->t) ssh->t = snew(struct t); \
303 #define crFinish(z) } *crLine = 0; return (z); }
304 #define crFinishV } *crLine = 0; return; }
305 #define crReturn(z) \
307 *crLine =__LINE__; return (z); case __LINE__:;\
311 *crLine=__LINE__; return; case __LINE__:;\
313 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
314 #define crStopV do{ *crLine = 0; return; }while(0)
315 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
316 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
318 typedef struct ssh_tag
*Ssh
;
321 static struct Packet
*ssh2_pkt_init(int pkt_type
);
322 static void ssh2_pkt_addbool(struct Packet
*, unsigned char value
);
323 static void ssh2_pkt_adduint32(struct Packet
*, unsigned long value
);
324 static void ssh2_pkt_addstring_start(struct Packet
*);
325 static void ssh2_pkt_addstring_str(struct Packet
*, char *data
);
326 static void ssh2_pkt_addstring_data(struct Packet
*, char *data
, int len
);
327 static void ssh2_pkt_addstring(struct Packet
*, char *data
);
328 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
329 static void ssh2_pkt_addmp(struct Packet
*, Bignum b
);
330 static int ssh2_pkt_construct(Ssh
, struct Packet
*);
331 static void ssh2_pkt_send(Ssh
, struct Packet
*);
332 static void ssh2_pkt_send_noqueue(Ssh
, struct Packet
*);
333 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
334 struct Packet
*pktin
);
335 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
336 struct Packet
*pktin
);
339 * Buffer management constants. There are several of these for
340 * various different purposes:
342 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
343 * on a local data stream before we throttle the whole SSH
344 * connection (in SSH1 only). Throttling the whole connection is
345 * pretty drastic so we set this high in the hope it won't
348 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
349 * on the SSH connection itself before we defensively throttle
350 * _all_ local data streams. This is pretty drastic too (though
351 * thankfully unlikely in SSH2 since the window mechanism should
352 * ensure that the server never has any need to throttle its end
353 * of the connection), so we set this high as well.
355 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
359 #define SSH1_BUFFER_LIMIT 32768
360 #define SSH_MAX_BACKLOG 32768
361 #define OUR_V2_WINSIZE 16384
363 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
365 static void *nullmac_make_context(void)
369 static void nullmac_free_context(void *handle
)
372 static void nullmac_key(void *handle
, unsigned char *key
)
375 static void nullmac_generate(void *handle
, unsigned char *blk
, int len
,
379 static int nullmac_verify(void *handle
, unsigned char *blk
, int len
,
384 const static struct ssh_mac ssh_mac_none
= {
385 nullmac_make_context
, nullmac_free_context
, nullmac_key
,
386 nullmac_generate
, nullmac_verify
, "none", 0
388 const static struct ssh_mac
*macs
[] = {
389 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
391 const static struct ssh_mac
*buggymacs
[] = {
392 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
395 static void *ssh_comp_none_init(void)
399 static void ssh_comp_none_cleanup(void *handle
)
402 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
403 unsigned char **outblock
, int *outlen
)
407 static int ssh_comp_none_disable(void *handle
)
411 const static struct ssh_compress ssh_comp_none
= {
413 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
414 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
415 ssh_comp_none_disable
, NULL
417 extern const struct ssh_compress ssh_zlib
;
418 const static struct ssh_compress
*compressions
[] = {
419 &ssh_zlib
, &ssh_comp_none
422 enum { /* channel types */
427 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
431 * 2-3-4 tree storing channels.
434 Ssh ssh
; /* pointer back to main context */
435 unsigned remoteid
, localid
;
438 * In SSH1, this value contains four bits:
440 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
441 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
442 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
443 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
445 * A channel is completely finished with when all four bits are set.
449 struct ssh1_data_channel
{
452 struct ssh2_data_channel
{
454 unsigned remwindow
, remmaxpkt
;
459 struct ssh_agent_channel
{
460 unsigned char *message
;
461 unsigned char msglen
[4];
462 unsigned lensofar
, totallen
;
464 struct ssh_x11_channel
{
467 struct ssh_pfd_channel
{
474 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
475 * 2 use this structure in different ways, reflecting SSH 2's
476 * altogether saner approach to port forwarding.
478 * In SSH 1, you arrange a remote forwarding by sending the server
479 * the remote port number, and the local destination host:port.
480 * When a connection comes in, the server sends you back that
481 * host:port pair, and you connect to it. This is a ready-made
482 * security hole if you're not on the ball: a malicious server
483 * could send you back _any_ host:port pair, so if you trustingly
484 * connect to the address it gives you then you've just opened the
485 * entire inside of your corporate network just by connecting
486 * through it to a dodgy SSH server. Hence, we must store a list of
487 * host:port pairs we _are_ trying to forward to, and reject a
488 * connection request from the server if it's not in the list.
490 * In SSH 2, each side of the connection minds its own business and
491 * doesn't send unnecessary information to the other. You arrange a
492 * remote forwarding by sending the server just the remote port
493 * number. When a connection comes in, the server tells you which
494 * of its ports was connected to; and _you_ have to remember what
495 * local host:port pair went with that port number.
497 * Hence, in SSH 1 this structure is indexed by destination
498 * host:port pair, whereas in SSH 2 it is indexed by source port.
500 struct ssh_portfwd
; /* forward declaration */
502 struct ssh_rportfwd
{
503 unsigned sport
, dport
;
506 struct ssh_portfwd
*pfrec
;
508 #define free_rportfwd(pf) ( \
509 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
512 * Separately to the rportfwd tree (which is for looking up port
513 * open requests from the server), a tree of _these_ structures is
514 * used to keep track of all the currently open port forwardings,
515 * so that we can reconfigure in mid-session if the user requests
519 enum { DESTROY
, KEEP
, CREATE
} status
;
521 unsigned sport
, dport
;
524 struct ssh_rportfwd
*remote
;
528 #define free_portfwd(pf) ( \
529 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
530 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
535 unsigned long sequence
;
540 long encrypted_len
; /* for SSH2 total-size counting */
543 * State associated with packet logging
547 struct logblank_t
*blanks
;
550 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
551 struct Packet
*pktin
);
552 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
553 struct Packet
*pktin
);
554 static void ssh1_protocol_setup(Ssh ssh
);
555 static void ssh2_protocol_setup(Ssh ssh
);
556 static void ssh_size(void *handle
, int width
, int height
);
557 static void ssh_special(void *handle
, Telnet_Special
);
558 static int ssh2_try_send(struct ssh_channel
*c
);
559 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
560 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
561 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
562 static int ssh_sendbuffer(void *handle
);
563 static void ssh_do_close(Ssh ssh
);
564 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
565 static int ssh2_pkt_getbool(struct Packet
*pkt
);
566 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
567 static void ssh2_timer(void *ctx
, long now
);
568 static int do_ssh2_transport(Ssh ssh
, unsigned char *in
, int inlen
,
569 struct Packet
*pktin
);
571 struct rdpkt1_state_tag
{
572 long len
, pad
, biglen
, to_read
;
573 unsigned long realcrc
, gotcrc
;
577 struct Packet
*pktin
;
580 struct rdpkt2_state_tag
{
581 long len
, pad
, payload
, packetlen
, maclen
;
584 unsigned long incoming_sequence
;
585 struct Packet
*pktin
;
588 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
589 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
591 struct queued_handler
;
592 struct queued_handler
{
594 chandler_fn_t handler
;
596 struct queued_handler
*next
;
600 const struct plug_function_table
*fn
;
601 /* the above field _must_ be first in the structure */
603 SHA_State exhash
, exhashbase
;
610 unsigned char session_key
[32];
612 int v1_remote_protoflags
;
613 int v1_local_protoflags
;
614 int agentfwd_enabled
;
617 const struct ssh_cipher
*cipher
;
620 const struct ssh2_cipher
*cscipher
, *sccipher
;
621 void *cs_cipher_ctx
, *sc_cipher_ctx
;
622 const struct ssh_mac
*csmac
, *scmac
;
623 void *cs_mac_ctx
, *sc_mac_ctx
;
624 const struct ssh_compress
*cscomp
, *sccomp
;
625 void *cs_comp_ctx
, *sc_comp_ctx
;
626 const struct ssh_kex
*kex
;
627 const struct ssh_signkey
*hostkey
;
628 unsigned char v2_session_id
[20];
634 int echoing
, editing
;
638 int ospeed
, ispeed
; /* temporaries */
639 int term_width
, term_height
;
641 tree234
*channels
; /* indexed by local id */
642 struct ssh_channel
*mainchan
; /* primary session channel */
645 tree234
*rportfwds
, *portfwds
;
649 SSH_STATE_BEFORE_SIZE
,
655 int size_needed
, eof_needed
;
657 struct Packet
**queue
;
658 int queuelen
, queuesize
;
660 unsigned char *deferred_send_data
;
661 int deferred_len
, deferred_size
;
664 * Gross hack: pscp will try to start SFTP but fall back to
665 * scp1 if that fails. This variable is the means by which
666 * scp.c can reach into the SSH code and find out which one it
672 * Used for username and password input.
674 char *userpass_input_buffer
;
675 int userpass_input_buflen
;
676 int userpass_input_bufpos
;
677 int userpass_input_echo
;
684 int v1_throttle_count
;
687 int v1_stdout_throttling
;
688 int v2_outgoing_sequence
;
690 int ssh1_rdpkt_crstate
;
691 int ssh2_rdpkt_crstate
;
692 int do_ssh_init_crstate
;
693 int ssh_gotdata_crstate
;
694 int do_ssh1_login_crstate
;
695 int do_ssh1_connection_crstate
;
696 int do_ssh2_transport_crstate
;
697 int do_ssh2_authconn_crstate
;
699 void *do_ssh_init_state
;
700 void *do_ssh1_login_state
;
701 void *do_ssh2_transport_state
;
702 void *do_ssh2_authconn_state
;
704 struct rdpkt1_state_tag rdpkt1_state
;
705 struct rdpkt2_state_tag rdpkt2_state
;
707 /* ssh1 and ssh2 use this for different things, but both use it */
708 int protocol_initial_phase_done
;
710 void (*protocol
) (Ssh ssh
, unsigned char *in
, int inlen
,
712 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
715 * We maintain a full _copy_ of a Config structure here, not
716 * merely a pointer to it. That way, when we're passed a new
717 * one for reconfiguration, we can check the differences and
718 * potentially reconfigure port forwardings etc in mid-session.
723 * Used to transfer data back from async agent callbacks.
725 void *agent_response
;
726 int agent_response_len
;
729 * Dispatch table for packet types that we may have to deal
732 handler_fn_t packet_dispatch
[256];
735 * Queues of one-off handler functions for success/failure
736 * indications from a request.
738 struct queued_handler
*qhead
, *qtail
;
741 * This module deals with sending keepalives.
746 * Track incoming and outgoing data sizes and time, for
749 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
750 unsigned long max_data_size
;
752 long next_rekey
, last_rekey
;
753 char *deferred_rekey_reason
; /* points to STATIC string; don't free */
756 #define logevent(s) logevent(ssh->frontend, s)
758 /* logevent, only printf-formatted. */
759 static void logeventf(Ssh ssh
, const char *fmt
, ...)
765 buf
= dupvprintf(fmt
, ap
);
771 #define bombout(msg) \
773 char *text = dupprintf msg; \
776 connection_fatal(ssh->frontend, "%s", text); \
780 /* Functions to leave bits out of the SSH packet log file. */
782 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
784 if (ssh
->cfg
.logomitpass
)
785 pkt
->logmode
= blanktype
;
788 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
790 if (ssh
->cfg
.logomitdata
)
791 pkt
->logmode
= blanktype
;
794 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
796 pkt
->logmode
= PKTLOG_EMIT
;
799 static int ssh_channelcmp(void *av
, void *bv
)
801 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
802 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
803 if (a
->localid
< b
->localid
)
805 if (a
->localid
> b
->localid
)
809 static int ssh_channelfind(void *av
, void *bv
)
811 unsigned *a
= (unsigned *) av
;
812 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
820 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
822 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
823 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
825 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
826 return i
< 0 ?
-1 : +1;
827 if (a
->dport
> b
->dport
)
829 if (a
->dport
< b
->dport
)
834 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
836 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
837 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
839 if (a
->sport
> b
->sport
)
841 if (a
->sport
< b
->sport
)
847 * Special form of strcmp which can cope with NULL inputs. NULL is
848 * defined to sort before even the empty string.
850 static int nullstrcmp(const char *a
, const char *b
)
852 if (a
== NULL
&& b
== NULL
)
861 static int ssh_portcmp(void *av
, void *bv
)
863 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
864 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
866 if (a
->type
> b
->type
)
868 if (a
->type
< b
->type
)
870 if (a
->addressfamily
> b
->addressfamily
)
872 if (a
->addressfamily
< b
->addressfamily
)
874 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
875 return i
< 0 ?
-1 : +1;
876 if (a
->sport
> b
->sport
)
878 if (a
->sport
< b
->sport
)
880 if (a
->type
!= 'D') {
881 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
882 return i
< 0 ?
-1 : +1;
883 if (a
->dport
> b
->dport
)
885 if (a
->dport
< b
->dport
)
891 static int alloc_channel_id(Ssh ssh
)
893 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
894 unsigned low
, high
, mid
;
896 struct ssh_channel
*c
;
899 * First-fit allocation of channel numbers: always pick the
900 * lowest unused one. To do this, binary-search using the
901 * counted B-tree to find the largest channel ID which is in a
902 * contiguous sequence from the beginning. (Precisely
903 * everything in that sequence must have ID equal to its tree
904 * index plus CHANNEL_NUMBER_OFFSET.)
906 tsize
= count234(ssh
->channels
);
910 while (high
- low
> 1) {
911 mid
= (high
+ low
) / 2;
912 c
= index234(ssh
->channels
, mid
);
913 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
914 low
= mid
; /* this one is fine */
916 high
= mid
; /* this one is past it */
919 * Now low points to either -1, or the tree index of the
920 * largest ID in the initial sequence.
923 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
924 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
926 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
929 static void c_write(Ssh ssh
, const char *buf
, int len
)
931 if ((flags
& FLAG_STDERR
)) {
933 for (i
= 0; i
< len
; i
++)
935 fputc(buf
[i
], stderr
);
938 from_backend(ssh
->frontend
, 1, buf
, len
);
941 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
944 for (i
= 0; i
< len
; i
++) {
946 c_write(ssh
, "\r\n", 2);
947 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
948 c_write(ssh
, buf
+ i
, 1);
952 static void c_write_str(Ssh ssh
, const char *buf
)
954 c_write(ssh
, buf
, strlen(buf
));
957 static void ssh_free_packet(struct Packet
*pkt
)
962 static struct Packet
*ssh_new_packet(void)
964 struct Packet
*pkt
= snew(struct Packet
);
968 pkt
->logmode
= PKTLOG_EMIT
;
976 * Collect incoming data in the incoming packet buffer.
977 * Decipher and verify the packet when it is completely read.
978 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
979 * Update the *data and *datalen variables.
980 * Return a Packet structure when a packet is completed.
982 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
984 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
986 crBegin(ssh
->ssh1_rdpkt_crstate
);
988 st
->pktin
= ssh_new_packet();
991 st
->pktin
->length
= 0;
993 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
994 while ((*datalen
) == 0)
996 st
->len
= (st
->len
<< 8) + **data
;
997 (*data
)++, (*datalen
)--;
1000 st
->pad
= 8 - (st
->len
% 8);
1001 st
->biglen
= st
->len
+ st
->pad
;
1002 st
->pktin
->length
= st
->len
- 5;
1004 if (st
->biglen
< 0) {
1005 bombout(("Extremely large packet length from server suggests"
1006 " data stream corruption"));
1007 ssh_free_packet(st
->pktin
);
1011 st
->pktin
->maxlen
= st
->biglen
;
1012 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1014 st
->to_read
= st
->biglen
;
1015 st
->p
= st
->pktin
->data
;
1016 while (st
->to_read
> 0) {
1017 st
->chunk
= st
->to_read
;
1018 while ((*datalen
) == 0)
1020 if (st
->chunk
> (*datalen
))
1021 st
->chunk
= (*datalen
);
1022 memcpy(st
->p
, *data
, st
->chunk
);
1024 *datalen
-= st
->chunk
;
1026 st
->to_read
-= st
->chunk
;
1029 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1030 st
->biglen
, NULL
)) {
1031 bombout(("Network attack (CRC compensation) detected!"));
1032 ssh_free_packet(st
->pktin
);
1037 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1039 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1040 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1041 if (st
->gotcrc
!= st
->realcrc
) {
1042 bombout(("Incorrect CRC received on packet"));
1043 ssh_free_packet(st
->pktin
);
1047 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1048 st
->pktin
->savedpos
= 0;
1050 if (ssh
->v1_compressing
) {
1051 unsigned char *decompblk
;
1053 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1054 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1055 &decompblk
, &decomplen
)) {
1056 bombout(("Zlib decompression encountered invalid data"));
1057 ssh_free_packet(st
->pktin
);
1061 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1062 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1063 st
->pktin
->data
= sresize(st
->pktin
->data
,
1064 st
->pktin
->maxlen
+ APIEXTRA
,
1066 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1069 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1071 st
->pktin
->length
= decomplen
- 1;
1074 st
->pktin
->type
= st
->pktin
->body
[-1];
1077 * Log incoming packet, possibly omitting sensitive fields.
1081 struct logblank_t blank
;
1082 if (ssh
->cfg
.logomitdata
) {
1083 int do_blank
= FALSE
, blank_prefix
= 0;
1084 /* "Session data" packets - omit the data field */
1085 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1086 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1087 do_blank
= TRUE
; blank_prefix
= 0;
1088 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1089 do_blank
= TRUE
; blank_prefix
= 4;
1092 blank
.offset
= blank_prefix
;
1093 blank
.len
= st
->pktin
->length
;
1094 blank
.type
= PKTLOG_OMIT
;
1098 log_packet(ssh
->logctx
,
1099 PKT_INCOMING
, st
->pktin
->type
,
1100 ssh1_pkt_type(st
->pktin
->type
),
1101 st
->pktin
->body
, st
->pktin
->length
,
1105 crFinish(st
->pktin
);
1108 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1110 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1112 crBegin(ssh
->ssh2_rdpkt_crstate
);
1114 st
->pktin
= ssh_new_packet();
1116 st
->pktin
->type
= 0;
1117 st
->pktin
->length
= 0;
1119 st
->cipherblk
= ssh
->sccipher
->blksize
;
1122 if (st
->cipherblk
< 8)
1125 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1128 * Acquire and decrypt the first block of the packet. This will
1129 * contain the length and padding details.
1131 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1132 while ((*datalen
) == 0)
1134 st
->pktin
->data
[st
->i
] = *(*data
)++;
1139 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1140 st
->pktin
->data
, st
->cipherblk
);
1143 * Now get the length and padding figures.
1145 st
->len
= GET_32BIT(st
->pktin
->data
);
1146 st
->pad
= st
->pktin
->data
[4];
1149 * _Completely_ silly lengths should be stomped on before they
1150 * do us any more damage.
1152 if (st
->len
< 0 || st
->pad
< 0 || st
->len
+ st
->pad
< 0) {
1153 bombout(("Incoming packet was garbled on decryption"));
1154 ssh_free_packet(st
->pktin
);
1159 * This enables us to deduce the payload length.
1161 st
->payload
= st
->len
- st
->pad
- 1;
1163 st
->pktin
->length
= st
->payload
+ 5;
1166 * So now we can work out the total packet length.
1168 st
->packetlen
= st
->len
+ 4;
1169 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1172 * Allocate memory for the rest of the packet.
1174 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1175 st
->pktin
->data
= sresize(st
->pktin
->data
,
1176 st
->pktin
->maxlen
+ APIEXTRA
,
1180 * Read and decrypt the remainder of the packet.
1182 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1184 while ((*datalen
) == 0)
1186 st
->pktin
->data
[st
->i
] = *(*data
)++;
1189 /* Decrypt everything _except_ the MAC. */
1191 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1192 st
->pktin
->data
+ st
->cipherblk
,
1193 st
->packetlen
- st
->cipherblk
);
1195 st
->pktin
->encrypted_len
= st
->packetlen
;
1201 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
, st
->len
+ 4,
1202 st
->incoming_sequence
)) {
1203 bombout(("Incorrect MAC received on packet"));
1204 ssh_free_packet(st
->pktin
);
1208 st
->pktin
->sequence
= st
->incoming_sequence
++;
1211 * Decompress packet payload.
1214 unsigned char *newpayload
;
1217 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1218 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1219 &newpayload
, &newlen
)) {
1220 if (st
->pktin
->maxlen
< newlen
+ 5) {
1221 st
->pktin
->maxlen
= newlen
+ 5;
1222 st
->pktin
->data
= sresize(st
->pktin
->data
,
1223 st
->pktin
->maxlen
+ APIEXTRA
,
1226 st
->pktin
->length
= 5 + newlen
;
1227 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1232 st
->pktin
->savedpos
= 6;
1233 st
->pktin
->body
= st
->pktin
->data
;
1234 st
->pktin
->type
= st
->pktin
->data
[5];
1237 * Log incoming packet, possibly omitting sensitive fields.
1241 struct logblank_t blank
;
1242 if (ssh
->cfg
.logomitdata
) {
1243 int do_blank
= FALSE
, blank_prefix
= 0;
1244 /* "Session data" packets - omit the data field */
1245 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1246 do_blank
= TRUE
; blank_prefix
= 4;
1247 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1248 do_blank
= TRUE
; blank_prefix
= 8;
1251 blank
.offset
= blank_prefix
;
1252 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1253 blank
.type
= PKTLOG_OMIT
;
1257 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1258 ssh2_pkt_type(ssh
->pkt_ctx
, st
->pktin
->type
),
1259 st
->pktin
->data
+6, st
->pktin
->length
-6,
1263 crFinish(st
->pktin
);
1266 static void ssh1_pktout_size(struct Packet
*pkt
, int len
)
1270 len
+= 5; /* type and CRC */
1271 pad
= 8 - (len
% 8);
1274 pkt
->length
= len
- 5;
1275 if (pkt
->maxlen
< biglen
) {
1276 pkt
->maxlen
= biglen
;
1277 pkt
->data
= sresize(pkt
->data
, biglen
+ 4 + APIEXTRA
, unsigned char);
1279 pkt
->body
= pkt
->data
+ 4 + pad
+ 1;
1282 static struct Packet
*s_wrpkt_start(int type
, int len
)
1284 struct Packet
*pkt
= ssh_new_packet();
1285 ssh1_pktout_size(pkt
, len
);
1287 /* Initialise log omission state */
1293 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
)
1299 * XXX various versions of SC (including 8.8.4) screw up the
1300 * register allocation in this function and use the same register
1301 * (D6) for len and as a temporary, with predictable results. The
1302 * following sledgehammer prevents this.
1308 pkt
->body
[-1] = pkt
->type
;
1311 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->type
,
1312 ssh1_pkt_type(pkt
->type
),
1313 pkt
->body
, pkt
->length
,
1314 pkt
->nblanks
, pkt
->blanks
);
1315 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1318 if (ssh
->v1_compressing
) {
1319 unsigned char *compblk
;
1321 zlib_compress_block(ssh
->cs_comp_ctx
,
1322 pkt
->body
- 1, pkt
->length
+ 1,
1323 &compblk
, &complen
);
1324 ssh1_pktout_size(pkt
, complen
- 1);
1325 memcpy(pkt
->body
- 1, compblk
, complen
);
1329 len
= pkt
->length
+ 5; /* type and CRC */
1330 pad
= 8 - (len
% 8);
1333 for (i
= 0; i
< pad
; i
++)
1334 pkt
->data
[i
+ 4] = random_byte();
1335 crc
= crc32_compute(pkt
->data
+ 4, biglen
- 4);
1336 PUT_32BIT(pkt
->data
+ biglen
, crc
);
1337 PUT_32BIT(pkt
->data
, len
);
1340 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
, pkt
->data
+ 4, biglen
);
1345 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1348 len
= s_wrpkt_prepare(ssh
, pkt
);
1349 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1350 if (backlog
> SSH_MAX_BACKLOG
)
1351 ssh_throttle_all(ssh
, 1, backlog
);
1354 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1357 len
= s_wrpkt_prepare(ssh
, pkt
);
1358 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1359 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1360 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1364 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1365 ssh
->deferred_len
+= len
;
1369 * Construct a packet with the specified contents.
1371 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
,
1372 va_list ap1
, va_list ap2
)
1374 unsigned char *p
, *argp
, argchar
;
1375 unsigned long argint
;
1376 int pktlen
, argtype
, arglen
;
1381 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1384 (void) va_arg(ap1
, int);
1388 (void) va_arg(ap1
, int);
1392 (void) va_arg(ap1
, unsigned char *);
1393 arglen
= va_arg(ap1
, int);
1397 argp
= va_arg(ap1
, unsigned char *);
1398 arglen
= strlen((char *)argp
);
1399 pktlen
+= 4 + arglen
;
1402 bn
= va_arg(ap1
, Bignum
);
1403 pktlen
+= ssh1_bignum_length(bn
);
1408 /* ignore this pass */
1415 pkt
= s_wrpkt_start(pkttype
, pktlen
);
1418 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1419 int offset
= p
- pkt
->body
, len
= 0;
1421 /* Actual fields in the packet */
1423 argint
= va_arg(ap2
, int);
1424 PUT_32BIT(p
, argint
);
1428 argchar
= (unsigned char) va_arg(ap2
, int);
1433 argp
= va_arg(ap2
, unsigned char *);
1434 arglen
= va_arg(ap2
, int);
1435 memcpy(p
, argp
, arglen
);
1439 argp
= va_arg(ap2
, unsigned char *);
1440 arglen
= strlen((char *)argp
);
1441 PUT_32BIT(p
, arglen
);
1442 memcpy(p
+ 4, argp
, arglen
);
1446 bn
= va_arg(ap2
, Bignum
);
1447 len
= ssh1_write_bignum(p
, bn
);
1449 /* Tokens for modifications to packet logging */
1451 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1454 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1457 end_log_omission(ssh
, pkt
);
1461 /* Deal with logfile omission, if required. */
1462 if (len
&& (pkt
->logmode
!= PKTLOG_EMIT
)) {
1464 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
,
1466 pkt
->blanks
[pkt
->nblanks
-1].offset
= offset
;
1467 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1468 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1475 static void send_packet(Ssh ssh
, int pkttype
, ...)
1479 va_start(ap1
, pkttype
);
1480 va_start(ap2
, pkttype
);
1481 pkt
= construct_packet(ssh
, pkttype
, ap1
, ap2
);
1485 ssh_free_packet(pkt
);
1488 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1492 va_start(ap1
, pkttype
);
1493 va_start(ap2
, pkttype
);
1494 pkt
= construct_packet(ssh
, pkttype
, ap1
, ap2
);
1497 s_wrpkt_defer(ssh
, pkt
);
1498 ssh_free_packet(pkt
);
1501 static int ssh_versioncmp(char *a
, char *b
)
1504 unsigned long av
, bv
;
1506 av
= strtoul(a
, &ae
, 10);
1507 bv
= strtoul(b
, &be
, 10);
1509 return (av
< bv ?
-1 : +1);
1514 av
= strtoul(ae
, &ae
, 10);
1515 bv
= strtoul(be
, &be
, 10);
1517 return (av
< bv ?
-1 : +1);
1522 * Utility routines for putting an SSH-protocol `string' and
1523 * `uint32' into a SHA state.
1526 static void sha_string(SHA_State
* s
, void *str
, int len
)
1528 unsigned char lenblk
[4];
1529 PUT_32BIT(lenblk
, len
);
1530 SHA_Bytes(s
, lenblk
, 4);
1531 SHA_Bytes(s
, str
, len
);
1534 static void sha_uint32(SHA_State
* s
, unsigned i
)
1536 unsigned char intblk
[4];
1537 PUT_32BIT(intblk
, i
);
1538 SHA_Bytes(s
, intblk
, 4);
1542 * SSH2 packet construction functions.
1544 static void ssh2_pkt_ensure(struct Packet
*pkt
, int length
)
1546 if (pkt
->maxlen
< length
) {
1547 pkt
->maxlen
= length
+ 256;
1548 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1551 static void ssh2_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1553 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1555 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1556 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
- 6;
1557 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1558 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1561 ssh2_pkt_ensure(pkt
, pkt
->length
);
1562 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1564 static void ssh2_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1566 ssh2_pkt_adddata(pkt
, &byte
, 1);
1568 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1570 struct Packet
*pkt
= ssh_new_packet();
1572 ssh2_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1575 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1577 ssh2_pkt_adddata(pkt
, &value
, 1);
1579 static void ssh2_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1582 PUT_32BIT(x
, value
);
1583 ssh2_pkt_adddata(pkt
, x
, 4);
1585 static void ssh2_pkt_addstring_start(struct Packet
*pkt
)
1587 ssh2_pkt_adduint32(pkt
, 0);
1588 pkt
->savedpos
= pkt
->length
;
1590 static void ssh2_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1592 ssh2_pkt_adddata(pkt
, data
, strlen(data
));
1593 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1595 static void ssh2_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1597 ssh2_pkt_adddata(pkt
, data
, len
);
1598 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1600 static void ssh2_pkt_addstring(struct Packet
*pkt
, char *data
)
1602 ssh2_pkt_addstring_start(pkt
);
1603 ssh2_pkt_addstring_str(pkt
, data
);
1605 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1608 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1609 p
= snewn(n
+ 1, unsigned char);
1611 fatalbox("out of memory");
1613 for (i
= 1; i
<= n
; i
++)
1614 p
[i
] = bignum_byte(b
, n
- i
);
1616 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1618 memmove(p
, p
+ i
, n
+ 1 - i
);
1622 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1626 p
= ssh2_mpint_fmt(b
, &len
);
1627 ssh2_pkt_addstring_start(pkt
);
1628 ssh2_pkt_addstring_data(pkt
, (char *)p
, len
);
1633 * Construct an SSH2 final-form packet: compress it, encrypt it,
1634 * put the MAC on it. Final packet, ready to be sent, is stored in
1635 * pkt->data. Total length is returned.
1637 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1639 int cipherblk
, maclen
, padding
, i
;
1642 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1643 ssh2_pkt_type(ssh
->pkt_ctx
, pkt
->data
[5]),
1644 pkt
->data
+ 6, pkt
->length
- 6,
1645 pkt
->nblanks
, pkt
->blanks
);
1646 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1650 * Compress packet payload.
1653 unsigned char *newpayload
;
1656 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1658 &newpayload
, &newlen
)) {
1660 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1666 * Add padding. At least four bytes, and must also bring total
1667 * length (minus MAC) up to a multiple of the block size.
1669 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1670 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1673 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1674 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1675 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1676 pkt
->data
[4] = padding
;
1677 for (i
= 0; i
< padding
; i
++)
1678 pkt
->data
[pkt
->length
+ i
] = random_byte();
1679 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1681 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1682 pkt
->length
+ padding
,
1683 ssh
->v2_outgoing_sequence
);
1684 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1687 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1688 pkt
->data
, pkt
->length
+ padding
);
1690 pkt
->encrypted_len
= pkt
->length
+ padding
;
1692 /* Ready-to-send packet starts at pkt->data. We return length. */
1693 return pkt
->length
+ padding
+ maclen
;
1697 * Routines called from the main SSH code to send packets. There
1698 * are quite a few of these, because we have two separate
1699 * mechanisms for delaying the sending of packets:
1701 * - In order to send an IGNORE message and a password message in
1702 * a single fixed-length blob, we require the ability to
1703 * concatenate the encrypted forms of those two packets _into_ a
1704 * single blob and then pass it to our <network.h> transport
1705 * layer in one go. Hence, there's a deferment mechanism which
1706 * works after packet encryption.
1708 * - In order to avoid sending any connection-layer messages
1709 * during repeat key exchange, we have to queue up any such
1710 * outgoing messages _before_ they are encrypted (and in
1711 * particular before they're allocated sequence numbers), and
1712 * then send them once we've finished.
1714 * I call these mechanisms `defer' and `queue' respectively, so as
1715 * to distinguish them reasonably easily.
1717 * The functions send_noqueue() and defer_noqueue() free the packet
1718 * structure they are passed. Every outgoing packet goes through
1719 * precisely one of these functions in its life; packets passed to
1720 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1721 * these or get queued, and then when the queue is later emptied
1722 * the packets are all passed to defer_noqueue().
1726 * Send an SSH2 packet immediately, without queuing or deferring.
1728 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
1732 len
= ssh2_pkt_construct(ssh
, pkt
);
1733 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1734 if (backlog
> SSH_MAX_BACKLOG
)
1735 ssh_throttle_all(ssh
, 1, backlog
);
1737 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
1738 if (!ssh
->kex_in_progress
&&
1739 ssh
->max_data_size
!= 0 &&
1740 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1741 do_ssh2_transport(ssh
, "Initiating key re-exchange "
1742 "(too much data sent)", -1, NULL
);
1744 ssh_free_packet(pkt
);
1748 * Defer an SSH2 packet.
1750 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
)
1752 int len
= ssh2_pkt_construct(ssh
, pkt
);
1753 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1754 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1755 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1759 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1760 ssh
->deferred_len
+= len
;
1761 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
1762 ssh_free_packet(pkt
);
1766 * Queue an SSH2 packet.
1768 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
1770 assert(ssh
->queueing
);
1772 if (ssh
->queuelen
>= ssh
->queuesize
) {
1773 ssh
->queuesize
= ssh
->queuelen
+ 32;
1774 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
1777 ssh
->queue
[ssh
->queuelen
++] = pkt
;
1781 * Either queue or send a packet, depending on whether queueing is
1784 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
1787 ssh2_pkt_queue(ssh
, pkt
);
1789 ssh2_pkt_send_noqueue(ssh
, pkt
);
1793 * Either queue or defer a packet, depending on whether queueing is
1796 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
1799 ssh2_pkt_queue(ssh
, pkt
);
1801 ssh2_pkt_defer_noqueue(ssh
, pkt
);
1805 * Send the whole deferred data block constructed by
1806 * ssh2_pkt_defer() or SSH1's defer_packet().
1808 * The expected use of the defer mechanism is that you call
1809 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1810 * not currently queueing, this simply sets up deferred_send_data
1811 * and then sends it. If we _are_ currently queueing, the calls to
1812 * ssh2_pkt_defer() put the deferred packets on to the queue
1813 * instead, and therefore ssh_pkt_defersend() has no deferred data
1814 * to send. Hence, there's no need to make it conditional on
1817 static void ssh_pkt_defersend(Ssh ssh
)
1820 backlog
= sk_write(ssh
->s
, (char *)ssh
->deferred_send_data
,
1822 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1823 sfree(ssh
->deferred_send_data
);
1824 ssh
->deferred_send_data
= NULL
;
1825 if (backlog
> SSH_MAX_BACKLOG
)
1826 ssh_throttle_all(ssh
, 1, backlog
);
1828 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
1829 if (!ssh
->kex_in_progress
&&
1830 ssh
->max_data_size
!= 0 &&
1831 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1832 do_ssh2_transport(ssh
, "Initiating key re-exchange "
1833 "(too much data sent)", -1, NULL
);
1834 ssh
->deferred_data_size
= 0;
1838 * Send all queued SSH2 packets. We send them by means of
1839 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1840 * packets that needed to be lumped together.
1842 static void ssh2_pkt_queuesend(Ssh ssh
)
1846 assert(!ssh
->queueing
);
1848 for (i
= 0; i
< ssh
->queuelen
; i
++)
1849 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
]);
1852 ssh_pkt_defersend(ssh
);
1856 void bndebug(char *string
, Bignum b
)
1860 p
= ssh2_mpint_fmt(b
, &len
);
1861 debug(("%s", string
));
1862 for (i
= 0; i
< len
; i
++)
1863 debug((" %02x", p
[i
]));
1869 static void sha_mpint(SHA_State
* s
, Bignum b
)
1873 p
= ssh2_mpint_fmt(b
, &len
);
1874 sha_string(s
, p
, len
);
1879 * Packet decode functions for both SSH1 and SSH2.
1881 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
1883 unsigned long value
;
1884 if (pkt
->length
- pkt
->savedpos
< 4)
1885 return 0; /* arrgh, no way to decline (FIXME?) */
1886 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1890 static int ssh2_pkt_getbool(struct Packet
*pkt
)
1892 unsigned long value
;
1893 if (pkt
->length
- pkt
->savedpos
< 1)
1894 return 0; /* arrgh, no way to decline (FIXME?) */
1895 value
= pkt
->body
[pkt
->savedpos
] != 0;
1899 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
1904 if (pkt
->length
- pkt
->savedpos
< 4)
1906 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1911 if (pkt
->length
- pkt
->savedpos
< *length
)
1913 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
1914 pkt
->savedpos
+= *length
;
1916 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
1918 if (pkt
->length
- pkt
->savedpos
< length
)
1920 pkt
->savedpos
+= length
;
1921 return pkt
->body
+ (pkt
->savedpos
- length
);
1923 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
1924 unsigned char **keystr
)
1928 j
= makekey(pkt
->body
+ pkt
->savedpos
,
1929 pkt
->length
- pkt
->savedpos
,
1936 assert(pkt
->savedpos
< pkt
->length
);
1940 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
1945 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
1946 pkt
->length
- pkt
->savedpos
, &b
);
1954 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
1960 ssh_pkt_getstring(pkt
, &p
, &length
);
1965 b
= bignum_from_bytes((unsigned char *)p
, length
);
1970 * Helper function to add an SSH2 signature blob to a packet.
1971 * Expects to be shown the public key blob as well as the signature
1972 * blob. Normally works just like ssh2_pkt_addstring, but will
1973 * fiddle with the signature packet if necessary for
1974 * BUG_SSH2_RSA_PADDING.
1976 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
1977 void *pkblob_v
, int pkblob_len
,
1978 void *sigblob_v
, int sigblob_len
)
1980 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
1981 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
1983 /* dmemdump(pkblob, pkblob_len); */
1984 /* dmemdump(sigblob, sigblob_len); */
1987 * See if this is in fact an ssh-rsa signature and a buggy
1988 * server; otherwise we can just do this the easy way.
1990 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
1991 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
1992 int pos
, len
, siglen
;
1995 * Find the byte length of the modulus.
1998 pos
= 4+7; /* skip over "ssh-rsa" */
1999 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
2000 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
2001 pos
+= 4; /* find modulus itself */
2002 while (len
> 0 && pkblob
[pos
] == 0)
2004 /* debug(("modulus length is %d\n", len)); */
2007 * Now find the signature integer.
2009 pos
= 4+7; /* skip over "ssh-rsa" */
2010 siglen
= GET_32BIT(sigblob
+pos
);
2011 /* debug(("signature length is %d\n", siglen)); */
2013 if (len
!= siglen
) {
2014 unsigned char newlen
[4];
2015 ssh2_pkt_addstring_start(pkt
);
2016 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
2017 /* dmemdump(sigblob, pos); */
2018 pos
+= 4; /* point to start of actual sig */
2019 PUT_32BIT(newlen
, len
);
2020 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
2021 /* dmemdump(newlen, 4); */
2023 while (len
-- > siglen
) {
2024 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
2025 /* dmemdump(newlen, 1); */
2027 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2028 /* dmemdump(sigblob+pos, siglen); */
2032 /* Otherwise fall through and do it the easy way. */
2035 ssh2_pkt_addstring_start(pkt
);
2036 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2040 * Examine the remote side's version string and compare it against
2041 * a list of known buggy implementations.
2043 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2045 char *imp
; /* pointer to implementation part */
2047 imp
+= strcspn(imp
, "-");
2049 imp
+= strcspn(imp
, "-");
2052 ssh
->remote_bugs
= 0;
2054 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
2055 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
2056 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2057 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2058 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2059 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2061 * These versions don't support SSH1_MSG_IGNORE, so we have
2062 * to use a different defence against password length
2065 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2066 logevent("We believe remote version has SSH1 ignore bug");
2069 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
2070 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
2071 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2073 * These versions need a plain password sent; they can't
2074 * handle having a null and a random length of data after
2077 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2078 logevent("We believe remote version needs a plain SSH1 password");
2081 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
2082 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
2083 (!strcmp(imp
, "Cisco-1.25")))) {
2085 * These versions apparently have no clue whatever about
2086 * RSA authentication and will panic and die if they see
2087 * an AUTH_RSA message.
2089 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2090 logevent("We believe remote version can't handle RSA authentication");
2093 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
2094 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
2095 !wc_match("* VShell", imp
) &&
2096 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2097 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2098 wc_match("2.1 *", imp
)))) {
2100 * These versions have the HMAC bug.
2102 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2103 logevent("We believe remote version has SSH2 HMAC bug");
2106 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
2107 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
2108 !wc_match("* VShell", imp
) &&
2109 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2111 * These versions have the key-derivation bug (failing to
2112 * include the literal shared secret in the hashes that
2113 * generate the keys).
2115 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2116 logevent("We believe remote version has SSH2 key-derivation bug");
2119 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2120 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2121 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2122 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2124 * These versions have the SSH2 RSA padding bug.
2126 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2127 logevent("We believe remote version has SSH2 RSA padding bug");
2130 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2131 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2132 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2134 * These versions have the SSH2 session-ID bug in
2135 * public-key authentication.
2137 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2138 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2143 * The `software version' part of an SSH version string is required
2144 * to contain no spaces or minus signs.
2146 static void ssh_fix_verstring(char *str
)
2148 /* Eat "SSH-<protoversion>-". */
2149 assert(*str
== 'S'); str
++;
2150 assert(*str
== 'S'); str
++;
2151 assert(*str
== 'H'); str
++;
2152 assert(*str
== '-'); str
++;
2153 while (*str
&& *str
!= '-') str
++;
2154 assert(*str
== '-'); str
++;
2156 /* Convert minus signs and spaces in the remaining string into
2159 if (*str
== '-' || *str
== ' ')
2165 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2167 struct do_ssh_init_state
{
2175 crState(do_ssh_init_state
);
2177 crBegin(ssh
->do_ssh_init_crstate
);
2179 /* Search for the string "SSH-" in the input. */
2182 static const int transS
[] = { 1, 2, 2, 1 };
2183 static const int transH
[] = { 0, 0, 3, 0 };
2184 static const int transminus
[] = { 0, 0, 0, -1 };
2186 s
->i
= transS
[s
->i
];
2188 s
->i
= transH
[s
->i
];
2190 s
->i
= transminus
[s
->i
];
2195 crReturn(1); /* get another character */
2199 s
->vstring
= snewn(s
->vstrsize
, char);
2200 strcpy(s
->vstring
, "SSH-");
2204 crReturn(1); /* get another char */
2205 if (s
->vslen
>= s
->vstrsize
- 1) {
2207 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2209 s
->vstring
[s
->vslen
++] = c
;
2212 s
->version
[s
->i
] = '\0';
2214 } else if (s
->i
< sizeof(s
->version
) - 1)
2215 s
->version
[s
->i
++] = c
;
2216 } else if (c
== '\012')
2220 ssh
->agentfwd_enabled
= FALSE
;
2221 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2223 s
->vstring
[s
->vslen
] = 0;
2224 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2227 vlog
= snewn(20 + s
->vslen
, char);
2228 sprintf(vlog
, "Server version: %s", s
->vstring
);
2232 ssh_detect_bugs(ssh
, s
->vstring
);
2235 * Decide which SSH protocol version to support.
2238 /* Anything strictly below "2.0" means protocol 1 is supported. */
2239 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2240 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2241 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2243 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2244 bombout(("SSH protocol version 1 required by user but not provided by server"));
2247 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2248 bombout(("SSH protocol version 2 required by user but not provided by server"));
2255 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
)) {
2257 * Construct a v2 version string.
2259 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2263 * Construct a v1 version string.
2265 verstring
= dupprintf("SSH-%s-%s\012",
2266 (ssh_versioncmp(s
->version
, "1.5") <= 0 ?
2267 s
->version
: "1.5"),
2272 ssh_fix_verstring(verstring
);
2274 if (ssh
->version
== 2) {
2276 * Hash our version string and their version string.
2278 SHA_Init(&ssh
->exhashbase
);
2279 sha_string(&ssh
->exhashbase
, verstring
,
2280 strcspn(verstring
, "\015\012"));
2281 sha_string(&ssh
->exhashbase
, s
->vstring
,
2282 strcspn(s
->vstring
, "\015\012"));
2285 * Initialise SSHv2 protocol.
2287 ssh
->protocol
= ssh2_protocol
;
2288 ssh2_protocol_setup(ssh
);
2289 ssh
->s_rdpkt
= ssh2_rdpkt
;
2292 * Initialise SSHv1 protocol.
2294 ssh
->protocol
= ssh1_protocol
;
2295 ssh1_protocol_setup(ssh
);
2296 ssh
->s_rdpkt
= ssh1_rdpkt
;
2298 logeventf(ssh
, "We claim version: %.*s",
2299 strcspn(verstring
, "\015\012"), verstring
);
2300 sk_write(ssh
->s
, verstring
, strlen(verstring
));
2304 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2306 update_specials_menu(ssh
->frontend
);
2307 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2308 ssh
->pinger
= pinger_new(&ssh
->cfg
, &ssh_backend
, ssh
);
2315 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2317 crBegin(ssh
->ssh_gotdata_crstate
);
2320 * To begin with, feed the characters one by one to the
2321 * protocol initialisation / selection function do_ssh_init().
2322 * When that returns 0, we're done with the initial greeting
2323 * exchange and can move on to packet discipline.
2326 int ret
; /* need not be kept across crReturn */
2328 crReturnV
; /* more data please */
2329 ret
= do_ssh_init(ssh
, *data
);
2337 * We emerge from that loop when the initial negotiation is
2338 * over and we have selected an s_rdpkt function. Now pass
2339 * everything to s_rdpkt, and then pass the resulting packets
2340 * to the proper protocol handler.
2345 while (datalen
> 0) {
2346 struct Packet
*pktin
= ssh
->s_rdpkt(ssh
, &data
, &datalen
);
2348 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2349 ssh_free_packet(pktin
);
2351 if (ssh
->state
== SSH_STATE_CLOSED
)
2359 static void ssh_do_close(Ssh ssh
)
2362 struct ssh_channel
*c
;
2364 ssh
->state
= SSH_STATE_CLOSED
;
2368 notify_remote_exit(ssh
->frontend
);
2371 * Now we must shut down any port and X forwardings going
2372 * through this connection.
2374 if (ssh
->channels
) {
2375 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2378 x11_close(c
->u
.x11
.s
);
2381 pfd_close(c
->u
.pfd
.s
);
2384 del234(ssh
->channels
, c
);
2385 if (ssh
->version
== 2)
2386 bufchain_clear(&c
->v
.v2
.outbuffer
);
2392 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2395 Ssh ssh
= (Ssh
) plug
;
2398 /* A socket error has occurred. */
2399 logevent(error_msg
);
2400 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2402 /* Otherwise, the remote side closed the connection normally. */
2407 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2409 Ssh ssh
= (Ssh
) plug
;
2410 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2411 if (ssh
->state
== SSH_STATE_CLOSED
) {
2418 static void ssh_sent(Plug plug
, int bufsize
)
2420 Ssh ssh
= (Ssh
) plug
;
2422 * If the send backlog on the SSH socket itself clears, we
2423 * should unthrottle the whole world if it was throttled.
2425 if (bufsize
< SSH_MAX_BACKLOG
)
2426 ssh_throttle_all(ssh
, 0, bufsize
);
2430 * Connect to specified host and port.
2431 * Returns an error message, or NULL on success.
2432 * Also places the canonical host name into `realhost'. It must be
2433 * freed by the caller.
2435 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2436 char **realhost
, int nodelay
, int keepalive
)
2438 static const struct plug_function_table fn_table
= {
2448 ssh
->savedhost
= snewn(1 + strlen(host
), char);
2449 if (!ssh
->savedhost
)
2450 fatalbox("Out of memory");
2451 strcpy(ssh
->savedhost
, host
);
2454 port
= 22; /* default ssh port */
2455 ssh
->savedport
= port
;
2460 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
2461 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
2462 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
2463 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
,
2464 ssh
->cfg
.addressfamily
);
2465 if ((err
= sk_addr_error(addr
)) != NULL
) {
2475 sk_getaddr(addr
, addrbuf
, 100);
2476 logeventf(ssh
, "Connecting to %s port %d", addrbuf
, port
);
2478 ssh
->fn
= &fn_table
;
2479 ssh
->s
= new_connection(addr
, *realhost
, port
,
2480 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
2481 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2483 notify_remote_exit(ssh
->frontend
);
2491 * Throttle or unthrottle the SSH connection.
2493 static void ssh1_throttle(Ssh ssh
, int adjust
)
2495 int old_count
= ssh
->v1_throttle_count
;
2496 ssh
->v1_throttle_count
+= adjust
;
2497 assert(ssh
->v1_throttle_count
>= 0);
2498 if (ssh
->v1_throttle_count
&& !old_count
) {
2499 sk_set_frozen(ssh
->s
, 1);
2500 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2501 sk_set_frozen(ssh
->s
, 0);
2506 * Throttle or unthrottle _all_ local data streams (for when sends
2507 * on the SSH connection itself back up).
2509 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2512 struct ssh_channel
*c
;
2514 if (enable
== ssh
->throttled_all
)
2516 ssh
->throttled_all
= enable
;
2517 ssh
->overall_bufsize
= bufsize
;
2520 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2522 case CHAN_MAINSESSION
:
2524 * This is treated separately, outside the switch.
2528 x11_override_throttle(c
->u
.x11
.s
, enable
);
2531 /* Agent channels require no buffer management. */
2534 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
2541 * Username and password input, abstracted off into routines
2542 * reusable in several places - even between SSH1 and SSH2.
2545 /* Set up a username or password input loop on a given buffer. */
2546 static void setup_userpass_input(Ssh ssh
, char *buffer
, int buflen
, int echo
)
2548 ssh
->userpass_input_buffer
= buffer
;
2549 ssh
->userpass_input_buflen
= buflen
;
2550 ssh
->userpass_input_bufpos
= 0;
2551 ssh
->userpass_input_echo
= echo
;
2555 * Process some terminal data in the course of username/password
2556 * input. Returns >0 for success (line of input returned in
2557 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2558 * for inconclusive (keep waiting for more input please).
2560 static int process_userpass_input(Ssh ssh
, unsigned char *in
, int inlen
)
2565 switch (c
= *in
++) {
2568 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
] = 0;
2569 ssh
->userpass_input_buffer
[ssh
->userpass_input_buflen
-1] = 0;
2574 if (ssh
->userpass_input_bufpos
> 0) {
2575 if (ssh
->userpass_input_echo
)
2576 c_write_str(ssh
, "\b \b");
2577 ssh
->userpass_input_bufpos
--;
2582 while (ssh
->userpass_input_bufpos
> 0) {
2583 if (ssh
->userpass_input_echo
)
2584 c_write_str(ssh
, "\b \b");
2585 ssh
->userpass_input_bufpos
--;
2594 * This simplistic check for printability is disabled
2595 * when we're doing password input, because some people
2596 * have control characters in their passwords.o
2598 if ((!ssh
->userpass_input_echo
||
2599 (c
>= ' ' && c
<= '~') ||
2600 ((unsigned char) c
>= 160))
2601 && ssh
->userpass_input_bufpos
< ssh
->userpass_input_buflen
-1) {
2602 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
++] = c
;
2603 if (ssh
->userpass_input_echo
)
2604 c_write(ssh
, &c
, 1);
2612 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
2614 Ssh ssh
= (Ssh
) sshv
;
2616 ssh
->agent_response
= reply
;
2617 ssh
->agent_response_len
= replylen
;
2619 if (ssh
->version
== 1)
2620 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2622 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
2625 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
2627 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
2629 void *sentreply
= reply
;
2632 /* Fake SSH_AGENT_FAILURE. */
2633 sentreply
= "\0\0\0\1\5";
2636 if (ssh
->version
== 2) {
2637 ssh2_add_channel_data(c
, sentreply
, replylen
);
2640 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
2641 PKT_INT
, c
->remoteid
,
2644 PKT_DATA
, sentreply
, replylen
,
2653 * Handle the key exchange and user authentication phases.
2655 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
2656 struct Packet
*pktin
)
2659 unsigned char cookie
[8], *ptr
;
2660 struct RSAKey servkey
, hostkey
;
2661 struct MD5Context md5c
;
2662 struct do_ssh1_login_state
{
2664 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2665 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2666 int tried_publickey
, tried_agent
;
2667 int tis_auth_refused
, ccard_auth_refused
;
2668 unsigned char session_id
[16];
2671 void *publickey_blob
;
2672 int publickey_bloblen
;
2678 unsigned char request
[5], *response
, *p
;
2687 crState(do_ssh1_login_state
);
2689 crBegin(ssh
->do_ssh1_login_crstate
);
2694 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
2695 bombout(("Public key packet not received"));
2699 logevent("Received public keys");
2701 ptr
= ssh_pkt_getdata(pktin
, 8);
2703 bombout(("SSH1 public key packet stopped before random cookie"));
2706 memcpy(cookie
, ptr
, 8);
2708 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
2709 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
2710 bombout(("Failed to read SSH1 public keys from public key packet"));
2715 * Log the host key fingerprint.
2719 logevent("Host key fingerprint is:");
2720 strcpy(logmsg
, " ");
2721 hostkey
.comment
= NULL
;
2722 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2723 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2727 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
2728 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
2729 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
2731 ssh
->v1_local_protoflags
=
2732 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2733 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2736 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
2737 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
2738 MD5Update(&md5c
, cookie
, 8);
2739 MD5Final(s
->session_id
, &md5c
);
2741 for (i
= 0; i
< 32; i
++)
2742 ssh
->session_key
[i
] = random_byte();
2745 * Verify that the `bits' and `bytes' parameters match.
2747 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
2748 servkey
.bits
> servkey
.bytes
* 8) {
2749 bombout(("SSH1 public keys were badly formatted"));
2753 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2755 s
->rsabuf
= snewn(s
->len
, unsigned char);
2757 fatalbox("Out of memory");
2760 * Verify the host key.
2764 * First format the key into a string.
2766 int len
= rsastr_len(&hostkey
);
2767 char fingerprint
[100];
2768 char *keystr
= snewn(len
, char);
2770 fatalbox("Out of memory");
2771 rsastr_fmt(keystr
, &hostkey
);
2772 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2773 verify_ssh_host_key(ssh
->frontend
,
2774 ssh
->savedhost
, ssh
->savedport
, "rsa", keystr
,
2779 for (i
= 0; i
< 32; i
++) {
2780 s
->rsabuf
[i
] = ssh
->session_key
[i
];
2782 s
->rsabuf
[i
] ^= s
->session_id
[i
];
2785 if (hostkey
.bytes
> servkey
.bytes
) {
2786 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
2788 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
2790 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
2792 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
2795 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2799 logevent("Encrypted session key");
2802 int cipher_chosen
= 0, warn
= 0;
2803 char *cipher_string
= NULL
;
2805 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2806 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
2807 if (next_cipher
== CIPHER_WARN
) {
2808 /* If/when we choose a cipher, warn about it */
2810 } else if (next_cipher
== CIPHER_AES
) {
2811 /* XXX Probably don't need to mention this. */
2812 logevent("AES not supported in SSH1, skipping");
2814 switch (next_cipher
) {
2815 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
2816 cipher_string
= "3DES"; break;
2817 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
2818 cipher_string
= "Blowfish"; break;
2819 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
2820 cipher_string
= "single-DES"; break;
2822 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
2826 if (!cipher_chosen
) {
2827 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2828 bombout(("Server violates SSH 1 protocol by not "
2829 "supporting 3DES encryption"));
2831 /* shouldn't happen */
2832 bombout(("No supported ciphers found"));
2836 /* Warn about chosen cipher if necessary. */
2838 sk_set_frozen(ssh
->s
, 1);
2839 askalg(ssh
->frontend
, "cipher", cipher_string
);
2840 sk_set_frozen(ssh
->s
, 0);
2844 switch (s
->cipher_type
) {
2845 case SSH_CIPHER_3DES
:
2846 logevent("Using 3DES encryption");
2848 case SSH_CIPHER_DES
:
2849 logevent("Using single-DES encryption");
2851 case SSH_CIPHER_BLOWFISH
:
2852 logevent("Using Blowfish encryption");
2856 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
2857 PKT_CHAR
, s
->cipher_type
,
2858 PKT_DATA
, cookie
, 8,
2859 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
2860 PKT_DATA
, s
->rsabuf
, s
->len
,
2861 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
2863 logevent("Trying to enable encryption...");
2867 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2868 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
2870 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
2871 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
2872 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
2874 ssh
->crcda_ctx
= crcda_make_context();
2875 logevent("Installing CRC compensation attack detector");
2877 if (servkey
.modulus
) {
2878 sfree(servkey
.modulus
);
2879 servkey
.modulus
= NULL
;
2881 if (servkey
.exponent
) {
2882 sfree(servkey
.exponent
);
2883 servkey
.exponent
= NULL
;
2885 if (hostkey
.modulus
) {
2886 sfree(hostkey
.modulus
);
2887 hostkey
.modulus
= NULL
;
2889 if (hostkey
.exponent
) {
2890 sfree(hostkey
.exponent
);
2891 hostkey
.exponent
= NULL
;
2895 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
2896 bombout(("Encryption not successfully enabled"));
2900 logevent("Successfully started encryption");
2904 if (!*ssh
->cfg
.username
) {
2905 if (ssh_get_line
&& !ssh_getline_pw_only
) {
2906 if (!ssh_get_line("login as: ",
2907 s
->username
, sizeof(s
->username
), FALSE
)) {
2909 * get_line failed to get a username.
2912 logevent("No username provided. Abandoning session.");
2913 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
2917 int ret
; /* need not be kept over crReturn */
2918 c_write_str(ssh
, "login as: ");
2921 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
2923 crWaitUntil(!pktin
);
2924 ret
= process_userpass_input(ssh
, in
, inlen
);
2928 c_write_str(ssh
, "\r\n");
2931 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
2932 s
->username
[sizeof(s
->username
)-1] = '\0';
2935 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
2937 char userlog
[22 + sizeof(s
->username
)];
2938 sprintf(userlog
, "Sent username \"%s\"", s
->username
);
2940 if (flags
& FLAG_INTERACTIVE
&&
2941 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2942 strcat(userlog
, "\r\n");
2943 c_write_str(ssh
, userlog
);
2950 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2951 /* We must not attempt PK auth. Pretend we've already tried it. */
2952 s
->tried_publickey
= s
->tried_agent
= 1;
2954 s
->tried_publickey
= s
->tried_agent
= 0;
2956 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
2957 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2958 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
2959 if (!rsakey_pubblob(&ssh
->cfg
.keyfile
,
2960 &s
->publickey_blob
, &s
->publickey_bloblen
, NULL
))
2961 s
->publickey_blob
= NULL
;
2963 s
->publickey_blob
= NULL
;
2965 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
2966 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2968 if (agent_exists() && !s
->tried_agent
) {
2970 * Attempt RSA authentication using Pageant.
2976 logevent("Pageant is running. Requesting keys.");
2978 /* Request the keys held by the agent. */
2979 PUT_32BIT(s
->request
, 1);
2980 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2981 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
2982 ssh_agent_callback
, ssh
)) {
2986 bombout(("Unexpected data from server while waiting"
2987 " for agent response"));
2990 } while (pktin
|| inlen
> 0);
2991 r
= ssh
->agent_response
;
2992 s
->responselen
= ssh
->agent_response_len
;
2994 s
->response
= (unsigned char *) r
;
2995 if (s
->response
&& s
->responselen
>= 5 &&
2996 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2997 s
->p
= s
->response
+ 5;
2998 s
->nkeys
= GET_32BIT(s
->p
);
3002 sprintf(buf
, "Pageant has %d SSH1 keys", s
->nkeys
);
3005 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3008 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
3011 if (s
->publickey_blob
&&
3012 !memcmp(s
->p
, s
->publickey_blob
,
3013 s
->publickey_bloblen
)) {
3014 logevent("This key matches configured key file");
3015 s
->tried_publickey
= 1;
3020 do { /* do while (0) to make breaking easy */
3021 n
= ssh1_read_bignum
3022 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3027 n
= ssh1_read_bignum
3028 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3033 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3035 s
->commentlen
= GET_32BIT(s
->p
);
3037 if (s
->responselen
- (s
->p
-s
->response
) <
3040 s
->commentp
= (char *)s
->p
;
3041 s
->p
+= s
->commentlen
;
3045 logevent("Pageant key list packet was truncated");
3049 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3050 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3052 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3053 logevent("Key refused");
3056 logevent("Received RSA challenge");
3057 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3058 bombout(("Server's RSA challenge was badly formatted"));
3063 char *agentreq
, *q
, *ret
;
3066 len
= 1 + 4; /* message type, bit count */
3067 len
+= ssh1_bignum_length(s
->key
.exponent
);
3068 len
+= ssh1_bignum_length(s
->key
.modulus
);
3069 len
+= ssh1_bignum_length(s
->challenge
);
3070 len
+= 16; /* session id */
3071 len
+= 4; /* response format */
3072 agentreq
= snewn(4 + len
, char);
3073 PUT_32BIT(agentreq
, len
);
3075 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3076 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3078 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3079 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3080 q
+= ssh1_write_bignum(q
, s
->challenge
);
3081 memcpy(q
, s
->session_id
, 16);
3083 PUT_32BIT(q
, 1); /* response format */
3084 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3085 ssh_agent_callback
, ssh
)) {
3090 bombout(("Unexpected data from server"
3091 " while waiting for agent"
3095 } while (pktin
|| inlen
> 0);
3096 vret
= ssh
->agent_response
;
3097 retlen
= ssh
->agent_response_len
;
3102 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3103 logevent("Sending Pageant's response");
3104 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3105 PKT_DATA
, ret
+ 5, 16,
3109 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3111 ("Pageant's response accepted");
3112 if (flags
& FLAG_VERBOSE
) {
3113 c_write_str(ssh
, "Authenticated using"
3115 c_write(ssh
, s
->commentp
,
3117 c_write_str(ssh
, "\" from agent\r\n");
3122 ("Pageant's response not accepted");
3125 ("Pageant failed to answer challenge");
3129 logevent("No reply received from Pageant");
3132 freebn(s
->key
.exponent
);
3133 freebn(s
->key
.modulus
);
3134 freebn(s
->challenge
);
3143 if (!filename_is_null(ssh
->cfg
.keyfile
) && !s
->tried_publickey
)
3144 s
->pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
3146 if (ssh
->cfg
.try_tis_auth
&&
3147 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3148 !s
->tis_auth_refused
) {
3149 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3150 logevent("Requested TIS authentication");
3151 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3153 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3154 logevent("TIS authentication declined");
3155 if (flags
& FLAG_INTERACTIVE
)
3156 c_write_str(ssh
, "TIS authentication refused.\r\n");
3157 s
->tis_auth_refused
= 1;
3163 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3165 bombout(("TIS challenge packet was badly formed"));
3168 logevent("Received TIS challenge");
3169 if (challengelen
> sizeof(s
->prompt
) - 1)
3170 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3171 memcpy(s
->prompt
, challenge
, challengelen
);
3172 /* Prompt heuristic comes from OpenSSH */
3173 strncpy(s
->prompt
+ challengelen
,
3174 memchr(s
->prompt
, '\n', challengelen
) ?
3175 "": "\r\nResponse: ",
3176 (sizeof s
->prompt
) - challengelen
);
3177 s
->prompt
[(sizeof s
->prompt
) - 1] = '\0';
3180 if (ssh
->cfg
.try_tis_auth
&&
3181 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3182 !s
->ccard_auth_refused
) {
3183 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3184 logevent("Requested CryptoCard authentication");
3185 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3187 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3188 logevent("CryptoCard authentication declined");
3189 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3190 s
->ccard_auth_refused
= 1;
3196 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3198 bombout(("CryptoCard challenge packet was badly formed"));
3201 logevent("Received CryptoCard challenge");
3202 if (challengelen
> sizeof(s
->prompt
) - 1)
3203 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3204 memcpy(s
->prompt
, challenge
, challengelen
);
3205 strncpy(s
->prompt
+ challengelen
,
3206 memchr(s
->prompt
, '\n', challengelen
) ?
3207 "" : "\r\nResponse: ",
3208 sizeof(s
->prompt
) - challengelen
);
3209 s
->prompt
[sizeof(s
->prompt
) - 1] = '\0';
3212 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3213 sprintf(s
->prompt
, "%.90s@%.90s's password: ",
3214 s
->username
, ssh
->savedhost
);
3216 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3217 char *comment
= NULL
;
3220 if (flags
& FLAG_VERBOSE
)
3221 c_write_str(ssh
, "Trying public key authentication.\r\n");
3222 logeventf(ssh
, "Trying public key \"%s\"",
3223 filename_to_str(&ssh
->cfg
.keyfile
));
3224 type
= key_type(&ssh
->cfg
.keyfile
);
3225 if (type
!= SSH_KEYTYPE_SSH1
) {
3226 sprintf(msgbuf
, "Key is of wrong type (%s)",
3227 key_type_to_str(type
));
3229 c_write_str(ssh
, msgbuf
);
3230 c_write_str(ssh
, "\r\n");
3231 s
->tried_publickey
= 1;
3234 if (!rsakey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
3235 if (flags
& FLAG_VERBOSE
)
3236 c_write_str(ssh
, "No passphrase required.\r\n");
3239 sprintf(s
->prompt
, "Passphrase for key \"%.100s\": ", comment
);
3244 * Show password prompt, having first obtained it via a TIS
3245 * or CryptoCard exchange if we're doing TIS or CryptoCard
3249 if (!ssh_get_line(s
->prompt
, s
->password
,
3250 sizeof(s
->password
), TRUE
)) {
3252 * get_line failed to get a password (for example
3253 * because one was supplied on the command line
3254 * which has already failed to work). Terminate.
3256 send_packet(ssh
, SSH1_MSG_DISCONNECT
,
3257 PKT_STR
, "No more passwords available to try",
3259 logevent("Unable to authenticate");
3260 connection_fatal(ssh
->frontend
, "Unable to authenticate");
3261 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
3265 /* Prompt may have come from server. We've munged it a bit, so
3266 * we know it to be zero-terminated at least once. */
3267 int ret
; /* need not be saved over crReturn */
3268 c_write_untrusted(ssh
, s
->prompt
, strlen(s
->prompt
));
3271 setup_userpass_input(ssh
, s
->password
, sizeof(s
->password
), 0);
3273 crWaitUntil(!pktin
);
3274 ret
= process_userpass_input(ssh
, in
, inlen
);
3278 c_write_str(ssh
, "\r\n");
3282 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3284 * Try public key authentication with the specified
3287 s
->tried_publickey
= 1;
3290 const char *error
= NULL
;
3291 int ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, s
->password
,
3294 c_write_str(ssh
, "Couldn't load private key from ");
3295 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3296 c_write_str(ssh
, " (");
3297 c_write_str(ssh
, error
);
3298 c_write_str(ssh
, ").\r\n");
3299 continue; /* go and try password */
3302 c_write_str(ssh
, "Wrong passphrase.\r\n");
3303 s
->tried_publickey
= 0;
3304 continue; /* try again */
3309 * Send a public key attempt.
3311 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3312 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3315 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3316 c_write_str(ssh
, "Server refused our public key.\r\n");
3317 continue; /* go and try password */
3319 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3320 bombout(("Bizarre response to offer of public key"));
3326 unsigned char buffer
[32];
3327 Bignum challenge
, response
;
3329 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3330 bombout(("Server's RSA challenge was badly formatted"));
3333 response
= rsadecrypt(challenge
, &s
->key
);
3334 freebn(s
->key
.private_exponent
);/* burn the evidence */
3336 for (i
= 0; i
< 32; i
++) {
3337 buffer
[i
] = bignum_byte(response
, 31 - i
);
3341 MD5Update(&md5c
, buffer
, 32);
3342 MD5Update(&md5c
, s
->session_id
, 16);
3343 MD5Final(buffer
, &md5c
);
3345 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3346 PKT_DATA
, buffer
, 16, PKT_END
);
3353 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3354 if (flags
& FLAG_VERBOSE
)
3355 c_write_str(ssh
, "Failed to authenticate with"
3356 " our public key.\r\n");
3357 continue; /* go and try password */
3358 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3359 bombout(("Bizarre response to RSA authentication response"));
3363 break; /* we're through! */
3365 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3367 * Defence against traffic analysis: we send a
3368 * whole bunch of packets containing strings of
3369 * different lengths. One of these strings is the
3370 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3371 * The others are all random data in
3372 * SSH1_MSG_IGNORE packets. This way a passive
3373 * listener can't tell which is the password, and
3374 * hence can't deduce the password length.
3376 * Anybody with a password length greater than 16
3377 * bytes is going to have enough entropy in their
3378 * password that a listener won't find it _that_
3379 * much help to know how long it is. So what we'll
3382 * - if password length < 16, we send 15 packets
3383 * containing string lengths 1 through 15
3385 * - otherwise, we let N be the nearest multiple
3386 * of 8 below the password length, and send 8
3387 * packets containing string lengths N through
3388 * N+7. This won't obscure the order of
3389 * magnitude of the password length, but it will
3390 * introduce a bit of extra uncertainty.
3392 * A few servers (the old 1.2.18 through 1.2.22)
3393 * can't deal with SSH1_MSG_IGNORE. For these
3394 * servers, we need an alternative defence. We make
3395 * use of the fact that the password is interpreted
3396 * as a C string: so we can append a NUL, then some
3399 * One server (a Cisco one) can deal with neither
3400 * SSH1_MSG_IGNORE _nor_ a padded password string.
3401 * For this server we are left with no defences
3402 * against password length sniffing.
3404 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
3406 * The server can deal with SSH1_MSG_IGNORE, so
3407 * we can use the primary defence.
3409 int bottom
, top
, pwlen
, i
;
3412 pwlen
= strlen(s
->password
);
3414 bottom
= 0; /* zero length passwords are OK! :-) */
3417 bottom
= pwlen
& ~7;
3421 assert(pwlen
>= bottom
&& pwlen
<= top
);
3423 randomstr
= snewn(top
+ 1, char);
3425 for (i
= bottom
; i
<= top
; i
++) {
3427 defer_packet(ssh
, s
->pwpkt_type
,
3428 PKTT_PASSWORD
, PKT_STR
, s
->password
,
3429 PKTT_OTHER
, PKT_END
);
3431 for (j
= 0; j
< i
; j
++) {
3433 randomstr
[j
] = random_byte();
3434 } while (randomstr
[j
] == '\0');
3436 randomstr
[i
] = '\0';
3437 defer_packet(ssh
, SSH1_MSG_IGNORE
,
3438 PKT_STR
, randomstr
, PKT_END
);
3441 logevent("Sending password with camouflage packets");
3442 ssh_pkt_defersend(ssh
);
3445 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3447 * The server can't deal with SSH1_MSG_IGNORE
3448 * but can deal with padded passwords, so we
3449 * can use the secondary defence.
3455 len
= strlen(s
->password
);
3456 if (len
< sizeof(string
)) {
3458 strcpy(string
, s
->password
);
3459 len
++; /* cover the zero byte */
3460 while (len
< sizeof(string
)) {
3461 string
[len
++] = (char) random_byte();
3466 logevent("Sending length-padded password");
3467 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3468 PKT_INT
, len
, PKT_DATA
, ss
, len
,
3469 PKTT_OTHER
, PKT_END
);
3472 * The server has _both_
3473 * BUG_CHOKES_ON_SSH1_IGNORE and
3474 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3475 * therefore nothing we can do.
3478 len
= strlen(s
->password
);
3479 logevent("Sending unpadded password");
3480 send_packet(ssh
, s
->pwpkt_type
,
3481 PKTT_PASSWORD
, PKT_INT
, len
,
3482 PKT_DATA
, s
->password
, len
,
3483 PKTT_OTHER
, PKT_END
);
3486 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3487 PKT_STR
, s
->password
, PKTT_OTHER
, PKT_END
);
3490 logevent("Sent password");
3491 memset(s
->password
, 0, strlen(s
->password
));
3493 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3494 if (flags
& FLAG_VERBOSE
)
3495 c_write_str(ssh
, "Access denied\r\n");
3496 logevent("Authentication refused");
3497 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3498 bombout(("Strange packet received, type %d", pktin
->type
));
3503 logevent("Authentication successful");
3508 void sshfwd_close(struct ssh_channel
*c
)
3512 if (ssh
->state
!= SSH_STATE_SESSION
) {
3513 assert(ssh
->state
== SSH_STATE_CLOSED
);
3517 if (c
&& !c
->closes
) {
3519 * If the channel's remoteid is -1, we have sent
3520 * CHANNEL_OPEN for this channel, but it hasn't even been
3521 * acknowledged by the server. So we must set a close flag
3522 * on it now, and then when the server acks the channel
3523 * open, we can close it then.
3525 if (((int)c
->remoteid
) != -1) {
3526 if (ssh
->version
== 1) {
3527 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3530 struct Packet
*pktout
;
3531 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3532 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
3533 ssh2_pkt_send(ssh
, pktout
);
3536 c
->closes
= 1; /* sent MSG_CLOSE */
3537 if (c
->type
== CHAN_X11
) {
3539 logevent("Forwarded X11 connection terminated");
3540 } else if (c
->type
== CHAN_SOCKDATA
||
3541 c
->type
== CHAN_SOCKDATA_DORMANT
) {
3543 logevent("Forwarded port closed");
3548 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
3552 if (ssh
->state
!= SSH_STATE_SESSION
) {
3553 assert(ssh
->state
== SSH_STATE_CLOSED
);
3557 if (ssh
->version
== 1) {
3558 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3559 PKT_INT
, c
->remoteid
,
3561 PKT_INT
, len
, PKT_DATA
, buf
, len
,
3562 PKTT_OTHER
, PKT_END
);
3564 * In SSH1 we can return 0 here - implying that forwarded
3565 * connections are never individually throttled - because
3566 * the only circumstance that can cause throttling will be
3567 * the whole SSH connection backing up, in which case
3568 * _everything_ will be throttled as a whole.
3572 ssh2_add_channel_data(c
, buf
, len
);
3573 return ssh2_try_send(c
);
3577 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
3581 if (ssh
->state
!= SSH_STATE_SESSION
) {
3582 assert(ssh
->state
== SSH_STATE_CLOSED
);
3586 if (ssh
->version
== 1) {
3587 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
3588 c
->v
.v1
.throttling
= 0;
3589 ssh1_throttle(ssh
, -1);
3592 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
3596 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
3598 struct queued_handler
*qh
= ssh
->qhead
;
3602 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
3605 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
3606 ssh
->packet_dispatch
[qh
->msg1
] = NULL
;
3609 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
3610 ssh
->packet_dispatch
[qh
->msg2
] = NULL
;
3614 ssh
->qhead
= qh
->next
;
3616 if (ssh
->qhead
->msg1
> 0) {
3617 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg1
] == NULL
);
3618 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
3620 if (ssh
->qhead
->msg2
> 0) {
3621 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg2
] == NULL
);
3622 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
3625 ssh
->qhead
= ssh
->qtail
= NULL
;
3626 ssh
->packet_dispatch
[pktin
->type
] = NULL
;
3629 qh
->handler(ssh
, pktin
, qh
->ctx
);
3634 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
3635 chandler_fn_t handler
, void *ctx
)
3637 struct queued_handler
*qh
;
3639 qh
= snew(struct queued_handler
);
3642 qh
->handler
= handler
;
3646 if (ssh
->qtail
== NULL
) {
3650 assert(ssh
->packet_dispatch
[qh
->msg1
] == NULL
);
3651 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
3654 assert(ssh
->packet_dispatch
[qh
->msg2
] == NULL
);
3655 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
3658 ssh
->qtail
->next
= qh
;
3663 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
3665 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
3667 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
3668 SSH2_MSG_REQUEST_SUCCESS
)) {
3669 logeventf(ssh
, "Remote port forwarding from %s enabled",
3672 logeventf(ssh
, "Remote port forwarding from %s refused",
3675 rpf
= del234(ssh
->rportfwds
, pf
);
3681 static void ssh_setup_portfwd(Ssh ssh
, const Config
*cfg
)
3683 const char *portfwd_strptr
= cfg
->portfwd
;
3684 struct ssh_portfwd
*epf
;
3687 if (!ssh
->portfwds
) {
3688 ssh
->portfwds
= newtree234(ssh_portcmp
);
3691 * Go through the existing port forwardings and tag them
3692 * with status==DESTROY. Any that we want to keep will be
3693 * re-enabled (status==KEEP) as we go through the
3694 * configuration and find out which bits are the same as
3697 struct ssh_portfwd
*epf
;
3699 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3700 epf
->status
= DESTROY
;
3703 while (*portfwd_strptr
) {
3704 char address_family
, type
;
3705 int sport
,dport
,sserv
,dserv
;
3706 char sports
[256], dports
[256], saddr
[256], host
[256];
3709 address_family
= 'A';
3711 if (*portfwd_strptr
== 'A' ||
3712 *portfwd_strptr
== '4' ||
3713 *portfwd_strptr
== '6')
3714 address_family
= *portfwd_strptr
++;
3715 if (*portfwd_strptr
== 'L' ||
3716 *portfwd_strptr
== 'R' ||
3717 *portfwd_strptr
== 'D')
3718 type
= *portfwd_strptr
++;
3723 while (*portfwd_strptr
&& *portfwd_strptr
!= '\t') {
3724 if (*portfwd_strptr
== ':') {
3726 * We've seen a colon in the middle of the
3727 * source port number. This means that
3728 * everything we've seen until now is the
3729 * source _address_, so we'll move it into
3730 * saddr and start sports from the beginning
3735 if (ssh
->version
== 1 && type
== 'R') {
3736 logeventf(ssh
, "SSH1 cannot handle remote source address "
3737 "spec \"%s\"; ignoring", sports
);
3739 strcpy(saddr
, sports
);
3742 if (n
< 255) sports
[n
++] = *portfwd_strptr
++;
3746 if (*portfwd_strptr
== '\t')
3749 while (*portfwd_strptr
&& *portfwd_strptr
!= ':') {
3750 if (n
< 255) host
[n
++] = *portfwd_strptr
++;
3753 if (*portfwd_strptr
== ':')
3756 while (*portfwd_strptr
) {
3757 if (n
< 255) dports
[n
++] = *portfwd_strptr
++;
3761 dport
= atoi(dports
);
3765 dport
= net_service_lookup(dports
);
3767 logeventf(ssh
, "Service lookup failed for destination"
3768 " port \"%s\"", dports
);
3772 while (*portfwd_strptr
) portfwd_strptr
++;
3774 portfwd_strptr
++; /* eat the NUL and move to next one */
3776 sport
= atoi(sports
);
3780 sport
= net_service_lookup(sports
);
3782 logeventf(ssh
, "Service lookup failed for source"
3783 " port \"%s\"", sports
);
3786 if (sport
&& dport
) {
3787 /* Set up a description of the source port. */
3788 struct ssh_portfwd
*pfrec
, *epfrec
;
3790 pfrec
= snew(struct ssh_portfwd
);
3792 pfrec
->saddr
= *saddr ?
dupstr(saddr
) : NULL
;
3793 pfrec
->sserv
= sserv ?
dupstr(sports
) : NULL
;
3794 pfrec
->sport
= sport
;
3795 pfrec
->daddr
= *host ?
dupstr(host
) : NULL
;
3796 pfrec
->dserv
= dserv ?
dupstr(dports
) : NULL
;
3797 pfrec
->dport
= dport
;
3798 pfrec
->local
= NULL
;
3799 pfrec
->remote
= NULL
;
3800 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
3801 address_family
== '6' ? ADDRTYPE_IPV6
:
3804 epfrec
= add234(ssh
->portfwds
, pfrec
);
3805 if (epfrec
!= pfrec
) {
3807 * We already have a port forwarding with precisely
3808 * these parameters. Hence, no need to do anything;
3809 * simply tag the existing one as KEEP.
3811 epfrec
->status
= KEEP
;
3812 free_portfwd(pfrec
);
3814 pfrec
->status
= CREATE
;
3820 * Now go through and destroy any port forwardings which were
3823 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3824 if (epf
->status
== DESTROY
) {
3827 message
= dupprintf("%s port forwarding from %s%s%d",
3828 epf
->type
== 'L' ?
"local" :
3829 epf
->type
== 'R' ?
"remote" : "dynamic",
3830 epf
->saddr ? epf
->saddr
: "",
3831 epf
->saddr ?
":" : "",
3834 if (epf
->type
!= 'D') {
3835 char *msg2
= dupprintf("%s to %s:%d", message
,
3836 epf
->daddr
, epf
->dport
);
3841 logeventf(ssh
, "Cancelling %s", message
);
3845 struct ssh_rportfwd
*rpf
= epf
->remote
;
3846 struct Packet
*pktout
;
3849 * Cancel the port forwarding at the server
3852 if (ssh
->version
== 1) {
3854 * We cannot cancel listening ports on the
3855 * server side in SSH1! There's no message
3856 * to support it. Instead, we simply remove
3857 * the rportfwd record from the local end
3858 * so that any connections the server tries
3859 * to make on it are rejected.
3862 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
3863 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
3864 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
3866 ssh2_pkt_addstring(pktout
, epf
->saddr
);
3867 } else if (ssh
->cfg
.rport_acceptall
) {
3868 ssh2_pkt_addstring(pktout
, "0.0.0.0");
3870 ssh2_pkt_addstring(pktout
, "127.0.0.1");
3872 ssh2_pkt_adduint32(pktout
, epf
->sport
);
3873 ssh2_pkt_send(ssh
, pktout
);
3876 del234(ssh
->rportfwds
, rpf
);
3878 } else if (epf
->local
) {
3879 pfd_terminate(epf
->local
);
3882 delpos234(ssh
->portfwds
, i
);
3884 i
--; /* so we don't skip one in the list */
3888 * And finally, set up any new port forwardings (status==CREATE).
3890 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3891 if (epf
->status
== CREATE
) {
3892 char *sportdesc
, *dportdesc
;
3893 sportdesc
= dupprintf("%s%s%s%s%d%s",
3894 epf
->saddr ? epf
->saddr
: "",
3895 epf
->saddr ?
":" : "",
3896 epf
->sserv ? epf
->sserv
: "",
3897 epf
->sserv ?
"(" : "",
3899 epf
->sserv ?
")" : "");
3900 if (epf
->type
== 'D') {
3903 dportdesc
= dupprintf("%s:%s%s%d%s",
3905 epf
->dserv ? epf
->dserv
: "",
3906 epf
->dserv ?
"(" : "",
3908 epf
->dserv ?
")" : "");
3911 if (epf
->type
== 'L') {
3912 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
3913 epf
->saddr
, epf
->sport
,
3916 epf
->addressfamily
);
3918 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
3919 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
3920 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
3921 sportdesc
, dportdesc
,
3922 err ?
" failed: " : "", err ? err
: "");
3923 } else if (epf
->type
== 'D') {
3924 const char *err
= pfd_addforward(NULL
, -1,
3925 epf
->saddr
, epf
->sport
,
3928 epf
->addressfamily
);
3930 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
3931 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
3932 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
3934 err ?
" failed: " : "", err ? err
: "");
3936 struct ssh_rportfwd
*pf
;
3939 * Ensure the remote port forwardings tree exists.
3941 if (!ssh
->rportfwds
) {
3942 if (ssh
->version
== 1)
3943 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
3945 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
3948 pf
= snew(struct ssh_rportfwd
);
3949 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
3950 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
3951 pf
->dport
= epf
->dport
;
3952 pf
->sport
= epf
->sport
;
3953 if (add234(ssh
->rportfwds
, pf
) != pf
) {
3954 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
3955 epf
->daddr
, epf
->dport
);
3958 logeventf(ssh
, "Requesting remote port %s"
3959 " forward to %s", sportdesc
, dportdesc
);
3961 pf
->sportdesc
= sportdesc
;
3966 if (ssh
->version
== 1) {
3967 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
3968 PKT_INT
, epf
->sport
,
3969 PKT_STR
, epf
->daddr
,
3970 PKT_INT
, epf
->dport
,
3972 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
3974 ssh_rportfwd_succfail
, pf
);
3976 struct Packet
*pktout
;
3977 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
3978 ssh2_pkt_addstring(pktout
, "tcpip-forward");
3979 ssh2_pkt_addbool(pktout
, 1);/* want reply */
3981 ssh2_pkt_addstring(pktout
, epf
->saddr
);
3982 } else if (ssh
->cfg
.rport_acceptall
) {
3983 ssh2_pkt_addstring(pktout
, "0.0.0.0");
3985 ssh2_pkt_addstring(pktout
, "127.0.0.1");
3987 ssh2_pkt_adduint32(pktout
, epf
->sport
);
3988 ssh2_pkt_send(ssh
, pktout
);
3990 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
3991 SSH2_MSG_REQUEST_FAILURE
,
3992 ssh_rportfwd_succfail
, pf
);
4001 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
4004 int stringlen
, bufsize
;
4006 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
4007 if (string
== NULL
) {
4008 bombout(("Incoming terminal data packet was badly formed"));
4012 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
4014 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4015 ssh
->v1_stdout_throttling
= 1;
4016 ssh1_throttle(ssh
, +1);
4020 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4022 /* Remote side is trying to open a channel to talk to our
4023 * X-Server. Give them back a local channel number. */
4024 struct ssh_channel
*c
;
4025 int remoteid
= ssh_pkt_getuint32(pktin
);
4027 logevent("Received X11 connect request");
4028 /* Refuse if X11 forwarding is disabled. */
4029 if (!ssh
->X11_fwd_enabled
) {
4030 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4031 PKT_INT
, remoteid
, PKT_END
);
4032 logevent("Rejected X11 connect request");
4034 c
= snew(struct ssh_channel
);
4037 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
4038 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
4039 logevent("Opening X11 forward connection failed");
4041 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4042 PKT_INT
, remoteid
, PKT_END
);
4045 ("Opening X11 forward connection succeeded");
4046 c
->remoteid
= remoteid
;
4047 c
->localid
= alloc_channel_id(ssh
);
4049 c
->v
.v1
.throttling
= 0;
4050 c
->type
= CHAN_X11
; /* identify channel type */
4051 add234(ssh
->channels
, c
);
4052 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4053 PKT_INT
, c
->remoteid
, PKT_INT
,
4054 c
->localid
, PKT_END
);
4055 logevent("Opened X11 forward channel");
4060 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4062 /* Remote side is trying to open a channel to talk to our
4063 * agent. Give them back a local channel number. */
4064 struct ssh_channel
*c
;
4065 int remoteid
= ssh_pkt_getuint32(pktin
);
4067 /* Refuse if agent forwarding is disabled. */
4068 if (!ssh
->agentfwd_enabled
) {
4069 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4070 PKT_INT
, remoteid
, PKT_END
);
4072 c
= snew(struct ssh_channel
);
4074 c
->remoteid
= remoteid
;
4075 c
->localid
= alloc_channel_id(ssh
);
4077 c
->v
.v1
.throttling
= 0;
4078 c
->type
= CHAN_AGENT
; /* identify channel type */
4079 c
->u
.a
.lensofar
= 0;
4080 add234(ssh
->channels
, c
);
4081 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4082 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4087 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4089 /* Remote side is trying to open a channel to talk to a
4090 * forwarded port. Give them back a local channel number. */
4091 struct ssh_channel
*c
;
4092 struct ssh_rportfwd pf
, *pfp
;
4095 char *host
, buf
[1024];
4097 c
= snew(struct ssh_channel
);
4100 remoteid
= ssh_pkt_getuint32(pktin
);
4101 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4102 port
= ssh_pkt_getuint32(pktin
);
4104 if (hostsize
>= lenof(pf
.dhost
))
4105 hostsize
= lenof(pf
.dhost
)-1;
4106 memcpy(pf
.dhost
, host
, hostsize
);
4107 pf
.dhost
[hostsize
] = '\0';
4109 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4112 sprintf(buf
, "Rejected remote port open request for %s:%d",
4115 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4116 PKT_INT
, remoteid
, PKT_END
);
4118 sprintf(buf
, "Received remote port open request for %s:%d",
4121 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4122 c
, &ssh
->cfg
, pfp
->pfrec
->addressfamily
);
4125 sprintf(buf
, "Port open failed: %s", e
);
4128 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4129 PKT_INT
, remoteid
, PKT_END
);
4131 c
->remoteid
= remoteid
;
4132 c
->localid
= alloc_channel_id(ssh
);
4134 c
->v
.v1
.throttling
= 0;
4135 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4136 add234(ssh
->channels
, c
);
4137 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4138 PKT_INT
, c
->remoteid
, PKT_INT
,
4139 c
->localid
, PKT_END
);
4140 logevent("Forwarded port opened successfully");
4145 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4147 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4148 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4149 struct ssh_channel
*c
;
4151 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4152 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4153 c
->remoteid
= localid
;
4154 c
->type
= CHAN_SOCKDATA
;
4155 c
->v
.v1
.throttling
= 0;
4156 pfd_confirm(c
->u
.pfd
.s
);
4159 if (c
&& c
->closes
) {
4161 * We have a pending close on this channel,
4162 * which we decided on before the server acked
4163 * the channel open. So now we know the
4164 * remoteid, we can close it again.
4166 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
4167 PKT_INT
, c
->remoteid
, PKT_END
);
4171 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4173 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4174 struct ssh_channel
*c
;
4176 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4177 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4178 logevent("Forwarded connection refused by server");
4179 pfd_close(c
->u
.pfd
.s
);
4180 del234(ssh
->channels
, c
);
4185 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4187 /* Remote side closes a channel. */
4188 unsigned i
= ssh_pkt_getuint32(pktin
);
4189 struct ssh_channel
*c
;
4190 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4191 if (c
&& ((int)c
->remoteid
) != -1) {
4194 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
4196 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
4197 logevent("Forwarded X11 connection terminated");
4198 assert(c
->u
.x11
.s
!= NULL
);
4199 x11_close(c
->u
.x11
.s
);
4202 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
4203 logevent("Forwarded port closed");
4204 assert(c
->u
.pfd
.s
!= NULL
);
4205 pfd_close(c
->u
.pfd
.s
);
4209 c
->closes
|= (closetype
<< 2); /* seen this message */
4210 if (!(c
->closes
& closetype
)) {
4211 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
4213 c
->closes
|= closetype
; /* sent it too */
4216 if (c
->closes
== 15) {
4217 del234(ssh
->channels
, c
);
4221 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4222 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
4223 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
4228 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
4230 /* Data sent down one of our channels. */
4231 int i
= ssh_pkt_getuint32(pktin
);
4234 struct ssh_channel
*c
;
4236 ssh_pkt_getstring(pktin
, &p
, &len
);
4238 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4243 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
4246 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
4249 /* Data for an agent message. Buffer it. */
4251 if (c
->u
.a
.lensofar
< 4) {
4252 unsigned int l
= min(4 - c
->u
.a
.lensofar
, len
);
4253 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
4257 c
->u
.a
.lensofar
+= l
;
4259 if (c
->u
.a
.lensofar
== 4) {
4261 4 + GET_32BIT(c
->u
.a
.msglen
);
4262 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
4264 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4266 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
4268 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4270 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
4274 c
->u
.a
.lensofar
+= l
;
4276 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4279 if (agent_query(c
->u
.a
.message
,
4282 ssh_agentf_callback
, c
))
4283 ssh_agentf_callback(c
, reply
, replylen
);
4284 sfree(c
->u
.a
.message
);
4285 c
->u
.a
.lensofar
= 0;
4288 bufsize
= 0; /* agent channels never back up */
4291 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4292 c
->v
.v1
.throttling
= 1;
4293 ssh1_throttle(ssh
, +1);
4298 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
4301 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
4302 sprintf(buf
, "Server sent command exit status %d",
4305 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
4307 * In case `helpful' firewalls or proxies tack
4308 * extra human-readable text on the end of the
4309 * session which we might mistake for another
4310 * encrypted packet, we close the session once
4311 * we've sent EXIT_CONFIRMATION.
4313 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
4316 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
4317 struct Packet
*pktin
)
4319 crBegin(ssh
->do_ssh1_connection_crstate
);
4321 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
4322 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
4323 ssh1_smsg_stdout_stderr_data
;
4325 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
4326 ssh1_msg_channel_open_confirmation
;
4327 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
4328 ssh1_msg_channel_open_failure
;
4329 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
4330 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
4331 ssh1_msg_channel_close
;
4332 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
4333 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
4335 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
4336 logevent("Requesting agent forwarding");
4337 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
4341 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4342 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4343 bombout(("Protocol confusion"));
4345 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4346 logevent("Agent forwarding refused");
4348 logevent("Agent forwarding enabled");
4349 ssh
->agentfwd_enabled
= TRUE
;
4350 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
4354 if (ssh
->cfg
.x11_forward
) {
4355 char proto
[20], data
[64];
4356 logevent("Requesting X11 forwarding");
4357 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
4358 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
4359 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
4360 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
4361 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4362 PKT_STR
, proto
, PKT_STR
, data
,
4363 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
4366 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4367 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
4372 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4373 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4374 bombout(("Protocol confusion"));
4376 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4377 logevent("X11 forwarding refused");
4379 logevent("X11 forwarding enabled");
4380 ssh
->X11_fwd_enabled
= TRUE
;
4381 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
4385 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
4386 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
4388 if (!ssh
->cfg
.nopty
) {
4389 /* Unpick the terminal-speed string. */
4390 /* XXX perhaps we should allow no speeds to be sent. */
4391 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
4392 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
4393 /* Send the pty request. */
4394 send_packet(ssh
, SSH1_CMSG_REQUEST_PTY
,
4395 PKT_STR
, ssh
->cfg
.termtype
,
4396 PKT_INT
, ssh
->term_height
,
4397 PKT_INT
, ssh
->term_width
,
4398 PKT_INT
, 0, PKT_INT
, 0, /* width,height in pixels */
4399 PKT_CHAR
, 192, PKT_INT
, ssh
->ispeed
, /* TTY_OP_ISPEED */
4400 PKT_CHAR
, 193, PKT_INT
, ssh
->ospeed
, /* TTY_OP_OSPEED */
4401 PKT_CHAR
, 0, PKT_END
);
4402 ssh
->state
= SSH_STATE_INTERMED
;
4406 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4407 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4408 bombout(("Protocol confusion"));
4410 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4411 c_write_str(ssh
, "Server refused to allocate pty\r\n");
4412 ssh
->editing
= ssh
->echoing
= 1;
4414 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4415 ssh
->ospeed
, ssh
->ispeed
);
4417 ssh
->editing
= ssh
->echoing
= 1;
4420 if (ssh
->cfg
.compression
) {
4421 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
4425 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4426 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4427 bombout(("Protocol confusion"));
4429 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4430 c_write_str(ssh
, "Server refused to compress\r\n");
4432 logevent("Started compression");
4433 ssh
->v1_compressing
= TRUE
;
4434 ssh
->cs_comp_ctx
= zlib_compress_init();
4435 logevent("Initialised zlib (RFC1950) compression");
4436 ssh
->sc_comp_ctx
= zlib_decompress_init();
4437 logevent("Initialised zlib (RFC1950) decompression");
4441 * Start the shell or command.
4443 * Special case: if the first-choice command is an SSH2
4444 * subsystem (hence not usable here) and the second choice
4445 * exists, we fall straight back to that.
4448 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
4450 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
4451 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
4452 ssh
->fallback_cmd
= TRUE
;
4455 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
4457 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
4458 logevent("Started session");
4461 ssh
->state
= SSH_STATE_SESSION
;
4462 if (ssh
->size_needed
)
4463 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
4464 if (ssh
->eof_needed
)
4465 ssh_special(ssh
, TS_EOF
);
4468 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
4470 ssh
->channels
= newtree234(ssh_channelcmp
);
4474 * By this point, most incoming packets are already being
4475 * handled by the dispatch table, and we need only pay
4476 * attention to the unusual ones.
4481 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
4482 /* may be from EXEC_SHELL on some servers */
4483 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4484 /* may be from EXEC_SHELL on some servers
4485 * if no pty is available or in other odd cases. Ignore */
4487 bombout(("Strange packet received: type %d", pktin
->type
));
4492 int len
= min(inlen
, 512);
4493 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
, PKTT_DATA
,
4494 PKT_INT
, len
, PKT_DATA
, in
, len
,
4495 PKTT_OTHER
, PKT_END
);
4506 * Handle the top-level SSH2 protocol.
4508 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
4513 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4514 buf
= dupprintf("Remote debug message: %.*s", msglen
, msg
);
4519 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
4521 /* log reason code in disconnect message */
4525 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4526 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
4529 void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
4531 /* Do nothing, because we're ignoring it! Duhh. */
4534 static void ssh1_protocol_setup(Ssh ssh
)
4539 * Most messages are handled by the coroutines.
4541 for (i
= 0; i
< 256; i
++)
4542 ssh
->packet_dispatch
[i
] = NULL
;
4545 * These special message types we install handlers for.
4547 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
4548 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
4549 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
4552 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
4553 struct Packet
*pktin
)
4555 if (ssh
->state
== SSH_STATE_CLOSED
)
4558 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
4559 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
4563 if (!ssh
->protocol_initial_phase_done
) {
4564 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
4565 ssh
->protocol_initial_phase_done
= TRUE
;
4570 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
4574 * Utility routine for decoding comma-separated strings in KEXINIT.
4576 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
4579 if (!needle
|| !haystack
) /* protect against null pointers */
4581 needlen
= strlen(needle
);
4584 * Is it at the start of the string?
4586 if (haylen
>= needlen
&& /* haystack is long enough */
4587 !memcmp(needle
, haystack
, needlen
) && /* initial match */
4588 (haylen
== needlen
|| haystack
[needlen
] == ',')
4589 /* either , or EOS follows */
4593 * If not, search for the next comma and resume after that.
4594 * If no comma found, terminate.
4596 while (haylen
> 0 && *haystack
!= ',')
4597 haylen
--, haystack
++;
4600 haylen
--, haystack
++; /* skip over comma itself */
4605 * SSH2 key creation method.
4607 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
,
4608 unsigned char *sessid
, char chr
,
4609 unsigned char *keyspace
)
4612 /* First 20 bytes. */
4614 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4616 SHA_Bytes(&s
, H
, 20);
4617 SHA_Bytes(&s
, &chr
, 1);
4618 SHA_Bytes(&s
, sessid
, 20);
4619 SHA_Final(&s
, keyspace
);
4620 /* Next 20 bytes. */
4622 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4624 SHA_Bytes(&s
, H
, 20);
4625 SHA_Bytes(&s
, keyspace
, 20);
4626 SHA_Final(&s
, keyspace
+ 20);
4630 * Handle the SSH2 transport layer.
4632 static int do_ssh2_transport(Ssh ssh
, unsigned char *in
, int inlen
,
4633 struct Packet
*pktin
)
4635 struct do_ssh2_transport_state
{
4636 int nbits
, pbits
, warn
;
4637 Bignum p
, g
, e
, f
, K
;
4638 int kex_init_value
, kex_reply_value
;
4639 const struct ssh_mac
**maclist
;
4641 const struct ssh2_cipher
*cscipher_tobe
;
4642 const struct ssh2_cipher
*sccipher_tobe
;
4643 const struct ssh_mac
*csmac_tobe
;
4644 const struct ssh_mac
*scmac_tobe
;
4645 const struct ssh_compress
*cscomp_tobe
;
4646 const struct ssh_compress
*sccomp_tobe
;
4647 char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
4648 int hostkeylen
, siglen
;
4649 void *hkey
; /* actual host key */
4650 unsigned char exchange_hash
[20];
4651 int n_preferred_kex
;
4652 const struct ssh_kex
*preferred_kex
[KEX_MAX
];
4653 int n_preferred_ciphers
;
4654 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
4655 const struct ssh_compress
*preferred_comp
;
4656 int got_session_id
, activated_authconn
;
4657 struct Packet
*pktout
;
4659 crState(do_ssh2_transport_state
);
4661 crBegin(ssh
->do_ssh2_transport_crstate
);
4663 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
4664 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
4665 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
4667 s
->got_session_id
= s
->activated_authconn
= FALSE
;
4670 * Be prepared to work around the buggy MAC problem.
4672 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
4673 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
4675 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
4679 int i
, j
, commalist_started
;
4682 * Set up the preferred key exchange. (NULL => warn below here)
4684 s
->n_preferred_kex
= 0;
4685 for (i
= 0; i
< KEX_MAX
; i
++) {
4686 switch (ssh
->cfg
.ssh_kexlist
[i
]) {
4688 s
->preferred_kex
[s
->n_preferred_kex
++] =
4689 &ssh_diffiehellman_gex
;
4692 s
->preferred_kex
[s
->n_preferred_kex
++] =
4693 &ssh_diffiehellman_group14
;
4696 s
->preferred_kex
[s
->n_preferred_kex
++] =
4697 &ssh_diffiehellman_group1
;
4700 /* Flag for later. Don't bother if it's the last in
4702 if (i
< KEX_MAX
- 1) {
4703 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
4710 * Set up the preferred ciphers. (NULL => warn below here)
4712 s
->n_preferred_ciphers
= 0;
4713 for (i
= 0; i
< CIPHER_MAX
; i
++) {
4714 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
4715 case CIPHER_BLOWFISH
:
4716 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
4719 if (ssh
->cfg
.ssh2_des_cbc
) {
4720 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
4724 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
4727 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
4730 /* Flag for later. Don't bother if it's the last in
4732 if (i
< CIPHER_MAX
- 1) {
4733 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
4740 * Set up preferred compression.
4742 if (ssh
->cfg
.compression
)
4743 s
->preferred_comp
= &ssh_zlib
;
4745 s
->preferred_comp
= &ssh_comp_none
;
4748 * Enable queueing of outgoing auth- or connection-layer
4749 * packets while we are in the middle of a key exchange.
4751 ssh
->queueing
= TRUE
;
4754 * Flag that KEX is in progress.
4756 ssh
->kex_in_progress
= TRUE
;
4759 * Construct and send our key exchange packet.
4761 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
4762 for (i
= 0; i
< 16; i
++)
4763 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
4764 /* List key exchange algorithms. */
4765 ssh2_pkt_addstring_start(s
->pktout
);
4766 commalist_started
= 0;
4767 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
4768 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
4769 if (!k
) continue; /* warning flag */
4770 if (commalist_started
)
4771 ssh2_pkt_addstring_str(s
->pktout
, ",");
4772 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_kex
[i
]->name
);
4773 commalist_started
= 1;
4775 /* List server host key algorithms. */
4776 ssh2_pkt_addstring_start(s
->pktout
);
4777 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
4778 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
4779 if (i
< lenof(hostkey_algs
) - 1)
4780 ssh2_pkt_addstring_str(s
->pktout
, ",");
4782 /* List client->server encryption algorithms. */
4783 ssh2_pkt_addstring_start(s
->pktout
);
4784 commalist_started
= 0;
4785 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4786 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4787 if (!c
) continue; /* warning flag */
4788 for (j
= 0; j
< c
->nciphers
; j
++) {
4789 if (commalist_started
)
4790 ssh2_pkt_addstring_str(s
->pktout
, ",");
4791 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4792 commalist_started
= 1;
4795 /* List server->client encryption algorithms. */
4796 ssh2_pkt_addstring_start(s
->pktout
);
4797 commalist_started
= 0;
4798 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4799 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4800 if (!c
) continue; /* warning flag */
4801 for (j
= 0; j
< c
->nciphers
; j
++) {
4802 if (commalist_started
)
4803 ssh2_pkt_addstring_str(s
->pktout
, ",");
4804 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4805 commalist_started
= 1;
4808 /* List client->server MAC algorithms. */
4809 ssh2_pkt_addstring_start(s
->pktout
);
4810 for (i
= 0; i
< s
->nmacs
; i
++) {
4811 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4812 if (i
< s
->nmacs
- 1)
4813 ssh2_pkt_addstring_str(s
->pktout
, ",");
4815 /* List server->client MAC algorithms. */
4816 ssh2_pkt_addstring_start(s
->pktout
);
4817 for (i
= 0; i
< s
->nmacs
; i
++) {
4818 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4819 if (i
< s
->nmacs
- 1)
4820 ssh2_pkt_addstring_str(s
->pktout
, ",");
4822 /* List client->server compression algorithms. */
4823 ssh2_pkt_addstring_start(s
->pktout
);
4824 assert(lenof(compressions
) > 1);
4825 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4826 for (i
= 0; i
< lenof(compressions
); i
++) {
4827 const struct ssh_compress
*c
= compressions
[i
];
4828 if (c
!= s
->preferred_comp
) {
4829 ssh2_pkt_addstring_str(s
->pktout
, ",");
4830 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4833 /* List server->client compression algorithms. */
4834 ssh2_pkt_addstring_start(s
->pktout
);
4835 assert(lenof(compressions
) > 1);
4836 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4837 for (i
= 0; i
< lenof(compressions
); i
++) {
4838 const struct ssh_compress
*c
= compressions
[i
];
4839 if (c
!= s
->preferred_comp
) {
4840 ssh2_pkt_addstring_str(s
->pktout
, ",");
4841 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4844 /* List client->server languages. Empty list. */
4845 ssh2_pkt_addstring_start(s
->pktout
);
4846 /* List server->client languages. Empty list. */
4847 ssh2_pkt_addstring_start(s
->pktout
);
4848 /* First KEX packet does _not_ follow, because we're not that brave. */
4849 ssh2_pkt_addbool(s
->pktout
, FALSE
);
4851 ssh2_pkt_adduint32(s
->pktout
, 0);
4854 ssh
->exhash
= ssh
->exhashbase
;
4855 sha_string(&ssh
->exhash
, s
->pktout
->data
+ 5, s
->pktout
->length
- 5);
4857 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
4861 if (pktin
->length
> 5)
4862 sha_string(&ssh
->exhash
, pktin
->data
+ 5, pktin
->length
- 5);
4865 * Now examine the other side's KEXINIT to see what we're up
4872 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
4873 bombout(("expected key exchange packet from server"));
4877 ssh
->hostkey
= NULL
;
4878 s
->cscipher_tobe
= NULL
;
4879 s
->sccipher_tobe
= NULL
;
4880 s
->csmac_tobe
= NULL
;
4881 s
->scmac_tobe
= NULL
;
4882 s
->cscomp_tobe
= NULL
;
4883 s
->sccomp_tobe
= NULL
;
4884 pktin
->savedpos
+= 16; /* skip garbage cookie */
4885 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
4887 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
4888 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
4891 } else if (in_commasep_string(k
->name
, str
, len
)) {
4896 sk_set_frozen(ssh
->s
, 1);
4897 askalg(ssh
->frontend
, "key-exchange algorithm",
4899 sk_set_frozen(ssh
->s
, 0);
4905 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
4906 str ? str
: "(null)"));
4909 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
4910 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
4911 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
4912 ssh
->hostkey
= hostkey_algs
[i
];
4916 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
4918 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4919 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4923 for (j
= 0; j
< c
->nciphers
; j
++) {
4924 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
4925 s
->cscipher_tobe
= c
->list
[j
];
4930 if (s
->cscipher_tobe
) {
4932 sk_set_frozen(ssh
->s
, 1);
4933 askalg(ssh
->frontend
, "client-to-server cipher",
4934 s
->cscipher_tobe
->name
);
4935 sk_set_frozen(ssh
->s
, 0);
4940 if (!s
->cscipher_tobe
) {
4941 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4942 str ? str
: "(null)"));
4946 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
4948 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4949 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4953 for (j
= 0; j
< c
->nciphers
; j
++) {
4954 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
4955 s
->sccipher_tobe
= c
->list
[j
];
4960 if (s
->sccipher_tobe
) {
4962 sk_set_frozen(ssh
->s
, 1);
4963 askalg(ssh
->frontend
, "server-to-client cipher",
4964 s
->sccipher_tobe
->name
);
4965 sk_set_frozen(ssh
->s
, 0);
4970 if (!s
->sccipher_tobe
) {
4971 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4972 str ? str
: "(null)"));
4976 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
4977 for (i
= 0; i
< s
->nmacs
; i
++) {
4978 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
4979 s
->csmac_tobe
= s
->maclist
[i
];
4983 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
4984 for (i
= 0; i
< s
->nmacs
; i
++) {
4985 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
4986 s
->scmac_tobe
= s
->maclist
[i
];
4990 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
4991 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
4992 const struct ssh_compress
*c
=
4993 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
4994 if (in_commasep_string(c
->name
, str
, len
)) {
4999 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
5000 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5001 const struct ssh_compress
*c
=
5002 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5003 if (in_commasep_string(c
->name
, str
, len
)) {
5011 * Work out the number of bits of key we will need from the key
5012 * exchange. We start with the maximum key length of either
5018 csbits
= s
->cscipher_tobe
->keylen
;
5019 scbits
= s
->sccipher_tobe
->keylen
;
5020 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5022 /* The keys only have 160-bit entropy, since they're based on
5023 * a SHA-1 hash. So cap the key size at 160 bits. */
5028 * If we're doing Diffie-Hellman group exchange, start by
5029 * requesting a group.
5031 if (!ssh
->kex
->pdata
) {
5032 logevent("Doing Diffie-Hellman group exchange");
5033 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
5035 * Work out how big a DH group we will need to allow that
5038 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
5039 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
5040 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
5041 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5044 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
5045 bombout(("expected key exchange group packet from server"));
5048 s
->p
= ssh2_pkt_getmp(pktin
);
5049 s
->g
= ssh2_pkt_getmp(pktin
);
5050 if (!s
->p
|| !s
->g
) {
5051 bombout(("unable to read mp-ints from incoming group packet"));
5054 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
5055 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
5056 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
5058 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP
;
5059 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
5060 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
5061 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
5062 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
5063 ssh
->kex
->groupname
);
5066 logevent("Doing Diffie-Hellman key exchange");
5068 * Now generate and send e for Diffie-Hellman.
5070 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
5071 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
5072 ssh2_pkt_addmp(s
->pktout
, s
->e
);
5073 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5076 if (pktin
->type
!= s
->kex_reply_value
) {
5077 bombout(("expected key exchange reply packet from server"));
5080 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5081 s
->f
= ssh2_pkt_getmp(pktin
);
5083 bombout(("unable to parse key exchange reply packet"));
5086 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5088 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
5090 sha_string(&ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
5091 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5092 sha_uint32(&ssh
->exhash
, s
->pbits
);
5093 sha_mpint(&ssh
->exhash
, s
->p
);
5094 sha_mpint(&ssh
->exhash
, s
->g
);
5096 sha_mpint(&ssh
->exhash
, s
->e
);
5097 sha_mpint(&ssh
->exhash
, s
->f
);
5098 sha_mpint(&ssh
->exhash
, s
->K
);
5099 SHA_Final(&ssh
->exhash
, s
->exchange_hash
);
5101 dh_cleanup(ssh
->kex_ctx
);
5102 ssh
->kex_ctx
= NULL
;
5105 debug(("Exchange hash is:\n"));
5106 dmemdump(s
->exchange_hash
, 20);
5109 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5111 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
5112 (char *)s
->exchange_hash
, 20)) {
5113 bombout(("Server's host key did not match the signature supplied"));
5118 * Authenticate remote host: verify host key. (We've already
5119 * checked the signature of the exchange hash.)
5121 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
5122 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
5123 sk_set_frozen(ssh
->s
, 1);
5124 verify_ssh_host_key(ssh
->frontend
,
5125 ssh
->savedhost
, ssh
->savedport
, ssh
->hostkey
->keytype
,
5126 s
->keystr
, s
->fingerprint
);
5127 sk_set_frozen(ssh
->s
, 0);
5128 if (!s
->got_session_id
) { /* don't bother logging this in rekeys */
5129 logevent("Host key fingerprint is:");
5130 logevent(s
->fingerprint
);
5132 sfree(s
->fingerprint
);
5134 ssh
->hostkey
->freekey(s
->hkey
);
5137 * The exchange hash from the very first key exchange is also
5138 * the session id, used in session key construction and
5141 if (!s
->got_session_id
) {
5142 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
5143 sizeof(s
->exchange_hash
));
5144 s
->got_session_id
= TRUE
;
5148 * Send SSH2_MSG_NEWKEYS.
5150 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
5151 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5152 ssh
->outgoing_data_size
= 0; /* start counting from here */
5155 * We've sent client NEWKEYS, so create and initialise
5156 * client-to-server session keys.
5158 if (ssh
->cs_cipher_ctx
)
5159 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
5160 ssh
->cscipher
= s
->cscipher_tobe
;
5161 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
5163 if (ssh
->cs_mac_ctx
)
5164 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
5165 ssh
->csmac
= s
->csmac_tobe
;
5166 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
5168 if (ssh
->cs_comp_ctx
)
5169 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
5170 ssh
->cscomp
= s
->cscomp_tobe
;
5171 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
5174 * Set IVs on client-to-server keys. Here we use the exchange
5175 * hash from the _first_ key exchange.
5178 unsigned char keyspace
[40];
5179 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'C',keyspace
);
5180 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
5181 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'A',keyspace
);
5182 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
5183 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'E',keyspace
);
5184 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
5187 logeventf(ssh
, "Initialised %.200s client->server encryption",
5188 ssh
->cscipher
->text_name
);
5189 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
5190 ssh
->csmac
->text_name
);
5191 if (ssh
->cscomp
->text_name
)
5192 logeventf(ssh
, "Initialised %s compression",
5193 ssh
->cscomp
->text_name
);
5196 * Now our end of the key exchange is complete, we can send all
5197 * our queued higher-layer packets.
5199 ssh
->queueing
= FALSE
;
5200 ssh2_pkt_queuesend(ssh
);
5203 * Expect SSH2_MSG_NEWKEYS from server.
5206 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
5207 bombout(("expected new-keys packet from server"));
5210 ssh
->incoming_data_size
= 0; /* start counting from here */
5213 * We've seen server NEWKEYS, so create and initialise
5214 * server-to-client session keys.
5216 if (ssh
->sc_cipher_ctx
)
5217 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
5218 ssh
->sccipher
= s
->sccipher_tobe
;
5219 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
5221 if (ssh
->sc_mac_ctx
)
5222 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
5223 ssh
->scmac
= s
->scmac_tobe
;
5224 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
5226 if (ssh
->sc_comp_ctx
)
5227 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
5228 ssh
->sccomp
= s
->sccomp_tobe
;
5229 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
5232 * Set IVs on server-to-client keys. Here we use the exchange
5233 * hash from the _first_ key exchange.
5236 unsigned char keyspace
[40];
5237 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'D',keyspace
);
5238 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
5239 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'B',keyspace
);
5240 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
5241 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'F',keyspace
);
5242 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
5244 logeventf(ssh
, "Initialised %.200s server->client encryption",
5245 ssh
->sccipher
->text_name
);
5246 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
5247 ssh
->scmac
->text_name
);
5248 if (ssh
->sccomp
->text_name
)
5249 logeventf(ssh
, "Initialised %s decompression",
5250 ssh
->sccomp
->text_name
);
5253 * Free key exchange data.
5257 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5263 * Key exchange is over. Loop straight back round if we have a
5264 * deferred rekey reason.
5266 if (ssh
->deferred_rekey_reason
) {
5267 logevent(ssh
->deferred_rekey_reason
);
5269 ssh
->deferred_rekey_reason
= NULL
;
5270 goto begin_key_exchange
;
5274 * Otherwise, schedule a timer for our next rekey.
5276 ssh
->kex_in_progress
= FALSE
;
5277 ssh
->last_rekey
= GETTICKCOUNT();
5278 if (ssh
->cfg
.ssh_rekey_time
!= 0)
5279 ssh
->next_rekey
= schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
5283 * If this is the first key exchange phase, we must pass the
5284 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5285 * wants to see it but because it will need time to initialise
5286 * itself before it sees an actual packet. In subsequent key
5287 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5288 * it would only confuse the layer above.
5290 if (s
->activated_authconn
) {
5293 s
->activated_authconn
= TRUE
;
5296 * Now we're encrypting. Begin returning 1 to the protocol main
5297 * function so that other things can run on top of the
5298 * transport. If we ever see a KEXINIT, we must go back to the
5301 * We _also_ go back to the start if we see pktin==NULL and
5302 * inlen==-1, because this is a special signal meaning
5303 * `initiate client-driven rekey', and `in' contains a message
5304 * giving the reason for the rekey.
5306 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
5307 (!pktin
&& inlen
== -1))) {
5311 logevent("Server initiated key re-exchange");
5313 logevent((char *)in
);
5315 goto begin_key_exchange
;
5321 * Add data to an SSH2 channel output buffer.
5323 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
5326 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
5330 * Attempt to send data on an SSH2 channel.
5332 static int ssh2_try_send(struct ssh_channel
*c
)
5335 struct Packet
*pktout
;
5337 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
5340 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
5341 if ((unsigned)len
> c
->v
.v2
.remwindow
)
5342 len
= c
->v
.v2
.remwindow
;
5343 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
5344 len
= c
->v
.v2
.remmaxpkt
;
5345 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
5346 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5347 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
5348 ssh2_pkt_addstring_start(pktout
);
5349 ssh2_pkt_addstring_data(pktout
, data
, len
);
5350 end_log_omission(ssh
, pktout
);
5351 ssh2_pkt_send(ssh
, pktout
);
5352 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
5353 c
->v
.v2
.remwindow
-= len
;
5357 * After having sent as much data as we can, return the amount
5360 return bufchain_size(&c
->v
.v2
.outbuffer
);
5364 * Potentially enlarge the window on an SSH2 channel.
5366 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
5371 * Never send WINDOW_ADJUST for a channel that the remote side
5372 * already thinks it's closed; there's no point, since it won't
5373 * be sending any more data anyway.
5378 if (newwin
> c
->v
.v2
.locwindow
) {
5379 struct Packet
*pktout
;
5381 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5382 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5383 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
5384 ssh2_pkt_send(ssh
, pktout
);
5385 c
->v
.v2
.locwindow
= newwin
;
5389 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
5391 unsigned i
= ssh_pkt_getuint32(pktin
);
5392 struct ssh_channel
*c
;
5393 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5394 if (c
&& !c
->closes
)
5395 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
5398 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
5401 unsigned int length
;
5402 unsigned i
= ssh_pkt_getuint32(pktin
);
5403 struct ssh_channel
*c
;
5404 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5406 return; /* nonexistent channel */
5407 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5408 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
5409 return; /* extended but not stderr */
5410 ssh_pkt_getstring(pktin
, &data
, &length
);
5413 c
->v
.v2
.locwindow
-= length
;
5415 case CHAN_MAINSESSION
:
5417 from_backend(ssh
->frontend
, pktin
->type
==
5418 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5422 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5425 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5428 while (length
> 0) {
5429 if (c
->u
.a
.lensofar
< 4) {
5430 unsigned int l
= min(4 - c
->u
.a
.lensofar
, length
);
5431 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5435 c
->u
.a
.lensofar
+= l
;
5437 if (c
->u
.a
.lensofar
== 4) {
5439 4 + GET_32BIT(c
->u
.a
.msglen
);
5440 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
5442 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5444 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5446 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5448 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5452 c
->u
.a
.lensofar
+= l
;
5454 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5457 if (agent_query(c
->u
.a
.message
,
5460 ssh_agentf_callback
, c
))
5461 ssh_agentf_callback(c
, reply
, replylen
);
5462 sfree(c
->u
.a
.message
);
5463 c
->u
.a
.lensofar
= 0;
5470 * If we are not buffering too much data,
5471 * enlarge the window again at the remote side.
5473 if (bufsize
< OUR_V2_WINSIZE
)
5474 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5478 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
5480 unsigned i
= ssh_pkt_getuint32(pktin
);
5481 struct ssh_channel
*c
;
5483 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5485 return; /* nonexistent channel */
5487 if (c
->type
== CHAN_X11
) {
5489 * Remote EOF on an X11 channel means we should
5490 * wrap up and close the channel ourselves.
5492 x11_close(c
->u
.x11
.s
);
5494 } else if (c
->type
== CHAN_AGENT
) {
5496 } else if (c
->type
== CHAN_SOCKDATA
) {
5497 pfd_close(c
->u
.pfd
.s
);
5502 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
5504 unsigned i
= ssh_pkt_getuint32(pktin
);
5505 struct ssh_channel
*c
;
5506 struct Packet
*pktout
;
5508 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5509 if (!c
|| ((int)c
->remoteid
) == -1) {
5510 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5511 c ?
"half-open" : "nonexistent", i
));
5514 /* Do pre-close processing on the channel. */
5516 case CHAN_MAINSESSION
:
5517 ssh
->mainchan
= NULL
;
5518 update_specials_menu(ssh
->frontend
);
5521 if (c
->u
.x11
.s
!= NULL
)
5522 x11_close(c
->u
.x11
.s
);
5529 if (c
->u
.pfd
.s
!= NULL
)
5530 pfd_close(c
->u
.pfd
.s
);
5534 if (c
->closes
== 0) {
5535 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5536 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5537 ssh2_pkt_send(ssh
, pktout
);
5539 del234(ssh
->channels
, c
);
5540 bufchain_clear(&c
->v
.v2
.outbuffer
);
5544 * See if that was the last channel left open.
5545 * (This is only our termination condition if we're
5546 * not running in -N mode.)
5548 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
5549 logevent("All channels closed. Disconnecting");
5552 * We used to send SSH_MSG_DISCONNECT here,
5553 * because I'd believed that _every_ conforming
5554 * SSH2 connection had to end with a disconnect
5555 * being sent by at least one side; apparently
5556 * I was wrong and it's perfectly OK to
5557 * unceremoniously slam the connection shut
5558 * when you're done, and indeed OpenSSH feels
5559 * this is more polite than sending a
5560 * DISCONNECT. So now we don't.
5562 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5563 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
5564 ssh2_pkt_addstring(s
->pktout
, "All open channels closed");
5565 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
5566 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5568 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5572 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
5574 unsigned i
= ssh_pkt_getuint32(pktin
);
5575 struct ssh_channel
*c
;
5576 struct Packet
*pktout
;
5578 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5580 return; /* nonexistent channel */
5581 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5582 return; /* dunno why they're confirming this */
5583 c
->remoteid
= ssh_pkt_getuint32(pktin
);
5584 c
->type
= CHAN_SOCKDATA
;
5585 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
5586 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
5588 pfd_confirm(c
->u
.pfd
.s
);
5591 * We have a pending close on this channel,
5592 * which we decided on before the server acked
5593 * the channel open. So now we know the
5594 * remoteid, we can close it again.
5596 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5597 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5598 ssh2_pkt_send(ssh
, pktout
);
5602 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
5604 static const char *const reasons
[] = {
5605 "<unknown reason code>",
5606 "Administratively prohibited",
5608 "Unknown channel type",
5609 "Resource shortage",
5611 unsigned i
= ssh_pkt_getuint32(pktin
);
5612 unsigned reason_code
;
5613 char *reason_string
;
5616 struct ssh_channel
*c
;
5617 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5619 return; /* nonexistent channel */
5620 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5621 return; /* dunno why they're failing this */
5623 reason_code
= ssh_pkt_getuint32(pktin
);
5624 if (reason_code
>= lenof(reasons
))
5625 reason_code
= 0; /* ensure reasons[reason_code] in range */
5626 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
5627 message
= dupprintf("Forwarded connection refused by"
5628 " server: %s [%.*s]", reasons
[reason_code
],
5629 reason_length
, reason_string
);
5633 pfd_close(c
->u
.pfd
.s
);
5635 del234(ssh
->channels
, c
);
5639 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
5643 int typelen
, want_reply
;
5644 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
5645 struct ssh_channel
*c
;
5646 struct Packet
*pktout
;
5648 localid
= ssh_pkt_getuint32(pktin
);
5649 ssh_pkt_getstring(pktin
, &type
, &typelen
);
5650 want_reply
= ssh2_pkt_getbool(pktin
);
5653 * First, check that the channel exists. Otherwise,
5654 * we can instantly disconnect with a rude message.
5656 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
5659 sprintf(buf
, "Received channel request for nonexistent"
5660 " channel %d", localid
);
5662 pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5663 ssh2_pkt_adduint32(pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
5664 ssh2_pkt_addstring(pktout
, buf
);
5665 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
5666 ssh2_pkt_send_noqueue(ssh
, pktout
);
5667 connection_fatal(ssh
->frontend
, "%s", buf
);
5668 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5673 * Having got the channel number, we now look at
5674 * the request type string to see if it's something
5677 if (c
== ssh
->mainchan
) {
5679 * We recognise "exit-status" and "exit-signal" on
5680 * the primary channel.
5682 if (typelen
== 11 &&
5683 !memcmp(type
, "exit-status", 11)) {
5685 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
5686 logeventf(ssh
, "Server sent command exit status %d",
5688 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
5690 } else if (typelen
== 11 &&
5691 !memcmp(type
, "exit-signal", 11)) {
5693 int is_plausible
= TRUE
, is_int
= FALSE
;
5694 char *fmt_sig
= "", *fmt_msg
= "";
5696 int msglen
= 0, core
= FALSE
;
5697 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
5698 * provide an `int' for the signal, despite its
5699 * having been a `string' in the drafts since at
5700 * least 2001. (Fixed in session.c 1.147.) Try to
5701 * infer which we can safely parse it as. */
5703 unsigned char *p
= pktin
->body
+
5705 long len
= pktin
->length
- pktin
->savedpos
;
5706 unsigned long num
= GET_32BIT(p
); /* what is it? */
5707 /* If it's 0, it hardly matters; assume string */
5711 int maybe_int
= FALSE
, maybe_str
= FALSE
;
5712 #define CHECK_HYPOTHESIS(offset, result) \
5715 if (q >= 0 && q+4 <= len) { \
5716 q = q + 4 + GET_32BIT(p+q); \
5717 if (q >= 0 && q+4 <= len && \
5718 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
5722 CHECK_HYPOTHESIS(4+1, maybe_int
);
5723 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
5724 #undef CHECK_HYPOTHESIS
5725 if (maybe_int
&& !maybe_str
)
5727 else if (!maybe_int
&& maybe_str
)
5730 /* Crikey. Either or neither. Panic. */
5731 is_plausible
= FALSE
;
5736 /* Old non-standard OpenSSH. */
5737 int signum
= ssh_pkt_getuint32(pktin
);
5738 fmt_sig
= dupprintf(" %d", signum
);
5740 /* As per the drafts. */
5743 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
5744 /* Signal name isn't supposed to be blank, but
5745 * let's cope gracefully if it is. */
5747 fmt_sig
= dupprintf(" \"%.*s\"",
5751 core
= ssh2_pkt_getbool(pktin
);
5752 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5754 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
5756 /* ignore lang tag */
5757 } /* else don't attempt to parse */
5758 logeventf(ssh
, "Server exited on signal%s%s%s",
5759 fmt_sig
, core ?
" (core dumped)" : "",
5761 if (*fmt_sig
) sfree(fmt_sig
);
5762 if (*fmt_msg
) sfree(fmt_msg
);
5763 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
5768 * This is a channel request we don't know
5769 * about, so we now either ignore the request
5770 * or respond with CHANNEL_FAILURE, depending
5773 reply
= SSH2_MSG_CHANNEL_FAILURE
;
5776 pktout
= ssh2_pkt_init(reply
);
5777 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5778 ssh2_pkt_send(ssh
, pktout
);
5782 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
5785 int typelen
, want_reply
;
5786 struct Packet
*pktout
;
5788 ssh_pkt_getstring(pktin
, &type
, &typelen
);
5789 want_reply
= ssh2_pkt_getbool(pktin
);
5792 * We currently don't support any global requests
5793 * at all, so we either ignore the request or
5794 * respond with REQUEST_FAILURE, depending on
5798 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
5799 ssh2_pkt_send(ssh
, pktout
);
5803 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
5811 struct ssh_channel
*c
;
5812 unsigned remid
, winsize
, pktsize
;
5813 struct Packet
*pktout
;
5815 ssh_pkt_getstring(pktin
, &type
, &typelen
);
5816 c
= snew(struct ssh_channel
);
5819 remid
= ssh_pkt_getuint32(pktin
);
5820 winsize
= ssh_pkt_getuint32(pktin
);
5821 pktsize
= ssh_pkt_getuint32(pktin
);
5823 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5826 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
5827 addrstr
= snewn(peeraddrlen
+1, char);
5828 memcpy(addrstr
, peeraddr
, peeraddrlen
);
5829 addrstr
[peeraddrlen
] = '\0';
5830 peerport
= ssh_pkt_getuint32(pktin
);
5832 logeventf(ssh
, "Received X11 connect request from %s:%d",
5835 if (!ssh
->X11_fwd_enabled
)
5836 error
= "X11 forwarding is not enabled";
5837 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
5838 ssh
->x11auth
, addrstr
, peerport
,
5839 &ssh
->cfg
) != NULL
) {
5840 error
= "Unable to open an X11 connection";
5842 logevent("Opening X11 forward connection succeeded");
5847 } else if (typelen
== 15 &&
5848 !memcmp(type
, "forwarded-tcpip", 15)) {
5849 struct ssh_rportfwd pf
, *realpf
;
5852 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
5853 pf
.sport
= ssh_pkt_getuint32(pktin
);
5854 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
5855 peerport
= ssh_pkt_getuint32(pktin
);
5856 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
5857 logeventf(ssh
, "Received remote port %d open request "
5858 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
5859 if (realpf
== NULL
) {
5860 error
= "Remote port is not recognised";
5862 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
5866 realpf
->pfrec
->addressfamily
);
5867 logeventf(ssh
, "Attempting to forward remote port to "
5868 "%s:%d", realpf
->dhost
, realpf
->dport
);
5870 logeventf(ssh
, "Port open failed: %s", e
);
5871 error
= "Port open failed";
5873 logevent("Forwarded port opened successfully");
5874 c
->type
= CHAN_SOCKDATA
;
5877 } else if (typelen
== 22 &&
5878 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5879 if (!ssh
->agentfwd_enabled
)
5880 error
= "Agent forwarding is not enabled";
5882 c
->type
= CHAN_AGENT
; /* identify channel type */
5883 c
->u
.a
.lensofar
= 0;
5886 error
= "Unsupported channel type requested";
5889 c
->remoteid
= remid
;
5891 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5892 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5893 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
5894 ssh2_pkt_addstring(pktout
, error
);
5895 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
5896 ssh2_pkt_send(ssh
, pktout
);
5897 logeventf(ssh
, "Rejected channel open: %s", error
);
5900 c
->localid
= alloc_channel_id(ssh
);
5902 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5903 c
->v
.v2
.remwindow
= winsize
;
5904 c
->v
.v2
.remmaxpkt
= pktsize
;
5905 bufchain_init(&c
->v
.v2
.outbuffer
);
5906 add234(ssh
->channels
, c
);
5907 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5908 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5909 ssh2_pkt_adduint32(pktout
, c
->localid
);
5910 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
5911 ssh2_pkt_adduint32(pktout
, 0x4000UL
); /* our max pkt size */
5912 ssh2_pkt_send(ssh
, pktout
);
5917 * Handle the SSH2 userauth and connection layers.
5919 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
5920 struct Packet
*pktin
)
5922 struct do_ssh2_authconn_state
{
5924 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
5926 AUTH_KEYBOARD_INTERACTIVE
5930 AUTH_TYPE_PUBLICKEY
,
5931 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
5932 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
5934 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
5935 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
5937 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
5938 int tried_pubkey_config
, tried_agent
;
5939 int kbd_inter_running
, kbd_inter_refused
;
5941 int num_prompts
, curr_prompt
, echo
;
5946 void *publickey_blob
;
5947 int publickey_bloblen
;
5948 unsigned char request
[5], *response
, *p
;
5952 char *pkblob
, *alg
, *commentp
;
5953 int pklen
, alglen
, commentlen
;
5954 int siglen
, retlen
, len
;
5955 char *q
, *agentreq
, *ret
;
5957 int num_env
, env_left
, env_ok
;
5958 struct Packet
*pktout
;
5960 crState(do_ssh2_authconn_state
);
5962 crBegin(ssh
->do_ssh2_authconn_crstate
);
5965 * Request userauth protocol, and await a response to it.
5967 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
5968 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
5969 ssh2_pkt_send(ssh
, s
->pktout
);
5970 crWaitUntilV(pktin
);
5971 if (pktin
->type
!= SSH2_MSG_SERVICE_ACCEPT
) {
5972 bombout(("Server refused user authentication protocol"));
5977 * We repeat this whole loop, including the username prompt,
5978 * until we manage a successful authentication. If the user
5979 * types the wrong _password_, they can be sent back to the
5980 * beginning to try another username, if this is configured on.
5981 * (If they specify a username in the config, they are never
5982 * asked, even if they do give a wrong password.)
5984 * I think this best serves the needs of
5986 * - the people who have no configuration, no keys, and just
5987 * want to try repeated (username,password) pairs until they
5988 * type both correctly
5990 * - people who have keys and configuration but occasionally
5991 * need to fall back to passwords
5993 * - people with a key held in Pageant, who might not have
5994 * logged in to a particular machine before; so they want to
5995 * type a username, and then _either_ their key will be
5996 * accepted, _or_ they will type a password. If they mistype
5997 * the username they will want to be able to get back and
6000 s
->username
[0] = '\0';
6001 s
->got_username
= FALSE
;
6006 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
6008 * We got a username last time round this loop, and
6009 * with change_username turned off we don't try to get
6012 } else if (!*ssh
->cfg
.username
) {
6013 if (ssh_get_line
&& !ssh_getline_pw_only
) {
6014 if (!ssh_get_line("login as: ",
6015 s
->username
, sizeof(s
->username
), FALSE
)) {
6017 * get_line failed to get a username.
6020 logevent("No username provided. Abandoning session.");
6021 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6025 int ret
; /* need not be saved across crReturn */
6026 c_write_str(ssh
, "login as: ");
6028 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
6030 crWaitUntilV(!pktin
);
6031 ret
= process_userpass_input(ssh
, in
, inlen
);
6035 c_write_str(ssh
, "\r\n");
6037 s
->username
[strcspn(s
->username
, "\n\r")] = '\0';
6040 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
6041 s
->username
[sizeof(s
->username
)-1] = '\0';
6042 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
6043 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
6044 c_write_str(ssh
, stuff
);
6048 s
->got_username
= TRUE
;
6051 * Send an authentication request using method "none": (a)
6052 * just in case it succeeds, and (b) so that we know what
6053 * authentication methods we can usefully try next.
6055 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6057 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6058 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6059 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
6060 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
6061 ssh2_pkt_send(ssh
, s
->pktout
);
6062 s
->type
= AUTH_TYPE_NONE
;
6064 s
->we_are_in
= FALSE
;
6066 s
->tried_pubkey_config
= FALSE
;
6067 s
->tried_agent
= FALSE
;
6068 s
->kbd_inter_running
= FALSE
;
6069 s
->kbd_inter_refused
= FALSE
;
6070 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6071 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
6073 logeventf(ssh
, "Reading private key file \"%.150s\"",
6074 filename_to_str(&ssh
->cfg
.keyfile
));
6075 keytype
= key_type(&ssh
->cfg
.keyfile
);
6076 if (keytype
== SSH_KEYTYPE_SSH2
) {
6078 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
, NULL
,
6079 &s
->publickey_bloblen
, NULL
);
6082 logeventf(ssh
, "Unable to use this key file (%s)",
6083 key_type_to_str(keytype
));
6084 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
6086 filename_to_str(&ssh
->cfg
.keyfile
),
6087 key_type_to_str(keytype
));
6088 c_write_str(ssh
, msgbuf
);
6090 s
->publickey_blob
= NULL
;
6093 s
->publickey_blob
= NULL
;
6097 * Wait for the result of the last authentication request.
6100 crWaitUntilV(pktin
);
6101 while (pktin
->type
== SSH2_MSG_USERAUTH_BANNER
) {
6105 * Don't show the banner if we're operating in
6106 * non-verbose non-interactive mode. (It's probably
6107 * a script, which means nobody will read the
6108 * banner _anyway_, and moreover the printing of
6109 * the banner will screw up processing on the
6110 * output of (say) plink.)
6112 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
6113 ssh_pkt_getstring(pktin
, &banner
, &size
);
6115 c_write_untrusted(ssh
, banner
, size
);
6117 crWaitUntilV(pktin
);
6119 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
6120 logevent("Access granted");
6121 s
->we_are_in
= TRUE
;
6125 if (s
->kbd_inter_running
&&
6126 pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
6128 * This is either a further set-of-prompts packet
6129 * in keyboard-interactive authentication, or it's
6130 * the same one and we came back here with `gotit'
6131 * set. In the former case, we must reset the
6132 * curr_prompt variable.
6136 } else if (pktin
->type
== SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
) {
6137 /* FIXME: perhaps we should support this? */
6138 bombout(("PASSWD_CHANGEREQ not yet supported"));
6140 } else if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
) {
6141 bombout(("Strange packet received during authentication: type %d",
6149 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6150 * we can look at the string in it and know what we can
6151 * helpfully try next.
6153 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
6156 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
6157 s
->kbd_inter_running
= FALSE
;
6158 if (!ssh2_pkt_getbool(pktin
)) {
6160 * We have received an unequivocal Access
6161 * Denied. This can translate to a variety of
6164 * - if we'd just tried "none" authentication,
6165 * it's not worth printing anything at all
6167 * - if we'd just tried a public key _offer_,
6168 * the message should be "Server refused our
6169 * key" (or no message at all if the key
6170 * came from Pageant)
6172 * - if we'd just tried anything else, the
6173 * message really should be "Access denied".
6175 * Additionally, if we'd just tried password
6176 * authentication, we should break out of this
6177 * whole loop so as to go back to the username
6178 * prompt (iff we're configured to allow
6179 * username change attempts).
6181 if (s
->type
== AUTH_TYPE_NONE
) {
6183 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
6184 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
6185 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
6186 c_write_str(ssh
, "Server refused our key\r\n");
6187 logevent("Server refused public key");
6188 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
6189 /* server declined keyboard-interactive; ignore */
6191 c_write_str(ssh
, "Access denied\r\n");
6192 logevent("Access denied");
6193 if (s
->type
== AUTH_TYPE_PASSWORD
&&
6194 ssh
->cfg
.change_username
) {
6195 /* XXX perhaps we should allow
6196 * keyboard-interactive to do this too? */
6197 s
->we_are_in
= FALSE
;
6202 c_write_str(ssh
, "Further authentication required\r\n");
6203 logevent("Further authentication required");
6207 in_commasep_string("publickey", methods
, methlen
);
6209 in_commasep_string("password", methods
, methlen
);
6210 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
6211 in_commasep_string("keyboard-interactive", methods
, methlen
);
6215 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6219 * Most password/passphrase prompts will be
6220 * non-echoing, so we set this to 0 by default.
6221 * Exception is that some keyboard-interactive prompts
6222 * can be echoing, in which case we'll set this to 1.
6226 if (!s
->method
&& s
->can_pubkey
&&
6227 agent_exists() && !s
->tried_agent
) {
6229 * Attempt public-key authentication using Pageant.
6234 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6235 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6237 s
->tried_agent
= TRUE
;
6239 logevent("Pageant is running. Requesting keys.");
6241 /* Request the keys held by the agent. */
6242 PUT_32BIT(s
->request
, 1);
6243 s
->request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
6244 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
6245 ssh_agent_callback
, ssh
)) {
6249 bombout(("Unexpected data from server while"
6250 " waiting for agent response"));
6253 } while (pktin
|| inlen
> 0);
6254 r
= ssh
->agent_response
;
6255 s
->responselen
= ssh
->agent_response_len
;
6257 s
->response
= (unsigned char *) r
;
6258 if (s
->response
&& s
->responselen
>= 5 &&
6259 s
->response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
6260 s
->p
= s
->response
+ 5;
6261 s
->nkeys
= GET_32BIT(s
->p
);
6265 sprintf(buf
, "Pageant has %d SSH2 keys", s
->nkeys
);
6268 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
6273 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
6276 s
->pklen
= GET_32BIT(s
->p
);
6278 if (s
->publickey_blob
&&
6279 s
->pklen
== s
->publickey_bloblen
&&
6280 !memcmp(s
->p
, s
->publickey_blob
,
6281 s
->publickey_bloblen
)) {
6282 logevent("This key matches configured key file");
6283 s
->tried_pubkey_config
= 1;
6285 s
->pkblob
= (char *)s
->p
;
6287 s
->alglen
= GET_32BIT(s
->pkblob
);
6288 s
->alg
= s
->pkblob
+ 4;
6289 s
->commentlen
= GET_32BIT(s
->p
);
6291 s
->commentp
= (char *)s
->p
;
6292 s
->p
+= s
->commentlen
;
6293 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6294 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6295 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6296 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6297 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6298 ssh2_pkt_addstring_start(s
->pktout
);
6299 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6300 ssh2_pkt_addstring_start(s
->pktout
);
6301 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6302 ssh2_pkt_send(ssh
, s
->pktout
);
6304 crWaitUntilV(pktin
);
6305 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6306 logevent("Key refused");
6310 if (flags
& FLAG_VERBOSE
) {
6311 c_write_str(ssh
, "Authenticating with "
6313 c_write(ssh
, s
->commentp
, s
->commentlen
);
6314 c_write_str(ssh
, "\" from agent\r\n");
6318 * Server is willing to accept the key.
6319 * Construct a SIGN_REQUEST.
6321 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6322 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6323 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6324 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6325 ssh2_pkt_addbool(s
->pktout
, TRUE
);
6326 ssh2_pkt_addstring_start(s
->pktout
);
6327 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6328 ssh2_pkt_addstring_start(s
->pktout
);
6329 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6331 s
->siglen
= s
->pktout
->length
- 5 + 4 + 20;
6332 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
6334 s
->len
= 1; /* message type */
6335 s
->len
+= 4 + s
->pklen
; /* key blob */
6336 s
->len
+= 4 + s
->siglen
; /* data to sign */
6337 s
->len
+= 4; /* flags */
6338 s
->agentreq
= snewn(4 + s
->len
, char);
6339 PUT_32BIT(s
->agentreq
, s
->len
);
6340 s
->q
= s
->agentreq
+ 4;
6341 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
6342 PUT_32BIT(s
->q
, s
->pklen
);
6344 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
6346 PUT_32BIT(s
->q
, s
->siglen
);
6348 /* Now the data to be signed... */
6349 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
6350 PUT_32BIT(s
->q
, 20);
6353 memcpy(s
->q
, ssh
->v2_session_id
, 20);
6355 memcpy(s
->q
, s
->pktout
->data
+ 5,
6356 s
->pktout
->length
- 5);
6357 s
->q
+= s
->pktout
->length
- 5;
6358 /* And finally the (zero) flags word. */
6360 if (!agent_query(s
->agentreq
, s
->len
+ 4,
6362 ssh_agent_callback
, ssh
)) {
6366 bombout(("Unexpected data from server"
6367 " while waiting for agent"
6371 } while (pktin
|| inlen
> 0);
6372 vret
= ssh
->agent_response
;
6373 s
->retlen
= ssh
->agent_response_len
;
6378 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
6379 logevent("Sending Pageant's response");
6380 ssh2_add_sigblob(ssh
, s
->pktout
,
6381 s
->pkblob
, s
->pklen
,
6383 GET_32BIT(s
->ret
+ 5));
6384 ssh2_pkt_send(ssh
, s
->pktout
);
6389 ("Pageant failed to answer challenge");
6400 if (!s
->method
&& s
->can_pubkey
&& s
->publickey_blob
6401 && !s
->tried_pubkey_config
) {
6402 unsigned char *pub_blob
;
6403 char *algorithm
, *comment
;
6406 s
->tried_pubkey_config
= TRUE
;
6408 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6409 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6412 * Try the public key supplied in the configuration.
6414 * First, offer the public blob to see if the server is
6415 * willing to accept it.
6418 (unsigned char *)ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
6423 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6424 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6425 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6426 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6427 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6428 ssh2_pkt_addstring(s
->pktout
, algorithm
);
6429 ssh2_pkt_addstring_start(s
->pktout
);
6430 ssh2_pkt_addstring_data(s
->pktout
, (char *)pub_blob
,
6432 ssh2_pkt_send(ssh
, s
->pktout
);
6433 logevent("Offered public key");
6435 crWaitUntilV(pktin
);
6436 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6438 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
6439 continue; /* key refused; give up on it */
6442 logevent("Offer of public key accepted");
6444 * Actually attempt a serious authentication using
6447 if (ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
6448 sprintf(s
->pwprompt
,
6449 "Passphrase for key \"%.100s\": ",
6455 if (flags
& FLAG_VERBOSE
) {
6456 c_write_str(ssh
, "Authenticating with public key \"");
6457 c_write_str(ssh
, comment
);
6458 c_write_str(ssh
, "\"\r\n");
6460 s
->method
= AUTH_PUBLICKEY_FILE
;
6464 if (!s
->method
&& s
->can_keyb_inter
&& !s
->kbd_inter_refused
) {
6465 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
6466 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6468 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6469 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
6471 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6472 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6473 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6474 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive"); /* method */
6475 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
6476 ssh2_pkt_addstring(s
->pktout
, "");
6477 ssh2_pkt_send(ssh
, s
->pktout
);
6479 crWaitUntilV(pktin
);
6480 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
6481 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
6483 logevent("Keyboard-interactive authentication refused");
6484 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
6485 s
->kbd_inter_refused
= TRUE
; /* don't try it again */
6489 s
->kbd_inter_running
= TRUE
;
6493 if (s
->kbd_inter_running
) {
6494 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
6495 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6497 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6498 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
6500 if (s
->curr_prompt
== 0) {
6502 * We've got a fresh USERAUTH_INFO_REQUEST.
6503 * Display header data, and start going through
6506 char *name
, *inst
, *lang
;
6507 int name_len
, inst_len
, lang_len
;
6509 ssh_pkt_getstring(pktin
, &name
, &name_len
);
6510 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
6511 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
6513 c_write_untrusted(ssh
, name
, name_len
);
6514 c_write_str(ssh
, "\r\n");
6517 c_write_untrusted(ssh
, inst
, inst_len
);
6518 c_write_str(ssh
, "\r\n");
6520 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
6524 * If there are prompts remaining in the packet,
6525 * display one and get a response.
6527 if (s
->curr_prompt
< s
->num_prompts
) {
6531 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
6532 if (prompt_len
> 0) {
6533 static const char trunc
[] = "<prompt truncated>: ";
6534 static const int prlen
= sizeof(s
->pwprompt
) -
6536 if (prompt_len
> prlen
) {
6537 memcpy(s
->pwprompt
, prompt
, prlen
);
6538 strcpy(s
->pwprompt
+ prlen
, trunc
);
6540 memcpy(s
->pwprompt
, prompt
, prompt_len
);
6541 s
->pwprompt
[prompt_len
] = '\0';
6545 "<server failed to send prompt>: ");
6547 s
->echo
= ssh2_pkt_getbool(pktin
);
6553 if (!s
->method
&& s
->can_passwd
) {
6554 s
->method
= AUTH_PASSWORD
;
6555 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6556 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
6557 sprintf(s
->pwprompt
, "%.90s@%.90s's password: ", s
->username
,
6564 if (!ssh_get_line(s
->pwprompt
, s
->password
,
6565 sizeof(s
->password
), TRUE
)) {
6567 * get_line failed to get a password (for
6568 * example because one was supplied on the
6569 * command line which has already failed to
6572 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
6573 ssh2_pkt_adduint32(s
->pktout
,SSH2_DISCONNECT_BY_APPLICATION
);
6574 ssh2_pkt_addstring(s
->pktout
, "No more passwords available"
6576 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6577 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6578 logevent("Unable to authenticate");
6579 connection_fatal(ssh
->frontend
,
6580 "Unable to authenticate");
6581 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6585 int ret
; /* need not be saved across crReturn */
6586 c_write_untrusted(ssh
, s
->pwprompt
, strlen(s
->pwprompt
));
6589 setup_userpass_input(ssh
, s
->password
,
6590 sizeof(s
->password
), s
->echo
);
6592 crWaitUntilV(!pktin
);
6593 ret
= process_userpass_input(ssh
, in
, inlen
);
6597 c_write_str(ssh
, "\r\n");
6601 if (s
->method
== AUTH_PUBLICKEY_FILE
) {
6603 * We have our passphrase. Now try the actual authentication.
6605 struct ssh2_userkey
*key
;
6606 const char *error
= NULL
;
6608 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, s
->password
,
6610 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
6611 if (key
== SSH2_WRONG_PASSPHRASE
) {
6612 c_write_str(ssh
, "Wrong passphrase\r\n");
6613 s
->tried_pubkey_config
= FALSE
;
6615 c_write_str(ssh
, "Unable to load private key (");
6616 c_write_str(ssh
, error
);
6617 c_write_str(ssh
, ")\r\n");
6618 s
->tried_pubkey_config
= TRUE
;
6620 /* Send a spurious AUTH_NONE to return to the top. */
6621 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6622 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6623 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6624 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
6625 ssh2_pkt_send(ssh
, s
->pktout
);
6626 s
->type
= AUTH_TYPE_NONE
;
6628 unsigned char *pkblob
, *sigblob
, *sigdata
;
6629 int pkblob_len
, sigblob_len
, sigdata_len
;
6633 * We have loaded the private key and the server
6634 * has announced that it's willing to accept it.
6635 * Hallelujah. Generate a signature and send it.
6637 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6638 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6639 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6640 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6641 ssh2_pkt_addbool(s
->pktout
, TRUE
);
6642 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
6643 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
6644 ssh2_pkt_addstring_start(s
->pktout
);
6645 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
, pkblob_len
);
6648 * The data to be signed is:
6652 * followed by everything so far placed in the
6655 sigdata_len
= s
->pktout
->length
- 5 + 4 + 20;
6656 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
6658 sigdata
= snewn(sigdata_len
, unsigned char);
6660 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
6661 PUT_32BIT(sigdata
+p
, 20);
6664 memcpy(sigdata
+p
, ssh
->v2_session_id
, 20); p
+= 20;
6665 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
6666 s
->pktout
->length
- 5);
6667 p
+= s
->pktout
->length
- 5;
6668 assert(p
== sigdata_len
);
6669 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
6670 sigdata_len
, &sigblob_len
);
6671 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
6672 sigblob
, sigblob_len
);
6677 ssh2_pkt_send(ssh
, s
->pktout
);
6678 s
->type
= AUTH_TYPE_PUBLICKEY
;
6679 key
->alg
->freekey(key
->data
);
6681 } else if (s
->method
== AUTH_PASSWORD
) {
6683 * We send the password packet lumped tightly together with
6684 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
6685 * string long enough to make the total length of the two
6686 * packets constant. This should ensure that a passive
6687 * listener doing traffic analyis can't work out the length
6690 * For this to work, we need an assumption about the
6691 * maximum length of the password packet. I think 256 is
6692 * pretty conservative. Anyone using a password longer than
6693 * that probably doesn't have much to worry about from
6694 * people who find out how long their password is!
6696 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6697 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6698 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6699 ssh2_pkt_addstring(s
->pktout
, "password");
6700 ssh2_pkt_addbool(s
->pktout
, FALSE
);
6701 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
6702 ssh2_pkt_addstring(s
->pktout
, s
->password
);
6703 memset(s
->password
, 0, sizeof(s
->password
));
6704 end_log_omission(ssh
, s
->pktout
);
6705 ssh2_pkt_defer(ssh
, s
->pktout
);
6707 * We'll include a string that's an exact multiple of the
6708 * cipher block size. If the cipher is NULL for some
6709 * reason, we don't do this trick at all because we gain
6712 if (ssh
->cscipher
) {
6715 stringlen
= (256 - ssh
->deferred_len
);
6716 stringlen
+= ssh
->cscipher
->blksize
- 1;
6717 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
6720 * Temporarily disable actual compression,
6721 * so we can guarantee to get this string
6722 * exactly the length we want it. The
6723 * compression-disabling routine should
6724 * return an integer indicating how many
6725 * bytes we should adjust our string length
6729 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
6731 s
->pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
6732 ssh2_pkt_addstring_start(s
->pktout
);
6733 for (i
= 0; i
< stringlen
; i
++) {
6734 char c
= (char) random_byte();
6735 ssh2_pkt_addstring_data(s
->pktout
, &c
, 1);
6737 ssh2_pkt_defer(ssh
, s
->pktout
);
6739 ssh_pkt_defersend(ssh
);
6740 logevent("Sent password");
6741 s
->type
= AUTH_TYPE_PASSWORD
;
6742 } else if (s
->method
== AUTH_KEYBOARD_INTERACTIVE
) {
6743 if (s
->curr_prompt
== 0) {
6744 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
6745 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
6747 if (s
->need_pw
) { /* only add pw if we just got one! */
6748 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
6749 ssh2_pkt_addstring(s
->pktout
, s
->password
);
6750 memset(s
->password
, 0, sizeof(s
->password
));
6751 end_log_omission(ssh
, s
->pktout
);
6754 if (s
->curr_prompt
>= s
->num_prompts
) {
6755 ssh2_pkt_send(ssh
, s
->pktout
);
6758 * If there are prompts remaining, we set
6759 * `gotit' so that we won't attempt to get
6760 * another packet. Then we go back round the
6761 * loop and will end up retrieving another
6762 * prompt out of the existing packet. Funky or
6767 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6769 c_write_str(ssh
, "No supported authentication methods"
6770 " left to try!\r\n");
6771 logevent("No supported authentications offered."
6773 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
6774 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
6775 ssh2_pkt_addstring(s
->pktout
, "No supported authentication"
6776 " methods available");
6777 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6778 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6779 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6783 } while (!s
->we_are_in
);
6786 * Now we're authenticated for the connection protocol. The
6787 * connection protocol will automatically have started at this
6788 * point; there's no need to send SERVICE_REQUEST.
6791 ssh
->channels
= newtree234(ssh_channelcmp
);
6794 * Set up handlers for some connection protocol messages, so we
6795 * don't have to handle them repeatedly in this coroutine.
6797 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
6798 ssh2_msg_channel_window_adjust
;
6799 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
6800 ssh2_msg_global_request
;
6803 * Create the main session channel.
6805 if (!ssh
->cfg
.ssh_no_shell
) {
6806 ssh
->mainchan
= snew(struct ssh_channel
);
6807 ssh
->mainchan
->ssh
= ssh
;
6808 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
6809 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
6810 ssh2_pkt_addstring(s
->pktout
, "session");
6811 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
6812 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6813 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
6814 ssh2_pkt_adduint32(s
->pktout
, 0x4000UL
); /* our max pkt size */
6815 ssh2_pkt_send(ssh
, s
->pktout
);
6816 crWaitUntilV(pktin
);
6817 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
6818 bombout(("Server refused to open a session"));
6820 /* FIXME: error data comes back in FAILURE packet */
6822 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
6823 bombout(("Server's channel confirmation cited wrong channel"));
6826 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
6827 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
6828 ssh
->mainchan
->closes
= 0;
6829 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
6830 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
6831 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
6832 add234(ssh
->channels
, ssh
->mainchan
);
6833 update_specials_menu(ssh
->frontend
);
6834 logevent("Opened channel for session");
6836 ssh
->mainchan
= NULL
;
6839 * Now we have a channel, make dispatch table entries for
6840 * general channel-based messages.
6842 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
6843 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
6844 ssh2_msg_channel_data
;
6845 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
6846 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
6847 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
6848 ssh2_msg_channel_open_confirmation
;
6849 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
6850 ssh2_msg_channel_open_failure
;
6851 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
6852 ssh2_msg_channel_request
;
6853 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
6854 ssh2_msg_channel_open
;
6857 * Potentially enable X11 forwarding.
6859 if (ssh
->mainchan
&& ssh
->cfg
.x11_forward
) {
6860 char proto
[20], data
[64];
6861 logevent("Requesting X11 forwarding");
6862 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
6863 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
6864 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
6865 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6866 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
6867 ssh2_pkt_addstring(s
->pktout
, "x11-req");
6868 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6869 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
6870 ssh2_pkt_addstring(s
->pktout
, proto
);
6871 ssh2_pkt_addstring(s
->pktout
, data
);
6872 ssh2_pkt_adduint32(s
->pktout
, x11_get_screen_number(ssh
->cfg
.x11_display
));
6873 ssh2_pkt_send(ssh
, s
->pktout
);
6875 crWaitUntilV(pktin
);
6877 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6878 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6879 bombout(("Unexpected response to X11 forwarding request:"
6880 " packet type %d", pktin
->type
));
6883 logevent("X11 forwarding refused");
6885 logevent("X11 forwarding enabled");
6886 ssh
->X11_fwd_enabled
= TRUE
;
6891 * Enable port forwardings.
6893 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
6896 * Potentially enable agent forwarding.
6898 if (ssh
->mainchan
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
6899 logevent("Requesting OpenSSH-style agent forwarding");
6900 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6901 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
6902 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
6903 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6904 ssh2_pkt_send(ssh
, s
->pktout
);
6906 crWaitUntilV(pktin
);
6908 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6909 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6910 bombout(("Unexpected response to agent forwarding request:"
6911 " packet type %d", pktin
->type
));
6914 logevent("Agent forwarding refused");
6916 logevent("Agent forwarding enabled");
6917 ssh
->agentfwd_enabled
= TRUE
;
6922 * Now allocate a pty for the session.
6924 if (ssh
->mainchan
&& !ssh
->cfg
.nopty
) {
6925 /* Unpick the terminal-speed string. */
6926 /* XXX perhaps we should allow no speeds to be sent. */
6927 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
6928 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
6929 /* Build the pty request. */
6930 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6931 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
6932 ssh2_pkt_addstring(s
->pktout
, "pty-req");
6933 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6934 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
6935 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
6936 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
6937 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
6938 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
6939 ssh2_pkt_addstring_start(s
->pktout
);
6940 ssh2_pkt_addbyte(s
->pktout
, 128); /* TTY_OP_ISPEED */
6941 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
6942 ssh2_pkt_addbyte(s
->pktout
, 129); /* TTY_OP_OSPEED */
6943 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
6944 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
6945 ssh2_pkt_send(ssh
, s
->pktout
);
6946 ssh
->state
= SSH_STATE_INTERMED
;
6948 crWaitUntilV(pktin
);
6950 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6951 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6952 bombout(("Unexpected response to pty request:"
6953 " packet type %d", pktin
->type
));
6956 c_write_str(ssh
, "Server refused to allocate pty\r\n");
6957 ssh
->editing
= ssh
->echoing
= 1;
6959 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6960 ssh
->ospeed
, ssh
->ispeed
);
6963 ssh
->editing
= ssh
->echoing
= 1;
6967 * Send environment variables.
6969 * Simplest thing here is to send all the requests at once, and
6970 * then wait for a whole bunch of successes or failures.
6972 if (ssh
->mainchan
&& *ssh
->cfg
.environmt
) {
6973 char *e
= ssh
->cfg
.environmt
;
6974 char *var
, *varend
, *val
;
6980 while (*e
&& *e
!= '\t') e
++;
6982 if (*e
== '\t') e
++;
6987 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6988 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
6989 ssh2_pkt_addstring(s
->pktout
, "env");
6990 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6991 ssh2_pkt_addstring_start(s
->pktout
);
6992 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
6993 ssh2_pkt_addstring(s
->pktout
, val
);
6994 ssh2_pkt_send(ssh
, s
->pktout
);
6999 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
7002 s
->env_left
= s
->num_env
;
7004 while (s
->env_left
> 0) {
7005 crWaitUntilV(pktin
);
7007 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7008 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7009 bombout(("Unexpected response to environment request:"
7010 " packet type %d", pktin
->type
));
7020 if (s
->env_ok
== s
->num_env
) {
7021 logevent("All environment variables successfully set");
7022 } else if (s
->env_ok
== 0) {
7023 logevent("All environment variables refused");
7024 c_write_str(ssh
, "Server refused to set environment variables\r\n");
7026 logeventf(ssh
, "%d environment variables refused",
7027 s
->num_env
- s
->env_ok
);
7028 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
7033 * Start a shell or a remote command. We may have to attempt
7034 * this twice if the config data has provided a second choice
7037 if (ssh
->mainchan
) while (1) {
7041 if (ssh
->fallback_cmd
) {
7042 subsys
= ssh
->cfg
.ssh_subsys2
;
7043 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
7045 subsys
= ssh
->cfg
.ssh_subsys
;
7046 cmd
= ssh
->cfg
.remote_cmd_ptr
;
7049 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7050 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
7052 ssh2_pkt_addstring(s
->pktout
, "subsystem");
7053 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7054 ssh2_pkt_addstring(s
->pktout
, cmd
);
7056 ssh2_pkt_addstring(s
->pktout
, "exec");
7057 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7058 ssh2_pkt_addstring(s
->pktout
, cmd
);
7060 ssh2_pkt_addstring(s
->pktout
, "shell");
7061 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7063 ssh2_pkt_send(ssh
, s
->pktout
);
7065 crWaitUntilV(pktin
);
7067 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7068 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7069 bombout(("Unexpected response to shell/command request:"
7070 " packet type %d", pktin
->type
));
7074 * We failed to start the command. If this is the
7075 * fallback command, we really are finished; if it's
7076 * not, and if the fallback command exists, try falling
7077 * back to it before complaining.
7079 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
7080 logevent("Primary command failed; attempting fallback");
7081 ssh
->fallback_cmd
= TRUE
;
7084 bombout(("Server refused to start a shell/command"));
7087 logevent("Started a shell/command");
7092 ssh
->state
= SSH_STATE_SESSION
;
7093 if (ssh
->size_needed
)
7094 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
7095 if (ssh
->eof_needed
)
7096 ssh_special(ssh
, TS_EOF
);
7102 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
7107 s
->try_send
= FALSE
;
7111 * _All_ the connection-layer packets we expect to
7112 * receive are now handled by the dispatch table.
7113 * Anything that reaches here must be bogus.
7116 bombout(("Strange packet received: type %d", pktin
->type
));
7118 } else if (ssh
->mainchan
) {
7120 * We have spare data. Add it to the channel buffer.
7122 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
7127 struct ssh_channel
*c
;
7129 * Try to send data on all channels if we can.
7131 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
7134 continue; /* don't send on closing channels */
7135 bufsize
= ssh2_try_send(c
);
7138 case CHAN_MAINSESSION
:
7139 /* stdin need not receive an unthrottle
7140 * notification since it will be polled */
7143 x11_unthrottle(c
->u
.x11
.s
);
7146 /* agent sockets are request/response and need no
7147 * buffer management */
7150 pfd_unthrottle(c
->u
.pfd
.s
);
7162 * Handlers for SSH2 messages that might arrive at any moment.
7164 void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
7166 /* log reason code in disconnect message */
7168 int nowlen
, reason
, msglen
;
7170 reason
= ssh_pkt_getuint32(pktin
);
7171 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7173 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
7174 buf
= dupprintf("Received disconnect message (%s)",
7175 ssh2_disconnect_reasons
[reason
]);
7177 buf
= dupprintf("Received disconnect message (unknown"
7178 " type %d)", reason
);
7182 buf
= dupprintf("Disconnection message text: %n%.*s",
7183 &nowlen
, msglen
, msg
);
7185 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7187 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
7188 ssh2_disconnect_reasons
[reason
] : "unknown",
7193 void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
7195 /* log the debug message */
7200 /* XXX maybe we should actually take notice of this */
7201 always_display
= ssh2_pkt_getbool(pktin
);
7202 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7204 buf
= dupprintf("Remote debug message: %.*s", msglen
, msg
);
7209 void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
7211 struct Packet
*pktout
;
7212 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
7213 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
7215 * UNIMPLEMENTED messages MUST appear in the same order as the
7216 * messages they respond to. Hence, never queue them.
7218 ssh2_pkt_send_noqueue(ssh
, pktout
);
7222 * Handle the top-level SSH2 protocol.
7224 static void ssh2_protocol_setup(Ssh ssh
)
7229 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7231 for (i
= 0; i
< 256; i
++)
7232 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
7235 * Any message we actually understand, we set to NULL so that
7236 * the coroutines will get it.
7238 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
7239 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
7240 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
7241 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
7242 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
7243 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
7244 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
7245 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7246 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7247 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
7248 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
7249 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
7250 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
7251 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
7252 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
7253 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
7254 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7255 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7256 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
7257 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
7258 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
7259 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
7260 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
7261 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
7262 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
7263 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
7264 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
7265 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
7266 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
7267 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
7268 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
7269 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
7270 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
7273 * These special message types we install handlers for.
7275 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
7276 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with ssh1 */
7277 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
7280 static void ssh2_timer(void *ctx
, long now
)
7284 if (!ssh
->kex_in_progress
&& ssh
->cfg
.ssh_rekey_time
!= 0 &&
7285 now
- ssh
->next_rekey
>= 0) {
7286 do_ssh2_transport(ssh
, "Initiating key re-exchange (timeout)",
7291 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
7292 struct Packet
*pktin
)
7294 if (ssh
->state
== SSH_STATE_CLOSED
)
7298 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
7299 if (!ssh
->kex_in_progress
&&
7300 ssh
->max_data_size
!= 0 &&
7301 ssh
->incoming_data_size
> ssh
->max_data_size
)
7302 do_ssh2_transport(ssh
, "Initiating key re-exchange "
7303 "(too much data received)", -1, NULL
);
7306 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
7307 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
7311 if (!ssh
->protocol_initial_phase_done
||
7312 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
7313 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
7314 !ssh
->protocol_initial_phase_done
) {
7315 ssh
->protocol_initial_phase_done
= TRUE
;
7317 * Allow authconn to initialise itself.
7319 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
7322 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
7327 * Called to set up the connection.
7329 * Returns an error message, or NULL on success.
7331 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
7333 char *host
, int port
, char **realhost
, int nodelay
,
7339 ssh
= snew(struct ssh_tag
);
7340 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7341 ssh
->version
= 0; /* when not ready yet */
7344 ssh
->v1_cipher_ctx
= NULL
;
7345 ssh
->crcda_ctx
= NULL
;
7346 ssh
->cscipher
= NULL
;
7347 ssh
->cs_cipher_ctx
= NULL
;
7348 ssh
->sccipher
= NULL
;
7349 ssh
->sc_cipher_ctx
= NULL
;
7351 ssh
->cs_mac_ctx
= NULL
;
7353 ssh
->sc_mac_ctx
= NULL
;
7355 ssh
->cs_comp_ctx
= NULL
;
7357 ssh
->sc_comp_ctx
= NULL
;
7359 ssh
->kex_ctx
= NULL
;
7360 ssh
->hostkey
= NULL
;
7362 ssh
->state
= SSH_STATE_PREPACKET
;
7363 ssh
->size_needed
= FALSE
;
7364 ssh
->eof_needed
= FALSE
;
7367 ssh
->deferred_send_data
= NULL
;
7368 ssh
->deferred_len
= 0;
7369 ssh
->deferred_size
= 0;
7370 ssh
->fallback_cmd
= 0;
7372 ssh
->x11auth
= NULL
;
7373 ssh
->v1_compressing
= FALSE
;
7374 ssh
->v2_outgoing_sequence
= 0;
7375 ssh
->ssh1_rdpkt_crstate
= 0;
7376 ssh
->ssh2_rdpkt_crstate
= 0;
7377 ssh
->do_ssh_init_crstate
= 0;
7378 ssh
->ssh_gotdata_crstate
= 0;
7379 ssh
->do_ssh1_connection_crstate
= 0;
7380 ssh
->do_ssh1_login_crstate
= 0;
7381 ssh
->do_ssh2_transport_crstate
= 0;
7382 ssh
->do_ssh2_authconn_crstate
= 0;
7383 ssh
->do_ssh_init_state
= NULL
;
7384 ssh
->do_ssh1_login_state
= NULL
;
7385 ssh
->do_ssh2_transport_state
= NULL
;
7386 ssh
->do_ssh2_authconn_state
= NULL
;
7387 ssh
->mainchan
= NULL
;
7388 ssh
->throttled_all
= 0;
7389 ssh
->v1_stdout_throttling
= 0;
7391 ssh
->queuelen
= ssh
->queuesize
= 0;
7392 ssh
->queueing
= FALSE
;
7393 ssh
->qhead
= ssh
->qtail
= NULL
;
7394 ssh
->deferred_rekey_reason
= NULL
;
7396 *backend_handle
= ssh
;
7399 if (crypto_startup() == 0)
7400 return "Microsoft high encryption pack not installed!";
7403 ssh
->frontend
= frontend_handle
;
7404 ssh
->term_width
= ssh
->cfg
.width
;
7405 ssh
->term_height
= ssh
->cfg
.height
;
7407 ssh
->channels
= NULL
;
7408 ssh
->rportfwds
= NULL
;
7409 ssh
->portfwds
= NULL
;
7414 ssh
->v1_throttle_count
= 0;
7415 ssh
->overall_bufsize
= 0;
7416 ssh
->fallback_cmd
= 0;
7418 ssh
->protocol
= NULL
;
7420 ssh
->protocol_initial_phase_done
= FALSE
;
7424 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
7425 ssh
->deferred_data_size
= 0L;
7426 ssh
->max_data_size
= parse_blocksize(ssh
->cfg
.ssh_rekey_data
);
7427 ssh
->kex_in_progress
= FALSE
;
7429 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
7438 static void ssh_free(void *handle
)
7440 Ssh ssh
= (Ssh
) handle
;
7441 struct ssh_channel
*c
;
7442 struct ssh_rportfwd
*pf
;
7444 if (ssh
->v1_cipher_ctx
)
7445 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
7446 if (ssh
->cs_cipher_ctx
)
7447 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
7448 if (ssh
->sc_cipher_ctx
)
7449 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
7450 if (ssh
->cs_mac_ctx
)
7451 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
7452 if (ssh
->sc_mac_ctx
)
7453 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
7454 if (ssh
->cs_comp_ctx
) {
7456 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
7458 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
7460 if (ssh
->sc_comp_ctx
) {
7462 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
7464 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
7467 dh_cleanup(ssh
->kex_ctx
);
7468 sfree(ssh
->savedhost
);
7470 while (ssh
->queuelen
-- > 0)
7471 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
7474 while (ssh
->qhead
) {
7475 struct queued_handler
*qh
= ssh
->qhead
;
7476 ssh
->qhead
= qh
->next
;
7479 ssh
->qhead
= ssh
->qtail
= NULL
;
7481 if (ssh
->channels
) {
7482 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
7485 if (c
->u
.x11
.s
!= NULL
)
7486 x11_close(c
->u
.x11
.s
);
7489 if (c
->u
.pfd
.s
!= NULL
)
7490 pfd_close(c
->u
.pfd
.s
);
7495 freetree234(ssh
->channels
);
7496 ssh
->channels
= NULL
;
7499 if (ssh
->rportfwds
) {
7500 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
7502 freetree234(ssh
->rportfwds
);
7503 ssh
->rportfwds
= NULL
;
7505 sfree(ssh
->deferred_send_data
);
7507 x11_free_auth(ssh
->x11auth
);
7508 sfree(ssh
->do_ssh_init_state
);
7509 sfree(ssh
->do_ssh1_login_state
);
7510 sfree(ssh
->do_ssh2_transport_state
);
7511 sfree(ssh
->do_ssh2_authconn_state
);
7512 if (ssh
->crcda_ctx
) {
7513 crcda_free_context(ssh
->crcda_ctx
);
7514 ssh
->crcda_ctx
= NULL
;
7518 expire_timer_context(ssh
);
7520 pinger_free(ssh
->pinger
);
7527 * Reconfigure the SSH backend.
7529 static void ssh_reconfig(void *handle
, Config
*cfg
)
7531 Ssh ssh
= (Ssh
) handle
;
7532 char *rekeying
= NULL
, rekey_mandatory
= FALSE
;
7533 unsigned long old_max_data_size
;
7535 pinger_reconfig(ssh
->pinger
, &ssh
->cfg
, cfg
);
7536 ssh_setup_portfwd(ssh
, cfg
);
7538 if (ssh
->cfg
.ssh_rekey_time
!= cfg
->ssh_rekey_time
&&
7539 cfg
->ssh_rekey_time
!= 0) {
7540 long new_next
= ssh
->last_rekey
+ cfg
->ssh_rekey_time
*60*TICKSPERSEC
;
7541 long now
= GETTICKCOUNT();
7543 if (new_next
- now
< 0) {
7544 rekeying
= "Initiating key re-exchange (timeout shortened)";
7546 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
7550 old_max_data_size
= ssh
->max_data_size
;
7551 ssh
->max_data_size
= parse_blocksize(cfg
->ssh_rekey_data
);
7552 if (old_max_data_size
!= ssh
->max_data_size
&&
7553 ssh
->max_data_size
!= 0) {
7554 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
7555 ssh
->incoming_data_size
> ssh
->max_data_size
)
7556 rekeying
= "Initiating key re-exchange (data limit lowered)";
7559 if (ssh
->cfg
.compression
!= cfg
->compression
) {
7560 rekeying
= "Initiating key re-exchange (compression setting changed)";
7561 rekey_mandatory
= TRUE
;
7564 if (ssh
->cfg
.ssh2_des_cbc
!= cfg
->ssh2_des_cbc
||
7565 memcmp(ssh
->cfg
.ssh_cipherlist
, cfg
->ssh_cipherlist
,
7566 sizeof(ssh
->cfg
.ssh_cipherlist
))) {
7567 rekeying
= "Initiating key re-exchange (cipher settings changed)";
7568 rekey_mandatory
= TRUE
;
7571 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7574 if (!ssh
->kex_in_progress
) {
7575 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
7576 } else if (rekey_mandatory
) {
7577 ssh
->deferred_rekey_reason
= rekeying
;
7583 * Called to send data down the Telnet connection.
7585 static int ssh_send(void *handle
, char *buf
, int len
)
7587 Ssh ssh
= (Ssh
) handle
;
7589 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7592 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
7594 return ssh_sendbuffer(ssh
);
7598 * Called to query the current amount of buffered stdin data.
7600 static int ssh_sendbuffer(void *handle
)
7602 Ssh ssh
= (Ssh
) handle
;
7605 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7609 * If the SSH socket itself has backed up, add the total backup
7610 * size on that to any individual buffer on the stdin channel.
7613 if (ssh
->throttled_all
)
7614 override_value
= ssh
->overall_bufsize
;
7616 if (ssh
->version
== 1) {
7617 return override_value
;
7618 } else if (ssh
->version
== 2) {
7619 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
7620 return override_value
;
7622 return (override_value
+
7623 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
7630 * Called to set the size of the window from SSH's POV.
7632 static void ssh_size(void *handle
, int width
, int height
)
7634 Ssh ssh
= (Ssh
) handle
;
7635 struct Packet
*pktout
;
7637 ssh
->term_width
= width
;
7638 ssh
->term_height
= height
;
7640 switch (ssh
->state
) {
7641 case SSH_STATE_BEFORE_SIZE
:
7642 case SSH_STATE_PREPACKET
:
7643 case SSH_STATE_CLOSED
:
7644 break; /* do nothing */
7645 case SSH_STATE_INTERMED
:
7646 ssh
->size_needed
= TRUE
; /* buffer for later */
7648 case SSH_STATE_SESSION
:
7649 if (!ssh
->cfg
.nopty
) {
7650 if (ssh
->version
== 1) {
7651 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
7652 PKT_INT
, ssh
->term_height
,
7653 PKT_INT
, ssh
->term_width
,
7654 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
7655 } else if (ssh
->mainchan
) {
7656 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7657 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7658 ssh2_pkt_addstring(pktout
, "window-change");
7659 ssh2_pkt_addbool(pktout
, 0);
7660 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
7661 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
7662 ssh2_pkt_adduint32(pktout
, 0);
7663 ssh2_pkt_adduint32(pktout
, 0);
7664 ssh2_pkt_send(ssh
, pktout
);
7672 * Return a list of the special codes that make sense in this
7675 static const struct telnet_special
*ssh_get_specials(void *handle
)
7677 static const struct telnet_special ssh1_ignore_special
[] = {
7678 {"IGNORE message", TS_NOP
}
7680 static const struct telnet_special ssh2_transport_specials
[] = {
7681 {"IGNORE message", TS_NOP
},
7682 {"Repeat key exchange", TS_REKEY
},
7684 static const struct telnet_special ssh2_session_specials
[] = {
7687 /* These are the signal names defined by draft-ietf-secsh-connect-23.
7688 * They include all the ISO C signals, but are a subset of the POSIX
7689 * required signals. */
7690 {"SIGINT (Interrupt)", TS_SIGINT
},
7691 {"SIGTERM (Terminate)", TS_SIGTERM
},
7692 {"SIGKILL (Kill)", TS_SIGKILL
},
7693 {"SIGQUIT (Quit)", TS_SIGQUIT
},
7694 {"SIGHUP (Hangup)", TS_SIGHUP
},
7695 {"More signals", TS_SUBMENU
},
7696 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
7697 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
7698 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
7699 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
7702 static const struct telnet_special specials_end
[] = {
7705 /* XXX review this length for any changes: */
7706 static struct telnet_special ssh_specials
[lenof(ssh2_transport_specials
) +
7707 lenof(ssh2_session_specials
) +
7708 lenof(specials_end
)];
7709 Ssh ssh
= (Ssh
) handle
;
7711 #define ADD_SPECIALS(name) \
7713 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7714 memcpy(&ssh_specials[i], name, sizeof name); \
7718 if (ssh
->version
== 1) {
7719 /* Don't bother offering IGNORE if we've decided the remote
7720 * won't cope with it, since we wouldn't bother sending it if
7722 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
7723 ADD_SPECIALS(ssh1_ignore_special
);
7724 } else if (ssh
->version
== 2) {
7725 ADD_SPECIALS(ssh2_transport_specials
);
7727 ADD_SPECIALS(ssh2_session_specials
);
7728 } /* else we're not ready yet */
7731 ADD_SPECIALS(specials_end
);
7732 return ssh_specials
;
7740 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7741 * can send an EOF and collect resulting output (e.g. `plink
7744 static void ssh_special(void *handle
, Telnet_Special code
)
7746 Ssh ssh
= (Ssh
) handle
;
7747 struct Packet
*pktout
;
7749 if (code
== TS_EOF
) {
7750 if (ssh
->state
!= SSH_STATE_SESSION
) {
7752 * Buffer the EOF in case we are pre-SESSION, so we can
7753 * send it as soon as we reach SESSION.
7756 ssh
->eof_needed
= TRUE
;
7759 if (ssh
->version
== 1) {
7760 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
7761 } else if (ssh
->mainchan
) {
7762 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
7763 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7764 ssh2_pkt_send(ssh
, pktout
);
7766 logevent("Sent EOF message");
7767 } else if (code
== TS_PING
|| code
== TS_NOP
) {
7768 if (ssh
->state
== SSH_STATE_CLOSED
7769 || ssh
->state
== SSH_STATE_PREPACKET
) return;
7770 if (ssh
->version
== 1) {
7771 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
7772 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
7774 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
7775 ssh2_pkt_addstring_start(pktout
);
7776 ssh2_pkt_send_noqueue(ssh
, pktout
);
7778 } else if (code
== TS_REKEY
) {
7779 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
7780 do_ssh2_transport(ssh
, "Initiating key re-exchange at"
7781 " user request", -1, NULL
);
7783 } else if (code
== TS_BRK
) {
7784 if (ssh
->state
== SSH_STATE_CLOSED
7785 || ssh
->state
== SSH_STATE_PREPACKET
) return;
7786 if (ssh
->version
== 1) {
7787 logevent("Unable to send BREAK signal in SSH1");
7788 } else if (ssh
->mainchan
) {
7789 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7790 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7791 ssh2_pkt_addstring(pktout
, "break");
7792 ssh2_pkt_addbool(pktout
, 0);
7793 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
7794 ssh2_pkt_send(ssh
, pktout
);
7797 /* Is is a POSIX signal? */
7798 char *signame
= NULL
;
7799 if (code
== TS_SIGABRT
) signame
= "ABRT";
7800 if (code
== TS_SIGALRM
) signame
= "ALRM";
7801 if (code
== TS_SIGFPE
) signame
= "FPE";
7802 if (code
== TS_SIGHUP
) signame
= "HUP";
7803 if (code
== TS_SIGILL
) signame
= "ILL";
7804 if (code
== TS_SIGINT
) signame
= "INT";
7805 if (code
== TS_SIGKILL
) signame
= "KILL";
7806 if (code
== TS_SIGPIPE
) signame
= "PIPE";
7807 if (code
== TS_SIGQUIT
) signame
= "QUIT";
7808 if (code
== TS_SIGSEGV
) signame
= "SEGV";
7809 if (code
== TS_SIGTERM
) signame
= "TERM";
7810 if (code
== TS_SIGUSR1
) signame
= "USR1";
7811 if (code
== TS_SIGUSR2
) signame
= "USR2";
7812 /* The SSH-2 protocol does in principle support arbitrary named
7813 * signals, including signame@domain, but we don't support those. */
7815 /* It's a signal. */
7816 if (ssh
->version
== 2 && ssh
->mainchan
) {
7817 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7818 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7819 ssh2_pkt_addstring(pktout
, "signal");
7820 ssh2_pkt_addbool(pktout
, 0);
7821 ssh2_pkt_addstring(pktout
, signame
);
7822 ssh2_pkt_send(ssh
, pktout
);
7823 logeventf(ssh
, "Sent signal SIG%s", signame
);
7826 /* Never heard of it. Do nothing */
7831 void *new_sock_channel(void *handle
, Socket s
)
7833 Ssh ssh
= (Ssh
) handle
;
7834 struct ssh_channel
*c
;
7835 c
= snew(struct ssh_channel
);
7839 c
->remoteid
= -1; /* to be set when open confirmed */
7840 c
->localid
= alloc_channel_id(ssh
);
7842 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
7844 bufchain_init(&c
->v
.v2
.outbuffer
);
7845 add234(ssh
->channels
, c
);
7851 * This is called when stdout/stderr (the entity to which
7852 * from_backend sends data) manages to clear some backlog.
7854 static void ssh_unthrottle(void *handle
, int bufsize
)
7856 Ssh ssh
= (Ssh
) handle
;
7857 if (ssh
->version
== 1) {
7858 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
7859 ssh
->v1_stdout_throttling
= 0;
7860 ssh1_throttle(ssh
, -1);
7863 if (ssh
->mainchan
&& ssh
->mainchan
->closes
== 0)
7864 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
7868 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
7870 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
7872 struct Packet
*pktout
;
7874 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
7876 if (ssh
->version
== 1) {
7877 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
7878 PKT_INT
, c
->localid
,
7881 /* PKT_STR, <org:orgport>, */
7884 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
7885 ssh2_pkt_addstring(pktout
, "direct-tcpip");
7886 ssh2_pkt_adduint32(pktout
, c
->localid
);
7887 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
7888 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
7889 ssh2_pkt_adduint32(pktout
, 0x4000UL
); /* our max pkt size */
7890 ssh2_pkt_addstring(pktout
, hostname
);
7891 ssh2_pkt_adduint32(pktout
, port
);
7893 * We make up values for the originator data; partly it's
7894 * too much hassle to keep track, and partly I'm not
7895 * convinced the server should be told details like that
7896 * about my local network configuration.
7898 ssh2_pkt_addstring(pktout
, "client-side-connection");
7899 ssh2_pkt_adduint32(pktout
, 0);
7900 ssh2_pkt_send(ssh
, pktout
);
7904 static Socket
ssh_socket(void *handle
)
7906 Ssh ssh
= (Ssh
) handle
;
7910 static int ssh_sendok(void *handle
)
7912 Ssh ssh
= (Ssh
) handle
;
7913 return ssh
->send_ok
;
7916 static int ssh_ldisc(void *handle
, int option
)
7918 Ssh ssh
= (Ssh
) handle
;
7919 if (option
== LD_ECHO
)
7920 return ssh
->echoing
;
7921 if (option
== LD_EDIT
)
7922 return ssh
->editing
;
7926 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
7928 Ssh ssh
= (Ssh
) handle
;
7932 static void ssh_provide_logctx(void *handle
, void *logctx
)
7934 Ssh ssh
= (Ssh
) handle
;
7935 ssh
->logctx
= logctx
;
7938 static int ssh_return_exitcode(void *handle
)
7940 Ssh ssh
= (Ssh
) handle
;
7944 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: 0);
7948 * cfg_info for SSH is the currently running version of the
7949 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
7951 static int ssh_cfg_info(void *handle
)
7953 Ssh ssh
= (Ssh
) handle
;
7954 return ssh
->version
;
7958 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7959 * that fails. This variable is the means by which scp.c can reach
7960 * into the SSH code and find out which one it got.
7962 extern int ssh_fallback_cmd(void *handle
)
7964 Ssh ssh
= (Ssh
) handle
;
7965 return ssh
->fallback_cmd
;
7968 Backend ssh_backend
= {
7978 ssh_return_exitcode
,