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
;
523 struct ssh_rportfwd
*remote
;
527 #define free_portfwd(pf) ( \
528 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr)) : (void)0 ), sfree(pf) )
533 unsigned long sequence
;
538 long encrypted_len
; /* for SSH2 total-size counting */
541 * State associated with packet logging
545 struct logblank_t
*blanks
;
548 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
549 struct Packet
*pktin
);
550 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
551 struct Packet
*pktin
);
552 static void ssh1_protocol_setup(Ssh ssh
);
553 static void ssh2_protocol_setup(Ssh ssh
);
554 static void ssh_size(void *handle
, int width
, int height
);
555 static void ssh_special(void *handle
, Telnet_Special
);
556 static int ssh2_try_send(struct ssh_channel
*c
);
557 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
558 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
559 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
560 static int ssh_sendbuffer(void *handle
);
561 static void ssh_do_close(Ssh ssh
);
562 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
563 static int ssh2_pkt_getbool(struct Packet
*pkt
);
564 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
565 static void ssh2_timer(void *ctx
, long now
);
566 static int do_ssh2_transport(Ssh ssh
, unsigned char *in
, int inlen
,
567 struct Packet
*pktin
);
569 struct rdpkt1_state_tag
{
570 long len
, pad
, biglen
, to_read
;
571 unsigned long realcrc
, gotcrc
;
575 struct Packet
*pktin
;
578 struct rdpkt2_state_tag
{
579 long len
, pad
, payload
, packetlen
, maclen
;
582 unsigned long incoming_sequence
;
583 struct Packet
*pktin
;
586 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
587 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
589 struct queued_handler
;
590 struct queued_handler
{
592 chandler_fn_t handler
;
594 struct queued_handler
*next
;
598 const struct plug_function_table
*fn
;
599 /* the above field _must_ be first in the structure */
601 SHA_State exhash
, exhashbase
;
608 unsigned char session_key
[32];
610 int v1_remote_protoflags
;
611 int v1_local_protoflags
;
612 int agentfwd_enabled
;
615 const struct ssh_cipher
*cipher
;
618 const struct ssh2_cipher
*cscipher
, *sccipher
;
619 void *cs_cipher_ctx
, *sc_cipher_ctx
;
620 const struct ssh_mac
*csmac
, *scmac
;
621 void *cs_mac_ctx
, *sc_mac_ctx
;
622 const struct ssh_compress
*cscomp
, *sccomp
;
623 void *cs_comp_ctx
, *sc_comp_ctx
;
624 const struct ssh_kex
*kex
;
625 const struct ssh_signkey
*hostkey
;
626 unsigned char v2_session_id
[20];
632 int echoing
, editing
;
636 int ospeed
, ispeed
; /* temporaries */
637 int term_width
, term_height
;
639 tree234
*channels
; /* indexed by local id */
640 struct ssh_channel
*mainchan
; /* primary session channel */
643 tree234
*rportfwds
, *portfwds
;
647 SSH_STATE_BEFORE_SIZE
,
653 int size_needed
, eof_needed
;
655 struct Packet
**queue
;
656 int queuelen
, queuesize
;
658 unsigned char *deferred_send_data
;
659 int deferred_len
, deferred_size
;
662 * Gross hack: pscp will try to start SFTP but fall back to
663 * scp1 if that fails. This variable is the means by which
664 * scp.c can reach into the SSH code and find out which one it
670 * Used for username and password input.
672 char *userpass_input_buffer
;
673 int userpass_input_buflen
;
674 int userpass_input_bufpos
;
675 int userpass_input_echo
;
682 int v1_throttle_count
;
685 int v1_stdout_throttling
;
686 int v2_outgoing_sequence
;
688 int ssh1_rdpkt_crstate
;
689 int ssh2_rdpkt_crstate
;
690 int do_ssh_init_crstate
;
691 int ssh_gotdata_crstate
;
692 int do_ssh1_login_crstate
;
693 int do_ssh1_connection_crstate
;
694 int do_ssh2_transport_crstate
;
695 int do_ssh2_authconn_crstate
;
697 void *do_ssh_init_state
;
698 void *do_ssh1_login_state
;
699 void *do_ssh2_transport_state
;
700 void *do_ssh2_authconn_state
;
702 struct rdpkt1_state_tag rdpkt1_state
;
703 struct rdpkt2_state_tag rdpkt2_state
;
705 /* ssh1 and ssh2 use this for different things, but both use it */
706 int protocol_initial_phase_done
;
708 void (*protocol
) (Ssh ssh
, unsigned char *in
, int inlen
,
710 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
713 * We maintain a full _copy_ of a Config structure here, not
714 * merely a pointer to it. That way, when we're passed a new
715 * one for reconfiguration, we can check the differences and
716 * potentially reconfigure port forwardings etc in mid-session.
721 * Used to transfer data back from async agent callbacks.
723 void *agent_response
;
724 int agent_response_len
;
727 * Dispatch table for packet types that we may have to deal
730 handler_fn_t packet_dispatch
[256];
733 * Queues of one-off handler functions for success/failure
734 * indications from a request.
736 struct queued_handler
*qhead
, *qtail
;
739 * This module deals with sending keepalives.
744 * Track incoming and outgoing data sizes and time, for
747 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
748 unsigned long max_data_size
;
750 long next_rekey
, last_rekey
;
753 #define logevent(s) logevent(ssh->frontend, s)
755 /* logevent, only printf-formatted. */
756 static void logeventf(Ssh ssh
, const char *fmt
, ...)
762 buf
= dupvprintf(fmt
, ap
);
768 #define bombout(msg) \
770 char *text = dupprintf msg; \
773 connection_fatal(ssh->frontend, "%s", text); \
777 /* Functions to leave bits out of the SSH packet log file. */
779 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
781 if (ssh
->cfg
.logomitpass
)
782 pkt
->logmode
= blanktype
;
785 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
787 if (ssh
->cfg
.logomitdata
)
788 pkt
->logmode
= blanktype
;
791 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
793 pkt
->logmode
= PKTLOG_EMIT
;
796 static int ssh_channelcmp(void *av
, void *bv
)
798 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
799 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
800 if (a
->localid
< b
->localid
)
802 if (a
->localid
> b
->localid
)
806 static int ssh_channelfind(void *av
, void *bv
)
808 unsigned *a
= (unsigned *) av
;
809 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
817 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
819 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
820 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
822 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
823 return i
< 0 ?
-1 : +1;
824 if (a
->dport
> b
->dport
)
826 if (a
->dport
< b
->dport
)
831 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
833 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
834 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
836 if (a
->sport
> b
->sport
)
838 if (a
->sport
< b
->sport
)
844 * Special form of strcmp which can cope with NULL inputs. NULL is
845 * defined to sort before even the empty string.
847 static int nullstrcmp(const char *a
, const char *b
)
849 if (a
== NULL
&& b
== NULL
)
858 static int ssh_portcmp(void *av
, void *bv
)
860 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
861 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
863 if (a
->type
> b
->type
)
865 if (a
->type
< b
->type
)
867 if (a
->addressfamily
> b
->addressfamily
)
869 if (a
->addressfamily
< b
->addressfamily
)
871 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
872 return i
< 0 ?
-1 : +1;
873 if (a
->sport
> b
->sport
)
875 if (a
->sport
< b
->sport
)
877 if (a
->type
!= 'D') {
878 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
879 return i
< 0 ?
-1 : +1;
880 if (a
->dport
> b
->dport
)
882 if (a
->dport
< b
->dport
)
888 static int alloc_channel_id(Ssh ssh
)
890 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
891 unsigned low
, high
, mid
;
893 struct ssh_channel
*c
;
896 * First-fit allocation of channel numbers: always pick the
897 * lowest unused one. To do this, binary-search using the
898 * counted B-tree to find the largest channel ID which is in a
899 * contiguous sequence from the beginning. (Precisely
900 * everything in that sequence must have ID equal to its tree
901 * index plus CHANNEL_NUMBER_OFFSET.)
903 tsize
= count234(ssh
->channels
);
907 while (high
- low
> 1) {
908 mid
= (high
+ low
) / 2;
909 c
= index234(ssh
->channels
, mid
);
910 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
911 low
= mid
; /* this one is fine */
913 high
= mid
; /* this one is past it */
916 * Now low points to either -1, or the tree index of the
917 * largest ID in the initial sequence.
920 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
921 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
923 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
926 static void c_write(Ssh ssh
, const char *buf
, int len
)
928 if ((flags
& FLAG_STDERR
)) {
930 for (i
= 0; i
< len
; i
++)
932 fputc(buf
[i
], stderr
);
935 from_backend(ssh
->frontend
, 1, buf
, len
);
938 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
941 for (i
= 0; i
< len
; i
++) {
943 c_write(ssh
, "\r\n", 2);
944 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
945 c_write(ssh
, buf
+ i
, 1);
949 static void c_write_str(Ssh ssh
, const char *buf
)
951 c_write(ssh
, buf
, strlen(buf
));
954 static void ssh_free_packet(struct Packet
*pkt
)
959 static struct Packet
*ssh_new_packet(void)
961 struct Packet
*pkt
= snew(struct Packet
);
965 pkt
->logmode
= PKTLOG_EMIT
;
973 * Collect incoming data in the incoming packet buffer.
974 * Decipher and verify the packet when it is completely read.
975 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
976 * Update the *data and *datalen variables.
977 * Return a Packet structure when a packet is completed.
979 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
981 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
983 crBegin(ssh
->ssh1_rdpkt_crstate
);
985 st
->pktin
= ssh_new_packet();
988 st
->pktin
->length
= 0;
990 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
991 while ((*datalen
) == 0)
993 st
->len
= (st
->len
<< 8) + **data
;
994 (*data
)++, (*datalen
)--;
997 st
->pad
= 8 - (st
->len
% 8);
998 st
->biglen
= st
->len
+ st
->pad
;
999 st
->pktin
->length
= st
->len
- 5;
1001 if (st
->biglen
< 0) {
1002 bombout(("Extremely large packet length from server suggests"
1003 " data stream corruption"));
1004 ssh_free_packet(st
->pktin
);
1008 st
->pktin
->maxlen
= st
->biglen
;
1009 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1011 st
->to_read
= st
->biglen
;
1012 st
->p
= st
->pktin
->data
;
1013 while (st
->to_read
> 0) {
1014 st
->chunk
= st
->to_read
;
1015 while ((*datalen
) == 0)
1017 if (st
->chunk
> (*datalen
))
1018 st
->chunk
= (*datalen
);
1019 memcpy(st
->p
, *data
, st
->chunk
);
1021 *datalen
-= st
->chunk
;
1023 st
->to_read
-= st
->chunk
;
1026 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1027 st
->biglen
, NULL
)) {
1028 bombout(("Network attack (CRC compensation) detected!"));
1029 ssh_free_packet(st
->pktin
);
1034 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1036 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1037 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1038 if (st
->gotcrc
!= st
->realcrc
) {
1039 bombout(("Incorrect CRC received on packet"));
1040 ssh_free_packet(st
->pktin
);
1044 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1045 st
->pktin
->savedpos
= 0;
1047 if (ssh
->v1_compressing
) {
1048 unsigned char *decompblk
;
1050 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1051 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1052 &decompblk
, &decomplen
)) {
1053 bombout(("Zlib decompression encountered invalid data"));
1054 ssh_free_packet(st
->pktin
);
1058 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1059 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1060 st
->pktin
->data
= sresize(st
->pktin
->data
,
1061 st
->pktin
->maxlen
+ APIEXTRA
,
1063 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1066 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1068 st
->pktin
->length
= decomplen
- 1;
1071 st
->pktin
->type
= st
->pktin
->body
[-1];
1074 * Log incoming packet, possibly omitting sensitive fields.
1078 struct logblank_t blank
;
1079 if (ssh
->cfg
.logomitdata
) {
1080 int do_blank
= FALSE
, blank_prefix
= 0;
1081 /* "Session data" packets - omit the data field */
1082 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1083 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1084 do_blank
= TRUE
; blank_prefix
= 0;
1085 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1086 do_blank
= TRUE
; blank_prefix
= 4;
1089 blank
.offset
= blank_prefix
;
1090 blank
.len
= st
->pktin
->length
;
1091 blank
.type
= PKTLOG_OMIT
;
1095 log_packet(ssh
->logctx
,
1096 PKT_INCOMING
, st
->pktin
->type
,
1097 ssh1_pkt_type(st
->pktin
->type
),
1098 st
->pktin
->body
, st
->pktin
->length
,
1102 crFinish(st
->pktin
);
1105 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1107 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1109 crBegin(ssh
->ssh2_rdpkt_crstate
);
1111 st
->pktin
= ssh_new_packet();
1113 st
->pktin
->type
= 0;
1114 st
->pktin
->length
= 0;
1116 st
->cipherblk
= ssh
->sccipher
->blksize
;
1119 if (st
->cipherblk
< 8)
1122 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1125 * Acquire and decrypt the first block of the packet. This will
1126 * contain the length and padding details.
1128 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1129 while ((*datalen
) == 0)
1131 st
->pktin
->data
[st
->i
] = *(*data
)++;
1136 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1137 st
->pktin
->data
, st
->cipherblk
);
1140 * Now get the length and padding figures.
1142 st
->len
= GET_32BIT(st
->pktin
->data
);
1143 st
->pad
= st
->pktin
->data
[4];
1146 * _Completely_ silly lengths should be stomped on before they
1147 * do us any more damage.
1149 if (st
->len
< 0 || st
->pad
< 0 || st
->len
+ st
->pad
< 0) {
1150 bombout(("Incoming packet was garbled on decryption"));
1151 ssh_free_packet(st
->pktin
);
1156 * This enables us to deduce the payload length.
1158 st
->payload
= st
->len
- st
->pad
- 1;
1160 st
->pktin
->length
= st
->payload
+ 5;
1163 * So now we can work out the total packet length.
1165 st
->packetlen
= st
->len
+ 4;
1166 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1169 * Allocate memory for the rest of the packet.
1171 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1172 st
->pktin
->data
= sresize(st
->pktin
->data
,
1173 st
->pktin
->maxlen
+ APIEXTRA
,
1177 * Read and decrypt the remainder of the packet.
1179 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1181 while ((*datalen
) == 0)
1183 st
->pktin
->data
[st
->i
] = *(*data
)++;
1186 /* Decrypt everything _except_ the MAC. */
1188 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1189 st
->pktin
->data
+ st
->cipherblk
,
1190 st
->packetlen
- st
->cipherblk
);
1192 st
->pktin
->encrypted_len
= st
->packetlen
;
1198 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
, st
->len
+ 4,
1199 st
->incoming_sequence
)) {
1200 bombout(("Incorrect MAC received on packet"));
1201 ssh_free_packet(st
->pktin
);
1205 st
->pktin
->sequence
= st
->incoming_sequence
++;
1208 * Decompress packet payload.
1211 unsigned char *newpayload
;
1214 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1215 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1216 &newpayload
, &newlen
)) {
1217 if (st
->pktin
->maxlen
< newlen
+ 5) {
1218 st
->pktin
->maxlen
= newlen
+ 5;
1219 st
->pktin
->data
= sresize(st
->pktin
->data
,
1220 st
->pktin
->maxlen
+ APIEXTRA
,
1223 st
->pktin
->length
= 5 + newlen
;
1224 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1229 st
->pktin
->savedpos
= 6;
1230 st
->pktin
->body
= st
->pktin
->data
;
1231 st
->pktin
->type
= st
->pktin
->data
[5];
1234 * Log incoming packet, possibly omitting sensitive fields.
1238 struct logblank_t blank
;
1239 if (ssh
->cfg
.logomitdata
) {
1240 int do_blank
= FALSE
, blank_prefix
= 0;
1241 /* "Session data" packets - omit the data field */
1242 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1243 do_blank
= TRUE
; blank_prefix
= 4;
1244 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1245 do_blank
= TRUE
; blank_prefix
= 8;
1248 blank
.offset
= blank_prefix
;
1249 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1250 blank
.type
= PKTLOG_OMIT
;
1254 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1255 ssh2_pkt_type(ssh
->pkt_ctx
, st
->pktin
->type
),
1256 st
->pktin
->data
+6, st
->pktin
->length
-6,
1260 crFinish(st
->pktin
);
1263 static void ssh1_pktout_size(struct Packet
*pkt
, int len
)
1267 len
+= 5; /* type and CRC */
1268 pad
= 8 - (len
% 8);
1271 pkt
->length
= len
- 5;
1272 if (pkt
->maxlen
< biglen
) {
1273 pkt
->maxlen
= biglen
;
1274 pkt
->data
= sresize(pkt
->data
, biglen
+ 4 + APIEXTRA
, unsigned char);
1276 pkt
->body
= pkt
->data
+ 4 + pad
+ 1;
1279 static struct Packet
*s_wrpkt_start(int type
, int len
)
1281 struct Packet
*pkt
= ssh_new_packet();
1282 ssh1_pktout_size(pkt
, len
);
1284 /* Initialise log omission state */
1290 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
)
1296 * XXX various versions of SC (including 8.8.4) screw up the
1297 * register allocation in this function and use the same register
1298 * (D6) for len and as a temporary, with predictable results. The
1299 * following sledgehammer prevents this.
1305 pkt
->body
[-1] = pkt
->type
;
1308 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->type
,
1309 ssh1_pkt_type(pkt
->type
),
1310 pkt
->body
, pkt
->length
,
1311 pkt
->nblanks
, pkt
->blanks
);
1312 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1315 if (ssh
->v1_compressing
) {
1316 unsigned char *compblk
;
1318 zlib_compress_block(ssh
->cs_comp_ctx
,
1319 pkt
->body
- 1, pkt
->length
+ 1,
1320 &compblk
, &complen
);
1321 ssh1_pktout_size(pkt
, complen
- 1);
1322 memcpy(pkt
->body
- 1, compblk
, complen
);
1326 len
= pkt
->length
+ 5; /* type and CRC */
1327 pad
= 8 - (len
% 8);
1330 for (i
= 0; i
< pad
; i
++)
1331 pkt
->data
[i
+ 4] = random_byte();
1332 crc
= crc32_compute(pkt
->data
+ 4, biglen
- 4);
1333 PUT_32BIT(pkt
->data
+ biglen
, crc
);
1334 PUT_32BIT(pkt
->data
, len
);
1337 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
, pkt
->data
+ 4, biglen
);
1342 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1345 len
= s_wrpkt_prepare(ssh
, pkt
);
1346 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1347 if (backlog
> SSH_MAX_BACKLOG
)
1348 ssh_throttle_all(ssh
, 1, backlog
);
1351 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1354 len
= s_wrpkt_prepare(ssh
, pkt
);
1355 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1356 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1357 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1361 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1362 ssh
->deferred_len
+= len
;
1366 * Construct a packet with the specified contents.
1368 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
,
1369 va_list ap1
, va_list ap2
)
1371 unsigned char *p
, *argp
, argchar
;
1372 unsigned long argint
;
1373 int pktlen
, argtype
, arglen
;
1378 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1381 (void) va_arg(ap1
, int);
1385 (void) va_arg(ap1
, int);
1389 (void) va_arg(ap1
, unsigned char *);
1390 arglen
= va_arg(ap1
, int);
1394 argp
= va_arg(ap1
, unsigned char *);
1395 arglen
= strlen((char *)argp
);
1396 pktlen
+= 4 + arglen
;
1399 bn
= va_arg(ap1
, Bignum
);
1400 pktlen
+= ssh1_bignum_length(bn
);
1405 /* ignore this pass */
1412 pkt
= s_wrpkt_start(pkttype
, pktlen
);
1415 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1416 int offset
= p
- pkt
->body
, len
= 0;
1418 /* Actual fields in the packet */
1420 argint
= va_arg(ap2
, int);
1421 PUT_32BIT(p
, argint
);
1425 argchar
= (unsigned char) va_arg(ap2
, int);
1430 argp
= va_arg(ap2
, unsigned char *);
1431 arglen
= va_arg(ap2
, int);
1432 memcpy(p
, argp
, arglen
);
1436 argp
= va_arg(ap2
, unsigned char *);
1437 arglen
= strlen((char *)argp
);
1438 PUT_32BIT(p
, arglen
);
1439 memcpy(p
+ 4, argp
, arglen
);
1443 bn
= va_arg(ap2
, Bignum
);
1444 len
= ssh1_write_bignum(p
, bn
);
1446 /* Tokens for modifications to packet logging */
1448 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1451 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1454 end_log_omission(ssh
, pkt
);
1458 /* Deal with logfile omission, if required. */
1459 if (len
&& (pkt
->logmode
!= PKTLOG_EMIT
)) {
1461 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
,
1463 pkt
->blanks
[pkt
->nblanks
-1].offset
= offset
;
1464 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1465 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1472 static void send_packet(Ssh ssh
, int pkttype
, ...)
1476 va_start(ap1
, pkttype
);
1477 va_start(ap2
, pkttype
);
1478 pkt
= construct_packet(ssh
, pkttype
, ap1
, ap2
);
1482 ssh_free_packet(pkt
);
1485 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1489 va_start(ap1
, pkttype
);
1490 va_start(ap2
, pkttype
);
1491 pkt
= construct_packet(ssh
, pkttype
, ap1
, ap2
);
1494 s_wrpkt_defer(ssh
, pkt
);
1495 ssh_free_packet(pkt
);
1498 static int ssh_versioncmp(char *a
, char *b
)
1501 unsigned long av
, bv
;
1503 av
= strtoul(a
, &ae
, 10);
1504 bv
= strtoul(b
, &be
, 10);
1506 return (av
< bv ?
-1 : +1);
1511 av
= strtoul(ae
, &ae
, 10);
1512 bv
= strtoul(be
, &be
, 10);
1514 return (av
< bv ?
-1 : +1);
1519 * Utility routines for putting an SSH-protocol `string' and
1520 * `uint32' into a SHA state.
1523 static void sha_string(SHA_State
* s
, void *str
, int len
)
1525 unsigned char lenblk
[4];
1526 PUT_32BIT(lenblk
, len
);
1527 SHA_Bytes(s
, lenblk
, 4);
1528 SHA_Bytes(s
, str
, len
);
1531 static void sha_uint32(SHA_State
* s
, unsigned i
)
1533 unsigned char intblk
[4];
1534 PUT_32BIT(intblk
, i
);
1535 SHA_Bytes(s
, intblk
, 4);
1539 * SSH2 packet construction functions.
1541 static void ssh2_pkt_ensure(struct Packet
*pkt
, int length
)
1543 if (pkt
->maxlen
< length
) {
1544 pkt
->maxlen
= length
+ 256;
1545 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1548 static void ssh2_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1550 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1552 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1553 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
- 6;
1554 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1555 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1558 ssh2_pkt_ensure(pkt
, pkt
->length
);
1559 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1561 static void ssh2_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1563 ssh2_pkt_adddata(pkt
, &byte
, 1);
1565 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1567 struct Packet
*pkt
= ssh_new_packet();
1569 ssh2_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1572 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1574 ssh2_pkt_adddata(pkt
, &value
, 1);
1576 static void ssh2_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1579 PUT_32BIT(x
, value
);
1580 ssh2_pkt_adddata(pkt
, x
, 4);
1582 static void ssh2_pkt_addstring_start(struct Packet
*pkt
)
1584 ssh2_pkt_adduint32(pkt
, 0);
1585 pkt
->savedpos
= pkt
->length
;
1587 static void ssh2_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1589 ssh2_pkt_adddata(pkt
, data
, strlen(data
));
1590 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1592 static void ssh2_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1594 ssh2_pkt_adddata(pkt
, data
, len
);
1595 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1597 static void ssh2_pkt_addstring(struct Packet
*pkt
, char *data
)
1599 ssh2_pkt_addstring_start(pkt
);
1600 ssh2_pkt_addstring_str(pkt
, data
);
1602 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1605 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1606 p
= snewn(n
+ 1, unsigned char);
1608 fatalbox("out of memory");
1610 for (i
= 1; i
<= n
; i
++)
1611 p
[i
] = bignum_byte(b
, n
- i
);
1613 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1615 memmove(p
, p
+ i
, n
+ 1 - i
);
1619 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1623 p
= ssh2_mpint_fmt(b
, &len
);
1624 ssh2_pkt_addstring_start(pkt
);
1625 ssh2_pkt_addstring_data(pkt
, (char *)p
, len
);
1630 * Construct an SSH2 final-form packet: compress it, encrypt it,
1631 * put the MAC on it. Final packet, ready to be sent, is stored in
1632 * pkt->data. Total length is returned.
1634 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1636 int cipherblk
, maclen
, padding
, i
;
1639 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1640 ssh2_pkt_type(ssh
->pkt_ctx
, pkt
->data
[5]),
1641 pkt
->data
+ 6, pkt
->length
- 6,
1642 pkt
->nblanks
, pkt
->blanks
);
1643 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1647 * Compress packet payload.
1650 unsigned char *newpayload
;
1653 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1655 &newpayload
, &newlen
)) {
1657 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1663 * Add padding. At least four bytes, and must also bring total
1664 * length (minus MAC) up to a multiple of the block size.
1666 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1667 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1670 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1671 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1672 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1673 pkt
->data
[4] = padding
;
1674 for (i
= 0; i
< padding
; i
++)
1675 pkt
->data
[pkt
->length
+ i
] = random_byte();
1676 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1678 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1679 pkt
->length
+ padding
,
1680 ssh
->v2_outgoing_sequence
);
1681 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1684 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1685 pkt
->data
, pkt
->length
+ padding
);
1687 pkt
->encrypted_len
= pkt
->length
+ padding
;
1689 /* Ready-to-send packet starts at pkt->data. We return length. */
1690 return pkt
->length
+ padding
+ maclen
;
1694 * Routines called from the main SSH code to send packets. There
1695 * are quite a few of these, because we have two separate
1696 * mechanisms for delaying the sending of packets:
1698 * - In order to send an IGNORE message and a password message in
1699 * a single fixed-length blob, we require the ability to
1700 * concatenate the encrypted forms of those two packets _into_ a
1701 * single blob and then pass it to our <network.h> transport
1702 * layer in one go. Hence, there's a deferment mechanism which
1703 * works after packet encryption.
1705 * - In order to avoid sending any connection-layer messages
1706 * during repeat key exchange, we have to queue up any such
1707 * outgoing messages _before_ they are encrypted (and in
1708 * particular before they're allocated sequence numbers), and
1709 * then send them once we've finished.
1711 * I call these mechanisms `defer' and `queue' respectively, so as
1712 * to distinguish them reasonably easily.
1714 * The functions send_noqueue() and defer_noqueue() free the packet
1715 * structure they are passed. Every outgoing packet goes through
1716 * precisely one of these functions in its life; packets passed to
1717 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1718 * these or get queued, and then when the queue is later emptied
1719 * the packets are all passed to defer_noqueue().
1723 * Send an SSH2 packet immediately, without queuing or deferring.
1725 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
1729 len
= ssh2_pkt_construct(ssh
, pkt
);
1730 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1731 if (backlog
> SSH_MAX_BACKLOG
)
1732 ssh_throttle_all(ssh
, 1, backlog
);
1734 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
1735 if (!ssh
->kex_in_progress
&&
1736 ssh
->max_data_size
!= 0 &&
1737 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1738 do_ssh2_transport(ssh
, "Initiating key re-exchange "
1739 "(too much data sent)", -1, NULL
);
1741 ssh_free_packet(pkt
);
1745 * Defer an SSH2 packet.
1747 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
)
1749 int len
= ssh2_pkt_construct(ssh
, pkt
);
1750 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1751 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1752 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1756 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1757 ssh
->deferred_len
+= len
;
1758 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
1759 ssh_free_packet(pkt
);
1763 * Queue an SSH2 packet.
1765 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
1767 assert(ssh
->queueing
);
1769 if (ssh
->queuelen
>= ssh
->queuesize
) {
1770 ssh
->queuesize
= ssh
->queuelen
+ 32;
1771 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
1774 ssh
->queue
[ssh
->queuelen
++] = pkt
;
1778 * Either queue or send a packet, depending on whether queueing is
1781 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
1784 ssh2_pkt_queue(ssh
, pkt
);
1786 ssh2_pkt_send_noqueue(ssh
, pkt
);
1790 * Either queue or defer a packet, depending on whether queueing is
1793 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
1796 ssh2_pkt_queue(ssh
, pkt
);
1798 ssh2_pkt_defer_noqueue(ssh
, pkt
);
1802 * Send the whole deferred data block constructed by
1803 * ssh2_pkt_defer() or SSH1's defer_packet().
1805 * The expected use of the defer mechanism is that you call
1806 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1807 * not currently queueing, this simply sets up deferred_send_data
1808 * and then sends it. If we _are_ currently queueing, the calls to
1809 * ssh2_pkt_defer() put the deferred packets on to the queue
1810 * instead, and therefore ssh_pkt_defersend() has no deferred data
1811 * to send. Hence, there's no need to make it conditional on
1814 static void ssh_pkt_defersend(Ssh ssh
)
1817 backlog
= sk_write(ssh
->s
, (char *)ssh
->deferred_send_data
,
1819 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1820 sfree(ssh
->deferred_send_data
);
1821 ssh
->deferred_send_data
= NULL
;
1822 if (backlog
> SSH_MAX_BACKLOG
)
1823 ssh_throttle_all(ssh
, 1, backlog
);
1825 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
1826 if (!ssh
->kex_in_progress
&&
1827 ssh
->max_data_size
!= 0 &&
1828 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1829 do_ssh2_transport(ssh
, "Initiating key re-exchange "
1830 "(too much data sent)", -1, NULL
);
1831 ssh
->deferred_data_size
= 0;
1835 * Send all queued SSH2 packets. We send them by means of
1836 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1837 * packets that needed to be lumped together.
1839 static void ssh2_pkt_queuesend(Ssh ssh
)
1843 assert(!ssh
->queueing
);
1845 for (i
= 0; i
< ssh
->queuelen
; i
++)
1846 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
]);
1849 ssh_pkt_defersend(ssh
);
1853 void bndebug(char *string
, Bignum b
)
1857 p
= ssh2_mpint_fmt(b
, &len
);
1858 debug(("%s", string
));
1859 for (i
= 0; i
< len
; i
++)
1860 debug((" %02x", p
[i
]));
1866 static void sha_mpint(SHA_State
* s
, Bignum b
)
1870 p
= ssh2_mpint_fmt(b
, &len
);
1871 sha_string(s
, p
, len
);
1876 * Packet decode functions for both SSH1 and SSH2.
1878 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
1880 unsigned long value
;
1881 if (pkt
->length
- pkt
->savedpos
< 4)
1882 return 0; /* arrgh, no way to decline (FIXME?) */
1883 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1887 static int ssh2_pkt_getbool(struct Packet
*pkt
)
1889 unsigned long value
;
1890 if (pkt
->length
- pkt
->savedpos
< 1)
1891 return 0; /* arrgh, no way to decline (FIXME?) */
1892 value
= pkt
->body
[pkt
->savedpos
] != 0;
1896 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
1901 if (pkt
->length
- pkt
->savedpos
< 4)
1903 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1908 if (pkt
->length
- pkt
->savedpos
< *length
)
1910 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
1911 pkt
->savedpos
+= *length
;
1913 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
1915 if (pkt
->length
- pkt
->savedpos
< length
)
1917 pkt
->savedpos
+= length
;
1918 return pkt
->body
+ (pkt
->savedpos
- length
);
1920 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
1921 unsigned char **keystr
)
1925 j
= makekey(pkt
->body
+ pkt
->savedpos
,
1926 pkt
->length
- pkt
->savedpos
,
1933 assert(pkt
->savedpos
< pkt
->length
);
1937 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
1942 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
1943 pkt
->length
- pkt
->savedpos
, &b
);
1951 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
1957 ssh_pkt_getstring(pkt
, &p
, &length
);
1962 b
= bignum_from_bytes((unsigned char *)p
, length
);
1967 * Helper function to add an SSH2 signature blob to a packet.
1968 * Expects to be shown the public key blob as well as the signature
1969 * blob. Normally works just like ssh2_pkt_addstring, but will
1970 * fiddle with the signature packet if necessary for
1971 * BUG_SSH2_RSA_PADDING.
1973 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
1974 void *pkblob_v
, int pkblob_len
,
1975 void *sigblob_v
, int sigblob_len
)
1977 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
1978 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
1980 /* dmemdump(pkblob, pkblob_len); */
1981 /* dmemdump(sigblob, sigblob_len); */
1984 * See if this is in fact an ssh-rsa signature and a buggy
1985 * server; otherwise we can just do this the easy way.
1987 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
1988 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
1989 int pos
, len
, siglen
;
1992 * Find the byte length of the modulus.
1995 pos
= 4+7; /* skip over "ssh-rsa" */
1996 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
1997 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
1998 pos
+= 4; /* find modulus itself */
1999 while (len
> 0 && pkblob
[pos
] == 0)
2001 /* debug(("modulus length is %d\n", len)); */
2004 * Now find the signature integer.
2006 pos
= 4+7; /* skip over "ssh-rsa" */
2007 siglen
= GET_32BIT(sigblob
+pos
);
2008 /* debug(("signature length is %d\n", siglen)); */
2010 if (len
!= siglen
) {
2011 unsigned char newlen
[4];
2012 ssh2_pkt_addstring_start(pkt
);
2013 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
2014 /* dmemdump(sigblob, pos); */
2015 pos
+= 4; /* point to start of actual sig */
2016 PUT_32BIT(newlen
, len
);
2017 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
2018 /* dmemdump(newlen, 4); */
2020 while (len
-- > siglen
) {
2021 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
2022 /* dmemdump(newlen, 1); */
2024 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2025 /* dmemdump(sigblob+pos, siglen); */
2029 /* Otherwise fall through and do it the easy way. */
2032 ssh2_pkt_addstring_start(pkt
);
2033 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2037 * Examine the remote side's version string and compare it against
2038 * a list of known buggy implementations.
2040 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2042 char *imp
; /* pointer to implementation part */
2044 imp
+= strcspn(imp
, "-");
2046 imp
+= strcspn(imp
, "-");
2049 ssh
->remote_bugs
= 0;
2051 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
2052 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
2053 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2054 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2055 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2056 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2058 * These versions don't support SSH1_MSG_IGNORE, so we have
2059 * to use a different defence against password length
2062 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2063 logevent("We believe remote version has SSH1 ignore bug");
2066 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
2067 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
2068 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2070 * These versions need a plain password sent; they can't
2071 * handle having a null and a random length of data after
2074 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2075 logevent("We believe remote version needs a plain SSH1 password");
2078 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
2079 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
2080 (!strcmp(imp
, "Cisco-1.25")))) {
2082 * These versions apparently have no clue whatever about
2083 * RSA authentication and will panic and die if they see
2084 * an AUTH_RSA message.
2086 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2087 logevent("We believe remote version can't handle RSA authentication");
2090 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
2091 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
2092 !wc_match("* VShell", imp
) &&
2093 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2094 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2095 wc_match("2.1 *", imp
)))) {
2097 * These versions have the HMAC bug.
2099 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2100 logevent("We believe remote version has SSH2 HMAC bug");
2103 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
2104 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
2105 !wc_match("* VShell", imp
) &&
2106 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2108 * These versions have the key-derivation bug (failing to
2109 * include the literal shared secret in the hashes that
2110 * generate the keys).
2112 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2113 logevent("We believe remote version has SSH2 key-derivation bug");
2116 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2117 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2118 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2119 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2121 * These versions have the SSH2 RSA padding bug.
2123 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2124 logevent("We believe remote version has SSH2 RSA padding bug");
2127 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2128 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2129 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2131 * These versions have the SSH2 session-ID bug in
2132 * public-key authentication.
2134 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2135 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2140 * The `software version' part of an SSH version string is required
2141 * to contain no spaces or minus signs.
2143 static void ssh_fix_verstring(char *str
)
2145 /* Eat "SSH-<protoversion>-". */
2146 assert(*str
== 'S'); str
++;
2147 assert(*str
== 'S'); str
++;
2148 assert(*str
== 'H'); str
++;
2149 assert(*str
== '-'); str
++;
2150 while (*str
&& *str
!= '-') str
++;
2151 assert(*str
== '-'); str
++;
2153 /* Convert minus signs and spaces in the remaining string into
2156 if (*str
== '-' || *str
== ' ')
2162 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2164 struct do_ssh_init_state
{
2172 crState(do_ssh_init_state
);
2174 crBegin(ssh
->do_ssh_init_crstate
);
2176 /* Search for the string "SSH-" in the input. */
2179 static const int transS
[] = { 1, 2, 2, 1 };
2180 static const int transH
[] = { 0, 0, 3, 0 };
2181 static const int transminus
[] = { 0, 0, 0, -1 };
2183 s
->i
= transS
[s
->i
];
2185 s
->i
= transH
[s
->i
];
2187 s
->i
= transminus
[s
->i
];
2192 crReturn(1); /* get another character */
2196 s
->vstring
= snewn(s
->vstrsize
, char);
2197 strcpy(s
->vstring
, "SSH-");
2201 crReturn(1); /* get another char */
2202 if (s
->vslen
>= s
->vstrsize
- 1) {
2204 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2206 s
->vstring
[s
->vslen
++] = c
;
2209 s
->version
[s
->i
] = '\0';
2211 } else if (s
->i
< sizeof(s
->version
) - 1)
2212 s
->version
[s
->i
++] = c
;
2213 } else if (c
== '\012')
2217 ssh
->agentfwd_enabled
= FALSE
;
2218 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2220 s
->vstring
[s
->vslen
] = 0;
2221 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2224 vlog
= snewn(20 + s
->vslen
, char);
2225 sprintf(vlog
, "Server version: %s", s
->vstring
);
2229 ssh_detect_bugs(ssh
, s
->vstring
);
2232 * Decide which SSH protocol version to support.
2235 /* Anything strictly below "2.0" means protocol 1 is supported. */
2236 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2237 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2238 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2240 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2241 bombout(("SSH protocol version 1 required by user but not provided by server"));
2244 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2245 bombout(("SSH protocol version 2 required by user but not provided by server"));
2252 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
)) {
2254 * Construct a v2 version string.
2256 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2260 * Construct a v1 version string.
2262 verstring
= dupprintf("SSH-%s-%s\012",
2263 (ssh_versioncmp(s
->version
, "1.5") <= 0 ?
2264 s
->version
: "1.5"),
2269 ssh_fix_verstring(verstring
);
2271 if (ssh
->version
== 2) {
2273 * Hash our version string and their version string.
2275 SHA_Init(&ssh
->exhashbase
);
2276 sha_string(&ssh
->exhashbase
, verstring
,
2277 strcspn(verstring
, "\015\012"));
2278 sha_string(&ssh
->exhashbase
, s
->vstring
,
2279 strcspn(s
->vstring
, "\015\012"));
2282 * Initialise SSHv2 protocol.
2284 ssh
->protocol
= ssh2_protocol
;
2285 ssh2_protocol_setup(ssh
);
2286 ssh
->s_rdpkt
= ssh2_rdpkt
;
2289 * Initialise SSHv1 protocol.
2291 ssh
->protocol
= ssh1_protocol
;
2292 ssh1_protocol_setup(ssh
);
2293 ssh
->s_rdpkt
= ssh1_rdpkt
;
2295 logeventf(ssh
, "We claim version: %.*s",
2296 strcspn(verstring
, "\015\012"), verstring
);
2297 sk_write(ssh
->s
, verstring
, strlen(verstring
));
2301 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2303 update_specials_menu(ssh
->frontend
);
2304 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2305 ssh
->pinger
= pinger_new(&ssh
->cfg
, &ssh_backend
, ssh
);
2312 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2314 crBegin(ssh
->ssh_gotdata_crstate
);
2317 * To begin with, feed the characters one by one to the
2318 * protocol initialisation / selection function do_ssh_init().
2319 * When that returns 0, we're done with the initial greeting
2320 * exchange and can move on to packet discipline.
2323 int ret
; /* need not be kept across crReturn */
2325 crReturnV
; /* more data please */
2326 ret
= do_ssh_init(ssh
, *data
);
2334 * We emerge from that loop when the initial negotiation is
2335 * over and we have selected an s_rdpkt function. Now pass
2336 * everything to s_rdpkt, and then pass the resulting packets
2337 * to the proper protocol handler.
2342 while (datalen
> 0) {
2343 struct Packet
*pktin
= ssh
->s_rdpkt(ssh
, &data
, &datalen
);
2345 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2346 ssh_free_packet(pktin
);
2348 if (ssh
->state
== SSH_STATE_CLOSED
)
2356 static void ssh_do_close(Ssh ssh
)
2359 struct ssh_channel
*c
;
2361 ssh
->state
= SSH_STATE_CLOSED
;
2365 notify_remote_exit(ssh
->frontend
);
2368 * Now we must shut down any port and X forwardings going
2369 * through this connection.
2371 if (ssh
->channels
) {
2372 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2375 x11_close(c
->u
.x11
.s
);
2378 pfd_close(c
->u
.pfd
.s
);
2381 del234(ssh
->channels
, c
);
2382 if (ssh
->version
== 2)
2383 bufchain_clear(&c
->v
.v2
.outbuffer
);
2389 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2392 Ssh ssh
= (Ssh
) plug
;
2395 /* A socket error has occurred. */
2396 logevent(error_msg
);
2397 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2399 /* Otherwise, the remote side closed the connection normally. */
2404 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2406 Ssh ssh
= (Ssh
) plug
;
2407 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2408 if (ssh
->state
== SSH_STATE_CLOSED
) {
2415 static void ssh_sent(Plug plug
, int bufsize
)
2417 Ssh ssh
= (Ssh
) plug
;
2419 * If the send backlog on the SSH socket itself clears, we
2420 * should unthrottle the whole world if it was throttled.
2422 if (bufsize
< SSH_MAX_BACKLOG
)
2423 ssh_throttle_all(ssh
, 0, bufsize
);
2427 * Connect to specified host and port.
2428 * Returns an error message, or NULL on success.
2429 * Also places the canonical host name into `realhost'. It must be
2430 * freed by the caller.
2432 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2433 char **realhost
, int nodelay
, int keepalive
)
2435 static const struct plug_function_table fn_table
= {
2445 ssh
->savedhost
= snewn(1 + strlen(host
), char);
2446 if (!ssh
->savedhost
)
2447 fatalbox("Out of memory");
2448 strcpy(ssh
->savedhost
, host
);
2451 port
= 22; /* default ssh port */
2452 ssh
->savedport
= port
;
2457 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
2458 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
2459 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
2460 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
,
2461 ssh
->cfg
.addressfamily
);
2462 if ((err
= sk_addr_error(addr
)) != NULL
) {
2472 sk_getaddr(addr
, addrbuf
, 100);
2473 logeventf(ssh
, "Connecting to %s port %d", addrbuf
, port
);
2475 ssh
->fn
= &fn_table
;
2476 ssh
->s
= new_connection(addr
, *realhost
, port
,
2477 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
2478 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2480 notify_remote_exit(ssh
->frontend
);
2488 * Throttle or unthrottle the SSH connection.
2490 static void ssh1_throttle(Ssh ssh
, int adjust
)
2492 int old_count
= ssh
->v1_throttle_count
;
2493 ssh
->v1_throttle_count
+= adjust
;
2494 assert(ssh
->v1_throttle_count
>= 0);
2495 if (ssh
->v1_throttle_count
&& !old_count
) {
2496 sk_set_frozen(ssh
->s
, 1);
2497 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2498 sk_set_frozen(ssh
->s
, 0);
2503 * Throttle or unthrottle _all_ local data streams (for when sends
2504 * on the SSH connection itself back up).
2506 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2509 struct ssh_channel
*c
;
2511 if (enable
== ssh
->throttled_all
)
2513 ssh
->throttled_all
= enable
;
2514 ssh
->overall_bufsize
= bufsize
;
2517 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2519 case CHAN_MAINSESSION
:
2521 * This is treated separately, outside the switch.
2525 x11_override_throttle(c
->u
.x11
.s
, enable
);
2528 /* Agent channels require no buffer management. */
2531 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
2538 * Username and password input, abstracted off into routines
2539 * reusable in several places - even between SSH1 and SSH2.
2542 /* Set up a username or password input loop on a given buffer. */
2543 static void setup_userpass_input(Ssh ssh
, char *buffer
, int buflen
, int echo
)
2545 ssh
->userpass_input_buffer
= buffer
;
2546 ssh
->userpass_input_buflen
= buflen
;
2547 ssh
->userpass_input_bufpos
= 0;
2548 ssh
->userpass_input_echo
= echo
;
2552 * Process some terminal data in the course of username/password
2553 * input. Returns >0 for success (line of input returned in
2554 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2555 * for inconclusive (keep waiting for more input please).
2557 static int process_userpass_input(Ssh ssh
, unsigned char *in
, int inlen
)
2562 switch (c
= *in
++) {
2565 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
] = 0;
2566 ssh
->userpass_input_buffer
[ssh
->userpass_input_buflen
-1] = 0;
2571 if (ssh
->userpass_input_bufpos
> 0) {
2572 if (ssh
->userpass_input_echo
)
2573 c_write_str(ssh
, "\b \b");
2574 ssh
->userpass_input_bufpos
--;
2579 while (ssh
->userpass_input_bufpos
> 0) {
2580 if (ssh
->userpass_input_echo
)
2581 c_write_str(ssh
, "\b \b");
2582 ssh
->userpass_input_bufpos
--;
2591 * This simplistic check for printability is disabled
2592 * when we're doing password input, because some people
2593 * have control characters in their passwords.o
2595 if ((!ssh
->userpass_input_echo
||
2596 (c
>= ' ' && c
<= '~') ||
2597 ((unsigned char) c
>= 160))
2598 && ssh
->userpass_input_bufpos
< ssh
->userpass_input_buflen
-1) {
2599 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
++] = c
;
2600 if (ssh
->userpass_input_echo
)
2601 c_write(ssh
, &c
, 1);
2609 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
2611 Ssh ssh
= (Ssh
) sshv
;
2613 ssh
->agent_response
= reply
;
2614 ssh
->agent_response_len
= replylen
;
2616 if (ssh
->version
== 1)
2617 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2619 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
2622 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
2624 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
2626 void *sentreply
= reply
;
2629 /* Fake SSH_AGENT_FAILURE. */
2630 sentreply
= "\0\0\0\1\5";
2633 if (ssh
->version
== 2) {
2634 ssh2_add_channel_data(c
, sentreply
, replylen
);
2637 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
2638 PKT_INT
, c
->remoteid
,
2641 PKT_DATA
, sentreply
, replylen
,
2650 * Handle the key exchange and user authentication phases.
2652 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
2653 struct Packet
*pktin
)
2656 unsigned char cookie
[8], *ptr
;
2657 struct RSAKey servkey
, hostkey
;
2658 struct MD5Context md5c
;
2659 struct do_ssh1_login_state
{
2661 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2662 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2663 int tried_publickey
, tried_agent
;
2664 int tis_auth_refused
, ccard_auth_refused
;
2665 unsigned char session_id
[16];
2668 void *publickey_blob
;
2669 int publickey_bloblen
;
2675 unsigned char request
[5], *response
, *p
;
2684 crState(do_ssh1_login_state
);
2686 crBegin(ssh
->do_ssh1_login_crstate
);
2691 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
2692 bombout(("Public key packet not received"));
2696 logevent("Received public keys");
2698 ptr
= ssh_pkt_getdata(pktin
, 8);
2700 bombout(("SSH1 public key packet stopped before random cookie"));
2703 memcpy(cookie
, ptr
, 8);
2705 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
2706 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
2707 bombout(("Failed to read SSH1 public keys from public key packet"));
2712 * Log the host key fingerprint.
2716 logevent("Host key fingerprint is:");
2717 strcpy(logmsg
, " ");
2718 hostkey
.comment
= NULL
;
2719 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2720 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2724 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
2725 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
2726 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
2728 ssh
->v1_local_protoflags
=
2729 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2730 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2733 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
2734 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
2735 MD5Update(&md5c
, cookie
, 8);
2736 MD5Final(s
->session_id
, &md5c
);
2738 for (i
= 0; i
< 32; i
++)
2739 ssh
->session_key
[i
] = random_byte();
2742 * Verify that the `bits' and `bytes' parameters match.
2744 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
2745 servkey
.bits
> servkey
.bytes
* 8) {
2746 bombout(("SSH1 public keys were badly formatted"));
2750 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2752 s
->rsabuf
= snewn(s
->len
, unsigned char);
2754 fatalbox("Out of memory");
2757 * Verify the host key.
2761 * First format the key into a string.
2763 int len
= rsastr_len(&hostkey
);
2764 char fingerprint
[100];
2765 char *keystr
= snewn(len
, char);
2767 fatalbox("Out of memory");
2768 rsastr_fmt(keystr
, &hostkey
);
2769 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2770 verify_ssh_host_key(ssh
->frontend
,
2771 ssh
->savedhost
, ssh
->savedport
, "rsa", keystr
,
2776 for (i
= 0; i
< 32; i
++) {
2777 s
->rsabuf
[i
] = ssh
->session_key
[i
];
2779 s
->rsabuf
[i
] ^= s
->session_id
[i
];
2782 if (hostkey
.bytes
> servkey
.bytes
) {
2783 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
2785 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
2787 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
2789 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
2792 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2796 logevent("Encrypted session key");
2799 int cipher_chosen
= 0, warn
= 0;
2800 char *cipher_string
= NULL
;
2802 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2803 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
2804 if (next_cipher
== CIPHER_WARN
) {
2805 /* If/when we choose a cipher, warn about it */
2807 } else if (next_cipher
== CIPHER_AES
) {
2808 /* XXX Probably don't need to mention this. */
2809 logevent("AES not supported in SSH1, skipping");
2811 switch (next_cipher
) {
2812 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
2813 cipher_string
= "3DES"; break;
2814 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
2815 cipher_string
= "Blowfish"; break;
2816 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
2817 cipher_string
= "single-DES"; break;
2819 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
2823 if (!cipher_chosen
) {
2824 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2825 bombout(("Server violates SSH 1 protocol by not "
2826 "supporting 3DES encryption"));
2828 /* shouldn't happen */
2829 bombout(("No supported ciphers found"));
2833 /* Warn about chosen cipher if necessary. */
2835 askalg(ssh
->frontend
, "cipher", cipher_string
);
2838 switch (s
->cipher_type
) {
2839 case SSH_CIPHER_3DES
:
2840 logevent("Using 3DES encryption");
2842 case SSH_CIPHER_DES
:
2843 logevent("Using single-DES encryption");
2845 case SSH_CIPHER_BLOWFISH
:
2846 logevent("Using Blowfish encryption");
2850 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
2851 PKT_CHAR
, s
->cipher_type
,
2852 PKT_DATA
, cookie
, 8,
2853 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
2854 PKT_DATA
, s
->rsabuf
, s
->len
,
2855 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
2857 logevent("Trying to enable encryption...");
2861 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2862 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
2864 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
2865 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
2866 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
2868 ssh
->crcda_ctx
= crcda_make_context();
2869 logevent("Installing CRC compensation attack detector");
2871 if (servkey
.modulus
) {
2872 sfree(servkey
.modulus
);
2873 servkey
.modulus
= NULL
;
2875 if (servkey
.exponent
) {
2876 sfree(servkey
.exponent
);
2877 servkey
.exponent
= NULL
;
2879 if (hostkey
.modulus
) {
2880 sfree(hostkey
.modulus
);
2881 hostkey
.modulus
= NULL
;
2883 if (hostkey
.exponent
) {
2884 sfree(hostkey
.exponent
);
2885 hostkey
.exponent
= NULL
;
2889 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
2890 bombout(("Encryption not successfully enabled"));
2894 logevent("Successfully started encryption");
2898 if (!*ssh
->cfg
.username
) {
2899 if (ssh_get_line
&& !ssh_getline_pw_only
) {
2900 if (!ssh_get_line("login as: ",
2901 s
->username
, sizeof(s
->username
), FALSE
)) {
2903 * get_line failed to get a username.
2906 logevent("No username provided. Abandoning session.");
2907 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
2911 int ret
; /* need not be kept over crReturn */
2912 c_write_str(ssh
, "login as: ");
2915 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
2917 crWaitUntil(!pktin
);
2918 ret
= process_userpass_input(ssh
, in
, inlen
);
2922 c_write_str(ssh
, "\r\n");
2925 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
2926 s
->username
[sizeof(s
->username
)-1] = '\0';
2929 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
2931 char userlog
[22 + sizeof(s
->username
)];
2932 sprintf(userlog
, "Sent username \"%s\"", s
->username
);
2934 if (flags
& FLAG_INTERACTIVE
&&
2935 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2936 strcat(userlog
, "\r\n");
2937 c_write_str(ssh
, userlog
);
2944 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2945 /* We must not attempt PK auth. Pretend we've already tried it. */
2946 s
->tried_publickey
= s
->tried_agent
= 1;
2948 s
->tried_publickey
= s
->tried_agent
= 0;
2950 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
2951 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2952 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
2953 if (!rsakey_pubblob(&ssh
->cfg
.keyfile
,
2954 &s
->publickey_blob
, &s
->publickey_bloblen
, NULL
))
2955 s
->publickey_blob
= NULL
;
2957 s
->publickey_blob
= NULL
;
2959 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
2960 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2962 if (agent_exists() && !s
->tried_agent
) {
2964 * Attempt RSA authentication using Pageant.
2970 logevent("Pageant is running. Requesting keys.");
2972 /* Request the keys held by the agent. */
2973 PUT_32BIT(s
->request
, 1);
2974 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2975 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
2976 ssh_agent_callback
, ssh
)) {
2980 bombout(("Unexpected data from server while waiting"
2981 " for agent response"));
2984 } while (pktin
|| inlen
> 0);
2985 r
= ssh
->agent_response
;
2986 s
->responselen
= ssh
->agent_response_len
;
2988 s
->response
= (unsigned char *) r
;
2989 if (s
->response
&& s
->responselen
>= 5 &&
2990 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2991 s
->p
= s
->response
+ 5;
2992 s
->nkeys
= GET_32BIT(s
->p
);
2996 sprintf(buf
, "Pageant has %d SSH1 keys", s
->nkeys
);
2999 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3002 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
3005 if (s
->publickey_blob
&&
3006 !memcmp(s
->p
, s
->publickey_blob
,
3007 s
->publickey_bloblen
)) {
3008 logevent("This key matches configured key file");
3009 s
->tried_publickey
= 1;
3014 do { /* do while (0) to make breaking easy */
3015 n
= ssh1_read_bignum
3016 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3021 n
= ssh1_read_bignum
3022 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3027 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3029 s
->commentlen
= GET_32BIT(s
->p
);
3031 if (s
->responselen
- (s
->p
-s
->response
) <
3034 s
->commentp
= (char *)s
->p
;
3035 s
->p
+= s
->commentlen
;
3039 logevent("Pageant key list packet was truncated");
3043 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3044 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3046 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3047 logevent("Key refused");
3050 logevent("Received RSA challenge");
3051 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3052 bombout(("Server's RSA challenge was badly formatted"));
3057 char *agentreq
, *q
, *ret
;
3060 len
= 1 + 4; /* message type, bit count */
3061 len
+= ssh1_bignum_length(s
->key
.exponent
);
3062 len
+= ssh1_bignum_length(s
->key
.modulus
);
3063 len
+= ssh1_bignum_length(s
->challenge
);
3064 len
+= 16; /* session id */
3065 len
+= 4; /* response format */
3066 agentreq
= snewn(4 + len
, char);
3067 PUT_32BIT(agentreq
, len
);
3069 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3070 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3072 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3073 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3074 q
+= ssh1_write_bignum(q
, s
->challenge
);
3075 memcpy(q
, s
->session_id
, 16);
3077 PUT_32BIT(q
, 1); /* response format */
3078 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3079 ssh_agent_callback
, ssh
)) {
3084 bombout(("Unexpected data from server"
3085 " while waiting for agent"
3089 } while (pktin
|| inlen
> 0);
3090 vret
= ssh
->agent_response
;
3091 retlen
= ssh
->agent_response_len
;
3096 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3097 logevent("Sending Pageant's response");
3098 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3099 PKT_DATA
, ret
+ 5, 16,
3103 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3105 ("Pageant's response accepted");
3106 if (flags
& FLAG_VERBOSE
) {
3107 c_write_str(ssh
, "Authenticated using"
3109 c_write(ssh
, s
->commentp
,
3111 c_write_str(ssh
, "\" from agent\r\n");
3116 ("Pageant's response not accepted");
3119 ("Pageant failed to answer challenge");
3123 logevent("No reply received from Pageant");
3126 freebn(s
->key
.exponent
);
3127 freebn(s
->key
.modulus
);
3128 freebn(s
->challenge
);
3137 if (!filename_is_null(ssh
->cfg
.keyfile
) && !s
->tried_publickey
)
3138 s
->pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
3140 if (ssh
->cfg
.try_tis_auth
&&
3141 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3142 !s
->tis_auth_refused
) {
3143 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3144 logevent("Requested TIS authentication");
3145 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3147 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3148 logevent("TIS authentication declined");
3149 if (flags
& FLAG_INTERACTIVE
)
3150 c_write_str(ssh
, "TIS authentication refused.\r\n");
3151 s
->tis_auth_refused
= 1;
3157 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3159 bombout(("TIS challenge packet was badly formed"));
3162 logevent("Received TIS challenge");
3163 if (challengelen
> sizeof(s
->prompt
) - 1)
3164 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3165 memcpy(s
->prompt
, challenge
, challengelen
);
3166 /* Prompt heuristic comes from OpenSSH */
3167 strncpy(s
->prompt
+ challengelen
,
3168 memchr(s
->prompt
, '\n', challengelen
) ?
3169 "": "\r\nResponse: ",
3170 (sizeof s
->prompt
) - challengelen
);
3171 s
->prompt
[(sizeof s
->prompt
) - 1] = '\0';
3174 if (ssh
->cfg
.try_tis_auth
&&
3175 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3176 !s
->ccard_auth_refused
) {
3177 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3178 logevent("Requested CryptoCard authentication");
3179 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3181 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3182 logevent("CryptoCard authentication declined");
3183 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3184 s
->ccard_auth_refused
= 1;
3190 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3192 bombout(("CryptoCard challenge packet was badly formed"));
3195 logevent("Received CryptoCard challenge");
3196 if (challengelen
> sizeof(s
->prompt
) - 1)
3197 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3198 memcpy(s
->prompt
, challenge
, challengelen
);
3199 strncpy(s
->prompt
+ challengelen
,
3200 memchr(s
->prompt
, '\n', challengelen
) ?
3201 "" : "\r\nResponse: ",
3202 sizeof(s
->prompt
) - challengelen
);
3203 s
->prompt
[sizeof(s
->prompt
) - 1] = '\0';
3206 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3207 sprintf(s
->prompt
, "%.90s@%.90s's password: ",
3208 s
->username
, ssh
->savedhost
);
3210 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3211 char *comment
= NULL
;
3214 if (flags
& FLAG_VERBOSE
)
3215 c_write_str(ssh
, "Trying public key authentication.\r\n");
3216 logeventf(ssh
, "Trying public key \"%s\"",
3217 filename_to_str(&ssh
->cfg
.keyfile
));
3218 type
= key_type(&ssh
->cfg
.keyfile
);
3219 if (type
!= SSH_KEYTYPE_SSH1
) {
3220 sprintf(msgbuf
, "Key is of wrong type (%s)",
3221 key_type_to_str(type
));
3223 c_write_str(ssh
, msgbuf
);
3224 c_write_str(ssh
, "\r\n");
3225 s
->tried_publickey
= 1;
3228 if (!rsakey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
3229 if (flags
& FLAG_VERBOSE
)
3230 c_write_str(ssh
, "No passphrase required.\r\n");
3233 sprintf(s
->prompt
, "Passphrase for key \"%.100s\": ", comment
);
3238 * Show password prompt, having first obtained it via a TIS
3239 * or CryptoCard exchange if we're doing TIS or CryptoCard
3243 if (!ssh_get_line(s
->prompt
, s
->password
,
3244 sizeof(s
->password
), TRUE
)) {
3246 * get_line failed to get a password (for example
3247 * because one was supplied on the command line
3248 * which has already failed to work). Terminate.
3250 send_packet(ssh
, SSH1_MSG_DISCONNECT
,
3251 PKT_STR
, "No more passwords available to try",
3253 logevent("Unable to authenticate");
3254 connection_fatal(ssh
->frontend
, "Unable to authenticate");
3255 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
3259 /* Prompt may have come from server. We've munged it a bit, so
3260 * we know it to be zero-terminated at least once. */
3261 int ret
; /* need not be saved over crReturn */
3262 c_write_untrusted(ssh
, s
->prompt
, strlen(s
->prompt
));
3265 setup_userpass_input(ssh
, s
->password
, sizeof(s
->password
), 0);
3267 crWaitUntil(!pktin
);
3268 ret
= process_userpass_input(ssh
, in
, inlen
);
3272 c_write_str(ssh
, "\r\n");
3276 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3278 * Try public key authentication with the specified
3281 s
->tried_publickey
= 1;
3284 const char *error
= NULL
;
3285 int ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, s
->password
,
3288 c_write_str(ssh
, "Couldn't load private key from ");
3289 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3290 c_write_str(ssh
, " (");
3291 c_write_str(ssh
, error
);
3292 c_write_str(ssh
, ").\r\n");
3293 continue; /* go and try password */
3296 c_write_str(ssh
, "Wrong passphrase.\r\n");
3297 s
->tried_publickey
= 0;
3298 continue; /* try again */
3303 * Send a public key attempt.
3305 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3306 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3309 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3310 c_write_str(ssh
, "Server refused our public key.\r\n");
3311 continue; /* go and try password */
3313 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3314 bombout(("Bizarre response to offer of public key"));
3320 unsigned char buffer
[32];
3321 Bignum challenge
, response
;
3323 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3324 bombout(("Server's RSA challenge was badly formatted"));
3327 response
= rsadecrypt(challenge
, &s
->key
);
3328 freebn(s
->key
.private_exponent
);/* burn the evidence */
3330 for (i
= 0; i
< 32; i
++) {
3331 buffer
[i
] = bignum_byte(response
, 31 - i
);
3335 MD5Update(&md5c
, buffer
, 32);
3336 MD5Update(&md5c
, s
->session_id
, 16);
3337 MD5Final(buffer
, &md5c
);
3339 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3340 PKT_DATA
, buffer
, 16, PKT_END
);
3347 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3348 if (flags
& FLAG_VERBOSE
)
3349 c_write_str(ssh
, "Failed to authenticate with"
3350 " our public key.\r\n");
3351 continue; /* go and try password */
3352 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3353 bombout(("Bizarre response to RSA authentication response"));
3357 break; /* we're through! */
3359 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3361 * Defence against traffic analysis: we send a
3362 * whole bunch of packets containing strings of
3363 * different lengths. One of these strings is the
3364 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3365 * The others are all random data in
3366 * SSH1_MSG_IGNORE packets. This way a passive
3367 * listener can't tell which is the password, and
3368 * hence can't deduce the password length.
3370 * Anybody with a password length greater than 16
3371 * bytes is going to have enough entropy in their
3372 * password that a listener won't find it _that_
3373 * much help to know how long it is. So what we'll
3376 * - if password length < 16, we send 15 packets
3377 * containing string lengths 1 through 15
3379 * - otherwise, we let N be the nearest multiple
3380 * of 8 below the password length, and send 8
3381 * packets containing string lengths N through
3382 * N+7. This won't obscure the order of
3383 * magnitude of the password length, but it will
3384 * introduce a bit of extra uncertainty.
3386 * A few servers (the old 1.2.18 through 1.2.22)
3387 * can't deal with SSH1_MSG_IGNORE. For these
3388 * servers, we need an alternative defence. We make
3389 * use of the fact that the password is interpreted
3390 * as a C string: so we can append a NUL, then some
3393 * One server (a Cisco one) can deal with neither
3394 * SSH1_MSG_IGNORE _nor_ a padded password string.
3395 * For this server we are left with no defences
3396 * against password length sniffing.
3398 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
3400 * The server can deal with SSH1_MSG_IGNORE, so
3401 * we can use the primary defence.
3403 int bottom
, top
, pwlen
, i
;
3406 pwlen
= strlen(s
->password
);
3408 bottom
= 0; /* zero length passwords are OK! :-) */
3411 bottom
= pwlen
& ~7;
3415 assert(pwlen
>= bottom
&& pwlen
<= top
);
3417 randomstr
= snewn(top
+ 1, char);
3419 for (i
= bottom
; i
<= top
; i
++) {
3421 defer_packet(ssh
, s
->pwpkt_type
,
3422 PKTT_PASSWORD
, PKT_STR
, s
->password
,
3423 PKTT_OTHER
, PKT_END
);
3425 for (j
= 0; j
< i
; j
++) {
3427 randomstr
[j
] = random_byte();
3428 } while (randomstr
[j
] == '\0');
3430 randomstr
[i
] = '\0';
3431 defer_packet(ssh
, SSH1_MSG_IGNORE
,
3432 PKT_STR
, randomstr
, PKT_END
);
3435 logevent("Sending password with camouflage packets");
3436 ssh_pkt_defersend(ssh
);
3439 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3441 * The server can't deal with SSH1_MSG_IGNORE
3442 * but can deal with padded passwords, so we
3443 * can use the secondary defence.
3449 len
= strlen(s
->password
);
3450 if (len
< sizeof(string
)) {
3452 strcpy(string
, s
->password
);
3453 len
++; /* cover the zero byte */
3454 while (len
< sizeof(string
)) {
3455 string
[len
++] = (char) random_byte();
3460 logevent("Sending length-padded password");
3461 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3462 PKT_INT
, len
, PKT_DATA
, ss
, len
,
3463 PKTT_OTHER
, PKT_END
);
3466 * The server has _both_
3467 * BUG_CHOKES_ON_SSH1_IGNORE and
3468 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3469 * therefore nothing we can do.
3472 len
= strlen(s
->password
);
3473 logevent("Sending unpadded password");
3474 send_packet(ssh
, s
->pwpkt_type
,
3475 PKTT_PASSWORD
, PKT_INT
, len
,
3476 PKT_DATA
, s
->password
, len
,
3477 PKTT_OTHER
, PKT_END
);
3480 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3481 PKT_STR
, s
->password
, PKTT_OTHER
, PKT_END
);
3484 logevent("Sent password");
3485 memset(s
->password
, 0, strlen(s
->password
));
3487 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3488 if (flags
& FLAG_VERBOSE
)
3489 c_write_str(ssh
, "Access denied\r\n");
3490 logevent("Authentication refused");
3491 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3492 bombout(("Strange packet received, type %d", pktin
->type
));
3497 logevent("Authentication successful");
3502 void sshfwd_close(struct ssh_channel
*c
)
3506 if (ssh
->state
!= SSH_STATE_SESSION
) {
3507 assert(ssh
->state
== SSH_STATE_CLOSED
);
3511 if (c
&& !c
->closes
) {
3513 * If the channel's remoteid is -1, we have sent
3514 * CHANNEL_OPEN for this channel, but it hasn't even been
3515 * acknowledged by the server. So we must set a close flag
3516 * on it now, and then when the server acks the channel
3517 * open, we can close it then.
3519 if (((int)c
->remoteid
) != -1) {
3520 if (ssh
->version
== 1) {
3521 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3524 struct Packet
*pktout
;
3525 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3526 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
3527 ssh2_pkt_send(ssh
, pktout
);
3530 c
->closes
= 1; /* sent MSG_CLOSE */
3531 if (c
->type
== CHAN_X11
) {
3533 logevent("Forwarded X11 connection terminated");
3534 } else if (c
->type
== CHAN_SOCKDATA
||
3535 c
->type
== CHAN_SOCKDATA_DORMANT
) {
3537 logevent("Forwarded port closed");
3542 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
3546 if (ssh
->state
!= SSH_STATE_SESSION
) {
3547 assert(ssh
->state
== SSH_STATE_CLOSED
);
3551 if (ssh
->version
== 1) {
3552 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3553 PKT_INT
, c
->remoteid
,
3555 PKT_INT
, len
, PKT_DATA
, buf
, len
,
3556 PKTT_OTHER
, PKT_END
);
3558 * In SSH1 we can return 0 here - implying that forwarded
3559 * connections are never individually throttled - because
3560 * the only circumstance that can cause throttling will be
3561 * the whole SSH connection backing up, in which case
3562 * _everything_ will be throttled as a whole.
3566 ssh2_add_channel_data(c
, buf
, len
);
3567 return ssh2_try_send(c
);
3571 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
3575 if (ssh
->state
!= SSH_STATE_SESSION
) {
3576 assert(ssh
->state
== SSH_STATE_CLOSED
);
3580 if (ssh
->version
== 1) {
3581 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
3582 c
->v
.v1
.throttling
= 0;
3583 ssh1_throttle(ssh
, -1);
3586 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
3590 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
3592 struct queued_handler
*qh
= ssh
->qhead
;
3596 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
3599 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
3600 ssh
->packet_dispatch
[qh
->msg1
] = NULL
;
3603 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
3604 ssh
->packet_dispatch
[qh
->msg2
] = NULL
;
3608 ssh
->qhead
= qh
->next
;
3610 if (ssh
->qhead
->msg1
> 0) {
3611 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg1
] == NULL
);
3612 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
3614 if (ssh
->qhead
->msg2
> 0) {
3615 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg2
] == NULL
);
3616 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
3619 ssh
->qhead
= ssh
->qtail
= NULL
;
3620 ssh
->packet_dispatch
[pktin
->type
] = NULL
;
3623 qh
->handler(ssh
, pktin
, qh
->ctx
);
3628 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
3629 chandler_fn_t handler
, void *ctx
)
3631 struct queued_handler
*qh
;
3633 qh
= snew(struct queued_handler
);
3636 qh
->handler
= handler
;
3640 if (ssh
->qtail
== NULL
) {
3644 assert(ssh
->packet_dispatch
[qh
->msg1
] == NULL
);
3645 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
3648 assert(ssh
->packet_dispatch
[qh
->msg2
] == NULL
);
3649 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
3652 ssh
->qtail
->next
= qh
;
3657 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
3659 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
3661 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
3662 SSH2_MSG_REQUEST_SUCCESS
)) {
3663 logeventf(ssh
, "Remote port forwarding from %s enabled",
3666 logeventf(ssh
, "Remote port forwarding from %s refused",
3669 rpf
= del234(ssh
->rportfwds
, pf
);
3675 static void ssh_setup_portfwd(Ssh ssh
, const Config
*cfg
)
3677 const char *portfwd_strptr
= cfg
->portfwd
;
3678 struct ssh_portfwd
*epf
;
3681 if (!ssh
->portfwds
) {
3682 ssh
->portfwds
= newtree234(ssh_portcmp
);
3685 * Go through the existing port forwardings and tag them
3686 * with status==DESTROY. Any that we want to keep will be
3687 * re-enabled (status==KEEP) as we go through the
3688 * configuration and find out which bits are the same as
3691 struct ssh_portfwd
*epf
;
3693 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3694 epf
->status
= DESTROY
;
3697 while (*portfwd_strptr
) {
3698 char address_family
, type
;
3699 int sport
,dport
,sserv
,dserv
;
3700 char sports
[256], dports
[256], saddr
[256], host
[256];
3703 address_family
= 'A';
3705 if (*portfwd_strptr
== 'A' ||
3706 *portfwd_strptr
== '4' ||
3707 *portfwd_strptr
== '6')
3708 address_family
= *portfwd_strptr
++;
3709 if (*portfwd_strptr
== 'L' ||
3710 *portfwd_strptr
== 'R' ||
3711 *portfwd_strptr
== 'D')
3712 type
= *portfwd_strptr
++;
3717 while (*portfwd_strptr
&& *portfwd_strptr
!= '\t') {
3718 if (*portfwd_strptr
== ':') {
3720 * We've seen a colon in the middle of the
3721 * source port number. This means that
3722 * everything we've seen until now is the
3723 * source _address_, so we'll move it into
3724 * saddr and start sports from the beginning
3729 if (ssh
->version
== 1 && type
== 'R') {
3730 logeventf(ssh
, "SSH1 cannot handle remote source address "
3731 "spec \"%s\"; ignoring", sports
);
3733 strcpy(saddr
, sports
);
3736 if (n
< 255) sports
[n
++] = *portfwd_strptr
++;
3740 if (*portfwd_strptr
== '\t')
3743 while (*portfwd_strptr
&& *portfwd_strptr
!= ':') {
3744 if (n
< 255) host
[n
++] = *portfwd_strptr
++;
3747 if (*portfwd_strptr
== ':')
3750 while (*portfwd_strptr
) {
3751 if (n
< 255) dports
[n
++] = *portfwd_strptr
++;
3755 dport
= atoi(dports
);
3759 dport
= net_service_lookup(dports
);
3761 logeventf(ssh
, "Service lookup failed for destination"
3762 " port \"%s\"", dports
);
3766 while (*portfwd_strptr
) portfwd_strptr
++;
3768 portfwd_strptr
++; /* eat the NUL and move to next one */
3770 sport
= atoi(sports
);
3774 sport
= net_service_lookup(sports
);
3776 logeventf(ssh
, "Service lookup failed for source"
3777 " port \"%s\"", sports
);
3780 if (sport
&& dport
) {
3781 /* Set up a description of the source port. */
3782 struct ssh_portfwd
*pfrec
, *epfrec
;
3784 pfrec
= snew(struct ssh_portfwd
);
3786 pfrec
->saddr
= *saddr ?
dupstr(saddr
) : NULL
;
3787 pfrec
->sport
= sport
;
3788 pfrec
->daddr
= *host ?
dupstr(host
) : NULL
;
3789 pfrec
->dport
= dport
;
3790 pfrec
->local
= NULL
;
3791 pfrec
->remote
= NULL
;
3792 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
3793 address_family
== '6' ? ADDRTYPE_IPV6
:
3796 epfrec
= add234(ssh
->portfwds
, pfrec
);
3797 if (epfrec
!= pfrec
) {
3799 * We already have a port forwarding with precisely
3800 * these parameters. Hence, no need to do anything;
3801 * simply tag the existing one as KEEP.
3803 epfrec
->status
= KEEP
;
3804 free_portfwd(pfrec
);
3806 pfrec
->status
= CREATE
;
3812 * Now go through and destroy any port forwardings which were
3815 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3816 if (epf
->status
== DESTROY
) {
3819 message
= dupprintf("%s port forwarding from %s%s%d",
3820 epf
->type
== 'L' ?
"local" :
3821 epf
->type
== 'R' ?
"remote" : "dynamic",
3822 epf
->saddr ? epf
->saddr
: "",
3823 epf
->saddr ?
":" : "",
3826 if (epf
->type
!= 'D') {
3827 char *msg2
= dupprintf("%s to %s:%d", message
,
3828 epf
->daddr
, epf
->dport
);
3833 logeventf(ssh
, "Cancelling %s", message
);
3837 struct ssh_rportfwd
*rpf
= epf
->remote
;
3838 struct Packet
*pktout
;
3841 * Cancel the port forwarding at the server
3844 if (ssh
->version
== 1) {
3846 * We cannot cancel listening ports on the
3847 * server side in SSH1! There's no message
3848 * to support it. Instead, we simply remove
3849 * the rportfwd record from the local end
3850 * so that any connections the server tries
3851 * to make on it are rejected.
3854 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
3855 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
3856 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
3858 ssh2_pkt_addstring(pktout
, epf
->saddr
);
3859 } else if (ssh
->cfg
.rport_acceptall
) {
3860 ssh2_pkt_addstring(pktout
, "0.0.0.0");
3862 ssh2_pkt_addstring(pktout
, "127.0.0.1");
3864 ssh2_pkt_adduint32(pktout
, epf
->sport
);
3865 ssh2_pkt_send(ssh
, pktout
);
3868 del234(ssh
->rportfwds
, rpf
);
3870 } else if (epf
->local
) {
3871 pfd_terminate(epf
->local
);
3874 delpos234(ssh
->portfwds
, i
);
3876 i
--; /* so we don't skip one in the list */
3880 * And finally, set up any new port forwardings (status==CREATE).
3882 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3883 if (epf
->status
== CREATE
) {
3884 char *sportdesc
, *dportdesc
;
3885 sportdesc
= dupprintf("%s%s%d",
3886 epf
->saddr ? epf
->saddr
: "",
3887 epf
->saddr ?
":" : "",
3889 if (epf
->type
== 'D') {
3892 dportdesc
= dupprintf("%s:%d", epf
->daddr
, epf
->dport
);
3895 if (epf
->type
== 'L') {
3896 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
3897 epf
->saddr
, epf
->sport
,
3900 epf
->addressfamily
);
3902 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
3903 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
3904 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
3905 sportdesc
, dportdesc
,
3906 err ?
" failed: " : "", err ? err
: "");
3907 } else if (epf
->type
== 'D') {
3908 const char *err
= pfd_addforward(NULL
, -1,
3909 epf
->saddr
, epf
->sport
,
3912 epf
->addressfamily
);
3914 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
3915 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
3916 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
3918 err ?
" failed: " : "", err ? err
: "");
3920 struct ssh_rportfwd
*pf
;
3923 * Ensure the remote port forwardings tree exists.
3925 if (!ssh
->rportfwds
) {
3926 if (ssh
->version
== 1)
3927 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
3929 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
3932 pf
= snew(struct ssh_rportfwd
);
3933 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
3934 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
3935 pf
->dport
= epf
->dport
;
3936 pf
->sport
= epf
->sport
;
3937 if (add234(ssh
->rportfwds
, pf
) != pf
) {
3938 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
3939 epf
->daddr
, epf
->dport
);
3942 logeventf(ssh
, "Requesting remote port %s"
3943 " forward to %s", sportdesc
, dportdesc
);
3945 pf
->sportdesc
= sportdesc
;
3950 if (ssh
->version
== 1) {
3951 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
3952 PKT_INT
, epf
->sport
,
3953 PKT_STR
, epf
->daddr
,
3954 PKT_INT
, epf
->dport
,
3956 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
3958 ssh_rportfwd_succfail
, pf
);
3960 struct Packet
*pktout
;
3961 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
3962 ssh2_pkt_addstring(pktout
, "tcpip-forward");
3963 ssh2_pkt_addbool(pktout
, 1);/* want reply */
3965 ssh2_pkt_addstring(pktout
, epf
->saddr
);
3966 } else if (ssh
->cfg
.rport_acceptall
) {
3967 ssh2_pkt_addstring(pktout
, "0.0.0.0");
3969 ssh2_pkt_addstring(pktout
, "127.0.0.1");
3971 ssh2_pkt_adduint32(pktout
, epf
->sport
);
3972 ssh2_pkt_send(ssh
, pktout
);
3974 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
3975 SSH2_MSG_REQUEST_FAILURE
,
3976 ssh_rportfwd_succfail
, pf
);
3985 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
3988 int stringlen
, bufsize
;
3990 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
3991 if (string
== NULL
) {
3992 bombout(("Incoming terminal data packet was badly formed"));
3996 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
3998 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3999 ssh
->v1_stdout_throttling
= 1;
4000 ssh1_throttle(ssh
, +1);
4004 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4006 /* Remote side is trying to open a channel to talk to our
4007 * X-Server. Give them back a local channel number. */
4008 struct ssh_channel
*c
;
4009 int remoteid
= ssh_pkt_getuint32(pktin
);
4011 logevent("Received X11 connect request");
4012 /* Refuse if X11 forwarding is disabled. */
4013 if (!ssh
->X11_fwd_enabled
) {
4014 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4015 PKT_INT
, remoteid
, PKT_END
);
4016 logevent("Rejected X11 connect request");
4018 c
= snew(struct ssh_channel
);
4021 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
4022 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
4023 logevent("Opening X11 forward connection failed");
4025 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4026 PKT_INT
, remoteid
, PKT_END
);
4029 ("Opening X11 forward connection succeeded");
4030 c
->remoteid
= remoteid
;
4031 c
->localid
= alloc_channel_id(ssh
);
4033 c
->v
.v1
.throttling
= 0;
4034 c
->type
= CHAN_X11
; /* identify channel type */
4035 add234(ssh
->channels
, c
);
4036 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4037 PKT_INT
, c
->remoteid
, PKT_INT
,
4038 c
->localid
, PKT_END
);
4039 logevent("Opened X11 forward channel");
4044 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4046 /* Remote side is trying to open a channel to talk to our
4047 * agent. Give them back a local channel number. */
4048 struct ssh_channel
*c
;
4049 int remoteid
= ssh_pkt_getuint32(pktin
);
4051 /* Refuse if agent forwarding is disabled. */
4052 if (!ssh
->agentfwd_enabled
) {
4053 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4054 PKT_INT
, remoteid
, PKT_END
);
4056 c
= snew(struct ssh_channel
);
4058 c
->remoteid
= remoteid
;
4059 c
->localid
= alloc_channel_id(ssh
);
4061 c
->v
.v1
.throttling
= 0;
4062 c
->type
= CHAN_AGENT
; /* identify channel type */
4063 c
->u
.a
.lensofar
= 0;
4064 add234(ssh
->channels
, c
);
4065 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4066 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4071 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4073 /* Remote side is trying to open a channel to talk to a
4074 * forwarded port. Give them back a local channel number. */
4075 struct ssh_channel
*c
;
4076 struct ssh_rportfwd pf
, *pfp
;
4079 char *host
, buf
[1024];
4081 c
= snew(struct ssh_channel
);
4084 remoteid
= ssh_pkt_getuint32(pktin
);
4085 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4086 port
= ssh_pkt_getuint32(pktin
);
4088 if (hostsize
>= lenof(pf
.dhost
))
4089 hostsize
= lenof(pf
.dhost
)-1;
4090 memcpy(pf
.dhost
, host
, hostsize
);
4091 pf
.dhost
[hostsize
] = '\0';
4093 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4096 sprintf(buf
, "Rejected remote port open request for %s:%d",
4099 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4100 PKT_INT
, remoteid
, PKT_END
);
4102 sprintf(buf
, "Received remote port open request for %s:%d",
4105 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4106 c
, &ssh
->cfg
, pfp
->pfrec
->addressfamily
);
4109 sprintf(buf
, "Port open failed: %s", e
);
4112 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4113 PKT_INT
, remoteid
, PKT_END
);
4115 c
->remoteid
= remoteid
;
4116 c
->localid
= alloc_channel_id(ssh
);
4118 c
->v
.v1
.throttling
= 0;
4119 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4120 add234(ssh
->channels
, c
);
4121 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4122 PKT_INT
, c
->remoteid
, PKT_INT
,
4123 c
->localid
, PKT_END
);
4124 logevent("Forwarded port opened successfully");
4129 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4131 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4132 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4133 struct ssh_channel
*c
;
4135 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4136 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4137 c
->remoteid
= localid
;
4138 c
->type
= CHAN_SOCKDATA
;
4139 c
->v
.v1
.throttling
= 0;
4140 pfd_confirm(c
->u
.pfd
.s
);
4143 if (c
&& c
->closes
) {
4145 * We have a pending close on this channel,
4146 * which we decided on before the server acked
4147 * the channel open. So now we know the
4148 * remoteid, we can close it again.
4150 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
4151 PKT_INT
, c
->remoteid
, PKT_END
);
4155 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4157 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4158 struct ssh_channel
*c
;
4160 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4161 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4162 logevent("Forwarded connection refused by server");
4163 pfd_close(c
->u
.pfd
.s
);
4164 del234(ssh
->channels
, c
);
4169 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4171 /* Remote side closes a channel. */
4172 unsigned i
= ssh_pkt_getuint32(pktin
);
4173 struct ssh_channel
*c
;
4174 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4175 if (c
&& ((int)c
->remoteid
) != -1) {
4178 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
4180 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
4181 logevent("Forwarded X11 connection terminated");
4182 assert(c
->u
.x11
.s
!= NULL
);
4183 x11_close(c
->u
.x11
.s
);
4186 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
4187 logevent("Forwarded port closed");
4188 assert(c
->u
.pfd
.s
!= NULL
);
4189 pfd_close(c
->u
.pfd
.s
);
4193 c
->closes
|= (closetype
<< 2); /* seen this message */
4194 if (!(c
->closes
& closetype
)) {
4195 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
4197 c
->closes
|= closetype
; /* sent it too */
4200 if (c
->closes
== 15) {
4201 del234(ssh
->channels
, c
);
4205 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4206 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
4207 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
4212 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
4214 /* Data sent down one of our channels. */
4215 int i
= ssh_pkt_getuint32(pktin
);
4218 struct ssh_channel
*c
;
4220 ssh_pkt_getstring(pktin
, &p
, &len
);
4222 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4227 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
4230 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
4233 /* Data for an agent message. Buffer it. */
4235 if (c
->u
.a
.lensofar
< 4) {
4236 unsigned int l
= min(4 - c
->u
.a
.lensofar
, len
);
4237 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
4241 c
->u
.a
.lensofar
+= l
;
4243 if (c
->u
.a
.lensofar
== 4) {
4245 4 + GET_32BIT(c
->u
.a
.msglen
);
4246 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
4248 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4250 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
4252 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4254 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
4258 c
->u
.a
.lensofar
+= l
;
4260 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4263 if (agent_query(c
->u
.a
.message
,
4266 ssh_agentf_callback
, c
))
4267 ssh_agentf_callback(c
, reply
, replylen
);
4268 sfree(c
->u
.a
.message
);
4269 c
->u
.a
.lensofar
= 0;
4272 bufsize
= 0; /* agent channels never back up */
4275 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4276 c
->v
.v1
.throttling
= 1;
4277 ssh1_throttle(ssh
, +1);
4282 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
4285 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
4286 sprintf(buf
, "Server sent command exit status %d",
4289 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
4291 * In case `helpful' firewalls or proxies tack
4292 * extra human-readable text on the end of the
4293 * session which we might mistake for another
4294 * encrypted packet, we close the session once
4295 * we've sent EXIT_CONFIRMATION.
4297 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
4300 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
4301 struct Packet
*pktin
)
4303 crBegin(ssh
->do_ssh1_connection_crstate
);
4305 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
4306 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
4307 ssh1_smsg_stdout_stderr_data
;
4309 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
4310 ssh1_msg_channel_open_confirmation
;
4311 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
4312 ssh1_msg_channel_open_failure
;
4313 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
4314 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
4315 ssh1_msg_channel_close
;
4316 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
4317 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
4319 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
4320 logevent("Requesting agent forwarding");
4321 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
4325 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4326 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4327 bombout(("Protocol confusion"));
4329 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4330 logevent("Agent forwarding refused");
4332 logevent("Agent forwarding enabled");
4333 ssh
->agentfwd_enabled
= TRUE
;
4334 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
4338 if (ssh
->cfg
.x11_forward
) {
4339 char proto
[20], data
[64];
4340 logevent("Requesting X11 forwarding");
4341 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
4342 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
4343 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
4344 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
4345 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4346 PKT_STR
, proto
, PKT_STR
, data
,
4347 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
4350 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4351 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
4356 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4357 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4358 bombout(("Protocol confusion"));
4360 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4361 logevent("X11 forwarding refused");
4363 logevent("X11 forwarding enabled");
4364 ssh
->X11_fwd_enabled
= TRUE
;
4365 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
4369 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
4370 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
4372 if (!ssh
->cfg
.nopty
) {
4373 /* Unpick the terminal-speed string. */
4374 /* XXX perhaps we should allow no speeds to be sent. */
4375 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
4376 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
4377 /* Send the pty request. */
4378 send_packet(ssh
, SSH1_CMSG_REQUEST_PTY
,
4379 PKT_STR
, ssh
->cfg
.termtype
,
4380 PKT_INT
, ssh
->term_height
,
4381 PKT_INT
, ssh
->term_width
,
4382 PKT_INT
, 0, PKT_INT
, 0, /* width,height in pixels */
4383 PKT_CHAR
, 192, PKT_INT
, ssh
->ispeed
, /* TTY_OP_ISPEED */
4384 PKT_CHAR
, 193, PKT_INT
, ssh
->ospeed
, /* TTY_OP_OSPEED */
4385 PKT_CHAR
, 0, PKT_END
);
4386 ssh
->state
= SSH_STATE_INTERMED
;
4390 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4391 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4392 bombout(("Protocol confusion"));
4394 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4395 c_write_str(ssh
, "Server refused to allocate pty\r\n");
4396 ssh
->editing
= ssh
->echoing
= 1;
4398 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4399 ssh
->ospeed
, ssh
->ispeed
);
4401 ssh
->editing
= ssh
->echoing
= 1;
4404 if (ssh
->cfg
.compression
) {
4405 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
4409 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4410 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4411 bombout(("Protocol confusion"));
4413 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4414 c_write_str(ssh
, "Server refused to compress\r\n");
4416 logevent("Started compression");
4417 ssh
->v1_compressing
= TRUE
;
4418 ssh
->cs_comp_ctx
= zlib_compress_init();
4419 logevent("Initialised zlib (RFC1950) compression");
4420 ssh
->sc_comp_ctx
= zlib_decompress_init();
4421 logevent("Initialised zlib (RFC1950) decompression");
4425 * Start the shell or command.
4427 * Special case: if the first-choice command is an SSH2
4428 * subsystem (hence not usable here) and the second choice
4429 * exists, we fall straight back to that.
4432 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
4434 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
4435 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
4436 ssh
->fallback_cmd
= TRUE
;
4439 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
4441 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
4442 logevent("Started session");
4445 ssh
->state
= SSH_STATE_SESSION
;
4446 if (ssh
->size_needed
)
4447 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
4448 if (ssh
->eof_needed
)
4449 ssh_special(ssh
, TS_EOF
);
4452 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
4454 ssh
->channels
= newtree234(ssh_channelcmp
);
4458 * By this point, most incoming packets are already being
4459 * handled by the dispatch table, and we need only pay
4460 * attention to the unusual ones.
4465 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
4466 /* may be from EXEC_SHELL on some servers */
4467 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4468 /* may be from EXEC_SHELL on some servers
4469 * if no pty is available or in other odd cases. Ignore */
4471 bombout(("Strange packet received: type %d", pktin
->type
));
4476 int len
= min(inlen
, 512);
4477 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
, PKTT_DATA
,
4478 PKT_INT
, len
, PKT_DATA
, in
, len
,
4479 PKTT_OTHER
, PKT_END
);
4490 * Handle the top-level SSH2 protocol.
4492 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
4497 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4498 buf
= dupprintf("Remote debug message: %.*s", msglen
, msg
);
4503 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
4505 /* log reason code in disconnect message */
4509 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4510 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
4513 void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
4515 /* Do nothing, because we're ignoring it! Duhh. */
4518 static void ssh1_protocol_setup(Ssh ssh
)
4523 * Most messages are handled by the coroutines.
4525 for (i
= 0; i
< 256; i
++)
4526 ssh
->packet_dispatch
[i
] = NULL
;
4529 * These special message types we install handlers for.
4531 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
4532 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
4533 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
4536 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
4537 struct Packet
*pktin
)
4539 if (ssh
->state
== SSH_STATE_CLOSED
)
4542 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
4543 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
4547 if (!ssh
->protocol_initial_phase_done
) {
4548 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
4549 ssh
->protocol_initial_phase_done
= TRUE
;
4554 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
4558 * Utility routine for decoding comma-separated strings in KEXINIT.
4560 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
4563 if (!needle
|| !haystack
) /* protect against null pointers */
4565 needlen
= strlen(needle
);
4568 * Is it at the start of the string?
4570 if (haylen
>= needlen
&& /* haystack is long enough */
4571 !memcmp(needle
, haystack
, needlen
) && /* initial match */
4572 (haylen
== needlen
|| haystack
[needlen
] == ',')
4573 /* either , or EOS follows */
4577 * If not, search for the next comma and resume after that.
4578 * If no comma found, terminate.
4580 while (haylen
> 0 && *haystack
!= ',')
4581 haylen
--, haystack
++;
4584 haylen
--, haystack
++; /* skip over comma itself */
4589 * SSH2 key creation method.
4591 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
,
4592 unsigned char *sessid
, char chr
,
4593 unsigned char *keyspace
)
4596 /* First 20 bytes. */
4598 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4600 SHA_Bytes(&s
, H
, 20);
4601 SHA_Bytes(&s
, &chr
, 1);
4602 SHA_Bytes(&s
, sessid
, 20);
4603 SHA_Final(&s
, keyspace
);
4604 /* Next 20 bytes. */
4606 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4608 SHA_Bytes(&s
, H
, 20);
4609 SHA_Bytes(&s
, keyspace
, 20);
4610 SHA_Final(&s
, keyspace
+ 20);
4614 * Handle the SSH2 transport layer.
4616 static int do_ssh2_transport(Ssh ssh
, unsigned char *in
, int inlen
,
4617 struct Packet
*pktin
)
4619 struct do_ssh2_transport_state
{
4620 int nbits
, pbits
, warn
;
4621 Bignum p
, g
, e
, f
, K
;
4622 int kex_init_value
, kex_reply_value
;
4623 const struct ssh_mac
**maclist
;
4625 const struct ssh2_cipher
*cscipher_tobe
;
4626 const struct ssh2_cipher
*sccipher_tobe
;
4627 const struct ssh_mac
*csmac_tobe
;
4628 const struct ssh_mac
*scmac_tobe
;
4629 const struct ssh_compress
*cscomp_tobe
;
4630 const struct ssh_compress
*sccomp_tobe
;
4631 char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
4632 int hostkeylen
, siglen
;
4633 void *hkey
; /* actual host key */
4634 unsigned char exchange_hash
[20];
4635 int n_preferred_kex
;
4636 const struct ssh_kex
*preferred_kex
[KEX_MAX
];
4637 int n_preferred_ciphers
;
4638 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
4639 const struct ssh_compress
*preferred_comp
;
4641 struct Packet
*pktout
;
4643 crState(do_ssh2_transport_state
);
4645 crBegin(ssh
->do_ssh2_transport_crstate
);
4647 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
4648 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
4649 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
4656 * Set up the preferred key exchange. (NULL => warn below here)
4658 s
->n_preferred_kex
= 0;
4659 for (i
= 0; i
< KEX_MAX
; i
++) {
4660 switch (ssh
->cfg
.ssh_kexlist
[i
]) {
4662 s
->preferred_kex
[s
->n_preferred_kex
++] =
4663 &ssh_diffiehellman_gex
;
4666 s
->preferred_kex
[s
->n_preferred_kex
++] =
4667 &ssh_diffiehellman_group14
;
4670 s
->preferred_kex
[s
->n_preferred_kex
++] =
4671 &ssh_diffiehellman_group1
;
4674 /* Flag for later. Don't bother if it's the last in
4676 if (i
< KEX_MAX
- 1) {
4677 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
4687 * Set up the preferred ciphers. (NULL => warn below here)
4689 s
->n_preferred_ciphers
= 0;
4690 for (i
= 0; i
< CIPHER_MAX
; i
++) {
4691 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
4692 case CIPHER_BLOWFISH
:
4693 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
4696 if (ssh
->cfg
.ssh2_des_cbc
) {
4697 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
4701 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
4704 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
4707 /* Flag for later. Don't bother if it's the last in
4709 if (i
< CIPHER_MAX
- 1) {
4710 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
4718 * Set up preferred compression.
4720 if (ssh
->cfg
.compression
)
4721 s
->preferred_comp
= &ssh_zlib
;
4723 s
->preferred_comp
= &ssh_comp_none
;
4726 * Be prepared to work around the buggy MAC problem.
4728 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
4729 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
4731 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
4735 int i
, j
, commalist_started
;
4738 * Enable queueing of outgoing auth- or connection-layer
4739 * packets while we are in the middle of a key exchange.
4741 ssh
->queueing
= TRUE
;
4744 * Flag that KEX is in progress.
4746 ssh
->kex_in_progress
= TRUE
;
4749 * Construct and send our key exchange packet.
4751 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
4752 for (i
= 0; i
< 16; i
++)
4753 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
4754 /* List key exchange algorithms. */
4755 ssh2_pkt_addstring_start(s
->pktout
);
4756 commalist_started
= 0;
4757 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
4758 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
4759 if (!k
) continue; /* warning flag */
4760 if (commalist_started
)
4761 ssh2_pkt_addstring_str(s
->pktout
, ",");
4762 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_kex
[i
]->name
);
4763 commalist_started
= 1;
4765 /* List server host key algorithms. */
4766 ssh2_pkt_addstring_start(s
->pktout
);
4767 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
4768 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
4769 if (i
< lenof(hostkey_algs
) - 1)
4770 ssh2_pkt_addstring_str(s
->pktout
, ",");
4772 /* List client->server encryption algorithms. */
4773 ssh2_pkt_addstring_start(s
->pktout
);
4774 commalist_started
= 0;
4775 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4776 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4777 if (!c
) continue; /* warning flag */
4778 for (j
= 0; j
< c
->nciphers
; j
++) {
4779 if (commalist_started
)
4780 ssh2_pkt_addstring_str(s
->pktout
, ",");
4781 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4782 commalist_started
= 1;
4785 /* List server->client encryption algorithms. */
4786 ssh2_pkt_addstring_start(s
->pktout
);
4787 commalist_started
= 0;
4788 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4789 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4790 if (!c
) continue; /* warning flag */
4791 for (j
= 0; j
< c
->nciphers
; j
++) {
4792 if (commalist_started
)
4793 ssh2_pkt_addstring_str(s
->pktout
, ",");
4794 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4795 commalist_started
= 1;
4798 /* List client->server MAC algorithms. */
4799 ssh2_pkt_addstring_start(s
->pktout
);
4800 for (i
= 0; i
< s
->nmacs
; i
++) {
4801 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4802 if (i
< s
->nmacs
- 1)
4803 ssh2_pkt_addstring_str(s
->pktout
, ",");
4805 /* List server->client MAC algorithms. */
4806 ssh2_pkt_addstring_start(s
->pktout
);
4807 for (i
= 0; i
< s
->nmacs
; i
++) {
4808 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4809 if (i
< s
->nmacs
- 1)
4810 ssh2_pkt_addstring_str(s
->pktout
, ",");
4812 /* List client->server compression algorithms. */
4813 ssh2_pkt_addstring_start(s
->pktout
);
4814 assert(lenof(compressions
) > 1);
4815 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4816 for (i
= 0; i
< lenof(compressions
); i
++) {
4817 const struct ssh_compress
*c
= compressions
[i
];
4818 if (c
!= s
->preferred_comp
) {
4819 ssh2_pkt_addstring_str(s
->pktout
, ",");
4820 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4823 /* List server->client compression algorithms. */
4824 ssh2_pkt_addstring_start(s
->pktout
);
4825 assert(lenof(compressions
) > 1);
4826 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4827 for (i
= 0; i
< lenof(compressions
); i
++) {
4828 const struct ssh_compress
*c
= compressions
[i
];
4829 if (c
!= s
->preferred_comp
) {
4830 ssh2_pkt_addstring_str(s
->pktout
, ",");
4831 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4834 /* List client->server languages. Empty list. */
4835 ssh2_pkt_addstring_start(s
->pktout
);
4836 /* List server->client languages. Empty list. */
4837 ssh2_pkt_addstring_start(s
->pktout
);
4838 /* First KEX packet does _not_ follow, because we're not that brave. */
4839 ssh2_pkt_addbool(s
->pktout
, FALSE
);
4841 ssh2_pkt_adduint32(s
->pktout
, 0);
4844 ssh
->exhash
= ssh
->exhashbase
;
4845 sha_string(&ssh
->exhash
, s
->pktout
->data
+ 5, s
->pktout
->length
- 5);
4847 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
4851 if (pktin
->length
> 5)
4852 sha_string(&ssh
->exhash
, pktin
->data
+ 5, pktin
->length
- 5);
4855 * Now examine the other side's KEXINIT to see what we're up
4862 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
4863 bombout(("expected key exchange packet from server"));
4867 ssh
->hostkey
= NULL
;
4868 s
->cscipher_tobe
= NULL
;
4869 s
->sccipher_tobe
= NULL
;
4870 s
->csmac_tobe
= NULL
;
4871 s
->scmac_tobe
= NULL
;
4872 s
->cscomp_tobe
= NULL
;
4873 s
->sccomp_tobe
= NULL
;
4874 pktin
->savedpos
+= 16; /* skip garbage cookie */
4875 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
4877 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
4878 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
4881 } else if (in_commasep_string(k
->name
, str
, len
)) {
4886 askalg(ssh
->frontend
, "key-exchange algorithm",
4892 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
4893 str ? str
: "(null)"));
4896 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
4897 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
4898 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
4899 ssh
->hostkey
= hostkey_algs
[i
];
4903 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
4905 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4906 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4910 for (j
= 0; j
< c
->nciphers
; j
++) {
4911 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
4912 s
->cscipher_tobe
= c
->list
[j
];
4917 if (s
->cscipher_tobe
) {
4919 askalg(ssh
->frontend
, "client-to-server cipher",
4920 s
->cscipher_tobe
->name
);
4924 if (!s
->cscipher_tobe
) {
4925 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4926 str ? str
: "(null)"));
4930 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
4932 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4933 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4937 for (j
= 0; j
< c
->nciphers
; j
++) {
4938 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
4939 s
->sccipher_tobe
= c
->list
[j
];
4944 if (s
->sccipher_tobe
) {
4946 askalg(ssh
->frontend
, "server-to-client cipher",
4947 s
->sccipher_tobe
->name
);
4951 if (!s
->sccipher_tobe
) {
4952 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4953 str ? str
: "(null)"));
4957 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
4958 for (i
= 0; i
< s
->nmacs
; i
++) {
4959 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
4960 s
->csmac_tobe
= s
->maclist
[i
];
4964 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
4965 for (i
= 0; i
< s
->nmacs
; i
++) {
4966 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
4967 s
->scmac_tobe
= s
->maclist
[i
];
4971 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
4972 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
4973 const struct ssh_compress
*c
=
4974 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
4975 if (in_commasep_string(c
->name
, str
, len
)) {
4980 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
4981 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
4982 const struct ssh_compress
*c
=
4983 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
4984 if (in_commasep_string(c
->name
, str
, len
)) {
4992 * Work out the number of bits of key we will need from the key
4993 * exchange. We start with the maximum key length of either
4999 csbits
= s
->cscipher_tobe
->keylen
;
5000 scbits
= s
->sccipher_tobe
->keylen
;
5001 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5003 /* The keys only have 160-bit entropy, since they're based on
5004 * a SHA-1 hash. So cap the key size at 160 bits. */
5009 * If we're doing Diffie-Hellman group exchange, start by
5010 * requesting a group.
5012 if (!ssh
->kex
->pdata
) {
5013 logevent("Doing Diffie-Hellman group exchange");
5014 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
5016 * Work out how big a DH group we will need to allow that
5019 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
5020 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
5021 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
5022 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5025 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
5026 bombout(("expected key exchange group packet from server"));
5029 s
->p
= ssh2_pkt_getmp(pktin
);
5030 s
->g
= ssh2_pkt_getmp(pktin
);
5031 if (!s
->p
|| !s
->g
) {
5032 bombout(("unable to read mp-ints from incoming group packet"));
5035 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
5036 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
5037 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
5039 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP
;
5040 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
5041 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
5042 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
5043 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
5044 ssh
->kex
->groupname
);
5047 logevent("Doing Diffie-Hellman key exchange");
5049 * Now generate and send e for Diffie-Hellman.
5051 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
5052 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
5053 ssh2_pkt_addmp(s
->pktout
, s
->e
);
5054 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5057 if (pktin
->type
!= s
->kex_reply_value
) {
5058 bombout(("expected key exchange reply packet from server"));
5061 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5062 s
->f
= ssh2_pkt_getmp(pktin
);
5064 bombout(("unable to parse key exchange reply packet"));
5067 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5069 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
5071 sha_string(&ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
5072 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5073 sha_uint32(&ssh
->exhash
, s
->pbits
);
5074 sha_mpint(&ssh
->exhash
, s
->p
);
5075 sha_mpint(&ssh
->exhash
, s
->g
);
5077 sha_mpint(&ssh
->exhash
, s
->e
);
5078 sha_mpint(&ssh
->exhash
, s
->f
);
5079 sha_mpint(&ssh
->exhash
, s
->K
);
5080 SHA_Final(&ssh
->exhash
, s
->exchange_hash
);
5082 dh_cleanup(ssh
->kex_ctx
);
5083 ssh
->kex_ctx
= NULL
;
5086 debug(("Exchange hash is:\n"));
5087 dmemdump(s
->exchange_hash
, 20);
5090 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5092 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
5093 (char *)s
->exchange_hash
, 20)) {
5094 bombout(("Server's host key did not match the signature supplied"));
5099 * Authenticate remote host: verify host key. (We've already
5100 * checked the signature of the exchange hash.)
5102 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
5103 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
5104 verify_ssh_host_key(ssh
->frontend
,
5105 ssh
->savedhost
, ssh
->savedport
, ssh
->hostkey
->keytype
,
5106 s
->keystr
, s
->fingerprint
);
5107 if (s
->first_kex
) { /* don't bother logging this in rekeys */
5108 logevent("Host key fingerprint is:");
5109 logevent(s
->fingerprint
);
5111 sfree(s
->fingerprint
);
5113 ssh
->hostkey
->freekey(s
->hkey
);
5116 * The exchange hash from the very first key exchange is also
5117 * the session id, used in session key construction and
5121 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
5122 sizeof(s
->exchange_hash
));
5125 * Send SSH2_MSG_NEWKEYS.
5127 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
5128 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5129 ssh
->outgoing_data_size
= 0; /* start counting from here */
5132 * We've sent client NEWKEYS, so create and initialise
5133 * client-to-server session keys.
5135 if (ssh
->cs_cipher_ctx
)
5136 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
5137 ssh
->cscipher
= s
->cscipher_tobe
;
5138 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
5140 if (ssh
->cs_mac_ctx
)
5141 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
5142 ssh
->csmac
= s
->csmac_tobe
;
5143 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
5145 if (ssh
->cs_comp_ctx
)
5146 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
5147 ssh
->cscomp
= s
->cscomp_tobe
;
5148 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
5151 * Set IVs on client-to-server keys. Here we use the exchange
5152 * hash from the _first_ key exchange.
5155 unsigned char keyspace
[40];
5156 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'C',keyspace
);
5157 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
5158 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'A',keyspace
);
5159 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
5160 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'E',keyspace
);
5161 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
5164 logeventf(ssh
, "Initialised %.200s client->server encryption",
5165 ssh
->cscipher
->text_name
);
5166 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
5167 ssh
->csmac
->text_name
);
5168 if (ssh
->cscomp
->text_name
)
5169 logeventf(ssh
, "Initialised %s compression",
5170 ssh
->cscomp
->text_name
);
5173 * Now our end of the key exchange is complete, we can send all
5174 * our queued higher-layer packets.
5176 ssh
->queueing
= FALSE
;
5177 ssh2_pkt_queuesend(ssh
);
5180 * Expect SSH2_MSG_NEWKEYS from server.
5183 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
5184 bombout(("expected new-keys packet from server"));
5187 ssh
->incoming_data_size
= 0; /* start counting from here */
5190 * We've seen server NEWKEYS, so create and initialise
5191 * server-to-client session keys.
5193 if (ssh
->sc_cipher_ctx
)
5194 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
5195 ssh
->sccipher
= s
->sccipher_tobe
;
5196 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
5198 if (ssh
->sc_mac_ctx
)
5199 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
5200 ssh
->scmac
= s
->scmac_tobe
;
5201 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
5203 if (ssh
->sc_comp_ctx
)
5204 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
5205 ssh
->sccomp
= s
->sccomp_tobe
;
5206 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
5209 * Set IVs on server-to-client keys. Here we use the exchange
5210 * hash from the _first_ key exchange.
5213 unsigned char keyspace
[40];
5214 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'D',keyspace
);
5215 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
5216 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'B',keyspace
);
5217 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
5218 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'F',keyspace
);
5219 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
5221 logeventf(ssh
, "Initialised %.200s server->client encryption",
5222 ssh
->sccipher
->text_name
);
5223 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
5224 ssh
->scmac
->text_name
);
5225 if (ssh
->sccomp
->text_name
)
5226 logeventf(ssh
, "Initialised %s decompression",
5227 ssh
->sccomp
->text_name
);
5230 * Free key exchange data.
5234 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5240 * Key exchange is over. Schedule a timer for our next rekey.
5242 ssh
->kex_in_progress
= FALSE
;
5243 ssh
->last_rekey
= GETTICKCOUNT();
5244 if (ssh
->cfg
.ssh_rekey_time
!= 0)
5245 ssh
->next_rekey
= schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
5249 * If this is the first key exchange phase, we must pass the
5250 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5251 * wants to see it but because it will need time to initialise
5252 * itself before it sees an actual packet. In subsequent key
5253 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5254 * it would only confuse the layer above.
5256 if (!s
->first_kex
) {
5262 * Now we're encrypting. Begin returning 1 to the protocol main
5263 * function so that other things can run on top of the
5264 * transport. If we ever see a KEXINIT, we must go back to the
5267 * We _also_ go back to the start if we see pktin==NULL and
5268 * inlen==-1, because this is a special signal meaning
5269 * `initiate client-driven rekey', and `in' contains a message
5270 * giving the reason for the rekey.
5272 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
5273 (!pktin
&& inlen
== -1))) {
5277 logevent("Server initiated key re-exchange");
5279 logevent((char *)in
);
5281 goto begin_key_exchange
;
5287 * Add data to an SSH2 channel output buffer.
5289 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
5292 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
5296 * Attempt to send data on an SSH2 channel.
5298 static int ssh2_try_send(struct ssh_channel
*c
)
5301 struct Packet
*pktout
;
5303 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
5306 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
5307 if ((unsigned)len
> c
->v
.v2
.remwindow
)
5308 len
= c
->v
.v2
.remwindow
;
5309 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
5310 len
= c
->v
.v2
.remmaxpkt
;
5311 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
5312 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5313 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
5314 ssh2_pkt_addstring_start(pktout
);
5315 ssh2_pkt_addstring_data(pktout
, data
, len
);
5316 end_log_omission(ssh
, pktout
);
5317 ssh2_pkt_send(ssh
, pktout
);
5318 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
5319 c
->v
.v2
.remwindow
-= len
;
5323 * After having sent as much data as we can, return the amount
5326 return bufchain_size(&c
->v
.v2
.outbuffer
);
5330 * Potentially enlarge the window on an SSH2 channel.
5332 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
5337 * Never send WINDOW_ADJUST for a channel that the remote side
5338 * already thinks it's closed; there's no point, since it won't
5339 * be sending any more data anyway.
5344 if (newwin
> c
->v
.v2
.locwindow
) {
5345 struct Packet
*pktout
;
5347 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5348 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5349 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
5350 ssh2_pkt_send(ssh
, pktout
);
5351 c
->v
.v2
.locwindow
= newwin
;
5355 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
5357 unsigned i
= ssh_pkt_getuint32(pktin
);
5358 struct ssh_channel
*c
;
5359 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5360 if (c
&& !c
->closes
)
5361 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
5364 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
5367 unsigned int length
;
5368 unsigned i
= ssh_pkt_getuint32(pktin
);
5369 struct ssh_channel
*c
;
5370 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5372 return; /* nonexistent channel */
5373 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5374 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
5375 return; /* extended but not stderr */
5376 ssh_pkt_getstring(pktin
, &data
, &length
);
5379 c
->v
.v2
.locwindow
-= length
;
5381 case CHAN_MAINSESSION
:
5383 from_backend(ssh
->frontend
, pktin
->type
==
5384 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5388 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5391 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5394 while (length
> 0) {
5395 if (c
->u
.a
.lensofar
< 4) {
5396 unsigned int l
= min(4 - c
->u
.a
.lensofar
, length
);
5397 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5401 c
->u
.a
.lensofar
+= l
;
5403 if (c
->u
.a
.lensofar
== 4) {
5405 4 + GET_32BIT(c
->u
.a
.msglen
);
5406 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
5408 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5410 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5412 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5414 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5418 c
->u
.a
.lensofar
+= l
;
5420 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5423 if (agent_query(c
->u
.a
.message
,
5426 ssh_agentf_callback
, c
))
5427 ssh_agentf_callback(c
, reply
, replylen
);
5428 sfree(c
->u
.a
.message
);
5429 c
->u
.a
.lensofar
= 0;
5436 * If we are not buffering too much data,
5437 * enlarge the window again at the remote side.
5439 if (bufsize
< OUR_V2_WINSIZE
)
5440 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5444 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
5446 unsigned i
= ssh_pkt_getuint32(pktin
);
5447 struct ssh_channel
*c
;
5449 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5451 return; /* nonexistent channel */
5453 if (c
->type
== CHAN_X11
) {
5455 * Remote EOF on an X11 channel means we should
5456 * wrap up and close the channel ourselves.
5458 x11_close(c
->u
.x11
.s
);
5460 } else if (c
->type
== CHAN_AGENT
) {
5462 } else if (c
->type
== CHAN_SOCKDATA
) {
5463 pfd_close(c
->u
.pfd
.s
);
5468 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
5470 unsigned i
= ssh_pkt_getuint32(pktin
);
5471 struct ssh_channel
*c
;
5472 struct Packet
*pktout
;
5474 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5475 if (!c
|| ((int)c
->remoteid
) == -1) {
5476 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5477 c ?
"half-open" : "nonexistent", i
));
5480 /* Do pre-close processing on the channel. */
5482 case CHAN_MAINSESSION
:
5483 ssh
->mainchan
= NULL
;
5484 update_specials_menu(ssh
->frontend
);
5487 if (c
->u
.x11
.s
!= NULL
)
5488 x11_close(c
->u
.x11
.s
);
5495 if (c
->u
.pfd
.s
!= NULL
)
5496 pfd_close(c
->u
.pfd
.s
);
5500 if (c
->closes
== 0) {
5501 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5502 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5503 ssh2_pkt_send(ssh
, pktout
);
5505 del234(ssh
->channels
, c
);
5506 bufchain_clear(&c
->v
.v2
.outbuffer
);
5510 * See if that was the last channel left open.
5511 * (This is only our termination condition if we're
5512 * not running in -N mode.)
5514 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
5515 logevent("All channels closed. Disconnecting");
5518 * We used to send SSH_MSG_DISCONNECT here,
5519 * because I'd believed that _every_ conforming
5520 * SSH2 connection had to end with a disconnect
5521 * being sent by at least one side; apparently
5522 * I was wrong and it's perfectly OK to
5523 * unceremoniously slam the connection shut
5524 * when you're done, and indeed OpenSSH feels
5525 * this is more polite than sending a
5526 * DISCONNECT. So now we don't.
5528 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5529 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
5530 ssh2_pkt_addstring(s
->pktout
, "All open channels closed");
5531 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
5532 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5534 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5538 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
5540 unsigned i
= ssh_pkt_getuint32(pktin
);
5541 struct ssh_channel
*c
;
5542 struct Packet
*pktout
;
5544 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5546 return; /* nonexistent channel */
5547 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5548 return; /* dunno why they're confirming this */
5549 c
->remoteid
= ssh_pkt_getuint32(pktin
);
5550 c
->type
= CHAN_SOCKDATA
;
5551 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
5552 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
5554 pfd_confirm(c
->u
.pfd
.s
);
5557 * We have a pending close on this channel,
5558 * which we decided on before the server acked
5559 * the channel open. So now we know the
5560 * remoteid, we can close it again.
5562 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5563 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5564 ssh2_pkt_send(ssh
, pktout
);
5568 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
5570 static const char *const reasons
[] = {
5571 "<unknown reason code>",
5572 "Administratively prohibited",
5574 "Unknown channel type",
5575 "Resource shortage",
5577 unsigned i
= ssh_pkt_getuint32(pktin
);
5578 unsigned reason_code
;
5579 char *reason_string
;
5582 struct ssh_channel
*c
;
5583 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5585 return; /* nonexistent channel */
5586 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5587 return; /* dunno why they're failing this */
5589 reason_code
= ssh_pkt_getuint32(pktin
);
5590 if (reason_code
>= lenof(reasons
))
5591 reason_code
= 0; /* ensure reasons[reason_code] in range */
5592 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
5593 message
= dupprintf("Forwarded connection refused by"
5594 " server: %s [%.*s]", reasons
[reason_code
],
5595 reason_length
, reason_string
);
5599 pfd_close(c
->u
.pfd
.s
);
5601 del234(ssh
->channels
, c
);
5605 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
5609 int typelen
, want_reply
;
5610 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
5611 struct ssh_channel
*c
;
5612 struct Packet
*pktout
;
5614 localid
= ssh_pkt_getuint32(pktin
);
5615 ssh_pkt_getstring(pktin
, &type
, &typelen
);
5616 want_reply
= ssh2_pkt_getbool(pktin
);
5619 * First, check that the channel exists. Otherwise,
5620 * we can instantly disconnect with a rude message.
5622 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
5625 sprintf(buf
, "Received channel request for nonexistent"
5626 " channel %d", localid
);
5628 pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5629 ssh2_pkt_adduint32(pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
5630 ssh2_pkt_addstring(pktout
, buf
);
5631 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
5632 ssh2_pkt_send_noqueue(ssh
, pktout
);
5633 connection_fatal(ssh
->frontend
, "%s", buf
);
5634 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5639 * Having got the channel number, we now look at
5640 * the request type string to see if it's something
5643 if (c
== ssh
->mainchan
) {
5645 * We recognise "exit-status" and "exit-signal" on
5646 * the primary channel.
5648 if (typelen
== 11 &&
5649 !memcmp(type
, "exit-status", 11)) {
5651 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
5652 logeventf(ssh
, "Server sent command exit status %d",
5654 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
5656 } else if (typelen
== 11 &&
5657 !memcmp(type
, "exit-signal", 11)) {
5659 int is_plausible
= TRUE
, is_int
= FALSE
;
5660 char *fmt_sig
= "", *fmt_msg
= "";
5662 int msglen
= 0, core
= FALSE
;
5663 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
5664 * provide an `int' for the signal, despite its
5665 * having been a `string' in the drafts since at
5666 * least 2001. (Fixed in session.c 1.147.) Try to
5667 * infer which we can safely parse it as. */
5669 unsigned char *p
= pktin
->body
+
5671 long len
= pktin
->length
- pktin
->savedpos
;
5672 unsigned long num
= GET_32BIT(p
); /* what is it? */
5673 /* If it's 0, it hardly matters; assume string */
5677 int maybe_int
= FALSE
, maybe_str
= FALSE
;
5678 #define CHECK_HYPOTHESIS(offset, result) \
5681 if (q >= 0 && q+4 <= len) { \
5682 q = q + 4 + GET_32BIT(p+q); \
5683 if (q >= 0 && q+4 <= len && \
5684 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
5688 CHECK_HYPOTHESIS(4+1, maybe_int
);
5689 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
5690 #undef CHECK_HYPOTHESIS
5691 if (maybe_int
&& !maybe_str
)
5693 else if (!maybe_int
&& maybe_str
)
5696 /* Crikey. Either or neither. Panic. */
5697 is_plausible
= FALSE
;
5702 /* Old non-standard OpenSSH. */
5703 int signum
= ssh_pkt_getuint32(pktin
);
5704 fmt_sig
= dupprintf(" %d", signum
);
5706 /* As per the drafts. */
5709 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
5710 /* Signal name isn't supposed to be blank, but
5711 * let's cope gracefully if it is. */
5713 fmt_sig
= dupprintf(" \"%.*s\"",
5717 core
= ssh2_pkt_getbool(pktin
);
5718 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5720 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
5722 /* ignore lang tag */
5723 } /* else don't attempt to parse */
5724 logeventf(ssh
, "Server exited on signal%s%s%s",
5725 fmt_sig
, core ?
" (core dumped)" : "",
5727 if (*fmt_sig
) sfree(fmt_sig
);
5728 if (*fmt_msg
) sfree(fmt_msg
);
5729 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
5734 * This is a channel request we don't know
5735 * about, so we now either ignore the request
5736 * or respond with CHANNEL_FAILURE, depending
5739 reply
= SSH2_MSG_CHANNEL_FAILURE
;
5742 pktout
= ssh2_pkt_init(reply
);
5743 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5744 ssh2_pkt_send(ssh
, pktout
);
5748 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
5751 int typelen
, want_reply
;
5752 struct Packet
*pktout
;
5754 ssh_pkt_getstring(pktin
, &type
, &typelen
);
5755 want_reply
= ssh2_pkt_getbool(pktin
);
5758 * We currently don't support any global requests
5759 * at all, so we either ignore the request or
5760 * respond with REQUEST_FAILURE, depending on
5764 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
5765 ssh2_pkt_send(ssh
, pktout
);
5769 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
5777 struct ssh_channel
*c
;
5778 unsigned remid
, winsize
, pktsize
;
5779 struct Packet
*pktout
;
5781 ssh_pkt_getstring(pktin
, &type
, &typelen
);
5782 c
= snew(struct ssh_channel
);
5785 remid
= ssh_pkt_getuint32(pktin
);
5786 winsize
= ssh_pkt_getuint32(pktin
);
5787 pktsize
= ssh_pkt_getuint32(pktin
);
5789 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5792 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
5793 addrstr
= snewn(peeraddrlen
+1, char);
5794 memcpy(addrstr
, peeraddr
, peeraddrlen
);
5795 addrstr
[peeraddrlen
] = '\0';
5796 peerport
= ssh_pkt_getuint32(pktin
);
5798 logeventf(ssh
, "Received X11 connect request from %s:%d",
5801 if (!ssh
->X11_fwd_enabled
)
5802 error
= "X11 forwarding is not enabled";
5803 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
5804 ssh
->x11auth
, addrstr
, peerport
,
5805 &ssh
->cfg
) != NULL
) {
5806 error
= "Unable to open an X11 connection";
5808 logevent("Opening X11 forward connection succeeded");
5813 } else if (typelen
== 15 &&
5814 !memcmp(type
, "forwarded-tcpip", 15)) {
5815 struct ssh_rportfwd pf
, *realpf
;
5818 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
5819 pf
.sport
= ssh_pkt_getuint32(pktin
);
5820 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
5821 peerport
= ssh_pkt_getuint32(pktin
);
5822 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
5823 logeventf(ssh
, "Received remote port %d open request "
5824 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
5825 if (realpf
== NULL
) {
5826 error
= "Remote port is not recognised";
5828 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
5832 realpf
->pfrec
->addressfamily
);
5833 logeventf(ssh
, "Attempting to forward remote port to "
5834 "%s:%d", realpf
->dhost
, realpf
->dport
);
5836 logeventf(ssh
, "Port open failed: %s", e
);
5837 error
= "Port open failed";
5839 logevent("Forwarded port opened successfully");
5840 c
->type
= CHAN_SOCKDATA
;
5843 } else if (typelen
== 22 &&
5844 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5845 if (!ssh
->agentfwd_enabled
)
5846 error
= "Agent forwarding is not enabled";
5848 c
->type
= CHAN_AGENT
; /* identify channel type */
5849 c
->u
.a
.lensofar
= 0;
5852 error
= "Unsupported channel type requested";
5855 c
->remoteid
= remid
;
5857 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5858 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5859 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
5860 ssh2_pkt_addstring(pktout
, error
);
5861 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
5862 ssh2_pkt_send(ssh
, pktout
);
5863 logeventf(ssh
, "Rejected channel open: %s", error
);
5866 c
->localid
= alloc_channel_id(ssh
);
5868 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5869 c
->v
.v2
.remwindow
= winsize
;
5870 c
->v
.v2
.remmaxpkt
= pktsize
;
5871 bufchain_init(&c
->v
.v2
.outbuffer
);
5872 add234(ssh
->channels
, c
);
5873 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5874 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5875 ssh2_pkt_adduint32(pktout
, c
->localid
);
5876 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
5877 ssh2_pkt_adduint32(pktout
, 0x4000UL
); /* our max pkt size */
5878 ssh2_pkt_send(ssh
, pktout
);
5883 * Handle the SSH2 userauth and connection layers.
5885 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
5886 struct Packet
*pktin
)
5888 struct do_ssh2_authconn_state
{
5890 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
5892 AUTH_KEYBOARD_INTERACTIVE
5896 AUTH_TYPE_PUBLICKEY
,
5897 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
5898 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
5900 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
5901 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
5903 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
5904 int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
5905 int kbd_inter_running
;
5907 int num_prompts
, curr_prompt
, echo
;
5912 void *publickey_blob
;
5913 int publickey_bloblen
;
5914 unsigned char request
[5], *response
, *p
;
5918 char *pkblob
, *alg
, *commentp
;
5919 int pklen
, alglen
, commentlen
;
5920 int siglen
, retlen
, len
;
5921 char *q
, *agentreq
, *ret
;
5923 int num_env
, env_left
, env_ok
;
5924 struct Packet
*pktout
;
5926 crState(do_ssh2_authconn_state
);
5928 crBegin(ssh
->do_ssh2_authconn_crstate
);
5931 * Request userauth protocol, and await a response to it.
5933 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
5934 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
5935 ssh2_pkt_send(ssh
, s
->pktout
);
5936 crWaitUntilV(pktin
);
5937 if (pktin
->type
!= SSH2_MSG_SERVICE_ACCEPT
) {
5938 bombout(("Server refused user authentication protocol"));
5943 * We repeat this whole loop, including the username prompt,
5944 * until we manage a successful authentication. If the user
5945 * types the wrong _password_, they can be sent back to the
5946 * beginning to try another username, if this is configured on.
5947 * (If they specify a username in the config, they are never
5948 * asked, even if they do give a wrong password.)
5950 * I think this best serves the needs of
5952 * - the people who have no configuration, no keys, and just
5953 * want to try repeated (username,password) pairs until they
5954 * type both correctly
5956 * - people who have keys and configuration but occasionally
5957 * need to fall back to passwords
5959 * - people with a key held in Pageant, who might not have
5960 * logged in to a particular machine before; so they want to
5961 * type a username, and then _either_ their key will be
5962 * accepted, _or_ they will type a password. If they mistype
5963 * the username they will want to be able to get back and
5966 s
->username
[0] = '\0';
5967 s
->got_username
= FALSE
;
5972 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
5974 * We got a username last time round this loop, and
5975 * with change_username turned off we don't try to get
5978 } else if (!*ssh
->cfg
.username
) {
5979 if (ssh_get_line
&& !ssh_getline_pw_only
) {
5980 if (!ssh_get_line("login as: ",
5981 s
->username
, sizeof(s
->username
), FALSE
)) {
5983 * get_line failed to get a username.
5986 logevent("No username provided. Abandoning session.");
5987 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5991 int ret
; /* need not be saved across crReturn */
5992 c_write_str(ssh
, "login as: ");
5994 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
5996 crWaitUntilV(!pktin
);
5997 ret
= process_userpass_input(ssh
, in
, inlen
);
6001 c_write_str(ssh
, "\r\n");
6003 s
->username
[strcspn(s
->username
, "\n\r")] = '\0';
6006 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
6007 s
->username
[sizeof(s
->username
)-1] = '\0';
6008 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
6009 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
6010 c_write_str(ssh
, stuff
);
6014 s
->got_username
= TRUE
;
6017 * Send an authentication request using method "none": (a)
6018 * just in case it succeeds, and (b) so that we know what
6019 * authentication methods we can usefully try next.
6021 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6023 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6024 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6025 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
6026 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
6027 ssh2_pkt_send(ssh
, s
->pktout
);
6028 s
->type
= AUTH_TYPE_NONE
;
6030 s
->we_are_in
= FALSE
;
6032 s
->tried_pubkey_config
= FALSE
;
6033 s
->tried_agent
= FALSE
;
6034 s
->tried_keyb_inter
= FALSE
;
6035 s
->kbd_inter_running
= FALSE
;
6036 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6037 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
6039 logeventf(ssh
, "Reading private key file \"%.150s\"",
6040 filename_to_str(&ssh
->cfg
.keyfile
));
6041 keytype
= key_type(&ssh
->cfg
.keyfile
);
6042 if (keytype
== SSH_KEYTYPE_SSH2
) {
6044 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
, NULL
,
6045 &s
->publickey_bloblen
, NULL
);
6048 logeventf(ssh
, "Unable to use this key file (%s)",
6049 key_type_to_str(keytype
));
6050 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
6052 filename_to_str(&ssh
->cfg
.keyfile
),
6053 key_type_to_str(keytype
));
6054 c_write_str(ssh
, msgbuf
);
6056 s
->publickey_blob
= NULL
;
6059 s
->publickey_blob
= NULL
;
6063 * Wait for the result of the last authentication request.
6066 crWaitUntilV(pktin
);
6067 while (pktin
->type
== SSH2_MSG_USERAUTH_BANNER
) {
6071 * Don't show the banner if we're operating in
6072 * non-verbose non-interactive mode. (It's probably
6073 * a script, which means nobody will read the
6074 * banner _anyway_, and moreover the printing of
6075 * the banner will screw up processing on the
6076 * output of (say) plink.)
6078 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
6079 ssh_pkt_getstring(pktin
, &banner
, &size
);
6081 c_write_untrusted(ssh
, banner
, size
);
6083 crWaitUntilV(pktin
);
6085 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
6086 logevent("Access granted");
6087 s
->we_are_in
= TRUE
;
6091 if (s
->kbd_inter_running
&&
6092 pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
6094 * This is either a further set-of-prompts packet
6095 * in keyboard-interactive authentication, or it's
6096 * the same one and we came back here with `gotit'
6097 * set. In the former case, we must reset the
6098 * curr_prompt variable.
6102 } else if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
) {
6103 bombout(("Strange packet received during authentication: type %d",
6111 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6112 * we can look at the string in it and know what we can
6113 * helpfully try next.
6115 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
6118 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
6119 s
->kbd_inter_running
= FALSE
;
6120 if (!ssh2_pkt_getbool(pktin
)) {
6122 * We have received an unequivocal Access
6123 * Denied. This can translate to a variety of
6126 * - if we'd just tried "none" authentication,
6127 * it's not worth printing anything at all
6129 * - if we'd just tried a public key _offer_,
6130 * the message should be "Server refused our
6131 * key" (or no message at all if the key
6132 * came from Pageant)
6134 * - if we'd just tried anything else, the
6135 * message really should be "Access denied".
6137 * Additionally, if we'd just tried password
6138 * authentication, we should break out of this
6139 * whole loop so as to go back to the username
6140 * prompt (iff we're configured to allow
6141 * username change attempts).
6143 if (s
->type
== AUTH_TYPE_NONE
) {
6145 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
6146 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
6147 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
6148 c_write_str(ssh
, "Server refused our key\r\n");
6149 logevent("Server refused public key");
6150 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
6151 /* server declined keyboard-interactive; ignore */
6153 c_write_str(ssh
, "Access denied\r\n");
6154 logevent("Access denied");
6155 if (s
->type
== AUTH_TYPE_PASSWORD
&&
6156 ssh
->cfg
.change_username
) {
6157 /* XXX perhaps we should allow
6158 * keyboard-interactive to do this too? */
6159 s
->we_are_in
= FALSE
;
6164 c_write_str(ssh
, "Further authentication required\r\n");
6165 logevent("Further authentication required");
6169 in_commasep_string("publickey", methods
, methlen
);
6171 in_commasep_string("password", methods
, methlen
);
6172 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
6173 in_commasep_string("keyboard-interactive", methods
, methlen
);
6177 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6181 * Most password/passphrase prompts will be
6182 * non-echoing, so we set this to 0 by default.
6183 * Exception is that some keyboard-interactive prompts
6184 * can be echoing, in which case we'll set this to 1.
6188 if (!s
->method
&& s
->can_pubkey
&&
6189 agent_exists() && !s
->tried_agent
) {
6191 * Attempt public-key authentication using Pageant.
6196 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6197 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6199 s
->tried_agent
= TRUE
;
6201 logevent("Pageant is running. Requesting keys.");
6203 /* Request the keys held by the agent. */
6204 PUT_32BIT(s
->request
, 1);
6205 s
->request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
6206 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
6207 ssh_agent_callback
, ssh
)) {
6211 bombout(("Unexpected data from server while"
6212 " waiting for agent response"));
6215 } while (pktin
|| inlen
> 0);
6216 r
= ssh
->agent_response
;
6217 s
->responselen
= ssh
->agent_response_len
;
6219 s
->response
= (unsigned char *) r
;
6220 if (s
->response
&& s
->responselen
>= 5 &&
6221 s
->response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
6222 s
->p
= s
->response
+ 5;
6223 s
->nkeys
= GET_32BIT(s
->p
);
6227 sprintf(buf
, "Pageant has %d SSH2 keys", s
->nkeys
);
6230 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
6235 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
6238 s
->pklen
= GET_32BIT(s
->p
);
6240 if (s
->publickey_blob
&&
6241 s
->pklen
== s
->publickey_bloblen
&&
6242 !memcmp(s
->p
, s
->publickey_blob
,
6243 s
->publickey_bloblen
)) {
6244 logevent("This key matches configured key file");
6245 s
->tried_pubkey_config
= 1;
6247 s
->pkblob
= (char *)s
->p
;
6249 s
->alglen
= GET_32BIT(s
->pkblob
);
6250 s
->alg
= s
->pkblob
+ 4;
6251 s
->commentlen
= GET_32BIT(s
->p
);
6253 s
->commentp
= (char *)s
->p
;
6254 s
->p
+= s
->commentlen
;
6255 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6256 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6257 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6258 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6259 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6260 ssh2_pkt_addstring_start(s
->pktout
);
6261 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6262 ssh2_pkt_addstring_start(s
->pktout
);
6263 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6264 ssh2_pkt_send(ssh
, s
->pktout
);
6266 crWaitUntilV(pktin
);
6267 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6268 logevent("Key refused");
6272 if (flags
& FLAG_VERBOSE
) {
6273 c_write_str(ssh
, "Authenticating with "
6275 c_write(ssh
, s
->commentp
, s
->commentlen
);
6276 c_write_str(ssh
, "\" from agent\r\n");
6280 * Server is willing to accept the key.
6281 * Construct a SIGN_REQUEST.
6283 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6284 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6285 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6286 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6287 ssh2_pkt_addbool(s
->pktout
, TRUE
);
6288 ssh2_pkt_addstring_start(s
->pktout
);
6289 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6290 ssh2_pkt_addstring_start(s
->pktout
);
6291 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6293 s
->siglen
= s
->pktout
->length
- 5 + 4 + 20;
6294 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
6296 s
->len
= 1; /* message type */
6297 s
->len
+= 4 + s
->pklen
; /* key blob */
6298 s
->len
+= 4 + s
->siglen
; /* data to sign */
6299 s
->len
+= 4; /* flags */
6300 s
->agentreq
= snewn(4 + s
->len
, char);
6301 PUT_32BIT(s
->agentreq
, s
->len
);
6302 s
->q
= s
->agentreq
+ 4;
6303 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
6304 PUT_32BIT(s
->q
, s
->pklen
);
6306 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
6308 PUT_32BIT(s
->q
, s
->siglen
);
6310 /* Now the data to be signed... */
6311 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
6312 PUT_32BIT(s
->q
, 20);
6315 memcpy(s
->q
, ssh
->v2_session_id
, 20);
6317 memcpy(s
->q
, s
->pktout
->data
+ 5,
6318 s
->pktout
->length
- 5);
6319 s
->q
+= s
->pktout
->length
- 5;
6320 /* And finally the (zero) flags word. */
6322 if (!agent_query(s
->agentreq
, s
->len
+ 4,
6324 ssh_agent_callback
, ssh
)) {
6328 bombout(("Unexpected data from server"
6329 " while waiting for agent"
6333 } while (pktin
|| inlen
> 0);
6334 vret
= ssh
->agent_response
;
6335 s
->retlen
= ssh
->agent_response_len
;
6340 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
6341 logevent("Sending Pageant's response");
6342 ssh2_add_sigblob(ssh
, s
->pktout
,
6343 s
->pkblob
, s
->pklen
,
6345 GET_32BIT(s
->ret
+ 5));
6346 ssh2_pkt_send(ssh
, s
->pktout
);
6351 ("Pageant failed to answer challenge");
6362 if (!s
->method
&& s
->can_pubkey
&& s
->publickey_blob
6363 && !s
->tried_pubkey_config
) {
6364 unsigned char *pub_blob
;
6365 char *algorithm
, *comment
;
6368 s
->tried_pubkey_config
= TRUE
;
6370 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6371 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6374 * Try the public key supplied in the configuration.
6376 * First, offer the public blob to see if the server is
6377 * willing to accept it.
6380 (unsigned char *)ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
6385 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6386 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6387 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6388 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6389 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6390 ssh2_pkt_addstring(s
->pktout
, algorithm
);
6391 ssh2_pkt_addstring_start(s
->pktout
);
6392 ssh2_pkt_addstring_data(s
->pktout
, (char *)pub_blob
,
6394 ssh2_pkt_send(ssh
, s
->pktout
);
6395 logevent("Offered public key");
6397 crWaitUntilV(pktin
);
6398 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6400 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
6401 continue; /* key refused; give up on it */
6404 logevent("Offer of public key accepted");
6406 * Actually attempt a serious authentication using
6409 if (ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
6410 sprintf(s
->pwprompt
,
6411 "Passphrase for key \"%.100s\": ",
6417 if (flags
& FLAG_VERBOSE
) {
6418 c_write_str(ssh
, "Authenticating with public key \"");
6419 c_write_str(ssh
, comment
);
6420 c_write_str(ssh
, "\"\r\n");
6422 s
->method
= AUTH_PUBLICKEY_FILE
;
6426 if (!s
->method
&& s
->can_keyb_inter
&& !s
->tried_keyb_inter
) {
6427 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
6428 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6429 s
->tried_keyb_inter
= TRUE
;
6431 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6432 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
6434 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6435 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6436 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6437 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive"); /* method */
6438 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
6439 ssh2_pkt_addstring(s
->pktout
, "");
6440 ssh2_pkt_send(ssh
, s
->pktout
);
6442 crWaitUntilV(pktin
);
6443 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
6444 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
6446 logevent("Keyboard-interactive authentication refused");
6447 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
6451 s
->kbd_inter_running
= TRUE
;
6455 if (s
->kbd_inter_running
) {
6456 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
6457 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6458 s
->tried_keyb_inter
= TRUE
;
6460 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6461 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
6463 if (s
->curr_prompt
== 0) {
6465 * We've got a fresh USERAUTH_INFO_REQUEST.
6466 * Display header data, and start going through
6469 char *name
, *inst
, *lang
;
6470 int name_len
, inst_len
, lang_len
;
6472 ssh_pkt_getstring(pktin
, &name
, &name_len
);
6473 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
6474 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
6476 c_write_untrusted(ssh
, name
, name_len
);
6477 c_write_str(ssh
, "\r\n");
6480 c_write_untrusted(ssh
, inst
, inst_len
);
6481 c_write_str(ssh
, "\r\n");
6483 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
6487 * If there are prompts remaining in the packet,
6488 * display one and get a response.
6490 if (s
->curr_prompt
< s
->num_prompts
) {
6494 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
6495 if (prompt_len
> 0) {
6496 static const char trunc
[] = "<prompt truncated>: ";
6497 static const int prlen
= sizeof(s
->pwprompt
) -
6499 if (prompt_len
> prlen
) {
6500 memcpy(s
->pwprompt
, prompt
, prlen
);
6501 strcpy(s
->pwprompt
+ prlen
, trunc
);
6503 memcpy(s
->pwprompt
, prompt
, prompt_len
);
6504 s
->pwprompt
[prompt_len
] = '\0';
6508 "<server failed to send prompt>: ");
6510 s
->echo
= ssh2_pkt_getbool(pktin
);
6516 if (!s
->method
&& s
->can_passwd
) {
6517 s
->method
= AUTH_PASSWORD
;
6518 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6519 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
6520 sprintf(s
->pwprompt
, "%.90s@%.90s's password: ", s
->username
,
6527 if (!ssh_get_line(s
->pwprompt
, s
->password
,
6528 sizeof(s
->password
), TRUE
)) {
6530 * get_line failed to get a password (for
6531 * example because one was supplied on the
6532 * command line which has already failed to
6535 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
6536 ssh2_pkt_adduint32(s
->pktout
,SSH2_DISCONNECT_BY_APPLICATION
);
6537 ssh2_pkt_addstring(s
->pktout
, "No more passwords available"
6539 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6540 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6541 logevent("Unable to authenticate");
6542 connection_fatal(ssh
->frontend
,
6543 "Unable to authenticate");
6544 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6548 int ret
; /* need not be saved across crReturn */
6549 c_write_untrusted(ssh
, s
->pwprompt
, strlen(s
->pwprompt
));
6552 setup_userpass_input(ssh
, s
->password
,
6553 sizeof(s
->password
), s
->echo
);
6555 crWaitUntilV(!pktin
);
6556 ret
= process_userpass_input(ssh
, in
, inlen
);
6560 c_write_str(ssh
, "\r\n");
6564 if (s
->method
== AUTH_PUBLICKEY_FILE
) {
6566 * We have our passphrase. Now try the actual authentication.
6568 struct ssh2_userkey
*key
;
6569 const char *error
= NULL
;
6571 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, s
->password
,
6573 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
6574 if (key
== SSH2_WRONG_PASSPHRASE
) {
6575 c_write_str(ssh
, "Wrong passphrase\r\n");
6576 s
->tried_pubkey_config
= FALSE
;
6578 c_write_str(ssh
, "Unable to load private key (");
6579 c_write_str(ssh
, error
);
6580 c_write_str(ssh
, ")\r\n");
6581 s
->tried_pubkey_config
= TRUE
;
6583 /* Send a spurious AUTH_NONE to return to the top. */
6584 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6585 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6586 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6587 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
6588 ssh2_pkt_send(ssh
, s
->pktout
);
6589 s
->type
= AUTH_TYPE_NONE
;
6591 unsigned char *pkblob
, *sigblob
, *sigdata
;
6592 int pkblob_len
, sigblob_len
, sigdata_len
;
6596 * We have loaded the private key and the server
6597 * has announced that it's willing to accept it.
6598 * Hallelujah. Generate a signature and send it.
6600 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6601 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6602 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6603 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6604 ssh2_pkt_addbool(s
->pktout
, TRUE
);
6605 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
6606 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
6607 ssh2_pkt_addstring_start(s
->pktout
);
6608 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
, pkblob_len
);
6611 * The data to be signed is:
6615 * followed by everything so far placed in the
6618 sigdata_len
= s
->pktout
->length
- 5 + 4 + 20;
6619 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
6621 sigdata
= snewn(sigdata_len
, unsigned char);
6623 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
6624 PUT_32BIT(sigdata
+p
, 20);
6627 memcpy(sigdata
+p
, ssh
->v2_session_id
, 20); p
+= 20;
6628 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
6629 s
->pktout
->length
- 5);
6630 p
+= s
->pktout
->length
- 5;
6631 assert(p
== sigdata_len
);
6632 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
6633 sigdata_len
, &sigblob_len
);
6634 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
6635 sigblob
, sigblob_len
);
6640 ssh2_pkt_send(ssh
, s
->pktout
);
6641 s
->type
= AUTH_TYPE_PUBLICKEY
;
6642 key
->alg
->freekey(key
->data
);
6644 } else if (s
->method
== AUTH_PASSWORD
) {
6646 * We send the password packet lumped tightly together with
6647 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
6648 * string long enough to make the total length of the two
6649 * packets constant. This should ensure that a passive
6650 * listener doing traffic analyis can't work out the length
6653 * For this to work, we need an assumption about the
6654 * maximum length of the password packet. I think 256 is
6655 * pretty conservative. Anyone using a password longer than
6656 * that probably doesn't have much to worry about from
6657 * people who find out how long their password is!
6659 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6660 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6661 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6662 ssh2_pkt_addstring(s
->pktout
, "password");
6663 ssh2_pkt_addbool(s
->pktout
, FALSE
);
6664 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
6665 ssh2_pkt_addstring(s
->pktout
, s
->password
);
6666 memset(s
->password
, 0, sizeof(s
->password
));
6667 end_log_omission(ssh
, s
->pktout
);
6668 ssh2_pkt_defer(ssh
, s
->pktout
);
6670 * We'll include a string that's an exact multiple of the
6671 * cipher block size. If the cipher is NULL for some
6672 * reason, we don't do this trick at all because we gain
6675 if (ssh
->cscipher
) {
6678 stringlen
= (256 - ssh
->deferred_len
);
6679 stringlen
+= ssh
->cscipher
->blksize
- 1;
6680 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
6683 * Temporarily disable actual compression,
6684 * so we can guarantee to get this string
6685 * exactly the length we want it. The
6686 * compression-disabling routine should
6687 * return an integer indicating how many
6688 * bytes we should adjust our string length
6692 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
6694 s
->pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
6695 ssh2_pkt_addstring_start(s
->pktout
);
6696 for (i
= 0; i
< stringlen
; i
++) {
6697 char c
= (char) random_byte();
6698 ssh2_pkt_addstring_data(s
->pktout
, &c
, 1);
6700 ssh2_pkt_defer(ssh
, s
->pktout
);
6702 ssh_pkt_defersend(ssh
);
6703 logevent("Sent password");
6704 s
->type
= AUTH_TYPE_PASSWORD
;
6705 } else if (s
->method
== AUTH_KEYBOARD_INTERACTIVE
) {
6706 if (s
->curr_prompt
== 0) {
6707 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
6708 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
6710 if (s
->need_pw
) { /* only add pw if we just got one! */
6711 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
6712 ssh2_pkt_addstring(s
->pktout
, s
->password
);
6713 memset(s
->password
, 0, sizeof(s
->password
));
6714 end_log_omission(ssh
, s
->pktout
);
6717 if (s
->curr_prompt
>= s
->num_prompts
) {
6718 ssh2_pkt_send(ssh
, s
->pktout
);
6721 * If there are prompts remaining, we set
6722 * `gotit' so that we won't attempt to get
6723 * another packet. Then we go back round the
6724 * loop and will end up retrieving another
6725 * prompt out of the existing packet. Funky or
6730 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6732 c_write_str(ssh
, "No supported authentication methods"
6733 " left to try!\r\n");
6734 logevent("No supported authentications offered."
6736 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
6737 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
6738 ssh2_pkt_addstring(s
->pktout
, "No supported authentication"
6739 " methods available");
6740 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6741 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6742 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6746 } while (!s
->we_are_in
);
6749 * Now we're authenticated for the connection protocol. The
6750 * connection protocol will automatically have started at this
6751 * point; there's no need to send SERVICE_REQUEST.
6754 ssh
->channels
= newtree234(ssh_channelcmp
);
6757 * Set up handlers for some connection protocol messages, so we
6758 * don't have to handle them repeatedly in this coroutine.
6760 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
6761 ssh2_msg_channel_window_adjust
;
6762 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
6763 ssh2_msg_global_request
;
6766 * Create the main session channel.
6768 if (!ssh
->cfg
.ssh_no_shell
) {
6769 ssh
->mainchan
= snew(struct ssh_channel
);
6770 ssh
->mainchan
->ssh
= ssh
;
6771 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
6772 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
6773 ssh2_pkt_addstring(s
->pktout
, "session");
6774 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
6775 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6776 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
6777 ssh2_pkt_adduint32(s
->pktout
, 0x4000UL
); /* our max pkt size */
6778 ssh2_pkt_send(ssh
, s
->pktout
);
6779 crWaitUntilV(pktin
);
6780 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
6781 bombout(("Server refused to open a session"));
6783 /* FIXME: error data comes back in FAILURE packet */
6785 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
6786 bombout(("Server's channel confirmation cited wrong channel"));
6789 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
6790 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
6791 ssh
->mainchan
->closes
= 0;
6792 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
6793 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
6794 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
6795 add234(ssh
->channels
, ssh
->mainchan
);
6796 update_specials_menu(ssh
->frontend
);
6797 logevent("Opened channel for session");
6799 ssh
->mainchan
= NULL
;
6802 * Now we have a channel, make dispatch table entries for
6803 * general channel-based messages.
6805 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
6806 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
6807 ssh2_msg_channel_data
;
6808 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
6809 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
6810 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
6811 ssh2_msg_channel_open_confirmation
;
6812 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
6813 ssh2_msg_channel_open_failure
;
6814 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
6815 ssh2_msg_channel_request
;
6816 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
6817 ssh2_msg_channel_open
;
6820 * Potentially enable X11 forwarding.
6822 if (ssh
->mainchan
&& ssh
->cfg
.x11_forward
) {
6823 char proto
[20], data
[64];
6824 logevent("Requesting X11 forwarding");
6825 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
6826 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
6827 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
6828 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6829 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
6830 ssh2_pkt_addstring(s
->pktout
, "x11-req");
6831 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6832 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
6833 ssh2_pkt_addstring(s
->pktout
, proto
);
6834 ssh2_pkt_addstring(s
->pktout
, data
);
6835 ssh2_pkt_adduint32(s
->pktout
, x11_get_screen_number(ssh
->cfg
.x11_display
));
6836 ssh2_pkt_send(ssh
, s
->pktout
);
6838 crWaitUntilV(pktin
);
6840 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6841 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6842 bombout(("Unexpected response to X11 forwarding request:"
6843 " packet type %d", pktin
->type
));
6846 logevent("X11 forwarding refused");
6848 logevent("X11 forwarding enabled");
6849 ssh
->X11_fwd_enabled
= TRUE
;
6854 * Enable port forwardings.
6856 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
6859 * Potentially enable agent forwarding.
6861 if (ssh
->mainchan
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
6862 logevent("Requesting OpenSSH-style agent forwarding");
6863 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6864 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
6865 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
6866 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6867 ssh2_pkt_send(ssh
, s
->pktout
);
6869 crWaitUntilV(pktin
);
6871 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6872 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6873 bombout(("Unexpected response to agent forwarding request:"
6874 " packet type %d", pktin
->type
));
6877 logevent("Agent forwarding refused");
6879 logevent("Agent forwarding enabled");
6880 ssh
->agentfwd_enabled
= TRUE
;
6885 * Now allocate a pty for the session.
6887 if (ssh
->mainchan
&& !ssh
->cfg
.nopty
) {
6888 /* Unpick the terminal-speed string. */
6889 /* XXX perhaps we should allow no speeds to be sent. */
6890 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
6891 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
6892 /* Build the pty request. */
6893 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6894 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
6895 ssh2_pkt_addstring(s
->pktout
, "pty-req");
6896 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6897 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
6898 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
6899 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
6900 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
6901 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
6902 ssh2_pkt_addstring_start(s
->pktout
);
6903 ssh2_pkt_addbyte(s
->pktout
, 128); /* TTY_OP_ISPEED */
6904 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
6905 ssh2_pkt_addbyte(s
->pktout
, 129); /* TTY_OP_OSPEED */
6906 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
6907 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
6908 ssh2_pkt_send(ssh
, s
->pktout
);
6909 ssh
->state
= SSH_STATE_INTERMED
;
6911 crWaitUntilV(pktin
);
6913 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6914 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6915 bombout(("Unexpected response to pty request:"
6916 " packet type %d", pktin
->type
));
6919 c_write_str(ssh
, "Server refused to allocate pty\r\n");
6920 ssh
->editing
= ssh
->echoing
= 1;
6922 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6923 ssh
->ospeed
, ssh
->ispeed
);
6926 ssh
->editing
= ssh
->echoing
= 1;
6930 * Send environment variables.
6932 * Simplest thing here is to send all the requests at once, and
6933 * then wait for a whole bunch of successes or failures.
6935 if (ssh
->mainchan
&& *ssh
->cfg
.environmt
) {
6936 char *e
= ssh
->cfg
.environmt
;
6937 char *var
, *varend
, *val
;
6943 while (*e
&& *e
!= '\t') e
++;
6945 if (*e
== '\t') e
++;
6950 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6951 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
6952 ssh2_pkt_addstring(s
->pktout
, "env");
6953 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6954 ssh2_pkt_addstring_start(s
->pktout
);
6955 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
6956 ssh2_pkt_addstring(s
->pktout
, val
);
6957 ssh2_pkt_send(ssh
, s
->pktout
);
6962 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
6965 s
->env_left
= s
->num_env
;
6967 while (s
->env_left
> 0) {
6968 crWaitUntilV(pktin
);
6970 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6971 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6972 bombout(("Unexpected response to environment request:"
6973 " packet type %d", pktin
->type
));
6983 if (s
->env_ok
== s
->num_env
) {
6984 logevent("All environment variables successfully set");
6985 } else if (s
->env_ok
== 0) {
6986 logevent("All environment variables refused");
6987 c_write_str(ssh
, "Server refused to set environment variables\r\n");
6989 logeventf(ssh
, "%d environment variables refused",
6990 s
->num_env
- s
->env_ok
);
6991 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
6996 * Start a shell or a remote command. We may have to attempt
6997 * this twice if the config data has provided a second choice
7000 if (ssh
->mainchan
) while (1) {
7004 if (ssh
->fallback_cmd
) {
7005 subsys
= ssh
->cfg
.ssh_subsys2
;
7006 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
7008 subsys
= ssh
->cfg
.ssh_subsys
;
7009 cmd
= ssh
->cfg
.remote_cmd_ptr
;
7012 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7013 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
7015 ssh2_pkt_addstring(s
->pktout
, "subsystem");
7016 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7017 ssh2_pkt_addstring(s
->pktout
, cmd
);
7019 ssh2_pkt_addstring(s
->pktout
, "exec");
7020 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7021 ssh2_pkt_addstring(s
->pktout
, cmd
);
7023 ssh2_pkt_addstring(s
->pktout
, "shell");
7024 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7026 ssh2_pkt_send(ssh
, s
->pktout
);
7028 crWaitUntilV(pktin
);
7030 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7031 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7032 bombout(("Unexpected response to shell/command request:"
7033 " packet type %d", pktin
->type
));
7037 * We failed to start the command. If this is the
7038 * fallback command, we really are finished; if it's
7039 * not, and if the fallback command exists, try falling
7040 * back to it before complaining.
7042 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
7043 logevent("Primary command failed; attempting fallback");
7044 ssh
->fallback_cmd
= TRUE
;
7047 bombout(("Server refused to start a shell/command"));
7050 logevent("Started a shell/command");
7055 ssh
->state
= SSH_STATE_SESSION
;
7056 if (ssh
->size_needed
)
7057 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
7058 if (ssh
->eof_needed
)
7059 ssh_special(ssh
, TS_EOF
);
7065 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
7070 s
->try_send
= FALSE
;
7074 * _All_ the connection-layer packets we expect to
7075 * receive are now handled by the dispatch table.
7076 * Anything that reaches here must be bogus.
7079 bombout(("Strange packet received: type %d", pktin
->type
));
7081 } else if (ssh
->mainchan
) {
7083 * We have spare data. Add it to the channel buffer.
7085 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
7090 struct ssh_channel
*c
;
7092 * Try to send data on all channels if we can.
7094 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
7097 continue; /* don't send on closing channels */
7098 bufsize
= ssh2_try_send(c
);
7101 case CHAN_MAINSESSION
:
7102 /* stdin need not receive an unthrottle
7103 * notification since it will be polled */
7106 x11_unthrottle(c
->u
.x11
.s
);
7109 /* agent sockets are request/response and need no
7110 * buffer management */
7113 pfd_unthrottle(c
->u
.pfd
.s
);
7125 * Handlers for SSH2 messages that might arrive at any moment.
7127 void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
7129 /* log reason code in disconnect message */
7131 int nowlen
, reason
, msglen
;
7133 reason
= ssh_pkt_getuint32(pktin
);
7134 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7136 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
7137 buf
= dupprintf("Received disconnect message (%s)",
7138 ssh2_disconnect_reasons
[reason
]);
7140 buf
= dupprintf("Received disconnect message (unknown"
7141 " type %d)", reason
);
7145 buf
= dupprintf("Disconnection message text: %n%.*s",
7146 &nowlen
, msglen
, msg
);
7148 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7150 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
7151 ssh2_disconnect_reasons
[reason
] : "unknown",
7156 void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
7158 /* log the debug message */
7163 /* XXX maybe we should actually take notice of this */
7164 always_display
= ssh2_pkt_getbool(pktin
);
7165 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7167 buf
= dupprintf("Remote debug message: %.*s", msglen
, msg
);
7172 void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
7174 struct Packet
*pktout
;
7175 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
7176 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
7178 * UNIMPLEMENTED messages MUST appear in the same order as the
7179 * messages they respond to. Hence, never queue them.
7181 ssh2_pkt_send_noqueue(ssh
, pktout
);
7185 * Handle the top-level SSH2 protocol.
7187 static void ssh2_protocol_setup(Ssh ssh
)
7192 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7194 for (i
= 0; i
< 256; i
++)
7195 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
7198 * Any message we actually understand, we set to NULL so that
7199 * the coroutines will get it.
7201 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
7202 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
7203 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
7204 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
7205 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
7206 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
7207 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
7208 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7209 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7210 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
7211 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
7212 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
7213 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
7214 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
7215 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
7216 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
7217 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7218 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7219 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
7220 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
7221 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
7222 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
7223 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
7224 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
7225 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
7226 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
7227 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
7228 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
7229 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
7230 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
7231 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
7232 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
7233 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
7236 * These special message types we install handlers for.
7238 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
7239 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with ssh1 */
7240 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
7243 static void ssh2_timer(void *ctx
, long now
)
7247 if (!ssh
->kex_in_progress
&& ssh
->cfg
.ssh_rekey_time
!= 0 &&
7248 now
- ssh
->next_rekey
>= 0) {
7249 do_ssh2_transport(ssh
, "Initiating key re-exchange (timeout)",
7254 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
7255 struct Packet
*pktin
)
7257 if (ssh
->state
== SSH_STATE_CLOSED
)
7261 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
7262 if (!ssh
->kex_in_progress
&&
7263 ssh
->max_data_size
!= 0 &&
7264 ssh
->incoming_data_size
> ssh
->max_data_size
)
7265 do_ssh2_transport(ssh
, "Initiating key re-exchange "
7266 "(too much data received)", -1, NULL
);
7269 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
7270 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
7274 if (!ssh
->protocol_initial_phase_done
||
7275 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
7276 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
7277 !ssh
->protocol_initial_phase_done
) {
7278 ssh
->protocol_initial_phase_done
= TRUE
;
7280 * Allow authconn to initialise itself.
7282 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
7285 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
7290 * Called to set up the connection.
7292 * Returns an error message, or NULL on success.
7294 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
7296 char *host
, int port
, char **realhost
, int nodelay
,
7302 ssh
= snew(struct ssh_tag
);
7303 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7304 ssh
->version
= 0; /* when not ready yet */
7307 ssh
->v1_cipher_ctx
= NULL
;
7308 ssh
->crcda_ctx
= NULL
;
7309 ssh
->cscipher
= NULL
;
7310 ssh
->cs_cipher_ctx
= NULL
;
7311 ssh
->sccipher
= NULL
;
7312 ssh
->sc_cipher_ctx
= NULL
;
7314 ssh
->cs_mac_ctx
= NULL
;
7316 ssh
->sc_mac_ctx
= NULL
;
7318 ssh
->cs_comp_ctx
= NULL
;
7320 ssh
->sc_comp_ctx
= NULL
;
7322 ssh
->kex_ctx
= NULL
;
7323 ssh
->hostkey
= NULL
;
7325 ssh
->state
= SSH_STATE_PREPACKET
;
7326 ssh
->size_needed
= FALSE
;
7327 ssh
->eof_needed
= FALSE
;
7330 ssh
->deferred_send_data
= NULL
;
7331 ssh
->deferred_len
= 0;
7332 ssh
->deferred_size
= 0;
7333 ssh
->fallback_cmd
= 0;
7335 ssh
->x11auth
= NULL
;
7336 ssh
->v1_compressing
= FALSE
;
7337 ssh
->v2_outgoing_sequence
= 0;
7338 ssh
->ssh1_rdpkt_crstate
= 0;
7339 ssh
->ssh2_rdpkt_crstate
= 0;
7340 ssh
->do_ssh_init_crstate
= 0;
7341 ssh
->ssh_gotdata_crstate
= 0;
7342 ssh
->do_ssh1_connection_crstate
= 0;
7343 ssh
->do_ssh1_login_crstate
= 0;
7344 ssh
->do_ssh2_transport_crstate
= 0;
7345 ssh
->do_ssh2_authconn_crstate
= 0;
7346 ssh
->do_ssh_init_state
= NULL
;
7347 ssh
->do_ssh1_login_state
= NULL
;
7348 ssh
->do_ssh2_transport_state
= NULL
;
7349 ssh
->do_ssh2_authconn_state
= NULL
;
7350 ssh
->mainchan
= NULL
;
7351 ssh
->throttled_all
= 0;
7352 ssh
->v1_stdout_throttling
= 0;
7354 ssh
->queuelen
= ssh
->queuesize
= 0;
7355 ssh
->queueing
= FALSE
;
7356 ssh
->qhead
= ssh
->qtail
= NULL
;
7358 *backend_handle
= ssh
;
7361 if (crypto_startup() == 0)
7362 return "Microsoft high encryption pack not installed!";
7365 ssh
->frontend
= frontend_handle
;
7366 ssh
->term_width
= ssh
->cfg
.width
;
7367 ssh
->term_height
= ssh
->cfg
.height
;
7369 ssh
->channels
= NULL
;
7370 ssh
->rportfwds
= NULL
;
7371 ssh
->portfwds
= NULL
;
7376 ssh
->v1_throttle_count
= 0;
7377 ssh
->overall_bufsize
= 0;
7378 ssh
->fallback_cmd
= 0;
7380 ssh
->protocol
= NULL
;
7382 ssh
->protocol_initial_phase_done
= FALSE
;
7386 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
7387 ssh
->deferred_data_size
= 0L;
7388 ssh
->max_data_size
= parse_blocksize(ssh
->cfg
.ssh_rekey_data
);
7389 ssh
->kex_in_progress
= FALSE
;
7391 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
7400 static void ssh_free(void *handle
)
7402 Ssh ssh
= (Ssh
) handle
;
7403 struct ssh_channel
*c
;
7404 struct ssh_rportfwd
*pf
;
7406 if (ssh
->v1_cipher_ctx
)
7407 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
7408 if (ssh
->cs_cipher_ctx
)
7409 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
7410 if (ssh
->sc_cipher_ctx
)
7411 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
7412 if (ssh
->cs_mac_ctx
)
7413 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
7414 if (ssh
->sc_mac_ctx
)
7415 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
7416 if (ssh
->cs_comp_ctx
) {
7418 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
7420 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
7422 if (ssh
->sc_comp_ctx
) {
7424 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
7426 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
7429 dh_cleanup(ssh
->kex_ctx
);
7430 sfree(ssh
->savedhost
);
7432 while (ssh
->queuelen
-- > 0)
7433 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
7436 while (ssh
->qhead
) {
7437 struct queued_handler
*qh
= ssh
->qhead
;
7438 ssh
->qhead
= qh
->next
;
7441 ssh
->qhead
= ssh
->qtail
= NULL
;
7443 if (ssh
->channels
) {
7444 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
7447 if (c
->u
.x11
.s
!= NULL
)
7448 x11_close(c
->u
.x11
.s
);
7451 if (c
->u
.pfd
.s
!= NULL
)
7452 pfd_close(c
->u
.pfd
.s
);
7457 freetree234(ssh
->channels
);
7458 ssh
->channels
= NULL
;
7461 if (ssh
->rportfwds
) {
7462 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
7464 freetree234(ssh
->rportfwds
);
7465 ssh
->rportfwds
= NULL
;
7467 sfree(ssh
->deferred_send_data
);
7469 x11_free_auth(ssh
->x11auth
);
7470 sfree(ssh
->do_ssh_init_state
);
7471 sfree(ssh
->do_ssh1_login_state
);
7472 sfree(ssh
->do_ssh2_transport_state
);
7473 sfree(ssh
->do_ssh2_authconn_state
);
7474 if (ssh
->crcda_ctx
) {
7475 crcda_free_context(ssh
->crcda_ctx
);
7476 ssh
->crcda_ctx
= NULL
;
7480 expire_timer_context(ssh
);
7482 pinger_free(ssh
->pinger
);
7489 * Reconfigure the SSH backend.
7491 static void ssh_reconfig(void *handle
, Config
*cfg
)
7493 Ssh ssh
= (Ssh
) handle
;
7494 char *rekeying
= NULL
;
7495 unsigned long old_max_data_size
;
7497 pinger_reconfig(ssh
->pinger
, &ssh
->cfg
, cfg
);
7498 ssh_setup_portfwd(ssh
, cfg
);
7500 if (ssh
->cfg
.ssh_rekey_time
!= cfg
->ssh_rekey_time
&&
7501 cfg
->ssh_rekey_time
!= 0) {
7502 long new_next
= ssh
->last_rekey
+ cfg
->ssh_rekey_time
*60*TICKSPERSEC
;
7503 long now
= GETTICKCOUNT();
7505 if (new_next
- now
< 0) {
7506 rekeying
= "Initiating key re-exchange (timeout shortened)";
7508 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
7512 old_max_data_size
= ssh
->max_data_size
;
7513 ssh
->max_data_size
= parse_blocksize(cfg
->ssh_rekey_data
);
7514 if (old_max_data_size
!= ssh
->max_data_size
&&
7515 ssh
->max_data_size
!= 0) {
7516 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
7517 ssh
->incoming_data_size
> ssh
->max_data_size
)
7518 rekeying
= "Initiating key re-exchange (data limit lowered)";
7521 if (rekeying
&& !ssh
->kex_in_progress
) {
7522 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
7525 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7529 * Called to send data down the Telnet connection.
7531 static int ssh_send(void *handle
, char *buf
, int len
)
7533 Ssh ssh
= (Ssh
) handle
;
7535 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7538 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
7540 return ssh_sendbuffer(ssh
);
7544 * Called to query the current amount of buffered stdin data.
7546 static int ssh_sendbuffer(void *handle
)
7548 Ssh ssh
= (Ssh
) handle
;
7551 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7555 * If the SSH socket itself has backed up, add the total backup
7556 * size on that to any individual buffer on the stdin channel.
7559 if (ssh
->throttled_all
)
7560 override_value
= ssh
->overall_bufsize
;
7562 if (ssh
->version
== 1) {
7563 return override_value
;
7564 } else if (ssh
->version
== 2) {
7565 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
7566 return override_value
;
7568 return (override_value
+
7569 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
7576 * Called to set the size of the window from SSH's POV.
7578 static void ssh_size(void *handle
, int width
, int height
)
7580 Ssh ssh
= (Ssh
) handle
;
7581 struct Packet
*pktout
;
7583 ssh
->term_width
= width
;
7584 ssh
->term_height
= height
;
7586 switch (ssh
->state
) {
7587 case SSH_STATE_BEFORE_SIZE
:
7588 case SSH_STATE_PREPACKET
:
7589 case SSH_STATE_CLOSED
:
7590 break; /* do nothing */
7591 case SSH_STATE_INTERMED
:
7592 ssh
->size_needed
= TRUE
; /* buffer for later */
7594 case SSH_STATE_SESSION
:
7595 if (!ssh
->cfg
.nopty
) {
7596 if (ssh
->version
== 1) {
7597 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
7598 PKT_INT
, ssh
->term_height
,
7599 PKT_INT
, ssh
->term_width
,
7600 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
7601 } else if (ssh
->mainchan
) {
7602 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7603 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7604 ssh2_pkt_addstring(pktout
, "window-change");
7605 ssh2_pkt_addbool(pktout
, 0);
7606 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
7607 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
7608 ssh2_pkt_adduint32(pktout
, 0);
7609 ssh2_pkt_adduint32(pktout
, 0);
7610 ssh2_pkt_send(ssh
, pktout
);
7618 * Return a list of the special codes that make sense in this
7621 static const struct telnet_special
*ssh_get_specials(void *handle
)
7623 static const struct telnet_special ssh1_ignore_special
[] = {
7624 {"IGNORE message", TS_NOP
}
7626 static const struct telnet_special ssh2_transport_specials
[] = {
7627 {"IGNORE message", TS_NOP
},
7628 {"Repeat key exchange", TS_REKEY
},
7630 static const struct telnet_special ssh2_session_specials
[] = {
7633 /* These are the signal names defined by draft-ietf-secsh-connect-23.
7634 * They include all the ISO C signals, but are a subset of the POSIX
7635 * required signals. */
7636 {"SIGINT (Interrupt)", TS_SIGINT
},
7637 {"SIGTERM (Terminate)", TS_SIGTERM
},
7638 {"SIGKILL (Kill)", TS_SIGKILL
},
7639 {"SIGQUIT (Quit)", TS_SIGQUIT
},
7640 {"SIGHUP (Hangup)", TS_SIGHUP
},
7641 {"More signals", TS_SUBMENU
},
7642 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
7643 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
7644 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
7645 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
7648 static const struct telnet_special specials_end
[] = {
7651 /* XXX review this length for any changes: */
7652 static struct telnet_special ssh_specials
[lenof(ssh2_transport_specials
) +
7653 lenof(ssh2_session_specials
) +
7654 lenof(specials_end
)];
7655 Ssh ssh
= (Ssh
) handle
;
7657 #define ADD_SPECIALS(name) \
7659 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7660 memcpy(&ssh_specials[i], name, sizeof name); \
7664 if (ssh
->version
== 1) {
7665 /* Don't bother offering IGNORE if we've decided the remote
7666 * won't cope with it, since we wouldn't bother sending it if
7668 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
7669 ADD_SPECIALS(ssh1_ignore_special
);
7670 } else if (ssh
->version
== 2) {
7671 ADD_SPECIALS(ssh2_transport_specials
);
7673 ADD_SPECIALS(ssh2_session_specials
);
7674 } /* else we're not ready yet */
7677 ADD_SPECIALS(specials_end
);
7678 return ssh_specials
;
7686 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7687 * can send an EOF and collect resulting output (e.g. `plink
7690 static void ssh_special(void *handle
, Telnet_Special code
)
7692 Ssh ssh
= (Ssh
) handle
;
7693 struct Packet
*pktout
;
7695 if (code
== TS_EOF
) {
7696 if (ssh
->state
!= SSH_STATE_SESSION
) {
7698 * Buffer the EOF in case we are pre-SESSION, so we can
7699 * send it as soon as we reach SESSION.
7702 ssh
->eof_needed
= TRUE
;
7705 if (ssh
->version
== 1) {
7706 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
7707 } else if (ssh
->mainchan
) {
7708 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
7709 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7710 ssh2_pkt_send(ssh
, pktout
);
7712 logevent("Sent EOF message");
7713 } else if (code
== TS_PING
|| code
== TS_NOP
) {
7714 if (ssh
->state
== SSH_STATE_CLOSED
7715 || ssh
->state
== SSH_STATE_PREPACKET
) return;
7716 if (ssh
->version
== 1) {
7717 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
7718 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
7720 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
7721 ssh2_pkt_addstring_start(pktout
);
7722 ssh2_pkt_send_noqueue(ssh
, pktout
);
7724 } else if (code
== TS_REKEY
) {
7725 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
7726 do_ssh2_transport(ssh
, "Initiating key re-exchange at"
7727 " user request", -1, NULL
);
7729 } else if (code
== TS_BRK
) {
7730 if (ssh
->state
== SSH_STATE_CLOSED
7731 || ssh
->state
== SSH_STATE_PREPACKET
) return;
7732 if (ssh
->version
== 1) {
7733 logevent("Unable to send BREAK signal in SSH1");
7734 } else if (ssh
->mainchan
) {
7735 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7736 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7737 ssh2_pkt_addstring(pktout
, "break");
7738 ssh2_pkt_addbool(pktout
, 0);
7739 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
7740 ssh2_pkt_send(ssh
, pktout
);
7743 /* Is is a POSIX signal? */
7744 char *signame
= NULL
;
7745 if (code
== TS_SIGABRT
) signame
= "ABRT";
7746 if (code
== TS_SIGALRM
) signame
= "ALRM";
7747 if (code
== TS_SIGFPE
) signame
= "FPE";
7748 if (code
== TS_SIGHUP
) signame
= "HUP";
7749 if (code
== TS_SIGILL
) signame
= "ILL";
7750 if (code
== TS_SIGINT
) signame
= "INT";
7751 if (code
== TS_SIGKILL
) signame
= "KILL";
7752 if (code
== TS_SIGPIPE
) signame
= "PIPE";
7753 if (code
== TS_SIGQUIT
) signame
= "QUIT";
7754 if (code
== TS_SIGSEGV
) signame
= "SEGV";
7755 if (code
== TS_SIGTERM
) signame
= "TERM";
7756 if (code
== TS_SIGUSR1
) signame
= "USR1";
7757 if (code
== TS_SIGUSR2
) signame
= "USR2";
7758 /* The SSH-2 protocol does in principle support arbitrary named
7759 * signals, including signame@domain, but we don't support those. */
7761 /* It's a signal. */
7762 if (ssh
->version
== 2 && ssh
->mainchan
) {
7763 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7764 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7765 ssh2_pkt_addstring(pktout
, "signal");
7766 ssh2_pkt_addbool(pktout
, 0);
7767 ssh2_pkt_addstring(pktout
, signame
);
7768 ssh2_pkt_send(ssh
, pktout
);
7769 logeventf(ssh
, "Sent signal SIG%s", signame
);
7772 /* Never heard of it. Do nothing */
7777 void *new_sock_channel(void *handle
, Socket s
)
7779 Ssh ssh
= (Ssh
) handle
;
7780 struct ssh_channel
*c
;
7781 c
= snew(struct ssh_channel
);
7785 c
->remoteid
= -1; /* to be set when open confirmed */
7786 c
->localid
= alloc_channel_id(ssh
);
7788 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
7790 bufchain_init(&c
->v
.v2
.outbuffer
);
7791 add234(ssh
->channels
, c
);
7797 * This is called when stdout/stderr (the entity to which
7798 * from_backend sends data) manages to clear some backlog.
7800 static void ssh_unthrottle(void *handle
, int bufsize
)
7802 Ssh ssh
= (Ssh
) handle
;
7803 if (ssh
->version
== 1) {
7804 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
7805 ssh
->v1_stdout_throttling
= 0;
7806 ssh1_throttle(ssh
, -1);
7809 if (ssh
->mainchan
&& ssh
->mainchan
->closes
== 0)
7810 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
7814 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
7816 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
7818 struct Packet
*pktout
;
7820 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
7822 if (ssh
->version
== 1) {
7823 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
7824 PKT_INT
, c
->localid
,
7827 /* PKT_STR, <org:orgport>, */
7830 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
7831 ssh2_pkt_addstring(pktout
, "direct-tcpip");
7832 ssh2_pkt_adduint32(pktout
, c
->localid
);
7833 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
7834 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
7835 ssh2_pkt_adduint32(pktout
, 0x4000UL
); /* our max pkt size */
7836 ssh2_pkt_addstring(pktout
, hostname
);
7837 ssh2_pkt_adduint32(pktout
, port
);
7839 * We make up values for the originator data; partly it's
7840 * too much hassle to keep track, and partly I'm not
7841 * convinced the server should be told details like that
7842 * about my local network configuration.
7844 ssh2_pkt_addstring(pktout
, "client-side-connection");
7845 ssh2_pkt_adduint32(pktout
, 0);
7846 ssh2_pkt_send(ssh
, pktout
);
7850 static Socket
ssh_socket(void *handle
)
7852 Ssh ssh
= (Ssh
) handle
;
7856 static int ssh_sendok(void *handle
)
7858 Ssh ssh
= (Ssh
) handle
;
7859 return ssh
->send_ok
;
7862 static int ssh_ldisc(void *handle
, int option
)
7864 Ssh ssh
= (Ssh
) handle
;
7865 if (option
== LD_ECHO
)
7866 return ssh
->echoing
;
7867 if (option
== LD_EDIT
)
7868 return ssh
->editing
;
7872 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
7874 Ssh ssh
= (Ssh
) handle
;
7878 static void ssh_provide_logctx(void *handle
, void *logctx
)
7880 Ssh ssh
= (Ssh
) handle
;
7881 ssh
->logctx
= logctx
;
7884 static int ssh_return_exitcode(void *handle
)
7886 Ssh ssh
= (Ssh
) handle
;
7890 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: 0);
7894 * cfg_info for SSH is the currently running version of the
7895 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
7897 static int ssh_cfg_info(void *handle
)
7899 Ssh ssh
= (Ssh
) handle
;
7900 return ssh
->version
;
7904 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7905 * that fails. This variable is the means by which scp.c can reach
7906 * into the SSH code and find out which one it got.
7908 extern int ssh_fallback_cmd(void *handle
)
7910 Ssh ssh
= (Ssh
) handle
;
7911 return ssh
->fallback_cmd
;
7914 Backend ssh_backend
= {
7924 ssh_return_exitcode
,