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_DHGROUP1 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 #define BUG_SSH2_DH_GEX 64
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_DHGROUP1
);
226 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP1
);
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_kex
*kex_algs
[] = {
364 &ssh_diffiehellman_gex
,
368 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
370 static void *nullmac_make_context(void)
374 static void nullmac_free_context(void *handle
)
377 static void nullmac_key(void *handle
, unsigned char *key
)
380 static void nullmac_generate(void *handle
, unsigned char *blk
, int len
,
384 static int nullmac_verify(void *handle
, unsigned char *blk
, int len
,
389 const static struct ssh_mac ssh_mac_none
= {
390 nullmac_make_context
, nullmac_free_context
, nullmac_key
,
391 nullmac_generate
, nullmac_verify
, "none", 0
393 const static struct ssh_mac
*macs
[] = {
394 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
396 const static struct ssh_mac
*buggymacs
[] = {
397 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
400 static void *ssh_comp_none_init(void)
404 static void ssh_comp_none_cleanup(void *handle
)
407 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
408 unsigned char **outblock
, int *outlen
)
412 static int ssh_comp_none_disable(void *handle
)
416 const static struct ssh_compress ssh_comp_none
= {
418 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
419 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
420 ssh_comp_none_disable
, NULL
422 extern const struct ssh_compress ssh_zlib
;
423 const static struct ssh_compress
*compressions
[] = {
424 &ssh_zlib
, &ssh_comp_none
427 enum { /* channel types */
432 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
436 * 2-3-4 tree storing channels.
439 Ssh ssh
; /* pointer back to main context */
440 unsigned remoteid
, localid
;
443 * In SSH1, this value contains four bits:
445 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
446 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
447 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
448 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
450 * A channel is completely finished with when all four bits are set.
454 struct ssh1_data_channel
{
457 struct ssh2_data_channel
{
459 unsigned remwindow
, remmaxpkt
;
464 struct ssh_agent_channel
{
465 unsigned char *message
;
466 unsigned char msglen
[4];
467 unsigned lensofar
, totallen
;
469 struct ssh_x11_channel
{
472 struct ssh_pfd_channel
{
479 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
480 * 2 use this structure in different ways, reflecting SSH 2's
481 * altogether saner approach to port forwarding.
483 * In SSH 1, you arrange a remote forwarding by sending the server
484 * the remote port number, and the local destination host:port.
485 * When a connection comes in, the server sends you back that
486 * host:port pair, and you connect to it. This is a ready-made
487 * security hole if you're not on the ball: a malicious server
488 * could send you back _any_ host:port pair, so if you trustingly
489 * connect to the address it gives you then you've just opened the
490 * entire inside of your corporate network just by connecting
491 * through it to a dodgy SSH server. Hence, we must store a list of
492 * host:port pairs we _are_ trying to forward to, and reject a
493 * connection request from the server if it's not in the list.
495 * In SSH 2, each side of the connection minds its own business and
496 * doesn't send unnecessary information to the other. You arrange a
497 * remote forwarding by sending the server just the remote port
498 * number. When a connection comes in, the server tells you which
499 * of its ports was connected to; and _you_ have to remember what
500 * local host:port pair went with that port number.
502 * Hence: in SSH 1 this structure stores host:port pairs we intend
503 * to allow connections to, and is indexed by those host:port
504 * pairs. In SSH 2 it stores a mapping from source port to
505 * destination host:port pair, and is indexed by source port.
507 struct ssh_rportfwd
{
508 unsigned sport
, dport
;
515 unsigned long sequence
;
522 * State associated with packet logging
526 struct logblank_t
*blanks
;
529 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
530 struct Packet
*pktin
);
531 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
532 struct Packet
*pktin
);
533 static void ssh1_protocol_setup(Ssh ssh
);
534 static void ssh2_protocol_setup(Ssh ssh
);
535 static void ssh_size(void *handle
, int width
, int height
);
536 static void ssh_special(void *handle
, Telnet_Special
);
537 static int ssh2_try_send(struct ssh_channel
*c
);
538 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
539 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
540 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
541 static int ssh_sendbuffer(void *handle
);
542 static void ssh_do_close(Ssh ssh
);
543 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
544 static int ssh2_pkt_getbool(struct Packet
*pkt
);
545 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
547 struct rdpkt1_state_tag
{
548 long len
, pad
, biglen
, to_read
;
549 unsigned long realcrc
, gotcrc
;
553 struct Packet
*pktin
;
556 struct rdpkt2_state_tag
{
557 long len
, pad
, payload
, packetlen
, maclen
;
560 unsigned long incoming_sequence
;
561 struct Packet
*pktin
;
564 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
567 const struct plug_function_table
*fn
;
568 /* the above field _must_ be first in the structure */
570 SHA_State exhash
, exhashbase
;
577 unsigned char session_key
[32];
579 int v1_remote_protoflags
;
580 int v1_local_protoflags
;
581 int agentfwd_enabled
;
584 const struct ssh_cipher
*cipher
;
587 const struct ssh2_cipher
*cscipher
, *sccipher
;
588 void *cs_cipher_ctx
, *sc_cipher_ctx
;
589 const struct ssh_mac
*csmac
, *scmac
;
590 void *cs_mac_ctx
, *sc_mac_ctx
;
591 const struct ssh_compress
*cscomp
, *sccomp
;
592 void *cs_comp_ctx
, *sc_comp_ctx
;
593 const struct ssh_kex
*kex
;
594 const struct ssh_signkey
*hostkey
;
595 unsigned char v2_session_id
[20];
601 int echoing
, editing
;
605 int ospeed
, ispeed
; /* temporaries */
606 int term_width
, term_height
;
608 tree234
*channels
; /* indexed by local id */
609 struct ssh_channel
*mainchan
; /* primary session channel */
616 SSH_STATE_BEFORE_SIZE
,
622 int size_needed
, eof_needed
;
624 struct Packet
**queue
;
625 int queuelen
, queuesize
;
627 unsigned char *deferred_send_data
;
628 int deferred_len
, deferred_size
;
631 * Gross hack: pscp will try to start SFTP but fall back to
632 * scp1 if that fails. This variable is the means by which
633 * scp.c can reach into the SSH code and find out which one it
639 * Used for username and password input.
641 char *userpass_input_buffer
;
642 int userpass_input_buflen
;
643 int userpass_input_bufpos
;
644 int userpass_input_echo
;
646 char *portfwd_strptr
;
652 int v1_throttle_count
;
655 int v1_stdout_throttling
;
656 int v2_outgoing_sequence
;
658 int ssh1_rdpkt_crstate
;
659 int ssh2_rdpkt_crstate
;
660 int do_ssh_init_crstate
;
661 int ssh_gotdata_crstate
;
662 int do_ssh1_login_crstate
;
663 int do_ssh1_connection_crstate
;
664 int do_ssh2_transport_crstate
;
665 int do_ssh2_authconn_crstate
;
667 void *do_ssh_init_state
;
668 void *do_ssh1_login_state
;
669 void *do_ssh2_transport_state
;
670 void *do_ssh2_authconn_state
;
672 struct rdpkt1_state_tag rdpkt1_state
;
673 struct rdpkt2_state_tag rdpkt2_state
;
675 /* ssh1 and ssh2 use this for different things, but both use it */
676 int protocol_initial_phase_done
;
678 void (*protocol
) (Ssh ssh
, unsigned char *in
, int inlen
,
680 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
683 * We maintain a full _copy_ of a Config structure here, not
684 * merely a pointer to it. That way, when we're passed a new
685 * one for reconfiguration, we can check the differences and
686 * potentially reconfigure port forwardings etc in mid-session.
691 * Used to transfer data back from async agent callbacks.
693 void *agent_response
;
694 int agent_response_len
;
697 * Dispatch table for packet types that we may have to deal
700 handler_fn_t packet_dispatch
[256];
703 #define logevent(s) logevent(ssh->frontend, s)
705 /* logevent, only printf-formatted. */
706 static void logeventf(Ssh ssh
, const char *fmt
, ...)
712 buf
= dupvprintf(fmt
, ap
);
718 #define bombout(msg) \
720 char *text = dupprintf msg; \
723 connection_fatal(ssh->frontend, "%s", text); \
727 /* Functions to leave bits out of the SSH packet log file. */
729 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
731 if (ssh
->cfg
.logomitpass
)
732 pkt
->logmode
= blanktype
;
735 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
737 if (ssh
->cfg
.logomitdata
)
738 pkt
->logmode
= blanktype
;
741 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
743 pkt
->logmode
= PKTLOG_EMIT
;
746 static int ssh_channelcmp(void *av
, void *bv
)
748 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
749 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
750 if (a
->localid
< b
->localid
)
752 if (a
->localid
> b
->localid
)
756 static int ssh_channelfind(void *av
, void *bv
)
758 unsigned *a
= (unsigned *) av
;
759 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
767 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
769 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
770 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
772 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
773 return i
< 0 ?
-1 : +1;
774 if (a
->dport
> b
->dport
)
776 if (a
->dport
< b
->dport
)
781 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
783 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
784 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
786 if (a
->sport
> b
->sport
)
788 if (a
->sport
< b
->sport
)
793 static int alloc_channel_id(Ssh ssh
)
795 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
796 unsigned low
, high
, mid
;
798 struct ssh_channel
*c
;
801 * First-fit allocation of channel numbers: always pick the
802 * lowest unused one. To do this, binary-search using the
803 * counted B-tree to find the largest channel ID which is in a
804 * contiguous sequence from the beginning. (Precisely
805 * everything in that sequence must have ID equal to its tree
806 * index plus CHANNEL_NUMBER_OFFSET.)
808 tsize
= count234(ssh
->channels
);
812 while (high
- low
> 1) {
813 mid
= (high
+ low
) / 2;
814 c
= index234(ssh
->channels
, mid
);
815 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
816 low
= mid
; /* this one is fine */
818 high
= mid
; /* this one is past it */
821 * Now low points to either -1, or the tree index of the
822 * largest ID in the initial sequence.
825 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
826 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
828 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
831 static void c_write(Ssh ssh
, const char *buf
, int len
)
833 if ((flags
& FLAG_STDERR
)) {
835 for (i
= 0; i
< len
; i
++)
837 fputc(buf
[i
], stderr
);
840 from_backend(ssh
->frontend
, 1, buf
, len
);
843 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
846 for (i
= 0; i
< len
; i
++) {
848 c_write(ssh
, "\r\n", 2);
849 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
850 c_write(ssh
, buf
+ i
, 1);
854 static void c_write_str(Ssh ssh
, const char *buf
)
856 c_write(ssh
, buf
, strlen(buf
));
859 static void ssh_free_packet(struct Packet
*pkt
)
864 static struct Packet
*ssh_new_packet(void)
866 struct Packet
*pkt
= snew(struct Packet
);
870 pkt
->logmode
= PKTLOG_EMIT
;
878 * Collect incoming data in the incoming packet buffer.
879 * Decipher and verify the packet when it is completely read.
880 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
881 * Update the *data and *datalen variables.
882 * Return a Packet structure when a packet is completed.
884 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
886 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
888 crBegin(ssh
->ssh1_rdpkt_crstate
);
890 st
->pktin
= ssh_new_packet();
893 st
->pktin
->length
= 0;
895 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
896 while ((*datalen
) == 0)
898 st
->len
= (st
->len
<< 8) + **data
;
899 (*data
)++, (*datalen
)--;
902 st
->pad
= 8 - (st
->len
% 8);
903 st
->biglen
= st
->len
+ st
->pad
;
904 st
->pktin
->length
= st
->len
- 5;
906 if (st
->biglen
< 0) {
907 bombout(("Extremely large packet length from server suggests"
908 " data stream corruption"));
909 ssh_free_packet(st
->pktin
);
913 st
->pktin
->maxlen
= st
->biglen
;
914 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
916 st
->to_read
= st
->biglen
;
917 st
->p
= st
->pktin
->data
;
918 while (st
->to_read
> 0) {
919 st
->chunk
= st
->to_read
;
920 while ((*datalen
) == 0)
922 if (st
->chunk
> (*datalen
))
923 st
->chunk
= (*datalen
);
924 memcpy(st
->p
, *data
, st
->chunk
);
926 *datalen
-= st
->chunk
;
928 st
->to_read
-= st
->chunk
;
931 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
933 bombout(("Network attack (CRC compensation) detected!"));
934 ssh_free_packet(st
->pktin
);
939 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
941 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
942 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
943 if (st
->gotcrc
!= st
->realcrc
) {
944 bombout(("Incorrect CRC received on packet"));
945 ssh_free_packet(st
->pktin
);
949 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
950 st
->pktin
->savedpos
= 0;
952 if (ssh
->v1_compressing
) {
953 unsigned char *decompblk
;
955 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
956 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
957 &decompblk
, &decomplen
)) {
958 bombout(("Zlib decompression encountered invalid data"));
959 ssh_free_packet(st
->pktin
);
963 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
964 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
965 st
->pktin
->data
= sresize(st
->pktin
->data
,
966 st
->pktin
->maxlen
+ APIEXTRA
,
968 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
971 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
973 st
->pktin
->length
= decomplen
- 1;
976 st
->pktin
->type
= st
->pktin
->body
[-1];
979 * Log incoming packet, possibly omitting sensitive fields.
983 struct logblank_t blank
;
984 if (ssh
->cfg
.logomitdata
) {
985 int do_blank
= FALSE
, blank_prefix
= 0;
986 /* "Session data" packets - omit the data field */
987 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
988 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
989 do_blank
= TRUE
; blank_prefix
= 0;
990 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
991 do_blank
= TRUE
; blank_prefix
= 4;
994 blank
.offset
= blank_prefix
;
995 blank
.len
= st
->pktin
->length
;
996 blank
.type
= PKTLOG_OMIT
;
1000 log_packet(ssh
->logctx
,
1001 PKT_INCOMING
, st
->pktin
->type
,
1002 ssh1_pkt_type(st
->pktin
->type
),
1003 st
->pktin
->body
, st
->pktin
->length
,
1007 crFinish(st
->pktin
);
1010 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1012 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1014 crBegin(ssh
->ssh2_rdpkt_crstate
);
1016 st
->pktin
= ssh_new_packet();
1018 st
->pktin
->type
= 0;
1019 st
->pktin
->length
= 0;
1021 st
->cipherblk
= ssh
->sccipher
->blksize
;
1024 if (st
->cipherblk
< 8)
1027 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1030 * Acquire and decrypt the first block of the packet. This will
1031 * contain the length and padding details.
1033 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1034 while ((*datalen
) == 0)
1036 st
->pktin
->data
[st
->i
] = *(*data
)++;
1041 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1042 st
->pktin
->data
, st
->cipherblk
);
1045 * Now get the length and padding figures.
1047 st
->len
= GET_32BIT(st
->pktin
->data
);
1048 st
->pad
= st
->pktin
->data
[4];
1051 * _Completely_ silly lengths should be stomped on before they
1052 * do us any more damage.
1054 if (st
->len
< 0 || st
->pad
< 0 || st
->len
+ st
->pad
< 0) {
1055 bombout(("Incoming packet was garbled on decryption"));
1056 ssh_free_packet(st
->pktin
);
1061 * This enables us to deduce the payload length.
1063 st
->payload
= st
->len
- st
->pad
- 1;
1065 st
->pktin
->length
= st
->payload
+ 5;
1068 * So now we can work out the total packet length.
1070 st
->packetlen
= st
->len
+ 4;
1071 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1074 * Allocate memory for the rest of the packet.
1076 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1077 st
->pktin
->data
= sresize(st
->pktin
->data
,
1078 st
->pktin
->maxlen
+ APIEXTRA
,
1082 * Read and decrypt the remainder of the packet.
1084 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1086 while ((*datalen
) == 0)
1088 st
->pktin
->data
[st
->i
] = *(*data
)++;
1091 /* Decrypt everything _except_ the MAC. */
1093 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1094 st
->pktin
->data
+ st
->cipherblk
,
1095 st
->packetlen
- st
->cipherblk
);
1101 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
, st
->len
+ 4,
1102 st
->incoming_sequence
)) {
1103 bombout(("Incorrect MAC received on packet"));
1104 ssh_free_packet(st
->pktin
);
1108 st
->pktin
->sequence
= st
->incoming_sequence
++;
1111 * Decompress packet payload.
1114 unsigned char *newpayload
;
1117 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1118 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1119 &newpayload
, &newlen
)) {
1120 if (st
->pktin
->maxlen
< newlen
+ 5) {
1121 st
->pktin
->maxlen
= newlen
+ 5;
1122 st
->pktin
->data
= sresize(st
->pktin
->data
,
1123 st
->pktin
->maxlen
+ APIEXTRA
,
1126 st
->pktin
->length
= 5 + newlen
;
1127 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1132 st
->pktin
->savedpos
= 6;
1133 st
->pktin
->body
= st
->pktin
->data
;
1134 st
->pktin
->type
= st
->pktin
->data
[5];
1137 * Log incoming packet, possibly omitting sensitive fields.
1141 struct logblank_t blank
;
1142 if (ssh
->cfg
.logomitdata
) {
1143 int do_blank
= FALSE
, blank_prefix
= 0;
1144 /* "Session data" packets - omit the data field */
1145 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1146 do_blank
= TRUE
; blank_prefix
= 4;
1147 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1148 do_blank
= TRUE
; blank_prefix
= 8;
1151 blank
.offset
= blank_prefix
;
1152 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1153 blank
.type
= PKTLOG_OMIT
;
1157 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1158 ssh2_pkt_type(ssh
->pkt_ctx
, st
->pktin
->type
),
1159 st
->pktin
->data
+6, st
->pktin
->length
-6,
1163 crFinish(st
->pktin
);
1166 static void ssh1_pktout_size(struct Packet
*pkt
, int len
)
1170 len
+= 5; /* type and CRC */
1171 pad
= 8 - (len
% 8);
1174 pkt
->length
= len
- 5;
1175 if (pkt
->maxlen
< biglen
) {
1176 pkt
->maxlen
= biglen
;
1177 pkt
->data
= sresize(pkt
->data
, biglen
+ 4 + APIEXTRA
, unsigned char);
1179 pkt
->body
= pkt
->data
+ 4 + pad
+ 1;
1182 static struct Packet
*s_wrpkt_start(int type
, int len
)
1184 struct Packet
*pkt
= ssh_new_packet();
1185 ssh1_pktout_size(pkt
, len
);
1187 /* Initialise log omission state */
1193 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
)
1199 * XXX various versions of SC (including 8.8.4) screw up the
1200 * register allocation in this function and use the same register
1201 * (D6) for len and as a temporary, with predictable results. The
1202 * following sledgehammer prevents this.
1208 pkt
->body
[-1] = pkt
->type
;
1211 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->type
,
1212 ssh1_pkt_type(pkt
->type
),
1213 pkt
->body
, pkt
->length
,
1214 pkt
->nblanks
, pkt
->blanks
);
1215 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1218 if (ssh
->v1_compressing
) {
1219 unsigned char *compblk
;
1221 zlib_compress_block(ssh
->cs_comp_ctx
,
1222 pkt
->body
- 1, pkt
->length
+ 1,
1223 &compblk
, &complen
);
1224 ssh1_pktout_size(pkt
, complen
- 1);
1225 memcpy(pkt
->body
- 1, compblk
, complen
);
1229 len
= pkt
->length
+ 5; /* type and CRC */
1230 pad
= 8 - (len
% 8);
1233 for (i
= 0; i
< pad
; i
++)
1234 pkt
->data
[i
+ 4] = random_byte();
1235 crc
= crc32_compute(pkt
->data
+ 4, biglen
- 4);
1236 PUT_32BIT(pkt
->data
+ biglen
, crc
);
1237 PUT_32BIT(pkt
->data
, len
);
1240 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
, pkt
->data
+ 4, biglen
);
1245 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1248 len
= s_wrpkt_prepare(ssh
, pkt
);
1249 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1250 if (backlog
> SSH_MAX_BACKLOG
)
1251 ssh_throttle_all(ssh
, 1, backlog
);
1254 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1257 len
= s_wrpkt_prepare(ssh
, pkt
);
1258 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1259 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1260 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1264 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1265 ssh
->deferred_len
+= len
;
1269 * Construct a packet with the specified contents.
1271 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
,
1272 va_list ap1
, va_list ap2
)
1274 unsigned char *p
, *argp
, argchar
;
1275 unsigned long argint
;
1276 int pktlen
, argtype
, arglen
;
1281 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1284 (void) va_arg(ap1
, int);
1288 (void) va_arg(ap1
, int);
1292 (void) va_arg(ap1
, unsigned char *);
1293 arglen
= va_arg(ap1
, int);
1297 argp
= va_arg(ap1
, unsigned char *);
1298 arglen
= strlen((char *)argp
);
1299 pktlen
+= 4 + arglen
;
1302 bn
= va_arg(ap1
, Bignum
);
1303 pktlen
+= ssh1_bignum_length(bn
);
1308 /* ignore this pass */
1315 pkt
= s_wrpkt_start(pkttype
, pktlen
);
1318 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1319 int offset
= p
- pkt
->body
, len
= 0;
1321 /* Actual fields in the packet */
1323 argint
= va_arg(ap2
, int);
1324 PUT_32BIT(p
, argint
);
1328 argchar
= (unsigned char) va_arg(ap2
, int);
1333 argp
= va_arg(ap2
, unsigned char *);
1334 arglen
= va_arg(ap2
, int);
1335 memcpy(p
, argp
, arglen
);
1339 argp
= va_arg(ap2
, unsigned char *);
1340 arglen
= strlen((char *)argp
);
1341 PUT_32BIT(p
, arglen
);
1342 memcpy(p
+ 4, argp
, arglen
);
1346 bn
= va_arg(ap2
, Bignum
);
1347 len
= ssh1_write_bignum(p
, bn
);
1349 /* Tokens for modifications to packet logging */
1351 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1354 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1357 end_log_omission(ssh
, pkt
);
1361 /* Deal with logfile omission, if required. */
1362 if (len
&& (pkt
->logmode
!= PKTLOG_EMIT
)) {
1364 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
,
1366 pkt
->blanks
[pkt
->nblanks
-1].offset
= offset
;
1367 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1368 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1375 static void send_packet(Ssh ssh
, int pkttype
, ...)
1379 va_start(ap1
, pkttype
);
1380 va_start(ap2
, pkttype
);
1381 pkt
= construct_packet(ssh
, pkttype
, ap1
, ap2
);
1385 ssh_free_packet(pkt
);
1388 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1392 va_start(ap1
, pkttype
);
1393 va_start(ap2
, pkttype
);
1394 pkt
= construct_packet(ssh
, pkttype
, ap1
, ap2
);
1397 s_wrpkt_defer(ssh
, pkt
);
1398 ssh_free_packet(pkt
);
1401 static int ssh_versioncmp(char *a
, char *b
)
1404 unsigned long av
, bv
;
1406 av
= strtoul(a
, &ae
, 10);
1407 bv
= strtoul(b
, &be
, 10);
1409 return (av
< bv ?
-1 : +1);
1414 av
= strtoul(ae
, &ae
, 10);
1415 bv
= strtoul(be
, &be
, 10);
1417 return (av
< bv ?
-1 : +1);
1422 * Utility routines for putting an SSH-protocol `string' and
1423 * `uint32' into a SHA state.
1426 static void sha_string(SHA_State
* s
, void *str
, int len
)
1428 unsigned char lenblk
[4];
1429 PUT_32BIT(lenblk
, len
);
1430 SHA_Bytes(s
, lenblk
, 4);
1431 SHA_Bytes(s
, str
, len
);
1434 static void sha_uint32(SHA_State
* s
, unsigned i
)
1436 unsigned char intblk
[4];
1437 PUT_32BIT(intblk
, i
);
1438 SHA_Bytes(s
, intblk
, 4);
1442 * SSH2 packet construction functions.
1444 static void ssh2_pkt_ensure(struct Packet
*pkt
, int length
)
1446 if (pkt
->maxlen
< length
) {
1447 pkt
->maxlen
= length
+ 256;
1448 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1451 static void ssh2_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1453 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1455 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1456 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
- 6;
1457 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1458 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1461 ssh2_pkt_ensure(pkt
, pkt
->length
);
1462 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1464 static void ssh2_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1466 ssh2_pkt_adddata(pkt
, &byte
, 1);
1468 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1470 struct Packet
*pkt
= ssh_new_packet();
1472 ssh2_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1475 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1477 ssh2_pkt_adddata(pkt
, &value
, 1);
1479 static void ssh2_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1482 PUT_32BIT(x
, value
);
1483 ssh2_pkt_adddata(pkt
, x
, 4);
1485 static void ssh2_pkt_addstring_start(struct Packet
*pkt
)
1487 ssh2_pkt_adduint32(pkt
, 0);
1488 pkt
->savedpos
= pkt
->length
;
1490 static void ssh2_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1492 ssh2_pkt_adddata(pkt
, data
, strlen(data
));
1493 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1495 static void ssh2_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1497 ssh2_pkt_adddata(pkt
, data
, len
);
1498 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1500 static void ssh2_pkt_addstring(struct Packet
*pkt
, char *data
)
1502 ssh2_pkt_addstring_start(pkt
);
1503 ssh2_pkt_addstring_str(pkt
, data
);
1505 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1508 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1509 p
= snewn(n
+ 1, unsigned char);
1511 fatalbox("out of memory");
1513 for (i
= 1; i
<= n
; i
++)
1514 p
[i
] = bignum_byte(b
, n
- i
);
1516 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1518 memmove(p
, p
+ i
, n
+ 1 - i
);
1522 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1526 p
= ssh2_mpint_fmt(b
, &len
);
1527 ssh2_pkt_addstring_start(pkt
);
1528 ssh2_pkt_addstring_data(pkt
, (char *)p
, len
);
1533 * Construct an SSH2 final-form packet: compress it, encrypt it,
1534 * put the MAC on it. Final packet, ready to be sent, is stored in
1535 * pkt->data. Total length is returned.
1537 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1539 int cipherblk
, maclen
, padding
, i
;
1542 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1543 ssh2_pkt_type(ssh
->pkt_ctx
, pkt
->data
[5]),
1544 pkt
->data
+ 6, pkt
->length
- 6,
1545 pkt
->nblanks
, pkt
->blanks
);
1546 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1550 * Compress packet payload.
1553 unsigned char *newpayload
;
1556 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1558 &newpayload
, &newlen
)) {
1560 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1566 * Add padding. At least four bytes, and must also bring total
1567 * length (minus MAC) up to a multiple of the block size.
1569 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1570 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1573 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1574 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1575 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1576 pkt
->data
[4] = padding
;
1577 for (i
= 0; i
< padding
; i
++)
1578 pkt
->data
[pkt
->length
+ i
] = random_byte();
1579 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1581 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1582 pkt
->length
+ padding
,
1583 ssh
->v2_outgoing_sequence
);
1584 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1587 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1588 pkt
->data
, pkt
->length
+ padding
);
1590 /* Ready-to-send packet starts at pkt->data. We return length. */
1591 return pkt
->length
+ padding
+ maclen
;
1595 * Routines called from the main SSH code to send packets. There
1596 * are quite a few of these, because we have two separate
1597 * mechanisms for delaying the sending of packets:
1599 * - In order to send an IGNORE message and a password message in
1600 * a single fixed-length blob, we require the ability to
1601 * concatenate the encrypted forms of those two packets _into_ a
1602 * single blob and then pass it to our <network.h> transport
1603 * layer in one go. Hence, there's a deferment mechanism which
1604 * works after packet encryption.
1606 * - In order to avoid sending any connection-layer messages
1607 * during repeat key exchange, we have to queue up any such
1608 * outgoing messages _before_ they are encrypted (and in
1609 * particular before they're allocated sequence numbers), and
1610 * then send them once we've finished.
1612 * I call these mechanisms `defer' and `queue' respectively, so as
1613 * to distinguish them reasonably easily.
1615 * The functions send_noqueue() and defer_noqueue() free the packet
1616 * structure they are passed. Every outgoing packet goes through
1617 * precisely one of these functions in its life; packets passed to
1618 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1619 * these or get queued, and then when the queue is later emptied
1620 * the packets are all passed to defer_noqueue().
1624 * Send an SSH2 packet immediately, without queuing or deferring.
1626 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
1630 len
= ssh2_pkt_construct(ssh
, pkt
);
1631 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1632 if (backlog
> SSH_MAX_BACKLOG
)
1633 ssh_throttle_all(ssh
, 1, backlog
);
1634 ssh_free_packet(pkt
);
1638 * Defer an SSH2 packet.
1640 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
)
1642 int len
= ssh2_pkt_construct(ssh
, pkt
);
1643 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1644 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1645 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1649 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1650 ssh
->deferred_len
+= len
;
1651 ssh_free_packet(pkt
);
1655 * Queue an SSH2 packet.
1657 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
1659 assert(ssh
->queueing
);
1661 if (ssh
->queuelen
>= ssh
->queuesize
) {
1662 ssh
->queuesize
= ssh
->queuelen
+ 32;
1663 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
1666 ssh
->queue
[ssh
->queuelen
++] = pkt
;
1670 * Either queue or send a packet, depending on whether queueing is
1673 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
1676 ssh2_pkt_queue(ssh
, pkt
);
1678 ssh2_pkt_send_noqueue(ssh
, pkt
);
1682 * Either queue or defer a packet, depending on whether queueing is
1685 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
1688 ssh2_pkt_queue(ssh
, pkt
);
1690 ssh2_pkt_defer_noqueue(ssh
, pkt
);
1694 * Send the whole deferred data block constructed by
1695 * ssh2_pkt_defer() or SSH1's defer_packet().
1697 * The expected use of the defer mechanism is that you call
1698 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1699 * not currently queueing, this simply sets up deferred_send_data
1700 * and then sends it. If we _are_ currently queueing, the calls to
1701 * ssh2_pkt_defer() put the deferred packets on to the queue
1702 * instead, and therefore ssh_pkt_defersend() has no deferred data
1703 * to send. Hence, there's no need to make it conditional on
1706 static void ssh_pkt_defersend(Ssh ssh
)
1709 backlog
= sk_write(ssh
->s
, (char *)ssh
->deferred_send_data
,
1711 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1712 sfree(ssh
->deferred_send_data
);
1713 ssh
->deferred_send_data
= NULL
;
1714 if (backlog
> SSH_MAX_BACKLOG
)
1715 ssh_throttle_all(ssh
, 1, backlog
);
1719 * Send all queued SSH2 packets. We send them by means of
1720 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1721 * packets that needed to be lumped together.
1723 static void ssh2_pkt_queuesend(Ssh ssh
)
1727 assert(!ssh
->queueing
);
1729 for (i
= 0; i
< ssh
->queuelen
; i
++)
1730 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
]);
1733 ssh_pkt_defersend(ssh
);
1737 void bndebug(char *string
, Bignum b
)
1741 p
= ssh2_mpint_fmt(b
, &len
);
1742 debug(("%s", string
));
1743 for (i
= 0; i
< len
; i
++)
1744 debug((" %02x", p
[i
]));
1750 static void sha_mpint(SHA_State
* s
, Bignum b
)
1754 p
= ssh2_mpint_fmt(b
, &len
);
1755 sha_string(s
, p
, len
);
1760 * Packet decode functions for both SSH1 and SSH2.
1762 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
1764 unsigned long value
;
1765 if (pkt
->length
- pkt
->savedpos
< 4)
1766 return 0; /* arrgh, no way to decline (FIXME?) */
1767 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1771 static int ssh2_pkt_getbool(struct Packet
*pkt
)
1773 unsigned long value
;
1774 if (pkt
->length
- pkt
->savedpos
< 1)
1775 return 0; /* arrgh, no way to decline (FIXME?) */
1776 value
= pkt
->body
[pkt
->savedpos
] != 0;
1780 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
1785 if (pkt
->length
- pkt
->savedpos
< 4)
1787 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1792 if (pkt
->length
- pkt
->savedpos
< *length
)
1794 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
1795 pkt
->savedpos
+= *length
;
1797 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
1799 if (pkt
->length
- pkt
->savedpos
< length
)
1801 pkt
->savedpos
+= length
;
1802 return pkt
->body
+ (pkt
->savedpos
- length
);
1804 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
1805 unsigned char **keystr
)
1809 j
= makekey(pkt
->body
+ pkt
->savedpos
,
1810 pkt
->length
- pkt
->savedpos
,
1817 assert(pkt
->savedpos
< pkt
->length
);
1821 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
1826 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
1827 pkt
->length
- pkt
->savedpos
, &b
);
1835 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
1841 ssh_pkt_getstring(pkt
, &p
, &length
);
1846 b
= bignum_from_bytes((unsigned char *)p
, length
);
1851 * Helper function to add an SSH2 signature blob to a packet.
1852 * Expects to be shown the public key blob as well as the signature
1853 * blob. Normally works just like ssh2_pkt_addstring, but will
1854 * fiddle with the signature packet if necessary for
1855 * BUG_SSH2_RSA_PADDING.
1857 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
1858 void *pkblob_v
, int pkblob_len
,
1859 void *sigblob_v
, int sigblob_len
)
1861 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
1862 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
1864 /* dmemdump(pkblob, pkblob_len); */
1865 /* dmemdump(sigblob, sigblob_len); */
1868 * See if this is in fact an ssh-rsa signature and a buggy
1869 * server; otherwise we can just do this the easy way.
1871 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
1872 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
1873 int pos
, len
, siglen
;
1876 * Find the byte length of the modulus.
1879 pos
= 4+7; /* skip over "ssh-rsa" */
1880 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
1881 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
1882 pos
+= 4; /* find modulus itself */
1883 while (len
> 0 && pkblob
[pos
] == 0)
1885 /* debug(("modulus length is %d\n", len)); */
1888 * Now find the signature integer.
1890 pos
= 4+7; /* skip over "ssh-rsa" */
1891 siglen
= GET_32BIT(sigblob
+pos
);
1892 /* debug(("signature length is %d\n", siglen)); */
1894 if (len
!= siglen
) {
1895 unsigned char newlen
[4];
1896 ssh2_pkt_addstring_start(pkt
);
1897 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
1898 /* dmemdump(sigblob, pos); */
1899 pos
+= 4; /* point to start of actual sig */
1900 PUT_32BIT(newlen
, len
);
1901 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
1902 /* dmemdump(newlen, 4); */
1904 while (len
-- > siglen
) {
1905 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
1906 /* dmemdump(newlen, 1); */
1908 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
1909 /* dmemdump(sigblob+pos, siglen); */
1913 /* Otherwise fall through and do it the easy way. */
1916 ssh2_pkt_addstring_start(pkt
);
1917 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
1921 * Examine the remote side's version string and compare it against
1922 * a list of known buggy implementations.
1924 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
1926 char *imp
; /* pointer to implementation part */
1928 imp
+= strcspn(imp
, "-");
1930 imp
+= strcspn(imp
, "-");
1933 ssh
->remote_bugs
= 0;
1935 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
1936 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
1937 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1938 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1939 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
1940 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
1942 * These versions don't support SSH1_MSG_IGNORE, so we have
1943 * to use a different defence against password length
1946 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1947 logevent("We believe remote version has SSH1 ignore bug");
1950 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
1951 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
1952 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
1954 * These versions need a plain password sent; they can't
1955 * handle having a null and a random length of data after
1958 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1959 logevent("We believe remote version needs a plain SSH1 password");
1962 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
1963 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
1964 (!strcmp(imp
, "Cisco-1.25")))) {
1966 * These versions apparently have no clue whatever about
1967 * RSA authentication and will panic and die if they see
1968 * an AUTH_RSA message.
1970 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
1971 logevent("We believe remote version can't handle RSA authentication");
1974 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
1975 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
1976 !wc_match("* VShell", imp
) &&
1977 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
1978 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
1979 wc_match("2.1 *", imp
)))) {
1981 * These versions have the HMAC bug.
1983 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
1984 logevent("We believe remote version has SSH2 HMAC bug");
1987 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
1988 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
1989 !wc_match("* VShell", imp
) &&
1990 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
1992 * These versions have the key-derivation bug (failing to
1993 * include the literal shared secret in the hashes that
1994 * generate the keys).
1996 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
1997 logevent("We believe remote version has SSH2 key-derivation bug");
2000 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2001 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2002 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2003 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2005 * These versions have the SSH2 RSA padding bug.
2007 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2008 logevent("We believe remote version has SSH2 RSA padding bug");
2011 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2012 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2013 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2015 * These versions have the SSH2 session-ID bug in
2016 * public-key authentication.
2018 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2019 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2022 if (ssh
->cfg
.sshbug_dhgex2
== FORCE_ON
) {
2024 * User specified the SSH2 DH GEX bug.
2026 ssh
->remote_bugs
|= BUG_SSH2_DH_GEX
;
2027 logevent("We believe remote version has SSH2 DH group exchange bug");
2031 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2033 struct do_ssh_init_state
{
2041 crState(do_ssh_init_state
);
2043 crBegin(ssh
->do_ssh_init_crstate
);
2045 /* Search for the string "SSH-" in the input. */
2048 static const int transS
[] = { 1, 2, 2, 1 };
2049 static const int transH
[] = { 0, 0, 3, 0 };
2050 static const int transminus
[] = { 0, 0, 0, -1 };
2052 s
->i
= transS
[s
->i
];
2054 s
->i
= transH
[s
->i
];
2056 s
->i
= transminus
[s
->i
];
2061 crReturn(1); /* get another character */
2065 s
->vstring
= snewn(s
->vstrsize
, char);
2066 strcpy(s
->vstring
, "SSH-");
2070 crReturn(1); /* get another char */
2071 if (s
->vslen
>= s
->vstrsize
- 1) {
2073 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2075 s
->vstring
[s
->vslen
++] = c
;
2078 s
->version
[s
->i
] = '\0';
2080 } else if (s
->i
< sizeof(s
->version
) - 1)
2081 s
->version
[s
->i
++] = c
;
2082 } else if (c
== '\012')
2086 ssh
->agentfwd_enabled
= FALSE
;
2087 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2089 s
->vstring
[s
->vslen
] = 0;
2090 s
->vstring
[strcspn(s
->vstring
, "\r\n")] = '\0';/* remove EOL chars */
2093 vlog
= snewn(20 + s
->vslen
, char);
2094 sprintf(vlog
, "Server version: %s", s
->vstring
);
2098 ssh_detect_bugs(ssh
, s
->vstring
);
2101 * Decide which SSH protocol version to support.
2104 /* Anything strictly below "2.0" means protocol 1 is supported. */
2105 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2106 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2107 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2109 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2110 bombout(("SSH protocol version 1 required by user but not provided by server"));
2113 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2114 bombout(("SSH protocol version 2 required by user but not provided by server"));
2118 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
)) {
2122 char verstring
[80], vlog
[100];
2123 sprintf(verstring
, "SSH-2.0-%s", sshver
);
2124 SHA_Init(&ssh
->exhashbase
);
2126 * Hash our version string and their version string.
2128 sha_string(&ssh
->exhashbase
, verstring
, strlen(verstring
));
2129 sha_string(&ssh
->exhashbase
, s
->vstring
, strcspn(s
->vstring
, "\r\n"));
2130 sprintf(vlog
, "We claim version: %s", verstring
);
2132 strcat(verstring
, "\012");
2133 logevent("Using SSH protocol version 2");
2134 sk_write(ssh
->s
, verstring
, strlen(verstring
));
2135 ssh
->protocol
= ssh2_protocol
;
2136 ssh2_protocol_setup(ssh
);
2138 ssh
->s_rdpkt
= ssh2_rdpkt
;
2143 char verstring
[80], vlog
[100];
2144 sprintf(verstring
, "SSH-%s-%s",
2145 (ssh_versioncmp(s
->version
, "1.5") <= 0 ? s
->version
: "1.5"),
2147 sprintf(vlog
, "We claim version: %s", verstring
);
2149 strcat(verstring
, "\012");
2151 logevent("Using SSH protocol version 1");
2152 sk_write(ssh
->s
, verstring
, strlen(verstring
));
2153 ssh
->protocol
= ssh1_protocol
;
2154 ssh1_protocol_setup(ssh
);
2156 ssh
->s_rdpkt
= ssh1_rdpkt
;
2158 update_specials_menu(ssh
->frontend
);
2159 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2166 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2168 crBegin(ssh
->ssh_gotdata_crstate
);
2171 * To begin with, feed the characters one by one to the
2172 * protocol initialisation / selection function do_ssh_init().
2173 * When that returns 0, we're done with the initial greeting
2174 * exchange and can move on to packet discipline.
2177 int ret
; /* need not be kept across crReturn */
2179 crReturnV
; /* more data please */
2180 ret
= do_ssh_init(ssh
, *data
);
2188 * We emerge from that loop when the initial negotiation is
2189 * over and we have selected an s_rdpkt function. Now pass
2190 * everything to s_rdpkt, and then pass the resulting packets
2191 * to the proper protocol handler.
2196 while (datalen
> 0) {
2197 struct Packet
*pktin
= ssh
->s_rdpkt(ssh
, &data
, &datalen
);
2199 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2200 ssh_free_packet(pktin
);
2202 if (ssh
->state
== SSH_STATE_CLOSED
)
2210 static void ssh_do_close(Ssh ssh
)
2213 struct ssh_channel
*c
;
2215 ssh
->state
= SSH_STATE_CLOSED
;
2221 * Now we must shut down any port and X forwardings going
2222 * through this connection.
2224 if (ssh
->channels
) {
2225 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2228 x11_close(c
->u
.x11
.s
);
2231 pfd_close(c
->u
.pfd
.s
);
2234 del234(ssh
->channels
, c
);
2235 if (ssh
->version
== 2)
2236 bufchain_clear(&c
->v
.v2
.outbuffer
);
2242 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2245 Ssh ssh
= (Ssh
) plug
;
2248 /* A socket error has occurred. */
2249 logevent(error_msg
);
2250 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2252 /* Otherwise, the remote side closed the connection normally. */
2257 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2259 Ssh ssh
= (Ssh
) plug
;
2260 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2261 if (ssh
->state
== SSH_STATE_CLOSED
) {
2268 static void ssh_sent(Plug plug
, int bufsize
)
2270 Ssh ssh
= (Ssh
) plug
;
2272 * If the send backlog on the SSH socket itself clears, we
2273 * should unthrottle the whole world if it was throttled.
2275 if (bufsize
< SSH_MAX_BACKLOG
)
2276 ssh_throttle_all(ssh
, 0, bufsize
);
2280 * Connect to specified host and port.
2281 * Returns an error message, or NULL on success.
2282 * Also places the canonical host name into `realhost'. It must be
2283 * freed by the caller.
2285 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2286 char **realhost
, int nodelay
, int keepalive
)
2288 static const struct plug_function_table fn_table
= {
2298 ssh
->savedhost
= snewn(1 + strlen(host
), char);
2299 if (!ssh
->savedhost
)
2300 fatalbox("Out of memory");
2301 strcpy(ssh
->savedhost
, host
);
2304 port
= 22; /* default ssh port */
2305 ssh
->savedport
= port
;
2310 logeventf(ssh
, "Looking up host \"%s\"", host
);
2311 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
);
2312 if ((err
= sk_addr_error(addr
)) != NULL
) {
2322 sk_getaddr(addr
, addrbuf
, 100);
2323 logeventf(ssh
, "Connecting to %s port %d", addrbuf
, port
);
2325 ssh
->fn
= &fn_table
;
2326 ssh
->s
= new_connection(addr
, *realhost
, port
,
2327 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
2328 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2337 * Throttle or unthrottle the SSH connection.
2339 static void ssh1_throttle(Ssh ssh
, int adjust
)
2341 int old_count
= ssh
->v1_throttle_count
;
2342 ssh
->v1_throttle_count
+= adjust
;
2343 assert(ssh
->v1_throttle_count
>= 0);
2344 if (ssh
->v1_throttle_count
&& !old_count
) {
2345 sk_set_frozen(ssh
->s
, 1);
2346 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2347 sk_set_frozen(ssh
->s
, 0);
2352 * Throttle or unthrottle _all_ local data streams (for when sends
2353 * on the SSH connection itself back up).
2355 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2358 struct ssh_channel
*c
;
2360 if (enable
== ssh
->throttled_all
)
2362 ssh
->throttled_all
= enable
;
2363 ssh
->overall_bufsize
= bufsize
;
2366 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2368 case CHAN_MAINSESSION
:
2370 * This is treated separately, outside the switch.
2374 x11_override_throttle(c
->u
.x11
.s
, enable
);
2377 /* Agent channels require no buffer management. */
2380 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
2387 * Username and password input, abstracted off into routines
2388 * reusable in several places - even between SSH1 and SSH2.
2391 /* Set up a username or password input loop on a given buffer. */
2392 static void setup_userpass_input(Ssh ssh
, char *buffer
, int buflen
, int echo
)
2394 ssh
->userpass_input_buffer
= buffer
;
2395 ssh
->userpass_input_buflen
= buflen
;
2396 ssh
->userpass_input_bufpos
= 0;
2397 ssh
->userpass_input_echo
= echo
;
2401 * Process some terminal data in the course of username/password
2402 * input. Returns >0 for success (line of input returned in
2403 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2404 * for inconclusive (keep waiting for more input please).
2406 static int process_userpass_input(Ssh ssh
, unsigned char *in
, int inlen
)
2411 switch (c
= *in
++) {
2414 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
] = 0;
2415 ssh
->userpass_input_buffer
[ssh
->userpass_input_buflen
-1] = 0;
2420 if (ssh
->userpass_input_bufpos
> 0) {
2421 if (ssh
->userpass_input_echo
)
2422 c_write_str(ssh
, "\b \b");
2423 ssh
->userpass_input_bufpos
--;
2428 while (ssh
->userpass_input_bufpos
> 0) {
2429 if (ssh
->userpass_input_echo
)
2430 c_write_str(ssh
, "\b \b");
2431 ssh
->userpass_input_bufpos
--;
2440 * This simplistic check for printability is disabled
2441 * when we're doing password input, because some people
2442 * have control characters in their passwords.o
2444 if ((!ssh
->userpass_input_echo
||
2445 (c
>= ' ' && c
<= '~') ||
2446 ((unsigned char) c
>= 160))
2447 && ssh
->userpass_input_bufpos
< ssh
->userpass_input_buflen
-1) {
2448 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
++] = c
;
2449 if (ssh
->userpass_input_echo
)
2450 c_write(ssh
, &c
, 1);
2458 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
2460 Ssh ssh
= (Ssh
) sshv
;
2462 ssh
->agent_response
= reply
;
2463 ssh
->agent_response_len
= replylen
;
2465 if (ssh
->version
== 1)
2466 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2468 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
2471 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
2473 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
2475 void *sentreply
= reply
;
2478 /* Fake SSH_AGENT_FAILURE. */
2479 sentreply
= "\0\0\0\1\5";
2482 if (ssh
->version
== 2) {
2483 ssh2_add_channel_data(c
, sentreply
, replylen
);
2486 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
2487 PKT_INT
, c
->remoteid
,
2490 PKT_DATA
, sentreply
, replylen
,
2499 * Handle the key exchange and user authentication phases.
2501 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
2502 struct Packet
*pktin
)
2505 unsigned char cookie
[8], *ptr
;
2506 struct RSAKey servkey
, hostkey
;
2507 struct MD5Context md5c
;
2508 struct do_ssh1_login_state
{
2510 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2511 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2512 int tried_publickey
, tried_agent
;
2513 int tis_auth_refused
, ccard_auth_refused
;
2514 unsigned char session_id
[16];
2517 void *publickey_blob
;
2518 int publickey_bloblen
;
2524 unsigned char request
[5], *response
, *p
;
2533 crState(do_ssh1_login_state
);
2535 crBegin(ssh
->do_ssh1_login_crstate
);
2542 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
2543 bombout(("Public key packet not received"));
2547 logevent("Received public keys");
2549 ptr
= ssh_pkt_getdata(pktin
, 8);
2551 bombout(("SSH1 public key packet stopped before random cookie"));
2554 memcpy(cookie
, ptr
, 8);
2556 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
2557 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
2558 bombout(("Failed to read SSH1 public keys from public key packet"));
2563 * Log the host key fingerprint.
2567 logevent("Host key fingerprint is:");
2568 strcpy(logmsg
, " ");
2569 hostkey
.comment
= NULL
;
2570 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2571 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2575 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
2576 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
2577 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
2579 ssh
->v1_local_protoflags
=
2580 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2581 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2584 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
2585 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
2586 MD5Update(&md5c
, cookie
, 8);
2587 MD5Final(s
->session_id
, &md5c
);
2589 for (i
= 0; i
< 32; i
++)
2590 ssh
->session_key
[i
] = random_byte();
2593 * Verify that the `bits' and `bytes' parameters match.
2595 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
2596 servkey
.bits
> servkey
.bytes
* 8) {
2597 bombout(("SSH1 public keys were badly formatted"));
2601 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2603 s
->rsabuf
= snewn(s
->len
, unsigned char);
2605 fatalbox("Out of memory");
2608 * Verify the host key.
2612 * First format the key into a string.
2614 int len
= rsastr_len(&hostkey
);
2615 char fingerprint
[100];
2616 char *keystr
= snewn(len
, char);
2618 fatalbox("Out of memory");
2619 rsastr_fmt(keystr
, &hostkey
);
2620 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2621 verify_ssh_host_key(ssh
->frontend
,
2622 ssh
->savedhost
, ssh
->savedport
, "rsa", keystr
,
2627 for (i
= 0; i
< 32; i
++) {
2628 s
->rsabuf
[i
] = ssh
->session_key
[i
];
2630 s
->rsabuf
[i
] ^= s
->session_id
[i
];
2633 if (hostkey
.bytes
> servkey
.bytes
) {
2634 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
2636 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
2638 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
2640 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
2643 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2647 logevent("Encrypted session key");
2650 int cipher_chosen
= 0, warn
= 0;
2651 char *cipher_string
= NULL
;
2653 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2654 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
2655 if (next_cipher
== CIPHER_WARN
) {
2656 /* If/when we choose a cipher, warn about it */
2658 } else if (next_cipher
== CIPHER_AES
) {
2659 /* XXX Probably don't need to mention this. */
2660 logevent("AES not supported in SSH1, skipping");
2662 switch (next_cipher
) {
2663 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
2664 cipher_string
= "3DES"; break;
2665 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
2666 cipher_string
= "Blowfish"; break;
2667 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
2668 cipher_string
= "single-DES"; break;
2670 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
2674 if (!cipher_chosen
) {
2675 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2676 bombout(("Server violates SSH 1 protocol by not "
2677 "supporting 3DES encryption"));
2679 /* shouldn't happen */
2680 bombout(("No supported ciphers found"));
2684 /* Warn about chosen cipher if necessary. */
2686 askcipher(ssh
->frontend
, cipher_string
, 0);
2689 switch (s
->cipher_type
) {
2690 case SSH_CIPHER_3DES
:
2691 logevent("Using 3DES encryption");
2693 case SSH_CIPHER_DES
:
2694 logevent("Using single-DES encryption");
2696 case SSH_CIPHER_BLOWFISH
:
2697 logevent("Using Blowfish encryption");
2701 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
2702 PKT_CHAR
, s
->cipher_type
,
2703 PKT_DATA
, cookie
, 8,
2704 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
2705 PKT_DATA
, s
->rsabuf
, s
->len
,
2706 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
2708 logevent("Trying to enable encryption...");
2712 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2713 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
2715 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
2716 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
2717 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
2719 ssh
->crcda_ctx
= crcda_make_context();
2720 logevent("Installing CRC compensation attack detector");
2722 if (servkey
.modulus
) {
2723 sfree(servkey
.modulus
);
2724 servkey
.modulus
= NULL
;
2726 if (servkey
.exponent
) {
2727 sfree(servkey
.exponent
);
2728 servkey
.exponent
= NULL
;
2730 if (hostkey
.modulus
) {
2731 sfree(hostkey
.modulus
);
2732 hostkey
.modulus
= NULL
;
2734 if (hostkey
.exponent
) {
2735 sfree(hostkey
.exponent
);
2736 hostkey
.exponent
= NULL
;
2740 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
2741 bombout(("Encryption not successfully enabled"));
2745 logevent("Successfully started encryption");
2749 if (!*ssh
->cfg
.username
) {
2750 if (ssh_get_line
&& !ssh_getline_pw_only
) {
2751 if (!ssh_get_line("login as: ",
2752 s
->username
, sizeof(s
->username
), FALSE
)) {
2754 * get_line failed to get a username.
2757 logevent("No username provided. Abandoning session.");
2758 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
2762 int ret
; /* need not be kept over crReturn */
2763 c_write_str(ssh
, "login as: ");
2766 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
2768 crWaitUntil(!pktin
);
2769 ret
= process_userpass_input(ssh
, in
, inlen
);
2773 c_write_str(ssh
, "\r\n");
2776 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
2777 s
->username
[sizeof(s
->username
)-1] = '\0';
2780 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
2782 char userlog
[22 + sizeof(s
->username
)];
2783 sprintf(userlog
, "Sent username \"%s\"", s
->username
);
2785 if (flags
& FLAG_INTERACTIVE
&&
2786 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2787 strcat(userlog
, "\r\n");
2788 c_write_str(ssh
, userlog
);
2795 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2796 /* We must not attempt PK auth. Pretend we've already tried it. */
2797 s
->tried_publickey
= s
->tried_agent
= 1;
2799 s
->tried_publickey
= s
->tried_agent
= 0;
2801 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
2802 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2803 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
2804 if (!rsakey_pubblob(&ssh
->cfg
.keyfile
,
2805 &s
->publickey_blob
, &s
->publickey_bloblen
, NULL
))
2806 s
->publickey_blob
= NULL
;
2808 s
->publickey_blob
= NULL
;
2810 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
2811 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2813 if (agent_exists() && !s
->tried_agent
) {
2815 * Attempt RSA authentication using Pageant.
2821 logevent("Pageant is running. Requesting keys.");
2823 /* Request the keys held by the agent. */
2824 PUT_32BIT(s
->request
, 1);
2825 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2826 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
2827 ssh_agent_callback
, ssh
)) {
2831 bombout(("Unexpected data from server while waiting"
2832 " for agent response"));
2835 } while (pktin
|| inlen
> 0);
2836 r
= ssh
->agent_response
;
2837 s
->responselen
= ssh
->agent_response_len
;
2839 s
->response
= (unsigned char *) r
;
2840 if (s
->response
&& s
->responselen
>= 5 &&
2841 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2842 s
->p
= s
->response
+ 5;
2843 s
->nkeys
= GET_32BIT(s
->p
);
2847 sprintf(buf
, "Pageant has %d SSH1 keys", s
->nkeys
);
2850 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
2853 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
2856 if (s
->publickey_blob
&&
2857 !memcmp(s
->p
, s
->publickey_blob
,
2858 s
->publickey_bloblen
)) {
2859 logevent("This key matches configured key file");
2860 s
->tried_publickey
= 1;
2865 do { /* do while (0) to make breaking easy */
2866 n
= ssh1_read_bignum
2867 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
2872 n
= ssh1_read_bignum
2873 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
2878 if (s
->responselen
- (s
->p
-s
->response
) < 4)
2880 s
->commentlen
= GET_32BIT(s
->p
);
2882 if (s
->responselen
- (s
->p
-s
->response
) <
2885 s
->commentp
= (char *)s
->p
;
2886 s
->p
+= s
->commentlen
;
2890 logevent("Pageant key list packet was truncated");
2894 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
2895 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
2897 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2898 logevent("Key refused");
2901 logevent("Received RSA challenge");
2902 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
2903 bombout(("Server's RSA challenge was badly formatted"));
2908 char *agentreq
, *q
, *ret
;
2911 len
= 1 + 4; /* message type, bit count */
2912 len
+= ssh1_bignum_length(s
->key
.exponent
);
2913 len
+= ssh1_bignum_length(s
->key
.modulus
);
2914 len
+= ssh1_bignum_length(s
->challenge
);
2915 len
+= 16; /* session id */
2916 len
+= 4; /* response format */
2917 agentreq
= snewn(4 + len
, char);
2918 PUT_32BIT(agentreq
, len
);
2920 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2921 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
2923 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
2924 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
2925 q
+= ssh1_write_bignum(q
, s
->challenge
);
2926 memcpy(q
, s
->session_id
, 16);
2928 PUT_32BIT(q
, 1); /* response format */
2929 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
2930 ssh_agent_callback
, ssh
)) {
2935 bombout(("Unexpected data from server"
2936 " while waiting for agent"
2940 } while (pktin
|| inlen
> 0);
2941 vret
= ssh
->agent_response
;
2942 retlen
= ssh
->agent_response_len
;
2947 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2948 logevent("Sending Pageant's response");
2949 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
2950 PKT_DATA
, ret
+ 5, 16,
2954 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
2956 ("Pageant's response accepted");
2957 if (flags
& FLAG_VERBOSE
) {
2958 c_write_str(ssh
, "Authenticated using"
2960 c_write(ssh
, s
->commentp
,
2962 c_write_str(ssh
, "\" from agent\r\n");
2967 ("Pageant's response not accepted");
2970 ("Pageant failed to answer challenge");
2974 logevent("No reply received from Pageant");
2977 freebn(s
->key
.exponent
);
2978 freebn(s
->key
.modulus
);
2979 freebn(s
->challenge
);
2988 if (!filename_is_null(ssh
->cfg
.keyfile
) && !s
->tried_publickey
)
2989 s
->pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2991 if (ssh
->cfg
.try_tis_auth
&&
2992 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2993 !s
->tis_auth_refused
) {
2994 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2995 logevent("Requested TIS authentication");
2996 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
2998 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2999 logevent("TIS authentication declined");
3000 if (flags
& FLAG_INTERACTIVE
)
3001 c_write_str(ssh
, "TIS authentication refused.\r\n");
3002 s
->tis_auth_refused
= 1;
3008 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3010 bombout(("TIS challenge packet was badly formed"));
3013 logevent("Received TIS challenge");
3014 if (challengelen
> sizeof(s
->prompt
) - 1)
3015 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3016 memcpy(s
->prompt
, challenge
, challengelen
);
3017 /* Prompt heuristic comes from OpenSSH */
3018 strncpy(s
->prompt
+ challengelen
,
3019 memchr(s
->prompt
, '\n', challengelen
) ?
3020 "": "\r\nResponse: ",
3021 (sizeof s
->prompt
) - challengelen
);
3022 s
->prompt
[(sizeof s
->prompt
) - 1] = '\0';
3025 if (ssh
->cfg
.try_tis_auth
&&
3026 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3027 !s
->ccard_auth_refused
) {
3028 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3029 logevent("Requested CryptoCard authentication");
3030 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3032 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3033 logevent("CryptoCard authentication declined");
3034 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3035 s
->ccard_auth_refused
= 1;
3041 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3043 bombout(("CryptoCard challenge packet was badly formed"));
3046 logevent("Received CryptoCard challenge");
3047 if (challengelen
> sizeof(s
->prompt
) - 1)
3048 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3049 memcpy(s
->prompt
, challenge
, challengelen
);
3050 strncpy(s
->prompt
+ challengelen
,
3051 memchr(s
->prompt
, '\n', challengelen
) ?
3052 "" : "\r\nResponse: ",
3053 sizeof(s
->prompt
) - challengelen
);
3054 s
->prompt
[sizeof(s
->prompt
) - 1] = '\0';
3057 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3058 sprintf(s
->prompt
, "%.90s@%.90s's password: ",
3059 s
->username
, ssh
->savedhost
);
3061 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3062 char *comment
= NULL
;
3065 if (flags
& FLAG_VERBOSE
)
3066 c_write_str(ssh
, "Trying public key authentication.\r\n");
3067 logeventf(ssh
, "Trying public key \"%s\"",
3068 filename_to_str(&ssh
->cfg
.keyfile
));
3069 type
= key_type(&ssh
->cfg
.keyfile
);
3070 if (type
!= SSH_KEYTYPE_SSH1
) {
3071 sprintf(msgbuf
, "Key is of wrong type (%s)",
3072 key_type_to_str(type
));
3074 c_write_str(ssh
, msgbuf
);
3075 c_write_str(ssh
, "\r\n");
3076 s
->tried_publickey
= 1;
3079 if (!rsakey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
3080 if (flags
& FLAG_VERBOSE
)
3081 c_write_str(ssh
, "No passphrase required.\r\n");
3084 sprintf(s
->prompt
, "Passphrase for key \"%.100s\": ", comment
);
3089 * Show password prompt, having first obtained it via a TIS
3090 * or CryptoCard exchange if we're doing TIS or CryptoCard
3094 if (!ssh_get_line(s
->prompt
, s
->password
,
3095 sizeof(s
->password
), TRUE
)) {
3097 * get_line failed to get a password (for example
3098 * because one was supplied on the command line
3099 * which has already failed to work). Terminate.
3101 send_packet(ssh
, SSH1_MSG_DISCONNECT
,
3102 PKT_STR
, "No more passwords available to try",
3104 logevent("Unable to authenticate");
3105 connection_fatal(ssh
->frontend
, "Unable to authenticate");
3106 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
3110 /* Prompt may have come from server. We've munged it a bit, so
3111 * we know it to be zero-terminated at least once. */
3112 int ret
; /* need not be saved over crReturn */
3113 c_write_untrusted(ssh
, s
->prompt
, strlen(s
->prompt
));
3116 setup_userpass_input(ssh
, s
->password
, sizeof(s
->password
), 0);
3118 crWaitUntil(!pktin
);
3119 ret
= process_userpass_input(ssh
, in
, inlen
);
3123 c_write_str(ssh
, "\r\n");
3127 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3129 * Try public key authentication with the specified
3132 s
->tried_publickey
= 1;
3135 const char *error
= NULL
;
3136 int ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, s
->password
,
3139 c_write_str(ssh
, "Couldn't load private key from ");
3140 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3141 c_write_str(ssh
, " (");
3142 c_write_str(ssh
, error
);
3143 c_write_str(ssh
, ").\r\n");
3144 continue; /* go and try password */
3147 c_write_str(ssh
, "Wrong passphrase.\r\n");
3148 s
->tried_publickey
= 0;
3149 continue; /* try again */
3154 * Send a public key attempt.
3156 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3157 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3160 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3161 c_write_str(ssh
, "Server refused our public key.\r\n");
3162 continue; /* go and try password */
3164 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3165 bombout(("Bizarre response to offer of public key"));
3171 unsigned char buffer
[32];
3172 Bignum challenge
, response
;
3174 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3175 bombout(("Server's RSA challenge was badly formatted"));
3178 response
= rsadecrypt(challenge
, &s
->key
);
3179 freebn(s
->key
.private_exponent
);/* burn the evidence */
3181 for (i
= 0; i
< 32; i
++) {
3182 buffer
[i
] = bignum_byte(response
, 31 - i
);
3186 MD5Update(&md5c
, buffer
, 32);
3187 MD5Update(&md5c
, s
->session_id
, 16);
3188 MD5Final(buffer
, &md5c
);
3190 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3191 PKT_DATA
, buffer
, 16, PKT_END
);
3198 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3199 if (flags
& FLAG_VERBOSE
)
3200 c_write_str(ssh
, "Failed to authenticate with"
3201 " our public key.\r\n");
3202 continue; /* go and try password */
3203 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3204 bombout(("Bizarre response to RSA authentication response"));
3208 break; /* we're through! */
3210 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3212 * Defence against traffic analysis: we send a
3213 * whole bunch of packets containing strings of
3214 * different lengths. One of these strings is the
3215 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3216 * The others are all random data in
3217 * SSH1_MSG_IGNORE packets. This way a passive
3218 * listener can't tell which is the password, and
3219 * hence can't deduce the password length.
3221 * Anybody with a password length greater than 16
3222 * bytes is going to have enough entropy in their
3223 * password that a listener won't find it _that_
3224 * much help to know how long it is. So what we'll
3227 * - if password length < 16, we send 15 packets
3228 * containing string lengths 1 through 15
3230 * - otherwise, we let N be the nearest multiple
3231 * of 8 below the password length, and send 8
3232 * packets containing string lengths N through
3233 * N+7. This won't obscure the order of
3234 * magnitude of the password length, but it will
3235 * introduce a bit of extra uncertainty.
3237 * A few servers (the old 1.2.18 through 1.2.22)
3238 * can't deal with SSH1_MSG_IGNORE. For these
3239 * servers, we need an alternative defence. We make
3240 * use of the fact that the password is interpreted
3241 * as a C string: so we can append a NUL, then some
3244 * One server (a Cisco one) can deal with neither
3245 * SSH1_MSG_IGNORE _nor_ a padded password string.
3246 * For this server we are left with no defences
3247 * against password length sniffing.
3249 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
3251 * The server can deal with SSH1_MSG_IGNORE, so
3252 * we can use the primary defence.
3254 int bottom
, top
, pwlen
, i
;
3257 pwlen
= strlen(s
->password
);
3259 bottom
= 0; /* zero length passwords are OK! :-) */
3262 bottom
= pwlen
& ~7;
3266 assert(pwlen
>= bottom
&& pwlen
<= top
);
3268 randomstr
= snewn(top
+ 1, char);
3270 for (i
= bottom
; i
<= top
; i
++) {
3272 defer_packet(ssh
, s
->pwpkt_type
,
3273 PKTT_PASSWORD
, PKT_STR
, s
->password
,
3274 PKTT_OTHER
, PKT_END
);
3276 for (j
= 0; j
< i
; j
++) {
3278 randomstr
[j
] = random_byte();
3279 } while (randomstr
[j
] == '\0');
3281 randomstr
[i
] = '\0';
3282 defer_packet(ssh
, SSH1_MSG_IGNORE
,
3283 PKT_STR
, randomstr
, PKT_END
);
3286 logevent("Sending password with camouflage packets");
3287 ssh_pkt_defersend(ssh
);
3290 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3292 * The server can't deal with SSH1_MSG_IGNORE
3293 * but can deal with padded passwords, so we
3294 * can use the secondary defence.
3300 len
= strlen(s
->password
);
3301 if (len
< sizeof(string
)) {
3303 strcpy(string
, s
->password
);
3304 len
++; /* cover the zero byte */
3305 while (len
< sizeof(string
)) {
3306 string
[len
++] = (char) random_byte();
3311 logevent("Sending length-padded password");
3312 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3313 PKT_INT
, len
, PKT_DATA
, ss
, len
,
3314 PKTT_OTHER
, PKT_END
);
3317 * The server has _both_
3318 * BUG_CHOKES_ON_SSH1_IGNORE and
3319 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3320 * therefore nothing we can do.
3323 len
= strlen(s
->password
);
3324 logevent("Sending unpadded password");
3325 send_packet(ssh
, s
->pwpkt_type
,
3326 PKTT_PASSWORD
, PKT_INT
, len
,
3327 PKT_DATA
, s
->password
, len
,
3328 PKTT_OTHER
, PKT_END
);
3331 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3332 PKT_STR
, s
->password
, PKTT_OTHER
, PKT_END
);
3335 logevent("Sent password");
3336 memset(s
->password
, 0, strlen(s
->password
));
3338 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3339 if (flags
& FLAG_VERBOSE
)
3340 c_write_str(ssh
, "Access denied\r\n");
3341 logevent("Authentication refused");
3342 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3343 bombout(("Strange packet received, type %d", pktin
->type
));
3348 logevent("Authentication successful");
3353 void sshfwd_close(struct ssh_channel
*c
)
3357 if (ssh
->state
!= SSH_STATE_SESSION
) {
3358 assert(ssh
->state
== SSH_STATE_CLOSED
);
3362 if (c
&& !c
->closes
) {
3364 * If the channel's remoteid is -1, we have sent
3365 * CHANNEL_OPEN for this channel, but it hasn't even been
3366 * acknowledged by the server. So we must set a close flag
3367 * on it now, and then when the server acks the channel
3368 * open, we can close it then.
3370 if (((int)c
->remoteid
) != -1) {
3371 if (ssh
->version
== 1) {
3372 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3375 struct Packet
*pktout
;
3376 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3377 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
3378 ssh2_pkt_send(ssh
, pktout
);
3381 c
->closes
= 1; /* sent MSG_CLOSE */
3382 if (c
->type
== CHAN_X11
) {
3384 logevent("Forwarded X11 connection terminated");
3385 } else if (c
->type
== CHAN_SOCKDATA
||
3386 c
->type
== CHAN_SOCKDATA_DORMANT
) {
3388 logevent("Forwarded port closed");
3393 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
3397 if (ssh
->state
!= SSH_STATE_SESSION
) {
3398 assert(ssh
->state
== SSH_STATE_CLOSED
);
3402 if (ssh
->version
== 1) {
3403 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3404 PKT_INT
, c
->remoteid
,
3406 PKT_INT
, len
, PKT_DATA
, buf
, len
,
3407 PKTT_OTHER
, PKT_END
);
3409 * In SSH1 we can return 0 here - implying that forwarded
3410 * connections are never individually throttled - because
3411 * the only circumstance that can cause throttling will be
3412 * the whole SSH connection backing up, in which case
3413 * _everything_ will be throttled as a whole.
3417 ssh2_add_channel_data(c
, buf
, len
);
3418 return ssh2_try_send(c
);
3422 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
3426 if (ssh
->state
!= SSH_STATE_SESSION
) {
3427 assert(ssh
->state
== SSH_STATE_CLOSED
);
3431 if (ssh
->version
== 1) {
3432 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
3433 c
->v
.v1
.throttling
= 0;
3434 ssh1_throttle(ssh
, -1);
3437 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
3441 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
3442 struct Packet
*pktin
)
3444 crBegin(ssh
->do_ssh1_connection_crstate
);
3446 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
3447 logevent("Requesting agent forwarding");
3448 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
3452 if (pktin
->type
!= SSH1_SMSG_SUCCESS
3453 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
3454 bombout(("Protocol confusion"));
3456 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3457 logevent("Agent forwarding refused");
3459 logevent("Agent forwarding enabled");
3460 ssh
->agentfwd_enabled
= TRUE
;
3464 if (ssh
->cfg
.x11_forward
) {
3465 char proto
[20], data
[64];
3466 logevent("Requesting X11 forwarding");
3467 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
3468 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
3469 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
3470 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
3471 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
3472 PKT_STR
, proto
, PKT_STR
, data
,
3473 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
3476 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
3477 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
3482 if (pktin
->type
!= SSH1_SMSG_SUCCESS
3483 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
3484 bombout(("Protocol confusion"));
3486 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3487 logevent("X11 forwarding refused");
3489 logevent("X11 forwarding enabled");
3490 ssh
->X11_fwd_enabled
= TRUE
;
3497 int sport
,dport
,sserv
,dserv
;
3498 char sports
[256], dports
[256], saddr
[256], host
[256];
3500 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
3501 /* Add port forwardings. */
3502 ssh
->portfwd_strptr
= ssh
->cfg
.portfwd
;
3503 while (*ssh
->portfwd_strptr
) {
3504 type
= *ssh
->portfwd_strptr
++;
3507 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= '\t') {
3508 if (*ssh
->portfwd_strptr
== ':') {
3510 * We've seen a colon in the middle of the
3511 * source port number. This means that
3512 * everything we've seen until now is the
3513 * source _address_, so we'll move it into
3514 * saddr and start sports from the beginning
3517 ssh
->portfwd_strptr
++;
3519 strcpy(saddr
, sports
);
3522 if (n
< 255) sports
[n
++] = *ssh
->portfwd_strptr
++;
3526 if (*ssh
->portfwd_strptr
== '\t')
3527 ssh
->portfwd_strptr
++;
3529 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= ':') {
3530 if (n
< 255) host
[n
++] = *ssh
->portfwd_strptr
++;
3533 if (*ssh
->portfwd_strptr
== ':')
3534 ssh
->portfwd_strptr
++;
3536 while (*ssh
->portfwd_strptr
) {
3537 if (n
< 255) dports
[n
++] = *ssh
->portfwd_strptr
++;
3540 ssh
->portfwd_strptr
++;
3541 dport
= atoi(dports
);
3545 dport
= net_service_lookup(dports
);
3547 logeventf(ssh
, "Service lookup failed for"
3548 " destination port \"%s\"", dports
);
3552 while (*ssh
->portfwd_strptr
) ssh
->portfwd_strptr
++;
3554 ssh
->portfwd_strptr
++; /* eat the NUL and move to next one */
3556 sport
= atoi(sports
);
3560 sport
= net_service_lookup(sports
);
3562 logeventf(ssh
, "Service lookup failed for source"
3563 " port \"%s\"", sports
);
3566 if (sport
&& dport
) {
3567 /* Set up a description of the source port. */
3568 static char *sportdesc
;
3569 sportdesc
= dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
3570 (int)(*saddr?
strlen(saddr
):0), *saddr?saddr
:NULL
,
3571 (int)(*saddr?
1:0), ":",
3572 (int)(sserv ?
strlen(sports
) : 0), sports
,
3573 sserv
, "(", sport
, sserv
, ")");
3575 /* Verbose description of the destination port */
3576 char *dportdesc
= dupprintf("%s:%.*s%.*s%d%.*s",
3578 (int)(dserv ?
strlen(dports
) : 0), dports
,
3579 dserv
, "(", dport
, dserv
, ")");
3580 const char *err
= pfd_addforward(host
, dport
,
3581 *saddr ? saddr
: NULL
,
3582 sport
, ssh
, &ssh
->cfg
);
3584 logeventf(ssh
, "Local port %s forward to %s"
3585 " failed: %s", sportdesc
, dportdesc
, err
);
3587 logeventf(ssh
, "Local port %s forwarding to %s",
3588 sportdesc
, dportdesc
);
3591 } else if (type
== 'D') {
3592 const char *err
= pfd_addforward(NULL
, -1,
3593 *saddr ? saddr
: NULL
,
3594 sport
, ssh
, &ssh
->cfg
);
3596 logeventf(ssh
, "Local port %s SOCKS dynamic forward"
3597 " setup failed: %s", sportdesc
, err
);
3599 logeventf(ssh
, "Local port %s doing SOCKS"
3600 " dynamic forwarding", sportdesc
);
3603 struct ssh_rportfwd
*pf
;
3604 pf
= snew(struct ssh_rportfwd
);
3605 strcpy(pf
->dhost
, host
);
3609 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
3612 if (add234(ssh
->rportfwds
, pf
) != pf
) {
3614 "Duplicate remote port forwarding to %s:%d",
3618 logeventf(ssh
, "Requesting remote port %.*s%.*s%d%.*s"
3619 " forward to %s:%.*s%.*s%d%.*s",
3620 (int)(sserv ?
strlen(sports
) : 0), sports
,
3621 sserv
, "(", sport
, sserv
, ")",
3623 (int)(dserv ?
strlen(dports
) : 0), dports
,
3624 dserv
, "(", dport
, dserv
, ")");
3625 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
3633 if (pktin
->type
!= SSH1_SMSG_SUCCESS
3634 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
3635 bombout(("Protocol confusion"));
3637 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3638 c_write_str(ssh
, "Server refused port"
3641 logevent("Remote port forwarding enabled");
3649 if (!ssh
->cfg
.nopty
) {
3650 /* Unpick the terminal-speed string. */
3651 /* XXX perhaps we should allow no speeds to be sent. */
3652 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
3653 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
3654 /* Send the pty request. */
3655 send_packet(ssh
, SSH1_CMSG_REQUEST_PTY
,
3656 PKT_STR
, ssh
->cfg
.termtype
,
3657 PKT_INT
, ssh
->term_height
,
3658 PKT_INT
, ssh
->term_width
,
3659 PKT_INT
, 0, PKT_INT
, 0, /* width,height in pixels */
3660 PKT_CHAR
, 192, PKT_INT
, ssh
->ispeed
, /* TTY_OP_ISPEED */
3661 PKT_CHAR
, 193, PKT_INT
, ssh
->ospeed
, /* TTY_OP_OSPEED */
3662 PKT_CHAR
, 0, PKT_END
);
3663 ssh
->state
= SSH_STATE_INTERMED
;
3667 if (pktin
->type
!= SSH1_SMSG_SUCCESS
3668 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
3669 bombout(("Protocol confusion"));
3671 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3672 c_write_str(ssh
, "Server refused to allocate pty\r\n");
3673 ssh
->editing
= ssh
->echoing
= 1;
3675 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
3676 ssh
->ospeed
, ssh
->ispeed
);
3678 ssh
->editing
= ssh
->echoing
= 1;
3681 if (ssh
->cfg
.compression
) {
3682 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
3686 if (pktin
->type
!= SSH1_SMSG_SUCCESS
3687 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
3688 bombout(("Protocol confusion"));
3690 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3691 c_write_str(ssh
, "Server refused to compress\r\n");
3693 logevent("Started compression");
3694 ssh
->v1_compressing
= TRUE
;
3695 ssh
->cs_comp_ctx
= zlib_compress_init();
3696 logevent("Initialised zlib (RFC1950) compression");
3697 ssh
->sc_comp_ctx
= zlib_decompress_init();
3698 logevent("Initialised zlib (RFC1950) decompression");
3702 * Start the shell or command.
3704 * Special case: if the first-choice command is an SSH2
3705 * subsystem (hence not usable here) and the second choice
3706 * exists, we fall straight back to that.
3709 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
3711 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
3712 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
3713 ssh
->fallback_cmd
= TRUE
;
3716 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
3718 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
3719 logevent("Started session");
3722 ssh
->state
= SSH_STATE_SESSION
;
3723 if (ssh
->size_needed
)
3724 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
3725 if (ssh
->eof_needed
)
3726 ssh_special(ssh
, TS_EOF
);
3729 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
3731 ssh
->channels
= newtree234(ssh_channelcmp
);
3735 if (pktin
->type
== SSH1_SMSG_STDOUT_DATA
||
3736 pktin
->type
== SSH1_SMSG_STDERR_DATA
) {
3738 int stringlen
, bufsize
;
3740 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
3741 if (string
== NULL
) {
3742 bombout(("Incoming terminal data packet was badly formed"));
3747 from_backend(ssh
->frontend
,
3748 pktin
->type
== SSH1_SMSG_STDERR_DATA
,
3750 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3751 ssh
->v1_stdout_throttling
= 1;
3752 ssh1_throttle(ssh
, +1);
3754 } else if (pktin
->type
== SSH1_MSG_DISCONNECT
) {
3755 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
3756 logevent("Received disconnect request");
3758 } else if (pktin
->type
== SSH1_SMSG_X11_OPEN
) {
3759 /* Remote side is trying to open a channel to talk to our
3760 * X-Server. Give them back a local channel number. */
3761 struct ssh_channel
*c
;
3762 int remoteid
= ssh_pkt_getuint32(pktin
);
3764 logevent("Received X11 connect request");
3765 /* Refuse if X11 forwarding is disabled. */
3766 if (!ssh
->X11_fwd_enabled
) {
3767 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3768 PKT_INT
, remoteid
, PKT_END
);
3769 logevent("Rejected X11 connect request");
3771 c
= snew(struct ssh_channel
);
3774 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
3775 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
3776 logevent("Opening X11 forward connection failed");
3778 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3779 PKT_INT
, remoteid
, PKT_END
);
3782 ("Opening X11 forward connection succeeded");
3783 c
->remoteid
= remoteid
;
3784 c
->localid
= alloc_channel_id(ssh
);
3786 c
->v
.v1
.throttling
= 0;
3787 c
->type
= CHAN_X11
; /* identify channel type */
3788 add234(ssh
->channels
, c
);
3789 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3790 PKT_INT
, c
->remoteid
, PKT_INT
,
3791 c
->localid
, PKT_END
);
3792 logevent("Opened X11 forward channel");
3795 } else if (pktin
->type
== SSH1_SMSG_AGENT_OPEN
) {
3796 /* Remote side is trying to open a channel to talk to our
3797 * agent. Give them back a local channel number. */
3798 struct ssh_channel
*c
;
3799 int remoteid
= ssh_pkt_getuint32(pktin
);
3801 /* Refuse if agent forwarding is disabled. */
3802 if (!ssh
->agentfwd_enabled
) {
3803 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3804 PKT_INT
, remoteid
, PKT_END
);
3806 c
= snew(struct ssh_channel
);
3808 c
->remoteid
= remoteid
;
3809 c
->localid
= alloc_channel_id(ssh
);
3811 c
->v
.v1
.throttling
= 0;
3812 c
->type
= CHAN_AGENT
; /* identify channel type */
3813 c
->u
.a
.lensofar
= 0;
3814 add234(ssh
->channels
, c
);
3815 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3816 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
3819 } else if (pktin
->type
== SSH1_MSG_PORT_OPEN
) {
3820 /* Remote side is trying to open a channel to talk to a
3821 * forwarded port. Give them back a local channel number. */
3822 struct ssh_channel
*c
;
3823 struct ssh_rportfwd pf
;
3826 char *host
, buf
[1024];
3828 c
= snew(struct ssh_channel
);
3831 remoteid
= ssh_pkt_getuint32(pktin
);
3832 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
3833 port
= ssh_pkt_getuint32(pktin
);
3835 if (hostsize
>= lenof(pf
.dhost
))
3836 hostsize
= lenof(pf
.dhost
)-1;
3837 memcpy(pf
.dhost
, host
, hostsize
);
3838 pf
.dhost
[hostsize
] = '\0';
3841 if (find234(ssh
->rportfwds
, &pf
, NULL
) == NULL
) {
3842 sprintf(buf
, "Rejected remote port open request for %s:%d",
3845 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3846 PKT_INT
, remoteid
, PKT_END
);
3848 sprintf(buf
, "Received remote port open request for %s:%d",
3851 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
3855 sprintf(buf
, "Port open failed: %s", e
);
3858 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3859 PKT_INT
, remoteid
, PKT_END
);
3861 c
->remoteid
= remoteid
;
3862 c
->localid
= alloc_channel_id(ssh
);
3864 c
->v
.v1
.throttling
= 0;
3865 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
3866 add234(ssh
->channels
, c
);
3867 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3868 PKT_INT
, c
->remoteid
, PKT_INT
,
3869 c
->localid
, PKT_END
);
3870 logevent("Forwarded port opened successfully");
3874 } else if (pktin
->type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3875 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
3876 unsigned int localid
= ssh_pkt_getuint32(pktin
);
3877 struct ssh_channel
*c
;
3879 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
3880 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3881 c
->remoteid
= localid
;
3882 c
->type
= CHAN_SOCKDATA
;
3883 c
->v
.v1
.throttling
= 0;
3884 pfd_confirm(c
->u
.pfd
.s
);
3887 if (c
&& c
->closes
) {
3889 * We have a pending close on this channel,
3890 * which we decided on before the server acked
3891 * the channel open. So now we know the
3892 * remoteid, we can close it again.
3894 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
3895 PKT_INT
, c
->remoteid
, PKT_END
);
3898 } else if (pktin
->type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
3899 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
3900 struct ssh_channel
*c
;
3902 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
3903 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3904 logevent("Forwarded connection refused by server");
3905 pfd_close(c
->u
.pfd
.s
);
3906 del234(ssh
->channels
, c
);
3910 } else if (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE
||
3911 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
3912 /* Remote side closes a channel. */
3913 unsigned i
= ssh_pkt_getuint32(pktin
);
3914 struct ssh_channel
*c
;
3915 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
3916 if (c
&& ((int)c
->remoteid
) != -1) {
3919 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
3921 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
3922 logevent("Forwarded X11 connection terminated");
3923 assert(c
->u
.x11
.s
!= NULL
);
3924 x11_close(c
->u
.x11
.s
);
3927 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
3928 logevent("Forwarded port closed");
3929 assert(c
->u
.pfd
.s
!= NULL
);
3930 pfd_close(c
->u
.pfd
.s
);
3934 c
->closes
|= (closetype
<< 2); /* seen this message */
3935 if (!(c
->closes
& closetype
)) {
3936 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
3938 c
->closes
|= closetype
; /* sent it too */
3941 if (c
->closes
== 15) {
3942 del234(ssh
->channels
, c
);
3946 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3947 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
3948 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
3952 } else if (pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
3953 /* Data sent down one of our channels. */
3954 int i
= ssh_pkt_getuint32(pktin
);
3957 struct ssh_channel
*c
;
3959 ssh_pkt_getstring(pktin
, &p
, &len
);
3961 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
3966 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
3969 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
3972 /* Data for an agent message. Buffer it. */
3974 if (c
->u
.a
.lensofar
< 4) {
3975 int l
= min(4 - c
->u
.a
.lensofar
, len
);
3976 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
3980 c
->u
.a
.lensofar
+= l
;
3982 if (c
->u
.a
.lensofar
== 4) {
3984 4 + GET_32BIT(c
->u
.a
.msglen
);
3985 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
3987 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3989 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3991 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3993 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3997 c
->u
.a
.lensofar
+= l
;
3999 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4002 if (agent_query(c
->u
.a
.message
,
4005 ssh_agentf_callback
, c
))
4006 ssh_agentf_callback(c
, reply
, replylen
);
4007 sfree(c
->u
.a
.message
);
4008 c
->u
.a
.lensofar
= 0;
4011 bufsize
= 0; /* agent channels never back up */
4014 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4015 c
->v
.v1
.throttling
= 1;
4016 ssh1_throttle(ssh
, +1);
4019 } else if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
4020 /* may be from EXEC_SHELL on some servers */
4021 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4022 /* may be from EXEC_SHELL on some servers
4023 * if no pty is available or in other odd cases. Ignore */
4024 } else if (pktin
->type
== SSH1_SMSG_EXIT_STATUS
) {
4026 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
4027 sprintf(buf
, "Server sent command exit status %d",
4030 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
4032 * In case `helpful' firewalls or proxies tack
4033 * extra human-readable text on the end of the
4034 * session which we might mistake for another
4035 * encrypted packet, we close the session once
4036 * we've sent EXIT_CONFIRMATION.
4038 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
4041 bombout(("Strange packet received: type %d", pktin
->type
));
4046 int len
= min(inlen
, 512);
4047 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
, PKTT_DATA
,
4048 PKT_INT
, len
, PKT_DATA
, in
, len
,
4049 PKTT_OTHER
, PKT_END
);
4060 * Handle the top-level SSH2 protocol.
4062 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
4067 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4068 buf
= dupprintf("Remote debug message: %.*s", msglen
, msg
);
4073 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
4075 /* log reason code in disconnect message */
4079 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4080 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
4083 void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
4085 /* Do nothing, because we're ignoring it! Duhh. */
4088 static void ssh1_protocol_setup(Ssh ssh
)
4093 * Most messages are handled by the coroutines.
4095 for (i
= 0; i
< 256; i
++)
4096 ssh
->packet_dispatch
[i
] = NULL
;
4099 * These special message types we install handlers for.
4101 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
4102 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
4103 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
4106 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
4107 struct Packet
*pktin
)
4109 if (ssh
->state
== SSH_STATE_CLOSED
)
4112 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
4113 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
4117 if (!ssh
->protocol_initial_phase_done
) {
4118 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
4119 ssh
->protocol_initial_phase_done
= TRUE
;
4124 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
4128 * Utility routine for decoding comma-separated strings in KEXINIT.
4130 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
4133 if (!needle
|| !haystack
) /* protect against null pointers */
4135 needlen
= strlen(needle
);
4138 * Is it at the start of the string?
4140 if (haylen
>= needlen
&& /* haystack is long enough */
4141 !memcmp(needle
, haystack
, needlen
) && /* initial match */
4142 (haylen
== needlen
|| haystack
[needlen
] == ',')
4143 /* either , or EOS follows */
4147 * If not, search for the next comma and resume after that.
4148 * If no comma found, terminate.
4150 while (haylen
> 0 && *haystack
!= ',')
4151 haylen
--, haystack
++;
4154 haylen
--, haystack
++; /* skip over comma itself */
4159 * SSH2 key creation method.
4161 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
,
4162 unsigned char *sessid
, char chr
,
4163 unsigned char *keyspace
)
4166 /* First 20 bytes. */
4168 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4170 SHA_Bytes(&s
, H
, 20);
4171 SHA_Bytes(&s
, &chr
, 1);
4172 SHA_Bytes(&s
, sessid
, 20);
4173 SHA_Final(&s
, keyspace
);
4174 /* Next 20 bytes. */
4176 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4178 SHA_Bytes(&s
, H
, 20);
4179 SHA_Bytes(&s
, keyspace
, 20);
4180 SHA_Final(&s
, keyspace
+ 20);
4184 * Handle the SSH2 transport layer.
4186 static int do_ssh2_transport(Ssh ssh
, unsigned char *in
, int inlen
,
4187 struct Packet
*pktin
)
4189 struct do_ssh2_transport_state
{
4190 int nbits
, pbits
, warn
;
4191 Bignum p
, g
, e
, f
, K
;
4192 int kex_init_value
, kex_reply_value
;
4193 const struct ssh_mac
**maclist
;
4195 const struct ssh2_cipher
*cscipher_tobe
;
4196 const struct ssh2_cipher
*sccipher_tobe
;
4197 const struct ssh_mac
*csmac_tobe
;
4198 const struct ssh_mac
*scmac_tobe
;
4199 const struct ssh_compress
*cscomp_tobe
;
4200 const struct ssh_compress
*sccomp_tobe
;
4201 char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
4202 int hostkeylen
, siglen
;
4203 void *hkey
; /* actual host key */
4204 unsigned char exchange_hash
[20];
4205 int n_preferred_ciphers
;
4206 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
4207 const struct ssh_compress
*preferred_comp
;
4209 struct Packet
*pktout
;
4211 crState(do_ssh2_transport_state
);
4213 crBegin(ssh
->do_ssh2_transport_crstate
);
4215 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
4216 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
4217 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
4225 * Set up the preferred ciphers. (NULL => warn below here)
4227 s
->n_preferred_ciphers
= 0;
4228 for (i
= 0; i
< CIPHER_MAX
; i
++) {
4229 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
4230 case CIPHER_BLOWFISH
:
4231 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
4234 if (ssh
->cfg
.ssh2_des_cbc
) {
4235 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
4239 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
4242 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
4245 /* Flag for later. Don't bother if it's the last in
4247 if (i
< CIPHER_MAX
- 1) {
4248 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
4256 * Set up preferred compression.
4258 if (ssh
->cfg
.compression
)
4259 s
->preferred_comp
= &ssh_zlib
;
4261 s
->preferred_comp
= &ssh_comp_none
;
4264 * Be prepared to work around the buggy MAC problem.
4266 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
4267 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
4269 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
4273 int i
, j
, cipherstr_started
;
4276 * Enable queueing of outgoing auth- or connection-layer
4277 * packets while we are in the middle of a key exchange.
4279 ssh
->queueing
= TRUE
;
4282 * Construct and send our key exchange packet.
4284 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
4285 for (i
= 0; i
< 16; i
++)
4286 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
4287 /* List key exchange algorithms. */
4288 ssh2_pkt_addstring_start(s
->pktout
);
4289 for (i
= 0; i
< lenof(kex_algs
); i
++) {
4290 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
4291 (ssh
->remote_bugs
& BUG_SSH2_DH_GEX
))
4293 ssh2_pkt_addstring_str(s
->pktout
, kex_algs
[i
]->name
);
4294 if (i
< lenof(kex_algs
) - 1)
4295 ssh2_pkt_addstring_str(s
->pktout
, ",");
4297 /* List server host key algorithms. */
4298 ssh2_pkt_addstring_start(s
->pktout
);
4299 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
4300 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
4301 if (i
< lenof(hostkey_algs
) - 1)
4302 ssh2_pkt_addstring_str(s
->pktout
, ",");
4304 /* List client->server encryption algorithms. */
4305 ssh2_pkt_addstring_start(s
->pktout
);
4306 cipherstr_started
= 0;
4307 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4308 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4309 if (!c
) continue; /* warning flag */
4310 for (j
= 0; j
< c
->nciphers
; j
++) {
4311 if (cipherstr_started
)
4312 ssh2_pkt_addstring_str(s
->pktout
, ",");
4313 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4314 cipherstr_started
= 1;
4317 /* List server->client encryption algorithms. */
4318 ssh2_pkt_addstring_start(s
->pktout
);
4319 cipherstr_started
= 0;
4320 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4321 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4322 if (!c
) continue; /* warning flag */
4323 for (j
= 0; j
< c
->nciphers
; j
++) {
4324 if (cipherstr_started
)
4325 ssh2_pkt_addstring_str(s
->pktout
, ",");
4326 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4327 cipherstr_started
= 1;
4330 /* List client->server MAC algorithms. */
4331 ssh2_pkt_addstring_start(s
->pktout
);
4332 for (i
= 0; i
< s
->nmacs
; i
++) {
4333 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4334 if (i
< s
->nmacs
- 1)
4335 ssh2_pkt_addstring_str(s
->pktout
, ",");
4337 /* List server->client MAC algorithms. */
4338 ssh2_pkt_addstring_start(s
->pktout
);
4339 for (i
= 0; i
< s
->nmacs
; i
++) {
4340 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4341 if (i
< s
->nmacs
- 1)
4342 ssh2_pkt_addstring_str(s
->pktout
, ",");
4344 /* List client->server compression algorithms. */
4345 ssh2_pkt_addstring_start(s
->pktout
);
4346 assert(lenof(compressions
) > 1);
4347 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4348 for (i
= 0; i
< lenof(compressions
); i
++) {
4349 const struct ssh_compress
*c
= compressions
[i
];
4350 if (c
!= s
->preferred_comp
) {
4351 ssh2_pkt_addstring_str(s
->pktout
, ",");
4352 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4355 /* List server->client compression algorithms. */
4356 ssh2_pkt_addstring_start(s
->pktout
);
4357 assert(lenof(compressions
) > 1);
4358 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4359 for (i
= 0; i
< lenof(compressions
); i
++) {
4360 const struct ssh_compress
*c
= compressions
[i
];
4361 if (c
!= s
->preferred_comp
) {
4362 ssh2_pkt_addstring_str(s
->pktout
, ",");
4363 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4366 /* List client->server languages. Empty list. */
4367 ssh2_pkt_addstring_start(s
->pktout
);
4368 /* List server->client languages. Empty list. */
4369 ssh2_pkt_addstring_start(s
->pktout
);
4370 /* First KEX packet does _not_ follow, because we're not that brave. */
4371 ssh2_pkt_addbool(s
->pktout
, FALSE
);
4373 ssh2_pkt_adduint32(s
->pktout
, 0);
4376 ssh
->exhash
= ssh
->exhashbase
;
4377 sha_string(&ssh
->exhash
, s
->pktout
->data
+ 5, s
->pktout
->length
- 5);
4379 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
4383 if (pktin
->length
> 5)
4384 sha_string(&ssh
->exhash
, pktin
->data
+ 5, pktin
->length
- 5);
4387 * Now examine the other side's KEXINIT to see what we're up
4394 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
4395 bombout(("expected key exchange packet from server"));
4399 ssh
->hostkey
= NULL
;
4400 s
->cscipher_tobe
= NULL
;
4401 s
->sccipher_tobe
= NULL
;
4402 s
->csmac_tobe
= NULL
;
4403 s
->scmac_tobe
= NULL
;
4404 s
->cscomp_tobe
= NULL
;
4405 s
->sccomp_tobe
= NULL
;
4406 pktin
->savedpos
+= 16; /* skip garbage cookie */
4407 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
4408 for (i
= 0; i
< lenof(kex_algs
); i
++) {
4409 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
4410 (ssh
->remote_bugs
& BUG_SSH2_DH_GEX
))
4412 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
4413 ssh
->kex
= kex_algs
[i
];
4417 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
4418 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
4419 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
4420 ssh
->hostkey
= hostkey_algs
[i
];
4424 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
4426 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4427 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4431 for (j
= 0; j
< c
->nciphers
; j
++) {
4432 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
4433 s
->cscipher_tobe
= c
->list
[j
];
4438 if (s
->cscipher_tobe
) {
4440 askcipher(ssh
->frontend
, s
->cscipher_tobe
->name
, 1);
4444 if (!s
->cscipher_tobe
) {
4445 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4446 str ? str
: "(null)"));
4450 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
4452 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4453 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4457 for (j
= 0; j
< c
->nciphers
; j
++) {
4458 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
4459 s
->sccipher_tobe
= c
->list
[j
];
4464 if (s
->sccipher_tobe
) {
4466 askcipher(ssh
->frontend
, s
->sccipher_tobe
->name
, 2);
4470 if (!s
->sccipher_tobe
) {
4471 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4472 str ? str
: "(null)"));
4476 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
4477 for (i
= 0; i
< s
->nmacs
; i
++) {
4478 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
4479 s
->csmac_tobe
= s
->maclist
[i
];
4483 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
4484 for (i
= 0; i
< s
->nmacs
; i
++) {
4485 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
4486 s
->scmac_tobe
= s
->maclist
[i
];
4490 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
4491 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
4492 const struct ssh_compress
*c
=
4493 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
4494 if (in_commasep_string(c
->name
, str
, len
)) {
4499 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
4500 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
4501 const struct ssh_compress
*c
=
4502 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
4503 if (in_commasep_string(c
->name
, str
, len
)) {
4511 * Work out the number of bits of key we will need from the key
4512 * exchange. We start with the maximum key length of either
4518 csbits
= s
->cscipher_tobe
->keylen
;
4519 scbits
= s
->sccipher_tobe
->keylen
;
4520 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
4522 /* The keys only have 160-bit entropy, since they're based on
4523 * a SHA-1 hash. So cap the key size at 160 bits. */
4528 * If we're doing Diffie-Hellman group exchange, start by
4529 * requesting a group.
4531 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
4532 logevent("Doing Diffie-Hellman group exchange");
4533 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
4535 * Work out how big a DH group we will need to allow that
4538 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
4539 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
4540 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
4541 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
4544 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
4545 bombout(("expected key exchange group packet from server"));
4548 s
->p
= ssh2_pkt_getmp(pktin
);
4549 s
->g
= ssh2_pkt_getmp(pktin
);
4550 if (!s
->p
|| !s
->g
) {
4551 bombout(("unable to read mp-ints from incoming group packet"));
4554 ssh
->kex_ctx
= dh_setup_group(s
->p
, s
->g
);
4555 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
4556 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
4558 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP1
;
4559 ssh
->kex_ctx
= dh_setup_group1();
4560 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
4561 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
4564 logevent("Doing Diffie-Hellman key exchange");
4566 * Now generate and send e for Diffie-Hellman.
4568 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
4569 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
4570 ssh2_pkt_addmp(s
->pktout
, s
->e
);
4571 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
4574 if (pktin
->type
!= s
->kex_reply_value
) {
4575 bombout(("expected key exchange reply packet from server"));
4578 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
4579 s
->f
= ssh2_pkt_getmp(pktin
);
4581 bombout(("unable to parse key exchange reply packet"));
4584 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
4586 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
4588 sha_string(&ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
4589 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
4590 sha_uint32(&ssh
->exhash
, s
->pbits
);
4591 sha_mpint(&ssh
->exhash
, s
->p
);
4592 sha_mpint(&ssh
->exhash
, s
->g
);
4594 sha_mpint(&ssh
->exhash
, s
->e
);
4595 sha_mpint(&ssh
->exhash
, s
->f
);
4596 sha_mpint(&ssh
->exhash
, s
->K
);
4597 SHA_Final(&ssh
->exhash
, s
->exchange_hash
);
4599 dh_cleanup(ssh
->kex_ctx
);
4600 ssh
->kex_ctx
= NULL
;
4603 debug(("Exchange hash is:\n"));
4604 dmemdump(s
->exchange_hash
, 20);
4607 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
4609 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
4610 (char *)s
->exchange_hash
, 20)) {
4611 bombout(("Server's host key did not match the signature supplied"));
4616 * Authenticate remote host: verify host key. (We've already
4617 * checked the signature of the exchange hash.)
4619 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
4620 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
4621 verify_ssh_host_key(ssh
->frontend
,
4622 ssh
->savedhost
, ssh
->savedport
, ssh
->hostkey
->keytype
,
4623 s
->keystr
, s
->fingerprint
);
4624 if (s
->first_kex
) { /* don't bother logging this in rekeys */
4625 logevent("Host key fingerprint is:");
4626 logevent(s
->fingerprint
);
4628 sfree(s
->fingerprint
);
4630 ssh
->hostkey
->freekey(s
->hkey
);
4633 * Send SSH2_MSG_NEWKEYS.
4635 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
4636 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
4639 * Now our end of the key exchange is complete, we can send all
4640 * our queued higher-layer packets.
4642 ssh
->queueing
= FALSE
;
4643 ssh2_pkt_queuesend(ssh
);
4646 * Expect SSH2_MSG_NEWKEYS from server.
4649 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
4650 bombout(("expected new-keys packet from server"));
4655 * Create and initialise session keys.
4657 if (ssh
->cs_cipher_ctx
)
4658 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
4659 ssh
->cscipher
= s
->cscipher_tobe
;
4660 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
4662 if (ssh
->sc_cipher_ctx
)
4663 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
4664 ssh
->sccipher
= s
->sccipher_tobe
;
4665 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
4667 if (ssh
->cs_mac_ctx
)
4668 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
4669 ssh
->csmac
= s
->csmac_tobe
;
4670 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
4672 if (ssh
->sc_mac_ctx
)
4673 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
4674 ssh
->scmac
= s
->scmac_tobe
;
4675 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
4677 if (ssh
->cs_comp_ctx
)
4678 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
4679 ssh
->cscomp
= s
->cscomp_tobe
;
4680 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
4682 if (ssh
->sc_comp_ctx
)
4683 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
4684 ssh
->sccomp
= s
->sccomp_tobe
;
4685 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
4688 * Set IVs after keys. Here we use the exchange hash from the
4689 * _first_ key exchange.
4692 unsigned char keyspace
[40];
4694 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
4695 sizeof(s
->exchange_hash
));
4696 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'C',keyspace
);
4697 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
4698 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'D',keyspace
);
4699 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
4700 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'A',keyspace
);
4701 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
4702 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'B',keyspace
);
4703 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
4704 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'E',keyspace
);
4705 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
4706 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'F',keyspace
);
4707 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
4709 logeventf(ssh
, "Initialised %.200s client->server encryption",
4710 ssh
->cscipher
->text_name
);
4711 logeventf(ssh
, "Initialised %.200s server->client encryption",
4712 ssh
->sccipher
->text_name
);
4713 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
4714 ssh
->csmac
->text_name
);
4715 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
4716 ssh
->scmac
->text_name
);
4717 if (ssh
->cscomp
->text_name
)
4718 logeventf(ssh
, "Initialised %s compression",
4719 ssh
->cscomp
->text_name
);
4720 if (ssh
->sccomp
->text_name
)
4721 logeventf(ssh
, "Initialised %s decompression",
4722 ssh
->sccomp
->text_name
);
4725 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
4731 * If this is the first key exchange phase, we must pass the
4732 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4733 * wants to see it but because it will need time to initialise
4734 * itself before it sees an actual packet. In subsequent key
4735 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4736 * it would only confuse the layer above.
4738 if (!s
->first_kex
) {
4744 * Now we're encrypting. Begin returning 1 to the protocol main
4745 * function so that other things can run on top of the
4746 * transport. If we ever see a KEXINIT, we must go back to the
4749 while (!(pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
)) {
4752 logevent("Server initiated key re-exchange");
4753 goto begin_key_exchange
;
4759 * Add data to an SSH2 channel output buffer.
4761 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
4764 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
4768 * Attempt to send data on an SSH2 channel.
4770 static int ssh2_try_send(struct ssh_channel
*c
)
4773 struct Packet
*pktout
;
4775 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
4778 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
4779 if ((unsigned)len
> c
->v
.v2
.remwindow
)
4780 len
= c
->v
.v2
.remwindow
;
4781 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
4782 len
= c
->v
.v2
.remmaxpkt
;
4783 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
4784 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
4785 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
4786 ssh2_pkt_addstring_start(pktout
);
4787 ssh2_pkt_addstring_data(pktout
, data
, len
);
4788 end_log_omission(ssh
, pktout
);
4789 ssh2_pkt_send(ssh
, pktout
);
4790 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
4791 c
->v
.v2
.remwindow
-= len
;
4795 * After having sent as much data as we can, return the amount
4798 return bufchain_size(&c
->v
.v2
.outbuffer
);
4802 * Potentially enlarge the window on an SSH2 channel.
4804 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
4809 * Never send WINDOW_ADJUST for a channel that the remote side
4810 * already thinks it's closed; there's no point, since it won't
4811 * be sending any more data anyway.
4816 if (newwin
> c
->v
.v2
.locwindow
) {
4817 struct Packet
*pktout
;
4819 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4820 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
4821 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
4822 ssh2_pkt_send(ssh
, pktout
);
4823 c
->v
.v2
.locwindow
= newwin
;
4827 void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
4829 unsigned i
= ssh_pkt_getuint32(pktin
);
4830 struct ssh_channel
*c
;
4831 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4832 if (c
&& !c
->closes
)
4833 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
4837 * Handle the SSH2 userauth and connection layers.
4839 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
4840 struct Packet
*pktin
)
4842 struct do_ssh2_authconn_state
{
4844 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
4846 AUTH_KEYBOARD_INTERACTIVE
4850 AUTH_TYPE_PUBLICKEY
,
4851 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
4852 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
4854 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
4855 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4857 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
4858 int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
4859 int kbd_inter_running
;
4861 int num_prompts
, curr_prompt
, echo
;
4866 void *publickey_blob
;
4867 int publickey_bloblen
;
4868 unsigned char request
[5], *response
, *p
;
4872 char *pkblob
, *alg
, *commentp
;
4873 int pklen
, alglen
, commentlen
;
4874 int siglen
, retlen
, len
;
4875 char *q
, *agentreq
, *ret
;
4877 int num_env
, env_left
, env_ok
;
4878 struct Packet
*pktout
;
4880 crState(do_ssh2_authconn_state
);
4882 crBegin(ssh
->do_ssh2_authconn_crstate
);
4885 * Request userauth protocol, and await a response to it.
4887 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
4888 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
4889 ssh2_pkt_send(ssh
, s
->pktout
);
4890 crWaitUntilV(pktin
);
4891 if (pktin
->type
!= SSH2_MSG_SERVICE_ACCEPT
) {
4892 bombout(("Server refused user authentication protocol"));
4897 * We repeat this whole loop, including the username prompt,
4898 * until we manage a successful authentication. If the user
4899 * types the wrong _password_, they can be sent back to the
4900 * beginning to try another username, if this is configured on.
4901 * (If they specify a username in the config, they are never
4902 * asked, even if they do give a wrong password.)
4904 * I think this best serves the needs of
4906 * - the people who have no configuration, no keys, and just
4907 * want to try repeated (username,password) pairs until they
4908 * type both correctly
4910 * - people who have keys and configuration but occasionally
4911 * need to fall back to passwords
4913 * - people with a key held in Pageant, who might not have
4914 * logged in to a particular machine before; so they want to
4915 * type a username, and then _either_ their key will be
4916 * accepted, _or_ they will type a password. If they mistype
4917 * the username they will want to be able to get back and
4920 s
->username
[0] = '\0';
4921 s
->got_username
= FALSE
;
4926 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
4928 * We got a username last time round this loop, and
4929 * with change_username turned off we don't try to get
4932 } else if (!*ssh
->cfg
.username
) {
4933 if (ssh_get_line
&& !ssh_getline_pw_only
) {
4934 if (!ssh_get_line("login as: ",
4935 s
->username
, sizeof(s
->username
), FALSE
)) {
4937 * get_line failed to get a username.
4940 logevent("No username provided. Abandoning session.");
4941 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
4945 int ret
; /* need not be saved across crReturn */
4946 c_write_str(ssh
, "login as: ");
4948 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
4950 crWaitUntilV(!pktin
);
4951 ret
= process_userpass_input(ssh
, in
, inlen
);
4955 c_write_str(ssh
, "\r\n");
4957 s
->username
[strcspn(s
->username
, "\n\r")] = '\0';
4960 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
4961 s
->username
[sizeof(s
->username
)-1] = '\0';
4962 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
4963 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
4964 c_write_str(ssh
, stuff
);
4968 s
->got_username
= TRUE
;
4971 * Send an authentication request using method "none": (a)
4972 * just in case it succeeds, and (b) so that we know what
4973 * authentication methods we can usefully try next.
4975 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4977 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4978 ssh2_pkt_addstring(s
->pktout
, s
->username
);
4979 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
4980 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
4981 ssh2_pkt_send(ssh
, s
->pktout
);
4982 s
->type
= AUTH_TYPE_NONE
;
4984 s
->we_are_in
= FALSE
;
4986 s
->tried_pubkey_config
= FALSE
;
4987 s
->tried_agent
= FALSE
;
4988 s
->tried_keyb_inter
= FALSE
;
4989 s
->kbd_inter_running
= FALSE
;
4990 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
4991 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
4993 logeventf(ssh
, "Reading private key file \"%.150s\"",
4994 filename_to_str(&ssh
->cfg
.keyfile
));
4995 keytype
= key_type(&ssh
->cfg
.keyfile
);
4996 if (keytype
== SSH_KEYTYPE_SSH2
) {
4998 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
, NULL
,
4999 &s
->publickey_bloblen
, NULL
);
5002 logeventf(ssh
, "Unable to use this key file (%s)",
5003 key_type_to_str(keytype
));
5004 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
5006 filename_to_str(&ssh
->cfg
.keyfile
),
5007 key_type_to_str(keytype
));
5008 c_write_str(ssh
, msgbuf
);
5010 s
->publickey_blob
= NULL
;
5013 s
->publickey_blob
= NULL
;
5017 * Wait for the result of the last authentication request.
5020 crWaitUntilV(pktin
);
5021 while (pktin
->type
== SSH2_MSG_USERAUTH_BANNER
) {
5025 * Don't show the banner if we're operating in
5026 * non-verbose non-interactive mode. (It's probably
5027 * a script, which means nobody will read the
5028 * banner _anyway_, and moreover the printing of
5029 * the banner will screw up processing on the
5030 * output of (say) plink.)
5032 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
5033 ssh_pkt_getstring(pktin
, &banner
, &size
);
5035 c_write_untrusted(ssh
, banner
, size
);
5037 crWaitUntilV(pktin
);
5039 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
5040 logevent("Access granted");
5041 s
->we_are_in
= TRUE
;
5045 if (s
->kbd_inter_running
&&
5046 pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
5048 * This is either a further set-of-prompts packet
5049 * in keyboard-interactive authentication, or it's
5050 * the same one and we came back here with `gotit'
5051 * set. In the former case, we must reset the
5052 * curr_prompt variable.
5056 } else if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
) {
5057 bombout(("Strange packet received during authentication: type %d",
5065 * OK, we're now sitting on a USERAUTH_FAILURE message, so
5066 * we can look at the string in it and know what we can
5067 * helpfully try next.
5069 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
5072 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
5073 s
->kbd_inter_running
= FALSE
;
5074 if (!ssh2_pkt_getbool(pktin
)) {
5076 * We have received an unequivocal Access
5077 * Denied. This can translate to a variety of
5080 * - if we'd just tried "none" authentication,
5081 * it's not worth printing anything at all
5083 * - if we'd just tried a public key _offer_,
5084 * the message should be "Server refused our
5085 * key" (or no message at all if the key
5086 * came from Pageant)
5088 * - if we'd just tried anything else, the
5089 * message really should be "Access denied".
5091 * Additionally, if we'd just tried password
5092 * authentication, we should break out of this
5093 * whole loop so as to go back to the username
5094 * prompt (iff we're configured to allow
5095 * username change attempts).
5097 if (s
->type
== AUTH_TYPE_NONE
) {
5099 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
5100 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
5101 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
5102 c_write_str(ssh
, "Server refused our key\r\n");
5103 logevent("Server refused public key");
5104 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
5105 /* server declined keyboard-interactive; ignore */
5107 c_write_str(ssh
, "Access denied\r\n");
5108 logevent("Access denied");
5109 if (s
->type
== AUTH_TYPE_PASSWORD
&&
5110 ssh
->cfg
.change_username
) {
5111 /* XXX perhaps we should allow
5112 * keyboard-interactive to do this too? */
5113 s
->we_are_in
= FALSE
;
5118 c_write_str(ssh
, "Further authentication required\r\n");
5119 logevent("Further authentication required");
5123 in_commasep_string("publickey", methods
, methlen
);
5125 in_commasep_string("password", methods
, methlen
);
5126 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
5127 in_commasep_string("keyboard-interactive", methods
, methlen
);
5131 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
5135 * Most password/passphrase prompts will be
5136 * non-echoing, so we set this to 0 by default.
5137 * Exception is that some keyboard-interactive prompts
5138 * can be echoing, in which case we'll set this to 1.
5142 if (!s
->method
&& s
->can_pubkey
&&
5143 agent_exists() && !s
->tried_agent
) {
5145 * Attempt public-key authentication using Pageant.
5150 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
5151 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
5153 s
->tried_agent
= TRUE
;
5155 logevent("Pageant is running. Requesting keys.");
5157 /* Request the keys held by the agent. */
5158 PUT_32BIT(s
->request
, 1);
5159 s
->request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
5160 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
5161 ssh_agent_callback
, ssh
)) {
5165 bombout(("Unexpected data from server while"
5166 " waiting for agent response"));
5169 } while (pktin
|| inlen
> 0);
5170 r
= ssh
->agent_response
;
5171 s
->responselen
= ssh
->agent_response_len
;
5173 s
->response
= (unsigned char *) r
;
5174 if (s
->response
&& s
->responselen
>= 5 &&
5175 s
->response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
5176 s
->p
= s
->response
+ 5;
5177 s
->nkeys
= GET_32BIT(s
->p
);
5181 sprintf(buf
, "Pageant has %d SSH2 keys", s
->nkeys
);
5184 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
5189 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
5192 s
->pklen
= GET_32BIT(s
->p
);
5194 if (s
->publickey_blob
&&
5195 s
->pklen
== s
->publickey_bloblen
&&
5196 !memcmp(s
->p
, s
->publickey_blob
,
5197 s
->publickey_bloblen
)) {
5198 logevent("This key matches configured key file");
5199 s
->tried_pubkey_config
= 1;
5201 s
->pkblob
= (char *)s
->p
;
5203 s
->alglen
= GET_32BIT(s
->pkblob
);
5204 s
->alg
= s
->pkblob
+ 4;
5205 s
->commentlen
= GET_32BIT(s
->p
);
5207 s
->commentp
= (char *)s
->p
;
5208 s
->p
+= s
->commentlen
;
5209 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
5210 ssh2_pkt_addstring(s
->pktout
, s
->username
);
5211 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
5212 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
5213 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
5214 ssh2_pkt_addstring_start(s
->pktout
);
5215 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
5216 ssh2_pkt_addstring_start(s
->pktout
);
5217 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
5218 ssh2_pkt_send(ssh
, s
->pktout
);
5220 crWaitUntilV(pktin
);
5221 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
5222 logevent("Key refused");
5226 if (flags
& FLAG_VERBOSE
) {
5227 c_write_str(ssh
, "Authenticating with "
5229 c_write(ssh
, s
->commentp
, s
->commentlen
);
5230 c_write_str(ssh
, "\" from agent\r\n");
5234 * Server is willing to accept the key.
5235 * Construct a SIGN_REQUEST.
5237 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
5238 ssh2_pkt_addstring(s
->pktout
, s
->username
);
5239 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
5240 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
5241 ssh2_pkt_addbool(s
->pktout
, TRUE
);
5242 ssh2_pkt_addstring_start(s
->pktout
);
5243 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
5244 ssh2_pkt_addstring_start(s
->pktout
);
5245 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
5247 s
->siglen
= s
->pktout
->length
- 5 + 4 + 20;
5248 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
5250 s
->len
= 1; /* message type */
5251 s
->len
+= 4 + s
->pklen
; /* key blob */
5252 s
->len
+= 4 + s
->siglen
; /* data to sign */
5253 s
->len
+= 4; /* flags */
5254 s
->agentreq
= snewn(4 + s
->len
, char);
5255 PUT_32BIT(s
->agentreq
, s
->len
);
5256 s
->q
= s
->agentreq
+ 4;
5257 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
5258 PUT_32BIT(s
->q
, s
->pklen
);
5260 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
5262 PUT_32BIT(s
->q
, s
->siglen
);
5264 /* Now the data to be signed... */
5265 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
5266 PUT_32BIT(s
->q
, 20);
5269 memcpy(s
->q
, ssh
->v2_session_id
, 20);
5271 memcpy(s
->q
, s
->pktout
->data
+ 5,
5272 s
->pktout
->length
- 5);
5273 s
->q
+= s
->pktout
->length
- 5;
5274 /* And finally the (zero) flags word. */
5276 if (!agent_query(s
->agentreq
, s
->len
+ 4,
5278 ssh_agent_callback
, ssh
)) {
5282 bombout(("Unexpected data from server"
5283 " while waiting for agent"
5287 } while (pktin
|| inlen
> 0);
5288 vret
= ssh
->agent_response
;
5289 s
->retlen
= ssh
->agent_response_len
;
5294 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
5295 logevent("Sending Pageant's response");
5296 ssh2_add_sigblob(ssh
, s
->pktout
,
5297 s
->pkblob
, s
->pklen
,
5299 GET_32BIT(s
->ret
+ 5));
5300 ssh2_pkt_send(ssh
, s
->pktout
);
5305 ("Pageant failed to answer challenge");
5316 if (!s
->method
&& s
->can_pubkey
&& s
->publickey_blob
5317 && !s
->tried_pubkey_config
) {
5318 unsigned char *pub_blob
;
5319 char *algorithm
, *comment
;
5322 s
->tried_pubkey_config
= TRUE
;
5324 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
5325 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
5328 * Try the public key supplied in the configuration.
5330 * First, offer the public blob to see if the server is
5331 * willing to accept it.
5334 (unsigned char *)ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
5339 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
5340 ssh2_pkt_addstring(s
->pktout
, s
->username
);
5341 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
5342 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
5343 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
5344 ssh2_pkt_addstring(s
->pktout
, algorithm
);
5345 ssh2_pkt_addstring_start(s
->pktout
);
5346 ssh2_pkt_addstring_data(s
->pktout
, (char *)pub_blob
,
5348 ssh2_pkt_send(ssh
, s
->pktout
);
5349 logevent("Offered public key");
5351 crWaitUntilV(pktin
);
5352 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
5354 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
5355 continue; /* key refused; give up on it */
5358 logevent("Offer of public key accepted");
5360 * Actually attempt a serious authentication using
5363 if (ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
5364 sprintf(s
->pwprompt
,
5365 "Passphrase for key \"%.100s\": ",
5371 if (flags
& FLAG_VERBOSE
) {
5372 c_write_str(ssh
, "Authenticating with public key \"");
5373 c_write_str(ssh
, comment
);
5374 c_write_str(ssh
, "\"\r\n");
5376 s
->method
= AUTH_PUBLICKEY_FILE
;
5380 if (!s
->method
&& s
->can_keyb_inter
&& !s
->tried_keyb_inter
) {
5381 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
5382 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
5383 s
->tried_keyb_inter
= TRUE
;
5385 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
5386 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
5388 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
5389 ssh2_pkt_addstring(s
->pktout
, s
->username
);
5390 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
5391 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive"); /* method */
5392 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
5393 ssh2_pkt_addstring(s
->pktout
, "");
5394 ssh2_pkt_send(ssh
, s
->pktout
);
5396 crWaitUntilV(pktin
);
5397 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
5398 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
5400 logevent("Keyboard-interactive authentication refused");
5401 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
5405 s
->kbd_inter_running
= TRUE
;
5409 if (s
->kbd_inter_running
) {
5410 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
5411 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
5412 s
->tried_keyb_inter
= TRUE
;
5414 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
5415 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
5417 if (s
->curr_prompt
== 0) {
5419 * We've got a fresh USERAUTH_INFO_REQUEST.
5420 * Display header data, and start going through
5423 char *name
, *inst
, *lang
;
5424 int name_len
, inst_len
, lang_len
;
5426 ssh_pkt_getstring(pktin
, &name
, &name_len
);
5427 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
5428 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
5430 c_write_untrusted(ssh
, name
, name_len
);
5431 c_write_str(ssh
, "\r\n");
5434 c_write_untrusted(ssh
, inst
, inst_len
);
5435 c_write_str(ssh
, "\r\n");
5437 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
5441 * If there are prompts remaining in the packet,
5442 * display one and get a response.
5444 if (s
->curr_prompt
< s
->num_prompts
) {
5448 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
5449 if (prompt_len
> 0) {
5450 static const char trunc
[] = "<prompt truncated>: ";
5451 static const int prlen
= sizeof(s
->pwprompt
) -
5453 if (prompt_len
> prlen
) {
5454 memcpy(s
->pwprompt
, prompt
, prlen
);
5455 strcpy(s
->pwprompt
+ prlen
, trunc
);
5457 memcpy(s
->pwprompt
, prompt
, prompt_len
);
5458 s
->pwprompt
[prompt_len
] = '\0';
5462 "<server failed to send prompt>: ");
5464 s
->echo
= ssh2_pkt_getbool(pktin
);
5470 if (!s
->method
&& s
->can_passwd
) {
5471 s
->method
= AUTH_PASSWORD
;
5472 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
5473 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
5474 sprintf(s
->pwprompt
, "%.90s@%.90s's password: ", s
->username
,
5481 if (!ssh_get_line(s
->pwprompt
, s
->password
,
5482 sizeof(s
->password
), TRUE
)) {
5484 * get_line failed to get a password (for
5485 * example because one was supplied on the
5486 * command line which has already failed to
5489 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5490 ssh2_pkt_adduint32(s
->pktout
,SSH2_DISCONNECT_BY_APPLICATION
);
5491 ssh2_pkt_addstring(s
->pktout
, "No more passwords available"
5493 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
5494 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5495 logevent("Unable to authenticate");
5496 connection_fatal(ssh
->frontend
,
5497 "Unable to authenticate");
5498 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5502 int ret
; /* need not be saved across crReturn */
5503 c_write_untrusted(ssh
, s
->pwprompt
, strlen(s
->pwprompt
));
5506 setup_userpass_input(ssh
, s
->password
,
5507 sizeof(s
->password
), s
->echo
);
5509 crWaitUntilV(!pktin
);
5510 ret
= process_userpass_input(ssh
, in
, inlen
);
5514 c_write_str(ssh
, "\r\n");
5518 if (s
->method
== AUTH_PUBLICKEY_FILE
) {
5520 * We have our passphrase. Now try the actual authentication.
5522 struct ssh2_userkey
*key
;
5523 const char *error
= NULL
;
5525 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, s
->password
,
5527 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
5528 if (key
== SSH2_WRONG_PASSPHRASE
) {
5529 c_write_str(ssh
, "Wrong passphrase\r\n");
5530 s
->tried_pubkey_config
= FALSE
;
5532 c_write_str(ssh
, "Unable to load private key (");
5533 c_write_str(ssh
, error
);
5534 c_write_str(ssh
, ")\r\n");
5535 s
->tried_pubkey_config
= TRUE
;
5537 /* Send a spurious AUTH_NONE to return to the top. */
5538 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
5539 ssh2_pkt_addstring(s
->pktout
, s
->username
);
5540 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
5541 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
5542 ssh2_pkt_send(ssh
, s
->pktout
);
5543 s
->type
= AUTH_TYPE_NONE
;
5545 unsigned char *pkblob
, *sigblob
, *sigdata
;
5546 int pkblob_len
, sigblob_len
, sigdata_len
;
5550 * We have loaded the private key and the server
5551 * has announced that it's willing to accept it.
5552 * Hallelujah. Generate a signature and send it.
5554 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
5555 ssh2_pkt_addstring(s
->pktout
, s
->username
);
5556 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
5557 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
5558 ssh2_pkt_addbool(s
->pktout
, TRUE
);
5559 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
5560 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
5561 ssh2_pkt_addstring_start(s
->pktout
);
5562 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
, pkblob_len
);
5565 * The data to be signed is:
5569 * followed by everything so far placed in the
5572 sigdata_len
= s
->pktout
->length
- 5 + 4 + 20;
5573 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
5575 sigdata
= snewn(sigdata_len
, unsigned char);
5577 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
5578 PUT_32BIT(sigdata
+p
, 20);
5581 memcpy(sigdata
+p
, ssh
->v2_session_id
, 20); p
+= 20;
5582 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
5583 s
->pktout
->length
- 5);
5584 p
+= s
->pktout
->length
- 5;
5585 assert(p
== sigdata_len
);
5586 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
5587 sigdata_len
, &sigblob_len
);
5588 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
5589 sigblob
, sigblob_len
);
5594 ssh2_pkt_send(ssh
, s
->pktout
);
5595 s
->type
= AUTH_TYPE_PUBLICKEY
;
5596 key
->alg
->freekey(key
->data
);
5598 } else if (s
->method
== AUTH_PASSWORD
) {
5600 * We send the password packet lumped tightly together with
5601 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
5602 * string long enough to make the total length of the two
5603 * packets constant. This should ensure that a passive
5604 * listener doing traffic analyis can't work out the length
5607 * For this to work, we need an assumption about the
5608 * maximum length of the password packet. I think 256 is
5609 * pretty conservative. Anyone using a password longer than
5610 * that probably doesn't have much to worry about from
5611 * people who find out how long their password is!
5613 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
5614 ssh2_pkt_addstring(s
->pktout
, s
->username
);
5615 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
5616 ssh2_pkt_addstring(s
->pktout
, "password");
5617 ssh2_pkt_addbool(s
->pktout
, FALSE
);
5618 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
5619 ssh2_pkt_addstring(s
->pktout
, s
->password
);
5620 memset(s
->password
, 0, sizeof(s
->password
));
5621 end_log_omission(ssh
, s
->pktout
);
5622 ssh2_pkt_defer(ssh
, s
->pktout
);
5624 * We'll include a string that's an exact multiple of the
5625 * cipher block size. If the cipher is NULL for some
5626 * reason, we don't do this trick at all because we gain
5629 if (ssh
->cscipher
) {
5632 stringlen
= (256 - ssh
->deferred_len
);
5633 stringlen
+= ssh
->cscipher
->blksize
- 1;
5634 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
5637 * Temporarily disable actual compression,
5638 * so we can guarantee to get this string
5639 * exactly the length we want it. The
5640 * compression-disabling routine should
5641 * return an integer indicating how many
5642 * bytes we should adjust our string length
5646 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
5648 s
->pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
5649 ssh2_pkt_addstring_start(s
->pktout
);
5650 for (i
= 0; i
< stringlen
; i
++) {
5651 char c
= (char) random_byte();
5652 ssh2_pkt_addstring_data(s
->pktout
, &c
, 1);
5654 ssh2_pkt_defer(ssh
, s
->pktout
);
5656 ssh_pkt_defersend(ssh
);
5657 logevent("Sent password");
5658 s
->type
= AUTH_TYPE_PASSWORD
;
5659 } else if (s
->method
== AUTH_KEYBOARD_INTERACTIVE
) {
5660 if (s
->curr_prompt
== 0) {
5661 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
5662 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
5664 if (s
->need_pw
) { /* only add pw if we just got one! */
5665 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
5666 ssh2_pkt_addstring(s
->pktout
, s
->password
);
5667 memset(s
->password
, 0, sizeof(s
->password
));
5668 end_log_omission(ssh
, s
->pktout
);
5671 if (s
->curr_prompt
>= s
->num_prompts
) {
5672 ssh2_pkt_send(ssh
, s
->pktout
);
5675 * If there are prompts remaining, we set
5676 * `gotit' so that we won't attempt to get
5677 * another packet. Then we go back round the
5678 * loop and will end up retrieving another
5679 * prompt out of the existing packet. Funky or
5684 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
5686 c_write_str(ssh
, "No supported authentication methods"
5687 " left to try!\r\n");
5688 logevent("No supported authentications offered."
5690 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5691 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
5692 ssh2_pkt_addstring(s
->pktout
, "No supported authentication"
5693 " methods available");
5694 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
5695 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5696 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5700 } while (!s
->we_are_in
);
5703 * Now we're authenticated for the connection protocol. The
5704 * connection protocol will automatically have started at this
5705 * point; there's no need to send SERVICE_REQUEST.
5708 ssh
->channels
= newtree234(ssh_channelcmp
);
5711 * Set up handlers for some connection protocol messages, so we
5712 * don't have to handle them repeatedly in this coroutine.
5714 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
5715 ssh2_msg_channel_window_adjust
;
5718 * Create the main session channel.
5720 if (!ssh
->cfg
.ssh_no_shell
) {
5721 ssh
->mainchan
= snew(struct ssh_channel
);
5722 ssh
->mainchan
->ssh
= ssh
;
5723 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
5724 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5725 ssh2_pkt_addstring(s
->pktout
, "session");
5726 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
5727 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5728 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
5729 ssh2_pkt_adduint32(s
->pktout
, 0x4000UL
); /* our max pkt size */
5730 ssh2_pkt_send(ssh
, s
->pktout
);
5731 crWaitUntilV(pktin
);
5732 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5733 bombout(("Server refused to open a session"));
5735 /* FIXME: error data comes back in FAILURE packet */
5737 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
5738 bombout(("Server's channel confirmation cited wrong channel"));
5741 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
5742 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
5743 ssh
->mainchan
->closes
= 0;
5744 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
5745 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
5746 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
5747 add234(ssh
->channels
, ssh
->mainchan
);
5748 update_specials_menu(ssh
->frontend
);
5749 logevent("Opened channel for session");
5751 ssh
->mainchan
= NULL
;
5754 * Potentially enable X11 forwarding.
5756 if (ssh
->mainchan
&& ssh
->cfg
.x11_forward
) {
5757 char proto
[20], data
[64];
5758 logevent("Requesting X11 forwarding");
5759 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
5760 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
5761 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
5762 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5763 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
5764 ssh2_pkt_addstring(s
->pktout
, "x11-req");
5765 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
5766 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
5767 ssh2_pkt_addstring(s
->pktout
, proto
);
5768 ssh2_pkt_addstring(s
->pktout
, data
);
5769 ssh2_pkt_adduint32(s
->pktout
, x11_get_screen_number(ssh
->cfg
.x11_display
));
5770 ssh2_pkt_send(ssh
, s
->pktout
);
5772 crWaitUntilV(pktin
);
5774 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5775 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5776 bombout(("Unexpected response to X11 forwarding request:"
5777 " packet type %d", pktin
->type
));
5780 logevent("X11 forwarding refused");
5782 logevent("X11 forwarding enabled");
5783 ssh
->X11_fwd_enabled
= TRUE
;
5788 * Enable port forwardings.
5793 int sport
,dport
,sserv
,dserv
;
5794 char sports
[256], dports
[256], saddr
[256], host
[256];
5796 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
5797 /* Add port forwardings. */
5798 ssh
->portfwd_strptr
= ssh
->cfg
.portfwd
;
5799 while (*ssh
->portfwd_strptr
) {
5800 type
= *ssh
->portfwd_strptr
++;
5803 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= '\t') {
5804 if (*ssh
->portfwd_strptr
== ':') {
5806 * We've seen a colon in the middle of the
5807 * source port number. This means that
5808 * everything we've seen until now is the
5809 * source _address_, so we'll move it into
5810 * saddr and start sports from the beginning
5813 ssh
->portfwd_strptr
++;
5815 strcpy(saddr
, sports
);
5818 if (n
< 255) sports
[n
++] = *ssh
->portfwd_strptr
++;
5822 if (*ssh
->portfwd_strptr
== '\t')
5823 ssh
->portfwd_strptr
++;
5825 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= ':') {
5826 if (n
< 255) host
[n
++] = *ssh
->portfwd_strptr
++;
5829 if (*ssh
->portfwd_strptr
== ':')
5830 ssh
->portfwd_strptr
++;
5832 while (*ssh
->portfwd_strptr
) {
5833 if (n
< 255) dports
[n
++] = *ssh
->portfwd_strptr
++;
5836 ssh
->portfwd_strptr
++;
5837 dport
= atoi(dports
);
5841 dport
= net_service_lookup(dports
);
5843 logeventf(ssh
, "Service lookup failed for destination"
5844 " port \"%s\"", dports
);
5848 while (*ssh
->portfwd_strptr
) ssh
->portfwd_strptr
++;
5850 ssh
->portfwd_strptr
++; /* eat the NUL and move to next one */
5852 sport
= atoi(sports
);
5856 sport
= net_service_lookup(sports
);
5858 logeventf(ssh
, "Service lookup failed for source"
5859 " port \"%s\"", sports
);
5862 if (sport
&& dport
) {
5863 /* Set up a description of the source port. */
5864 static char *sportdesc
;
5865 sportdesc
= dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
5866 (int)(*saddr?
strlen(saddr
):0), *saddr?saddr
:NULL
,
5867 (int)(*saddr?
1:0), ":",
5868 (int)(sserv ?
strlen(sports
) : 0), sports
,
5869 sserv
, "(", sport
, sserv
, ")");
5871 /* Verbose description of the destination port */
5872 char *dportdesc
= dupprintf("%s:%.*s%.*s%d%.*s",
5874 (int)(dserv ?
strlen(dports
) : 0), dports
,
5875 dserv
, "(", dport
, dserv
, ")");
5876 const char *err
= pfd_addforward(host
, dport
,
5877 *saddr ? saddr
: NULL
,
5878 sport
, ssh
, &ssh
->cfg
);
5880 logeventf(ssh
, "Local port %s forward to %s"
5881 " failed: %s", sportdesc
, dportdesc
, err
);
5883 logeventf(ssh
, "Local port %s forwarding to %s",
5884 sportdesc
, dportdesc
);
5887 } else if (type
== 'D') {
5888 const char *err
= pfd_addforward(NULL
, -1,
5889 *saddr ? saddr
: NULL
,
5890 sport
, ssh
, &ssh
->cfg
);
5892 logeventf(ssh
, "Local port %s SOCKS dynamic forward"
5893 " setup failed: %s", sportdesc
, err
);
5895 logeventf(ssh
, "Local port %s doing SOCKS"
5896 " dynamic forwarding", sportdesc
);
5899 struct ssh_rportfwd
*pf
;
5900 pf
= snew(struct ssh_rportfwd
);
5901 strcpy(pf
->dhost
, host
);
5904 if (add234(ssh
->rportfwds
, pf
) != pf
) {
5905 logeventf(ssh
, "Duplicate remote port forwarding"
5906 " to %s:%d", host
, dport
);
5909 logeventf(ssh
, "Requesting remote port %s"
5910 " forward to %s:%.*s%.*s%d%.*s",
5913 (int)(dserv ?
strlen(dports
) : 0), dports
,
5914 dserv
, "(", dport
, dserv
, ")");
5915 s
->pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
5916 ssh2_pkt_addstring(s
->pktout
, "tcpip-forward");
5917 ssh2_pkt_addbool(s
->pktout
, 1);/* want reply */
5919 ssh2_pkt_addstring(s
->pktout
, saddr
);
5920 } else if (ssh
->cfg
.rport_acceptall
) {
5921 ssh2_pkt_addstring(s
->pktout
, "0.0.0.0");
5923 ssh2_pkt_addstring(s
->pktout
, "127.0.0.1");
5925 ssh2_pkt_adduint32(s
->pktout
, sport
);
5926 ssh2_pkt_send(ssh
, s
->pktout
);
5928 crWaitUntilV(pktin
);
5930 if (pktin
->type
!= SSH2_MSG_REQUEST_SUCCESS
) {
5931 if (pktin
->type
!= SSH2_MSG_REQUEST_FAILURE
) {
5932 bombout(("Unexpected response to port "
5933 "forwarding request: packet type %d",
5937 logevent("Server refused this port forwarding");
5939 logevent("Remote port forwarding enabled");
5949 * Potentially enable agent forwarding.
5951 if (ssh
->mainchan
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
5952 logevent("Requesting OpenSSH-style agent forwarding");
5953 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5954 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
5955 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
5956 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
5957 ssh2_pkt_send(ssh
, s
->pktout
);
5959 crWaitUntilV(pktin
);
5961 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5962 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5963 bombout(("Unexpected response to agent forwarding request:"
5964 " packet type %d", pktin
->type
));
5967 logevent("Agent forwarding refused");
5969 logevent("Agent forwarding enabled");
5970 ssh
->agentfwd_enabled
= TRUE
;
5975 * Now allocate a pty for the session.
5977 if (ssh
->mainchan
&& !ssh
->cfg
.nopty
) {
5978 /* Unpick the terminal-speed string. */
5979 /* XXX perhaps we should allow no speeds to be sent. */
5980 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
5981 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
5982 /* Build the pty request. */
5983 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5984 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
5985 ssh2_pkt_addstring(s
->pktout
, "pty-req");
5986 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
5987 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
5988 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
5989 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
5990 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
5991 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
5992 ssh2_pkt_addstring_start(s
->pktout
);
5993 ssh2_pkt_addbyte(s
->pktout
, 128); /* TTY_OP_ISPEED */
5994 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
5995 ssh2_pkt_addbyte(s
->pktout
, 129); /* TTY_OP_OSPEED */
5996 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
5997 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
5998 ssh2_pkt_send(ssh
, s
->pktout
);
5999 ssh
->state
= SSH_STATE_INTERMED
;
6001 crWaitUntilV(pktin
);
6003 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6004 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6005 bombout(("Unexpected response to pty request:"
6006 " packet type %d", pktin
->type
));
6009 c_write_str(ssh
, "Server refused to allocate pty\r\n");
6010 ssh
->editing
= ssh
->echoing
= 1;
6012 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6013 ssh
->ospeed
, ssh
->ispeed
);
6016 ssh
->editing
= ssh
->echoing
= 1;
6020 * Send environment variables.
6022 * Simplest thing here is to send all the requests at once, and
6023 * then wait for a whole bunch of successes or failures.
6025 if (ssh
->mainchan
&& *ssh
->cfg
.environmt
) {
6026 char *e
= ssh
->cfg
.environmt
;
6027 char *var
, *varend
, *val
;
6033 while (*e
&& *e
!= '\t') e
++;
6035 if (*e
== '\t') e
++;
6040 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6041 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
6042 ssh2_pkt_addstring(s
->pktout
, "env");
6043 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6044 ssh2_pkt_addstring_start(s
->pktout
);
6045 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
6046 ssh2_pkt_addstring(s
->pktout
, val
);
6047 ssh2_pkt_send(ssh
, s
->pktout
);
6052 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
6055 s
->env_left
= s
->num_env
;
6057 while (s
->env_left
> 0) {
6058 crWaitUntilV(pktin
);
6060 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6061 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6062 bombout(("Unexpected response to environment request:"
6063 " packet type %d", pktin
->type
));
6073 if (s
->env_ok
== s
->num_env
) {
6074 logevent("All environment variables successfully set");
6075 } else if (s
->env_ok
== 0) {
6076 logevent("All environment variables refused");
6077 c_write_str(ssh
, "Server refused to set environment variables\r\n");
6079 logeventf(ssh
, "%d environment variables refused",
6080 s
->num_env
- s
->env_ok
);
6081 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
6086 * Start a shell or a remote command. We may have to attempt
6087 * this twice if the config data has provided a second choice
6090 if (ssh
->mainchan
) while (1) {
6094 if (ssh
->fallback_cmd
) {
6095 subsys
= ssh
->cfg
.ssh_subsys2
;
6096 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
6098 subsys
= ssh
->cfg
.ssh_subsys
;
6099 cmd
= ssh
->cfg
.remote_cmd_ptr
;
6102 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6103 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
6105 ssh2_pkt_addstring(s
->pktout
, "subsystem");
6106 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6107 ssh2_pkt_addstring(s
->pktout
, cmd
);
6109 ssh2_pkt_addstring(s
->pktout
, "exec");
6110 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6111 ssh2_pkt_addstring(s
->pktout
, cmd
);
6113 ssh2_pkt_addstring(s
->pktout
, "shell");
6114 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
6116 ssh2_pkt_send(ssh
, s
->pktout
);
6118 crWaitUntilV(pktin
);
6120 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
6121 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
6122 bombout(("Unexpected response to shell/command request:"
6123 " packet type %d", pktin
->type
));
6127 * We failed to start the command. If this is the
6128 * fallback command, we really are finished; if it's
6129 * not, and if the fallback command exists, try falling
6130 * back to it before complaining.
6132 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
6133 logevent("Primary command failed; attempting fallback");
6134 ssh
->fallback_cmd
= TRUE
;
6137 bombout(("Server refused to start a shell/command"));
6140 logevent("Started a shell/command");
6145 ssh
->state
= SSH_STATE_SESSION
;
6146 if (ssh
->size_needed
)
6147 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
6148 if (ssh
->eof_needed
)
6149 ssh_special(ssh
, TS_EOF
);
6155 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
6160 s
->try_send
= FALSE
;
6162 if (pktin
->type
== SSH2_MSG_CHANNEL_DATA
||
6163 pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
6166 unsigned i
= ssh_pkt_getuint32(pktin
);
6167 struct ssh_channel
*c
;
6168 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6170 continue; /* nonexistent channel */
6171 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
6172 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
6173 continue; /* extended but not stderr */
6174 ssh_pkt_getstring(pktin
, &data
, &length
);
6177 c
->v
.v2
.locwindow
-= length
;
6179 case CHAN_MAINSESSION
:
6181 from_backend(ssh
->frontend
, pktin
->type
==
6182 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
6186 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
6189 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
6192 while (length
> 0) {
6193 if (c
->u
.a
.lensofar
< 4) {
6194 int l
= min(4 - c
->u
.a
.lensofar
, length
);
6195 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
6199 c
->u
.a
.lensofar
+= l
;
6201 if (c
->u
.a
.lensofar
== 4) {
6203 4 + GET_32BIT(c
->u
.a
.msglen
);
6204 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
6206 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
6208 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
6210 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
6212 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
6216 c
->u
.a
.lensofar
+= l
;
6218 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
6221 if (agent_query(c
->u
.a
.message
,
6224 ssh_agentf_callback
, c
))
6225 ssh_agentf_callback(c
, reply
, replylen
);
6226 sfree(c
->u
.a
.message
);
6227 c
->u
.a
.lensofar
= 0;
6234 * If we are not buffering too much data,
6235 * enlarge the window again at the remote side.
6237 if (bufsize
< OUR_V2_WINSIZE
)
6238 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
6240 } else if (pktin
->type
== SSH2_MSG_CHANNEL_EOF
) {
6241 unsigned i
= ssh_pkt_getuint32(pktin
);
6242 struct ssh_channel
*c
;
6244 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6246 continue; /* nonexistent channel */
6248 if (c
->type
== CHAN_X11
) {
6250 * Remote EOF on an X11 channel means we should
6251 * wrap up and close the channel ourselves.
6253 x11_close(c
->u
.x11
.s
);
6255 } else if (c
->type
== CHAN_AGENT
) {
6257 } else if (c
->type
== CHAN_SOCKDATA
) {
6258 pfd_close(c
->u
.pfd
.s
);
6261 } else if (pktin
->type
== SSH2_MSG_CHANNEL_CLOSE
) {
6262 unsigned i
= ssh_pkt_getuint32(pktin
);
6263 struct ssh_channel
*c
;
6265 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6266 if (!c
|| ((int)c
->remoteid
) == -1) {
6267 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
6268 c ?
"half-open" : "nonexistent", i
));
6271 /* Do pre-close processing on the channel. */
6273 case CHAN_MAINSESSION
:
6274 ssh
->mainchan
= NULL
;
6275 update_specials_menu(ssh
->frontend
);
6278 if (c
->u
.x11
.s
!= NULL
)
6279 x11_close(c
->u
.x11
.s
);
6286 if (c
->u
.pfd
.s
!= NULL
)
6287 pfd_close(c
->u
.pfd
.s
);
6291 if (c
->closes
== 0) {
6292 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6293 ssh2_pkt_adduint32(s
->pktout
, c
->remoteid
);
6294 ssh2_pkt_send(ssh
, s
->pktout
);
6296 del234(ssh
->channels
, c
);
6297 bufchain_clear(&c
->v
.v2
.outbuffer
);
6301 * See if that was the last channel left open.
6302 * (This is only our termination condition if we're
6303 * not running in -N mode.)
6305 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
6306 logevent("All channels closed. Disconnecting");
6309 * We used to send SSH_MSG_DISCONNECT here,
6310 * because I'd believed that _every_ conforming
6311 * SSH2 connection had to end with a disconnect
6312 * being sent by at least one side; apparently
6313 * I was wrong and it's perfectly OK to
6314 * unceremoniously slam the connection shut
6315 * when you're done, and indeed OpenSSH feels
6316 * this is more polite than sending a
6317 * DISCONNECT. So now we don't.
6319 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
6320 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
6321 ssh2_pkt_addstring(s
->pktout
, "All open channels closed");
6322 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6323 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6325 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6328 continue; /* remote sends close; ignore (FIXME) */
6329 } else if (pktin
->type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
6330 unsigned i
= ssh_pkt_getuint32(pktin
);
6331 struct ssh_channel
*c
;
6332 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6334 continue; /* nonexistent channel */
6335 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6336 continue; /* dunno why they're confirming this */
6337 c
->remoteid
= ssh_pkt_getuint32(pktin
);
6338 c
->type
= CHAN_SOCKDATA
;
6339 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
6340 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
6342 pfd_confirm(c
->u
.pfd
.s
);
6345 * We have a pending close on this channel,
6346 * which we decided on before the server acked
6347 * the channel open. So now we know the
6348 * remoteid, we can close it again.
6350 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6351 ssh2_pkt_adduint32(s
->pktout
, c
->remoteid
);
6352 ssh2_pkt_send(ssh
, s
->pktout
);
6354 } else if (pktin
->type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
6355 static const char *const reasons
[] = {
6356 "<unknown reason code>",
6357 "Administratively prohibited",
6359 "Unknown channel type",
6360 "Resource shortage",
6362 unsigned i
= ssh_pkt_getuint32(pktin
);
6363 unsigned reason_code
;
6364 char *reason_string
;
6367 struct ssh_channel
*c
;
6368 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
6370 continue; /* nonexistent channel */
6371 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
6372 continue; /* dunno why they're failing this */
6374 reason_code
= ssh_pkt_getuint32(pktin
);
6375 if (reason_code
>= lenof(reasons
))
6376 reason_code
= 0; /* ensure reasons[reason_code] in range */
6377 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
6378 message
= dupprintf("Forwarded connection refused by"
6379 " server: %s [%.*s]", reasons
[reason_code
],
6380 reason_length
, reason_string
);
6384 pfd_close(c
->u
.pfd
.s
);
6386 del234(ssh
->channels
, c
);
6388 } else if (pktin
->type
== SSH2_MSG_CHANNEL_REQUEST
) {
6391 int typelen
, want_reply
;
6392 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
6393 struct ssh_channel
*c
;
6395 localid
= ssh_pkt_getuint32(pktin
);
6396 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6397 want_reply
= ssh2_pkt_getbool(pktin
);
6400 * First, check that the channel exists. Otherwise,
6401 * we can instantly disconnect with a rude message.
6403 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
6406 sprintf(buf
, "Received channel request for nonexistent"
6407 " channel %d", localid
);
6409 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
6410 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
6411 ssh2_pkt_addstring(s
->pktout
, buf
);
6412 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6413 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6414 connection_fatal(ssh
->frontend
, "%s", buf
);
6415 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6420 * Having got the channel number, we now look at
6421 * the request type string to see if it's something
6424 if (c
== ssh
->mainchan
) {
6426 * We recognise "exit-status" and "exit-signal" on
6427 * the primary channel.
6429 if (typelen
== 11 &&
6430 !memcmp(type
, "exit-status", 11)) {
6432 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
6433 logeventf(ssh
, "Server sent command exit status %d",
6435 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6437 } else if (typelen
== 11 &&
6438 !memcmp(type
, "exit-signal", 11)) {
6440 int is_plausible
= TRUE
, is_int
= FALSE
;
6441 char *fmt_sig
= "", *fmt_msg
= "";
6443 int msglen
= 0, core
= FALSE
;
6444 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6445 * provide an `int' for the signal, despite its
6446 * having been a `string' in the drafts since at
6447 * least 2001. (Fixed in session.c 1.147.) Try to
6448 * infer which we can safely parse it as. */
6450 unsigned char *p
= pktin
->body
+
6452 long len
= pktin
->length
- pktin
->savedpos
;
6453 unsigned long num
= GET_32BIT(p
); /* what is it? */
6454 /* If it's 0, it hardly matters; assume string */
6458 int maybe_int
= FALSE
, maybe_str
= FALSE
;
6459 #define CHECK_HYPOTHESIS(offset, result) \
6462 if (q >= 0 && q+4 <= len) { \
6463 q = q + 4 + GET_32BIT(p+q); \
6464 if (q >= 0 && q+4 <= len && \
6465 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
6469 CHECK_HYPOTHESIS(4+1, maybe_int
);
6470 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
6471 #undef CHECK_HYPOTHESIS
6472 if (maybe_int
&& !maybe_str
)
6474 else if (!maybe_int
&& maybe_str
)
6477 /* Crikey. Either or neither. Panic. */
6478 is_plausible
= FALSE
;
6483 /* Old non-standard OpenSSH. */
6484 int signum
= ssh_pkt_getuint32(pktin
);
6485 fmt_sig
= dupprintf(" %d", signum
);
6487 /* As per the drafts. */
6490 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
6491 /* Signal name isn't supposed to be blank, but
6492 * let's cope gracefully if it is. */
6494 fmt_sig
= dupprintf(" \"%.*s\"",
6498 core
= ssh2_pkt_getbool(pktin
);
6499 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
6501 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
6503 /* ignore lang tag */
6504 } /* else don't attempt to parse */
6505 logeventf(ssh
, "Server exited on signal%s%s%s",
6506 fmt_sig
, core ?
" (core dumped)" : "",
6508 if (*fmt_sig
) sfree(fmt_sig
);
6509 if (*fmt_msg
) sfree(fmt_msg
);
6510 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6515 * This is a channel request we don't know
6516 * about, so we now either ignore the request
6517 * or respond with CHANNEL_FAILURE, depending
6520 reply
= SSH2_MSG_CHANNEL_FAILURE
;
6523 s
->pktout
= ssh2_pkt_init(reply
);
6524 ssh2_pkt_adduint32(s
->pktout
, c
->remoteid
);
6525 ssh2_pkt_send(ssh
, s
->pktout
);
6527 } else if (pktin
->type
== SSH2_MSG_GLOBAL_REQUEST
) {
6529 int typelen
, want_reply
;
6531 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6532 want_reply
= ssh2_pkt_getbool(pktin
);
6535 * We currently don't support any global requests
6536 * at all, so we either ignore the request or
6537 * respond with REQUEST_FAILURE, depending on
6541 s
->pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
6542 ssh2_pkt_send(ssh
, s
->pktout
);
6544 } else if (pktin
->type
== SSH2_MSG_CHANNEL_OPEN
) {
6551 struct ssh_channel
*c
;
6552 unsigned remid
, winsize
, pktsize
;
6553 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6554 c
= snew(struct ssh_channel
);
6557 remid
= ssh_pkt_getuint32(pktin
);
6558 winsize
= ssh_pkt_getuint32(pktin
);
6559 pktsize
= ssh_pkt_getuint32(pktin
);
6561 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
6564 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6565 addrstr
= snewn(peeraddrlen
+1, char);
6566 memcpy(addrstr
, peeraddr
, peeraddrlen
);
6567 addrstr
[peeraddrlen
] = '\0';
6568 peerport
= ssh_pkt_getuint32(pktin
);
6570 logeventf(ssh
, "Received X11 connect request from %s:%d",
6573 if (!ssh
->X11_fwd_enabled
)
6574 error
= "X11 forwarding is not enabled";
6575 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
6576 ssh
->x11auth
, addrstr
, peerport
,
6577 &ssh
->cfg
) != NULL
) {
6578 error
= "Unable to open an X11 connection";
6580 logevent("Opening X11 forward connection succeeded");
6585 } else if (typelen
== 15 &&
6586 !memcmp(type
, "forwarded-tcpip", 15)) {
6587 struct ssh_rportfwd pf
, *realpf
;
6590 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
6591 pf
.sport
= ssh_pkt_getuint32(pktin
);
6592 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6593 peerport
= ssh_pkt_getuint32(pktin
);
6594 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
6595 logeventf(ssh
, "Received remote port %d open request "
6596 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
6597 if (realpf
== NULL
) {
6598 error
= "Remote port is not recognised";
6600 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
6604 logeventf(ssh
, "Attempting to forward remote port to "
6605 "%s:%d", realpf
->dhost
, realpf
->dport
);
6607 logeventf(ssh
, "Port open failed: %s", e
);
6608 error
= "Port open failed";
6610 logevent("Forwarded port opened successfully");
6611 c
->type
= CHAN_SOCKDATA
;
6614 } else if (typelen
== 22 &&
6615 !memcmp(type
, "auth-agent@openssh.com", 3)) {
6616 if (!ssh
->agentfwd_enabled
)
6617 error
= "Agent forwarding is not enabled";
6619 c
->type
= CHAN_AGENT
; /* identify channel type */
6620 c
->u
.a
.lensofar
= 0;
6623 error
= "Unsupported channel type requested";
6626 c
->remoteid
= remid
;
6628 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
6629 ssh2_pkt_adduint32(s
->pktout
, c
->remoteid
);
6630 ssh2_pkt_adduint32(s
->pktout
, SSH2_OPEN_CONNECT_FAILED
);
6631 ssh2_pkt_addstring(s
->pktout
, error
);
6632 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6633 ssh2_pkt_send(ssh
, s
->pktout
);
6634 logeventf(ssh
, "Rejected channel open: %s", error
);
6637 c
->localid
= alloc_channel_id(ssh
);
6639 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6640 c
->v
.v2
.remwindow
= winsize
;
6641 c
->v
.v2
.remmaxpkt
= pktsize
;
6642 bufchain_init(&c
->v
.v2
.outbuffer
);
6643 add234(ssh
->channels
, c
);
6644 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
6645 ssh2_pkt_adduint32(s
->pktout
, c
->remoteid
);
6646 ssh2_pkt_adduint32(s
->pktout
, c
->localid
);
6647 ssh2_pkt_adduint32(s
->pktout
, c
->v
.v2
.locwindow
);
6648 ssh2_pkt_adduint32(s
->pktout
, 0x4000UL
); /* our max pkt size */
6649 ssh2_pkt_send(ssh
, s
->pktout
);
6652 bombout(("Strange packet received: type %d", pktin
->type
));
6655 } else if (ssh
->mainchan
) {
6657 * We have spare data. Add it to the channel buffer.
6659 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
6664 struct ssh_channel
*c
;
6666 * Try to send data on all channels if we can.
6668 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
6671 continue; /* don't send on closing channels */
6672 bufsize
= ssh2_try_send(c
);
6675 case CHAN_MAINSESSION
:
6676 /* stdin need not receive an unthrottle
6677 * notification since it will be polled */
6680 x11_unthrottle(c
->u
.x11
.s
);
6683 /* agent sockets are request/response and need no
6684 * buffer management */
6687 pfd_unthrottle(c
->u
.pfd
.s
);
6699 * Handlers for SSH2 messages that might arrive at any moment.
6701 void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
6703 /* log reason code in disconnect message */
6705 int nowlen
, reason
, msglen
;
6707 reason
= ssh_pkt_getuint32(pktin
);
6708 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
6710 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
6711 buf
= dupprintf("Received disconnect message (%s)",
6712 ssh2_disconnect_reasons
[reason
]);
6714 buf
= dupprintf("Received disconnect message (unknown"
6715 " type %d)", reason
);
6719 buf
= dupprintf("Disconnection message text: %n%.*s",
6720 &nowlen
, msglen
, msg
);
6722 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
6724 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
6725 ssh2_disconnect_reasons
[reason
] : "unknown",
6730 void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
6732 /* log the debug message */
6737 /* XXX maybe we should actually take notice of this */
6738 always_display
= ssh2_pkt_getbool(pktin
);
6739 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
6741 buf
= dupprintf("Remote debug message: %.*s", msglen
, msg
);
6746 void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
6748 struct Packet
*pktout
;
6749 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
6750 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
6752 * UNIMPLEMENTED messages MUST appear in the same order as the
6753 * messages they respond to. Hence, never queue them.
6755 ssh2_pkt_send_noqueue(ssh
, pktout
);
6759 * Handle the top-level SSH2 protocol.
6761 static void ssh2_protocol_setup(Ssh ssh
)
6766 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
6768 for (i
= 0; i
< 256; i
++)
6769 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
6772 * Any message we actually understand, we set to NULL so that
6773 * the coroutines will get it.
6775 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
6776 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
6777 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
6778 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
6779 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
6780 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
6781 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
6782 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
6783 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
6784 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
6785 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
6786 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
6787 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
6788 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
6789 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
6790 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
6791 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
6792 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
6793 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
6794 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
6795 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
6796 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
6797 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
6798 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
6799 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
6800 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
6801 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
6802 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
6803 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
6804 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
6805 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
6806 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
6807 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
6810 * These special message types we install handlers for.
6812 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
6813 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with ssh1 */
6814 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
6817 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
,
6818 struct Packet
*pktin
)
6820 if (ssh
->state
== SSH_STATE_CLOSED
)
6823 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
6824 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
6828 if (!ssh
->protocol_initial_phase_done
||
6829 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
6830 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
6831 !ssh
->protocol_initial_phase_done
) {
6832 ssh
->protocol_initial_phase_done
= TRUE
;
6834 * Allow authconn to initialise itself.
6836 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
6839 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
6844 * Called to set up the connection.
6846 * Returns an error message, or NULL on success.
6848 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
6850 char *host
, int port
, char **realhost
, int nodelay
,
6856 ssh
= snew(struct ssh_tag
);
6857 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
6858 ssh
->version
= 0; /* when not ready yet */
6861 ssh
->v1_cipher_ctx
= NULL
;
6862 ssh
->crcda_ctx
= NULL
;
6863 ssh
->cscipher
= NULL
;
6864 ssh
->cs_cipher_ctx
= NULL
;
6865 ssh
->sccipher
= NULL
;
6866 ssh
->sc_cipher_ctx
= NULL
;
6868 ssh
->cs_mac_ctx
= NULL
;
6870 ssh
->sc_mac_ctx
= NULL
;
6872 ssh
->cs_comp_ctx
= NULL
;
6874 ssh
->sc_comp_ctx
= NULL
;
6876 ssh
->kex_ctx
= NULL
;
6877 ssh
->hostkey
= NULL
;
6879 ssh
->state
= SSH_STATE_PREPACKET
;
6880 ssh
->size_needed
= FALSE
;
6881 ssh
->eof_needed
= FALSE
;
6884 ssh
->deferred_send_data
= NULL
;
6885 ssh
->deferred_len
= 0;
6886 ssh
->deferred_size
= 0;
6887 ssh
->fallback_cmd
= 0;
6889 ssh
->x11auth
= NULL
;
6890 ssh
->v1_compressing
= FALSE
;
6891 ssh
->v2_outgoing_sequence
= 0;
6892 ssh
->ssh1_rdpkt_crstate
= 0;
6893 ssh
->ssh2_rdpkt_crstate
= 0;
6894 ssh
->do_ssh_init_crstate
= 0;
6895 ssh
->ssh_gotdata_crstate
= 0;
6896 ssh
->do_ssh1_connection_crstate
= 0;
6897 ssh
->do_ssh1_login_crstate
= 0;
6898 ssh
->do_ssh2_transport_crstate
= 0;
6899 ssh
->do_ssh2_authconn_crstate
= 0;
6900 ssh
->do_ssh_init_state
= NULL
;
6901 ssh
->do_ssh1_login_state
= NULL
;
6902 ssh
->do_ssh2_transport_state
= NULL
;
6903 ssh
->do_ssh2_authconn_state
= NULL
;
6904 ssh
->mainchan
= NULL
;
6905 ssh
->throttled_all
= 0;
6906 ssh
->v1_stdout_throttling
= 0;
6908 ssh
->queuelen
= ssh
->queuesize
= 0;
6909 ssh
->queueing
= FALSE
;
6911 *backend_handle
= ssh
;
6914 if (crypto_startup() == 0)
6915 return "Microsoft high encryption pack not installed!";
6918 ssh
->frontend
= frontend_handle
;
6919 ssh
->term_width
= ssh
->cfg
.width
;
6920 ssh
->term_height
= ssh
->cfg
.height
;
6922 ssh
->channels
= NULL
;
6923 ssh
->rportfwds
= NULL
;
6928 ssh
->v1_throttle_count
= 0;
6929 ssh
->overall_bufsize
= 0;
6930 ssh
->fallback_cmd
= 0;
6932 ssh
->protocol
= NULL
;
6934 ssh
->protocol_initial_phase_done
= FALSE
;
6936 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
6943 static void ssh_free(void *handle
)
6945 Ssh ssh
= (Ssh
) handle
;
6946 struct ssh_channel
*c
;
6947 struct ssh_rportfwd
*pf
;
6949 if (ssh
->v1_cipher_ctx
)
6950 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
6951 if (ssh
->cs_cipher_ctx
)
6952 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
6953 if (ssh
->sc_cipher_ctx
)
6954 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
6955 if (ssh
->cs_mac_ctx
)
6956 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
6957 if (ssh
->sc_mac_ctx
)
6958 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
6959 if (ssh
->cs_comp_ctx
) {
6961 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
6963 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
6965 if (ssh
->sc_comp_ctx
) {
6967 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
6969 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
6972 dh_cleanup(ssh
->kex_ctx
);
6973 sfree(ssh
->savedhost
);
6975 while (ssh
->queuelen
-- > 0)
6976 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
6979 if (ssh
->channels
) {
6980 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
6983 if (c
->u
.x11
.s
!= NULL
)
6984 x11_close(c
->u
.x11
.s
);
6987 if (c
->u
.pfd
.s
!= NULL
)
6988 pfd_close(c
->u
.pfd
.s
);
6993 freetree234(ssh
->channels
);
6996 if (ssh
->rportfwds
) {
6997 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
6999 freetree234(ssh
->rportfwds
);
7001 sfree(ssh
->deferred_send_data
);
7003 x11_free_auth(ssh
->x11auth
);
7004 sfree(ssh
->do_ssh_init_state
);
7005 sfree(ssh
->do_ssh1_login_state
);
7006 sfree(ssh
->do_ssh2_transport_state
);
7007 sfree(ssh
->do_ssh2_authconn_state
);
7008 if (ssh
->crcda_ctx
) {
7009 crcda_free_context(ssh
->crcda_ctx
);
7010 ssh
->crcda_ctx
= NULL
;
7018 * Reconfigure the SSH backend.
7020 * Currently, this function does nothing very useful. In future,
7021 * however, we could do some handy things with it. For example, we
7022 * could make the port forwarding configurer active in the Change
7023 * Settings box, and this routine could close down existing
7024 * forwardings and open up new ones in response to changes.
7026 static void ssh_reconfig(void *handle
, Config
*cfg
)
7028 Ssh ssh
= (Ssh
) handle
;
7029 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7033 * Called to send data down the Telnet connection.
7035 static int ssh_send(void *handle
, char *buf
, int len
)
7037 Ssh ssh
= (Ssh
) handle
;
7039 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7042 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
7044 return ssh_sendbuffer(ssh
);
7048 * Called to query the current amount of buffered stdin data.
7050 static int ssh_sendbuffer(void *handle
)
7052 Ssh ssh
= (Ssh
) handle
;
7055 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7059 * If the SSH socket itself has backed up, add the total backup
7060 * size on that to any individual buffer on the stdin channel.
7063 if (ssh
->throttled_all
)
7064 override_value
= ssh
->overall_bufsize
;
7066 if (ssh
->version
== 1) {
7067 return override_value
;
7068 } else if (ssh
->version
== 2) {
7069 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
7070 return override_value
;
7072 return (override_value
+
7073 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
7080 * Called to set the size of the window from SSH's POV.
7082 static void ssh_size(void *handle
, int width
, int height
)
7084 Ssh ssh
= (Ssh
) handle
;
7085 struct Packet
*pktout
;
7087 ssh
->term_width
= width
;
7088 ssh
->term_height
= height
;
7090 switch (ssh
->state
) {
7091 case SSH_STATE_BEFORE_SIZE
:
7092 case SSH_STATE_PREPACKET
:
7093 case SSH_STATE_CLOSED
:
7094 break; /* do nothing */
7095 case SSH_STATE_INTERMED
:
7096 ssh
->size_needed
= TRUE
; /* buffer for later */
7098 case SSH_STATE_SESSION
:
7099 if (!ssh
->cfg
.nopty
) {
7100 if (ssh
->version
== 1) {
7101 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
7102 PKT_INT
, ssh
->term_height
,
7103 PKT_INT
, ssh
->term_width
,
7104 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
7105 } else if (ssh
->mainchan
) {
7106 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7107 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7108 ssh2_pkt_addstring(pktout
, "window-change");
7109 ssh2_pkt_addbool(pktout
, 0);
7110 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
7111 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
7112 ssh2_pkt_adduint32(pktout
, 0);
7113 ssh2_pkt_adduint32(pktout
, 0);
7114 ssh2_pkt_send(ssh
, pktout
);
7122 * Return a list of the special codes that make sense in this
7125 static const struct telnet_special
*ssh_get_specials(void *handle
)
7127 static const struct telnet_special ignore_special
[] = {
7128 {"IGNORE message", TS_NOP
},
7130 static const struct telnet_special ssh2_session_specials
[] = {
7133 /* These are the signal names defined by draft-ietf-secsh-connect-19.
7134 * They include all the ISO C signals, but are a subset of the POSIX
7135 * required signals. */
7136 {"SIGINT (Interrupt)", TS_SIGINT
},
7137 {"SIGTERM (Terminate)", TS_SIGTERM
},
7138 {"SIGKILL (Kill)", TS_SIGKILL
},
7139 {"SIGQUIT (Quit)", TS_SIGQUIT
},
7140 {"SIGHUP (Hangup)", TS_SIGHUP
},
7141 {"More signals", TS_SUBMENU
},
7142 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
7143 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
7144 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
7145 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
7148 static const struct telnet_special specials_end
[] = {
7151 static struct telnet_special ssh_specials
[lenof(ignore_special
) +
7152 lenof(ssh2_session_specials
) +
7153 lenof(specials_end
)];
7154 Ssh ssh
= (Ssh
) handle
;
7156 #define ADD_SPECIALS(name) \
7158 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7159 memcpy(&ssh_specials[i], name, sizeof name); \
7163 if (ssh
->version
== 1) {
7164 /* Don't bother offering IGNORE if we've decided the remote
7165 * won't cope with it, since we wouldn't bother sending it if
7167 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
7168 ADD_SPECIALS(ignore_special
);
7169 } else if (ssh
->version
== 2) {
7170 /* XXX add rekey, when implemented */
7171 ADD_SPECIALS(ignore_special
);
7173 ADD_SPECIALS(ssh2_session_specials
);
7174 } /* else we're not ready yet */
7177 ADD_SPECIALS(specials_end
);
7178 return ssh_specials
;
7186 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7187 * can send an EOF and collect resulting output (e.g. `plink
7190 static void ssh_special(void *handle
, Telnet_Special code
)
7192 Ssh ssh
= (Ssh
) handle
;
7193 struct Packet
*pktout
;
7195 if (code
== TS_EOF
) {
7196 if (ssh
->state
!= SSH_STATE_SESSION
) {
7198 * Buffer the EOF in case we are pre-SESSION, so we can
7199 * send it as soon as we reach SESSION.
7202 ssh
->eof_needed
= TRUE
;
7205 if (ssh
->version
== 1) {
7206 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
7207 } else if (ssh
->mainchan
) {
7208 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
7209 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7210 ssh2_pkt_send(ssh
, pktout
);
7212 logevent("Sent EOF message");
7213 } else if (code
== TS_PING
|| code
== TS_NOP
) {
7214 if (ssh
->state
== SSH_STATE_CLOSED
7215 || ssh
->state
== SSH_STATE_PREPACKET
) return;
7216 if (ssh
->version
== 1) {
7217 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
7218 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
7220 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
7221 ssh2_pkt_addstring_start(pktout
);
7222 ssh2_pkt_send_noqueue(ssh
, pktout
);
7224 } else if (code
== TS_BRK
) {
7225 if (ssh
->state
== SSH_STATE_CLOSED
7226 || ssh
->state
== SSH_STATE_PREPACKET
) return;
7227 if (ssh
->version
== 1) {
7228 logevent("Unable to send BREAK signal in SSH1");
7229 } else if (ssh
->mainchan
) {
7230 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7231 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7232 ssh2_pkt_addstring(pktout
, "break");
7233 ssh2_pkt_addbool(pktout
, 0);
7234 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
7235 ssh2_pkt_send(ssh
, pktout
);
7238 /* Is is a POSIX signal? */
7239 char *signame
= NULL
;
7240 if (code
== TS_SIGABRT
) signame
= "ABRT";
7241 if (code
== TS_SIGALRM
) signame
= "ALRM";
7242 if (code
== TS_SIGFPE
) signame
= "FPE";
7243 if (code
== TS_SIGHUP
) signame
= "HUP";
7244 if (code
== TS_SIGILL
) signame
= "ILL";
7245 if (code
== TS_SIGINT
) signame
= "INT";
7246 if (code
== TS_SIGKILL
) signame
= "KILL";
7247 if (code
== TS_SIGPIPE
) signame
= "PIPE";
7248 if (code
== TS_SIGQUIT
) signame
= "QUIT";
7249 if (code
== TS_SIGSEGV
) signame
= "SEGV";
7250 if (code
== TS_SIGTERM
) signame
= "TERM";
7251 if (code
== TS_SIGUSR1
) signame
= "USR1";
7252 if (code
== TS_SIGUSR2
) signame
= "USR2";
7253 /* The SSH-2 protocol does in principle support arbitrary named
7254 * signals, including signame@domain, but we don't support those. */
7256 /* It's a signal. */
7257 if (ssh
->version
== 2 && ssh
->mainchan
) {
7258 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7259 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7260 ssh2_pkt_addstring(pktout
, "signal");
7261 ssh2_pkt_addbool(pktout
, 0);
7262 ssh2_pkt_addstring(pktout
, signame
);
7263 ssh2_pkt_send(ssh
, pktout
);
7264 logeventf(ssh
, "Sent signal SIG%s", signame
);
7267 /* Never heard of it. Do nothing */
7272 void *new_sock_channel(void *handle
, Socket s
)
7274 Ssh ssh
= (Ssh
) handle
;
7275 struct ssh_channel
*c
;
7276 c
= snew(struct ssh_channel
);
7280 c
->remoteid
= -1; /* to be set when open confirmed */
7281 c
->localid
= alloc_channel_id(ssh
);
7283 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
7285 bufchain_init(&c
->v
.v2
.outbuffer
);
7286 add234(ssh
->channels
, c
);
7292 * This is called when stdout/stderr (the entity to which
7293 * from_backend sends data) manages to clear some backlog.
7295 static void ssh_unthrottle(void *handle
, int bufsize
)
7297 Ssh ssh
= (Ssh
) handle
;
7298 if (ssh
->version
== 1) {
7299 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
7300 ssh
->v1_stdout_throttling
= 0;
7301 ssh1_throttle(ssh
, -1);
7304 if (ssh
->mainchan
&& ssh
->mainchan
->closes
== 0)
7305 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
7309 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
7311 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
7313 struct Packet
*pktout
;
7315 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
7317 if (ssh
->version
== 1) {
7318 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
7319 PKT_INT
, c
->localid
,
7322 //PKT_STR, <org:orgport>,
7325 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
7326 ssh2_pkt_addstring(pktout
, "direct-tcpip");
7327 ssh2_pkt_adduint32(pktout
, c
->localid
);
7328 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
7329 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
7330 ssh2_pkt_adduint32(pktout
, 0x4000UL
); /* our max pkt size */
7331 ssh2_pkt_addstring(pktout
, hostname
);
7332 ssh2_pkt_adduint32(pktout
, port
);
7334 * We make up values for the originator data; partly it's
7335 * too much hassle to keep track, and partly I'm not
7336 * convinced the server should be told details like that
7337 * about my local network configuration.
7339 ssh2_pkt_addstring(pktout
, "client-side-connection");
7340 ssh2_pkt_adduint32(pktout
, 0);
7341 ssh2_pkt_send(ssh
, pktout
);
7345 static Socket
ssh_socket(void *handle
)
7347 Ssh ssh
= (Ssh
) handle
;
7351 static int ssh_sendok(void *handle
)
7353 Ssh ssh
= (Ssh
) handle
;
7354 return ssh
->send_ok
;
7357 static int ssh_ldisc(void *handle
, int option
)
7359 Ssh ssh
= (Ssh
) handle
;
7360 if (option
== LD_ECHO
)
7361 return ssh
->echoing
;
7362 if (option
== LD_EDIT
)
7363 return ssh
->editing
;
7367 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
7369 Ssh ssh
= (Ssh
) handle
;
7373 static void ssh_provide_logctx(void *handle
, void *logctx
)
7375 Ssh ssh
= (Ssh
) handle
;
7376 ssh
->logctx
= logctx
;
7379 static int ssh_return_exitcode(void *handle
)
7381 Ssh ssh
= (Ssh
) handle
;
7385 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: 0);
7389 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7390 * that fails. This variable is the means by which scp.c can reach
7391 * into the SSH code and find out which one it got.
7393 extern int ssh_fallback_cmd(void *handle
)
7395 Ssh ssh
= (Ssh
) handle
;
7396 return ssh
->fallback_cmd
;
7399 Backend ssh_backend
= {
7409 ssh_return_exitcode
,