17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_KEX_MASK 0x000F
110 #define SSH2_PKTCTX_PUBLICKEY 0x0010
111 #define SSH2_PKTCTX_PASSWORD 0x0020
112 #define SSH2_PKTCTX_KBDINTER 0x0040
113 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons
[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
162 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
163 #define BUG_CHOKES_ON_RSA 8
164 #define BUG_SSH2_RSA_PADDING 16
165 #define BUG_SSH2_DERIVEKEY 32
166 #define BUG_SSH2_REKEY 64
167 #define BUG_SSH2_PK_SESSIONID 128
169 #define translate(x) if (type == x) return #x
170 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
171 static char *ssh1_pkt_type(int type
)
173 translate(SSH1_MSG_DISCONNECT
);
174 translate(SSH1_SMSG_PUBLIC_KEY
);
175 translate(SSH1_CMSG_SESSION_KEY
);
176 translate(SSH1_CMSG_USER
);
177 translate(SSH1_CMSG_AUTH_RSA
);
178 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
179 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
180 translate(SSH1_CMSG_AUTH_PASSWORD
);
181 translate(SSH1_CMSG_REQUEST_PTY
);
182 translate(SSH1_CMSG_WINDOW_SIZE
);
183 translate(SSH1_CMSG_EXEC_SHELL
);
184 translate(SSH1_CMSG_EXEC_CMD
);
185 translate(SSH1_SMSG_SUCCESS
);
186 translate(SSH1_SMSG_FAILURE
);
187 translate(SSH1_CMSG_STDIN_DATA
);
188 translate(SSH1_SMSG_STDOUT_DATA
);
189 translate(SSH1_SMSG_STDERR_DATA
);
190 translate(SSH1_CMSG_EOF
);
191 translate(SSH1_SMSG_EXIT_STATUS
);
192 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
193 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
194 translate(SSH1_MSG_CHANNEL_DATA
);
195 translate(SSH1_MSG_CHANNEL_CLOSE
);
196 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
197 translate(SSH1_SMSG_X11_OPEN
);
198 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
199 translate(SSH1_MSG_PORT_OPEN
);
200 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
201 translate(SSH1_SMSG_AGENT_OPEN
);
202 translate(SSH1_MSG_IGNORE
);
203 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
204 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
205 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
206 translate(SSH1_MSG_DEBUG
);
207 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
208 translate(SSH1_CMSG_AUTH_TIS
);
209 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
210 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
211 translate(SSH1_CMSG_AUTH_CCARD
);
212 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
213 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
216 static char *ssh2_pkt_type(int pkt_ctx
, int type
)
218 translate(SSH2_MSG_DISCONNECT
);
219 translate(SSH2_MSG_IGNORE
);
220 translate(SSH2_MSG_UNIMPLEMENTED
);
221 translate(SSH2_MSG_DEBUG
);
222 translate(SSH2_MSG_SERVICE_REQUEST
);
223 translate(SSH2_MSG_SERVICE_ACCEPT
);
224 translate(SSH2_MSG_KEXINIT
);
225 translate(SSH2_MSG_NEWKEYS
);
226 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP
);
227 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP
);
228 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
229 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
230 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
231 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
232 translate(SSH2_MSG_USERAUTH_REQUEST
);
233 translate(SSH2_MSG_USERAUTH_FAILURE
);
234 translate(SSH2_MSG_USERAUTH_SUCCESS
);
235 translate(SSH2_MSG_USERAUTH_BANNER
);
236 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
237 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
238 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
239 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
240 translate(SSH2_MSG_GLOBAL_REQUEST
);
241 translate(SSH2_MSG_REQUEST_SUCCESS
);
242 translate(SSH2_MSG_REQUEST_FAILURE
);
243 translate(SSH2_MSG_CHANNEL_OPEN
);
244 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
245 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
246 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
247 translate(SSH2_MSG_CHANNEL_DATA
);
248 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
249 translate(SSH2_MSG_CHANNEL_EOF
);
250 translate(SSH2_MSG_CHANNEL_CLOSE
);
251 translate(SSH2_MSG_CHANNEL_REQUEST
);
252 translate(SSH2_MSG_CHANNEL_SUCCESS
);
253 translate(SSH2_MSG_CHANNEL_FAILURE
);
259 /* Enumeration values for fields in SSH-1 packets */
261 PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
,
262 /* These values are for communicating relevant semantics of
263 * fields to the packet logging code. */
264 PKTT_OTHER
, PKTT_PASSWORD
, PKTT_DATA
268 * Coroutine mechanics for the sillier bits of the code. If these
269 * macros look impenetrable to you, you might find it helpful to
272 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
274 * which explains the theory behind these macros.
276 * In particular, if you are getting `case expression not constant'
277 * errors when building with MS Visual Studio, this is because MS's
278 * Edit and Continue debugging feature causes their compiler to
279 * violate ANSI C. To disable Edit and Continue debugging:
281 * - right-click ssh.c in the FileView
283 * - select the C/C++ tab and the General category
284 * - under `Debug info:', select anything _other_ than `Program
285 * Database for Edit and Continue'.
287 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
290 if (!ssh->t) ssh->t = snew(struct t); \
292 #define crFinish(z) } *crLine = 0; return (z); }
293 #define crFinishV } *crLine = 0; return; }
294 #define crReturn(z) \
296 *crLine =__LINE__; return (z); case __LINE__:;\
300 *crLine=__LINE__; return; case __LINE__:;\
302 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
303 #define crStopV do{ *crLine = 0; return; }while(0)
304 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
305 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
307 typedef struct ssh_tag
*Ssh
;
310 static struct Packet
*ssh1_pkt_init(int pkt_type
);
311 static struct Packet
*ssh2_pkt_init(int pkt_type
);
312 static void ssh_pkt_ensure(struct Packet
*, int length
);
313 static void ssh_pkt_adddata(struct Packet
*, void *data
, int len
);
314 static void ssh_pkt_addbyte(struct Packet
*, unsigned char value
);
315 static void ssh2_pkt_addbool(struct Packet
*, unsigned char value
);
316 static void ssh_pkt_adduint32(struct Packet
*, unsigned long value
);
317 static void ssh_pkt_addstring_start(struct Packet
*);
318 static void ssh_pkt_addstring_str(struct Packet
*, char *data
);
319 static void ssh_pkt_addstring_data(struct Packet
*, char *data
, int len
);
320 static void ssh_pkt_addstring(struct Packet
*, char *data
);
321 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
322 static void ssh1_pkt_addmp(struct Packet
*, Bignum b
);
323 static void ssh2_pkt_addmp(struct Packet
*, Bignum b
);
324 static int ssh2_pkt_construct(Ssh
, struct Packet
*);
325 static void ssh2_pkt_send(Ssh
, struct Packet
*);
326 static void ssh2_pkt_send_noqueue(Ssh
, struct Packet
*);
327 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
328 struct Packet
*pktin
);
329 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
330 struct Packet
*pktin
);
333 * Buffer management constants. There are several of these for
334 * various different purposes:
336 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
337 * on a local data stream before we throttle the whole SSH
338 * connection (in SSH-1 only). Throttling the whole connection is
339 * pretty drastic so we set this high in the hope it won't
342 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
343 * on the SSH connection itself before we defensively throttle
344 * _all_ local data streams. This is pretty drastic too (though
345 * thankfully unlikely in SSH-2 since the window mechanism should
346 * ensure that the server never has any need to throttle its end
347 * of the connection), so we set this high as well.
349 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
353 #define SSH1_BUFFER_LIMIT 32768
354 #define SSH_MAX_BACKLOG 32768
355 #define OUR_V2_WINSIZE 16384
356 #define OUR_V2_MAXPKT 0x4000UL
358 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
360 static void *nullmac_make_context(void)
364 static void nullmac_free_context(void *handle
)
367 static void nullmac_key(void *handle
, unsigned char *key
)
370 static void nullmac_generate(void *handle
, unsigned char *blk
, int len
,
374 static int nullmac_verify(void *handle
, unsigned char *blk
, int len
,
379 const static struct ssh_mac ssh_mac_none
= {
380 nullmac_make_context
, nullmac_free_context
, nullmac_key
,
381 nullmac_generate
, nullmac_verify
, "none", 0
383 const static struct ssh_mac
*macs
[] = {
384 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
386 const static struct ssh_mac
*buggymacs
[] = {
387 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
390 static void *ssh_comp_none_init(void)
394 static void ssh_comp_none_cleanup(void *handle
)
397 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
398 unsigned char **outblock
, int *outlen
)
402 static int ssh_comp_none_disable(void *handle
)
406 const static struct ssh_compress ssh_comp_none
= {
408 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
409 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
410 ssh_comp_none_disable
, NULL
412 extern const struct ssh_compress ssh_zlib
;
413 const static struct ssh_compress
*compressions
[] = {
414 &ssh_zlib
, &ssh_comp_none
417 enum { /* channel types */
422 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
426 * 2-3-4 tree storing channels.
429 Ssh ssh
; /* pointer back to main context */
430 unsigned remoteid
, localid
;
432 /* True if we opened this channel but server hasn't confirmed. */
435 * In SSH-1, this value contains four bits:
437 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
438 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
439 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
440 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
442 * A channel is completely finished with when all four bits are set.
446 struct ssh1_data_channel
{
449 struct ssh2_data_channel
{
451 unsigned remwindow
, remmaxpkt
;
456 struct ssh_agent_channel
{
457 unsigned char *message
;
458 unsigned char msglen
[4];
459 unsigned lensofar
, totallen
;
461 struct ssh_x11_channel
{
464 struct ssh_pfd_channel
{
471 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
472 * use this structure in different ways, reflecting SSH-2's
473 * altogether saner approach to port forwarding.
475 * In SSH-1, you arrange a remote forwarding by sending the server
476 * the remote port number, and the local destination host:port.
477 * When a connection comes in, the server sends you back that
478 * host:port pair, and you connect to it. This is a ready-made
479 * security hole if you're not on the ball: a malicious server
480 * could send you back _any_ host:port pair, so if you trustingly
481 * connect to the address it gives you then you've just opened the
482 * entire inside of your corporate network just by connecting
483 * through it to a dodgy SSH server. Hence, we must store a list of
484 * host:port pairs we _are_ trying to forward to, and reject a
485 * connection request from the server if it's not in the list.
487 * In SSH-2, each side of the connection minds its own business and
488 * doesn't send unnecessary information to the other. You arrange a
489 * remote forwarding by sending the server just the remote port
490 * number. When a connection comes in, the server tells you which
491 * of its ports was connected to; and _you_ have to remember what
492 * local host:port pair went with that port number.
494 * Hence, in SSH-1 this structure is indexed by destination
495 * host:port pair, whereas in SSH-2 it is indexed by source port.
497 struct ssh_portfwd
; /* forward declaration */
499 struct ssh_rportfwd
{
500 unsigned sport
, dport
;
503 struct ssh_portfwd
*pfrec
;
505 #define free_rportfwd(pf) ( \
506 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
509 * Separately to the rportfwd tree (which is for looking up port
510 * open requests from the server), a tree of _these_ structures is
511 * used to keep track of all the currently open port forwardings,
512 * so that we can reconfigure in mid-session if the user requests
516 enum { DESTROY
, KEEP
, CREATE
} status
;
518 unsigned sport
, dport
;
521 struct ssh_rportfwd
*remote
;
525 #define free_portfwd(pf) ( \
526 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
527 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
530 long length
; /* length of `data' actually used */
531 long forcepad
; /* SSH-2: force padding to at least this length */
532 int type
; /* only used for incoming packets */
533 unsigned long sequence
; /* SSH-2 incoming sequence number */
534 unsigned char *data
; /* allocated storage */
535 unsigned char *body
; /* offset of payload within `data' */
536 long savedpos
; /* temporary index into `data' (for strings) */
537 long maxlen
; /* amount of storage allocated for `data' */
538 long encrypted_len
; /* for SSH-2 total-size counting */
541 * State associated with packet logging
545 struct logblank_t
*blanks
;
548 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
549 struct Packet
*pktin
);
550 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
551 struct Packet
*pktin
);
552 static void ssh1_protocol_setup(Ssh ssh
);
553 static void ssh2_protocol_setup(Ssh ssh
);
554 static void ssh_size(void *handle
, int width
, int height
);
555 static void ssh_special(void *handle
, Telnet_Special
);
556 static int ssh2_try_send(struct ssh_channel
*c
);
557 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
558 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
559 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
560 static int ssh_sendbuffer(void *handle
);
561 static int ssh_do_close(Ssh ssh
, int notify_exit
);
562 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
563 static int ssh2_pkt_getbool(struct Packet
*pkt
);
564 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
565 static void ssh2_timer(void *ctx
, long now
);
566 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
567 struct Packet
*pktin
);
569 struct rdpkt1_state_tag
{
570 long len
, pad
, biglen
, to_read
;
571 unsigned long realcrc
, gotcrc
;
575 struct Packet
*pktin
;
578 struct rdpkt2_state_tag
{
579 long len
, pad
, payload
, packetlen
, maclen
;
582 unsigned long incoming_sequence
;
583 struct Packet
*pktin
;
586 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
587 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
589 struct queued_handler
;
590 struct queued_handler
{
592 chandler_fn_t handler
;
594 struct queued_handler
*next
;
598 const struct plug_function_table
*fn
;
599 /* the above field _must_ be first in the structure */
601 SHA_State exhash
, exhashbase
;
608 unsigned char session_key
[32];
610 int v1_remote_protoflags
;
611 int v1_local_protoflags
;
612 int agentfwd_enabled
;
615 const struct ssh_cipher
*cipher
;
618 const struct ssh2_cipher
*cscipher
, *sccipher
;
619 void *cs_cipher_ctx
, *sc_cipher_ctx
;
620 const struct ssh_mac
*csmac
, *scmac
;
621 void *cs_mac_ctx
, *sc_mac_ctx
;
622 const struct ssh_compress
*cscomp
, *sccomp
;
623 void *cs_comp_ctx
, *sc_comp_ctx
;
624 const struct ssh_kex
*kex
;
625 const struct ssh_signkey
*hostkey
;
626 unsigned char v2_session_id
[20];
632 int echoing
, editing
;
636 int ospeed
, ispeed
; /* temporaries */
637 int term_width
, term_height
;
639 tree234
*channels
; /* indexed by local id */
640 struct ssh_channel
*mainchan
; /* primary session channel */
644 tree234
*rportfwds
, *portfwds
;
648 SSH_STATE_BEFORE_SIZE
,
654 int size_needed
, eof_needed
;
656 struct Packet
**queue
;
657 int queuelen
, queuesize
;
659 unsigned char *deferred_send_data
;
660 int deferred_len
, deferred_size
;
663 * Gross hack: pscp will try to start SFTP but fall back to
664 * scp1 if that fails. This variable is the means by which
665 * scp.c can reach into the SSH code and find out which one it
671 * Used for username and password input.
673 char *userpass_input_buffer
;
674 int userpass_input_buflen
;
675 int userpass_input_bufpos
;
676 int userpass_input_echo
;
683 int v1_throttle_count
;
686 int v1_stdout_throttling
;
687 unsigned long v2_outgoing_sequence
;
689 int ssh1_rdpkt_crstate
;
690 int ssh2_rdpkt_crstate
;
691 int do_ssh_init_crstate
;
692 int ssh_gotdata_crstate
;
693 int do_ssh1_login_crstate
;
694 int do_ssh1_connection_crstate
;
695 int do_ssh2_transport_crstate
;
696 int do_ssh2_authconn_crstate
;
698 void *do_ssh_init_state
;
699 void *do_ssh1_login_state
;
700 void *do_ssh2_transport_state
;
701 void *do_ssh2_authconn_state
;
703 struct rdpkt1_state_tag rdpkt1_state
;
704 struct rdpkt2_state_tag rdpkt2_state
;
706 /* SSH-1 and SSH-2 use this for different things, but both use it */
707 int protocol_initial_phase_done
;
709 void (*protocol
) (Ssh ssh
, void *vin
, int inlen
,
711 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
714 * We maintain a full _copy_ of a Config structure here, not
715 * merely a pointer to it. That way, when we're passed a new
716 * one for reconfiguration, we can check the differences and
717 * potentially reconfigure port forwardings etc in mid-session.
722 * Used to transfer data back from async callbacks.
724 void *agent_response
;
725 int agent_response_len
;
729 * The SSH connection can be set as `frozen', meaning we are
730 * not currently accepting incoming data from the network. This
731 * is slightly more serious than setting the _socket_ as
732 * frozen, because we may already have had data passed to us
733 * from the network which we need to delay processing until
734 * after the freeze is lifted, so we also need a bufchain to
738 bufchain queued_incoming_data
;
741 * Dispatch table for packet types that we may have to deal
744 handler_fn_t packet_dispatch
[256];
747 * Queues of one-off handler functions for success/failure
748 * indications from a request.
750 struct queued_handler
*qhead
, *qtail
;
753 * This module deals with sending keepalives.
758 * Track incoming and outgoing data sizes and time, for
761 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
762 unsigned long max_data_size
;
764 long next_rekey
, last_rekey
;
765 char *deferred_rekey_reason
; /* points to STATIC string; don't free */
768 #define logevent(s) logevent(ssh->frontend, s)
770 /* logevent, only printf-formatted. */
771 static void logeventf(Ssh ssh
, const char *fmt
, ...)
777 buf
= dupvprintf(fmt
, ap
);
783 #define bombout(msg) \
785 char *text = dupprintf msg; \
786 ssh_do_close(ssh, FALSE); \
788 connection_fatal(ssh->frontend, "%s", text); \
792 /* Functions to leave bits out of the SSH packet log file. */
794 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
796 if (ssh
->cfg
.logomitpass
)
797 pkt
->logmode
= blanktype
;
800 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
802 if (ssh
->cfg
.logomitdata
)
803 pkt
->logmode
= blanktype
;
806 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
808 pkt
->logmode
= PKTLOG_EMIT
;
811 static int ssh_channelcmp(void *av
, void *bv
)
813 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
814 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
815 if (a
->localid
< b
->localid
)
817 if (a
->localid
> b
->localid
)
821 static int ssh_channelfind(void *av
, void *bv
)
823 unsigned *a
= (unsigned *) av
;
824 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
832 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
834 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
835 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
837 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
838 return i
< 0 ?
-1 : +1;
839 if (a
->dport
> b
->dport
)
841 if (a
->dport
< b
->dport
)
846 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
848 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
849 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
851 if (a
->sport
> b
->sport
)
853 if (a
->sport
< b
->sport
)
859 * Special form of strcmp which can cope with NULL inputs. NULL is
860 * defined to sort before even the empty string.
862 static int nullstrcmp(const char *a
, const char *b
)
864 if (a
== NULL
&& b
== NULL
)
873 static int ssh_portcmp(void *av
, void *bv
)
875 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
876 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
878 if (a
->type
> b
->type
)
880 if (a
->type
< b
->type
)
882 if (a
->addressfamily
> b
->addressfamily
)
884 if (a
->addressfamily
< b
->addressfamily
)
886 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
887 return i
< 0 ?
-1 : +1;
888 if (a
->sport
> b
->sport
)
890 if (a
->sport
< b
->sport
)
892 if (a
->type
!= 'D') {
893 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
894 return i
< 0 ?
-1 : +1;
895 if (a
->dport
> b
->dport
)
897 if (a
->dport
< b
->dport
)
903 static int alloc_channel_id(Ssh ssh
)
905 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
906 unsigned low
, high
, mid
;
908 struct ssh_channel
*c
;
911 * First-fit allocation of channel numbers: always pick the
912 * lowest unused one. To do this, binary-search using the
913 * counted B-tree to find the largest channel ID which is in a
914 * contiguous sequence from the beginning. (Precisely
915 * everything in that sequence must have ID equal to its tree
916 * index plus CHANNEL_NUMBER_OFFSET.)
918 tsize
= count234(ssh
->channels
);
922 while (high
- low
> 1) {
923 mid
= (high
+ low
) / 2;
924 c
= index234(ssh
->channels
, mid
);
925 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
926 low
= mid
; /* this one is fine */
928 high
= mid
; /* this one is past it */
931 * Now low points to either -1, or the tree index of the
932 * largest ID in the initial sequence.
935 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
936 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
938 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
941 static void c_write(Ssh ssh
, const char *buf
, int len
)
943 if ((flags
& FLAG_STDERR
)) {
945 for (i
= 0; i
< len
; i
++)
947 fputc(buf
[i
], stderr
);
950 from_backend(ssh
->frontend
, 1, buf
, len
);
953 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
956 for (i
= 0; i
< len
; i
++) {
958 c_write(ssh
, "\r\n", 2);
959 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
960 c_write(ssh
, buf
+ i
, 1);
964 static void c_write_str(Ssh ssh
, const char *buf
)
966 c_write(ssh
, buf
, strlen(buf
));
969 static void ssh_free_packet(struct Packet
*pkt
)
974 static struct Packet
*ssh_new_packet(void)
976 struct Packet
*pkt
= snew(struct Packet
);
978 pkt
->body
= pkt
->data
= NULL
;
980 pkt
->logmode
= PKTLOG_EMIT
;
988 * Collect incoming data in the incoming packet buffer.
989 * Decipher and verify the packet when it is completely read.
990 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
991 * Update the *data and *datalen variables.
992 * Return a Packet structure when a packet is completed.
994 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
996 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
998 crBegin(ssh
->ssh1_rdpkt_crstate
);
1000 st
->pktin
= ssh_new_packet();
1002 st
->pktin
->type
= 0;
1003 st
->pktin
->length
= 0;
1005 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
1006 while ((*datalen
) == 0)
1008 st
->len
= (st
->len
<< 8) + **data
;
1009 (*data
)++, (*datalen
)--;
1012 st
->pad
= 8 - (st
->len
% 8);
1013 st
->biglen
= st
->len
+ st
->pad
;
1014 st
->pktin
->length
= st
->len
- 5;
1016 if (st
->biglen
< 0) {
1017 bombout(("Extremely large packet length from server suggests"
1018 " data stream corruption"));
1019 ssh_free_packet(st
->pktin
);
1023 st
->pktin
->maxlen
= st
->biglen
;
1024 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1026 st
->to_read
= st
->biglen
;
1027 st
->p
= st
->pktin
->data
;
1028 while (st
->to_read
> 0) {
1029 st
->chunk
= st
->to_read
;
1030 while ((*datalen
) == 0)
1032 if (st
->chunk
> (*datalen
))
1033 st
->chunk
= (*datalen
);
1034 memcpy(st
->p
, *data
, st
->chunk
);
1036 *datalen
-= st
->chunk
;
1038 st
->to_read
-= st
->chunk
;
1041 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1042 st
->biglen
, NULL
)) {
1043 bombout(("Network attack (CRC compensation) detected!"));
1044 ssh_free_packet(st
->pktin
);
1049 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1051 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1052 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1053 if (st
->gotcrc
!= st
->realcrc
) {
1054 bombout(("Incorrect CRC received on packet"));
1055 ssh_free_packet(st
->pktin
);
1059 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1060 st
->pktin
->savedpos
= 0;
1062 if (ssh
->v1_compressing
) {
1063 unsigned char *decompblk
;
1065 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1066 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1067 &decompblk
, &decomplen
)) {
1068 bombout(("Zlib decompression encountered invalid data"));
1069 ssh_free_packet(st
->pktin
);
1073 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1074 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1075 st
->pktin
->data
= sresize(st
->pktin
->data
,
1076 st
->pktin
->maxlen
+ APIEXTRA
,
1078 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1081 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1083 st
->pktin
->length
= decomplen
- 1;
1086 st
->pktin
->type
= st
->pktin
->body
[-1];
1089 * Log incoming packet, possibly omitting sensitive fields.
1093 struct logblank_t blank
;
1094 if (ssh
->cfg
.logomitdata
) {
1095 int do_blank
= FALSE
, blank_prefix
= 0;
1096 /* "Session data" packets - omit the data field */
1097 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1098 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1099 do_blank
= TRUE
; blank_prefix
= 0;
1100 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1101 do_blank
= TRUE
; blank_prefix
= 4;
1104 blank
.offset
= blank_prefix
;
1105 blank
.len
= st
->pktin
->length
;
1106 blank
.type
= PKTLOG_OMIT
;
1110 log_packet(ssh
->logctx
,
1111 PKT_INCOMING
, st
->pktin
->type
,
1112 ssh1_pkt_type(st
->pktin
->type
),
1113 st
->pktin
->body
, st
->pktin
->length
,
1117 crFinish(st
->pktin
);
1120 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1122 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1124 crBegin(ssh
->ssh2_rdpkt_crstate
);
1126 st
->pktin
= ssh_new_packet();
1128 st
->pktin
->type
= 0;
1129 st
->pktin
->length
= 0;
1131 st
->cipherblk
= ssh
->sccipher
->blksize
;
1134 if (st
->cipherblk
< 8)
1137 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1140 * Acquire and decrypt the first block of the packet. This will
1141 * contain the length and padding details.
1143 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1144 while ((*datalen
) == 0)
1146 st
->pktin
->data
[st
->i
] = *(*data
)++;
1151 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1152 st
->pktin
->data
, st
->cipherblk
);
1155 * Now get the length and padding figures.
1157 st
->len
= GET_32BIT(st
->pktin
->data
);
1158 st
->pad
= st
->pktin
->data
[4];
1161 * _Completely_ silly lengths should be stomped on before they
1162 * do us any more damage.
1164 if (st
->len
< 0 || st
->pad
< 0 || st
->len
+ st
->pad
< 0) {
1165 bombout(("Incoming packet was garbled on decryption"));
1166 ssh_free_packet(st
->pktin
);
1171 * This enables us to deduce the payload length.
1173 st
->payload
= st
->len
- st
->pad
- 1;
1175 st
->pktin
->length
= st
->payload
+ 5;
1178 * So now we can work out the total packet length.
1180 st
->packetlen
= st
->len
+ 4;
1181 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1184 * Allocate memory for the rest of the packet.
1186 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1187 st
->pktin
->data
= sresize(st
->pktin
->data
,
1188 st
->pktin
->maxlen
+ APIEXTRA
,
1192 * Read and decrypt the remainder of the packet.
1194 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1196 while ((*datalen
) == 0)
1198 st
->pktin
->data
[st
->i
] = *(*data
)++;
1201 /* Decrypt everything _except_ the MAC. */
1203 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1204 st
->pktin
->data
+ st
->cipherblk
,
1205 st
->packetlen
- st
->cipherblk
);
1207 st
->pktin
->encrypted_len
= st
->packetlen
;
1213 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
, st
->len
+ 4,
1214 st
->incoming_sequence
)) {
1215 bombout(("Incorrect MAC received on packet"));
1216 ssh_free_packet(st
->pktin
);
1220 st
->pktin
->sequence
= st
->incoming_sequence
++;
1223 * Decompress packet payload.
1226 unsigned char *newpayload
;
1229 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1230 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1231 &newpayload
, &newlen
)) {
1232 if (st
->pktin
->maxlen
< newlen
+ 5) {
1233 st
->pktin
->maxlen
= newlen
+ 5;
1234 st
->pktin
->data
= sresize(st
->pktin
->data
,
1235 st
->pktin
->maxlen
+ APIEXTRA
,
1238 st
->pktin
->length
= 5 + newlen
;
1239 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1244 st
->pktin
->savedpos
= 6;
1245 st
->pktin
->body
= st
->pktin
->data
;
1246 st
->pktin
->type
= st
->pktin
->data
[5];
1249 * Log incoming packet, possibly omitting sensitive fields.
1253 struct logblank_t blank
;
1254 if (ssh
->cfg
.logomitdata
) {
1255 int do_blank
= FALSE
, blank_prefix
= 0;
1256 /* "Session data" packets - omit the data field */
1257 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1258 do_blank
= TRUE
; blank_prefix
= 4;
1259 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1260 do_blank
= TRUE
; blank_prefix
= 8;
1263 blank
.offset
= blank_prefix
;
1264 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1265 blank
.type
= PKTLOG_OMIT
;
1269 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1270 ssh2_pkt_type(ssh
->pkt_ctx
, st
->pktin
->type
),
1271 st
->pktin
->data
+6, st
->pktin
->length
-6,
1275 crFinish(st
->pktin
);
1278 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
, int *offset_p
)
1280 int pad
, biglen
, i
, pktoffs
;
1284 * XXX various versions of SC (including 8.8.4) screw up the
1285 * register allocation in this function and use the same register
1286 * (D6) for len and as a temporary, with predictable results. The
1287 * following sledgehammer prevents this.
1294 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[12],
1295 ssh1_pkt_type(pkt
->data
[12]),
1296 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1297 pkt
->nblanks
, pkt
->blanks
);
1298 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1301 if (ssh
->v1_compressing
) {
1302 unsigned char *compblk
;
1304 zlib_compress_block(ssh
->cs_comp_ctx
,
1305 pkt
->data
+ 12, pkt
->length
- 12,
1306 &compblk
, &complen
);
1307 memcpy(pkt
->data
+ 12, compblk
, complen
);
1309 pkt
->length
= complen
+ 12;
1312 ssh_pkt_ensure(pkt
, pkt
->length
+ 4); /* space for CRC */
1314 len
= pkt
->length
- 4 - 8; /* len(type+data+CRC) */
1315 pad
= 8 - (len
% 8);
1317 biglen
= len
+ pad
; /* len(padding+type+data+CRC) */
1319 for (i
= pktoffs
; i
< 4+8; i
++)
1320 pkt
->data
[i
] = random_byte();
1321 crc
= crc32_compute(pkt
->data
+ pktoffs
+ 4, biglen
- 4); /* all ex len */
1322 PUT_32BIT(pkt
->data
+ pktoffs
+ 4 + biglen
- 4, crc
);
1323 PUT_32BIT(pkt
->data
+ pktoffs
, len
);
1326 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
,
1327 pkt
->data
+ pktoffs
+ 4, biglen
);
1329 if (offset_p
) *offset_p
= pktoffs
;
1330 return biglen
+ 4; /* len(length+padding+type+data+CRC) */
1333 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1335 int len
, backlog
, offset
;
1336 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1337 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
+ offset
, len
);
1338 if (backlog
> SSH_MAX_BACKLOG
)
1339 ssh_throttle_all(ssh
, 1, backlog
);
1340 ssh_free_packet(pkt
);
1343 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1346 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1347 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1348 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1349 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1353 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
,
1354 pkt
->data
+ offset
, len
);
1355 ssh
->deferred_len
+= len
;
1356 ssh_free_packet(pkt
);
1360 * Construct a SSH-1 packet with the specified contents.
1361 * (This all-at-once interface used to be the only one, but now SSH-1
1362 * packets can also be constructed incrementally.)
1364 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
, va_list ap
)
1370 pkt
= ssh1_pkt_init(pkttype
);
1372 while ((argtype
= va_arg(ap
, int)) != PKT_END
) {
1373 unsigned char *argp
, argchar
;
1374 unsigned long argint
;
1377 /* Actual fields in the packet */
1379 argint
= va_arg(ap
, int);
1380 ssh_pkt_adduint32(pkt
, argint
);
1383 argchar
= (unsigned char) va_arg(ap
, int);
1384 ssh_pkt_addbyte(pkt
, argchar
);
1387 argp
= va_arg(ap
, unsigned char *);
1388 arglen
= va_arg(ap
, int);
1389 ssh_pkt_adddata(pkt
, argp
, arglen
);
1392 argp
= va_arg(ap
, unsigned char *);
1393 ssh_pkt_addstring(pkt
, argp
);
1396 bn
= va_arg(ap
, Bignum
);
1397 ssh1_pkt_addmp(pkt
, bn
);
1399 /* Tokens for modifications to packet logging */
1401 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1404 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1407 end_log_omission(ssh
, pkt
);
1415 static void send_packet(Ssh ssh
, int pkttype
, ...)
1419 va_start(ap
, pkttype
);
1420 pkt
= construct_packet(ssh
, pkttype
, ap
);
1425 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1429 va_start(ap
, pkttype
);
1430 pkt
= construct_packet(ssh
, pkttype
, ap
);
1432 s_wrpkt_defer(ssh
, pkt
);
1435 static int ssh_versioncmp(char *a
, char *b
)
1438 unsigned long av
, bv
;
1440 av
= strtoul(a
, &ae
, 10);
1441 bv
= strtoul(b
, &be
, 10);
1443 return (av
< bv ?
-1 : +1);
1448 av
= strtoul(ae
, &ae
, 10);
1449 bv
= strtoul(be
, &be
, 10);
1451 return (av
< bv ?
-1 : +1);
1456 * Utility routines for putting an SSH-protocol `string' and
1457 * `uint32' into a SHA state.
1459 static void sha_string(SHA_State
* s
, void *str
, int len
)
1461 unsigned char lenblk
[4];
1462 PUT_32BIT(lenblk
, len
);
1463 SHA_Bytes(s
, lenblk
, 4);
1464 SHA_Bytes(s
, str
, len
);
1467 static void sha_uint32(SHA_State
* s
, unsigned i
)
1469 unsigned char intblk
[4];
1470 PUT_32BIT(intblk
, i
);
1471 SHA_Bytes(s
, intblk
, 4);
1475 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1477 static void ssh_pkt_ensure(struct Packet
*pkt
, int length
)
1479 if (pkt
->maxlen
< length
) {
1480 unsigned char *body
= pkt
->body
;
1481 int offset
= body ? pkt
->data
- body
: 0;
1482 pkt
->maxlen
= length
+ 256;
1483 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1484 if (body
) pkt
->body
= pkt
->data
+ offset
;
1487 static void ssh_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1489 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1491 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1493 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
-
1494 (pkt
->body
- pkt
->data
);
1495 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1496 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1499 ssh_pkt_ensure(pkt
, pkt
->length
);
1500 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1502 static void ssh_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1504 ssh_pkt_adddata(pkt
, &byte
, 1);
1506 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1508 ssh_pkt_adddata(pkt
, &value
, 1);
1510 static void ssh_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1513 PUT_32BIT(x
, value
);
1514 ssh_pkt_adddata(pkt
, x
, 4);
1516 static void ssh_pkt_addstring_start(struct Packet
*pkt
)
1518 ssh_pkt_adduint32(pkt
, 0);
1519 pkt
->savedpos
= pkt
->length
;
1521 static void ssh_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1523 ssh_pkt_adddata(pkt
, data
, strlen(data
));
1524 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1526 static void ssh_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1528 ssh_pkt_adddata(pkt
, data
, len
);
1529 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1531 static void ssh_pkt_addstring(struct Packet
*pkt
, char *data
)
1533 ssh_pkt_addstring_start(pkt
);
1534 ssh_pkt_addstring_str(pkt
, data
);
1536 static void ssh1_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1538 int len
= ssh1_bignum_length(b
);
1539 unsigned char *data
= snewn(len
, char);
1540 (void) ssh1_write_bignum(data
, b
);
1541 ssh_pkt_adddata(pkt
, data
, len
);
1544 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1547 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1548 p
= snewn(n
+ 1, unsigned char);
1550 fatalbox("out of memory");
1552 for (i
= 1; i
<= n
; i
++)
1553 p
[i
] = bignum_byte(b
, n
- i
);
1555 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1557 memmove(p
, p
+ i
, n
+ 1 - i
);
1561 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1565 p
= ssh2_mpint_fmt(b
, &len
);
1566 ssh_pkt_addstring_start(pkt
);
1567 ssh_pkt_addstring_data(pkt
, (char *)p
, len
);
1571 static struct Packet
*ssh1_pkt_init(int pkt_type
)
1573 struct Packet
*pkt
= ssh_new_packet();
1574 pkt
->length
= 4 + 8; /* space for length + max padding */
1575 ssh_pkt_addbyte(pkt
, pkt_type
);
1576 pkt
->body
= pkt
->data
+ pkt
->length
;
1580 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1581 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1582 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1583 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1584 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1585 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1586 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1587 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1588 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1590 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1592 struct Packet
*pkt
= ssh_new_packet();
1595 ssh_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1596 pkt
->body
= pkt
->data
+ pkt
->length
;
1601 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1602 * put the MAC on it. Final packet, ready to be sent, is stored in
1603 * pkt->data. Total length is returned.
1605 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1607 int cipherblk
, maclen
, padding
, i
;
1610 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1611 ssh2_pkt_type(ssh
->pkt_ctx
, pkt
->data
[5]),
1612 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1613 pkt
->nblanks
, pkt
->blanks
);
1614 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1618 * Compress packet payload.
1621 unsigned char *newpayload
;
1624 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1626 &newpayload
, &newlen
)) {
1628 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1634 * Add padding. At least four bytes, and must also bring total
1635 * length (minus MAC) up to a multiple of the block size.
1636 * If pkt->forcepad is set, make sure the packet is at least that size
1639 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1640 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1642 if (pkt
->length
+ padding
< pkt
->forcepad
)
1643 padding
= pkt
->forcepad
- pkt
->length
;
1645 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1646 assert(padding
<= 255);
1647 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1648 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1649 pkt
->data
[4] = padding
;
1650 for (i
= 0; i
< padding
; i
++)
1651 pkt
->data
[pkt
->length
+ i
] = random_byte();
1652 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
1654 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
1655 pkt
->length
+ padding
,
1656 ssh
->v2_outgoing_sequence
);
1657 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1660 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1661 pkt
->data
, pkt
->length
+ padding
);
1663 pkt
->encrypted_len
= pkt
->length
+ padding
;
1665 /* Ready-to-send packet starts at pkt->data. We return length. */
1666 return pkt
->length
+ padding
+ maclen
;
1670 * Routines called from the main SSH code to send packets. There
1671 * are quite a few of these, because we have two separate
1672 * mechanisms for delaying the sending of packets:
1674 * - In order to send an IGNORE message and a password message in
1675 * a single fixed-length blob, we require the ability to
1676 * concatenate the encrypted forms of those two packets _into_ a
1677 * single blob and then pass it to our <network.h> transport
1678 * layer in one go. Hence, there's a deferment mechanism which
1679 * works after packet encryption.
1681 * - In order to avoid sending any connection-layer messages
1682 * during repeat key exchange, we have to queue up any such
1683 * outgoing messages _before_ they are encrypted (and in
1684 * particular before they're allocated sequence numbers), and
1685 * then send them once we've finished.
1687 * I call these mechanisms `defer' and `queue' respectively, so as
1688 * to distinguish them reasonably easily.
1690 * The functions send_noqueue() and defer_noqueue() free the packet
1691 * structure they are passed. Every outgoing packet goes through
1692 * precisely one of these functions in its life; packets passed to
1693 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1694 * these or get queued, and then when the queue is later emptied
1695 * the packets are all passed to defer_noqueue().
1699 * Send an SSH-2 packet immediately, without queuing or deferring.
1701 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
1705 len
= ssh2_pkt_construct(ssh
, pkt
);
1706 backlog
= sk_write(ssh
->s
, (char *)pkt
->data
, len
);
1707 if (backlog
> SSH_MAX_BACKLOG
)
1708 ssh_throttle_all(ssh
, 1, backlog
);
1710 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
1711 if (!ssh
->kex_in_progress
&&
1712 ssh
->max_data_size
!= 0 &&
1713 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1714 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
1716 ssh_free_packet(pkt
);
1720 * Defer an SSH-2 packet.
1722 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
)
1724 int len
= ssh2_pkt_construct(ssh
, pkt
);
1725 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1726 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1727 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1731 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
1732 ssh
->deferred_len
+= len
;
1733 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
1734 ssh_free_packet(pkt
);
1738 * Queue an SSH-2 packet.
1740 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
1742 assert(ssh
->queueing
);
1744 if (ssh
->queuelen
>= ssh
->queuesize
) {
1745 ssh
->queuesize
= ssh
->queuelen
+ 32;
1746 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
1749 ssh
->queue
[ssh
->queuelen
++] = pkt
;
1753 * Either queue or send a packet, depending on whether queueing is
1756 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
1759 ssh2_pkt_queue(ssh
, pkt
);
1761 ssh2_pkt_send_noqueue(ssh
, pkt
);
1766 * Either queue or defer a packet, depending on whether queueing is
1769 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
1772 ssh2_pkt_queue(ssh
, pkt
);
1774 ssh2_pkt_defer_noqueue(ssh
, pkt
);
1779 * Send the whole deferred data block constructed by
1780 * ssh2_pkt_defer() or SSH-1's defer_packet().
1782 * The expected use of the defer mechanism is that you call
1783 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1784 * not currently queueing, this simply sets up deferred_send_data
1785 * and then sends it. If we _are_ currently queueing, the calls to
1786 * ssh2_pkt_defer() put the deferred packets on to the queue
1787 * instead, and therefore ssh_pkt_defersend() has no deferred data
1788 * to send. Hence, there's no need to make it conditional on
1791 static void ssh_pkt_defersend(Ssh ssh
)
1794 backlog
= sk_write(ssh
->s
, (char *)ssh
->deferred_send_data
,
1796 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1797 sfree(ssh
->deferred_send_data
);
1798 ssh
->deferred_send_data
= NULL
;
1799 if (backlog
> SSH_MAX_BACKLOG
)
1800 ssh_throttle_all(ssh
, 1, backlog
);
1802 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
1803 if (!ssh
->kex_in_progress
&&
1804 ssh
->max_data_size
!= 0 &&
1805 ssh
->outgoing_data_size
> ssh
->max_data_size
)
1806 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
1807 ssh
->deferred_data_size
= 0;
1811 * Send all queued SSH-2 packets. We send them by means of
1812 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1813 * packets that needed to be lumped together.
1815 static void ssh2_pkt_queuesend(Ssh ssh
)
1819 assert(!ssh
->queueing
);
1821 for (i
= 0; i
< ssh
->queuelen
; i
++)
1822 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
]);
1825 ssh_pkt_defersend(ssh
);
1829 void bndebug(char *string
, Bignum b
)
1833 p
= ssh2_mpint_fmt(b
, &len
);
1834 debug(("%s", string
));
1835 for (i
= 0; i
< len
; i
++)
1836 debug((" %02x", p
[i
]));
1842 static void sha_mpint(SHA_State
* s
, Bignum b
)
1846 p
= ssh2_mpint_fmt(b
, &len
);
1847 sha_string(s
, p
, len
);
1852 * Packet decode functions for both SSH-1 and SSH-2.
1854 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
1856 unsigned long value
;
1857 if (pkt
->length
- pkt
->savedpos
< 4)
1858 return 0; /* arrgh, no way to decline (FIXME?) */
1859 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1863 static int ssh2_pkt_getbool(struct Packet
*pkt
)
1865 unsigned long value
;
1866 if (pkt
->length
- pkt
->savedpos
< 1)
1867 return 0; /* arrgh, no way to decline (FIXME?) */
1868 value
= pkt
->body
[pkt
->savedpos
] != 0;
1872 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
1877 if (pkt
->length
- pkt
->savedpos
< 4)
1879 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
1884 if (pkt
->length
- pkt
->savedpos
< *length
)
1886 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
1887 pkt
->savedpos
+= *length
;
1889 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
1891 if (pkt
->length
- pkt
->savedpos
< length
)
1893 pkt
->savedpos
+= length
;
1894 return pkt
->body
+ (pkt
->savedpos
- length
);
1896 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
1897 unsigned char **keystr
)
1901 j
= makekey(pkt
->body
+ pkt
->savedpos
,
1902 pkt
->length
- pkt
->savedpos
,
1909 assert(pkt
->savedpos
< pkt
->length
);
1913 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
1918 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
1919 pkt
->length
- pkt
->savedpos
, &b
);
1927 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
1933 ssh_pkt_getstring(pkt
, &p
, &length
);
1938 b
= bignum_from_bytes((unsigned char *)p
, length
);
1943 * Helper function to add an SSH-2 signature blob to a packet.
1944 * Expects to be shown the public key blob as well as the signature
1945 * blob. Normally works just like ssh2_pkt_addstring, but will
1946 * fiddle with the signature packet if necessary for
1947 * BUG_SSH2_RSA_PADDING.
1949 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
1950 void *pkblob_v
, int pkblob_len
,
1951 void *sigblob_v
, int sigblob_len
)
1953 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
1954 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
1956 /* dmemdump(pkblob, pkblob_len); */
1957 /* dmemdump(sigblob, sigblob_len); */
1960 * See if this is in fact an ssh-rsa signature and a buggy
1961 * server; otherwise we can just do this the easy way.
1963 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
1964 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
1965 int pos
, len
, siglen
;
1968 * Find the byte length of the modulus.
1971 pos
= 4+7; /* skip over "ssh-rsa" */
1972 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
1973 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
1974 pos
+= 4; /* find modulus itself */
1975 while (len
> 0 && pkblob
[pos
] == 0)
1977 /* debug(("modulus length is %d\n", len)); */
1980 * Now find the signature integer.
1982 pos
= 4+7; /* skip over "ssh-rsa" */
1983 siglen
= GET_32BIT(sigblob
+pos
);
1984 /* debug(("signature length is %d\n", siglen)); */
1986 if (len
!= siglen
) {
1987 unsigned char newlen
[4];
1988 ssh2_pkt_addstring_start(pkt
);
1989 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
1990 /* dmemdump(sigblob, pos); */
1991 pos
+= 4; /* point to start of actual sig */
1992 PUT_32BIT(newlen
, len
);
1993 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
1994 /* dmemdump(newlen, 4); */
1996 while (len
-- > siglen
) {
1997 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
1998 /* dmemdump(newlen, 1); */
2000 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2001 /* dmemdump(sigblob+pos, siglen); */
2005 /* Otherwise fall through and do it the easy way. */
2008 ssh2_pkt_addstring_start(pkt
);
2009 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2013 * Examine the remote side's version string and compare it against
2014 * a list of known buggy implementations.
2016 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2018 char *imp
; /* pointer to implementation part */
2020 imp
+= strcspn(imp
, "-");
2022 imp
+= strcspn(imp
, "-");
2025 ssh
->remote_bugs
= 0;
2027 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
2028 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
2029 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2030 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2031 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2032 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2034 * These versions don't support SSH1_MSG_IGNORE, so we have
2035 * to use a different defence against password length
2038 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2039 logevent("We believe remote version has SSH-1 ignore bug");
2042 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
2043 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
2044 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2046 * These versions need a plain password sent; they can't
2047 * handle having a null and a random length of data after
2050 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2051 logevent("We believe remote version needs a plain SSH-1 password");
2054 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
2055 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
2056 (!strcmp(imp
, "Cisco-1.25")))) {
2058 * These versions apparently have no clue whatever about
2059 * RSA authentication and will panic and die if they see
2060 * an AUTH_RSA message.
2062 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2063 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2066 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
2067 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
2068 !wc_match("* VShell", imp
) &&
2069 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2070 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2071 wc_match("2.1 *", imp
)))) {
2073 * These versions have the HMAC bug.
2075 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2076 logevent("We believe remote version has SSH-2 HMAC bug");
2079 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
2080 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
2081 !wc_match("* VShell", imp
) &&
2082 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2084 * These versions have the key-derivation bug (failing to
2085 * include the literal shared secret in the hashes that
2086 * generate the keys).
2088 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2089 logevent("We believe remote version has SSH-2 key-derivation bug");
2092 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
2093 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
2094 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2095 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2097 * These versions have the SSH-2 RSA padding bug.
2099 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2100 logevent("We believe remote version has SSH-2 RSA padding bug");
2103 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
2104 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
2105 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2107 * These versions have the SSH-2 session-ID bug in
2108 * public-key authentication.
2110 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2111 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2114 if (ssh
->cfg
.sshbug_rekey2
== FORCE_ON
||
2115 (ssh
->cfg
.sshbug_rekey2
== AUTO
&&
2116 (wc_match("OpenSSH_2.[0-4]*", imp
) ||
2117 wc_match("OpenSSH_2.5.[0-3]*", imp
) ||
2118 wc_match("Sun_SSH_1.0", imp
) ||
2119 wc_match("Sun_SSH_1.0.1", imp
)))) {
2121 * These versions have the SSH-2 rekey bug.
2123 ssh
->remote_bugs
|= BUG_SSH2_REKEY
;
2124 logevent("We believe remote version has SSH-2 rekey bug");
2129 * The `software version' part of an SSH version string is required
2130 * to contain no spaces or minus signs.
2132 static void ssh_fix_verstring(char *str
)
2134 /* Eat "SSH-<protoversion>-". */
2135 assert(*str
== 'S'); str
++;
2136 assert(*str
== 'S'); str
++;
2137 assert(*str
== 'H'); str
++;
2138 assert(*str
== '-'); str
++;
2139 while (*str
&& *str
!= '-') str
++;
2140 assert(*str
== '-'); str
++;
2142 /* Convert minus signs and spaces in the remaining string into
2145 if (*str
== '-' || *str
== ' ')
2151 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2153 struct do_ssh_init_state
{
2161 crState(do_ssh_init_state
);
2163 crBegin(ssh
->do_ssh_init_crstate
);
2165 /* Search for the string "SSH-" in the input. */
2168 static const int transS
[] = { 1, 2, 2, 1 };
2169 static const int transH
[] = { 0, 0, 3, 0 };
2170 static const int transminus
[] = { 0, 0, 0, -1 };
2172 s
->i
= transS
[s
->i
];
2174 s
->i
= transH
[s
->i
];
2176 s
->i
= transminus
[s
->i
];
2181 crReturn(1); /* get another character */
2185 s
->vstring
= snewn(s
->vstrsize
, char);
2186 strcpy(s
->vstring
, "SSH-");
2190 crReturn(1); /* get another char */
2191 if (s
->vslen
>= s
->vstrsize
- 1) {
2193 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2195 s
->vstring
[s
->vslen
++] = c
;
2198 s
->version
[s
->i
] = '\0';
2200 } else if (s
->i
< sizeof(s
->version
) - 1)
2201 s
->version
[s
->i
++] = c
;
2202 } else if (c
== '\012')
2206 ssh
->agentfwd_enabled
= FALSE
;
2207 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2209 s
->vstring
[s
->vslen
] = 0;
2210 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2211 logeventf(ssh
, "Server version: %s", s
->vstring
);
2212 ssh_detect_bugs(ssh
, s
->vstring
);
2215 * Decide which SSH protocol version to support.
2218 /* Anything strictly below "2.0" means protocol 1 is supported. */
2219 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2220 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2221 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2223 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
2224 bombout(("SSH protocol version 1 required by user but not provided by server"));
2227 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
2228 bombout(("SSH protocol version 2 required by user but not provided by server"));
2235 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
)) {
2237 * Construct a v2 version string.
2239 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2243 * Construct a v1 version string.
2245 verstring
= dupprintf("SSH-%s-%s\012",
2246 (ssh_versioncmp(s
->version
, "1.5") <= 0 ?
2247 s
->version
: "1.5"),
2252 ssh_fix_verstring(verstring
);
2254 if (ssh
->version
== 2) {
2256 * Hash our version string and their version string.
2258 SHA_Init(&ssh
->exhashbase
);
2259 sha_string(&ssh
->exhashbase
, verstring
,
2260 strcspn(verstring
, "\015\012"));
2261 sha_string(&ssh
->exhashbase
, s
->vstring
,
2262 strcspn(s
->vstring
, "\015\012"));
2265 * Initialise SSH-2 protocol.
2267 ssh
->protocol
= ssh2_protocol
;
2268 ssh2_protocol_setup(ssh
);
2269 ssh
->s_rdpkt
= ssh2_rdpkt
;
2272 * Initialise SSH-1 protocol.
2274 ssh
->protocol
= ssh1_protocol
;
2275 ssh1_protocol_setup(ssh
);
2276 ssh
->s_rdpkt
= ssh1_rdpkt
;
2278 logeventf(ssh
, "We claim version: %.*s",
2279 strcspn(verstring
, "\015\012"), verstring
);
2280 sk_write(ssh
->s
, verstring
, strlen(verstring
));
2284 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2286 update_specials_menu(ssh
->frontend
);
2287 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2288 ssh
->pinger
= pinger_new(&ssh
->cfg
, &ssh_backend
, ssh
);
2295 static void ssh_process_incoming_data(Ssh ssh
,
2296 unsigned char **data
, int *datalen
)
2298 struct Packet
*pktin
= ssh
->s_rdpkt(ssh
, data
, datalen
);
2300 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2301 ssh_free_packet(pktin
);
2305 static void ssh_queue_incoming_data(Ssh ssh
,
2306 unsigned char **data
, int *datalen
)
2308 bufchain_add(&ssh
->queued_incoming_data
, *data
, *datalen
);
2313 static void ssh_process_queued_incoming_data(Ssh ssh
)
2316 unsigned char *data
;
2319 while (!ssh
->frozen
&& bufchain_size(&ssh
->queued_incoming_data
)) {
2320 bufchain_prefix(&ssh
->queued_incoming_data
, &vdata
, &len
);
2324 while (!ssh
->frozen
&& len
> 0)
2325 ssh_process_incoming_data(ssh
, &data
, &len
);
2328 bufchain_consume(&ssh
->queued_incoming_data
, origlen
- len
);
2332 static void ssh_set_frozen(Ssh ssh
, int frozen
)
2335 sk_set_frozen(ssh
->s
, frozen
);
2336 ssh
->frozen
= frozen
;
2339 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2341 crBegin(ssh
->ssh_gotdata_crstate
);
2344 * To begin with, feed the characters one by one to the
2345 * protocol initialisation / selection function do_ssh_init().
2346 * When that returns 0, we're done with the initial greeting
2347 * exchange and can move on to packet discipline.
2350 int ret
; /* need not be kept across crReturn */
2352 crReturnV
; /* more data please */
2353 ret
= do_ssh_init(ssh
, *data
);
2361 * We emerge from that loop when the initial negotiation is
2362 * over and we have selected an s_rdpkt function. Now pass
2363 * everything to s_rdpkt, and then pass the resulting packets
2364 * to the proper protocol handler.
2370 * Process queued data if there is any.
2372 ssh_process_queued_incoming_data(ssh
);
2375 while (datalen
> 0) {
2377 ssh_queue_incoming_data(ssh
, &data
, &datalen
);
2379 ssh_process_incoming_data(ssh
, &data
, &datalen
);
2381 if (ssh
->state
== SSH_STATE_CLOSED
)
2389 static int ssh_do_close(Ssh ssh
, int notify_exit
)
2392 struct ssh_channel
*c
;
2394 ssh
->state
= SSH_STATE_CLOSED
;
2395 expire_timer_context(ssh
);
2400 notify_remote_exit(ssh
->frontend
);
2405 * Now we must shut down any port- and X-forwarded channels going
2406 * through this connection.
2408 if (ssh
->channels
) {
2409 while (NULL
!= (c
= index234(ssh
->channels
, 0))) {
2412 x11_close(c
->u
.x11
.s
);
2415 pfd_close(c
->u
.pfd
.s
);
2418 del234(ssh
->channels
, c
); /* moving next one to index 0 */
2419 if (ssh
->version
== 2)
2420 bufchain_clear(&c
->v
.v2
.outbuffer
);
2425 * Go through port-forwardings, and close any associated
2426 * listening sockets.
2428 if (ssh
->portfwds
) {
2429 struct ssh_portfwd
*pf
;
2430 while (NULL
!= (pf
= index234(ssh
->portfwds
, 0))) {
2431 /* Dispose of any listening socket. */
2433 pfd_terminate(pf
->local
);
2434 del234(ssh
->portfwds
, pf
); /* moving next one to index 0 */
2442 static void ssh_log(Plug plug
, int type
, SockAddr addr
, int port
,
2443 const char *error_msg
, int error_code
)
2445 Ssh ssh
= (Ssh
) plug
;
2446 char addrbuf
[256], *msg
;
2448 sk_getaddr(addr
, addrbuf
, lenof(addrbuf
));
2451 msg
= dupprintf("Connecting to %s port %d", addrbuf
, port
);
2453 msg
= dupprintf("Failed to connect to %s: %s", addrbuf
, error_msg
);
2459 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2462 Ssh ssh
= (Ssh
) plug
;
2463 int need_notify
= ssh_do_close(ssh
, FALSE
);
2465 if (!error_msg
&& !ssh
->close_expected
) {
2466 error_msg
= "Server unexpectedly closed network connection";
2470 notify_remote_exit(ssh
->frontend
);
2473 /* A socket error has occurred. */
2474 logevent(error_msg
);
2475 connection_fatal(ssh
->frontend
, "%s", error_msg
);
2477 logevent("Server closed network connection");
2482 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2484 Ssh ssh
= (Ssh
) plug
;
2485 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2486 if (ssh
->state
== SSH_STATE_CLOSED
) {
2487 ssh_do_close(ssh
, TRUE
);
2493 static void ssh_sent(Plug plug
, int bufsize
)
2495 Ssh ssh
= (Ssh
) plug
;
2497 * If the send backlog on the SSH socket itself clears, we
2498 * should unthrottle the whole world if it was throttled.
2500 if (bufsize
< SSH_MAX_BACKLOG
)
2501 ssh_throttle_all(ssh
, 0, bufsize
);
2505 * Connect to specified host and port.
2506 * Returns an error message, or NULL on success.
2507 * Also places the canonical host name into `realhost'. It must be
2508 * freed by the caller.
2510 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
2511 char **realhost
, int nodelay
, int keepalive
)
2513 static const struct plug_function_table fn_table
= {
2524 ssh
->savedhost
= snewn(1 + strlen(host
), char);
2525 if (!ssh
->savedhost
)
2526 fatalbox("Out of memory");
2527 strcpy(ssh
->savedhost
, host
);
2530 port
= 22; /* default ssh port */
2531 ssh
->savedport
= port
;
2536 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
2537 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
2538 (ssh
->cfg
.addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
2539 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
,
2540 ssh
->cfg
.addressfamily
);
2541 if ((err
= sk_addr_error(addr
)) != NULL
) {
2549 ssh
->fn
= &fn_table
;
2550 ssh
->s
= new_connection(addr
, *realhost
, port
,
2551 0, 1, nodelay
, keepalive
, (Plug
) ssh
, &ssh
->cfg
);
2552 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2554 notify_remote_exit(ssh
->frontend
);
2562 * Throttle or unthrottle the SSH connection.
2564 static void ssh1_throttle(Ssh ssh
, int adjust
)
2566 int old_count
= ssh
->v1_throttle_count
;
2567 ssh
->v1_throttle_count
+= adjust
;
2568 assert(ssh
->v1_throttle_count
>= 0);
2569 if (ssh
->v1_throttle_count
&& !old_count
) {
2570 ssh_set_frozen(ssh
, 1);
2571 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2572 ssh_set_frozen(ssh
, 0);
2577 * Throttle or unthrottle _all_ local data streams (for when sends
2578 * on the SSH connection itself back up).
2580 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2583 struct ssh_channel
*c
;
2585 if (enable
== ssh
->throttled_all
)
2587 ssh
->throttled_all
= enable
;
2588 ssh
->overall_bufsize
= bufsize
;
2591 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2593 case CHAN_MAINSESSION
:
2595 * This is treated separately, outside the switch.
2599 x11_override_throttle(c
->u
.x11
.s
, enable
);
2602 /* Agent channels require no buffer management. */
2605 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
2612 * Username and password input, abstracted off into routines
2613 * reusable in several places - even between SSH-1 and SSH-2.
2616 /* Set up a username or password input loop on a given buffer. */
2617 static void setup_userpass_input(Ssh ssh
, char *buffer
, int buflen
, int echo
)
2619 ssh
->userpass_input_buffer
= buffer
;
2620 ssh
->userpass_input_buflen
= buflen
;
2621 ssh
->userpass_input_bufpos
= 0;
2622 ssh
->userpass_input_echo
= echo
;
2626 * Process some terminal data in the course of username/password
2627 * input. Returns >0 for success (line of input returned in
2628 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2629 * for inconclusive (keep waiting for more input please).
2631 static int process_userpass_input(Ssh ssh
, unsigned char *in
, int inlen
)
2636 switch (c
= *in
++) {
2639 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
] = 0;
2640 ssh
->userpass_input_buffer
[ssh
->userpass_input_buflen
-1] = 0;
2645 if (ssh
->userpass_input_bufpos
> 0) {
2646 if (ssh
->userpass_input_echo
)
2647 c_write_str(ssh
, "\b \b");
2648 ssh
->userpass_input_bufpos
--;
2653 while (ssh
->userpass_input_bufpos
> 0) {
2654 if (ssh
->userpass_input_echo
)
2655 c_write_str(ssh
, "\b \b");
2656 ssh
->userpass_input_bufpos
--;
2665 * This simplistic check for printability is disabled
2666 * when we're doing password input, because some people
2667 * have control characters in their passwords.o
2669 if ((!ssh
->userpass_input_echo
||
2670 (c
>= ' ' && c
<= '~') ||
2671 ((unsigned char) c
>= 160))
2672 && ssh
->userpass_input_bufpos
< ssh
->userpass_input_buflen
-1) {
2673 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
++] = c
;
2674 if (ssh
->userpass_input_echo
)
2675 c_write(ssh
, &c
, 1);
2683 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
2685 Ssh ssh
= (Ssh
) sshv
;
2687 ssh
->agent_response
= reply
;
2688 ssh
->agent_response_len
= replylen
;
2690 if (ssh
->version
== 1)
2691 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2693 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
2696 static void ssh_dialog_callback(void *sshv
, int ret
)
2698 Ssh ssh
= (Ssh
) sshv
;
2700 ssh
->user_response
= ret
;
2702 if (ssh
->version
== 1)
2703 do_ssh1_login(ssh
, NULL
, -1, NULL
);
2705 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2708 * This may have unfrozen the SSH connection, so do a
2711 ssh_process_queued_incoming_data(ssh
);
2714 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
2716 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
2718 void *sentreply
= reply
;
2721 /* Fake SSH_AGENT_FAILURE. */
2722 sentreply
= "\0\0\0\1\5";
2725 if (ssh
->version
== 2) {
2726 ssh2_add_channel_data(c
, sentreply
, replylen
);
2729 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
2730 PKT_INT
, c
->remoteid
,
2733 PKT_DATA
, sentreply
, replylen
,
2742 * Handle the key exchange and user authentication phases.
2744 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
2745 struct Packet
*pktin
)
2748 unsigned char cookie
[8], *ptr
;
2749 struct RSAKey servkey
, hostkey
;
2750 struct MD5Context md5c
;
2751 struct do_ssh1_login_state
{
2753 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2754 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2755 int tried_publickey
, tried_agent
;
2756 int tis_auth_refused
, ccard_auth_refused
;
2757 unsigned char session_id
[16];
2760 void *publickey_blob
;
2761 int publickey_bloblen
;
2767 unsigned char request
[5], *response
, *p
;
2777 crState(do_ssh1_login_state
);
2779 crBegin(ssh
->do_ssh1_login_crstate
);
2784 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
2785 bombout(("Public key packet not received"));
2789 logevent("Received public keys");
2791 ptr
= ssh_pkt_getdata(pktin
, 8);
2793 bombout(("SSH-1 public key packet stopped before random cookie"));
2796 memcpy(cookie
, ptr
, 8);
2798 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
2799 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
2800 bombout(("Failed to read SSH-1 public keys from public key packet"));
2805 * Log the host key fingerprint.
2809 logevent("Host key fingerprint is:");
2810 strcpy(logmsg
, " ");
2811 hostkey
.comment
= NULL
;
2812 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2813 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2817 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
2818 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
2819 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
2821 ssh
->v1_local_protoflags
=
2822 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2823 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2826 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
2827 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
2828 MD5Update(&md5c
, cookie
, 8);
2829 MD5Final(s
->session_id
, &md5c
);
2831 for (i
= 0; i
< 32; i
++)
2832 ssh
->session_key
[i
] = random_byte();
2835 * Verify that the `bits' and `bytes' parameters match.
2837 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
2838 servkey
.bits
> servkey
.bytes
* 8) {
2839 bombout(("SSH-1 public keys were badly formatted"));
2843 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2845 s
->rsabuf
= snewn(s
->len
, unsigned char);
2847 fatalbox("Out of memory");
2850 * Verify the host key.
2854 * First format the key into a string.
2856 int len
= rsastr_len(&hostkey
);
2857 char fingerprint
[100];
2858 char *keystr
= snewn(len
, char);
2860 fatalbox("Out of memory");
2861 rsastr_fmt(keystr
, &hostkey
);
2862 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2864 ssh_set_frozen(ssh
, 1);
2865 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
2866 ssh
->savedhost
, ssh
->savedport
,
2867 "rsa", keystr
, fingerprint
,
2868 ssh_dialog_callback
, ssh
);
2870 if (s
->dlgret
< 0) {
2874 bombout(("Unexpected data from server while waiting"
2875 " for user host key response"));
2878 } while (pktin
|| inlen
> 0);
2879 s
->dlgret
= ssh
->user_response
;
2881 ssh_set_frozen(ssh
, 0);
2883 if (s
->dlgret
== 0) {
2884 ssh
->close_expected
= TRUE
;
2885 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
2890 for (i
= 0; i
< 32; i
++) {
2891 s
->rsabuf
[i
] = ssh
->session_key
[i
];
2893 s
->rsabuf
[i
] ^= s
->session_id
[i
];
2896 if (hostkey
.bytes
> servkey
.bytes
) {
2897 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
2899 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
2901 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
2903 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
2906 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
2910 logevent("Encrypted session key");
2913 int cipher_chosen
= 0, warn
= 0;
2914 char *cipher_string
= NULL
;
2916 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2917 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
2918 if (next_cipher
== CIPHER_WARN
) {
2919 /* If/when we choose a cipher, warn about it */
2921 } else if (next_cipher
== CIPHER_AES
) {
2922 /* XXX Probably don't need to mention this. */
2923 logevent("AES not supported in SSH-1, skipping");
2925 switch (next_cipher
) {
2926 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
2927 cipher_string
= "3DES"; break;
2928 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
2929 cipher_string
= "Blowfish"; break;
2930 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
2931 cipher_string
= "single-DES"; break;
2933 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
2937 if (!cipher_chosen
) {
2938 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2939 bombout(("Server violates SSH-1 protocol by not "
2940 "supporting 3DES encryption"));
2942 /* shouldn't happen */
2943 bombout(("No supported ciphers found"));
2947 /* Warn about chosen cipher if necessary. */
2949 ssh_set_frozen(ssh
, 1);
2950 s
->dlgret
= askalg(ssh
->frontend
, "cipher", cipher_string
,
2951 ssh_dialog_callback
, ssh
);
2952 if (s
->dlgret
< 0) {
2956 bombout(("Unexpected data from server while waiting"
2957 " for user response"));
2960 } while (pktin
|| inlen
> 0);
2961 s
->dlgret
= ssh
->user_response
;
2963 ssh_set_frozen(ssh
, 0);
2964 if (s
->dlgret
== 0) {
2965 ssh
->close_expected
= TRUE
;
2966 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
2972 switch (s
->cipher_type
) {
2973 case SSH_CIPHER_3DES
:
2974 logevent("Using 3DES encryption");
2976 case SSH_CIPHER_DES
:
2977 logevent("Using single-DES encryption");
2979 case SSH_CIPHER_BLOWFISH
:
2980 logevent("Using Blowfish encryption");
2984 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
2985 PKT_CHAR
, s
->cipher_type
,
2986 PKT_DATA
, cookie
, 8,
2987 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
2988 PKT_DATA
, s
->rsabuf
, s
->len
,
2989 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
2991 logevent("Trying to enable encryption...");
2995 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2996 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
2998 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
2999 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
3000 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
3002 ssh
->crcda_ctx
= crcda_make_context();
3003 logevent("Installing CRC compensation attack detector");
3005 if (servkey
.modulus
) {
3006 sfree(servkey
.modulus
);
3007 servkey
.modulus
= NULL
;
3009 if (servkey
.exponent
) {
3010 sfree(servkey
.exponent
);
3011 servkey
.exponent
= NULL
;
3013 if (hostkey
.modulus
) {
3014 sfree(hostkey
.modulus
);
3015 hostkey
.modulus
= NULL
;
3017 if (hostkey
.exponent
) {
3018 sfree(hostkey
.exponent
);
3019 hostkey
.exponent
= NULL
;
3023 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3024 bombout(("Encryption not successfully enabled"));
3028 logevent("Successfully started encryption");
3032 if (!*ssh
->cfg
.username
) {
3033 if (ssh_get_line
&& !ssh_getline_pw_only
) {
3034 if (!ssh_get_line("login as: ",
3035 s
->username
, sizeof(s
->username
), FALSE
)) {
3037 * get_line failed to get a username.
3040 logevent("No username provided. Abandoning session.");
3041 ssh
->close_expected
= TRUE
;
3042 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
3046 int ret
; /* need not be kept over crReturn */
3047 c_write_str(ssh
, "login as: ");
3050 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
3052 crWaitUntil(!pktin
);
3053 ret
= process_userpass_input(ssh
, in
, inlen
);
3057 c_write_str(ssh
, "\r\n");
3060 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
3061 s
->username
[sizeof(s
->username
)-1] = '\0';
3064 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
3066 char userlog
[22 + sizeof(s
->username
)];
3067 sprintf(userlog
, "Sent username \"%s\"", s
->username
);
3069 if (flags
& FLAG_INTERACTIVE
&&
3070 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
3071 strcat(userlog
, "\r\n");
3072 c_write_str(ssh
, userlog
);
3079 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
3080 /* We must not attempt PK auth. Pretend we've already tried it. */
3081 s
->tried_publickey
= s
->tried_agent
= 1;
3083 s
->tried_publickey
= s
->tried_agent
= 0;
3085 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
3086 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
3087 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
3088 if (!rsakey_pubblob(&ssh
->cfg
.keyfile
,
3089 &s
->publickey_blob
, &s
->publickey_bloblen
, NULL
))
3090 s
->publickey_blob
= NULL
;
3092 s
->publickey_blob
= NULL
;
3094 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
3095 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
3097 if (agent_exists() && !s
->tried_agent
) {
3099 * Attempt RSA authentication using Pageant.
3105 logevent("Pageant is running. Requesting keys.");
3107 /* Request the keys held by the agent. */
3108 PUT_32BIT(s
->request
, 1);
3109 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
3110 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
3111 ssh_agent_callback
, ssh
)) {
3115 bombout(("Unexpected data from server while waiting"
3116 " for agent response"));
3119 } while (pktin
|| inlen
> 0);
3120 r
= ssh
->agent_response
;
3121 s
->responselen
= ssh
->agent_response_len
;
3123 s
->response
= (unsigned char *) r
;
3124 if (s
->response
&& s
->responselen
>= 5 &&
3125 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
3126 s
->p
= s
->response
+ 5;
3127 s
->nkeys
= GET_32BIT(s
->p
);
3129 logeventf(ssh
, "Pageant has %d SSH-1 keys", s
->nkeys
);
3130 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3131 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
3132 if (s
->publickey_blob
&&
3133 !memcmp(s
->p
, s
->publickey_blob
,
3134 s
->publickey_bloblen
)) {
3135 logevent("This key matches configured key file");
3136 s
->tried_publickey
= 1;
3141 do { /* do while (0) to make breaking easy */
3142 n
= ssh1_read_bignum
3143 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3148 n
= ssh1_read_bignum
3149 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3154 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3156 s
->commentlen
= GET_32BIT(s
->p
);
3158 if (s
->responselen
- (s
->p
-s
->response
) <
3161 s
->commentp
= (char *)s
->p
;
3162 s
->p
+= s
->commentlen
;
3166 logevent("Pageant key list packet was truncated");
3170 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3171 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3173 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3174 logevent("Key refused");
3177 logevent("Received RSA challenge");
3178 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3179 bombout(("Server's RSA challenge was badly formatted"));
3184 char *agentreq
, *q
, *ret
;
3187 len
= 1 + 4; /* message type, bit count */
3188 len
+= ssh1_bignum_length(s
->key
.exponent
);
3189 len
+= ssh1_bignum_length(s
->key
.modulus
);
3190 len
+= ssh1_bignum_length(s
->challenge
);
3191 len
+= 16; /* session id */
3192 len
+= 4; /* response format */
3193 agentreq
= snewn(4 + len
, char);
3194 PUT_32BIT(agentreq
, len
);
3196 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3197 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3199 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3200 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3201 q
+= ssh1_write_bignum(q
, s
->challenge
);
3202 memcpy(q
, s
->session_id
, 16);
3204 PUT_32BIT(q
, 1); /* response format */
3205 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3206 ssh_agent_callback
, ssh
)) {
3211 bombout(("Unexpected data from server"
3212 " while waiting for agent"
3216 } while (pktin
|| inlen
> 0);
3217 vret
= ssh
->agent_response
;
3218 retlen
= ssh
->agent_response_len
;
3223 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3224 logevent("Sending Pageant's response");
3225 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3226 PKT_DATA
, ret
+ 5, 16,
3230 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3232 ("Pageant's response accepted");
3233 if (flags
& FLAG_VERBOSE
) {
3234 c_write_str(ssh
, "Authenticated using"
3236 c_write(ssh
, s
->commentp
,
3238 c_write_str(ssh
, "\" from agent\r\n");
3243 ("Pageant's response not accepted");
3246 ("Pageant failed to answer challenge");
3250 logevent("No reply received from Pageant");
3253 freebn(s
->key
.exponent
);
3254 freebn(s
->key
.modulus
);
3255 freebn(s
->challenge
);
3264 if (!filename_is_null(ssh
->cfg
.keyfile
) && !s
->tried_publickey
)
3265 s
->pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
3267 if (ssh
->cfg
.try_tis_auth
&&
3268 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3269 !s
->tis_auth_refused
) {
3270 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3271 logevent("Requested TIS authentication");
3272 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3274 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3275 logevent("TIS authentication declined");
3276 if (flags
& FLAG_INTERACTIVE
)
3277 c_write_str(ssh
, "TIS authentication refused.\r\n");
3278 s
->tis_auth_refused
= 1;
3284 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3286 bombout(("TIS challenge packet was badly formed"));
3289 c_write_str(ssh
, "Using TIS authentication.\r\n");
3290 logevent("Received TIS challenge");
3291 if (challengelen
> sizeof(s
->prompt
) - 1)
3292 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3293 memcpy(s
->prompt
, challenge
, challengelen
);
3294 /* Prompt heuristic comes from OpenSSH */
3295 strncpy(s
->prompt
+ challengelen
,
3296 memchr(s
->prompt
, '\n', challengelen
) ?
3297 "": "\r\nResponse: ",
3298 (sizeof s
->prompt
) - challengelen
);
3299 s
->prompt
[(sizeof s
->prompt
) - 1] = '\0';
3302 if (ssh
->cfg
.try_tis_auth
&&
3303 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
3304 !s
->ccard_auth_refused
) {
3305 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
3306 logevent("Requested CryptoCard authentication");
3307 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
3309 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
3310 logevent("CryptoCard authentication declined");
3311 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
3312 s
->ccard_auth_refused
= 1;
3318 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3320 bombout(("CryptoCard challenge packet was badly formed"));
3323 c_write_str(ssh
, "Using CryptoCard authentication.\r\n");
3324 logevent("Received CryptoCard challenge");
3325 if (challengelen
> sizeof(s
->prompt
) - 1)
3326 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
3327 memcpy(s
->prompt
, challenge
, challengelen
);
3328 strncpy(s
->prompt
+ challengelen
,
3329 memchr(s
->prompt
, '\n', challengelen
) ?
3330 "" : "\r\nResponse: ",
3331 sizeof(s
->prompt
) - challengelen
);
3332 s
->prompt
[sizeof(s
->prompt
) - 1] = '\0';
3335 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3336 sprintf(s
->prompt
, "%.90s@%.90s's password: ",
3337 s
->username
, ssh
->savedhost
);
3339 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3340 char *comment
= NULL
;
3342 if (flags
& FLAG_VERBOSE
)
3343 c_write_str(ssh
, "Trying public key authentication.\r\n");
3344 logeventf(ssh
, "Trying public key \"%s\"",
3345 filename_to_str(&ssh
->cfg
.keyfile
));
3346 type
= key_type(&ssh
->cfg
.keyfile
);
3347 if (type
!= SSH_KEYTYPE_SSH1
) {
3348 char *msg
= dupprintf("Key is of wrong type (%s)",
3349 key_type_to_str(type
));
3351 c_write_str(ssh
, msg
);
3352 c_write_str(ssh
, "\r\n");
3354 s
->tried_publickey
= 1;
3357 if (!rsakey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
3358 if (flags
& FLAG_VERBOSE
)
3359 c_write_str(ssh
, "No passphrase required.\r\n");
3362 sprintf(s
->prompt
, "Passphrase for key \"%.100s\": ", comment
);
3367 * Show password prompt, having first obtained it via a TIS
3368 * or CryptoCard exchange if we're doing TIS or CryptoCard
3372 if (!ssh_get_line(s
->prompt
, s
->password
,
3373 sizeof(s
->password
), TRUE
)) {
3375 * get_line failed to get a password (for example
3376 * because one was supplied on the command line
3377 * which has already failed to work). Terminate.
3379 send_packet(ssh
, SSH1_MSG_DISCONNECT
,
3380 PKT_STR
, "No more passwords available to try",
3382 logevent("Unable to authenticate");
3383 connection_fatal(ssh
->frontend
, "Unable to authenticate");
3384 ssh
->close_expected
= TRUE
;
3385 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
3389 /* Prompt may have come from server. We've munged it a bit, so
3390 * we know it to be zero-terminated at least once. */
3391 int ret
; /* need not be saved over crReturn */
3392 c_write_untrusted(ssh
, s
->prompt
, strlen(s
->prompt
));
3395 setup_userpass_input(ssh
, s
->password
, sizeof(s
->password
), 0);
3397 crWaitUntil(!pktin
);
3398 ret
= process_userpass_input(ssh
, in
, inlen
);
3402 c_write_str(ssh
, "\r\n");
3406 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
3408 * Try public key authentication with the specified
3411 s
->tried_publickey
= 1;
3414 const char *error
= NULL
;
3415 int ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, s
->password
,
3418 c_write_str(ssh
, "Couldn't load private key from ");
3419 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
3420 c_write_str(ssh
, " (");
3421 c_write_str(ssh
, error
);
3422 c_write_str(ssh
, ").\r\n");
3423 continue; /* go and try password */
3426 c_write_str(ssh
, "Wrong passphrase.\r\n");
3427 s
->tried_publickey
= 0;
3428 continue; /* try again */
3433 * Send a public key attempt.
3435 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3436 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3439 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3440 c_write_str(ssh
, "Server refused our public key.\r\n");
3441 continue; /* go and try password */
3443 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3444 bombout(("Bizarre response to offer of public key"));
3450 unsigned char buffer
[32];
3451 Bignum challenge
, response
;
3453 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3454 bombout(("Server's RSA challenge was badly formatted"));
3457 response
= rsadecrypt(challenge
, &s
->key
);
3458 freebn(s
->key
.private_exponent
);/* burn the evidence */
3460 for (i
= 0; i
< 32; i
++) {
3461 buffer
[i
] = bignum_byte(response
, 31 - i
);
3465 MD5Update(&md5c
, buffer
, 32);
3466 MD5Update(&md5c
, s
->session_id
, 16);
3467 MD5Final(buffer
, &md5c
);
3469 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3470 PKT_DATA
, buffer
, 16, PKT_END
);
3477 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3478 if (flags
& FLAG_VERBOSE
)
3479 c_write_str(ssh
, "Failed to authenticate with"
3480 " our public key.\r\n");
3481 continue; /* go and try password */
3482 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3483 bombout(("Bizarre response to RSA authentication response"));
3487 break; /* we're through! */
3489 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
3491 * Defence against traffic analysis: we send a
3492 * whole bunch of packets containing strings of
3493 * different lengths. One of these strings is the
3494 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3495 * The others are all random data in
3496 * SSH1_MSG_IGNORE packets. This way a passive
3497 * listener can't tell which is the password, and
3498 * hence can't deduce the password length.
3500 * Anybody with a password length greater than 16
3501 * bytes is going to have enough entropy in their
3502 * password that a listener won't find it _that_
3503 * much help to know how long it is. So what we'll
3506 * - if password length < 16, we send 15 packets
3507 * containing string lengths 1 through 15
3509 * - otherwise, we let N be the nearest multiple
3510 * of 8 below the password length, and send 8
3511 * packets containing string lengths N through
3512 * N+7. This won't obscure the order of
3513 * magnitude of the password length, but it will
3514 * introduce a bit of extra uncertainty.
3516 * A few servers (the old 1.2.18 through 1.2.22)
3517 * can't deal with SSH1_MSG_IGNORE. For these
3518 * servers, we need an alternative defence. We make
3519 * use of the fact that the password is interpreted
3520 * as a C string: so we can append a NUL, then some
3523 * One server (a Cisco one) can deal with neither
3524 * SSH1_MSG_IGNORE _nor_ a padded password string.
3525 * For this server we are left with no defences
3526 * against password length sniffing.
3528 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
3530 * The server can deal with SSH1_MSG_IGNORE, so
3531 * we can use the primary defence.
3533 int bottom
, top
, pwlen
, i
;
3536 pwlen
= strlen(s
->password
);
3538 bottom
= 0; /* zero length passwords are OK! :-) */
3541 bottom
= pwlen
& ~7;
3545 assert(pwlen
>= bottom
&& pwlen
<= top
);
3547 randomstr
= snewn(top
+ 1, char);
3549 for (i
= bottom
; i
<= top
; i
++) {
3551 defer_packet(ssh
, s
->pwpkt_type
,
3552 PKTT_PASSWORD
, PKT_STR
, s
->password
,
3553 PKTT_OTHER
, PKT_END
);
3555 for (j
= 0; j
< i
; j
++) {
3557 randomstr
[j
] = random_byte();
3558 } while (randomstr
[j
] == '\0');
3560 randomstr
[i
] = '\0';
3561 defer_packet(ssh
, SSH1_MSG_IGNORE
,
3562 PKT_STR
, randomstr
, PKT_END
);
3565 logevent("Sending password with camouflage packets");
3566 ssh_pkt_defersend(ssh
);
3569 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
3571 * The server can't deal with SSH1_MSG_IGNORE
3572 * but can deal with padded passwords, so we
3573 * can use the secondary defence.
3579 len
= strlen(s
->password
);
3580 if (len
< sizeof(string
)) {
3582 strcpy(string
, s
->password
);
3583 len
++; /* cover the zero byte */
3584 while (len
< sizeof(string
)) {
3585 string
[len
++] = (char) random_byte();
3590 logevent("Sending length-padded password");
3591 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3592 PKT_INT
, len
, PKT_DATA
, ss
, len
,
3593 PKTT_OTHER
, PKT_END
);
3596 * The server has _both_
3597 * BUG_CHOKES_ON_SSH1_IGNORE and
3598 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3599 * therefore nothing we can do.
3602 len
= strlen(s
->password
);
3603 logevent("Sending unpadded password");
3604 send_packet(ssh
, s
->pwpkt_type
,
3605 PKTT_PASSWORD
, PKT_INT
, len
,
3606 PKT_DATA
, s
->password
, len
,
3607 PKTT_OTHER
, PKT_END
);
3610 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
3611 PKT_STR
, s
->password
, PKTT_OTHER
, PKT_END
);
3614 logevent("Sent password");
3615 memset(s
->password
, 0, strlen(s
->password
));
3617 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3618 if (flags
& FLAG_VERBOSE
)
3619 c_write_str(ssh
, "Access denied\r\n");
3620 logevent("Authentication refused");
3621 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3622 bombout(("Strange packet received, type %d", pktin
->type
));
3627 logevent("Authentication successful");
3632 void sshfwd_close(struct ssh_channel
*c
)
3636 if (ssh
->state
== SSH_STATE_CLOSED
)
3639 if (c
&& !c
->closes
) {
3641 * If halfopen is true, we have sent
3642 * CHANNEL_OPEN for this channel, but it hasn't even been
3643 * acknowledged by the server. So we must set a close flag
3644 * on it now, and then when the server acks the channel
3645 * open, we can close it then.
3648 if (ssh
->version
== 1) {
3649 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3652 struct Packet
*pktout
;
3653 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3654 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
3655 ssh2_pkt_send(ssh
, pktout
);
3658 c
->closes
= 1; /* sent MSG_CLOSE */
3659 if (c
->type
== CHAN_X11
) {
3661 logevent("Forwarded X11 connection terminated");
3662 } else if (c
->type
== CHAN_SOCKDATA
||
3663 c
->type
== CHAN_SOCKDATA_DORMANT
) {
3665 logevent("Forwarded port closed");
3670 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
3674 if (ssh
->state
== SSH_STATE_CLOSED
)
3677 if (ssh
->version
== 1) {
3678 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3679 PKT_INT
, c
->remoteid
,
3681 PKT_INT
, len
, PKT_DATA
, buf
, len
,
3682 PKTT_OTHER
, PKT_END
);
3684 * In SSH-1 we can return 0 here - implying that forwarded
3685 * connections are never individually throttled - because
3686 * the only circumstance that can cause throttling will be
3687 * the whole SSH connection backing up, in which case
3688 * _everything_ will be throttled as a whole.
3692 ssh2_add_channel_data(c
, buf
, len
);
3693 return ssh2_try_send(c
);
3697 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
3701 if (ssh
->state
== SSH_STATE_CLOSED
)
3704 if (ssh
->version
== 1) {
3705 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
3706 c
->v
.v1
.throttling
= 0;
3707 ssh1_throttle(ssh
, -1);
3710 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
3714 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
3716 struct queued_handler
*qh
= ssh
->qhead
;
3720 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
3723 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
3724 ssh
->packet_dispatch
[qh
->msg1
] = NULL
;
3727 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
3728 ssh
->packet_dispatch
[qh
->msg2
] = NULL
;
3732 ssh
->qhead
= qh
->next
;
3734 if (ssh
->qhead
->msg1
> 0) {
3735 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg1
] == NULL
);
3736 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
3738 if (ssh
->qhead
->msg2
> 0) {
3739 assert(ssh
->packet_dispatch
[ssh
->qhead
->msg2
] == NULL
);
3740 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
3743 ssh
->qhead
= ssh
->qtail
= NULL
;
3744 ssh
->packet_dispatch
[pktin
->type
] = NULL
;
3747 qh
->handler(ssh
, pktin
, qh
->ctx
);
3752 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
3753 chandler_fn_t handler
, void *ctx
)
3755 struct queued_handler
*qh
;
3757 qh
= snew(struct queued_handler
);
3760 qh
->handler
= handler
;
3764 if (ssh
->qtail
== NULL
) {
3768 assert(ssh
->packet_dispatch
[qh
->msg1
] == NULL
);
3769 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
3772 assert(ssh
->packet_dispatch
[qh
->msg2
] == NULL
);
3773 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
3776 ssh
->qtail
->next
= qh
;
3781 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
3783 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
3785 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
3786 SSH2_MSG_REQUEST_SUCCESS
)) {
3787 logeventf(ssh
, "Remote port forwarding from %s enabled",
3790 logeventf(ssh
, "Remote port forwarding from %s refused",
3793 rpf
= del234(ssh
->rportfwds
, pf
);
3799 static void ssh_setup_portfwd(Ssh ssh
, const Config
*cfg
)
3801 const char *portfwd_strptr
= cfg
->portfwd
;
3802 struct ssh_portfwd
*epf
;
3805 if (!ssh
->portfwds
) {
3806 ssh
->portfwds
= newtree234(ssh_portcmp
);
3809 * Go through the existing port forwardings and tag them
3810 * with status==DESTROY. Any that we want to keep will be
3811 * re-enabled (status==KEEP) as we go through the
3812 * configuration and find out which bits are the same as
3815 struct ssh_portfwd
*epf
;
3817 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3818 epf
->status
= DESTROY
;
3821 while (*portfwd_strptr
) {
3822 char address_family
, type
;
3823 int sport
,dport
,sserv
,dserv
;
3824 char sports
[256], dports
[256], saddr
[256], host
[256];
3827 address_family
= 'A';
3829 if (*portfwd_strptr
== 'A' ||
3830 *portfwd_strptr
== '4' ||
3831 *portfwd_strptr
== '6')
3832 address_family
= *portfwd_strptr
++;
3833 if (*portfwd_strptr
== 'L' ||
3834 *portfwd_strptr
== 'R' ||
3835 *portfwd_strptr
== 'D')
3836 type
= *portfwd_strptr
++;
3841 while (*portfwd_strptr
&& *portfwd_strptr
!= '\t') {
3842 if (*portfwd_strptr
== ':') {
3844 * We've seen a colon in the middle of the
3845 * source port number. This means that
3846 * everything we've seen until now is the
3847 * source _address_, so we'll move it into
3848 * saddr and start sports from the beginning
3853 if (ssh
->version
== 1 && type
== 'R') {
3854 logeventf(ssh
, "SSH-1 cannot handle remote source address "
3855 "spec \"%s\"; ignoring", sports
);
3857 strcpy(saddr
, sports
);
3860 if (n
< lenof(sports
)-1) sports
[n
++] = *portfwd_strptr
++;
3864 if (*portfwd_strptr
== '\t')
3867 while (*portfwd_strptr
&& *portfwd_strptr
!= ':') {
3868 if (n
< lenof(host
)-1) host
[n
++] = *portfwd_strptr
++;
3871 if (*portfwd_strptr
== ':')
3874 while (*portfwd_strptr
) {
3875 if (n
< lenof(dports
)-1) dports
[n
++] = *portfwd_strptr
++;
3879 dport
= atoi(dports
);
3883 dport
= net_service_lookup(dports
);
3885 logeventf(ssh
, "Service lookup failed for destination"
3886 " port \"%s\"", dports
);
3890 while (*portfwd_strptr
) portfwd_strptr
++;
3894 portfwd_strptr
++; /* eat the NUL and move to next one */
3896 sport
= atoi(sports
);
3900 sport
= net_service_lookup(sports
);
3902 logeventf(ssh
, "Service lookup failed for source"
3903 " port \"%s\"", sports
);
3906 if (sport
&& dport
) {
3907 /* Set up a description of the source port. */
3908 struct ssh_portfwd
*pfrec
, *epfrec
;
3910 pfrec
= snew(struct ssh_portfwd
);
3912 pfrec
->saddr
= *saddr ?
dupstr(saddr
) : NULL
;
3913 pfrec
->sserv
= sserv ?
dupstr(sports
) : NULL
;
3914 pfrec
->sport
= sport
;
3915 pfrec
->daddr
= *host ?
dupstr(host
) : NULL
;
3916 pfrec
->dserv
= dserv ?
dupstr(dports
) : NULL
;
3917 pfrec
->dport
= dport
;
3918 pfrec
->local
= NULL
;
3919 pfrec
->remote
= NULL
;
3920 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
3921 address_family
== '6' ? ADDRTYPE_IPV6
:
3924 epfrec
= add234(ssh
->portfwds
, pfrec
);
3925 if (epfrec
!= pfrec
) {
3927 * We already have a port forwarding with precisely
3928 * these parameters. Hence, no need to do anything;
3929 * simply tag the existing one as KEEP.
3931 epfrec
->status
= KEEP
;
3932 free_portfwd(pfrec
);
3934 pfrec
->status
= CREATE
;
3940 * Now go through and destroy any port forwardings which were
3943 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
3944 if (epf
->status
== DESTROY
) {
3947 message
= dupprintf("%s port forwarding from %s%s%d",
3948 epf
->type
== 'L' ?
"local" :
3949 epf
->type
== 'R' ?
"remote" : "dynamic",
3950 epf
->saddr ? epf
->saddr
: "",
3951 epf
->saddr ?
":" : "",
3954 if (epf
->type
!= 'D') {
3955 char *msg2
= dupprintf("%s to %s:%d", message
,
3956 epf
->daddr
, epf
->dport
);
3961 logeventf(ssh
, "Cancelling %s", message
);
3965 struct ssh_rportfwd
*rpf
= epf
->remote
;
3966 struct Packet
*pktout
;
3969 * Cancel the port forwarding at the server
3972 if (ssh
->version
== 1) {
3974 * We cannot cancel listening ports on the
3975 * server side in SSH-1! There's no message
3976 * to support it. Instead, we simply remove
3977 * the rportfwd record from the local end
3978 * so that any connections the server tries
3979 * to make on it are rejected.
3982 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
3983 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
3984 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
3986 ssh2_pkt_addstring(pktout
, epf
->saddr
);
3987 } else if (ssh
->cfg
.rport_acceptall
) {
3988 /* XXX: ssh->cfg.rport_acceptall may not represent
3989 * what was used to open the original connection,
3990 * since it's reconfigurable. */
3991 ssh2_pkt_addstring(pktout
, "0.0.0.0");
3993 ssh2_pkt_addstring(pktout
, "127.0.0.1");
3995 ssh2_pkt_adduint32(pktout
, epf
->sport
);
3996 ssh2_pkt_send(ssh
, pktout
);
3999 del234(ssh
->rportfwds
, rpf
);
4001 } else if (epf
->local
) {
4002 pfd_terminate(epf
->local
);
4005 delpos234(ssh
->portfwds
, i
);
4007 i
--; /* so we don't skip one in the list */
4011 * And finally, set up any new port forwardings (status==CREATE).
4013 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4014 if (epf
->status
== CREATE
) {
4015 char *sportdesc
, *dportdesc
;
4016 sportdesc
= dupprintf("%s%s%s%s%d%s",
4017 epf
->saddr ? epf
->saddr
: "",
4018 epf
->saddr ?
":" : "",
4019 epf
->sserv ? epf
->sserv
: "",
4020 epf
->sserv ?
"(" : "",
4022 epf
->sserv ?
")" : "");
4023 if (epf
->type
== 'D') {
4026 dportdesc
= dupprintf("%s:%s%s%d%s",
4028 epf
->dserv ? epf
->dserv
: "",
4029 epf
->dserv ?
"(" : "",
4031 epf
->dserv ?
")" : "");
4034 if (epf
->type
== 'L') {
4035 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
4036 epf
->saddr
, epf
->sport
,
4039 epf
->addressfamily
);
4041 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
4042 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4043 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4044 sportdesc
, dportdesc
,
4045 err ?
" failed: " : "", err ? err
: "");
4046 } else if (epf
->type
== 'D') {
4047 const char *err
= pfd_addforward(NULL
, -1,
4048 epf
->saddr
, epf
->sport
,
4051 epf
->addressfamily
);
4053 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
4054 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4055 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4057 err ?
" failed: " : "", err ? err
: "");
4059 struct ssh_rportfwd
*pf
;
4062 * Ensure the remote port forwardings tree exists.
4064 if (!ssh
->rportfwds
) {
4065 if (ssh
->version
== 1)
4066 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
4068 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4071 pf
= snew(struct ssh_rportfwd
);
4072 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
4073 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
4074 pf
->dport
= epf
->dport
;
4075 pf
->sport
= epf
->sport
;
4076 if (add234(ssh
->rportfwds
, pf
) != pf
) {
4077 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
4078 epf
->daddr
, epf
->dport
);
4081 logeventf(ssh
, "Requesting remote port %s"
4082 " forward to %s", sportdesc
, dportdesc
);
4084 pf
->sportdesc
= sportdesc
;
4089 if (ssh
->version
== 1) {
4090 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
4091 PKT_INT
, epf
->sport
,
4092 PKT_STR
, epf
->daddr
,
4093 PKT_INT
, epf
->dport
,
4095 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
4097 ssh_rportfwd_succfail
, pf
);
4099 struct Packet
*pktout
;
4100 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4101 ssh2_pkt_addstring(pktout
, "tcpip-forward");
4102 ssh2_pkt_addbool(pktout
, 1);/* want reply */
4104 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4105 } else if (cfg
->rport_acceptall
) {
4106 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4108 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4110 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4111 ssh2_pkt_send(ssh
, pktout
);
4113 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
4114 SSH2_MSG_REQUEST_FAILURE
,
4115 ssh_rportfwd_succfail
, pf
);
4124 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
4127 int stringlen
, bufsize
;
4129 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
4130 if (string
== NULL
) {
4131 bombout(("Incoming terminal data packet was badly formed"));
4135 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
4137 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4138 ssh
->v1_stdout_throttling
= 1;
4139 ssh1_throttle(ssh
, +1);
4143 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4145 /* Remote side is trying to open a channel to talk to our
4146 * X-Server. Give them back a local channel number. */
4147 struct ssh_channel
*c
;
4148 int remoteid
= ssh_pkt_getuint32(pktin
);
4150 logevent("Received X11 connect request");
4151 /* Refuse if X11 forwarding is disabled. */
4152 if (!ssh
->X11_fwd_enabled
) {
4153 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4154 PKT_INT
, remoteid
, PKT_END
);
4155 logevent("Rejected X11 connect request");
4157 c
= snew(struct ssh_channel
);
4160 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
4161 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
4162 logevent("Opening X11 forward connection failed");
4164 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4165 PKT_INT
, remoteid
, PKT_END
);
4168 ("Opening X11 forward connection succeeded");
4169 c
->remoteid
= remoteid
;
4170 c
->halfopen
= FALSE
;
4171 c
->localid
= alloc_channel_id(ssh
);
4173 c
->v
.v1
.throttling
= 0;
4174 c
->type
= CHAN_X11
; /* identify channel type */
4175 add234(ssh
->channels
, c
);
4176 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4177 PKT_INT
, c
->remoteid
, PKT_INT
,
4178 c
->localid
, PKT_END
);
4179 logevent("Opened X11 forward channel");
4184 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4186 /* Remote side is trying to open a channel to talk to our
4187 * agent. Give them back a local channel number. */
4188 struct ssh_channel
*c
;
4189 int remoteid
= ssh_pkt_getuint32(pktin
);
4191 /* Refuse if agent forwarding is disabled. */
4192 if (!ssh
->agentfwd_enabled
) {
4193 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4194 PKT_INT
, remoteid
, PKT_END
);
4196 c
= snew(struct ssh_channel
);
4198 c
->remoteid
= remoteid
;
4199 c
->halfopen
= FALSE
;
4200 c
->localid
= alloc_channel_id(ssh
);
4202 c
->v
.v1
.throttling
= 0;
4203 c
->type
= CHAN_AGENT
; /* identify channel type */
4204 c
->u
.a
.lensofar
= 0;
4205 add234(ssh
->channels
, c
);
4206 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4207 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4212 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4214 /* Remote side is trying to open a channel to talk to a
4215 * forwarded port. Give them back a local channel number. */
4216 struct ssh_channel
*c
;
4217 struct ssh_rportfwd pf
, *pfp
;
4222 c
= snew(struct ssh_channel
);
4225 remoteid
= ssh_pkt_getuint32(pktin
);
4226 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4227 port
= ssh_pkt_getuint32(pktin
);
4229 if (hostsize
>= lenof(pf
.dhost
))
4230 hostsize
= lenof(pf
.dhost
)-1;
4231 memcpy(pf
.dhost
, host
, hostsize
);
4232 pf
.dhost
[hostsize
] = '\0';
4234 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4237 logeventf(ssh
, "Rejected remote port open request for %s:%d",
4239 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4240 PKT_INT
, remoteid
, PKT_END
);
4242 logeventf(ssh
, "Received remote port open request for %s:%d",
4244 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4245 c
, &ssh
->cfg
, pfp
->pfrec
->addressfamily
);
4247 logeventf(ssh
, "Port open failed: %s", e
);
4249 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4250 PKT_INT
, remoteid
, PKT_END
);
4252 c
->remoteid
= remoteid
;
4253 c
->halfopen
= FALSE
;
4254 c
->localid
= alloc_channel_id(ssh
);
4256 c
->v
.v1
.throttling
= 0;
4257 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4258 add234(ssh
->channels
, c
);
4259 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4260 PKT_INT
, c
->remoteid
, PKT_INT
,
4261 c
->localid
, PKT_END
);
4262 logevent("Forwarded port opened successfully");
4267 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4269 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4270 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4271 struct ssh_channel
*c
;
4273 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4274 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4275 c
->remoteid
= localid
;
4276 c
->halfopen
= FALSE
;
4277 c
->type
= CHAN_SOCKDATA
;
4278 c
->v
.v1
.throttling
= 0;
4279 pfd_confirm(c
->u
.pfd
.s
);
4282 if (c
&& c
->closes
) {
4284 * We have a pending close on this channel,
4285 * which we decided on before the server acked
4286 * the channel open. So now we know the
4287 * remoteid, we can close it again.
4289 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
4290 PKT_INT
, c
->remoteid
, PKT_END
);
4294 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4296 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4297 struct ssh_channel
*c
;
4299 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4300 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4301 logevent("Forwarded connection refused by server");
4302 pfd_close(c
->u
.pfd
.s
);
4303 del234(ssh
->channels
, c
);
4308 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4310 /* Remote side closes a channel. */
4311 unsigned i
= ssh_pkt_getuint32(pktin
);
4312 struct ssh_channel
*c
;
4313 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4314 if (c
&& !c
->halfopen
) {
4317 (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
4319 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
4320 logevent("Forwarded X11 connection terminated");
4321 assert(c
->u
.x11
.s
!= NULL
);
4322 x11_close(c
->u
.x11
.s
);
4325 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
4326 logevent("Forwarded port closed");
4327 assert(c
->u
.pfd
.s
!= NULL
);
4328 pfd_close(c
->u
.pfd
.s
);
4332 c
->closes
|= (closetype
<< 2); /* seen this message */
4333 if (!(c
->closes
& closetype
)) {
4334 send_packet(ssh
, pktin
->type
, PKT_INT
, c
->remoteid
,
4336 c
->closes
|= closetype
; /* sent it too */
4339 if (c
->closes
== 15) {
4340 del234(ssh
->channels
, c
);
4344 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4345 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
4346 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
4351 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
4353 /* Data sent down one of our channels. */
4354 int i
= ssh_pkt_getuint32(pktin
);
4357 struct ssh_channel
*c
;
4359 ssh_pkt_getstring(pktin
, &p
, &len
);
4361 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4366 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
4369 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
4372 /* Data for an agent message. Buffer it. */
4374 if (c
->u
.a
.lensofar
< 4) {
4375 unsigned int l
= min(4 - c
->u
.a
.lensofar
, len
);
4376 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
4380 c
->u
.a
.lensofar
+= l
;
4382 if (c
->u
.a
.lensofar
== 4) {
4384 4 + GET_32BIT(c
->u
.a
.msglen
);
4385 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
4387 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4389 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
4391 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4393 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
4397 c
->u
.a
.lensofar
+= l
;
4399 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4402 if (agent_query(c
->u
.a
.message
,
4405 ssh_agentf_callback
, c
))
4406 ssh_agentf_callback(c
, reply
, replylen
);
4407 sfree(c
->u
.a
.message
);
4408 c
->u
.a
.lensofar
= 0;
4411 bufsize
= 0; /* agent channels never back up */
4414 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4415 c
->v
.v1
.throttling
= 1;
4416 ssh1_throttle(ssh
, +1);
4421 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
4423 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
4424 logeventf(ssh
, "Server sent command exit status %d", ssh
->exitcode
);
4425 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
4427 * In case `helpful' firewalls or proxies tack
4428 * extra human-readable text on the end of the
4429 * session which we might mistake for another
4430 * encrypted packet, we close the session once
4431 * we've sent EXIT_CONFIRMATION.
4433 ssh
->close_expected
= TRUE
;
4434 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
4437 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
4438 struct Packet
*pktin
)
4440 crBegin(ssh
->do_ssh1_connection_crstate
);
4442 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
4443 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
4444 ssh1_smsg_stdout_stderr_data
;
4446 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
4447 ssh1_msg_channel_open_confirmation
;
4448 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
4449 ssh1_msg_channel_open_failure
;
4450 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
4451 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
4452 ssh1_msg_channel_close
;
4453 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
4454 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
4456 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
4457 logevent("Requesting agent forwarding");
4458 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
4462 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4463 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4464 bombout(("Protocol confusion"));
4466 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4467 logevent("Agent forwarding refused");
4469 logevent("Agent forwarding enabled");
4470 ssh
->agentfwd_enabled
= TRUE
;
4471 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
4475 if (ssh
->cfg
.x11_forward
) {
4476 char proto
[20], data
[64];
4477 logevent("Requesting X11 forwarding");
4478 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
4479 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
4480 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
4481 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
4482 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4483 PKT_STR
, proto
, PKT_STR
, data
,
4484 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
4487 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
4488 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
4493 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4494 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4495 bombout(("Protocol confusion"));
4497 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4498 logevent("X11 forwarding refused");
4500 logevent("X11 forwarding enabled");
4501 ssh
->X11_fwd_enabled
= TRUE
;
4502 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
4506 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
4507 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
4509 if (!ssh
->cfg
.nopty
) {
4510 /* Unpick the terminal-speed string. */
4511 /* XXX perhaps we should allow no speeds to be sent. */
4512 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
4513 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
4514 /* Send the pty request. */
4515 send_packet(ssh
, SSH1_CMSG_REQUEST_PTY
,
4516 PKT_STR
, ssh
->cfg
.termtype
,
4517 PKT_INT
, ssh
->term_height
,
4518 PKT_INT
, ssh
->term_width
,
4519 PKT_INT
, 0, PKT_INT
, 0, /* width,height in pixels */
4520 PKT_CHAR
, 192, PKT_INT
, ssh
->ispeed
, /* TTY_OP_ISPEED */
4521 PKT_CHAR
, 193, PKT_INT
, ssh
->ospeed
, /* TTY_OP_OSPEED */
4522 PKT_CHAR
, 0, PKT_END
);
4523 ssh
->state
= SSH_STATE_INTERMED
;
4527 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4528 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4529 bombout(("Protocol confusion"));
4531 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4532 c_write_str(ssh
, "Server refused to allocate pty\r\n");
4533 ssh
->editing
= ssh
->echoing
= 1;
4535 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4536 ssh
->ospeed
, ssh
->ispeed
);
4538 ssh
->editing
= ssh
->echoing
= 1;
4541 if (ssh
->cfg
.compression
) {
4542 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
4546 if (pktin
->type
!= SSH1_SMSG_SUCCESS
4547 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
4548 bombout(("Protocol confusion"));
4550 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4551 c_write_str(ssh
, "Server refused to compress\r\n");
4553 logevent("Started compression");
4554 ssh
->v1_compressing
= TRUE
;
4555 ssh
->cs_comp_ctx
= zlib_compress_init();
4556 logevent("Initialised zlib (RFC1950) compression");
4557 ssh
->sc_comp_ctx
= zlib_decompress_init();
4558 logevent("Initialised zlib (RFC1950) decompression");
4562 * Start the shell or command.
4564 * Special case: if the first-choice command is an SSH-2
4565 * subsystem (hence not usable here) and the second choice
4566 * exists, we fall straight back to that.
4569 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
4571 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
4573 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
4574 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
4575 ssh
->fallback_cmd
= TRUE
;
4578 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
4580 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
4581 logevent("Started session");
4584 ssh
->state
= SSH_STATE_SESSION
;
4585 if (ssh
->size_needed
)
4586 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
4587 if (ssh
->eof_needed
)
4588 ssh_special(ssh
, TS_EOF
);
4591 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
4593 ssh
->channels
= newtree234(ssh_channelcmp
);
4597 * By this point, most incoming packets are already being
4598 * handled by the dispatch table, and we need only pay
4599 * attention to the unusual ones.
4604 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
4605 /* may be from EXEC_SHELL on some servers */
4606 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4607 /* may be from EXEC_SHELL on some servers
4608 * if no pty is available or in other odd cases. Ignore */
4610 bombout(("Strange packet received: type %d", pktin
->type
));
4615 int len
= min(inlen
, 512);
4616 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
, PKTT_DATA
,
4617 PKT_INT
, len
, PKT_DATA
, in
, len
,
4618 PKTT_OTHER
, PKT_END
);
4629 * Handle the top-level SSH-2 protocol.
4631 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
4636 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4637 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
4640 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
4642 /* log reason code in disconnect message */
4646 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
4647 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
4650 static void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
4652 /* Do nothing, because we're ignoring it! Duhh. */
4655 static void ssh1_protocol_setup(Ssh ssh
)
4660 * Most messages are handled by the coroutines.
4662 for (i
= 0; i
< 256; i
++)
4663 ssh
->packet_dispatch
[i
] = NULL
;
4666 * These special message types we install handlers for.
4668 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
4669 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
4670 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
4673 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
4674 struct Packet
*pktin
)
4676 unsigned char *in
=(unsigned char*)vin
;
4677 if (ssh
->state
== SSH_STATE_CLOSED
)
4680 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
4681 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
4685 if (!ssh
->protocol_initial_phase_done
) {
4686 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
4687 ssh
->protocol_initial_phase_done
= TRUE
;
4692 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
4696 * Utility routine for decoding comma-separated strings in KEXINIT.
4698 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
4701 if (!needle
|| !haystack
) /* protect against null pointers */
4703 needlen
= strlen(needle
);
4706 * Is it at the start of the string?
4708 if (haylen
>= needlen
&& /* haystack is long enough */
4709 !memcmp(needle
, haystack
, needlen
) && /* initial match */
4710 (haylen
== needlen
|| haystack
[needlen
] == ',')
4711 /* either , or EOS follows */
4715 * If not, search for the next comma and resume after that.
4716 * If no comma found, terminate.
4718 while (haylen
> 0 && *haystack
!= ',')
4719 haylen
--, haystack
++;
4722 haylen
--, haystack
++; /* skip over comma itself */
4727 * Similar routine for checking whether we have the first string in a list.
4729 static int first_in_commasep_string(char *needle
, char *haystack
, int haylen
)
4732 if (!needle
|| !haystack
) /* protect against null pointers */
4734 needlen
= strlen(needle
);
4736 * Is it at the start of the string?
4738 if (haylen
>= needlen
&& /* haystack is long enough */
4739 !memcmp(needle
, haystack
, needlen
) && /* initial match */
4740 (haylen
== needlen
|| haystack
[needlen
] == ',')
4741 /* either , or EOS follows */
4749 * SSH-2 key creation method.
4751 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
,
4752 unsigned char *sessid
, char chr
,
4753 unsigned char *keyspace
)
4756 /* First 20 bytes. */
4758 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4760 SHA_Bytes(&s
, H
, 20);
4761 SHA_Bytes(&s
, &chr
, 1);
4762 SHA_Bytes(&s
, sessid
, 20);
4763 SHA_Final(&s
, keyspace
);
4764 /* Next 20 bytes. */
4766 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
4768 SHA_Bytes(&s
, H
, 20);
4769 SHA_Bytes(&s
, keyspace
, 20);
4770 SHA_Final(&s
, keyspace
+ 20);
4774 * Handle the SSH-2 transport layer.
4776 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
4777 struct Packet
*pktin
)
4779 unsigned char *in
= (unsigned char *)vin
;
4780 struct do_ssh2_transport_state
{
4781 int nbits
, pbits
, warn_kex
, warn_cscipher
, warn_sccipher
;
4782 Bignum p
, g
, e
, f
, K
;
4783 int kex_init_value
, kex_reply_value
;
4784 const struct ssh_mac
**maclist
;
4786 const struct ssh2_cipher
*cscipher_tobe
;
4787 const struct ssh2_cipher
*sccipher_tobe
;
4788 const struct ssh_mac
*csmac_tobe
;
4789 const struct ssh_mac
*scmac_tobe
;
4790 const struct ssh_compress
*cscomp_tobe
;
4791 const struct ssh_compress
*sccomp_tobe
;
4792 char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
4793 int hostkeylen
, siglen
;
4794 void *hkey
; /* actual host key */
4795 unsigned char exchange_hash
[20];
4796 int n_preferred_kex
;
4797 const struct ssh_kex
*preferred_kex
[KEX_MAX
];
4798 int n_preferred_ciphers
;
4799 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
4800 const struct ssh_compress
*preferred_comp
;
4801 int got_session_id
, activated_authconn
;
4802 struct Packet
*pktout
;
4807 crState(do_ssh2_transport_state
);
4809 crBegin(ssh
->do_ssh2_transport_crstate
);
4811 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
4812 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
4813 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
4815 s
->got_session_id
= s
->activated_authconn
= FALSE
;
4818 * Be prepared to work around the buggy MAC problem.
4820 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
4821 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
4823 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
4826 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_KEX_MASK
;
4828 int i
, j
, commalist_started
;
4831 * Set up the preferred key exchange. (NULL => warn below here)
4833 s
->n_preferred_kex
= 0;
4834 for (i
= 0; i
< KEX_MAX
; i
++) {
4835 switch (ssh
->cfg
.ssh_kexlist
[i
]) {
4837 s
->preferred_kex
[s
->n_preferred_kex
++] =
4838 &ssh_diffiehellman_gex
;
4841 s
->preferred_kex
[s
->n_preferred_kex
++] =
4842 &ssh_diffiehellman_group14
;
4845 s
->preferred_kex
[s
->n_preferred_kex
++] =
4846 &ssh_diffiehellman_group1
;
4849 /* Flag for later. Don't bother if it's the last in
4851 if (i
< KEX_MAX
- 1) {
4852 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
4859 * Set up the preferred ciphers. (NULL => warn below here)
4861 s
->n_preferred_ciphers
= 0;
4862 for (i
= 0; i
< CIPHER_MAX
; i
++) {
4863 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
4864 case CIPHER_BLOWFISH
:
4865 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
4868 if (ssh
->cfg
.ssh2_des_cbc
) {
4869 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
4873 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
4876 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
4878 case CIPHER_ARCFOUR
:
4879 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_arcfour
;
4882 /* Flag for later. Don't bother if it's the last in
4884 if (i
< CIPHER_MAX
- 1) {
4885 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
4892 * Set up preferred compression.
4894 if (ssh
->cfg
.compression
)
4895 s
->preferred_comp
= &ssh_zlib
;
4897 s
->preferred_comp
= &ssh_comp_none
;
4900 * Enable queueing of outgoing auth- or connection-layer
4901 * packets while we are in the middle of a key exchange.
4903 ssh
->queueing
= TRUE
;
4906 * Flag that KEX is in progress.
4908 ssh
->kex_in_progress
= TRUE
;
4911 * Construct and send our key exchange packet.
4913 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
4914 for (i
= 0; i
< 16; i
++)
4915 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
4916 /* List key exchange algorithms. */
4917 ssh2_pkt_addstring_start(s
->pktout
);
4918 commalist_started
= 0;
4919 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
4920 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
4921 if (!k
) continue; /* warning flag */
4922 if (commalist_started
)
4923 ssh2_pkt_addstring_str(s
->pktout
, ",");
4924 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_kex
[i
]->name
);
4925 commalist_started
= 1;
4927 /* List server host key algorithms. */
4928 ssh2_pkt_addstring_start(s
->pktout
);
4929 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
4930 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
4931 if (i
< lenof(hostkey_algs
) - 1)
4932 ssh2_pkt_addstring_str(s
->pktout
, ",");
4934 /* List client->server encryption algorithms. */
4935 ssh2_pkt_addstring_start(s
->pktout
);
4936 commalist_started
= 0;
4937 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4938 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4939 if (!c
) continue; /* warning flag */
4940 for (j
= 0; j
< c
->nciphers
; j
++) {
4941 if (commalist_started
)
4942 ssh2_pkt_addstring_str(s
->pktout
, ",");
4943 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4944 commalist_started
= 1;
4947 /* List server->client encryption algorithms. */
4948 ssh2_pkt_addstring_start(s
->pktout
);
4949 commalist_started
= 0;
4950 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
4951 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
4952 if (!c
) continue; /* warning flag */
4953 for (j
= 0; j
< c
->nciphers
; j
++) {
4954 if (commalist_started
)
4955 ssh2_pkt_addstring_str(s
->pktout
, ",");
4956 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
4957 commalist_started
= 1;
4960 /* List client->server MAC algorithms. */
4961 ssh2_pkt_addstring_start(s
->pktout
);
4962 for (i
= 0; i
< s
->nmacs
; i
++) {
4963 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4964 if (i
< s
->nmacs
- 1)
4965 ssh2_pkt_addstring_str(s
->pktout
, ",");
4967 /* List server->client MAC algorithms. */
4968 ssh2_pkt_addstring_start(s
->pktout
);
4969 for (i
= 0; i
< s
->nmacs
; i
++) {
4970 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
4971 if (i
< s
->nmacs
- 1)
4972 ssh2_pkt_addstring_str(s
->pktout
, ",");
4974 /* List client->server compression algorithms. */
4975 ssh2_pkt_addstring_start(s
->pktout
);
4976 assert(lenof(compressions
) > 1);
4977 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4978 for (i
= 0; i
< lenof(compressions
); i
++) {
4979 const struct ssh_compress
*c
= compressions
[i
];
4980 if (c
!= s
->preferred_comp
) {
4981 ssh2_pkt_addstring_str(s
->pktout
, ",");
4982 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4985 /* List server->client compression algorithms. */
4986 ssh2_pkt_addstring_start(s
->pktout
);
4987 assert(lenof(compressions
) > 1);
4988 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
4989 for (i
= 0; i
< lenof(compressions
); i
++) {
4990 const struct ssh_compress
*c
= compressions
[i
];
4991 if (c
!= s
->preferred_comp
) {
4992 ssh2_pkt_addstring_str(s
->pktout
, ",");
4993 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
4996 /* List client->server languages. Empty list. */
4997 ssh2_pkt_addstring_start(s
->pktout
);
4998 /* List server->client languages. Empty list. */
4999 ssh2_pkt_addstring_start(s
->pktout
);
5000 /* First KEX packet does _not_ follow, because we're not that brave. */
5001 ssh2_pkt_addbool(s
->pktout
, FALSE
);
5003 ssh2_pkt_adduint32(s
->pktout
, 0);
5006 ssh
->exhash
= ssh
->exhashbase
;
5007 sha_string(&ssh
->exhash
, s
->pktout
->data
+ 5, s
->pktout
->length
- 5);
5009 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5013 if (pktin
->length
> 5)
5014 sha_string(&ssh
->exhash
, pktin
->data
+ 5, pktin
->length
- 5);
5017 * Now examine the other side's KEXINIT to see what we're up
5021 char *str
, *preferred
;
5024 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
5025 bombout(("expected key exchange packet from server"));
5029 ssh
->hostkey
= NULL
;
5030 s
->cscipher_tobe
= NULL
;
5031 s
->sccipher_tobe
= NULL
;
5032 s
->csmac_tobe
= NULL
;
5033 s
->scmac_tobe
= NULL
;
5034 s
->cscomp_tobe
= NULL
;
5035 s
->sccomp_tobe
= NULL
;
5036 s
->warn_kex
= s
->warn_cscipher
= s
->warn_sccipher
= FALSE
;
5038 pktin
->savedpos
+= 16; /* skip garbage cookie */
5039 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
5042 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5043 const struct ssh_kex
*k
= s
->preferred_kex
[i
];
5047 if (!preferred
) preferred
= k
->name
;
5048 if (in_commasep_string(k
->name
, str
, len
))
5055 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5056 str ? str
: "(null)"));
5060 * Note that the server's guess is considered wrong if it doesn't match
5061 * the first algorithm in our list, even if it's still the algorithm
5064 s
->guessok
= first_in_commasep_string(preferred
, str
, len
);
5065 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
5066 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5067 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
5068 ssh
->hostkey
= hostkey_algs
[i
];
5072 s
->guessok
= s
->guessok
&&
5073 first_in_commasep_string(hostkey_algs
[0]->name
, str
, len
);
5074 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
5075 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5076 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5078 s
->warn_cscipher
= TRUE
;
5080 for (j
= 0; j
< c
->nciphers
; j
++) {
5081 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5082 s
->cscipher_tobe
= c
->list
[j
];
5087 if (s
->cscipher_tobe
)
5090 if (!s
->cscipher_tobe
) {
5091 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5092 str ? str
: "(null)"));
5096 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
5097 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5098 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5100 s
->warn_sccipher
= TRUE
;
5102 for (j
= 0; j
< c
->nciphers
; j
++) {
5103 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5104 s
->sccipher_tobe
= c
->list
[j
];
5109 if (s
->sccipher_tobe
)
5112 if (!s
->sccipher_tobe
) {
5113 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5114 str ? str
: "(null)"));
5118 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
5119 for (i
= 0; i
< s
->nmacs
; i
++) {
5120 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5121 s
->csmac_tobe
= s
->maclist
[i
];
5125 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
5126 for (i
= 0; i
< s
->nmacs
; i
++) {
5127 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5128 s
->scmac_tobe
= s
->maclist
[i
];
5132 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
5133 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5134 const struct ssh_compress
*c
=
5135 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5136 if (in_commasep_string(c
->name
, str
, len
)) {
5141 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
5142 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5143 const struct ssh_compress
*c
=
5144 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5145 if (in_commasep_string(c
->name
, str
, len
)) {
5150 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server language */
5151 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client language */
5152 s
->ignorepkt
= ssh2_pkt_getbool(pktin
) && !s
->guessok
;
5155 ssh_set_frozen(ssh
, 1);
5156 s
->dlgret
= askalg(ssh
->frontend
, "key-exchange algorithm",
5158 ssh_dialog_callback
, ssh
);
5159 if (s
->dlgret
< 0) {
5163 bombout(("Unexpected data from server while"
5164 " waiting for user response"));
5167 } while (pktin
|| inlen
> 0);
5168 s
->dlgret
= ssh
->user_response
;
5170 ssh_set_frozen(ssh
, 0);
5171 if (s
->dlgret
== 0) {
5172 ssh
->close_expected
= TRUE
;
5173 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5178 if (s
->warn_cscipher
) {
5179 ssh_set_frozen(ssh
, 1);
5180 s
->dlgret
= askalg(ssh
->frontend
,
5181 "client-to-server cipher",
5182 s
->cscipher_tobe
->name
,
5183 ssh_dialog_callback
, ssh
);
5184 if (s
->dlgret
< 0) {
5188 bombout(("Unexpected data from server while"
5189 " waiting for user response"));
5192 } while (pktin
|| inlen
> 0);
5193 s
->dlgret
= ssh
->user_response
;
5195 ssh_set_frozen(ssh
, 0);
5196 if (s
->dlgret
== 0) {
5197 ssh
->close_expected
= TRUE
;
5198 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5203 if (s
->warn_sccipher
) {
5204 ssh_set_frozen(ssh
, 1);
5205 s
->dlgret
= askalg(ssh
->frontend
,
5206 "server-to-client cipher",
5207 s
->sccipher_tobe
->name
,
5208 ssh_dialog_callback
, ssh
);
5209 if (s
->dlgret
< 0) {
5213 bombout(("Unexpected data from server while"
5214 " waiting for user response"));
5217 } while (pktin
|| inlen
> 0);
5218 s
->dlgret
= ssh
->user_response
;
5220 ssh_set_frozen(ssh
, 0);
5221 if (s
->dlgret
== 0) {
5222 ssh
->close_expected
= TRUE
;
5223 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5228 if (s
->ignorepkt
) /* first_kex_packet_follows */
5229 crWaitUntil(pktin
); /* Ignore packet */
5233 * Work out the number of bits of key we will need from the key
5234 * exchange. We start with the maximum key length of either
5240 csbits
= s
->cscipher_tobe
->keylen
;
5241 scbits
= s
->sccipher_tobe
->keylen
;
5242 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5244 /* The keys only have 160-bit entropy, since they're based on
5245 * a SHA-1 hash. So cap the key size at 160 bits. */
5250 * If we're doing Diffie-Hellman group exchange, start by
5251 * requesting a group.
5253 if (!ssh
->kex
->pdata
) {
5254 logevent("Doing Diffie-Hellman group exchange");
5255 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
5257 * Work out how big a DH group we will need to allow that
5260 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
5261 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
5262 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
5263 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5266 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
5267 bombout(("expected key exchange group packet from server"));
5270 s
->p
= ssh2_pkt_getmp(pktin
);
5271 s
->g
= ssh2_pkt_getmp(pktin
);
5272 if (!s
->p
|| !s
->g
) {
5273 bombout(("unable to read mp-ints from incoming group packet"));
5276 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
5277 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
5278 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
5280 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP
;
5281 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
5282 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
5283 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
5284 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
5285 ssh
->kex
->groupname
);
5288 logevent("Doing Diffie-Hellman key exchange");
5290 * Now generate and send e for Diffie-Hellman.
5292 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* this can take a while */
5293 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
5294 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
5295 ssh2_pkt_addmp(s
->pktout
, s
->e
);
5296 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5298 set_busy_status(ssh
->frontend
, BUSY_WAITING
); /* wait for server */
5300 if (pktin
->type
!= s
->kex_reply_value
) {
5301 bombout(("expected key exchange reply packet from server"));
5304 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* cogitate */
5305 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
5306 s
->f
= ssh2_pkt_getmp(pktin
);
5308 bombout(("unable to parse key exchange reply packet"));
5311 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
5313 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
5315 /* We assume everything from now on will be quick, and it might
5316 * involve user interaction. */
5317 set_busy_status(ssh
->frontend
, BUSY_NOT
);
5319 sha_string(&ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
5320 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5321 sha_uint32(&ssh
->exhash
, s
->pbits
);
5322 sha_mpint(&ssh
->exhash
, s
->p
);
5323 sha_mpint(&ssh
->exhash
, s
->g
);
5325 sha_mpint(&ssh
->exhash
, s
->e
);
5326 sha_mpint(&ssh
->exhash
, s
->f
);
5327 sha_mpint(&ssh
->exhash
, s
->K
);
5328 SHA_Final(&ssh
->exhash
, s
->exchange_hash
);
5330 dh_cleanup(ssh
->kex_ctx
);
5331 ssh
->kex_ctx
= NULL
;
5334 debug(("Exchange hash is:\n"));
5335 dmemdump(s
->exchange_hash
, 20);
5338 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
5340 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
5341 (char *)s
->exchange_hash
, 20)) {
5342 bombout(("Server's host key did not match the signature supplied"));
5347 * Authenticate remote host: verify host key. (We've already
5348 * checked the signature of the exchange hash.)
5350 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
5351 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
5352 ssh_set_frozen(ssh
, 1);
5353 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
5354 ssh
->savedhost
, ssh
->savedport
,
5355 ssh
->hostkey
->keytype
, s
->keystr
,
5357 ssh_dialog_callback
, ssh
);
5358 if (s
->dlgret
< 0) {
5362 bombout(("Unexpected data from server while waiting"
5363 " for user host key response"));
5366 } while (pktin
|| inlen
> 0);
5367 s
->dlgret
= ssh
->user_response
;
5369 ssh_set_frozen(ssh
, 0);
5370 if (s
->dlgret
== 0) {
5371 ssh
->close_expected
= TRUE
;
5372 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5375 if (!s
->got_session_id
) { /* don't bother logging this in rekeys */
5376 logevent("Host key fingerprint is:");
5377 logevent(s
->fingerprint
);
5379 sfree(s
->fingerprint
);
5381 ssh
->hostkey
->freekey(s
->hkey
);
5384 * The exchange hash from the very first key exchange is also
5385 * the session id, used in session key construction and
5388 if (!s
->got_session_id
) {
5389 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
5390 sizeof(s
->exchange_hash
));
5391 s
->got_session_id
= TRUE
;
5395 * Send SSH2_MSG_NEWKEYS.
5397 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
5398 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5399 ssh
->outgoing_data_size
= 0; /* start counting from here */
5402 * We've sent client NEWKEYS, so create and initialise
5403 * client-to-server session keys.
5405 if (ssh
->cs_cipher_ctx
)
5406 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
5407 ssh
->cscipher
= s
->cscipher_tobe
;
5408 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
5410 if (ssh
->cs_mac_ctx
)
5411 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
5412 ssh
->csmac
= s
->csmac_tobe
;
5413 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
5415 if (ssh
->cs_comp_ctx
)
5416 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
5417 ssh
->cscomp
= s
->cscomp_tobe
;
5418 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
5421 * Set IVs on client-to-server keys. Here we use the exchange
5422 * hash from the _first_ key exchange.
5425 unsigned char keyspace
[40];
5426 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'C',keyspace
);
5427 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
5428 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'A',keyspace
);
5429 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
5430 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'E',keyspace
);
5431 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
5434 logeventf(ssh
, "Initialised %.200s client->server encryption",
5435 ssh
->cscipher
->text_name
);
5436 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
5437 ssh
->csmac
->text_name
);
5438 if (ssh
->cscomp
->text_name
)
5439 logeventf(ssh
, "Initialised %s compression",
5440 ssh
->cscomp
->text_name
);
5443 * Now our end of the key exchange is complete, we can send all
5444 * our queued higher-layer packets.
5446 ssh
->queueing
= FALSE
;
5447 ssh2_pkt_queuesend(ssh
);
5450 * Expect SSH2_MSG_NEWKEYS from server.
5453 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
5454 bombout(("expected new-keys packet from server"));
5457 ssh
->incoming_data_size
= 0; /* start counting from here */
5460 * We've seen server NEWKEYS, so create and initialise
5461 * server-to-client session keys.
5463 if (ssh
->sc_cipher_ctx
)
5464 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
5465 ssh
->sccipher
= s
->sccipher_tobe
;
5466 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
5468 if (ssh
->sc_mac_ctx
)
5469 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
5470 ssh
->scmac
= s
->scmac_tobe
;
5471 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
5473 if (ssh
->sc_comp_ctx
)
5474 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
5475 ssh
->sccomp
= s
->sccomp_tobe
;
5476 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
5479 * Set IVs on server-to-client keys. Here we use the exchange
5480 * hash from the _first_ key exchange.
5483 unsigned char keyspace
[40];
5484 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'D',keyspace
);
5485 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
5486 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'B',keyspace
);
5487 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
5488 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'F',keyspace
);
5489 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
5491 logeventf(ssh
, "Initialised %.200s server->client encryption",
5492 ssh
->sccipher
->text_name
);
5493 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
5494 ssh
->scmac
->text_name
);
5495 if (ssh
->sccomp
->text_name
)
5496 logeventf(ssh
, "Initialised %s decompression",
5497 ssh
->sccomp
->text_name
);
5500 * Free key exchange data.
5504 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
5510 * Key exchange is over. Loop straight back round if we have a
5511 * deferred rekey reason.
5513 if (ssh
->deferred_rekey_reason
) {
5514 logevent(ssh
->deferred_rekey_reason
);
5516 ssh
->deferred_rekey_reason
= NULL
;
5517 goto begin_key_exchange
;
5521 * Otherwise, schedule a timer for our next rekey.
5523 ssh
->kex_in_progress
= FALSE
;
5524 ssh
->last_rekey
= GETTICKCOUNT();
5525 if (ssh
->cfg
.ssh_rekey_time
!= 0)
5526 ssh
->next_rekey
= schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
5530 * If this is the first key exchange phase, we must pass the
5531 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5532 * wants to see it but because it will need time to initialise
5533 * itself before it sees an actual packet. In subsequent key
5534 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5535 * it would only confuse the layer above.
5537 if (s
->activated_authconn
) {
5540 s
->activated_authconn
= TRUE
;
5543 * Now we're encrypting. Begin returning 1 to the protocol main
5544 * function so that other things can run on top of the
5545 * transport. If we ever see a KEXINIT, we must go back to the
5548 * We _also_ go back to the start if we see pktin==NULL and
5549 * inlen==-1, because this is a special signal meaning
5550 * `initiate client-driven rekey', and `in' contains a message
5551 * giving the reason for the rekey.
5553 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
5554 (!pktin
&& inlen
== -1))) {
5559 logevent("Server initiated key re-exchange");
5562 * Special case: if the server bug is set that doesn't
5563 * allow rekeying, we give a different log message and
5564 * continue waiting. (If such a server _initiates_ a rekey,
5565 * we process it anyway!)
5567 if ((ssh
->remote_bugs
& BUG_SSH2_REKEY
)) {
5568 logeventf(ssh
, "Server bug prevents key re-exchange (%s)",
5570 /* Reset the counters, so that at least this message doesn't
5571 * hit the event log _too_ often. */
5572 ssh
->outgoing_data_size
= 0;
5573 ssh
->incoming_data_size
= 0;
5574 if (ssh
->cfg
.ssh_rekey_time
!= 0) {
5576 schedule_timer(ssh
->cfg
.ssh_rekey_time
*60*TICKSPERSEC
,
5579 goto wait_for_rekey
; /* this is utterly horrid */
5581 logeventf(ssh
, "Initiating key re-exchange (%s)", (char *)in
);
5584 goto begin_key_exchange
;
5590 * Add data to an SSH-2 channel output buffer.
5592 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
5595 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
5599 * Attempt to send data on an SSH-2 channel.
5601 static int ssh2_try_send(struct ssh_channel
*c
)
5604 struct Packet
*pktout
;
5606 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
5609 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
5610 if ((unsigned)len
> c
->v
.v2
.remwindow
)
5611 len
= c
->v
.v2
.remwindow
;
5612 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
5613 len
= c
->v
.v2
.remmaxpkt
;
5614 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
5615 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5616 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
5617 ssh2_pkt_addstring_start(pktout
);
5618 ssh2_pkt_addstring_data(pktout
, data
, len
);
5619 end_log_omission(ssh
, pktout
);
5620 ssh2_pkt_send(ssh
, pktout
);
5621 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
5622 c
->v
.v2
.remwindow
-= len
;
5626 * After having sent as much data as we can, return the amount
5629 return bufchain_size(&c
->v
.v2
.outbuffer
);
5632 static void ssh2_try_send_and_unthrottle(struct ssh_channel
*c
)
5636 return; /* don't send on closing channels */
5637 bufsize
= ssh2_try_send(c
);
5640 case CHAN_MAINSESSION
:
5641 /* stdin need not receive an unthrottle
5642 * notification since it will be polled */
5645 x11_unthrottle(c
->u
.x11
.s
);
5648 /* agent sockets are request/response and need no
5649 * buffer management */
5652 pfd_unthrottle(c
->u
.pfd
.s
);
5659 * Potentially enlarge the window on an SSH-2 channel.
5661 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
5666 * Never send WINDOW_ADJUST for a channel that the remote side
5667 * already thinks it's closed; there's no point, since it won't
5668 * be sending any more data anyway.
5674 * Only send a WINDOW_ADJUST if there's significantly more window
5675 * available than the other end thinks there is. This saves us
5676 * sending a WINDOW_ADJUST for every character in a shell session.
5678 * "Significant" is arbitrarily defined as half the window size.
5680 if (newwin
> c
->v
.v2
.locwindow
* 2) {
5681 struct Packet
*pktout
;
5683 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5684 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5685 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
5686 ssh2_pkt_send(ssh
, pktout
);
5687 c
->v
.v2
.locwindow
= newwin
;
5691 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
5693 unsigned i
= ssh_pkt_getuint32(pktin
);
5694 struct ssh_channel
*c
;
5695 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5696 if (c
&& !c
->closes
) {
5697 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
5698 ssh2_try_send_and_unthrottle(c
);
5702 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
5706 unsigned i
= ssh_pkt_getuint32(pktin
);
5707 struct ssh_channel
*c
;
5708 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5710 return; /* nonexistent channel */
5711 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5712 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
5713 return; /* extended but not stderr */
5714 ssh_pkt_getstring(pktin
, &data
, &length
);
5717 c
->v
.v2
.locwindow
-= length
;
5719 case CHAN_MAINSESSION
:
5721 from_backend(ssh
->frontend
, pktin
->type
==
5722 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5726 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5729 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5732 while (length
> 0) {
5733 if (c
->u
.a
.lensofar
< 4) {
5734 unsigned int l
= min(4 - c
->u
.a
.lensofar
, length
);
5735 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5739 c
->u
.a
.lensofar
+= l
;
5741 if (c
->u
.a
.lensofar
== 4) {
5743 4 + GET_32BIT(c
->u
.a
.msglen
);
5744 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
5746 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5748 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5750 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5752 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5756 c
->u
.a
.lensofar
+= l
;
5758 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5761 if (agent_query(c
->u
.a
.message
,
5764 ssh_agentf_callback
, c
))
5765 ssh_agentf_callback(c
, reply
, replylen
);
5766 sfree(c
->u
.a
.message
);
5767 c
->u
.a
.lensofar
= 0;
5774 * If we are not buffering too much data,
5775 * enlarge the window again at the remote side.
5777 if (bufsize
< OUR_V2_WINSIZE
)
5778 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5782 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
5784 unsigned i
= ssh_pkt_getuint32(pktin
);
5785 struct ssh_channel
*c
;
5787 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5789 return; /* nonexistent channel */
5791 if (c
->type
== CHAN_X11
) {
5793 * Remote EOF on an X11 channel means we should
5794 * wrap up and close the channel ourselves.
5796 x11_close(c
->u
.x11
.s
);
5798 } else if (c
->type
== CHAN_AGENT
) {
5800 } else if (c
->type
== CHAN_SOCKDATA
) {
5801 pfd_close(c
->u
.pfd
.s
);
5806 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
5808 unsigned i
= ssh_pkt_getuint32(pktin
);
5809 struct ssh_channel
*c
;
5810 struct Packet
*pktout
;
5812 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5813 if (!c
|| c
->halfopen
) {
5814 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5815 c ?
"half-open" : "nonexistent", i
));
5818 /* Do pre-close processing on the channel. */
5820 case CHAN_MAINSESSION
:
5821 ssh
->mainchan
= NULL
;
5822 update_specials_menu(ssh
->frontend
);
5825 if (c
->u
.x11
.s
!= NULL
)
5826 x11_close(c
->u
.x11
.s
);
5833 if (c
->u
.pfd
.s
!= NULL
)
5834 pfd_close(c
->u
.pfd
.s
);
5838 if (c
->closes
== 0) {
5839 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5840 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5841 ssh2_pkt_send(ssh
, pktout
);
5843 del234(ssh
->channels
, c
);
5844 bufchain_clear(&c
->v
.v2
.outbuffer
);
5848 * See if that was the last channel left open.
5849 * (This is only our termination condition if we're
5850 * not running in -N mode.)
5852 if (!ssh
->cfg
.ssh_no_shell
&& count234(ssh
->channels
) == 0) {
5853 logevent("All channels closed. Disconnecting");
5856 * We used to send SSH_MSG_DISCONNECT here,
5857 * because I'd believed that _every_ conforming
5858 * SSH-2 connection had to end with a disconnect
5859 * being sent by at least one side; apparently
5860 * I was wrong and it's perfectly OK to
5861 * unceremoniously slam the connection shut
5862 * when you're done, and indeed OpenSSH feels
5863 * this is more polite than sending a
5864 * DISCONNECT. So now we don't.
5866 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5867 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
5868 ssh2_pkt_addstring(s
->pktout
, "All open channels closed");
5869 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
5870 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5872 ssh
->close_expected
= TRUE
;
5873 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5877 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
5879 unsigned i
= ssh_pkt_getuint32(pktin
);
5880 struct ssh_channel
*c
;
5881 struct Packet
*pktout
;
5883 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5885 return; /* nonexistent channel */
5886 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5887 return; /* dunno why they're confirming this */
5888 c
->remoteid
= ssh_pkt_getuint32(pktin
);
5889 c
->halfopen
= FALSE
;
5890 c
->type
= CHAN_SOCKDATA
;
5891 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
5892 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
5894 pfd_confirm(c
->u
.pfd
.s
);
5897 * We have a pending close on this channel,
5898 * which we decided on before the server acked
5899 * the channel open. So now we know the
5900 * remoteid, we can close it again.
5902 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5903 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
5904 ssh2_pkt_send(ssh
, pktout
);
5908 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
5910 static const char *const reasons
[] = {
5911 "<unknown reason code>",
5912 "Administratively prohibited",
5914 "Unknown channel type",
5915 "Resource shortage",
5917 unsigned i
= ssh_pkt_getuint32(pktin
);
5918 unsigned reason_code
;
5919 char *reason_string
;
5921 struct ssh_channel
*c
;
5922 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5924 return; /* nonexistent channel */
5925 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5926 return; /* dunno why they're failing this */
5928 reason_code
= ssh_pkt_getuint32(pktin
);
5929 if (reason_code
>= lenof(reasons
))
5930 reason_code
= 0; /* ensure reasons[reason_code] in range */
5931 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
5932 logeventf(ssh
, "Forwarded connection refused by server: %s [%.*s]",
5933 reasons
[reason_code
], reason_length
, reason_string
);
5935 pfd_close(c
->u
.pfd
.s
);
5937 del234(ssh
->channels
, c
);
5941 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
5945 int typelen
, want_reply
;
5946 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
5947 struct ssh_channel
*c
;
5948 struct Packet
*pktout
;
5950 localid
= ssh_pkt_getuint32(pktin
);
5951 ssh_pkt_getstring(pktin
, &type
, &typelen
);
5952 want_reply
= ssh2_pkt_getbool(pktin
);
5955 * First, check that the channel exists. Otherwise,
5956 * we can instantly disconnect with a rude message.
5958 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
5961 sprintf(buf
, "Received channel request for nonexistent"
5962 " channel %d", localid
);
5964 pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5965 ssh2_pkt_adduint32(pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
5966 ssh2_pkt_addstring(pktout
, buf
);
5967 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
5968 ssh2_pkt_send_noqueue(ssh
, pktout
);
5969 connection_fatal(ssh
->frontend
, "%s", buf
);
5970 ssh
->close_expected
= TRUE
;
5971 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
5976 * Having got the channel number, we now look at
5977 * the request type string to see if it's something
5980 if (c
== ssh
->mainchan
) {
5982 * We recognise "exit-status" and "exit-signal" on
5983 * the primary channel.
5985 if (typelen
== 11 &&
5986 !memcmp(type
, "exit-status", 11)) {
5988 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
5989 logeventf(ssh
, "Server sent command exit status %d",
5991 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
5993 } else if (typelen
== 11 &&
5994 !memcmp(type
, "exit-signal", 11)) {
5996 int is_plausible
= TRUE
, is_int
= FALSE
;
5997 char *fmt_sig
= "", *fmt_msg
= "";
5999 int msglen
= 0, core
= FALSE
;
6000 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6001 * provide an `int' for the signal, despite its
6002 * having been a `string' in the drafts since at
6003 * least 2001. (Fixed in session.c 1.147.) Try to
6004 * infer which we can safely parse it as. */
6006 unsigned char *p
= pktin
->body
+
6008 long len
= pktin
->length
- pktin
->savedpos
;
6009 unsigned long num
= GET_32BIT(p
); /* what is it? */
6010 /* If it's 0, it hardly matters; assume string */
6014 int maybe_int
= FALSE
, maybe_str
= FALSE
;
6015 #define CHECK_HYPOTHESIS(offset, result) \
6018 if (q >= 0 && q+4 <= len) { \
6019 q = q + 4 + GET_32BIT(p+q); \
6020 if (q >= 0 && q+4 <= len && \
6021 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6025 CHECK_HYPOTHESIS(4+1, maybe_int
);
6026 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
6027 #undef CHECK_HYPOTHESIS
6028 if (maybe_int
&& !maybe_str
)
6030 else if (!maybe_int
&& maybe_str
)
6033 /* Crikey. Either or neither. Panic. */
6034 is_plausible
= FALSE
;
6039 /* Old non-standard OpenSSH. */
6040 int signum
= ssh_pkt_getuint32(pktin
);
6041 fmt_sig
= dupprintf(" %d", signum
);
6043 /* As per the drafts. */
6046 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
6047 /* Signal name isn't supposed to be blank, but
6048 * let's cope gracefully if it is. */
6050 fmt_sig
= dupprintf(" \"%.*s\"",
6054 core
= ssh2_pkt_getbool(pktin
);
6055 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
6057 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
6059 /* ignore lang tag */
6060 } /* else don't attempt to parse */
6061 logeventf(ssh
, "Server exited on signal%s%s%s",
6062 fmt_sig
, core ?
" (core dumped)" : "",
6064 if (*fmt_sig
) sfree(fmt_sig
);
6065 if (*fmt_msg
) sfree(fmt_msg
);
6066 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
6071 * This is a channel request we don't know
6072 * about, so we now either ignore the request
6073 * or respond with CHANNEL_FAILURE, depending
6076 reply
= SSH2_MSG_CHANNEL_FAILURE
;
6079 pktout
= ssh2_pkt_init(reply
);
6080 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6081 ssh2_pkt_send(ssh
, pktout
);
6085 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
6088 int typelen
, want_reply
;
6089 struct Packet
*pktout
;
6091 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6092 want_reply
= ssh2_pkt_getbool(pktin
);
6095 * We currently don't support any global requests
6096 * at all, so we either ignore the request or
6097 * respond with REQUEST_FAILURE, depending on
6101 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
6102 ssh2_pkt_send(ssh
, pktout
);
6106 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
6114 struct ssh_channel
*c
;
6115 unsigned remid
, winsize
, pktsize
;
6116 struct Packet
*pktout
;
6118 ssh_pkt_getstring(pktin
, &type
, &typelen
);
6119 c
= snew(struct ssh_channel
);
6122 remid
= ssh_pkt_getuint32(pktin
);
6123 winsize
= ssh_pkt_getuint32(pktin
);
6124 pktsize
= ssh_pkt_getuint32(pktin
);
6126 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
6129 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6130 addrstr
= snewn(peeraddrlen
+1, char);
6131 memcpy(addrstr
, peeraddr
, peeraddrlen
);
6132 addrstr
[peeraddrlen
] = '\0';
6133 peerport
= ssh_pkt_getuint32(pktin
);
6135 logeventf(ssh
, "Received X11 connect request from %s:%d",
6138 if (!ssh
->X11_fwd_enabled
)
6139 error
= "X11 forwarding is not enabled";
6140 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
6141 ssh
->x11auth
, addrstr
, peerport
,
6142 &ssh
->cfg
) != NULL
) {
6143 error
= "Unable to open an X11 connection";
6145 logevent("Opening X11 forward connection succeeded");
6150 } else if (typelen
== 15 &&
6151 !memcmp(type
, "forwarded-tcpip", 15)) {
6152 struct ssh_rportfwd pf
, *realpf
;
6155 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
6156 pf
.sport
= ssh_pkt_getuint32(pktin
);
6157 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
6158 peerport
= ssh_pkt_getuint32(pktin
);
6159 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
6160 logeventf(ssh
, "Received remote port %d open request "
6161 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
6162 if (realpf
== NULL
) {
6163 error
= "Remote port is not recognised";
6165 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
6169 realpf
->pfrec
->addressfamily
);
6170 logeventf(ssh
, "Attempting to forward remote port to "
6171 "%s:%d", realpf
->dhost
, realpf
->dport
);
6173 logeventf(ssh
, "Port open failed: %s", e
);
6174 error
= "Port open failed";
6176 logevent("Forwarded port opened successfully");
6177 c
->type
= CHAN_SOCKDATA
;
6180 } else if (typelen
== 22 &&
6181 !memcmp(type
, "auth-agent@openssh.com", 3)) {
6182 if (!ssh
->agentfwd_enabled
)
6183 error
= "Agent forwarding is not enabled";
6185 c
->type
= CHAN_AGENT
; /* identify channel type */
6186 c
->u
.a
.lensofar
= 0;
6189 error
= "Unsupported channel type requested";
6192 c
->remoteid
= remid
;
6193 c
->halfopen
= FALSE
;
6195 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
6196 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6197 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
6198 ssh2_pkt_addstring(pktout
, error
);
6199 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
6200 ssh2_pkt_send(ssh
, pktout
);
6201 logeventf(ssh
, "Rejected channel open: %s", error
);
6204 c
->localid
= alloc_channel_id(ssh
);
6206 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6207 c
->v
.v2
.remwindow
= winsize
;
6208 c
->v
.v2
.remmaxpkt
= pktsize
;
6209 bufchain_init(&c
->v
.v2
.outbuffer
);
6210 add234(ssh
->channels
, c
);
6211 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
6212 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6213 ssh2_pkt_adduint32(pktout
, c
->localid
);
6214 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
6215 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
6216 ssh2_pkt_send(ssh
, pktout
);
6221 * Handle the SSH-2 userauth and connection layers.
6223 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
6224 struct Packet
*pktin
)
6226 struct do_ssh2_authconn_state
{
6228 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
6230 AUTH_KEYBOARD_INTERACTIVE
6234 AUTH_TYPE_PUBLICKEY
,
6235 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
6236 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
6238 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
6239 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6241 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
6242 int tried_pubkey_config
, tried_agent
;
6243 int kbd_inter_running
, kbd_inter_refused
;
6245 int num_prompts
, curr_prompt
, echo
;
6250 void *publickey_blob
;
6251 int publickey_bloblen
;
6252 unsigned char request
[5], *response
, *p
;
6256 char *pkblob
, *alg
, *commentp
;
6257 int pklen
, alglen
, commentlen
;
6258 int siglen
, retlen
, len
;
6259 char *q
, *agentreq
, *ret
;
6261 int num_env
, env_left
, env_ok
;
6262 struct Packet
*pktout
;
6264 crState(do_ssh2_authconn_state
);
6266 crBegin(ssh
->do_ssh2_authconn_crstate
);
6269 * Request userauth protocol, and await a response to it.
6271 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
6272 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
6273 ssh2_pkt_send(ssh
, s
->pktout
);
6274 crWaitUntilV(pktin
);
6275 if (pktin
->type
!= SSH2_MSG_SERVICE_ACCEPT
) {
6276 bombout(("Server refused user authentication protocol"));
6281 * We repeat this whole loop, including the username prompt,
6282 * until we manage a successful authentication. If the user
6283 * types the wrong _password_, they can be sent back to the
6284 * beginning to try another username, if this is configured on.
6285 * (If they specify a username in the config, they are never
6286 * asked, even if they do give a wrong password.)
6288 * I think this best serves the needs of
6290 * - the people who have no configuration, no keys, and just
6291 * want to try repeated (username,password) pairs until they
6292 * type both correctly
6294 * - people who have keys and configuration but occasionally
6295 * need to fall back to passwords
6297 * - people with a key held in Pageant, who might not have
6298 * logged in to a particular machine before; so they want to
6299 * type a username, and then _either_ their key will be
6300 * accepted, _or_ they will type a password. If they mistype
6301 * the username they will want to be able to get back and
6304 s
->username
[0] = '\0';
6305 s
->got_username
= FALSE
;
6310 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
6312 * We got a username last time round this loop, and
6313 * with change_username turned off we don't try to get
6316 } else if (!*ssh
->cfg
.username
) {
6317 if (ssh_get_line
&& !ssh_getline_pw_only
) {
6318 if (!ssh_get_line("login as: ",
6319 s
->username
, sizeof(s
->username
), FALSE
)) {
6321 * get_line failed to get a username.
6324 logevent("No username provided. Abandoning session.");
6325 ssh
->close_expected
= TRUE
;
6326 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6330 int ret
; /* need not be saved across crReturn */
6331 c_write_str(ssh
, "login as: ");
6333 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
6335 crWaitUntilV(!pktin
);
6336 ret
= process_userpass_input(ssh
, in
, inlen
);
6340 c_write_str(ssh
, "\r\n");
6342 s
->username
[strcspn(s
->username
, "\n\r")] = '\0';
6345 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
6346 s
->username
[sizeof(s
->username
)-1] = '\0';
6347 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
6348 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
6349 c_write_str(ssh
, stuff
);
6353 s
->got_username
= TRUE
;
6356 * Send an authentication request using method "none": (a)
6357 * just in case it succeeds, and (b) so that we know what
6358 * authentication methods we can usefully try next.
6360 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6362 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6363 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6364 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
6365 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
6366 ssh2_pkt_send(ssh
, s
->pktout
);
6367 s
->type
= AUTH_TYPE_NONE
;
6369 s
->we_are_in
= FALSE
;
6371 s
->tried_pubkey_config
= FALSE
;
6372 s
->tried_agent
= FALSE
;
6373 s
->kbd_inter_running
= FALSE
;
6374 s
->kbd_inter_refused
= FALSE
;
6375 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6376 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
6378 logeventf(ssh
, "Reading private key file \"%.150s\"",
6379 filename_to_str(&ssh
->cfg
.keyfile
));
6380 keytype
= key_type(&ssh
->cfg
.keyfile
);
6381 if (keytype
== SSH_KEYTYPE_SSH2
) {
6383 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
, NULL
,
6384 &s
->publickey_bloblen
, NULL
);
6387 logeventf(ssh
, "Unable to use this key file (%s)",
6388 key_type_to_str(keytype
));
6389 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
6391 filename_to_str(&ssh
->cfg
.keyfile
),
6392 key_type_to_str(keytype
));
6393 c_write_str(ssh
, msgbuf
);
6395 s
->publickey_blob
= NULL
;
6398 s
->publickey_blob
= NULL
;
6402 * Wait for the result of the last authentication request.
6405 crWaitUntilV(pktin
);
6406 while (pktin
->type
== SSH2_MSG_USERAUTH_BANNER
) {
6410 * Don't show the banner if we're operating in
6411 * non-verbose non-interactive mode. (It's probably
6412 * a script, which means nobody will read the
6413 * banner _anyway_, and moreover the printing of
6414 * the banner will screw up processing on the
6415 * output of (say) plink.)
6417 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
6418 ssh_pkt_getstring(pktin
, &banner
, &size
);
6420 c_write_untrusted(ssh
, banner
, size
);
6422 crWaitUntilV(pktin
);
6424 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
6425 logevent("Access granted");
6426 s
->we_are_in
= TRUE
;
6430 if (s
->kbd_inter_running
&&
6431 pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
6433 * This is either a further set-of-prompts packet
6434 * in keyboard-interactive authentication, or it's
6435 * the same one and we came back here with `gotit'
6436 * set. In the former case, we must reset the
6437 * curr_prompt variable.
6441 } else if (pktin
->type
== SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
) {
6442 /* FIXME: perhaps we should support this? */
6443 bombout(("PASSWD_CHANGEREQ not yet supported"));
6445 } else if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
) {
6446 bombout(("Strange packet received during authentication: type %d",
6454 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6455 * we can look at the string in it and know what we can
6456 * helpfully try next.
6458 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
6461 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
6462 s
->kbd_inter_running
= FALSE
;
6463 if (!ssh2_pkt_getbool(pktin
)) {
6465 * We have received an unequivocal Access
6466 * Denied. This can translate to a variety of
6469 * - if we'd just tried "none" authentication,
6470 * it's not worth printing anything at all
6472 * - if we'd just tried a public key _offer_,
6473 * the message should be "Server refused our
6474 * key" (or no message at all if the key
6475 * came from Pageant)
6477 * - if we'd just tried anything else, the
6478 * message really should be "Access denied".
6480 * Additionally, if we'd just tried password
6481 * authentication, we should break out of this
6482 * whole loop so as to go back to the username
6483 * prompt (iff we're configured to allow
6484 * username change attempts).
6486 if (s
->type
== AUTH_TYPE_NONE
) {
6488 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
6489 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
6490 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
6491 c_write_str(ssh
, "Server refused our key\r\n");
6492 logevent("Server refused public key");
6493 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
6494 /* server declined keyboard-interactive; ignore */
6496 c_write_str(ssh
, "Access denied\r\n");
6497 logevent("Access denied");
6498 if (s
->type
== AUTH_TYPE_PASSWORD
&&
6499 ssh
->cfg
.change_username
) {
6500 /* XXX perhaps we should allow
6501 * keyboard-interactive to do this too? */
6502 s
->we_are_in
= FALSE
;
6507 c_write_str(ssh
, "Further authentication required\r\n");
6508 logevent("Further authentication required");
6512 in_commasep_string("publickey", methods
, methlen
);
6514 in_commasep_string("password", methods
, methlen
);
6515 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
6516 in_commasep_string("keyboard-interactive", methods
, methlen
);
6520 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6524 * Most password/passphrase prompts will be
6525 * non-echoing, so we set this to 0 by default.
6526 * Exception is that some keyboard-interactive prompts
6527 * can be echoing, in which case we'll set this to 1.
6531 if (!s
->method
&& s
->can_pubkey
&&
6532 agent_exists() && !s
->tried_agent
) {
6534 * Attempt public-key authentication using Pageant.
6539 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6540 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6542 s
->tried_agent
= TRUE
;
6544 logevent("Pageant is running. Requesting keys.");
6546 /* Request the keys held by the agent. */
6547 PUT_32BIT(s
->request
, 1);
6548 s
->request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
6549 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
6550 ssh_agent_callback
, ssh
)) {
6554 bombout(("Unexpected data from server while"
6555 " waiting for agent response"));
6558 } while (pktin
|| inlen
> 0);
6559 r
= ssh
->agent_response
;
6560 s
->responselen
= ssh
->agent_response_len
;
6562 s
->response
= (unsigned char *) r
;
6563 if (s
->response
&& s
->responselen
>= 5 &&
6564 s
->response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
6565 s
->p
= s
->response
+ 5;
6566 s
->nkeys
= GET_32BIT(s
->p
);
6568 logeventf(ssh
, "Pageant has %d SSH-2 keys", s
->nkeys
);
6569 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
6572 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
6573 s
->pklen
= GET_32BIT(s
->p
);
6575 if (s
->publickey_blob
&&
6576 s
->pklen
== s
->publickey_bloblen
&&
6577 !memcmp(s
->p
, s
->publickey_blob
,
6578 s
->publickey_bloblen
)) {
6579 logevent("This key matches configured key file");
6580 s
->tried_pubkey_config
= 1;
6582 s
->pkblob
= (char *)s
->p
;
6584 s
->alglen
= GET_32BIT(s
->pkblob
);
6585 s
->alg
= s
->pkblob
+ 4;
6586 s
->commentlen
= GET_32BIT(s
->p
);
6588 s
->commentp
= (char *)s
->p
;
6589 s
->p
+= s
->commentlen
;
6590 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6591 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6592 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6593 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6594 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6595 ssh2_pkt_addstring_start(s
->pktout
);
6596 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6597 ssh2_pkt_addstring_start(s
->pktout
);
6598 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6599 ssh2_pkt_send(ssh
, s
->pktout
);
6601 crWaitUntilV(pktin
);
6602 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6603 logevent("Key refused");
6607 if (flags
& FLAG_VERBOSE
) {
6608 c_write_str(ssh
, "Authenticating with "
6610 c_write(ssh
, s
->commentp
, s
->commentlen
);
6611 c_write_str(ssh
, "\" from agent\r\n");
6615 * Server is willing to accept the key.
6616 * Construct a SIGN_REQUEST.
6618 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6619 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6620 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6621 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6622 ssh2_pkt_addbool(s
->pktout
, TRUE
);
6623 ssh2_pkt_addstring_start(s
->pktout
);
6624 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
6625 ssh2_pkt_addstring_start(s
->pktout
);
6626 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
6628 s
->siglen
= s
->pktout
->length
- 5 + 4 + 20;
6629 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
6631 s
->len
= 1; /* message type */
6632 s
->len
+= 4 + s
->pklen
; /* key blob */
6633 s
->len
+= 4 + s
->siglen
; /* data to sign */
6634 s
->len
+= 4; /* flags */
6635 s
->agentreq
= snewn(4 + s
->len
, char);
6636 PUT_32BIT(s
->agentreq
, s
->len
);
6637 s
->q
= s
->agentreq
+ 4;
6638 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
6639 PUT_32BIT(s
->q
, s
->pklen
);
6641 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
6643 PUT_32BIT(s
->q
, s
->siglen
);
6645 /* Now the data to be signed... */
6646 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
6647 PUT_32BIT(s
->q
, 20);
6650 memcpy(s
->q
, ssh
->v2_session_id
, 20);
6652 memcpy(s
->q
, s
->pktout
->data
+ 5,
6653 s
->pktout
->length
- 5);
6654 s
->q
+= s
->pktout
->length
- 5;
6655 /* And finally the (zero) flags word. */
6657 if (!agent_query(s
->agentreq
, s
->len
+ 4,
6659 ssh_agent_callback
, ssh
)) {
6663 bombout(("Unexpected data from server"
6664 " while waiting for agent"
6668 } while (pktin
|| inlen
> 0);
6669 vret
= ssh
->agent_response
;
6670 s
->retlen
= ssh
->agent_response_len
;
6675 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
6676 logevent("Sending Pageant's response");
6677 ssh2_add_sigblob(ssh
, s
->pktout
,
6678 s
->pkblob
, s
->pklen
,
6680 GET_32BIT(s
->ret
+ 5));
6681 ssh2_pkt_send(ssh
, s
->pktout
);
6686 ("Pageant failed to answer challenge");
6697 if (!s
->method
&& s
->can_pubkey
&& s
->publickey_blob
6698 && !s
->tried_pubkey_config
) {
6699 unsigned char *pub_blob
;
6700 char *algorithm
, *comment
;
6703 s
->tried_pubkey_config
= TRUE
;
6705 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6706 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
6709 * Try the public key supplied in the configuration.
6711 * First, offer the public blob to see if the server is
6712 * willing to accept it.
6715 (unsigned char *)ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
6720 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6721 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6722 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6723 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6724 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
6725 ssh2_pkt_addstring(s
->pktout
, algorithm
);
6726 ssh2_pkt_addstring_start(s
->pktout
);
6727 ssh2_pkt_addstring_data(s
->pktout
, (char *)pub_blob
,
6729 ssh2_pkt_send(ssh
, s
->pktout
);
6730 logevent("Offered public key");
6732 crWaitUntilV(pktin
);
6733 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
6735 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
6736 continue; /* key refused; give up on it */
6739 logevent("Offer of public key accepted");
6741 * Actually attempt a serious authentication using
6744 if (ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
6745 sprintf(s
->pwprompt
,
6746 "Passphrase for key \"%.100s\": ",
6752 if (flags
& FLAG_VERBOSE
) {
6753 c_write_str(ssh
, "Authenticating with public key \"");
6754 c_write_str(ssh
, comment
);
6755 c_write_str(ssh
, "\"\r\n");
6757 s
->method
= AUTH_PUBLICKEY_FILE
;
6761 if (!s
->method
&& s
->can_keyb_inter
&& !s
->kbd_inter_refused
&&
6762 !s
->kbd_inter_running
) {
6763 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
6764 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6766 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6767 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
6769 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6770 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6771 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6772 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive"); /* method */
6773 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
6774 ssh2_pkt_addstring(s
->pktout
, "");
6775 ssh2_pkt_send(ssh
, s
->pktout
);
6777 crWaitUntilV(pktin
);
6778 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
6779 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
)
6781 logevent("Keyboard-interactive authentication refused");
6782 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
6783 s
->kbd_inter_refused
= TRUE
; /* don't try it again */
6787 c_write_str(ssh
, "Using keyboard-interactive authentication.\r\n");
6788 s
->kbd_inter_running
= TRUE
;
6792 if (s
->kbd_inter_running
) {
6793 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
6794 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
6796 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6797 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
6799 if (s
->curr_prompt
== 0) {
6801 * We've got a fresh USERAUTH_INFO_REQUEST.
6802 * Display header data, and start going through
6805 char *name
, *inst
, *lang
;
6806 int name_len
, inst_len
, lang_len
;
6808 ssh_pkt_getstring(pktin
, &name
, &name_len
);
6809 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
6810 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
6812 c_write_untrusted(ssh
, name
, name_len
);
6813 c_write_str(ssh
, "\r\n");
6816 c_write_untrusted(ssh
, inst
, inst_len
);
6817 c_write_str(ssh
, "\r\n");
6819 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
6823 * If there are prompts remaining in the packet,
6824 * display one and get a response.
6826 if (s
->curr_prompt
< s
->num_prompts
) {
6830 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
6831 if (prompt_len
> 0) {
6832 static const char trunc
[] = "<prompt truncated>: ";
6833 static const int prlen
= sizeof(s
->pwprompt
) -
6835 if (prompt_len
> prlen
) {
6836 memcpy(s
->pwprompt
, prompt
, prlen
);
6837 strcpy(s
->pwprompt
+ prlen
, trunc
);
6839 memcpy(s
->pwprompt
, prompt
, prompt_len
);
6840 s
->pwprompt
[prompt_len
] = '\0';
6844 "<server failed to send prompt>: ");
6846 s
->echo
= ssh2_pkt_getbool(pktin
);
6852 if (!s
->method
&& s
->can_passwd
) {
6853 s
->method
= AUTH_PASSWORD
;
6854 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
6855 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
6856 sprintf(s
->pwprompt
, "%.90s@%.90s's password: ", s
->username
,
6863 if (!ssh_get_line(s
->pwprompt
, s
->password
,
6864 sizeof(s
->password
), TRUE
)) {
6866 * get_line failed to get a password (for
6867 * example because one was supplied on the
6868 * command line which has already failed to
6871 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
6872 ssh2_pkt_adduint32(s
->pktout
,SSH2_DISCONNECT_BY_APPLICATION
);
6873 ssh2_pkt_addstring(s
->pktout
, "No more passwords available"
6875 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
6876 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6877 logevent("Unable to authenticate");
6878 connection_fatal(ssh
->frontend
,
6879 "Unable to authenticate");
6880 ssh
->close_expected
= TRUE
;
6881 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
6885 int ret
; /* need not be saved across crReturn */
6886 c_write_untrusted(ssh
, s
->pwprompt
, strlen(s
->pwprompt
));
6889 setup_userpass_input(ssh
, s
->password
,
6890 sizeof(s
->password
), s
->echo
);
6892 crWaitUntilV(!pktin
);
6893 ret
= process_userpass_input(ssh
, in
, inlen
);
6897 c_write_str(ssh
, "\r\n");
6901 if (s
->method
== AUTH_PUBLICKEY_FILE
) {
6903 * We have our passphrase. Now try the actual authentication.
6905 struct ssh2_userkey
*key
;
6906 const char *error
= NULL
;
6908 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, s
->password
,
6910 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
6911 if (key
== SSH2_WRONG_PASSPHRASE
) {
6912 c_write_str(ssh
, "Wrong passphrase\r\n");
6913 s
->tried_pubkey_config
= FALSE
;
6915 c_write_str(ssh
, "Unable to load private key (");
6916 c_write_str(ssh
, error
);
6917 c_write_str(ssh
, ")\r\n");
6918 s
->tried_pubkey_config
= TRUE
;
6920 /* Send a spurious AUTH_NONE to return to the top. */
6921 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6922 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6923 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6924 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
6925 ssh2_pkt_send(ssh
, s
->pktout
);
6926 s
->type
= AUTH_TYPE_NONE
;
6928 unsigned char *pkblob
, *sigblob
, *sigdata
;
6929 int pkblob_len
, sigblob_len
, sigdata_len
;
6933 * We have loaded the private key and the server
6934 * has announced that it's willing to accept it.
6935 * Hallelujah. Generate a signature and send it.
6937 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6938 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6939 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6940 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
6941 ssh2_pkt_addbool(s
->pktout
, TRUE
);
6942 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
6943 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
6944 ssh2_pkt_addstring_start(s
->pktout
);
6945 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
, pkblob_len
);
6948 * The data to be signed is:
6952 * followed by everything so far placed in the
6955 sigdata_len
= s
->pktout
->length
- 5 + 4 + 20;
6956 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
6958 sigdata
= snewn(sigdata_len
, unsigned char);
6960 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
6961 PUT_32BIT(sigdata
+p
, 20);
6964 memcpy(sigdata
+p
, ssh
->v2_session_id
, 20); p
+= 20;
6965 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
6966 s
->pktout
->length
- 5);
6967 p
+= s
->pktout
->length
- 5;
6968 assert(p
== sigdata_len
);
6969 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
6970 sigdata_len
, &sigblob_len
);
6971 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
6972 sigblob
, sigblob_len
);
6977 ssh2_pkt_send(ssh
, s
->pktout
);
6978 s
->type
= AUTH_TYPE_PUBLICKEY
;
6979 key
->alg
->freekey(key
->data
);
6981 } else if (s
->method
== AUTH_PASSWORD
) {
6983 * We pad out the password packet to 256 bytes to make
6984 * it harder for an attacker to find the length of the
6987 * Anyone using a password longer than 256 bytes
6988 * probably doesn't have much to worry about from
6989 * people who find out how long their password is!
6991 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
6992 s
->pktout
->forcepad
= 256;
6993 ssh2_pkt_addstring(s
->pktout
, s
->username
);
6994 ssh2_pkt_addstring(s
->pktout
, "ssh-connection"); /* service requested */
6995 ssh2_pkt_addstring(s
->pktout
, "password");
6996 ssh2_pkt_addbool(s
->pktout
, FALSE
);
6997 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
6998 ssh2_pkt_addstring(s
->pktout
, s
->password
);
6999 memset(s
->password
, 0, sizeof(s
->password
));
7000 end_log_omission(ssh
, s
->pktout
);
7001 ssh2_pkt_send(ssh
, s
->pktout
);
7002 logevent("Sent password");
7003 s
->type
= AUTH_TYPE_PASSWORD
;
7004 } else if (s
->method
== AUTH_KEYBOARD_INTERACTIVE
) {
7005 if (s
->curr_prompt
== 0) {
7006 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
7007 s
->pktout
->forcepad
= 256;
7008 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
7010 if (s
->need_pw
) { /* only add pw if we just got one! */
7011 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
7012 ssh2_pkt_addstring(s
->pktout
, s
->password
);
7013 memset(s
->password
, 0, sizeof(s
->password
));
7014 end_log_omission(ssh
, s
->pktout
);
7017 if (s
->curr_prompt
>= s
->num_prompts
) {
7018 ssh2_pkt_send(ssh
, s
->pktout
);
7021 * If there are prompts remaining, we set
7022 * `gotit' so that we won't attempt to get
7023 * another packet. Then we go back round the
7024 * loop and will end up retrieving another
7025 * prompt out of the existing packet. Funky or
7030 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
7032 c_write_str(ssh
, "No supported authentication methods"
7033 " left to try!\r\n");
7034 logevent("No supported authentications offered."
7036 s
->pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
7037 ssh2_pkt_adduint32(s
->pktout
, SSH2_DISCONNECT_BY_APPLICATION
);
7038 ssh2_pkt_addstring(s
->pktout
, "No supported authentication"
7039 " methods available");
7040 ssh2_pkt_addstring(s
->pktout
, "en"); /* language tag */
7041 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
7042 ssh
->close_expected
= TRUE
;
7043 ssh_closing((Plug
)ssh
, NULL
, 0, 0);
7047 } while (!s
->we_are_in
);
7050 * Now we're authenticated for the connection protocol. The
7051 * connection protocol will automatically have started at this
7052 * point; there's no need to send SERVICE_REQUEST.
7055 ssh
->channels
= newtree234(ssh_channelcmp
);
7058 * Set up handlers for some connection protocol messages, so we
7059 * don't have to handle them repeatedly in this coroutine.
7061 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
7062 ssh2_msg_channel_window_adjust
;
7063 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
7064 ssh2_msg_global_request
;
7067 * Create the main session channel.
7069 if (!ssh
->cfg
.ssh_no_shell
) {
7070 ssh
->mainchan
= snew(struct ssh_channel
);
7071 ssh
->mainchan
->ssh
= ssh
;
7072 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
7073 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
7074 ssh2_pkt_addstring(s
->pktout
, "session");
7075 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
7076 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
7077 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
7078 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
7079 ssh2_pkt_send(ssh
, s
->pktout
);
7080 crWaitUntilV(pktin
);
7081 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
7082 bombout(("Server refused to open a session"));
7084 /* FIXME: error data comes back in FAILURE packet */
7086 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
7087 bombout(("Server's channel confirmation cited wrong channel"));
7090 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
7091 ssh
->mainchan
->halfopen
= FALSE
;
7092 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
7093 ssh
->mainchan
->closes
= 0;
7094 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
7095 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
7096 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
7097 add234(ssh
->channels
, ssh
->mainchan
);
7098 update_specials_menu(ssh
->frontend
);
7099 logevent("Opened channel for session");
7101 ssh
->mainchan
= NULL
;
7104 * Now we have a channel, make dispatch table entries for
7105 * general channel-based messages.
7107 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
7108 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
7109 ssh2_msg_channel_data
;
7110 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
7111 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
7112 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
7113 ssh2_msg_channel_open_confirmation
;
7114 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
7115 ssh2_msg_channel_open_failure
;
7116 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
7117 ssh2_msg_channel_request
;
7118 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
7119 ssh2_msg_channel_open
;
7122 * Potentially enable X11 forwarding.
7124 if (ssh
->mainchan
&& ssh
->cfg
.x11_forward
) {
7125 char proto
[20], data
[64];
7126 logevent("Requesting X11 forwarding");
7127 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
7128 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
7129 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
7130 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7131 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
7132 ssh2_pkt_addstring(s
->pktout
, "x11-req");
7133 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7134 ssh2_pkt_addbool(s
->pktout
, 0); /* many connections */
7135 ssh2_pkt_addstring(s
->pktout
, proto
);
7136 ssh2_pkt_addstring(s
->pktout
, data
);
7137 ssh2_pkt_adduint32(s
->pktout
, x11_get_screen_number(ssh
->cfg
.x11_display
));
7138 ssh2_pkt_send(ssh
, s
->pktout
);
7140 crWaitUntilV(pktin
);
7142 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7143 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7144 bombout(("Unexpected response to X11 forwarding request:"
7145 " packet type %d", pktin
->type
));
7148 logevent("X11 forwarding refused");
7150 logevent("X11 forwarding enabled");
7151 ssh
->X11_fwd_enabled
= TRUE
;
7156 * Enable port forwardings.
7158 ssh_setup_portfwd(ssh
, &ssh
->cfg
);
7161 * Potentially enable agent forwarding.
7163 if (ssh
->mainchan
&& ssh
->cfg
.agentfwd
&& agent_exists()) {
7164 logevent("Requesting OpenSSH-style agent forwarding");
7165 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7166 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
7167 ssh2_pkt_addstring(s
->pktout
, "auth-agent-req@openssh.com");
7168 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7169 ssh2_pkt_send(ssh
, s
->pktout
);
7171 crWaitUntilV(pktin
);
7173 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7174 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7175 bombout(("Unexpected response to agent forwarding request:"
7176 " packet type %d", pktin
->type
));
7179 logevent("Agent forwarding refused");
7181 logevent("Agent forwarding enabled");
7182 ssh
->agentfwd_enabled
= TRUE
;
7187 * Now allocate a pty for the session.
7189 if (ssh
->mainchan
&& !ssh
->cfg
.nopty
) {
7190 /* Unpick the terminal-speed string. */
7191 /* XXX perhaps we should allow no speeds to be sent. */
7192 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
7193 sscanf(ssh
->cfg
.termspeed
, "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
7194 /* Build the pty request. */
7195 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7196 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
7197 ssh2_pkt_addstring(s
->pktout
, "pty-req");
7198 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7199 ssh2_pkt_addstring(s
->pktout
, ssh
->cfg
.termtype
);
7200 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_width
);
7201 ssh2_pkt_adduint32(s
->pktout
, ssh
->term_height
);
7202 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel width */
7203 ssh2_pkt_adduint32(s
->pktout
, 0); /* pixel height */
7204 ssh2_pkt_addstring_start(s
->pktout
);
7205 ssh2_pkt_addbyte(s
->pktout
, 128); /* TTY_OP_ISPEED */
7206 ssh2_pkt_adduint32(s
->pktout
, ssh
->ispeed
);
7207 ssh2_pkt_addbyte(s
->pktout
, 129); /* TTY_OP_OSPEED */
7208 ssh2_pkt_adduint32(s
->pktout
, ssh
->ospeed
);
7209 ssh2_pkt_addstring_data(s
->pktout
, "\0", 1); /* TTY_OP_END */
7210 ssh2_pkt_send(ssh
, s
->pktout
);
7211 ssh
->state
= SSH_STATE_INTERMED
;
7213 crWaitUntilV(pktin
);
7215 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7216 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7217 bombout(("Unexpected response to pty request:"
7218 " packet type %d", pktin
->type
));
7221 c_write_str(ssh
, "Server refused to allocate pty\r\n");
7222 ssh
->editing
= ssh
->echoing
= 1;
7224 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7225 ssh
->ospeed
, ssh
->ispeed
);
7228 ssh
->editing
= ssh
->echoing
= 1;
7232 * Send environment variables.
7234 * Simplest thing here is to send all the requests at once, and
7235 * then wait for a whole bunch of successes or failures.
7237 if (ssh
->mainchan
&& *ssh
->cfg
.environmt
) {
7238 char *e
= ssh
->cfg
.environmt
;
7239 char *var
, *varend
, *val
;
7245 while (*e
&& *e
!= '\t') e
++;
7247 if (*e
== '\t') e
++;
7252 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7253 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
);
7254 ssh2_pkt_addstring(s
->pktout
, "env");
7255 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7256 ssh2_pkt_addstring_start(s
->pktout
);
7257 ssh2_pkt_addstring_data(s
->pktout
, var
, varend
-var
);
7258 ssh2_pkt_addstring(s
->pktout
, val
);
7259 ssh2_pkt_send(ssh
, s
->pktout
);
7264 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
7267 s
->env_left
= s
->num_env
;
7269 while (s
->env_left
> 0) {
7270 crWaitUntilV(pktin
);
7272 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7273 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7274 bombout(("Unexpected response to environment request:"
7275 " packet type %d", pktin
->type
));
7285 if (s
->env_ok
== s
->num_env
) {
7286 logevent("All environment variables successfully set");
7287 } else if (s
->env_ok
== 0) {
7288 logevent("All environment variables refused");
7289 c_write_str(ssh
, "Server refused to set environment variables\r\n");
7291 logeventf(ssh
, "%d environment variables refused",
7292 s
->num_env
- s
->env_ok
);
7293 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
7298 * Start a shell or a remote command. We may have to attempt
7299 * this twice if the config data has provided a second choice
7302 if (ssh
->mainchan
) while (1) {
7306 if (ssh
->fallback_cmd
) {
7307 subsys
= ssh
->cfg
.ssh_subsys2
;
7308 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
7310 subsys
= ssh
->cfg
.ssh_subsys
;
7311 cmd
= ssh
->cfg
.remote_cmd_ptr
;
7312 if (!cmd
) cmd
= ssh
->cfg
.remote_cmd
;
7315 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7316 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->remoteid
); /* recipient channel */
7318 ssh2_pkt_addstring(s
->pktout
, "subsystem");
7319 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7320 ssh2_pkt_addstring(s
->pktout
, cmd
);
7322 ssh2_pkt_addstring(s
->pktout
, "exec");
7323 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7324 ssh2_pkt_addstring(s
->pktout
, cmd
);
7326 ssh2_pkt_addstring(s
->pktout
, "shell");
7327 ssh2_pkt_addbool(s
->pktout
, 1); /* want reply */
7329 ssh2_pkt_send(ssh
, s
->pktout
);
7331 crWaitUntilV(pktin
);
7333 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
7334 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
7335 bombout(("Unexpected response to shell/command request:"
7336 " packet type %d", pktin
->type
));
7340 * We failed to start the command. If this is the
7341 * fallback command, we really are finished; if it's
7342 * not, and if the fallback command exists, try falling
7343 * back to it before complaining.
7345 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
7346 logevent("Primary command failed; attempting fallback");
7347 ssh
->fallback_cmd
= TRUE
;
7350 bombout(("Server refused to start a shell/command"));
7353 logevent("Started a shell/command");
7358 ssh
->state
= SSH_STATE_SESSION
;
7359 if (ssh
->size_needed
)
7360 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
7361 if (ssh
->eof_needed
)
7362 ssh_special(ssh
, TS_EOF
);
7368 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
7373 s
->try_send
= FALSE
;
7377 * _All_ the connection-layer packets we expect to
7378 * receive are now handled by the dispatch table.
7379 * Anything that reaches here must be bogus.
7382 bombout(("Strange packet received: type %d", pktin
->type
));
7384 } else if (ssh
->mainchan
) {
7386 * We have spare data. Add it to the channel buffer.
7388 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
7393 struct ssh_channel
*c
;
7395 * Try to send data on all channels if we can.
7397 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++)
7398 ssh2_try_send_and_unthrottle(c
);
7406 * Handlers for SSH-2 messages that might arrive at any moment.
7408 static void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
7410 /* log reason code in disconnect message */
7412 int nowlen
, reason
, msglen
;
7414 reason
= ssh_pkt_getuint32(pktin
);
7415 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7417 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
7418 buf
= dupprintf("Received disconnect message (%s)",
7419 ssh2_disconnect_reasons
[reason
]);
7421 buf
= dupprintf("Received disconnect message (unknown"
7422 " type %d)", reason
);
7426 buf
= dupprintf("Disconnection message text: %n%.*s",
7427 &nowlen
, msglen
, msg
);
7429 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7431 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
7432 ssh2_disconnect_reasons
[reason
] : "unknown",
7437 static void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
7439 /* log the debug message */
7444 /* XXX maybe we should actually take notice of this */
7445 always_display
= ssh2_pkt_getbool(pktin
);
7446 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7448 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
7451 static void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
7453 struct Packet
*pktout
;
7454 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
7455 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
7457 * UNIMPLEMENTED messages MUST appear in the same order as the
7458 * messages they respond to. Hence, never queue them.
7460 ssh2_pkt_send_noqueue(ssh
, pktout
);
7464 * Handle the top-level SSH-2 protocol.
7466 static void ssh2_protocol_setup(Ssh ssh
)
7471 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7473 for (i
= 0; i
< 256; i
++)
7474 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
7477 * Any message we actually understand, we set to NULL so that
7478 * the coroutines will get it.
7480 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = NULL
;
7481 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = NULL
;
7482 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = NULL
;
7483 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = NULL
;
7484 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = NULL
;
7485 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = NULL
;
7486 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = NULL
;
7487 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7488 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7489 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = NULL
;
7490 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = NULL
;
7491 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = NULL
;
7492 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = NULL
;
7493 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = NULL
;
7494 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
7495 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = NULL
;
7496 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7497 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7498 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = NULL
;
7499 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = NULL
;
7500 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = NULL
;
7501 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = NULL
;
7502 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = NULL
;
7503 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = NULL
;
7504 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = NULL
;
7505 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = NULL
;
7506 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = NULL
;
7507 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = NULL
;
7508 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = NULL
;
7509 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = NULL
;
7510 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = NULL
;
7511 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = NULL
;
7512 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = NULL
;
7515 * These special message types we install handlers for.
7517 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
7518 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with SSH-1 */
7519 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
7522 static void ssh2_timer(void *ctx
, long now
)
7526 if (ssh
->state
== SSH_STATE_CLOSED
)
7529 if (!ssh
->kex_in_progress
&& ssh
->cfg
.ssh_rekey_time
!= 0 &&
7530 now
- ssh
->next_rekey
>= 0) {
7531 do_ssh2_transport(ssh
, "timeout", -1, NULL
);
7535 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
7536 struct Packet
*pktin
)
7538 unsigned char *in
= (unsigned char *)vin
;
7539 if (ssh
->state
== SSH_STATE_CLOSED
)
7543 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
7544 if (!ssh
->kex_in_progress
&&
7545 ssh
->max_data_size
!= 0 &&
7546 ssh
->incoming_data_size
> ssh
->max_data_size
)
7547 do_ssh2_transport(ssh
, "too much data received", -1, NULL
);
7550 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
7551 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
7555 if (!ssh
->protocol_initial_phase_done
||
7556 (pktin
&& pktin
->type
>= 20 && pktin
->type
< 50)) {
7557 if (do_ssh2_transport(ssh
, in
, inlen
, pktin
) &&
7558 !ssh
->protocol_initial_phase_done
) {
7559 ssh
->protocol_initial_phase_done
= TRUE
;
7561 * Allow authconn to initialise itself.
7563 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
7566 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
7571 * Called to set up the connection.
7573 * Returns an error message, or NULL on success.
7575 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
7577 char *host
, int port
, char **realhost
, int nodelay
,
7583 ssh
= snew(struct ssh_tag
);
7584 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7585 ssh
->version
= 0; /* when not ready yet */
7588 ssh
->v1_cipher_ctx
= NULL
;
7589 ssh
->crcda_ctx
= NULL
;
7590 ssh
->cscipher
= NULL
;
7591 ssh
->cs_cipher_ctx
= NULL
;
7592 ssh
->sccipher
= NULL
;
7593 ssh
->sc_cipher_ctx
= NULL
;
7595 ssh
->cs_mac_ctx
= NULL
;
7597 ssh
->sc_mac_ctx
= NULL
;
7599 ssh
->cs_comp_ctx
= NULL
;
7601 ssh
->sc_comp_ctx
= NULL
;
7603 ssh
->kex_ctx
= NULL
;
7604 ssh
->hostkey
= NULL
;
7606 ssh
->close_expected
= FALSE
;
7607 ssh
->state
= SSH_STATE_PREPACKET
;
7608 ssh
->size_needed
= FALSE
;
7609 ssh
->eof_needed
= FALSE
;
7612 ssh
->deferred_send_data
= NULL
;
7613 ssh
->deferred_len
= 0;
7614 ssh
->deferred_size
= 0;
7615 ssh
->fallback_cmd
= 0;
7617 ssh
->x11auth
= NULL
;
7618 ssh
->v1_compressing
= FALSE
;
7619 ssh
->v2_outgoing_sequence
= 0;
7620 ssh
->ssh1_rdpkt_crstate
= 0;
7621 ssh
->ssh2_rdpkt_crstate
= 0;
7622 ssh
->do_ssh_init_crstate
= 0;
7623 ssh
->ssh_gotdata_crstate
= 0;
7624 ssh
->do_ssh1_connection_crstate
= 0;
7625 ssh
->do_ssh1_login_crstate
= 0;
7626 ssh
->do_ssh2_transport_crstate
= 0;
7627 ssh
->do_ssh2_authconn_crstate
= 0;
7628 ssh
->do_ssh_init_state
= NULL
;
7629 ssh
->do_ssh1_login_state
= NULL
;
7630 ssh
->do_ssh2_transport_state
= NULL
;
7631 ssh
->do_ssh2_authconn_state
= NULL
;
7632 ssh
->mainchan
= NULL
;
7633 ssh
->throttled_all
= 0;
7634 ssh
->v1_stdout_throttling
= 0;
7636 ssh
->queuelen
= ssh
->queuesize
= 0;
7637 ssh
->queueing
= FALSE
;
7638 ssh
->qhead
= ssh
->qtail
= NULL
;
7639 ssh
->deferred_rekey_reason
= NULL
;
7640 bufchain_init(&ssh
->queued_incoming_data
);
7641 ssh
->frozen
= FALSE
;
7643 *backend_handle
= ssh
;
7646 if (crypto_startup() == 0)
7647 return "Microsoft high encryption pack not installed!";
7650 ssh
->frontend
= frontend_handle
;
7651 ssh
->term_width
= ssh
->cfg
.width
;
7652 ssh
->term_height
= ssh
->cfg
.height
;
7654 ssh
->channels
= NULL
;
7655 ssh
->rportfwds
= NULL
;
7656 ssh
->portfwds
= NULL
;
7661 ssh
->v1_throttle_count
= 0;
7662 ssh
->overall_bufsize
= 0;
7663 ssh
->fallback_cmd
= 0;
7665 ssh
->protocol
= NULL
;
7667 ssh
->protocol_initial_phase_done
= FALSE
;
7671 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
7672 ssh
->deferred_data_size
= 0L;
7673 ssh
->max_data_size
= parse_blocksize(ssh
->cfg
.ssh_rekey_data
);
7674 ssh
->kex_in_progress
= FALSE
;
7676 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
7685 static void ssh_free(void *handle
)
7687 Ssh ssh
= (Ssh
) handle
;
7688 struct ssh_channel
*c
;
7689 struct ssh_rportfwd
*pf
;
7691 if (ssh
->v1_cipher_ctx
)
7692 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
7693 if (ssh
->cs_cipher_ctx
)
7694 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
7695 if (ssh
->sc_cipher_ctx
)
7696 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
7697 if (ssh
->cs_mac_ctx
)
7698 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
7699 if (ssh
->sc_mac_ctx
)
7700 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
7701 if (ssh
->cs_comp_ctx
) {
7703 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
7705 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
7707 if (ssh
->sc_comp_ctx
) {
7709 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
7711 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
7714 dh_cleanup(ssh
->kex_ctx
);
7715 sfree(ssh
->savedhost
);
7717 while (ssh
->queuelen
-- > 0)
7718 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
7721 while (ssh
->qhead
) {
7722 struct queued_handler
*qh
= ssh
->qhead
;
7723 ssh
->qhead
= qh
->next
;
7726 ssh
->qhead
= ssh
->qtail
= NULL
;
7728 if (ssh
->channels
) {
7729 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
7732 if (c
->u
.x11
.s
!= NULL
)
7733 x11_close(c
->u
.x11
.s
);
7736 if (c
->u
.pfd
.s
!= NULL
)
7737 pfd_close(c
->u
.pfd
.s
);
7742 freetree234(ssh
->channels
);
7743 ssh
->channels
= NULL
;
7746 if (ssh
->rportfwds
) {
7747 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
7749 freetree234(ssh
->rportfwds
);
7750 ssh
->rportfwds
= NULL
;
7752 sfree(ssh
->deferred_send_data
);
7754 x11_free_auth(ssh
->x11auth
);
7755 sfree(ssh
->do_ssh_init_state
);
7756 sfree(ssh
->do_ssh1_login_state
);
7757 sfree(ssh
->do_ssh2_transport_state
);
7758 sfree(ssh
->do_ssh2_authconn_state
);
7759 if (ssh
->crcda_ctx
) {
7760 crcda_free_context(ssh
->crcda_ctx
);
7761 ssh
->crcda_ctx
= NULL
;
7764 ssh_do_close(ssh
, TRUE
);
7765 expire_timer_context(ssh
);
7767 pinger_free(ssh
->pinger
);
7768 bufchain_clear(&ssh
->queued_incoming_data
);
7775 * Reconfigure the SSH backend.
7777 static void ssh_reconfig(void *handle
, Config
*cfg
)
7779 Ssh ssh
= (Ssh
) handle
;
7780 char *rekeying
= NULL
, rekey_mandatory
= FALSE
;
7781 unsigned long old_max_data_size
;
7783 pinger_reconfig(ssh
->pinger
, &ssh
->cfg
, cfg
);
7784 ssh_setup_portfwd(ssh
, cfg
);
7786 if (ssh
->cfg
.ssh_rekey_time
!= cfg
->ssh_rekey_time
&&
7787 cfg
->ssh_rekey_time
!= 0) {
7788 long new_next
= ssh
->last_rekey
+ cfg
->ssh_rekey_time
*60*TICKSPERSEC
;
7789 long now
= GETTICKCOUNT();
7791 if (new_next
- now
< 0) {
7792 rekeying
= "timeout shortened";
7794 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
7798 old_max_data_size
= ssh
->max_data_size
;
7799 ssh
->max_data_size
= parse_blocksize(cfg
->ssh_rekey_data
);
7800 if (old_max_data_size
!= ssh
->max_data_size
&&
7801 ssh
->max_data_size
!= 0) {
7802 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
7803 ssh
->incoming_data_size
> ssh
->max_data_size
)
7804 rekeying
= "data limit lowered";
7807 if (ssh
->cfg
.compression
!= cfg
->compression
) {
7808 rekeying
= "compression setting changed";
7809 rekey_mandatory
= TRUE
;
7812 if (ssh
->cfg
.ssh2_des_cbc
!= cfg
->ssh2_des_cbc
||
7813 memcmp(ssh
->cfg
.ssh_cipherlist
, cfg
->ssh_cipherlist
,
7814 sizeof(ssh
->cfg
.ssh_cipherlist
))) {
7815 rekeying
= "cipher settings changed";
7816 rekey_mandatory
= TRUE
;
7819 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
7822 if (!ssh
->kex_in_progress
) {
7823 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
7824 } else if (rekey_mandatory
) {
7825 ssh
->deferred_rekey_reason
= rekeying
;
7831 * Called to send data down the Telnet connection.
7833 static int ssh_send(void *handle
, char *buf
, int len
)
7835 Ssh ssh
= (Ssh
) handle
;
7837 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7840 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
7842 return ssh_sendbuffer(ssh
);
7846 * Called to query the current amount of buffered stdin data.
7848 static int ssh_sendbuffer(void *handle
)
7850 Ssh ssh
= (Ssh
) handle
;
7853 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
7857 * If the SSH socket itself has backed up, add the total backup
7858 * size on that to any individual buffer on the stdin channel.
7861 if (ssh
->throttled_all
)
7862 override_value
= ssh
->overall_bufsize
;
7864 if (ssh
->version
== 1) {
7865 return override_value
;
7866 } else if (ssh
->version
== 2) {
7867 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
7868 return override_value
;
7870 return (override_value
+
7871 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
7878 * Called to set the size of the window from SSH's POV.
7880 static void ssh_size(void *handle
, int width
, int height
)
7882 Ssh ssh
= (Ssh
) handle
;
7883 struct Packet
*pktout
;
7885 ssh
->term_width
= width
;
7886 ssh
->term_height
= height
;
7888 switch (ssh
->state
) {
7889 case SSH_STATE_BEFORE_SIZE
:
7890 case SSH_STATE_PREPACKET
:
7891 case SSH_STATE_CLOSED
:
7892 break; /* do nothing */
7893 case SSH_STATE_INTERMED
:
7894 ssh
->size_needed
= TRUE
; /* buffer for later */
7896 case SSH_STATE_SESSION
:
7897 if (!ssh
->cfg
.nopty
) {
7898 if (ssh
->version
== 1) {
7899 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
7900 PKT_INT
, ssh
->term_height
,
7901 PKT_INT
, ssh
->term_width
,
7902 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
7903 } else if (ssh
->mainchan
) {
7904 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
7905 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
7906 ssh2_pkt_addstring(pktout
, "window-change");
7907 ssh2_pkt_addbool(pktout
, 0);
7908 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
7909 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
7910 ssh2_pkt_adduint32(pktout
, 0);
7911 ssh2_pkt_adduint32(pktout
, 0);
7912 ssh2_pkt_send(ssh
, pktout
);
7920 * Return a list of the special codes that make sense in this
7923 static const struct telnet_special
*ssh_get_specials(void *handle
)
7925 static const struct telnet_special ssh1_ignore_special
[] = {
7926 {"IGNORE message", TS_NOP
}
7928 static const struct telnet_special ssh2_transport_specials
[] = {
7929 {"IGNORE message", TS_NOP
},
7930 {"Repeat key exchange", TS_REKEY
},
7932 static const struct telnet_special ssh2_session_specials
[] = {
7935 /* These are the signal names defined by draft-ietf-secsh-connect-23.
7936 * They include all the ISO C signals, but are a subset of the POSIX
7937 * required signals. */
7938 {"SIGINT (Interrupt)", TS_SIGINT
},
7939 {"SIGTERM (Terminate)", TS_SIGTERM
},
7940 {"SIGKILL (Kill)", TS_SIGKILL
},
7941 {"SIGQUIT (Quit)", TS_SIGQUIT
},
7942 {"SIGHUP (Hangup)", TS_SIGHUP
},
7943 {"More signals", TS_SUBMENU
},
7944 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
7945 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
7946 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
7947 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
7950 static const struct telnet_special specials_end
[] = {
7953 /* XXX review this length for any changes: */
7954 static struct telnet_special ssh_specials
[lenof(ssh2_transport_specials
) +
7955 lenof(ssh2_session_specials
) +
7956 lenof(specials_end
)];
7957 Ssh ssh
= (Ssh
) handle
;
7959 #define ADD_SPECIALS(name) \
7961 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7962 memcpy(&ssh_specials[i], name, sizeof name); \
7966 if (ssh
->version
== 1) {
7967 /* Don't bother offering IGNORE if we've decided the remote
7968 * won't cope with it, since we wouldn't bother sending it if
7970 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
7971 ADD_SPECIALS(ssh1_ignore_special
);
7972 } else if (ssh
->version
== 2) {
7973 ADD_SPECIALS(ssh2_transport_specials
);
7975 ADD_SPECIALS(ssh2_session_specials
);
7976 } /* else we're not ready yet */
7979 ADD_SPECIALS(specials_end
);
7980 return ssh_specials
;
7988 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7989 * can send an EOF and collect resulting output (e.g. `plink
7992 static void ssh_special(void *handle
, Telnet_Special code
)
7994 Ssh ssh
= (Ssh
) handle
;
7995 struct Packet
*pktout
;
7997 if (code
== TS_EOF
) {
7998 if (ssh
->state
!= SSH_STATE_SESSION
) {
8000 * Buffer the EOF in case we are pre-SESSION, so we can
8001 * send it as soon as we reach SESSION.
8004 ssh
->eof_needed
= TRUE
;
8007 if (ssh
->version
== 1) {
8008 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
8009 } else if (ssh
->mainchan
) {
8010 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
8011 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8012 ssh2_pkt_send(ssh
, pktout
);
8013 ssh
->send_ok
= 0; /* now stop trying to read from stdin */
8015 logevent("Sent EOF message");
8016 } else if (code
== TS_PING
|| code
== TS_NOP
) {
8017 if (ssh
->state
== SSH_STATE_CLOSED
8018 || ssh
->state
== SSH_STATE_PREPACKET
) return;
8019 if (ssh
->version
== 1) {
8020 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
8021 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
8023 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
8024 ssh2_pkt_addstring_start(pktout
);
8025 ssh2_pkt_send_noqueue(ssh
, pktout
);
8027 } else if (code
== TS_REKEY
) {
8028 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
8029 do_ssh2_transport(ssh
, "at user request", -1, NULL
);
8031 } else if (code
== TS_BRK
) {
8032 if (ssh
->state
== SSH_STATE_CLOSED
8033 || ssh
->state
== SSH_STATE_PREPACKET
) return;
8034 if (ssh
->version
== 1) {
8035 logevent("Unable to send BREAK signal in SSH-1");
8036 } else if (ssh
->mainchan
) {
8037 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8038 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8039 ssh2_pkt_addstring(pktout
, "break");
8040 ssh2_pkt_addbool(pktout
, 0);
8041 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
8042 ssh2_pkt_send(ssh
, pktout
);
8045 /* Is is a POSIX signal? */
8046 char *signame
= NULL
;
8047 if (code
== TS_SIGABRT
) signame
= "ABRT";
8048 if (code
== TS_SIGALRM
) signame
= "ALRM";
8049 if (code
== TS_SIGFPE
) signame
= "FPE";
8050 if (code
== TS_SIGHUP
) signame
= "HUP";
8051 if (code
== TS_SIGILL
) signame
= "ILL";
8052 if (code
== TS_SIGINT
) signame
= "INT";
8053 if (code
== TS_SIGKILL
) signame
= "KILL";
8054 if (code
== TS_SIGPIPE
) signame
= "PIPE";
8055 if (code
== TS_SIGQUIT
) signame
= "QUIT";
8056 if (code
== TS_SIGSEGV
) signame
= "SEGV";
8057 if (code
== TS_SIGTERM
) signame
= "TERM";
8058 if (code
== TS_SIGUSR1
) signame
= "USR1";
8059 if (code
== TS_SIGUSR2
) signame
= "USR2";
8060 /* The SSH-2 protocol does in principle support arbitrary named
8061 * signals, including signame@domain, but we don't support those. */
8063 /* It's a signal. */
8064 if (ssh
->version
== 2 && ssh
->mainchan
) {
8065 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
8066 ssh2_pkt_adduint32(pktout
, ssh
->mainchan
->remoteid
);
8067 ssh2_pkt_addstring(pktout
, "signal");
8068 ssh2_pkt_addbool(pktout
, 0);
8069 ssh2_pkt_addstring(pktout
, signame
);
8070 ssh2_pkt_send(ssh
, pktout
);
8071 logeventf(ssh
, "Sent signal SIG%s", signame
);
8074 /* Never heard of it. Do nothing */
8079 void *new_sock_channel(void *handle
, Socket s
)
8081 Ssh ssh
= (Ssh
) handle
;
8082 struct ssh_channel
*c
;
8083 c
= snew(struct ssh_channel
);
8088 c
->localid
= alloc_channel_id(ssh
);
8090 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
8092 bufchain_init(&c
->v
.v2
.outbuffer
);
8093 add234(ssh
->channels
, c
);
8099 * This is called when stdout/stderr (the entity to which
8100 * from_backend sends data) manages to clear some backlog.
8102 static void ssh_unthrottle(void *handle
, int bufsize
)
8104 Ssh ssh
= (Ssh
) handle
;
8105 if (ssh
->version
== 1) {
8106 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
8107 ssh
->v1_stdout_throttling
= 0;
8108 ssh1_throttle(ssh
, -1);
8111 if (ssh
->mainchan
&& ssh
->mainchan
->closes
== 0)
8112 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
8116 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
8118 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
8120 struct Packet
*pktout
;
8122 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
8124 if (ssh
->version
== 1) {
8125 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
8126 PKT_INT
, c
->localid
,
8129 /* PKT_STR, <org:orgport>, */
8132 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
8133 ssh2_pkt_addstring(pktout
, "direct-tcpip");
8134 ssh2_pkt_adduint32(pktout
, c
->localid
);
8135 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
8136 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
8137 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
8138 ssh2_pkt_addstring(pktout
, hostname
);
8139 ssh2_pkt_adduint32(pktout
, port
);
8141 * We make up values for the originator data; partly it's
8142 * too much hassle to keep track, and partly I'm not
8143 * convinced the server should be told details like that
8144 * about my local network configuration.
8146 ssh2_pkt_addstring(pktout
, "client-side-connection");
8147 ssh2_pkt_adduint32(pktout
, 0);
8148 ssh2_pkt_send(ssh
, pktout
);
8152 static Socket
ssh_socket(void *handle
)
8154 Ssh ssh
= (Ssh
) handle
;
8158 static int ssh_sendok(void *handle
)
8160 Ssh ssh
= (Ssh
) handle
;
8161 return ssh
->send_ok
;
8164 static int ssh_ldisc(void *handle
, int option
)
8166 Ssh ssh
= (Ssh
) handle
;
8167 if (option
== LD_ECHO
)
8168 return ssh
->echoing
;
8169 if (option
== LD_EDIT
)
8170 return ssh
->editing
;
8174 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
8176 Ssh ssh
= (Ssh
) handle
;
8180 static void ssh_provide_logctx(void *handle
, void *logctx
)
8182 Ssh ssh
= (Ssh
) handle
;
8183 ssh
->logctx
= logctx
;
8186 static int ssh_return_exitcode(void *handle
)
8188 Ssh ssh
= (Ssh
) handle
;
8192 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: 0);
8196 * cfg_info for SSH is the currently running version of the
8197 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
8199 static int ssh_cfg_info(void *handle
)
8201 Ssh ssh
= (Ssh
) handle
;
8202 return ssh
->version
;
8206 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
8207 * that fails. This variable is the means by which scp.c can reach
8208 * into the SSH code and find out which one it got.
8210 extern int ssh_fallback_cmd(void *handle
)
8212 Ssh ssh
= (Ssh
) handle
;
8213 return ssh
->fallback_cmd
;
8216 Backend ssh_backend
= {
8226 ssh_return_exitcode
,