18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
22 /* logevent, only printf-formatted. */
23 void logeventf(char *fmt, ...)
29 vsprintf(stuff, fmt, ap);
34 #define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
35 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
36 logeventf msg, connection_fatal msg )
38 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
39 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
40 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
41 #define SSH1_CMSG_USER 4 /* 0x4 */
42 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
43 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
44 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
45 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
46 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
47 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
48 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
49 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
50 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
51 #define SSH1_SMSG_FAILURE 15 /* 0xf */
52 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
53 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
54 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
55 #define SSH1_CMSG_EOF 19 /* 0x13 */
56 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
57 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
58 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
59 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
60 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
61 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
62 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
63 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
64 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
65 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
66 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
67 #define SSH1_MSG_IGNORE 32 /* 0x20 */
68 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
69 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
70 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
71 #define SSH1_MSG_DEBUG 36 /* 0x24 */
72 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
73 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
74 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
75 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
76 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
77 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
78 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
80 #define SSH1_AUTH_TIS 5 /* 0x5 */
81 #define SSH1_AUTH_CCARD 16 /* 0x10 */
83 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
84 /* Mask for protoflags we will echo back to server if seen */
85 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
87 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
88 #define SSH2_MSG_IGNORE 2 /* 0x2 */
89 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
90 #define SSH2_MSG_DEBUG 4 /* 0x4 */
91 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
92 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
93 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
94 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
95 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
96 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
97 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
98 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
99 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
100 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
101 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
102 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
103 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
104 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
105 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
106 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
107 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
109 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
110 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
111 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
112 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
113 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
114 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
115 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
116 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
117 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
118 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
119 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
120 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
121 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
122 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
125 * Packet type contexts, so that ssh2_pkt_type can correctly decode
126 * the ambiguous type numbers back into the correct type strings.
128 #define SSH2_PKTCTX_DHGROUP1 0x0001
129 #define SSH2_PKTCTX_DHGEX 0x0002
130 #define SSH2_PKTCTX_PUBLICKEY 0x0010
131 #define SSH2_PKTCTX_PASSWORD 0x0020
132 #define SSH2_PKTCTX_KBDINTER 0x0040
133 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
135 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
136 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
137 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
138 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
139 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
140 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
141 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
142 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
143 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
144 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
145 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
146 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
147 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
148 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
149 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
151 static const char *const ssh2_disconnect_reasons[] = {
153 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
154 "SSH_DISCONNECT_PROTOCOL_ERROR",
155 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
156 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
157 "SSH_DISCONNECT_MAC_ERROR",
158 "SSH_DISCONNECT_COMPRESSION_ERROR",
159 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
160 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
161 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
162 "SSH_DISCONNECT_CONNECTION_LOST",
163 "SSH_DISCONNECT_BY_APPLICATION",
164 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
165 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
166 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
167 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
170 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
171 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
172 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
173 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
175 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
178 * Various remote-bug flags.
180 #define BUG_CHOKES_ON_SSH1_IGNORE 1
181 #define BUG_SSH2_HMAC 2
182 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
183 #define BUG_CHOKES_ON_RSA 8
184 #define BUG_SSH2_RSA_PADDING 16
185 #define BUG_SSH2_DERIVEKEY 32
186 #define BUG_SSH2_DH_GEX 64
188 #define translate(x) if (type == x) return #x
189 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
190 char *ssh1_pkt_type(int type)
192 translate(SSH1_MSG_DISCONNECT);
193 translate(SSH1_SMSG_PUBLIC_KEY);
194 translate(SSH1_CMSG_SESSION_KEY);
195 translate(SSH1_CMSG_USER);
196 translate(SSH1_CMSG_AUTH_RSA);
197 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
198 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
199 translate(SSH1_CMSG_AUTH_PASSWORD);
200 translate(SSH1_CMSG_REQUEST_PTY);
201 translate(SSH1_CMSG_WINDOW_SIZE);
202 translate(SSH1_CMSG_EXEC_SHELL);
203 translate(SSH1_CMSG_EXEC_CMD);
204 translate(SSH1_SMSG_SUCCESS);
205 translate(SSH1_SMSG_FAILURE);
206 translate(SSH1_CMSG_STDIN_DATA);
207 translate(SSH1_SMSG_STDOUT_DATA);
208 translate(SSH1_SMSG_STDERR_DATA);
209 translate(SSH1_CMSG_EOF);
210 translate(SSH1_SMSG_EXIT_STATUS);
211 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
212 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
213 translate(SSH1_MSG_CHANNEL_DATA);
214 translate(SSH1_MSG_CHANNEL_CLOSE);
215 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
216 translate(SSH1_SMSG_X11_OPEN);
217 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
218 translate(SSH1_MSG_PORT_OPEN);
219 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
220 translate(SSH1_SMSG_AGENT_OPEN);
221 translate(SSH1_MSG_IGNORE);
222 translate(SSH1_CMSG_EXIT_CONFIRMATION);
223 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
224 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
225 translate(SSH1_MSG_DEBUG);
226 translate(SSH1_CMSG_REQUEST_COMPRESSION);
227 translate(SSH1_CMSG_AUTH_TIS);
228 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
229 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
230 translate(SSH1_CMSG_AUTH_CCARD);
231 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
232 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
235 char *ssh2_pkt_type(int pkt_ctx, int type)
237 translate(SSH2_MSG_DISCONNECT);
238 translate(SSH2_MSG_IGNORE);
239 translate(SSH2_MSG_UNIMPLEMENTED);
240 translate(SSH2_MSG_DEBUG);
241 translate(SSH2_MSG_SERVICE_REQUEST);
242 translate(SSH2_MSG_SERVICE_ACCEPT);
243 translate(SSH2_MSG_KEXINIT);
244 translate(SSH2_MSG_NEWKEYS);
245 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
246 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
247 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
248 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
249 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
250 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
251 translate(SSH2_MSG_USERAUTH_REQUEST);
252 translate(SSH2_MSG_USERAUTH_FAILURE);
253 translate(SSH2_MSG_USERAUTH_SUCCESS);
254 translate(SSH2_MSG_USERAUTH_BANNER);
255 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
256 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
257 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
258 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
259 translate(SSH2_MSG_GLOBAL_REQUEST);
260 translate(SSH2_MSG_REQUEST_SUCCESS);
261 translate(SSH2_MSG_REQUEST_FAILURE);
262 translate(SSH2_MSG_CHANNEL_OPEN);
263 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
264 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
265 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
266 translate(SSH2_MSG_CHANNEL_DATA);
267 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
268 translate(SSH2_MSG_CHANNEL_EOF);
269 translate(SSH2_MSG_CHANNEL_CLOSE);
270 translate(SSH2_MSG_CHANNEL_REQUEST);
271 translate(SSH2_MSG_CHANNEL_SUCCESS);
272 translate(SSH2_MSG_CHANNEL_FAILURE);
278 #define GET_32BIT(cp) \
279 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
280 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
281 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
282 ((unsigned long)(unsigned char)(cp)[3]))
284 #define PUT_32BIT(cp, value) { \
285 (cp)[0] = (unsigned char)((value) >> 24); \
286 (cp)[1] = (unsigned char)((value) >> 16); \
287 (cp)[2] = (unsigned char)((value) >> 8); \
288 (cp)[3] = (unsigned char)(value); }
290 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
292 /* Coroutine mechanics for the sillier bits of the code */
293 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
296 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
298 #define crFinish(z) } *crLine = 0; return (z); }
299 #define crFinishV } *crLine = 0; return; }
300 #define crReturn(z) \
302 *crLine =__LINE__; return (z); case __LINE__:;\
306 *crLine=__LINE__; return; case __LINE__:;\
308 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
309 #define crStopV do{ *crLine = 0; return; }while(0)
310 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
311 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
313 typedef struct ssh_tag *Ssh;
315 extern char *x11_init(Socket *, char *, void *);
316 extern void x11_close(Socket);
317 extern int x11_send(Socket, char *, int);
318 extern void x11_invent_auth(char *, int, char *, int);
319 extern void x11_unthrottle(Socket s);
320 extern void x11_override_throttle(Socket s, int enable);
322 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
323 extern char *pfd_addforward(char *desthost, int destport, int port);
324 extern void pfd_close(Socket s);
325 extern int pfd_send(Socket s, char *data, int len);
326 extern void pfd_confirm(Socket s);
327 extern void pfd_unthrottle(Socket s);
328 extern void pfd_override_throttle(Socket s, int enable);
330 static void ssh2_pkt_init(Ssh, int pkt_type);
331 static void ssh2_pkt_addbool(Ssh, unsigned char value);
332 static void ssh2_pkt_adduint32(Ssh, unsigned long value);
333 static void ssh2_pkt_addstring_start(Ssh);
334 static void ssh2_pkt_addstring_str(Ssh, char *data);
335 static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
336 static void ssh2_pkt_addstring(Ssh, char *data);
337 static char *ssh2_mpint_fmt(Bignum b, int *len);
338 static void ssh2_pkt_addmp(Ssh, Bignum b);
339 static int ssh2_pkt_construct(Ssh);
340 static void ssh2_pkt_send(Ssh);
343 * Buffer management constants. There are several of these for
344 * various different purposes:
346 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
347 * on a local data stream before we throttle the whole SSH
348 * connection (in SSH1 only). Throttling the whole connection is
349 * pretty drastic so we set this high in the hope it won't
352 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
353 * on the SSH connection itself before we defensively throttle
354 * _all_ local data streams. This is pretty drastic too (though
355 * thankfully unlikely in SSH2 since the window mechanism should
356 * ensure that the server never has any need to throttle its end
357 * of the connection), so we set this high as well.
359 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
363 #define SSH1_BUFFER_LIMIT 32768
364 #define SSH_MAX_BACKLOG 32768
365 #define OUR_V2_WINSIZE 16384
367 const static struct ssh_kex *kex_algs[] = {
368 &ssh_diffiehellman_gex,
372 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
374 static void *nullmac_make_context(void)
378 static void nullmac_free_context(void *handle)
381 static void nullmac_key(void *handle, unsigned char *key)
384 static void nullmac_generate(void *handle, unsigned char *blk, int len,
388 static int nullmac_verify(void *handle, unsigned char *blk, int len,
393 const static struct ssh_mac ssh_mac_none = {
394 nullmac_make_context, nullmac_free_context, nullmac_key,
395 nullmac_generate, nullmac_verify, "none", 0
397 const static struct ssh_mac *macs[] = {
398 &ssh_sha1, &ssh_md5, &ssh_mac_none
400 const static struct ssh_mac *buggymacs[] = {
401 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
404 static void ssh_comp_none_init(void)
407 static int ssh_comp_none_block(unsigned char *block, int len,
408 unsigned char **outblock, int *outlen)
412 static int ssh_comp_none_disable(void)
416 const static struct ssh_compress ssh_comp_none = {
418 ssh_comp_none_init, ssh_comp_none_block,
419 ssh_comp_none_init, ssh_comp_none_block,
420 ssh_comp_none_disable
422 extern const struct ssh_compress ssh_zlib;
423 const static struct ssh_compress *compressions[] = {
424 &ssh_zlib, &ssh_comp_none
427 enum { /* channel types */
432 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
436 * 2-3-4 tree storing channels.
439 Ssh ssh; /* pointer back to main context */
440 unsigned remoteid, localid;
443 * In SSH1, this value contains four bits:
445 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
446 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
447 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
448 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
450 * A channel is completely finished with when all four bits are set.
454 struct ssh1_data_channel {
457 struct ssh2_data_channel {
459 unsigned remwindow, remmaxpkt;
464 struct ssh_agent_channel {
465 unsigned char *message;
466 unsigned char msglen[4];
467 int lensofar, totallen;
469 struct ssh_x11_channel {
472 struct ssh_pfd_channel {
479 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
480 * 2 use this structure in different ways, reflecting SSH 2's
481 * altogether saner approach to port forwarding.
483 * In SSH 1, you arrange a remote forwarding by sending the server
484 * the remote port number, and the local destination host:port.
485 * When a connection comes in, the server sends you back that
486 * host:port pair, and you connect to it. This is a ready-made
487 * security hole if you're not on the ball: a malicious server
488 * could send you back _any_ host:port pair, so if you trustingly
489 * connect to the address it gives you then you've just opened the
490 * entire inside of your corporate network just by connecting
491 * through it to a dodgy SSH server. Hence, we must store a list of
492 * host:port pairs we _are_ trying to forward to, and reject a
493 * connection request from the server if it's not in the list.
495 * In SSH 2, each side of the connection minds its own business and
496 * doesn't send unnecessary information to the other. You arrange a
497 * remote forwarding by sending the server just the remote port
498 * number. When a connection comes in, the server tells you which
499 * of its ports was connected to; and _you_ have to remember what
500 * local host:port pair went with that port number.
502 * Hence: in SSH 1 this structure stores host:port pairs we intend
503 * to allow connections to, and is indexed by those host:port
504 * pairs. In SSH 2 it stores a mapping from source port to
505 * destination host:port pair, and is indexed by source port.
507 struct ssh_rportfwd {
508 unsigned sport, dport;
521 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
522 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
523 static void ssh_size(void *handle, int width, int height);
524 static void ssh_special(void *handle, Telnet_Special);
525 static int ssh2_try_send(struct ssh_channel *c);
526 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
527 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
528 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
529 static int ssh_sendbuffer(void *handle);
531 struct rdpkt1_state_tag {
532 long len, pad, biglen, to_read;
533 unsigned long realcrc, gotcrc;
539 struct rdpkt2_state_tag {
540 long len, pad, payload, packetlen, maclen;
543 unsigned long incoming_sequence;
547 const struct plug_function_table *fn;
548 /* the above field _must_ be first in the structure */
550 SHA_State exhash, exhashbase;
554 unsigned char session_key[32];
556 int v1_remote_protoflags;
557 int v1_local_protoflags;
558 int agentfwd_enabled;
561 const struct ssh_cipher *cipher;
563 const struct ssh2_cipher *cscipher, *sccipher;
564 void *cs_cipher_ctx, *sc_cipher_ctx;
565 const struct ssh_mac *csmac, *scmac;
566 void *cs_mac_ctx, *sc_mac_ctx;
567 const struct ssh_compress *cscomp, *sccomp;
568 const struct ssh_kex *kex;
569 const struct ssh_signkey *hostkey;
570 unsigned char v2_session_id[20];
575 int echoing, editing;
579 int term_width, term_height;
581 tree234 *channels; /* indexed by local id */
582 struct ssh_channel *mainchan; /* primary session channel */
589 SSH_STATE_BEFORE_SIZE,
595 int size_needed, eof_needed;
598 struct Packet pktout;
599 unsigned char *deferred_send_data;
600 int deferred_len, deferred_size;
603 * Gross hack: pscp will try to start SFTP but fall back to
604 * scp1 if that fails. This variable is the means by which
605 * scp.c can reach into the SSH code and find out which one it
611 * Used for username and password input.
613 char *userpass_input_buffer;
614 int userpass_input_buflen;
615 int userpass_input_bufpos;
616 int userpass_input_echo;
618 char *portfwd_strptr;
622 int v1_throttle_count;
625 int v1_stdout_throttling;
626 int v2_outgoing_sequence;
628 int ssh1_rdpkt_crstate;
629 int ssh2_rdpkt_crstate;
630 int do_ssh_init_crstate;
631 int ssh_gotdata_crstate;
632 int ssh1_protocol_crstate;
633 int do_ssh1_login_crstate;
634 int do_ssh2_transport_crstate;
635 int do_ssh2_authconn_crstate;
637 void *do_ssh_init_state;
638 void *do_ssh1_login_state;
639 void *do_ssh2_transport_state;
640 void *do_ssh2_authconn_state;
642 struct rdpkt1_state_tag rdpkt1_state;
643 struct rdpkt2_state_tag rdpkt2_state;
645 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
646 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
649 static int ssh_channelcmp(void *av, void *bv)
651 struct ssh_channel *a = (struct ssh_channel *) av;
652 struct ssh_channel *b = (struct ssh_channel *) bv;
653 if (a->localid < b->localid)
655 if (a->localid > b->localid)
659 static int ssh_channelfind(void *av, void *bv)
661 unsigned *a = (unsigned *) av;
662 struct ssh_channel *b = (struct ssh_channel *) bv;
670 static int ssh_rportcmp_ssh1(void *av, void *bv)
672 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
673 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
675 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
676 return i < 0 ? -1 : +1;
677 if (a->dport > b->dport)
679 if (a->dport < b->dport)
684 static int ssh_rportcmp_ssh2(void *av, void *bv)
686 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
687 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
689 if (a->sport > b->sport)
691 if (a->sport < b->sport)
696 static int alloc_channel_id(Ssh ssh)
698 const unsigned CHANNEL_NUMBER_OFFSET = 256;
699 unsigned low, high, mid;
701 struct ssh_channel *c;
704 * First-fit allocation of channel numbers: always pick the
705 * lowest unused one. To do this, binary-search using the
706 * counted B-tree to find the largest channel ID which is in a
707 * contiguous sequence from the beginning. (Precisely
708 * everything in that sequence must have ID equal to its tree
709 * index plus CHANNEL_NUMBER_OFFSET.)
711 tsize = count234(ssh->channels);
715 while (high - low > 1) {
716 mid = (high + low) / 2;
717 c = index234(ssh->channels, mid);
718 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
719 low = mid; /* this one is fine */
721 high = mid; /* this one is past it */
724 * Now low points to either -1, or the tree index of the
725 * largest ID in the initial sequence.
728 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
729 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
731 return low + 1 + CHANNEL_NUMBER_OFFSET;
734 static void c_write(Ssh ssh, char *buf, int len)
736 if ((flags & FLAG_STDERR)) {
738 for (i = 0; i < len; i++)
740 fputc(buf[i], stderr);
743 from_backend(ssh->frontend, 1, buf, len);
746 static void c_write_untrusted(Ssh ssh, char *buf, int len)
749 for (i = 0; i < len; i++) {
751 c_write(ssh, "\r\n", 2);
752 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
753 c_write(ssh, buf + i, 1);
757 static void c_write_str(Ssh ssh, char *buf)
759 c_write(ssh, buf, strlen(buf));
763 * Collect incoming data in the incoming packet buffer.
764 * Decipher and verify the packet when it is completely read.
765 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
766 * Update the *data and *datalen variables.
767 * Return the additional nr of bytes needed, or 0 when
768 * a complete packet is available.
770 static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
772 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
774 crBegin(ssh->ssh1_rdpkt_crstate);
779 ssh->pktin.length = 0;
781 for (st->i = st->len = 0; st->i < 4; st->i++) {
782 while ((*datalen) == 0)
784 st->len = (st->len << 8) + **data;
785 (*data)++, (*datalen)--;
788 st->pad = 8 - (st->len % 8);
789 st->biglen = st->len + st->pad;
790 ssh->pktin.length = st->len - 5;
792 if (ssh->pktin.maxlen < st->biglen) {
793 ssh->pktin.maxlen = st->biglen;
794 ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
797 st->to_read = st->biglen;
798 st->p = ssh->pktin.data;
799 while (st->to_read > 0) {
800 st->chunk = st->to_read;
801 while ((*datalen) == 0)
802 crReturn(st->to_read);
803 if (st->chunk > (*datalen))
804 st->chunk = (*datalen);
805 memcpy(st->p, *data, st->chunk);
807 *datalen -= st->chunk;
809 st->to_read -= st->chunk;
812 if (ssh->cipher && detect_attack(ssh->pktin.data, st->biglen, NULL)) {
813 bombout(("Network attack (CRC compensation) detected!"));
818 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
820 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
821 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
822 if (st->gotcrc != st->realcrc) {
823 bombout(("Incorrect CRC received on packet"));
827 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
829 if (ssh->v1_compressing) {
830 unsigned char *decompblk;
832 zlib_decompress_block(ssh->pktin.body - 1, ssh->pktin.length + 1,
833 &decompblk, &decomplen);
835 if (ssh->pktin.maxlen < st->pad + decomplen) {
836 ssh->pktin.maxlen = st->pad + decomplen;
837 ssh->pktin.data = srealloc(ssh->pktin.data,
838 ssh->pktin.maxlen + APIEXTRA);
839 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
842 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
844 ssh->pktin.length = decomplen - 1;
847 ssh->pktin.type = ssh->pktin.body[-1];
849 log_packet(PKT_INCOMING, ssh->pktin.type, ssh1_pkt_type(ssh->pktin.type),
850 ssh->pktin.body, ssh->pktin.length);
852 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
853 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
854 ssh->pktin.type == SSH1_MSG_DEBUG ||
855 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
856 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
857 long stringlen = GET_32BIT(ssh->pktin.body);
858 if (stringlen + 4 != ssh->pktin.length) {
859 bombout(("Received data packet with bogus string length"));
864 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
865 /* log debug message */
867 int stringlen = GET_32BIT(ssh->pktin.body);
868 strcpy(buf, "Remote debug message: ");
871 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
872 buf[8 + stringlen] = '\0';
875 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
880 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
881 /* log reason code in disconnect message */
883 unsigned msglen = GET_32BIT(ssh->pktin.body);
885 strcpy(buf, "Remote sent disconnect: ");
886 nowlen = strlen(buf);
887 if (msglen > sizeof(buf) - nowlen - 1)
888 msglen = sizeof(buf) - nowlen - 1;
889 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
890 buf[nowlen + msglen] = '\0';
891 /* logevent(buf); (this is now done within the bombout macro) */
892 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
899 static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
901 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
903 crBegin(ssh->ssh2_rdpkt_crstate);
907 ssh->pktin.length = 0;
909 st->cipherblk = ssh->sccipher->blksize;
912 if (st->cipherblk < 8)
915 if (ssh->pktin.maxlen < st->cipherblk) {
916 ssh->pktin.maxlen = st->cipherblk;
917 ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
921 * Acquire and decrypt the first block of the packet. This will
922 * contain the length and padding details.
924 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
925 while ((*datalen) == 0)
926 crReturn(st->cipherblk - st->i);
927 ssh->pktin.data[st->i] = *(*data)++;
932 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
933 ssh->pktin.data, st->cipherblk);
936 * Now get the length and padding figures.
938 st->len = GET_32BIT(ssh->pktin.data);
939 st->pad = ssh->pktin.data[4];
942 * _Completely_ silly lengths should be stomped on before they
943 * do us any more damage.
945 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
946 bombout(("Incoming packet was garbled on decryption"));
951 * This enables us to deduce the payload length.
953 st->payload = st->len - st->pad - 1;
955 ssh->pktin.length = st->payload + 5;
958 * So now we can work out the total packet length.
960 st->packetlen = st->len + 4;
961 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
964 * Adjust memory allocation if packet is too big.
966 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
967 ssh->pktin.maxlen = st->packetlen + st->maclen;
968 ssh->pktin.data = srealloc(ssh->pktin.data,
969 ssh->pktin.maxlen + APIEXTRA);
973 * Read and decrypt the remainder of the packet.
975 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
977 while ((*datalen) == 0)
978 crReturn(st->packetlen + st->maclen - st->i);
979 ssh->pktin.data[st->i] = *(*data)++;
982 /* Decrypt everything _except_ the MAC. */
984 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
985 ssh->pktin.data + st->cipherblk,
986 st->packetlen - st->cipherblk);
992 && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
993 st->incoming_sequence)) {
994 bombout(("Incorrect MAC received on packet"));
997 st->incoming_sequence++; /* whether or not we MACed */
1000 * Decompress packet payload.
1003 unsigned char *newpayload;
1006 ssh->sccomp->decompress(ssh->pktin.data + 5, ssh->pktin.length - 5,
1007 &newpayload, &newlen)) {
1008 if (ssh->pktin.maxlen < newlen + 5) {
1009 ssh->pktin.maxlen = newlen + 5;
1010 ssh->pktin.data = srealloc(ssh->pktin.data,
1011 ssh->pktin.maxlen + APIEXTRA);
1013 ssh->pktin.length = 5 + newlen;
1014 memcpy(ssh->pktin.data + 5, newpayload, newlen);
1019 ssh->pktin.savedpos = 6;
1020 ssh->pktin.type = ssh->pktin.data[5];
1022 log_packet(PKT_INCOMING, ssh->pktin.type,
1023 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1024 ssh->pktin.data+6, ssh->pktin.length-6);
1026 switch (ssh->pktin.type) {
1028 * These packets we must handle instantly.
1030 case SSH2_MSG_DISCONNECT:
1032 /* log reason code in disconnect message */
1034 int reason = GET_32BIT(ssh->pktin.data + 6);
1035 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
1037 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1038 sprintf(buf, "Received disconnect message (%s)",
1039 ssh2_disconnect_reasons[reason]);
1041 sprintf(buf, "Received disconnect message (unknown type %d)",
1045 strcpy(buf, "Disconnection message text: ");
1046 nowlen = strlen(buf);
1047 if (msglen > sizeof(buf) - nowlen - 1)
1048 msglen = sizeof(buf) - nowlen - 1;
1049 memcpy(buf + nowlen, ssh->pktin.data + 14, msglen);
1050 buf[nowlen + msglen] = '\0';
1052 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1054 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1055 ssh2_disconnect_reasons[reason] : "unknown",
1060 case SSH2_MSG_IGNORE:
1062 case SSH2_MSG_DEBUG:
1064 /* log the debug message */
1066 /* int display = ssh->pktin.body[6]; */
1067 int stringlen = GET_32BIT(ssh->pktin.data+7);
1069 strcpy(buf, "Remote debug message: ");
1070 prefix = strlen(buf);
1071 if (stringlen > (int)(sizeof(buf)-prefix-1))
1072 stringlen = sizeof(buf)-prefix-1;
1073 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
1074 buf[prefix + stringlen] = '\0';
1077 goto next_packet; /* FIXME: print the debug message */
1080 * These packets we need do nothing about here.
1082 case SSH2_MSG_UNIMPLEMENTED:
1083 case SSH2_MSG_SERVICE_REQUEST:
1084 case SSH2_MSG_SERVICE_ACCEPT:
1085 case SSH2_MSG_KEXINIT:
1086 case SSH2_MSG_NEWKEYS:
1087 case SSH2_MSG_KEXDH_INIT:
1088 case SSH2_MSG_KEXDH_REPLY:
1089 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1090 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1091 case SSH2_MSG_KEX_DH_GEX_INIT:
1092 case SSH2_MSG_KEX_DH_GEX_REPLY:
1093 case SSH2_MSG_USERAUTH_REQUEST:
1094 case SSH2_MSG_USERAUTH_FAILURE:
1095 case SSH2_MSG_USERAUTH_SUCCESS:
1096 case SSH2_MSG_USERAUTH_BANNER:
1097 case SSH2_MSG_USERAUTH_PK_OK:
1098 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1099 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1100 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1101 case SSH2_MSG_GLOBAL_REQUEST:
1102 case SSH2_MSG_REQUEST_SUCCESS:
1103 case SSH2_MSG_REQUEST_FAILURE:
1104 case SSH2_MSG_CHANNEL_OPEN:
1105 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1106 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1107 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1108 case SSH2_MSG_CHANNEL_DATA:
1109 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1110 case SSH2_MSG_CHANNEL_EOF:
1111 case SSH2_MSG_CHANNEL_CLOSE:
1112 case SSH2_MSG_CHANNEL_REQUEST:
1113 case SSH2_MSG_CHANNEL_SUCCESS:
1114 case SSH2_MSG_CHANNEL_FAILURE:
1118 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1121 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1122 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1130 static void ssh1_pktout_size(Ssh ssh, int len)
1134 len += 5; /* type and CRC */
1135 pad = 8 - (len % 8);
1138 ssh->pktout.length = len - 5;
1139 if (ssh->pktout.maxlen < biglen) {
1140 ssh->pktout.maxlen = biglen;
1142 /* Allocate enough buffer space for extra block
1143 * for MS CryptEncrypt() */
1144 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
1146 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
1149 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
1152 static void s_wrpkt_start(Ssh ssh, int type, int len)
1154 ssh1_pktout_size(ssh, len);
1155 ssh->pktout.type = type;
1158 static int s_wrpkt_prepare(Ssh ssh)
1160 int pad, len, biglen, i;
1163 ssh->pktout.body[-1] = ssh->pktout.type;
1165 log_packet(PKT_OUTGOING, ssh->pktout.type, ssh1_pkt_type(ssh->pktout.type),
1166 ssh->pktout.body, ssh->pktout.length);
1168 if (ssh->v1_compressing) {
1169 unsigned char *compblk;
1171 zlib_compress_block(ssh->pktout.body - 1, ssh->pktout.length + 1,
1172 &compblk, &complen);
1173 ssh1_pktout_size(ssh, complen - 1);
1174 memcpy(ssh->pktout.body - 1, compblk, complen);
1178 len = ssh->pktout.length + 5; /* type and CRC */
1179 pad = 8 - (len % 8);
1182 for (i = 0; i < pad; i++)
1183 ssh->pktout.data[i + 4] = random_byte();
1184 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1185 PUT_32BIT(ssh->pktout.data + biglen, crc);
1186 PUT_32BIT(ssh->pktout.data, len);
1189 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
1194 static void s_wrpkt(Ssh ssh)
1197 len = s_wrpkt_prepare(ssh);
1198 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1199 if (backlog > SSH_MAX_BACKLOG)
1200 ssh_throttle_all(ssh, 1, backlog);
1203 static void s_wrpkt_defer(Ssh ssh)
1206 len = s_wrpkt_prepare(ssh);
1207 if (ssh->deferred_len + len > ssh->deferred_size) {
1208 ssh->deferred_size = ssh->deferred_len + len + 128;
1209 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1210 ssh->deferred_size);
1212 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1213 ssh->deferred_len += len;
1217 * Construct a packet with the specified contents.
1219 static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
1221 unsigned char *p, *argp, argchar;
1222 unsigned long argint;
1223 int pktlen, argtype, arglen;
1227 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1230 (void) va_arg(ap1, int);
1234 (void) va_arg(ap1, char);
1238 (void) va_arg(ap1, unsigned char *);
1239 arglen = va_arg(ap1, int);
1243 argp = va_arg(ap1, unsigned char *);
1244 arglen = strlen(argp);
1245 pktlen += 4 + arglen;
1248 bn = va_arg(ap1, Bignum);
1249 pktlen += ssh1_bignum_length(bn);
1256 s_wrpkt_start(ssh, pkttype, pktlen);
1257 p = ssh->pktout.body;
1259 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1262 argint = va_arg(ap2, int);
1263 PUT_32BIT(p, argint);
1267 argchar = va_arg(ap2, unsigned char);
1272 argp = va_arg(ap2, unsigned char *);
1273 arglen = va_arg(ap2, int);
1274 memcpy(p, argp, arglen);
1278 argp = va_arg(ap2, unsigned char *);
1279 arglen = strlen(argp);
1280 PUT_32BIT(p, arglen);
1281 memcpy(p + 4, argp, arglen);
1285 bn = va_arg(ap2, Bignum);
1286 p += ssh1_write_bignum(p, bn);
1292 static void send_packet(Ssh ssh, int pkttype, ...)
1295 va_start(ap1, pkttype);
1296 va_start(ap2, pkttype);
1297 construct_packet(ssh, pkttype, ap1, ap2);
1301 static void defer_packet(Ssh ssh, int pkttype, ...)
1304 va_start(ap1, pkttype);
1305 va_start(ap2, pkttype);
1306 construct_packet(ssh, pkttype, ap1, ap2);
1310 static int ssh_versioncmp(char *a, char *b)
1313 unsigned long av, bv;
1315 av = strtoul(a, &ae, 10);
1316 bv = strtoul(b, &be, 10);
1318 return (av < bv ? -1 : +1);
1323 av = strtoul(ae, &ae, 10);
1324 bv = strtoul(be, &be, 10);
1326 return (av < bv ? -1 : +1);
1331 * Utility routines for putting an SSH-protocol `string' and
1332 * `uint32' into a SHA state.
1335 static void sha_string(SHA_State * s, void *str, int len)
1337 unsigned char lenblk[4];
1338 PUT_32BIT(lenblk, len);
1339 SHA_Bytes(s, lenblk, 4);
1340 SHA_Bytes(s, str, len);
1343 static void sha_uint32(SHA_State * s, unsigned i)
1345 unsigned char intblk[4];
1346 PUT_32BIT(intblk, i);
1347 SHA_Bytes(s, intblk, 4);
1351 * SSH2 packet construction functions.
1353 static void ssh2_pkt_ensure(Ssh ssh, int length)
1355 if (ssh->pktout.maxlen < length) {
1356 ssh->pktout.maxlen = length + 256;
1357 ssh->pktout.data = srealloc(ssh->pktout.data,
1358 ssh->pktout.maxlen + APIEXTRA);
1359 if (!ssh->pktout.data)
1360 fatalbox("Out of memory");
1363 static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
1365 ssh->pktout.length += len;
1366 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1367 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
1369 static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
1371 ssh2_pkt_adddata(ssh, &byte, 1);
1373 static void ssh2_pkt_init(Ssh ssh, int pkt_type)
1375 ssh->pktout.length = 5;
1376 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
1378 static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
1380 ssh2_pkt_adddata(ssh, &value, 1);
1382 static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
1385 PUT_32BIT(x, value);
1386 ssh2_pkt_adddata(ssh, x, 4);
1388 static void ssh2_pkt_addstring_start(Ssh ssh)
1390 ssh2_pkt_adduint32(ssh, 0);
1391 ssh->pktout.savedpos = ssh->pktout.length;
1393 static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
1395 ssh2_pkt_adddata(ssh, data, strlen(data));
1396 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1397 ssh->pktout.length - ssh->pktout.savedpos);
1399 static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
1401 ssh2_pkt_adddata(ssh, data, len);
1402 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1403 ssh->pktout.length - ssh->pktout.savedpos);
1405 static void ssh2_pkt_addstring(Ssh ssh, char *data)
1407 ssh2_pkt_addstring_start(ssh);
1408 ssh2_pkt_addstring_str(ssh, data);
1410 static char *ssh2_mpint_fmt(Bignum b, int *len)
1413 int i, n = (bignum_bitcount(b) + 7) / 8;
1416 fatalbox("out of memory");
1418 for (i = 1; i <= n; i++)
1419 p[i] = bignum_byte(b, n - i);
1421 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1423 memmove(p, p + i, n + 1 - i);
1427 static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
1431 p = ssh2_mpint_fmt(b, &len);
1432 ssh2_pkt_addstring_start(ssh);
1433 ssh2_pkt_addstring_data(ssh, p, len);
1438 * Construct an SSH2 final-form packet: compress it, encrypt it,
1439 * put the MAC on it. Final packet, ready to be sent, is stored in
1440 * ssh->pktout.data. Total length is returned.
1442 static int ssh2_pkt_construct(Ssh ssh)
1444 int cipherblk, maclen, padding, i;
1446 log_packet(PKT_OUTGOING, ssh->pktout.data[5],
1447 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1448 ssh->pktout.data + 6, ssh->pktout.length - 6);
1451 * Compress packet payload.
1454 unsigned char *newpayload;
1457 ssh->cscomp->compress(ssh->pktout.data + 5, ssh->pktout.length - 5,
1458 &newpayload, &newlen)) {
1459 ssh->pktout.length = 5;
1460 ssh2_pkt_adddata(ssh, newpayload, newlen);
1466 * Add padding. At least four bytes, and must also bring total
1467 * length (minus MAC) up to a multiple of the block size.
1469 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1470 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1473 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1474 maclen = ssh->csmac ? ssh->csmac->len : 0;
1475 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1476 ssh->pktout.data[4] = padding;
1477 for (i = 0; i < padding; i++)
1478 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1479 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1481 ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
1482 ssh->pktout.length + padding,
1483 ssh->v2_outgoing_sequence);
1484 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1487 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1488 ssh->pktout.data, ssh->pktout.length + padding);
1490 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1491 return ssh->pktout.length + padding + maclen;
1495 * Construct and send an SSH2 packet immediately.
1497 static void ssh2_pkt_send(Ssh ssh)
1501 len = ssh2_pkt_construct(ssh);
1502 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1503 if (backlog > SSH_MAX_BACKLOG)
1504 ssh_throttle_all(ssh, 1, backlog);
1508 * Construct an SSH2 packet and add it to a deferred data block.
1509 * Useful for sending multiple packets in a single sk_write() call,
1510 * to prevent a traffic-analysing listener from being able to work
1511 * out the length of any particular packet (such as the password
1514 * Note that because SSH2 sequence-numbers its packets, this can
1515 * NOT be used as an m4-style `defer' allowing packets to be
1516 * constructed in one order and sent in another.
1518 static void ssh2_pkt_defer(Ssh ssh)
1520 int len = ssh2_pkt_construct(ssh);
1521 if (ssh->deferred_len + len > ssh->deferred_size) {
1522 ssh->deferred_size = ssh->deferred_len + len + 128;
1523 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1524 ssh->deferred_size);
1526 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1527 ssh->deferred_len += len;
1531 * Send the whole deferred data block constructed by
1532 * ssh2_pkt_defer() or SSH1's defer_packet().
1534 static void ssh_pkt_defersend(Ssh ssh)
1537 backlog = sk_write(ssh->s, ssh->deferred_send_data, ssh->deferred_len);
1538 ssh->deferred_len = ssh->deferred_size = 0;
1539 sfree(ssh->deferred_send_data);
1540 ssh->deferred_send_data = NULL;
1541 if (backlog > SSH_MAX_BACKLOG)
1542 ssh_throttle_all(ssh, 1, backlog);
1546 void bndebug(char *string, Bignum b)
1550 p = ssh2_mpint_fmt(b, &len);
1551 debug(("%s", string));
1552 for (i = 0; i < len; i++)
1553 debug((" %02x", p[i]));
1559 static void sha_mpint(SHA_State * s, Bignum b)
1563 p = ssh2_mpint_fmt(b, &len);
1564 sha_string(s, p, len);
1569 * SSH2 packet decode functions.
1571 static unsigned long ssh2_pkt_getuint32(Ssh ssh)
1573 unsigned long value;
1574 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1575 return 0; /* arrgh, no way to decline (FIXME?) */
1576 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1577 ssh->pktin.savedpos += 4;
1580 static int ssh2_pkt_getbool(Ssh ssh)
1582 unsigned long value;
1583 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
1584 return 0; /* arrgh, no way to decline (FIXME?) */
1585 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1586 ssh->pktin.savedpos++;
1589 static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
1593 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1595 *length = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1596 ssh->pktin.savedpos += 4;
1597 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
1599 *p = ssh->pktin.data + ssh->pktin.savedpos;
1600 ssh->pktin.savedpos += *length;
1602 static Bignum ssh2_pkt_getmp(Ssh ssh)
1608 ssh2_pkt_getstring(ssh, &p, &length);
1612 bombout(("internal error: Can't handle negative mpints"));
1615 b = bignum_from_bytes(p, length);
1620 * Helper function to add an SSH2 signature blob to a packet.
1621 * Expects to be shown the public key blob as well as the signature
1622 * blob. Normally works just like ssh2_pkt_addstring, but will
1623 * fiddle with the signature packet if necessary for
1624 * BUG_SSH2_RSA_PADDING.
1626 static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1627 void *sigblob_v, int sigblob_len)
1629 unsigned char *pkblob = (unsigned char *)pkblob_v;
1630 unsigned char *sigblob = (unsigned char *)sigblob_v;
1632 /* dmemdump(pkblob, pkblob_len); */
1633 /* dmemdump(sigblob, sigblob_len); */
1636 * See if this is in fact an ssh-rsa signature and a buggy
1637 * server; otherwise we can just do this the easy way.
1639 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1640 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1641 int pos, len, siglen;
1644 * Find the byte length of the modulus.
1647 pos = 4+7; /* skip over "ssh-rsa" */
1648 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1649 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1650 pos += 4; /* find modulus itself */
1651 while (len > 0 && pkblob[pos] == 0)
1653 /* debug(("modulus length is %d\n", len)); */
1656 * Now find the signature integer.
1658 pos = 4+7; /* skip over "ssh-rsa" */
1659 siglen = GET_32BIT(sigblob+pos);
1660 /* debug(("signature length is %d\n", siglen)); */
1662 if (len != siglen) {
1663 unsigned char newlen[4];
1664 ssh2_pkt_addstring_start(ssh);
1665 ssh2_pkt_addstring_data(ssh, sigblob, pos);
1666 /* dmemdump(sigblob, pos); */
1667 pos += 4; /* point to start of actual sig */
1668 PUT_32BIT(newlen, len);
1669 ssh2_pkt_addstring_data(ssh, newlen, 4);
1670 /* dmemdump(newlen, 4); */
1672 while (len-- > siglen) {
1673 ssh2_pkt_addstring_data(ssh, newlen, 1);
1674 /* dmemdump(newlen, 1); */
1676 ssh2_pkt_addstring_data(ssh, sigblob+pos, siglen);
1677 /* dmemdump(sigblob+pos, siglen); */
1681 /* Otherwise fall through and do it the easy way. */
1684 ssh2_pkt_addstring_start(ssh);
1685 ssh2_pkt_addstring_data(ssh, sigblob, sigblob_len);
1689 * Examine the remote side's version string and compare it against
1690 * a list of known buggy implementations.
1692 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1694 char *imp; /* pointer to implementation part */
1696 imp += strcspn(imp, "-");
1698 imp += strcspn(imp, "-");
1701 ssh->remote_bugs = 0;
1703 if (cfg.sshbug_ignore1 == BUG_ON ||
1704 (cfg.sshbug_ignore1 == BUG_AUTO &&
1705 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1706 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1707 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1709 * These versions don't support SSH1_MSG_IGNORE, so we have
1710 * to use a different defence against password length
1713 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1714 logevent("We believe remote version has SSH1 ignore bug");
1717 if (cfg.sshbug_plainpw1 == BUG_ON ||
1718 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1719 (!strcmp(imp, "Cisco-1.25")))) {
1721 * These versions need a plain password sent; they can't
1722 * handle having a null and a random length of data after
1725 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1726 logevent("We believe remote version needs a plain SSH1 password");
1729 if (cfg.sshbug_rsa1 == BUG_ON ||
1730 (cfg.sshbug_rsa1 == BUG_AUTO &&
1731 (!strcmp(imp, "Cisco-1.25")))) {
1733 * These versions apparently have no clue whatever about
1734 * RSA authentication and will panic and die if they see
1735 * an AUTH_RSA message.
1737 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
1738 logevent("We believe remote version can't handle RSA authentication");
1741 if (cfg.sshbug_hmac2 == BUG_ON ||
1742 (cfg.sshbug_hmac2 == BUG_AUTO &&
1743 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1744 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1745 !strncmp(imp, "2.1 ", 4)))) {
1747 * These versions have the HMAC bug.
1749 ssh->remote_bugs |= BUG_SSH2_HMAC;
1750 logevent("We believe remote version has SSH2 HMAC bug");
1753 if (cfg.sshbug_derivekey2 == BUG_ON ||
1754 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1755 (!strncmp(imp, "2.0.", 4)))) {
1757 * These versions have the key-derivation bug (failing to
1758 * include the literal shared secret in the hashes that
1759 * generate the keys).
1761 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
1762 logevent("We believe remote version has SSH2 key-derivation bug");
1765 if (cfg.sshbug_rsapad2 == BUG_ON ||
1766 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1767 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1768 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1770 * These versions have the SSH2 RSA padding bug.
1772 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1773 logevent("We believe remote version has SSH2 RSA padding bug");
1776 if (cfg.sshbug_dhgex2 == BUG_ON) {
1778 * These versions have the SSH2 DH GEX bug.
1780 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
1781 logevent("We believe remote version has SSH2 DH group exchange bug");
1785 static int do_ssh_init(Ssh ssh, unsigned char c)
1787 struct do_ssh_init_state {
1795 crState(do_ssh_init_state);
1797 crBegin(ssh->do_ssh_init_crstate);
1799 /* Search for the string "SSH-" in the input. */
1802 static const int transS[] = { 1, 2, 2, 1 };
1803 static const int transH[] = { 0, 0, 3, 0 };
1804 static const int transminus[] = { 0, 0, 0, -1 };
1806 s->i = transS[s->i];
1808 s->i = transH[s->i];
1810 s->i = transminus[s->i];
1815 crReturn(1); /* get another character */
1819 s->vstring = smalloc(s->vstrsize);
1820 strcpy(s->vstring, "SSH-");
1824 crReturn(1); /* get another char */
1825 if (s->vslen >= s->vstrsize - 1) {
1827 s->vstring = srealloc(s->vstring, s->vstrsize);
1829 s->vstring[s->vslen++] = c;
1832 s->version[s->i] = '\0';
1834 } else if (s->i < sizeof(s->version) - 1)
1835 s->version[s->i++] = c;
1836 } else if (c == '\n')
1840 ssh->agentfwd_enabled = FALSE;
1841 ssh->rdpkt2_state.incoming_sequence = 0;
1843 s->vstring[s->vslen] = 0;
1844 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1847 vlog = smalloc(20 + s->vslen);
1848 sprintf(vlog, "Server version: %s", s->vstring);
1852 ssh_detect_bugs(ssh, s->vstring);
1855 * Decide which SSH protocol version to support.
1858 /* Anything strictly below "2.0" means protocol 1 is supported. */
1859 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
1860 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1861 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
1863 if (cfg.sshprot == 0 && !s->proto1) {
1864 bombout(("SSH protocol version 1 required by user but not provided by server"));
1867 if (cfg.sshprot == 3 && !s->proto2) {
1868 bombout(("SSH protocol version 2 required by user but not provided by server"));
1872 if (s->proto2 && (cfg.sshprot >= 2 || !s->proto1)) {
1876 char verstring[80], vlog[100];
1877 sprintf(verstring, "SSH-2.0-%s", sshver);
1878 SHA_Init(&ssh->exhashbase);
1880 * Hash our version string and their version string.
1882 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1883 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
1884 sprintf(vlog, "We claim version: %s", verstring);
1886 strcat(verstring, "\n");
1887 logevent("Using SSH protocol version 2");
1888 sk_write(ssh->s, verstring, strlen(verstring));
1889 ssh->protocol = ssh2_protocol;
1891 ssh->s_rdpkt = ssh2_rdpkt;
1896 char verstring[80], vlog[100];
1897 sprintf(verstring, "SSH-%s-%s",
1898 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
1900 sprintf(vlog, "We claim version: %s", verstring);
1902 strcat(verstring, "\n");
1904 logevent("Using SSH protocol version 1");
1905 sk_write(ssh->s, verstring, strlen(verstring));
1906 ssh->protocol = ssh1_protocol;
1908 ssh->s_rdpkt = ssh1_rdpkt;
1910 ssh->state = SSH_STATE_BEFORE_SIZE;
1917 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
1919 crBegin(ssh->ssh_gotdata_crstate);
1922 * To begin with, feed the characters one by one to the
1923 * protocol initialisation / selection function do_ssh_init().
1924 * When that returns 0, we're done with the initial greeting
1925 * exchange and can move on to packet discipline.
1928 int ret; /* need not be kept across crReturn */
1930 crReturnV; /* more data please */
1931 ret = do_ssh_init(ssh, *data);
1939 * We emerge from that loop when the initial negotiation is
1940 * over and we have selected an s_rdpkt function. Now pass
1941 * everything to s_rdpkt, and then pass the resulting packets
1942 * to the proper protocol handler.
1947 while (datalen > 0) {
1948 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
1949 if (ssh->state == SSH_STATE_CLOSED) {
1952 ssh->protocol(ssh, NULL, 0, 1);
1953 if (ssh->state == SSH_STATE_CLOSED) {
1963 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1966 Ssh ssh = (Ssh) plug;
1967 ssh->state = SSH_STATE_CLOSED;
1973 /* A socket error has occurred. */
1974 logevent(error_msg);
1975 connection_fatal(error_msg);
1977 /* Otherwise, the remote side closed the connection normally. */
1982 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1984 Ssh ssh = (Ssh) plug;
1985 ssh_gotdata(ssh, data, len);
1986 if (ssh->state == SSH_STATE_CLOSED) {
1996 static void ssh_sent(Plug plug, int bufsize)
1998 Ssh ssh = (Ssh) plug;
2000 * If the send backlog on the SSH socket itself clears, we
2001 * should unthrottle the whole world if it was throttled.
2003 if (bufsize < SSH_MAX_BACKLOG)
2004 ssh_throttle_all(ssh, 0, bufsize);
2008 * Connect to specified host and port.
2009 * Returns an error message, or NULL on success.
2010 * Also places the canonical host name into `realhost'. It must be
2011 * freed by the caller.
2013 static char *connect_to_host(Ssh ssh, char *host, int port,
2014 char **realhost, int nodelay)
2016 static const struct plug_function_table fn_table = {
2026 ssh->savedhost = smalloc(1 + strlen(host));
2027 if (!ssh->savedhost)
2028 fatalbox("Out of memory");
2029 strcpy(ssh->savedhost, host);
2032 port = 22; /* default ssh port */
2033 ssh->savedport = port;
2040 sprintf(buf, "Looking up host \"%.170s\"", host);
2043 addr = sk_namelookup(host, realhost);
2044 if ((err = sk_addr_error(addr)))
2051 char buf[200], addrbuf[100];
2052 sk_getaddr(addr, addrbuf, 100);
2053 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2056 ssh->fn = &fn_table;
2057 ssh->s = new_connection(addr, *realhost, port, 0, 1, nodelay, (Plug) ssh);
2058 if ((err = sk_socket_error(ssh->s))) {
2067 * Throttle or unthrottle the SSH connection.
2069 static void ssh1_throttle(Ssh ssh, int adjust)
2071 int old_count = ssh->v1_throttle_count;
2072 ssh->v1_throttle_count += adjust;
2073 assert(ssh->v1_throttle_count >= 0);
2074 if (ssh->v1_throttle_count && !old_count) {
2075 sk_set_frozen(ssh->s, 1);
2076 } else if (!ssh->v1_throttle_count && old_count) {
2077 sk_set_frozen(ssh->s, 0);
2082 * Throttle or unthrottle _all_ local data streams (for when sends
2083 * on the SSH connection itself back up).
2085 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2088 struct ssh_channel *c;
2090 if (enable == ssh->throttled_all)
2092 ssh->throttled_all = enable;
2093 ssh->overall_bufsize = bufsize;
2096 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2098 case CHAN_MAINSESSION:
2100 * This is treated separately, outside the switch.
2104 x11_override_throttle(c->u.x11.s, enable);
2107 /* Agent channels require no buffer management. */
2110 pfd_override_throttle(c->u.x11.s, enable);
2117 * Username and password input, abstracted off into routines
2118 * reusable in several places - even between SSH1 and SSH2.
2121 /* Set up a username or password input loop on a given buffer. */
2122 void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2124 ssh->userpass_input_buffer = buffer;
2125 ssh->userpass_input_buflen = buflen;
2126 ssh->userpass_input_bufpos = 0;
2127 ssh->userpass_input_echo = echo;
2131 * Process some terminal data in the course of username/password
2132 * input. Returns >0 for success (line of input returned in
2133 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2134 * for inconclusive (keep waiting for more input please).
2136 int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2141 switch (c = *in++) {
2144 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2145 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2150 if (ssh->userpass_input_bufpos > 0) {
2151 if (ssh->userpass_input_echo)
2152 c_write_str(ssh, "\b \b");
2153 ssh->userpass_input_bufpos--;
2158 while (ssh->userpass_input_bufpos > 0) {
2159 if (ssh->userpass_input_echo)
2160 c_write_str(ssh, "\b \b");
2161 ssh->userpass_input_bufpos--;
2169 if (((c >= ' ' && c <= '~') ||
2170 ((unsigned char) c >= 160))
2171 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2172 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2173 if (ssh->userpass_input_echo)
2174 c_write(ssh, &c, 1);
2183 * Handle the key exchange and user authentication phases.
2185 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2188 unsigned char cookie[8];
2189 struct RSAKey servkey, hostkey;
2190 struct MD5Context md5c;
2191 struct do_ssh1_login_state {
2193 unsigned char *rsabuf, *keystr1, *keystr2;
2194 unsigned long supported_ciphers_mask, supported_auths_mask;
2195 int tried_publickey, tried_agent;
2196 int tis_auth_refused, ccard_auth_refused;
2197 unsigned char session_id[16];
2200 void *publickey_blob;
2201 int publickey_bloblen;
2207 unsigned char request[5], *response, *p;
2216 crState(do_ssh1_login_state);
2218 crBegin(ssh->do_ssh1_login_crstate);
2223 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2224 bombout(("Public key packet not received"));
2228 logevent("Received public keys");
2230 memcpy(cookie, ssh->pktin.body, 8);
2232 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2233 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
2236 * Log the host key fingerprint.
2240 logevent("Host key fingerprint is:");
2241 strcpy(logmsg, " ");
2242 hostkey.comment = NULL;
2243 rsa_fingerprint(logmsg + strlen(logmsg),
2244 sizeof(logmsg) - strlen(logmsg), &hostkey);
2248 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2249 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2250 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
2252 ssh->v1_local_protoflags =
2253 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2254 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2257 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2258 MD5Update(&md5c, s->keystr1, servkey.bytes);
2259 MD5Update(&md5c, ssh->pktin.body, 8);
2260 MD5Final(s->session_id, &md5c);
2262 for (i = 0; i < 32; i++)
2263 ssh->session_key[i] = random_byte();
2265 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2267 s->rsabuf = smalloc(s->len);
2269 fatalbox("Out of memory");
2272 * Verify the host key.
2276 * First format the key into a string.
2278 int len = rsastr_len(&hostkey);
2279 char fingerprint[100];
2280 char *keystr = smalloc(len);
2282 fatalbox("Out of memory");
2283 rsastr_fmt(keystr, &hostkey);
2284 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2285 verify_ssh_host_key(ssh->savedhost, ssh->savedport, "rsa", keystr,
2290 for (i = 0; i < 32; i++) {
2291 s->rsabuf[i] = ssh->session_key[i];
2293 s->rsabuf[i] ^= s->session_id[i];
2296 if (hostkey.bytes > servkey.bytes) {
2297 rsaencrypt(s->rsabuf, 32, &servkey);
2298 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2300 rsaencrypt(s->rsabuf, 32, &hostkey);
2301 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2304 logevent("Encrypted session key");
2307 int cipher_chosen = 0, warn = 0;
2308 char *cipher_string = NULL;
2310 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2311 int next_cipher = cfg.ssh_cipherlist[i];
2312 if (next_cipher == CIPHER_WARN) {
2313 /* If/when we choose a cipher, warn about it */
2315 } else if (next_cipher == CIPHER_AES) {
2316 /* XXX Probably don't need to mention this. */
2317 logevent("AES not supported in SSH1, skipping");
2319 switch (next_cipher) {
2320 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2321 cipher_string = "3DES"; break;
2322 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2323 cipher_string = "Blowfish"; break;
2324 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2325 cipher_string = "single-DES"; break;
2327 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2331 if (!cipher_chosen) {
2332 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2333 bombout(("Server violates SSH 1 protocol by not "
2334 "supporting 3DES encryption"));
2336 /* shouldn't happen */
2337 bombout(("No supported ciphers found"));
2341 /* Warn about chosen cipher if necessary. */
2343 askcipher(cipher_string, 0);
2346 switch (s->cipher_type) {
2347 case SSH_CIPHER_3DES:
2348 logevent("Using 3DES encryption");
2350 case SSH_CIPHER_DES:
2351 logevent("Using single-DES encryption");
2353 case SSH_CIPHER_BLOWFISH:
2354 logevent("Using Blowfish encryption");
2358 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2359 PKT_CHAR, s->cipher_type,
2360 PKT_DATA, cookie, 8,
2361 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2362 PKT_DATA, s->rsabuf, s->len,
2363 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2365 logevent("Trying to enable encryption...");
2369 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2370 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2372 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2373 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2376 sprintf(buf, "Initialised %.200s encryption", ssh->cipher->text_name);
2382 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2383 bombout(("Encryption not successfully enabled"));
2387 logevent("Successfully started encryption");
2391 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2392 if (ssh_get_line && !ssh_getline_pw_only) {
2393 if (!ssh_get_line("login as: ",
2394 s->username, sizeof(s->username), FALSE)) {
2396 * get_line failed to get a username.
2399 logevent("No username provided. Abandoning session.");
2400 ssh->state = SSH_STATE_CLOSED;
2404 int ret; /* need not be kept over crReturn */
2405 c_write_str(ssh, "login as: ");
2408 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2410 crWaitUntil(!ispkt);
2411 ret = process_userpass_input(ssh, in, inlen);
2415 c_write_str(ssh, "\r\n");
2418 strncpy(s->username, cfg.username, sizeof(s->username));
2419 s->username[sizeof(s->username)-1] = '\0';
2422 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2424 char userlog[22 + sizeof(s->username)];
2425 sprintf(userlog, "Sent username \"%s\"", s->username);
2427 if (flags & FLAG_INTERACTIVE &&
2428 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2429 strcat(userlog, "\r\n");
2430 c_write_str(ssh, userlog);
2437 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2438 /* We must not attempt PK auth. Pretend we've already tried it. */
2439 s->tried_publickey = s->tried_agent = 1;
2441 s->tried_publickey = s->tried_agent = 0;
2443 s->tis_auth_refused = s->ccard_auth_refused = 0;
2444 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2446 if (!rsakey_pubblob(cfg.keyfile,
2447 &s->publickey_blob, &s->publickey_bloblen))
2448 s->publickey_blob = NULL;
2450 s->publickey_blob = NULL;
2452 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2453 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2455 if (agent_exists() && !s->tried_agent) {
2457 * Attempt RSA authentication using Pageant.
2463 logevent("Pageant is running. Requesting keys.");
2465 /* Request the keys held by the agent. */
2466 PUT_32BIT(s->request, 1);
2467 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2468 agent_query(s->request, 5, &r, &s->responselen);
2469 s->response = (unsigned char *) r;
2470 if (s->response && s->responselen >= 5 &&
2471 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2472 s->p = s->response + 5;
2473 s->nkeys = GET_32BIT(s->p);
2477 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2480 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2483 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2486 if (s->publickey_blob &&
2487 !memcmp(s->p, s->publickey_blob,
2488 s->publickey_bloblen)) {
2489 logevent("This key matches configured key file");
2490 s->tried_publickey = 1;
2493 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2494 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2495 s->commentlen = GET_32BIT(s->p);
2498 s->p += s->commentlen;
2499 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2500 PKT_BIGNUM, s->key.modulus, PKT_END);
2502 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2503 logevent("Key refused");
2506 logevent("Received RSA challenge");
2507 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
2509 char *agentreq, *q, *ret;
2512 len = 1 + 4; /* message type, bit count */
2513 len += ssh1_bignum_length(s->key.exponent);
2514 len += ssh1_bignum_length(s->key.modulus);
2515 len += ssh1_bignum_length(s->challenge);
2516 len += 16; /* session id */
2517 len += 4; /* response format */
2518 agentreq = smalloc(4 + len);
2519 PUT_32BIT(agentreq, len);
2521 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2522 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2524 q += ssh1_write_bignum(q, s->key.exponent);
2525 q += ssh1_write_bignum(q, s->key.modulus);
2526 q += ssh1_write_bignum(q, s->challenge);
2527 memcpy(q, s->session_id, 16);
2529 PUT_32BIT(q, 1); /* response format */
2530 agent_query(agentreq, len + 4, &vret, &retlen);
2534 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2535 logevent("Sending Pageant's response");
2536 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2537 PKT_DATA, ret + 5, 16,
2541 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
2543 ("Pageant's response accepted");
2544 if (flags & FLAG_VERBOSE) {
2545 c_write_str(ssh, "Authenticated using"
2547 c_write(ssh, s->commentp,
2549 c_write_str(ssh, "\" from agent\r\n");
2554 ("Pageant's response not accepted");
2557 ("Pageant failed to answer challenge");
2561 logevent("No reply received from Pageant");
2564 freebn(s->key.exponent);
2565 freebn(s->key.modulus);
2566 freebn(s->challenge);
2574 if (*cfg.keyfile && !s->tried_publickey)
2575 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
2577 if (cfg.try_tis_auth &&
2578 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2579 !s->tis_auth_refused) {
2580 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2581 logevent("Requested TIS authentication");
2582 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
2584 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2585 logevent("TIS authentication declined");
2586 if (flags & FLAG_INTERACTIVE)
2587 c_write_str(ssh, "TIS authentication refused.\r\n");
2588 s->tis_auth_refused = 1;
2591 int challengelen = GET_32BIT(ssh->pktin.body);
2592 logevent("Received TIS challenge");
2593 if (challengelen > sizeof(s->prompt) - 1)
2594 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2595 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2596 /* Prompt heuristic comes from OpenSSH */
2597 strncpy(s->prompt + challengelen,
2598 memchr(s->prompt, '\n', challengelen) ?
2599 "": "\r\nResponse: ",
2600 (sizeof s->prompt) - challengelen);
2601 s->prompt[(sizeof s->prompt) - 1] = '\0';
2604 if (cfg.try_tis_auth &&
2605 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2606 !s->ccard_auth_refused) {
2607 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2608 logevent("Requested CryptoCard authentication");
2609 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
2611 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2612 logevent("CryptoCard authentication declined");
2613 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2614 s->ccard_auth_refused = 1;
2617 int challengelen = GET_32BIT(ssh->pktin.body);
2618 logevent("Received CryptoCard challenge");
2619 if (challengelen > sizeof(s->prompt) - 1)
2620 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2621 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2622 strncpy(s->prompt + challengelen,
2623 memchr(s->prompt, '\n', challengelen) ?
2624 "" : "\r\nResponse: ",
2625 sizeof(s->prompt) - challengelen);
2626 s->prompt[sizeof(s->prompt) - 1] = '\0';
2629 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2630 sprintf(s->prompt, "%.90s@%.90s's password: ",
2631 s->username, ssh->savedhost);
2633 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2634 char *comment = NULL;
2637 if (flags & FLAG_VERBOSE)
2638 c_write_str(ssh, "Trying public key authentication.\r\n");
2639 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2641 type = key_type(cfg.keyfile);
2642 if (type != SSH_KEYTYPE_SSH1) {
2643 sprintf(msgbuf, "Key is of wrong type (%s)",
2644 key_type_to_str(type));
2646 c_write_str(ssh, msgbuf);
2647 c_write_str(ssh, "\r\n");
2648 s->tried_publickey = 1;
2651 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2652 if (flags & FLAG_VERBOSE)
2653 c_write_str(ssh, "No passphrase required.\r\n");
2656 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
2661 * Show password prompt, having first obtained it via a TIS
2662 * or CryptoCard exchange if we're doing TIS or CryptoCard
2666 if (!ssh_get_line(s->prompt, s->password,
2667 sizeof(s->password), TRUE)) {
2669 * get_line failed to get a password (for example
2670 * because one was supplied on the command line
2671 * which has already failed to work). Terminate.
2673 send_packet(ssh, SSH1_MSG_DISCONNECT,
2674 PKT_STR, "No more passwords available to try",
2676 logevent("Unable to authenticate");
2677 connection_fatal("Unable to authenticate");
2678 ssh->state = SSH_STATE_CLOSED;
2682 /* Prompt may have come from server. We've munged it a bit, so
2683 * we know it to be zero-terminated at least once. */
2684 int ret; /* need not be saved over crReturn */
2685 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2688 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
2690 crWaitUntil(!ispkt);
2691 ret = process_userpass_input(ssh, in, inlen);
2695 c_write_str(ssh, "\r\n");
2699 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2701 * Try public key authentication with the specified
2704 s->tried_publickey = 1;
2707 int ret = loadrsakey(cfg.keyfile, &s->key, s->password);
2709 c_write_str(ssh, "Couldn't load private key from ");
2710 c_write_str(ssh, cfg.keyfile);
2711 c_write_str(ssh, ".\r\n");
2712 continue; /* go and try password */
2715 c_write_str(ssh, "Wrong passphrase.\r\n");
2716 s->tried_publickey = 0;
2717 continue; /* try again */
2722 * Send a public key attempt.
2724 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2725 PKT_BIGNUM, s->key.modulus, PKT_END);
2728 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2729 c_write_str(ssh, "Server refused our public key.\r\n");
2730 continue; /* go and try password */
2732 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2733 bombout(("Bizarre response to offer of public key"));
2739 unsigned char buffer[32];
2740 Bignum challenge, response;
2742 ssh1_read_bignum(ssh->pktin.body, &challenge);
2743 response = rsadecrypt(challenge, &s->key);
2744 freebn(s->key.private_exponent);/* burn the evidence */
2746 for (i = 0; i < 32; i++) {
2747 buffer[i] = bignum_byte(response, 31 - i);
2751 MD5Update(&md5c, buffer, 32);
2752 MD5Update(&md5c, s->session_id, 16);
2753 MD5Final(buffer, &md5c);
2755 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2756 PKT_DATA, buffer, 16, PKT_END);
2763 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2764 if (flags & FLAG_VERBOSE)
2765 c_write_str(ssh, "Failed to authenticate with"
2766 " our public key.\r\n");
2767 continue; /* go and try password */
2768 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2769 bombout(("Bizarre response to RSA authentication response"));
2773 break; /* we're through! */
2775 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2777 * Defence against traffic analysis: we send a
2778 * whole bunch of packets containing strings of
2779 * different lengths. One of these strings is the
2780 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2781 * The others are all random data in
2782 * SSH1_MSG_IGNORE packets. This way a passive
2783 * listener can't tell which is the password, and
2784 * hence can't deduce the password length.
2786 * Anybody with a password length greater than 16
2787 * bytes is going to have enough entropy in their
2788 * password that a listener won't find it _that_
2789 * much help to know how long it is. So what we'll
2792 * - if password length < 16, we send 15 packets
2793 * containing string lengths 1 through 15
2795 * - otherwise, we let N be the nearest multiple
2796 * of 8 below the password length, and send 8
2797 * packets containing string lengths N through
2798 * N+7. This won't obscure the order of
2799 * magnitude of the password length, but it will
2800 * introduce a bit of extra uncertainty.
2802 * A few servers (the old 1.2.18 through 1.2.22)
2803 * can't deal with SSH1_MSG_IGNORE. For these
2804 * servers, we need an alternative defence. We make
2805 * use of the fact that the password is interpreted
2806 * as a C string: so we can append a NUL, then some
2809 * One server (a Cisco one) can deal with neither
2810 * SSH1_MSG_IGNORE _nor_ a padded password string.
2811 * For this server we are left with no defences
2812 * against password length sniffing.
2814 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2816 * The server can deal with SSH1_MSG_IGNORE, so
2817 * we can use the primary defence.
2819 int bottom, top, pwlen, i;
2822 pwlen = strlen(s->password);
2824 bottom = 0; /* zero length passwords are OK! :-) */
2827 bottom = pwlen & ~7;
2831 assert(pwlen >= bottom && pwlen <= top);
2833 randomstr = smalloc(top + 1);
2835 for (i = bottom; i <= top; i++) {
2837 defer_packet(ssh, s->pwpkt_type,
2838 PKT_STR, s->password, PKT_END);
2840 for (j = 0; j < i; j++) {
2842 randomstr[j] = random_byte();
2843 } while (randomstr[j] == '\0');
2845 randomstr[i] = '\0';
2846 defer_packet(ssh, SSH1_MSG_IGNORE,
2847 PKT_STR, randomstr, PKT_END);
2850 logevent("Sending password with camouflage packets");
2851 ssh_pkt_defersend(ssh);
2853 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2855 * The server can't deal with SSH1_MSG_IGNORE
2856 * but can deal with padded passwords, so we
2857 * can use the secondary defence.
2863 len = strlen(s->password);
2864 if (len < sizeof(string)) {
2866 strcpy(string, s->password);
2867 len++; /* cover the zero byte */
2868 while (len < sizeof(string)) {
2869 string[len++] = (char) random_byte();
2874 logevent("Sending length-padded password");
2875 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2876 PKT_DATA, ss, len, PKT_END);
2879 * The server has _both_
2880 * BUG_CHOKES_ON_SSH1_IGNORE and
2881 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2882 * therefore nothing we can do.
2885 len = strlen(s->password);
2886 logevent("Sending unpadded password");
2887 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2888 PKT_DATA, s->password, len, PKT_END);
2891 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
2894 logevent("Sent password");
2895 memset(s->password, 0, strlen(s->password));
2897 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2898 if (flags & FLAG_VERBOSE)
2899 c_write_str(ssh, "Access denied\r\n");
2900 logevent("Authentication refused");
2901 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2902 bombout(("Strange packet received, type %d", ssh->pktin.type));
2907 logevent("Authentication successful");
2912 void sshfwd_close(struct ssh_channel *c)
2916 if (c && !c->closes) {
2918 * If the channel's remoteid is -1, we have sent
2919 * CHANNEL_OPEN for this channel, but it hasn't even been
2920 * acknowledged by the server. So we must set a close flag
2921 * on it now, and then when the server acks the channel
2922 * open, we can close it then.
2924 if (((int)c->remoteid) != -1) {
2925 if (ssh->version == 1) {
2926 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2929 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
2930 ssh2_pkt_adduint32(ssh, c->remoteid);
2934 c->closes = 1; /* sent MSG_CLOSE */
2935 if (c->type == CHAN_X11) {
2937 logevent("Forwarded X11 connection terminated");
2938 } else if (c->type == CHAN_SOCKDATA ||
2939 c->type == CHAN_SOCKDATA_DORMANT) {
2941 logevent("Forwarded port closed");
2946 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2950 if (ssh->version == 1) {
2951 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2952 PKT_INT, c->remoteid,
2953 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2955 * In SSH1 we can return 0 here - implying that forwarded
2956 * connections are never individually throttled - because
2957 * the only circumstance that can cause throttling will be
2958 * the whole SSH connection backing up, in which case
2959 * _everything_ will be throttled as a whole.
2963 ssh2_add_channel_data(c, buf, len);
2964 return ssh2_try_send(c);
2968 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2972 if (ssh->version == 1) {
2973 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2974 c->v.v1.throttling = 0;
2975 ssh1_throttle(ssh, -1);
2978 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2982 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2984 crBegin(ssh->ssh1_protocol_crstate);
2988 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
2991 if (ssh->state == SSH_STATE_CLOSED)
2994 if (cfg.agentfwd && agent_exists()) {
2995 logevent("Requesting agent forwarding");
2996 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3000 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3001 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3002 bombout(("Protocol confusion"));
3004 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3005 logevent("Agent forwarding refused");
3007 logevent("Agent forwarding enabled");
3008 ssh->agentfwd_enabled = TRUE;
3012 if (cfg.x11_forward) {
3013 char proto[20], data[64];
3014 logevent("Requesting X11 forwarding");
3015 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3016 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3017 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3018 PKT_STR, proto, PKT_STR, data,
3019 PKT_INT, 0, PKT_END);
3021 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3022 PKT_STR, proto, PKT_STR, data, PKT_END);
3027 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3028 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3029 bombout(("Protocol confusion"));
3031 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3032 logevent("X11 forwarding refused");
3034 logevent("X11 forwarding enabled");
3035 ssh->X11_fwd_enabled = TRUE;
3042 int sport,dport,sserv,dserv;
3043 char sports[256], dports[256], host[256];
3047 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3048 /* Add port forwardings. */
3049 ssh->portfwd_strptr = cfg.portfwd;
3050 while (*ssh->portfwd_strptr) {
3051 type = *ssh->portfwd_strptr++;
3053 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
3054 sports[n++] = *ssh->portfwd_strptr++;
3056 if (*ssh->portfwd_strptr == '\t')
3057 ssh->portfwd_strptr++;
3059 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
3060 host[n++] = *ssh->portfwd_strptr++;
3062 if (*ssh->portfwd_strptr == ':')
3063 ssh->portfwd_strptr++;
3065 while (*ssh->portfwd_strptr)
3066 dports[n++] = *ssh->portfwd_strptr++;
3068 ssh->portfwd_strptr++;
3069 dport = atoi(dports);
3073 se = getservbyname(dports, NULL);
3075 dport = ntohs(se->s_port);
3078 "Service lookup failed for destination port \"%s\"",
3083 sport = atoi(sports);
3087 se = getservbyname(sports, NULL);
3089 sport = ntohs(se->s_port);
3092 "Service lookup failed for source port \"%s\"",
3097 if (sport && dport) {
3099 pfd_addforward(host, dport, sport);
3100 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3101 " %s:%.*s%.*s%d%.*s",
3102 sserv ? strlen(sports) : 0, sports,
3103 sserv, "(", sport, sserv, ")",
3105 dserv ? strlen(dports) : 0, dports,
3106 dserv, "(", dport, dserv, ")");
3109 struct ssh_rportfwd *pf;
3110 pf = smalloc(sizeof(*pf));
3111 strcpy(pf->dhost, host);
3113 if (add234(ssh->rportfwds, pf) != pf) {
3115 "Duplicate remote port forwarding to %s:%d",
3120 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3121 " forward to %s:%.*s%.*s%d%.*s",
3122 sserv ? strlen(sports) : 0, sports,
3123 sserv, "(", sport, sserv, ")",
3125 dserv ? strlen(dports) : 0, dports,
3126 dserv, "(", dport, dserv, ")");
3128 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3136 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3137 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3138 bombout(("Protocol confusion"));
3140 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3141 c_write_str(ssh, "Server refused port"
3144 logevent("Remote port forwarding enabled");
3152 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
3153 PKT_STR, cfg.termtype,
3154 PKT_INT, ssh->term_height,
3155 PKT_INT, ssh->term_width,
3156 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3157 ssh->state = SSH_STATE_INTERMED;
3161 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3162 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3163 bombout(("Protocol confusion"));
3165 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3166 c_write_str(ssh, "Server refused to allocate pty\r\n");
3167 ssh->editing = ssh->echoing = 1;
3169 logevent("Allocated pty");
3171 ssh->editing = ssh->echoing = 1;
3174 if (cfg.compression) {
3175 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3179 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3180 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3181 bombout(("Protocol confusion"));
3183 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3184 c_write_str(ssh, "Server refused to compress\r\n");
3186 logevent("Started compression");
3187 ssh->v1_compressing = TRUE;
3188 zlib_compress_init();
3189 zlib_decompress_init();
3193 * Start the shell or command.
3195 * Special case: if the first-choice command is an SSH2
3196 * subsystem (hence not usable here) and the second choice
3197 * exists, we fall straight back to that.
3200 char *cmd = cfg.remote_cmd_ptr;
3202 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3203 cmd = cfg.remote_cmd_ptr2;
3204 ssh->fallback_cmd = TRUE;
3207 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3209 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
3210 logevent("Started session");
3213 ssh->state = SSH_STATE_SESSION;
3214 if (ssh->size_needed)
3215 ssh_size(ssh, ssh->term_width, ssh->term_height);
3216 if (ssh->eof_needed)
3217 ssh_special(ssh, TS_EOF);
3219 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
3221 ssh->channels = newtree234(ssh_channelcmp);
3225 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
3226 ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
3227 long len = GET_32BIT(ssh->pktin.body);
3229 from_backend(ssh->frontend,
3230 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
3231 ssh->pktin.body + 4, len);
3232 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3233 ssh->v1_stdout_throttling = 1;
3234 ssh1_throttle(ssh, +1);
3236 } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
3237 ssh->state = SSH_STATE_CLOSED;
3238 logevent("Received disconnect request");
3240 } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
3241 /* Remote side is trying to open a channel to talk to our
3242 * X-Server. Give them back a local channel number. */
3243 struct ssh_channel *c;
3245 logevent("Received X11 connect request");
3246 /* Refuse if X11 forwarding is disabled. */
3247 if (!ssh->X11_fwd_enabled) {
3248 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3249 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3250 logevent("Rejected X11 connect request");
3252 c = smalloc(sizeof(struct ssh_channel));
3255 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3256 logevent("opening X11 forward connection failed");
3258 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3259 PKT_INT, GET_32BIT(ssh->pktin.body),
3263 ("opening X11 forward connection succeeded");
3264 c->remoteid = GET_32BIT(ssh->pktin.body);
3265 c->localid = alloc_channel_id(ssh);
3267 c->v.v1.throttling = 0;
3268 c->type = CHAN_X11; /* identify channel type */
3269 add234(ssh->channels, c);
3270 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3271 PKT_INT, c->remoteid, PKT_INT,
3272 c->localid, PKT_END);
3273 logevent("Opened X11 forward channel");
3276 } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
3277 /* Remote side is trying to open a channel to talk to our
3278 * agent. Give them back a local channel number. */
3279 struct ssh_channel *c;
3281 /* Refuse if agent forwarding is disabled. */
3282 if (!ssh->agentfwd_enabled) {
3283 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3284 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3286 c = smalloc(sizeof(struct ssh_channel));
3288 c->remoteid = GET_32BIT(ssh->pktin.body);
3289 c->localid = alloc_channel_id(ssh);
3291 c->v.v1.throttling = 0;
3292 c->type = CHAN_AGENT; /* identify channel type */
3293 c->u.a.lensofar = 0;
3294 add234(ssh->channels, c);
3295 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3296 PKT_INT, c->remoteid, PKT_INT, c->localid,
3299 } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
3300 /* Remote side is trying to open a channel to talk to a
3301 * forwarded port. Give them back a local channel number. */
3302 struct ssh_channel *c;
3303 struct ssh_rportfwd pf;
3305 char host[256], buf[1024];
3307 c = smalloc(sizeof(struct ssh_channel));
3310 hostsize = GET_32BIT(ssh->pktin.body+4);
3311 for(h = host, p = ssh->pktin.body+8; hostsize != 0; hostsize--) {
3312 if (h+1 < host+sizeof(host))
3317 port = GET_32BIT(p);
3319 strcpy(pf.dhost, host);
3322 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3323 sprintf(buf, "Rejected remote port open request for %s:%d",
3326 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3327 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3329 sprintf(buf, "Received remote port open request for %s:%d",
3332 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3335 sprintf(buf, "Port open failed: %s", e);
3338 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3339 PKT_INT, GET_32BIT(ssh->pktin.body),
3342 c->remoteid = GET_32BIT(ssh->pktin.body);
3343 c->localid = alloc_channel_id(ssh);
3345 c->v.v1.throttling = 0;
3346 c->type = CHAN_SOCKDATA; /* identify channel type */
3347 add234(ssh->channels, c);
3348 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3349 PKT_INT, c->remoteid, PKT_INT,
3350 c->localid, PKT_END);
3351 logevent("Forwarded port opened successfully");
3355 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3356 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3357 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3358 struct ssh_channel *c;
3360 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3361 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3362 c->remoteid = localid;
3363 c->type = CHAN_SOCKDATA;
3364 c->v.v1.throttling = 0;
3365 pfd_confirm(c->u.pfd.s);
3368 if (c && c->closes) {
3370 * We have a pending close on this channel,
3371 * which we decided on before the server acked
3372 * the channel open. So now we know the
3373 * remoteid, we can close it again.
3375 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3376 PKT_INT, c->remoteid, PKT_END);
3379 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3380 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3381 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3382 struct ssh_channel *c;
3384 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3385 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3386 logevent("Forwarded connection refused by server");
3387 pfd_close(c->u.pfd.s);
3388 del234(ssh->channels, c);
3392 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3393 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3394 /* Remote side closes a channel. */
3395 unsigned i = GET_32BIT(ssh->pktin.body);
3396 struct ssh_channel *c;
3397 c = find234(ssh->channels, &i, ssh_channelfind);
3398 if (c && ((int)c->remoteid) != -1) {
3401 (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3403 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3404 logevent("Forwarded X11 connection terminated");
3405 assert(c->u.x11.s != NULL);
3406 x11_close(c->u.x11.s);
3409 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3410 logevent("Forwarded port closed");
3411 assert(c->u.pfd.s != NULL);
3412 pfd_close(c->u.pfd.s);
3416 c->closes |= (closetype << 2); /* seen this message */
3417 if (!(c->closes & closetype)) {
3418 send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
3420 c->closes |= closetype; /* sent it too */
3423 if (c->closes == 15) {
3424 del234(ssh->channels, c);
3428 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3429 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3430 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3433 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
3434 /* Data sent down one of our channels. */
3435 int i = GET_32BIT(ssh->pktin.body);
3436 int len = GET_32BIT(ssh->pktin.body + 4);
3437 unsigned char *p = ssh->pktin.body + 8;
3438 struct ssh_channel *c;
3439 c = find234(ssh->channels, &i, ssh_channelfind);
3444 bufsize = x11_send(c->u.x11.s, p, len);
3447 bufsize = pfd_send(c->u.pfd.s, p, len);
3450 /* Data for an agent message. Buffer it. */
3452 if (c->u.a.lensofar < 4) {
3453 int l = min(4 - c->u.a.lensofar, len);
3454 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3458 c->u.a.lensofar += l;
3460 if (c->u.a.lensofar == 4) {
3462 4 + GET_32BIT(c->u.a.msglen);
3463 c->u.a.message = smalloc(c->u.a.totallen);
3464 memcpy(c->u.a.message, c->u.a.msglen, 4);
3466 if (c->u.a.lensofar >= 4 && len > 0) {
3468 min(c->u.a.totallen - c->u.a.lensofar,
3470 memcpy(c->u.a.message + c->u.a.lensofar, p,
3474 c->u.a.lensofar += l;
3476 if (c->u.a.lensofar == c->u.a.totallen) {
3477 void *reply, *sentreply;
3479 agent_query(c->u.a.message,
3480 c->u.a.totallen, &reply,
3485 /* Fake SSH_AGENT_FAILURE. */
3486 sentreply = "\0\0\0\1\5";
3489 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3490 PKT_INT, c->remoteid,
3492 PKT_DATA, sentreply, replylen,
3496 sfree(c->u.a.message);
3497 c->u.a.lensofar = 0;
3500 bufsize = 0; /* agent channels never back up */
3503 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3504 c->v.v1.throttling = 1;
3505 ssh1_throttle(ssh, +1);
3508 } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
3509 /* may be from EXEC_SHELL on some servers */
3510 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3511 /* may be from EXEC_SHELL on some servers
3512 * if no pty is available or in other odd cases. Ignore */
3513 } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
3515 ssh->exitcode = GET_32BIT(ssh->pktin.body);
3516 sprintf(buf, "Server sent command exit status %d",
3519 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3521 * In case `helpful' firewalls or proxies tack
3522 * extra human-readable text on the end of the
3523 * session which we might mistake for another
3524 * encrypted packet, we close the session once
3525 * we've sent EXIT_CONFIRMATION.
3527 ssh->state = SSH_STATE_CLOSED;
3530 bombout(("Strange packet received: type %d", ssh->pktin.type));
3535 int len = min(inlen, 512);
3536 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
3537 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3548 * Utility routine for decoding comma-separated strings in KEXINIT.
3550 static int in_commasep_string(char *needle, char *haystack, int haylen)
3552 int needlen = strlen(needle);
3555 * Is it at the start of the string?
3557 if (haylen >= needlen && /* haystack is long enough */
3558 !memcmp(needle, haystack, needlen) && /* initial match */
3559 (haylen == needlen || haystack[needlen] == ',')
3560 /* either , or EOS follows */
3564 * If not, search for the next comma and resume after that.
3565 * If no comma found, terminate.
3567 while (haylen > 0 && *haystack != ',')
3568 haylen--, haystack++;
3571 haylen--, haystack++; /* skip over comma itself */
3576 * SSH2 key creation method.
3578 static void ssh2_mkkey(Ssh ssh, Bignum K, char *H, char *sessid, char chr,
3582 /* First 20 bytes. */
3584 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3586 SHA_Bytes(&s, H, 20);
3587 SHA_Bytes(&s, &chr, 1);
3588 SHA_Bytes(&s, sessid, 20);
3589 SHA_Final(&s, keyspace);
3590 /* Next 20 bytes. */
3592 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3594 SHA_Bytes(&s, H, 20);
3595 SHA_Bytes(&s, keyspace, 20);
3596 SHA_Final(&s, keyspace + 20);
3600 * Handle the SSH2 transport layer.
3602 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3604 struct do_ssh2_transport_state {
3605 int nbits, pbits, warn;
3606 Bignum p, g, e, f, K;
3607 int kex_init_value, kex_reply_value;
3608 const struct ssh_mac **maclist;
3610 const struct ssh2_cipher *cscipher_tobe;
3611 const struct ssh2_cipher *sccipher_tobe;
3612 const struct ssh_mac *csmac_tobe;
3613 const struct ssh_mac *scmac_tobe;
3614 const struct ssh_compress *cscomp_tobe;
3615 const struct ssh_compress *sccomp_tobe;
3616 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3617 int hostkeylen, siglen;
3618 void *hkey; /* actual host key */
3619 unsigned char exchange_hash[20];
3620 int n_preferred_ciphers;
3621 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3622 const struct ssh_compress *preferred_comp;
3625 crState(do_ssh2_transport_state);
3627 crBegin(ssh->do_ssh2_transport_crstate);
3629 s->cscipher_tobe = s->sccipher_tobe = NULL;
3630 s->csmac_tobe = s->scmac_tobe = NULL;
3631 s->cscomp_tobe = s->sccomp_tobe = NULL;
3639 * Set up the preferred ciphers. (NULL => warn below here)
3641 s->n_preferred_ciphers = 0;
3642 for (i = 0; i < CIPHER_MAX; i++) {
3643 switch (cfg.ssh_cipherlist[i]) {
3644 case CIPHER_BLOWFISH:
3645 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3648 if (cfg.ssh2_des_cbc) {
3649 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3653 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3656 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3659 /* Flag for later. Don't bother if it's the last in
3661 if (i < CIPHER_MAX - 1) {
3662 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3670 * Set up preferred compression.
3672 if (cfg.compression)
3673 s->preferred_comp = &ssh_zlib;
3675 s->preferred_comp = &ssh_comp_none;
3678 * Be prepared to work around the buggy MAC problem.
3680 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3681 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
3683 s->maclist = macs, s->nmacs = lenof(macs);
3687 int i, j, cipherstr_started;
3690 * Construct and send our key exchange packet.
3692 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3693 for (i = 0; i < 16; i++)
3694 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3695 /* List key exchange algorithms. */
3696 ssh2_pkt_addstring_start(ssh);
3697 for (i = 0; i < lenof(kex_algs); i++) {
3698 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3699 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3701 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3702 if (i < lenof(kex_algs) - 1)
3703 ssh2_pkt_addstring_str(ssh, ",");
3705 /* List server host key algorithms. */
3706 ssh2_pkt_addstring_start(ssh);
3707 for (i = 0; i < lenof(hostkey_algs); i++) {
3708 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3709 if (i < lenof(hostkey_algs) - 1)
3710 ssh2_pkt_addstring_str(ssh, ",");
3712 /* List client->server encryption algorithms. */
3713 ssh2_pkt_addstring_start(ssh);
3714 cipherstr_started = 0;
3715 for (i = 0; i < s->n_preferred_ciphers; i++) {
3716 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3717 if (!c) continue; /* warning flag */
3718 for (j = 0; j < c->nciphers; j++) {
3719 if (cipherstr_started)
3720 ssh2_pkt_addstring_str(ssh, ",");
3721 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3722 cipherstr_started = 1;
3725 /* List server->client encryption algorithms. */
3726 ssh2_pkt_addstring_start(ssh);
3727 cipherstr_started = 0;
3728 for (i = 0; i < s->n_preferred_ciphers; i++) {
3729 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3730 if (!c) continue; /* warning flag */
3731 for (j = 0; j < c->nciphers; j++) {
3732 if (cipherstr_started)
3733 ssh2_pkt_addstring_str(ssh, ",");
3734 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3735 cipherstr_started = 1;
3738 /* List client->server MAC algorithms. */
3739 ssh2_pkt_addstring_start(ssh);
3740 for (i = 0; i < s->nmacs; i++) {
3741 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3742 if (i < s->nmacs - 1)
3743 ssh2_pkt_addstring_str(ssh, ",");
3745 /* List server->client MAC algorithms. */
3746 ssh2_pkt_addstring_start(ssh);
3747 for (i = 0; i < s->nmacs; i++) {
3748 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3749 if (i < s->nmacs - 1)
3750 ssh2_pkt_addstring_str(ssh, ",");
3752 /* List client->server compression algorithms. */
3753 ssh2_pkt_addstring_start(ssh);
3754 for (i = 0; i < lenof(compressions) + 1; i++) {
3755 const struct ssh_compress *c =
3756 i == 0 ? s->preferred_comp : compressions[i - 1];
3757 ssh2_pkt_addstring_str(ssh, c->name);
3758 if (i < lenof(compressions))
3759 ssh2_pkt_addstring_str(ssh, ",");
3761 /* List server->client compression algorithms. */
3762 ssh2_pkt_addstring_start(ssh);
3763 for (i = 0; i < lenof(compressions) + 1; i++) {
3764 const struct ssh_compress *c =
3765 i == 0 ? s->preferred_comp : compressions[i - 1];
3766 ssh2_pkt_addstring_str(ssh, c->name);
3767 if (i < lenof(compressions))
3768 ssh2_pkt_addstring_str(ssh, ",");
3770 /* List client->server languages. Empty list. */
3771 ssh2_pkt_addstring_start(ssh);
3772 /* List server->client languages. Empty list. */
3773 ssh2_pkt_addstring_start(ssh);
3774 /* First KEX packet does _not_ follow, because we're not that brave. */
3775 ssh2_pkt_addbool(ssh, FALSE);
3777 ssh2_pkt_adduint32(ssh, 0);
3780 ssh->exhash = ssh->exhashbase;
3781 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
3787 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
3790 * Now examine the other side's KEXINIT to see what we're up
3797 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
3798 bombout(("expected key exchange packet from server"));
3802 ssh->hostkey = NULL;
3803 s->cscipher_tobe = NULL;
3804 s->sccipher_tobe = NULL;
3805 s->csmac_tobe = NULL;
3806 s->scmac_tobe = NULL;
3807 s->cscomp_tobe = NULL;
3808 s->sccomp_tobe = NULL;
3809 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3810 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3811 for (i = 0; i < lenof(kex_algs); i++) {
3812 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3813 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3815 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3816 ssh->kex = kex_algs[i];
3820 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3821 for (i = 0; i < lenof(hostkey_algs); i++) {
3822 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3823 ssh->hostkey = hostkey_algs[i];
3827 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3829 for (i = 0; i < s->n_preferred_ciphers; i++) {
3830 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3834 for (j = 0; j < c->nciphers; j++) {
3835 if (in_commasep_string(c->list[j]->name, str, len)) {
3836 s->cscipher_tobe = c->list[j];
3841 if (s->cscipher_tobe) {
3843 askcipher(s->cscipher_tobe->name, 1);
3847 if (!s->cscipher_tobe) {
3848 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3852 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3854 for (i = 0; i < s->n_preferred_ciphers; i++) {
3855 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3859 for (j = 0; j < c->nciphers; j++) {
3860 if (in_commasep_string(c->list[j]->name, str, len)) {
3861 s->sccipher_tobe = c->list[j];
3866 if (s->sccipher_tobe) {
3868 askcipher(s->sccipher_tobe->name, 2);
3872 if (!s->sccipher_tobe) {
3873 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3877 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3878 for (i = 0; i < s->nmacs; i++) {
3879 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3880 s->csmac_tobe = s->maclist[i];
3884 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3885 for (i = 0; i < s->nmacs; i++) {
3886 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3887 s->scmac_tobe = s->maclist[i];
3891 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3892 for (i = 0; i < lenof(compressions) + 1; i++) {
3893 const struct ssh_compress *c =
3894 i == 0 ? s->preferred_comp : compressions[i - 1];
3895 if (in_commasep_string(c->name, str, len)) {
3900 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
3901 for (i = 0; i < lenof(compressions) + 1; i++) {
3902 const struct ssh_compress *c =
3903 i == 0 ? s->preferred_comp : compressions[i - 1];
3904 if (in_commasep_string(c->name, str, len)) {
3912 * Work out the number of bits of key we will need from the key
3913 * exchange. We start with the maximum key length of either
3919 csbits = s->cscipher_tobe->keylen;
3920 scbits = s->sccipher_tobe->keylen;
3921 s->nbits = (csbits > scbits ? csbits : scbits);
3923 /* The keys only have 160-bit entropy, since they're based on
3924 * a SHA-1 hash. So cap the key size at 160 bits. */
3929 * If we're doing Diffie-Hellman group exchange, start by
3930 * requesting a group.
3932 if (ssh->kex == &ssh_diffiehellman_gex) {
3933 logevent("Doing Diffie-Hellman group exchange");
3934 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
3936 * Work out how big a DH group we will need to allow that
3939 s->pbits = 512 << ((s->nbits - 1) / 64);
3940 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
3941 ssh2_pkt_adduint32(ssh, s->pbits);
3945 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3946 bombout(("expected key exchange group packet from server"));
3949 s->p = ssh2_pkt_getmp(ssh);
3950 s->g = ssh2_pkt_getmp(ssh);
3951 dh_setup_group(s->p, s->g);
3952 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3953 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3955 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3957 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
3958 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3961 logevent("Doing Diffie-Hellman key exchange");
3963 * Now generate and send e for Diffie-Hellman.
3965 s->e = dh_create_e(s->nbits * 2);
3966 ssh2_pkt_init(ssh, s->kex_init_value);
3967 ssh2_pkt_addmp(ssh, s->e);
3971 if (ssh->pktin.type != s->kex_reply_value) {
3972 bombout(("expected key exchange reply packet from server"));
3975 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
3976 s->f = ssh2_pkt_getmp(ssh);
3977 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
3979 s->K = dh_find_K(s->f);
3981 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
3982 if (ssh->kex == &ssh_diffiehellman_gex) {
3983 sha_uint32(&ssh->exhash, s->pbits);
3984 sha_mpint(&ssh->exhash, s->p);
3985 sha_mpint(&ssh->exhash, s->g);
3987 sha_mpint(&ssh->exhash, s->e);
3988 sha_mpint(&ssh->exhash, s->f);
3989 sha_mpint(&ssh->exhash, s->K);
3990 SHA_Final(&ssh->exhash, s->exchange_hash);
3995 debug(("Exchange hash is:\n"));
3996 dmemdump(s->exchange_hash, 20);
3999 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4001 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4002 s->exchange_hash, 20)) {
4003 bombout(("Server's host key did not match the signature supplied"));
4008 * Authenticate remote host: verify host key. (We've already
4009 * checked the signature of the exchange hash.)
4011 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4012 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4013 verify_ssh_host_key(ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4014 s->keystr, s->fingerprint);
4015 if (s->first_kex) { /* don't bother logging this in rekeys */
4016 logevent("Host key fingerprint is:");
4017 logevent(s->fingerprint);
4019 sfree(s->fingerprint);
4021 ssh->hostkey->freekey(s->hkey);
4024 * Send SSH2_MSG_NEWKEYS.
4026 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4030 * Expect SSH2_MSG_NEWKEYS from server.
4033 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
4034 bombout(("expected new-keys packet from server"));
4039 * Create and initialise session keys.
4041 if (ssh->cs_cipher_ctx)
4042 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4043 ssh->cscipher = s->cscipher_tobe;
4044 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4046 if (ssh->sc_cipher_ctx)
4047 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4048 ssh->sccipher = s->sccipher_tobe;
4049 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4051 if (ssh->cs_mac_ctx)
4052 ssh->csmac->free_context(ssh->cs_mac_ctx);
4053 ssh->csmac = s->csmac_tobe;
4054 ssh->cs_mac_ctx = ssh->csmac->make_context();
4056 if (ssh->sc_mac_ctx)
4057 ssh->scmac->free_context(ssh->sc_mac_ctx);
4058 ssh->scmac = s->scmac_tobe;
4059 ssh->sc_mac_ctx = ssh->scmac->make_context();
4061 ssh->cscomp = s->cscomp_tobe;
4062 ssh->sccomp = s->sccomp_tobe;
4063 ssh->cscomp->compress_init();
4064 ssh->sccomp->decompress_init();
4066 * Set IVs after keys. Here we use the exchange hash from the
4067 * _first_ key exchange.
4070 unsigned char keyspace[40];
4072 memcpy(ssh->v2_session_id, s->exchange_hash,
4073 sizeof(s->exchange_hash));
4074 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4075 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4076 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4077 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4078 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4079 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4080 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4081 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4082 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4083 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4084 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4085 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4089 sprintf(buf, "Initialised %.200s client->server encryption",
4090 ssh->cscipher->text_name);
4092 sprintf(buf, "Initialised %.200s server->client encryption",
4093 ssh->sccipher->text_name);
4099 * If this is the first key exchange phase, we must pass the
4100 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4101 * wants to see it but because it will need time to initialise
4102 * itself before it sees an actual packet. In subsequent key
4103 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4104 * it would only confuse the layer above.
4106 if (!s->first_kex) {
4112 * Now we're encrypting. Begin returning 1 to the protocol main
4113 * function so that other things can run on top of the
4114 * transport. If we ever see a KEXINIT, we must go back to the
4117 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
4120 logevent("Server initiated key re-exchange");
4121 goto begin_key_exchange;
4127 * Add data to an SSH2 channel output buffer.
4129 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4132 bufchain_add(&c->v.v2.outbuffer, buf, len);
4136 * Attempt to send data on an SSH2 channel.
4138 static int ssh2_try_send(struct ssh_channel *c)
4142 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4145 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4146 if ((unsigned)len > c->v.v2.remwindow)
4147 len = c->v.v2.remwindow;
4148 if ((unsigned)len > c->v.v2.remmaxpkt)
4149 len = c->v.v2.remmaxpkt;
4150 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4151 ssh2_pkt_adduint32(ssh, c->remoteid);
4152 ssh2_pkt_addstring_start(ssh);
4153 ssh2_pkt_addstring_data(ssh, data, len);
4155 bufchain_consume(&c->v.v2.outbuffer, len);
4156 c->v.v2.remwindow -= len;
4160 * After having sent as much data as we can, return the amount
4163 return bufchain_size(&c->v.v2.outbuffer);
4167 * Potentially enlarge the window on an SSH2 channel.
4169 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4174 * Never send WINDOW_ADJUST for a channel that the remote side
4175 * already thinks it's closed; there's no point, since it won't
4176 * be sending any more data anyway.
4181 if (newwin > c->v.v2.locwindow) {
4182 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4183 ssh2_pkt_adduint32(ssh, c->remoteid);
4184 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4186 c->v.v2.locwindow = newwin;
4191 * Handle the SSH2 userauth and connection layers.
4193 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
4195 struct do_ssh2_authconn_state {
4197 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4199 AUTH_KEYBOARD_INTERACTIVE
4203 AUTH_TYPE_PUBLICKEY,
4204 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4205 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4207 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4208 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4210 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4211 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4212 int kbd_inter_running;
4214 int num_prompts, curr_prompt, echo;
4219 void *publickey_blob;
4220 int publickey_bloblen;
4221 unsigned char request[5], *response, *p;
4225 char *pkblob, *alg, *commentp;
4226 int pklen, alglen, commentlen;
4227 int siglen, retlen, len;
4228 char *q, *agentreq, *ret;
4231 crState(do_ssh2_authconn_state);
4233 crBegin(ssh->do_ssh2_authconn_crstate);
4236 * Request userauth protocol, and await a response to it.
4238 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4239 ssh2_pkt_addstring(ssh, "ssh-userauth");
4241 crWaitUntilV(ispkt);
4242 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4243 bombout(("Server refused user authentication protocol"));
4248 * We repeat this whole loop, including the username prompt,
4249 * until we manage a successful authentication. If the user
4250 * types the wrong _password_, they can be sent back to the
4251 * beginning to try another username, if this is configured on.
4252 * (If they specify a username in the config, they are never
4253 * asked, even if they do give a wrong password.)
4255 * I think this best serves the needs of
4257 * - the people who have no configuration, no keys, and just
4258 * want to try repeated (username,password) pairs until they
4259 * type both correctly
4261 * - people who have keys and configuration but occasionally
4262 * need to fall back to passwords
4264 * - people with a key held in Pageant, who might not have
4265 * logged in to a particular machine before; so they want to
4266 * type a username, and then _either_ their key will be
4267 * accepted, _or_ they will type a password. If they mistype
4268 * the username they will want to be able to get back and
4271 s->username[0] = '\0';
4272 s->got_username = FALSE;
4277 if (s->got_username && !cfg.change_username) {
4279 * We got a username last time round this loop, and
4280 * with change_username turned off we don't try to get
4283 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4284 if (ssh_get_line && !ssh_getline_pw_only) {
4285 if (!ssh_get_line("login as: ",
4286 s->username, sizeof(s->username), FALSE)) {
4288 * get_line failed to get a username.
4291 logevent("No username provided. Abandoning session.");
4292 ssh->state = SSH_STATE_CLOSED;
4296 int ret; /* need not be saved across crReturn */
4297 c_write_str(ssh, "login as: ");
4299 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
4301 crWaitUntilV(!ispkt);
4302 ret = process_userpass_input(ssh, in, inlen);
4307 c_write_str(ssh, "\r\n");
4308 s->username[strcspn(s->username, "\n\r")] = '\0';
4311 strncpy(s->username, cfg.username, sizeof(s->username));
4312 s->username[sizeof(s->username)-1] = '\0';
4313 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4314 sprintf(stuff, "Using username \"%s\".\r\n", s->username);
4315 c_write_str(ssh, stuff);
4318 s->got_username = TRUE;
4321 * Send an authentication request using method "none": (a)
4322 * just in case it succeeds, and (b) so that we know what
4323 * authentication methods we can usefully try next.
4325 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4327 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4328 ssh2_pkt_addstring(ssh, s->username);
4329 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4330 ssh2_pkt_addstring(ssh, "none"); /* method */
4332 s->type = AUTH_TYPE_NONE;
4334 s->we_are_in = FALSE;
4336 s->tried_pubkey_config = FALSE;
4337 s->tried_agent = FALSE;
4338 s->tried_keyb_inter = FALSE;
4339 s->kbd_inter_running = FALSE;
4340 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4343 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4344 keytype = key_type(cfg.keyfile);
4345 if (keytype == SSH_KEYTYPE_SSH2) {
4347 ssh2_userkey_loadpub(cfg.keyfile, NULL,
4348 &s->publickey_bloblen);
4351 logeventf("Unable to use this key file (%s)",
4352 key_type_to_str(keytype));
4353 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4354 cfg.keyfile, key_type_to_str(keytype));
4355 c_write_str(ssh, msgbuf);
4356 s->publickey_blob = NULL;
4359 s->publickey_blob = NULL;
4363 * Wait for the result of the last authentication request.
4366 crWaitUntilV(ispkt);
4367 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4371 * Don't show the banner if we're operating in
4372 * non-verbose non-interactive mode. (It's probably
4373 * a script, which means nobody will read the
4374 * banner _anyway_, and moreover the printing of
4375 * the banner will screw up processing on the
4376 * output of (say) plink.)
4378 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4379 ssh2_pkt_getstring(ssh, &banner, &size);
4381 c_write_untrusted(ssh, banner, size);
4383 crWaitUntilV(ispkt);
4385 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4386 logevent("Access granted");
4387 s->we_are_in = TRUE;
4391 if (s->kbd_inter_running &&
4392 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4394 * This is either a further set-of-prompts packet
4395 * in keyboard-interactive authentication, or it's
4396 * the same one and we came back here with `gotit'
4397 * set. In the former case, we must reset the
4398 * curr_prompt variable.
4402 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4403 bombout(("Strange packet received during authentication: type %d",
4411 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4412 * we can look at the string in it and know what we can
4413 * helpfully try next.
4415 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4418 ssh2_pkt_getstring(ssh, &methods, &methlen);
4419 s->kbd_inter_running = FALSE;
4420 if (!ssh2_pkt_getbool(ssh)) {
4422 * We have received an unequivocal Access
4423 * Denied. This can translate to a variety of
4426 * - if we'd just tried "none" authentication,
4427 * it's not worth printing anything at all
4429 * - if we'd just tried a public key _offer_,
4430 * the message should be "Server refused our
4431 * key" (or no message at all if the key
4432 * came from Pageant)
4434 * - if we'd just tried anything else, the
4435 * message really should be "Access denied".
4437 * Additionally, if we'd just tried password
4438 * authentication, we should break out of this
4439 * whole loop so as to go back to the username
4442 if (s->type == AUTH_TYPE_NONE) {
4444 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4445 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4446 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4447 c_write_str(ssh, "Server refused our key\r\n");
4448 logevent("Server refused public key");
4449 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4450 /* server declined keyboard-interactive; ignore */
4452 c_write_str(ssh, "Access denied\r\n");
4453 logevent("Access denied");
4454 if (s->type == AUTH_TYPE_PASSWORD) {
4455 s->we_are_in = FALSE;
4460 c_write_str(ssh, "Further authentication required\r\n");
4461 logevent("Further authentication required");
4465 in_commasep_string("publickey", methods, methlen);
4467 in_commasep_string("password", methods, methlen);
4468 s->can_keyb_inter = cfg.try_ki_auth &&
4469 in_commasep_string("keyboard-interactive", methods, methlen);
4473 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4476 * Most password/passphrase prompts will be
4477 * non-echoing, so we set this to 0 by default.
4478 * Exception is that some keyboard-interactive prompts
4479 * can be echoing, in which case we'll set this to 1.
4483 if (!s->method && s->can_pubkey &&
4484 agent_exists() && !s->tried_agent) {
4486 * Attempt public-key authentication using Pageant.
4491 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4492 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4494 s->tried_agent = TRUE;
4496 logevent("Pageant is running. Requesting keys.");
4498 /* Request the keys held by the agent. */
4499 PUT_32BIT(s->request, 1);
4500 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4501 agent_query(s->request, 5, &r, &s->responselen);
4502 s->response = (unsigned char *) r;
4503 if (s->response && s->responselen >= 5 &&
4504 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4505 s->p = s->response + 5;
4506 s->nkeys = GET_32BIT(s->p);
4510 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
4513 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4518 sprintf(buf, "Trying Pageant key #%d", s->keyi);
4521 s->pklen = GET_32BIT(s->p);
4523 if (s->publickey_blob &&
4524 s->pklen == s->publickey_bloblen &&
4525 !memcmp(s->p, s->publickey_blob,
4526 s->publickey_bloblen)) {
4527 logevent("This key matches configured key file");
4528 s->tried_pubkey_config = 1;
4532 s->alglen = GET_32BIT(s->pkblob);
4533 s->alg = s->pkblob + 4;
4534 s->commentlen = GET_32BIT(s->p);
4537 s->p += s->commentlen;
4538 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4539 ssh2_pkt_addstring(ssh, s->username);
4540 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4541 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4542 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4543 ssh2_pkt_addstring_start(ssh);
4544 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4545 ssh2_pkt_addstring_start(ssh);
4546 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4549 crWaitUntilV(ispkt);
4550 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4551 logevent("Key refused");
4555 if (flags & FLAG_VERBOSE) {
4556 c_write_str(ssh, "Authenticating with "
4558 c_write(ssh, s->commentp, s->commentlen);
4559 c_write_str(ssh, "\" from agent\r\n");
4563 * Server is willing to accept the key.
4564 * Construct a SIGN_REQUEST.
4566 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4567 ssh2_pkt_addstring(ssh, s->username);
4568 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4569 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4570 ssh2_pkt_addbool(ssh, TRUE);
4571 ssh2_pkt_addstring_start(ssh);
4572 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4573 ssh2_pkt_addstring_start(ssh);
4574 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4576 s->siglen = ssh->pktout.length - 5 + 4 + 20;
4577 s->len = 1; /* message type */
4578 s->len += 4 + s->pklen; /* key blob */
4579 s->len += 4 + s->siglen; /* data to sign */
4580 s->len += 4; /* flags */
4581 s->agentreq = smalloc(4 + s->len);
4582 PUT_32BIT(s->agentreq, s->len);
4583 s->q = s->agentreq + 4;
4584 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4585 PUT_32BIT(s->q, s->pklen);
4587 memcpy(s->q, s->pkblob, s->pklen);
4589 PUT_32BIT(s->q, s->siglen);
4591 /* Now the data to be signed... */
4592 PUT_32BIT(s->q, 20);
4594 memcpy(s->q, ssh->v2_session_id, 20);
4596 memcpy(s->q, ssh->pktout.data + 5,
4597 ssh->pktout.length - 5);
4598 s->q += ssh->pktout.length - 5;
4599 /* And finally the (zero) flags word. */
4601 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4605 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4606 logevent("Sending Pageant's response");
4607 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4609 GET_32BIT(s->ret + 5));
4615 ("Pageant failed to answer challenge");
4625 if (!s->method && s->can_pubkey && s->publickey_blob
4626 && !s->tried_pubkey_config) {
4627 unsigned char *pub_blob;
4628 char *algorithm, *comment;
4631 s->tried_pubkey_config = TRUE;
4633 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4634 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4637 * Try the public key supplied in the configuration.
4639 * First, offer the public blob to see if the server is
4640 * willing to accept it.
4642 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4645 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4646 ssh2_pkt_addstring(ssh, s->username);
4647 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4648 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4649 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4650 ssh2_pkt_addstring(ssh, algorithm);
4651 ssh2_pkt_addstring_start(ssh);
4652 ssh2_pkt_addstring_data(ssh, pub_blob, pub_blob_len);
4654 logevent("Offered public key"); /* FIXME */
4656 crWaitUntilV(ispkt);
4657 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4659 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4660 continue; /* key refused; give up on it */
4663 logevent("Offer of public key accepted");
4665 * Actually attempt a serious authentication using
4668 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4669 sprintf(s->pwprompt,
4670 "Passphrase for key \"%.100s\": ",
4676 c_write_str(ssh, "Authenticating with public key \"");
4677 c_write_str(ssh, comment);
4678 c_write_str(ssh, "\"\r\n");
4679 s->method = AUTH_PUBLICKEY_FILE;
4683 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4684 s->method = AUTH_KEYBOARD_INTERACTIVE;
4685 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4686 s->tried_keyb_inter = TRUE;
4688 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4689 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4691 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4692 ssh2_pkt_addstring(ssh, s->username);
4693 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4694 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4695 ssh2_pkt_addstring(ssh, ""); /* lang */
4696 ssh2_pkt_addstring(ssh, "");
4699 crWaitUntilV(ispkt);
4700 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4701 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4703 logevent("Keyboard-interactive authentication refused");
4704 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4708 s->kbd_inter_running = TRUE;
4712 if (s->kbd_inter_running) {
4713 s->method = AUTH_KEYBOARD_INTERACTIVE;
4714 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4715 s->tried_keyb_inter = TRUE;
4717 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4718 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4720 if (s->curr_prompt == 0) {
4722 * We've got a fresh USERAUTH_INFO_REQUEST.
4723 * Display header data, and start going through
4726 char *name, *inst, *lang;
4727 int name_len, inst_len, lang_len;
4729 ssh2_pkt_getstring(ssh, &name, &name_len);
4730 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4731 ssh2_pkt_getstring(ssh, &lang, &lang_len);
4733 c_write_untrusted(ssh, name, name_len);
4734 c_write_str(ssh, "\r\n");
4737 c_write_untrusted(ssh, inst, inst_len);
4738 c_write_str(ssh, "\r\n");
4740 s->num_prompts = ssh2_pkt_getuint32(ssh);
4744 * If there are prompts remaining in the packet,
4745 * display one and get a response.
4747 if (s->curr_prompt < s->num_prompts) {
4751 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
4752 if (prompt_len > 0) {
4753 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4754 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4755 prompt_len : sizeof(s->pwprompt)-1] = '\0';
4758 "<server failed to send prompt>: ");
4760 s->echo = ssh2_pkt_getbool(ssh);
4766 if (!s->method && s->can_passwd) {
4767 s->method = AUTH_PASSWORD;
4768 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4769 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4770 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4777 if (!ssh_get_line(s->pwprompt, s->password,
4778 sizeof(s->password), TRUE)) {
4780 * get_line failed to get a password (for
4781 * example because one was supplied on the
4782 * command line which has already failed to
4785 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4786 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4787 ssh2_pkt_addstring(ssh, "No more passwords available"
4789 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4791 logevent("Unable to authenticate");
4792 connection_fatal("Unable to authenticate");
4793 ssh->state = SSH_STATE_CLOSED;
4797 int ret; /* need not be saved across crReturn */
4798 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4801 setup_userpass_input(ssh, s->password,
4802 sizeof(s->password), s->echo);
4804 crWaitUntilV(!ispkt);
4805 ret = process_userpass_input(ssh, in, inlen);
4809 c_write_str(ssh, "\r\n");
4813 if (s->method == AUTH_PUBLICKEY_FILE) {
4815 * We have our passphrase. Now try the actual authentication.
4817 struct ssh2_userkey *key;
4819 key = ssh2_load_userkey(cfg.keyfile, s->password);
4820 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4821 if (key == SSH2_WRONG_PASSPHRASE) {
4822 c_write_str(ssh, "Wrong passphrase\r\n");
4823 s->tried_pubkey_config = FALSE;
4825 c_write_str(ssh, "Unable to load private key\r\n");
4826 s->tried_pubkey_config = TRUE;
4828 /* Send a spurious AUTH_NONE to return to the top. */
4829 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4830 ssh2_pkt_addstring(ssh, s->username);
4831 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4832 ssh2_pkt_addstring(ssh, "none"); /* method */
4834 s->type = AUTH_TYPE_NONE;
4836 unsigned char *pkblob, *sigblob, *sigdata;
4837 int pkblob_len, sigblob_len, sigdata_len;
4840 * We have loaded the private key and the server
4841 * has announced that it's willing to accept it.
4842 * Hallelujah. Generate a signature and send it.
4844 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4845 ssh2_pkt_addstring(ssh, s->username);
4846 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4847 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4848 ssh2_pkt_addbool(ssh, TRUE);
4849 ssh2_pkt_addstring(ssh, key->alg->name);
4850 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4851 ssh2_pkt_addstring_start(ssh);
4852 ssh2_pkt_addstring_data(ssh, pkblob, pkblob_len);
4855 * The data to be signed is:
4859 * followed by everything so far placed in the
4862 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
4863 sigdata = smalloc(sigdata_len);
4864 PUT_32BIT(sigdata, 20);
4865 memcpy(sigdata + 4, ssh->v2_session_id, 20);
4866 memcpy(sigdata + 24, ssh->pktout.data + 5,
4867 ssh->pktout.length - 5);
4868 sigblob = key->alg->sign(key->data, sigdata,
4869 sigdata_len, &sigblob_len);
4870 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
4871 sigblob, sigblob_len);
4877 s->type = AUTH_TYPE_PUBLICKEY;
4879 } else if (s->method == AUTH_PASSWORD) {
4881 * We send the password packet lumped tightly together with
4882 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4883 * string long enough to make the total length of the two
4884 * packets constant. This should ensure that a passive
4885 * listener doing traffic analyis can't work out the length
4888 * For this to work, we need an assumption about the
4889 * maximum length of the password packet. I think 256 is
4890 * pretty conservative. Anyone using a password longer than
4891 * that probably doesn't have much to worry about from
4892 * people who find out how long their password is!
4894 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4895 ssh2_pkt_addstring(ssh, s->username);
4896 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4897 ssh2_pkt_addstring(ssh, "password");
4898 ssh2_pkt_addbool(ssh, FALSE);
4899 ssh2_pkt_addstring(ssh, s->password);
4900 ssh2_pkt_defer(ssh);
4902 * We'll include a string that's an exact multiple of the
4903 * cipher block size. If the cipher is NULL for some
4904 * reason, we don't do this trick at all because we gain
4907 if (ssh->cscipher) {
4910 stringlen = (256 - ssh->deferred_len);
4911 stringlen += ssh->cscipher->blksize - 1;
4912 stringlen -= (stringlen % ssh->cscipher->blksize);
4915 * Temporarily disable actual compression,
4916 * so we can guarantee to get this string
4917 * exactly the length we want it. The
4918 * compression-disabling routine should
4919 * return an integer indicating how many
4920 * bytes we should adjust our string length
4923 stringlen -= ssh->cscomp->disable_compression();
4925 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
4926 ssh2_pkt_addstring_start(ssh);
4927 for (i = 0; i < stringlen; i++) {
4928 char c = (char) random_byte();
4929 ssh2_pkt_addstring_data(ssh, &c, 1);
4931 ssh2_pkt_defer(ssh);
4933 ssh_pkt_defersend(ssh);
4934 logevent("Sent password");
4935 s->type = AUTH_TYPE_PASSWORD;
4936 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
4937 if (s->curr_prompt == 0) {
4938 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
4939 ssh2_pkt_adduint32(ssh, s->num_prompts);
4941 if (s->need_pw) { /* only add pw if we just got one! */
4942 ssh2_pkt_addstring(ssh, s->password);
4943 memset(s->password, 0, sizeof(s->password));
4946 if (s->curr_prompt >= s->num_prompts) {
4950 * If there are prompts remaining, we set
4951 * `gotit' so that we won't attempt to get
4952 * another packet. Then we go back round the
4953 * loop and will end up retrieving another
4954 * prompt out of the existing packet. Funky or
4959 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4961 c_write_str(ssh, "No supported authentication methods"
4962 " left to try!\r\n");
4963 logevent("No supported authentications offered."
4965 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4966 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
4967 ssh2_pkt_addstring(ssh, "No supported authentication"
4968 " methods available");
4969 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4971 ssh->state = SSH_STATE_CLOSED;
4975 } while (!s->we_are_in);
4978 * Now we're authenticated for the connection protocol. The
4979 * connection protocol will automatically have started at this
4980 * point; there's no need to send SERVICE_REQUEST.
4984 * So now create a channel with a session in it.
4986 ssh->channels = newtree234(ssh_channelcmp);
4987 ssh->mainchan = smalloc(sizeof(struct ssh_channel));
4988 ssh->mainchan->ssh = ssh;
4989 ssh->mainchan->localid = alloc_channel_id(ssh);
4990 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
4991 ssh2_pkt_addstring(ssh, "session");
4992 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
4993 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4994 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
4995 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
4997 crWaitUntilV(ispkt);
4998 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4999 bombout(("Server refused to open a session"));
5001 /* FIXME: error data comes back in FAILURE packet */
5003 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
5004 bombout(("Server's channel confirmation cited wrong channel"));
5007 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
5008 ssh->mainchan->type = CHAN_MAINSESSION;
5009 ssh->mainchan->closes = 0;
5010 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5011 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5012 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5013 add234(ssh->channels, ssh->mainchan);
5014 logevent("Opened channel for session");
5017 * Potentially enable X11 forwarding.
5019 if (cfg.x11_forward) {
5020 char proto[20], data[64];
5021 logevent("Requesting X11 forwarding");
5022 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
5023 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5024 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5025 ssh2_pkt_addstring(ssh, "x11-req");
5026 ssh2_pkt_addbool(ssh, 1); /* want reply */
5027 ssh2_pkt_addbool(ssh, 0); /* many connections */
5028 ssh2_pkt_addstring(ssh, proto);
5029 ssh2_pkt_addstring(ssh, data);
5030 ssh2_pkt_adduint32(ssh, 0); /* screen number */
5034 crWaitUntilV(ispkt);
5035 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5036 unsigned i = ssh2_pkt_getuint32(ssh);
5037 struct ssh_channel *c;
5038 c = find234(ssh->channels, &i, ssh_channelfind);
5040 continue; /* nonexistent channel */
5041 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5043 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5045 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5046 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5047 bombout(("Unexpected response to X11 forwarding request:"
5048 " packet type %d", ssh->pktin.type));
5051 logevent("X11 forwarding refused");
5053 logevent("X11 forwarding enabled");
5054 ssh->X11_fwd_enabled = TRUE;
5059 * Enable port forwardings.
5064 int sport,dport,sserv,dserv;
5065 char sports[256], dports[256], host[256];
5069 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5070 /* Add port forwardings. */
5071 ssh->portfwd_strptr = cfg.portfwd;
5072 while (*ssh->portfwd_strptr) {
5073 type = *ssh->portfwd_strptr++;
5075 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
5076 sports[n++] = *ssh->portfwd_strptr++;
5078 if (*ssh->portfwd_strptr == '\t')
5079 ssh->portfwd_strptr++;
5081 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
5082 host[n++] = *ssh->portfwd_strptr++;
5084 if (*ssh->portfwd_strptr == ':')
5085 ssh->portfwd_strptr++;
5087 while (*ssh->portfwd_strptr)
5088 dports[n++] = *ssh->portfwd_strptr++;
5090 ssh->portfwd_strptr++;
5091 dport = atoi(dports);
5095 se = getservbyname(dports, NULL);
5097 dport = ntohs(se->s_port);
5100 "Service lookup failed for destination port \"%s\"",
5105 sport = atoi(sports);
5109 se = getservbyname(sports, NULL);
5111 sport = ntohs(se->s_port);
5114 "Service lookup failed for source port \"%s\"",
5119 if (sport && dport) {
5121 pfd_addforward(host, dport, sport);
5122 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
5123 " %s:%.*s%.*s%d%.*s",
5124 sserv ? strlen(sports) : 0, sports,
5125 sserv, "(", sport, sserv, ")",
5127 dserv ? strlen(dports) : 0, dports,
5128 dserv, "(", dport, dserv, ")");
5131 struct ssh_rportfwd *pf;
5132 pf = smalloc(sizeof(*pf));
5133 strcpy(pf->dhost, host);
5136 if (add234(ssh->rportfwds, pf) != pf) {
5138 "Duplicate remote port forwarding to %s:%d",
5143 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5144 " forward to %s:%.*s%.*s%d%.*s",
5145 sserv ? strlen(sports) : 0, sports,
5146 sserv, "(", sport, sserv, ")",
5148 dserv ? strlen(dports) : 0, dports,
5149 dserv, "(", dport, dserv, ")");
5151 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5152 ssh2_pkt_addstring(ssh, "tcpip-forward");
5153 ssh2_pkt_addbool(ssh, 1);/* want reply */
5154 if (cfg.rport_acceptall)
5155 ssh2_pkt_addstring(ssh, "0.0.0.0");
5157 ssh2_pkt_addstring(ssh, "127.0.0.1");
5158 ssh2_pkt_adduint32(ssh, sport);
5162 crWaitUntilV(ispkt);
5163 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5164 unsigned i = ssh2_pkt_getuint32(ssh);
5165 struct ssh_channel *c;
5166 c = find234(ssh->channels, &i, ssh_channelfind);
5168 continue;/* nonexistent channel */
5169 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5171 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5173 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5174 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5175 bombout(("Unexpected response to port "
5176 "forwarding request: packet type %d",
5180 logevent("Server refused this port forwarding");
5182 logevent("Remote port forwarding enabled");
5191 * Potentially enable agent forwarding.
5193 if (cfg.agentfwd && agent_exists()) {
5194 logevent("Requesting OpenSSH-style agent forwarding");
5195 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5196 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5197 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5198 ssh2_pkt_addbool(ssh, 1); /* want reply */
5202 crWaitUntilV(ispkt);
5203 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5204 unsigned i = ssh2_pkt_getuint32(ssh);
5205 struct ssh_channel *c;
5206 c = find234(ssh->channels, &i, ssh_channelfind);
5208 continue; /* nonexistent channel */
5209 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5211 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5213 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5214 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5215 bombout(("Unexpected response to agent forwarding request:"
5216 " packet type %d", ssh->pktin.type));
5219 logevent("Agent forwarding refused");
5221 logevent("Agent forwarding enabled");
5222 ssh->agentfwd_enabled = TRUE;
5227 * Now allocate a pty for the session.
5230 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5231 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5232 ssh2_pkt_addstring(ssh, "pty-req");
5233 ssh2_pkt_addbool(ssh, 1); /* want reply */
5234 ssh2_pkt_addstring(ssh, cfg.termtype);
5235 ssh2_pkt_adduint32(ssh, ssh->term_width);
5236 ssh2_pkt_adduint32(ssh, ssh->term_height);
5237 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5238 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5239 ssh2_pkt_addstring_start(ssh);
5240 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5242 ssh->state = SSH_STATE_INTERMED;
5245 crWaitUntilV(ispkt);
5246 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5247 unsigned i = ssh2_pkt_getuint32(ssh);
5248 struct ssh_channel *c;
5249 c = find234(ssh->channels, &i, ssh_channelfind);
5251 continue; /* nonexistent channel */
5252 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5254 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5256 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5257 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5258 bombout(("Unexpected response to pty request:"
5259 " packet type %d", ssh->pktin.type));
5262 c_write_str(ssh, "Server refused to allocate pty\r\n");
5263 ssh->editing = ssh->echoing = 1;
5265 logevent("Allocated pty");
5268 ssh->editing = ssh->echoing = 1;
5272 * Start a shell or a remote command. We may have to attempt
5273 * this twice if the config data has provided a second choice
5280 if (ssh->fallback_cmd) {
5281 subsys = cfg.ssh_subsys2;
5282 cmd = cfg.remote_cmd_ptr2;
5284 subsys = cfg.ssh_subsys;
5285 cmd = cfg.remote_cmd_ptr;
5288 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5289 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5291 ssh2_pkt_addstring(ssh, "subsystem");
5292 ssh2_pkt_addbool(ssh, 1); /* want reply */
5293 ssh2_pkt_addstring(ssh, cmd);
5295 ssh2_pkt_addstring(ssh, "exec");
5296 ssh2_pkt_addbool(ssh, 1); /* want reply */
5297 ssh2_pkt_addstring(ssh, cmd);
5299 ssh2_pkt_addstring(ssh, "shell");
5300 ssh2_pkt_addbool(ssh, 1); /* want reply */
5304 crWaitUntilV(ispkt);
5305 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5306 unsigned i = ssh2_pkt_getuint32(ssh);
5307 struct ssh_channel *c;
5308 c = find234(ssh->channels, &i, ssh_channelfind);
5310 continue; /* nonexistent channel */
5311 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5313 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5314 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5315 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5316 bombout(("Unexpected response to shell/command request:"
5317 " packet type %d", ssh->pktin.type));
5321 * We failed to start the command. If this is the
5322 * fallback command, we really are finished; if it's
5323 * not, and if the fallback command exists, try falling
5324 * back to it before complaining.
5326 if (!ssh->fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5327 logevent("Primary command failed; attempting fallback");
5328 ssh->fallback_cmd = TRUE;
5331 bombout(("Server refused to start a shell/command"));
5334 logevent("Started a shell/command");
5339 ssh->state = SSH_STATE_SESSION;
5340 if (ssh->size_needed)
5341 ssh_size(ssh, ssh->term_width, ssh->term_height);
5342 if (ssh->eof_needed)
5343 ssh_special(ssh, TS_EOF);
5348 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
5352 s->try_send = FALSE;
5354 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5355 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5358 unsigned i = ssh2_pkt_getuint32(ssh);
5359 struct ssh_channel *c;
5360 c = find234(ssh->channels, &i, ssh_channelfind);
5362 continue; /* nonexistent channel */
5363 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5364 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
5365 continue; /* extended but not stderr */
5366 ssh2_pkt_getstring(ssh, &data, &length);
5369 c->v.v2.locwindow -= length;
5371 case CHAN_MAINSESSION:
5373 from_backend(ssh->frontend, ssh->pktin.type ==
5374 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5378 bufsize = x11_send(c->u.x11.s, data, length);
5381 bufsize = pfd_send(c->u.pfd.s, data, length);
5384 while (length > 0) {
5385 if (c->u.a.lensofar < 4) {
5386 int l = min(4 - c->u.a.lensofar, length);
5387 memcpy(c->u.a.msglen + c->u.a.lensofar,
5391 c->u.a.lensofar += l;
5393 if (c->u.a.lensofar == 4) {
5395 4 + GET_32BIT(c->u.a.msglen);
5396 c->u.a.message = smalloc(c->u.a.totallen);
5397 memcpy(c->u.a.message, c->u.a.msglen, 4);
5399 if (c->u.a.lensofar >= 4 && length > 0) {
5401 min(c->u.a.totallen - c->u.a.lensofar,
5403 memcpy(c->u.a.message + c->u.a.lensofar,
5407 c->u.a.lensofar += l;
5409 if (c->u.a.lensofar == c->u.a.totallen) {
5410 void *reply, *sentreply;
5412 agent_query(c->u.a.message,
5413 c->u.a.totallen, &reply,
5418 /* Fake SSH_AGENT_FAILURE. */
5419 sentreply = "\0\0\0\1\5";
5422 ssh2_add_channel_data(c, sentreply, replylen);
5426 sfree(c->u.a.message);
5427 c->u.a.lensofar = 0;
5434 * If we are not buffering too much data,
5435 * enlarge the window again at the remote side.
5437 if (bufsize < OUR_V2_WINSIZE)
5438 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5440 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5441 unsigned i = ssh2_pkt_getuint32(ssh);
5442 struct ssh_channel *c;
5444 c = find234(ssh->channels, &i, ssh_channelfind);
5446 continue; /* nonexistent channel */
5448 if (c->type == CHAN_X11) {
5450 * Remote EOF on an X11 channel means we should
5451 * wrap up and close the channel ourselves.
5453 x11_close(c->u.x11.s);
5455 } else if (c->type == CHAN_AGENT) {
5457 } else if (c->type == CHAN_SOCKDATA) {
5458 pfd_close(c->u.pfd.s);
5461 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5462 unsigned i = ssh2_pkt_getuint32(ssh);
5463 struct ssh_channel *c;
5465 c = find234(ssh->channels, &i, ssh_channelfind);
5466 if (!c || ((int)c->remoteid) == -1) {
5467 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5468 c ? "half-open" : "nonexistent", i));
5470 /* Do pre-close processing on the channel. */
5472 case CHAN_MAINSESSION:
5473 break; /* nothing to see here, move along */
5475 if (c->u.x11.s != NULL)
5476 x11_close(c->u.x11.s);
5483 if (c->u.pfd.s != NULL)
5484 pfd_close(c->u.pfd.s);
5488 if (c->closes == 0) {
5489 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5490 ssh2_pkt_adduint32(ssh, c->remoteid);
5493 del234(ssh->channels, c);
5494 bufchain_clear(&c->v.v2.outbuffer);
5498 * See if that was the last channel left open.
5500 if (count234(ssh->channels) == 0) {
5503 * We used to send SSH_MSG_DISCONNECT here,
5504 * because I'd believed that _every_ conforming
5505 * SSH2 connection had to end with a disconnect
5506 * being sent by at least one side; apparently
5507 * I was wrong and it's perfectly OK to
5508 * unceremoniously slam the connection shut
5509 * when you're done, and indeed OpenSSH feels
5510 * this is more polite than sending a
5511 * DISCONNECT. So now we don't.
5513 logevent("All channels closed. Disconnecting");
5514 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5515 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5516 ssh2_pkt_addstring(ssh, "All open channels closed");
5517 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5520 ssh->state = SSH_STATE_CLOSED;
5523 continue; /* remote sends close; ignore (FIXME) */
5524 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5525 unsigned i = ssh2_pkt_getuint32(ssh);
5526 struct ssh_channel *c;
5527 c = find234(ssh->channels, &i, ssh_channelfind);
5529 continue; /* nonexistent channel */
5530 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5532 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5533 unsigned i = ssh2_pkt_getuint32(ssh);
5534 struct ssh_channel *c;
5535 c = find234(ssh->channels, &i, ssh_channelfind);
5537 continue; /* nonexistent channel */
5538 if (c->type != CHAN_SOCKDATA_DORMANT)
5539 continue; /* dunno why they're confirming this */
5540 c->remoteid = ssh2_pkt_getuint32(ssh);
5541 c->type = CHAN_SOCKDATA;
5542 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5543 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5545 pfd_confirm(c->u.pfd.s);
5548 * We have a pending close on this channel,
5549 * which we decided on before the server acked
5550 * the channel open. So now we know the
5551 * remoteid, we can close it again.
5553 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5554 ssh2_pkt_adduint32(ssh, c->remoteid);
5557 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5558 unsigned i = ssh2_pkt_getuint32(ssh);
5559 struct ssh_channel *c;
5560 c = find234(ssh->channels, &i, ssh_channelfind);
5562 continue; /* nonexistent channel */
5563 if (c->type != CHAN_SOCKDATA_DORMANT)
5564 continue; /* dunno why they're failing this */
5566 logevent("Forwarded connection refused by server");
5568 pfd_close(c->u.pfd.s);
5570 del234(ssh->channels, c);
5572 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5575 int typelen, want_reply;
5576 struct ssh_channel *c;
5578 localid = ssh2_pkt_getuint32(ssh);
5579 ssh2_pkt_getstring(ssh, &type, &typelen);
5580 want_reply = ssh2_pkt_getbool(ssh);
5583 * First, check that the channel exists. Otherwise,
5584 * we can instantly disconnect with a rude message.
5586 c = find234(ssh->channels, &localid, ssh_channelfind);
5589 sprintf(buf, "Received channel request for nonexistent"
5590 " channel %d", localid);
5592 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5593 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5594 ssh2_pkt_addstring(ssh, buf);
5595 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5597 connection_fatal("%s", buf);
5598 ssh->state = SSH_STATE_CLOSED;
5603 * Having got the channel number, we now look at
5604 * the request type string to see if it's something
5607 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5608 c == ssh->mainchan) {
5609 /* We recognise "exit-status" on the primary channel. */
5611 ssh->exitcode = ssh2_pkt_getuint32(ssh);
5612 sprintf(buf, "Server sent command exit status %d",
5616 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5617 ssh2_pkt_adduint32(ssh, c->remoteid);
5622 * This is a channel request we don't know
5623 * about, so we now either ignore the request
5624 * or respond with CHANNEL_FAILURE, depending
5628 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5629 ssh2_pkt_adduint32(ssh, c->remoteid);
5633 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5635 int typelen, want_reply;
5637 ssh2_pkt_getstring(ssh, &type, &typelen);
5638 want_reply = ssh2_pkt_getbool(ssh);
5641 * We currently don't support any global requests
5642 * at all, so we either ignore the request or
5643 * respond with REQUEST_FAILURE, depending on
5647 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5650 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5654 struct ssh_channel *c;
5655 unsigned remid, winsize, pktsize;
5656 ssh2_pkt_getstring(ssh, &type, &typelen);
5657 c = smalloc(sizeof(struct ssh_channel));
5660 remid = ssh2_pkt_getuint32(ssh);
5661 winsize = ssh2_pkt_getuint32(ssh);
5662 pktsize = ssh2_pkt_getuint32(ssh);
5664 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5665 if (!ssh->X11_fwd_enabled)
5666 error = "X11 forwarding is not enabled";
5667 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5669 error = "Unable to open an X11 connection";
5673 } else if (typelen == 15 &&
5674 !memcmp(type, "forwarded-tcpip", 15)) {
5675 struct ssh_rportfwd pf, *realpf;
5678 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5679 pf.sport = ssh2_pkt_getuint32(ssh);
5680 realpf = find234(ssh->rportfwds, &pf, NULL);
5681 if (realpf == NULL) {
5682 error = "Remote port is not recognised";
5684 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5687 sprintf(buf, "Received remote port open request for %s:%d",
5688 realpf->dhost, realpf->dport);
5691 sprintf(buf, "Port open failed: %s", e);
5693 error = "Port open failed";
5695 logevent("Forwarded port opened successfully");
5696 c->type = CHAN_SOCKDATA;
5699 } else if (typelen == 22 &&
5700 !memcmp(type, "auth-agent@openssh.com", 3)) {
5701 if (!ssh->agentfwd_enabled)
5702 error = "Agent forwarding is not enabled";
5704 c->type = CHAN_AGENT; /* identify channel type */
5705 c->u.a.lensofar = 0;
5708 error = "Unsupported channel type requested";
5711 c->remoteid = remid;
5713 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5714 ssh2_pkt_adduint32(ssh, c->remoteid);
5715 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5716 ssh2_pkt_addstring(ssh, error);
5717 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5721 c->localid = alloc_channel_id(ssh);
5723 c->v.v2.locwindow = OUR_V2_WINSIZE;
5724 c->v.v2.remwindow = winsize;
5725 c->v.v2.remmaxpkt = pktsize;
5726 bufchain_init(&c->v.v2.outbuffer);
5727 add234(ssh->channels, c);
5728 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5729 ssh2_pkt_adduint32(ssh, c->remoteid);
5730 ssh2_pkt_adduint32(ssh, c->localid);
5731 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5732 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5736 bombout(("Strange packet received: type %d", ssh->pktin.type));
5741 * We have spare data. Add it to the channel buffer.
5743 ssh2_add_channel_data(ssh->mainchan, in, inlen);
5748 struct ssh_channel *c;
5750 * Try to send data on all channels if we can.
5752 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5753 int bufsize = ssh2_try_send(c);
5756 case CHAN_MAINSESSION:
5757 /* stdin need not receive an unthrottle
5758 * notification since it will be polled */
5761 x11_unthrottle(c->u.x11.s);
5764 /* agent sockets are request/response and need no
5765 * buffer management */
5768 pfd_unthrottle(c->u.pfd.s);
5780 * Handle the top-level SSH2 protocol.
5782 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
5784 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
5786 do_ssh2_authconn(ssh, in, inlen, ispkt);
5790 * Called to set up the connection.
5792 * Returns an error message, or NULL on success.
5794 static char *ssh_init(void *frontend_handle, void **backend_handle,
5795 char *host, int port, char **realhost, int nodelay)
5800 ssh = smalloc(sizeof(*ssh));
5803 ssh->v1_cipher_ctx = NULL;
5804 ssh->cscipher = NULL;
5805 ssh->cs_cipher_ctx = NULL;
5806 ssh->sccipher = NULL;
5807 ssh->sc_cipher_ctx = NULL;
5809 ssh->sc_mac_ctx = NULL;
5811 ssh->sc_mac_ctx = NULL;
5815 ssh->hostkey = NULL;
5817 ssh->state = SSH_STATE_PREPACKET;
5818 ssh->size_needed = FALSE;
5819 ssh->eof_needed = FALSE;
5821 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5822 ssh->pktin = ssh->pktout = empty;
5824 ssh->deferred_send_data = NULL;
5825 ssh->deferred_len = 0;
5826 ssh->deferred_size = 0;
5827 ssh->fallback_cmd = 0;
5829 ssh->v2_outgoing_sequence = 0;
5830 ssh->ssh1_rdpkt_crstate = 0;
5831 ssh->ssh2_rdpkt_crstate = 0;
5832 ssh->do_ssh_init_crstate = 0;
5833 ssh->ssh_gotdata_crstate = 0;
5834 ssh->ssh1_protocol_crstate = 0;
5835 ssh->do_ssh1_login_crstate = 0;
5836 ssh->do_ssh2_transport_crstate = 0;
5837 ssh->do_ssh2_authconn_crstate = 0;
5838 ssh->do_ssh_init_state = NULL;
5839 ssh->do_ssh1_login_state = NULL;
5840 ssh->do_ssh2_transport_state = NULL;
5841 ssh->do_ssh2_authconn_state = NULL;
5843 *backend_handle = ssh;
5846 if (crypto_startup() == 0)
5847 return "Microsoft high encryption pack not installed!";
5850 ssh->frontend = frontend_handle;
5851 ssh->term_width = cfg.width;
5852 ssh->term_height = cfg.height;
5857 ssh->v1_throttle_count = 0;
5858 ssh->overall_bufsize = 0;
5859 ssh->fallback_cmd = 0;
5861 p = connect_to_host(ssh, host, port, realhost, nodelay);
5869 * Called to send data down the Telnet connection.
5871 static int ssh_send(void *handle, char *buf, int len)
5873 Ssh ssh = (Ssh) handle;
5875 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5878 ssh->protocol(ssh, buf, len, 0);
5880 return ssh_sendbuffer(ssh);
5884 * Called to query the current amount of buffered stdin data.
5886 static int ssh_sendbuffer(void *handle)
5888 Ssh ssh = (Ssh) handle;
5891 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5895 * If the SSH socket itself has backed up, add the total backup
5896 * size on that to any individual buffer on the stdin channel.
5899 if (ssh->throttled_all)
5900 override_value = ssh->overall_bufsize;
5902 if (ssh->version == 1) {
5903 return override_value;
5904 } else if (ssh->version == 2) {
5905 if (!ssh->mainchan || ssh->mainchan->closes > 0)
5906 return override_value;
5908 return (override_value +
5909 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5916 * Called to set the size of the window from SSH's POV.
5918 static void ssh_size(void *handle, int width, int height)
5920 Ssh ssh = (Ssh) handle;
5922 ssh->term_width = width;
5923 ssh->term_height = height;
5925 switch (ssh->state) {
5926 case SSH_STATE_BEFORE_SIZE:
5927 case SSH_STATE_PREPACKET:
5928 case SSH_STATE_CLOSED:
5929 break; /* do nothing */
5930 case SSH_STATE_INTERMED:
5931 ssh->size_needed = TRUE; /* buffer for later */
5933 case SSH_STATE_SESSION:
5937 if (ssh->version == 1) {
5938 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
5939 PKT_INT, ssh->term_height,
5940 PKT_INT, ssh->term_width,
5941 PKT_INT, 0, PKT_INT, 0, PKT_END);
5943 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5944 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5945 ssh2_pkt_addstring(ssh, "window-change");
5946 ssh2_pkt_addbool(ssh, 0);
5947 ssh2_pkt_adduint32(ssh, ssh->term_width);
5948 ssh2_pkt_adduint32(ssh, ssh->term_height);
5949 ssh2_pkt_adduint32(ssh, 0);
5950 ssh2_pkt_adduint32(ssh, 0);
5959 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5960 * can send an EOF and collect resulting output (e.g. `plink
5963 static void ssh_special(void *handle, Telnet_Special code)
5965 Ssh ssh = (Ssh) handle;
5967 if (code == TS_EOF) {
5968 if (ssh->state != SSH_STATE_SESSION) {
5970 * Buffer the EOF in case we are pre-SESSION, so we can
5971 * send it as soon as we reach SESSION.
5974 ssh->eof_needed = TRUE;
5977 if (ssh->version == 1) {
5978 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
5980 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
5981 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5984 logevent("Sent EOF message");
5985 } else if (code == TS_PING) {
5986 if (ssh->state == SSH_STATE_CLOSED
5987 || ssh->state == SSH_STATE_PREPACKET) return;
5988 if (ssh->version == 1) {
5989 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
5990 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5992 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
5993 ssh2_pkt_addstring_start(ssh);
6001 void *new_sock_channel(void *handle, Socket s)
6003 Ssh ssh = (Ssh) handle;
6004 struct ssh_channel *c;
6005 c = smalloc(sizeof(struct ssh_channel));
6009 c->remoteid = -1; /* to be set when open confirmed */
6010 c->localid = alloc_channel_id(ssh);
6012 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
6014 bufchain_init(&c->v.v2.outbuffer);
6015 add234(ssh->channels, c);
6021 * This is called when stdout/stderr (the entity to which
6022 * from_backend sends data) manages to clear some backlog.
6024 void ssh_unthrottle(void *handle, int bufsize)
6026 Ssh ssh = (Ssh) handle;
6027 if (ssh->version == 1) {
6028 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6029 ssh->v1_stdout_throttling = 0;
6030 ssh1_throttle(ssh, -1);
6033 if (ssh->mainchan && ssh->mainchan->closes == 0)
6034 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
6038 void ssh_send_port_open(void *handle, void *channel, char *hostname,
6039 int port, char *org)
6041 Ssh ssh = (Ssh) handle;
6042 struct ssh_channel *c = (struct ssh_channel *)channel;
6045 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
6048 if (ssh->version == 1) {
6049 send_packet(ssh, SSH1_MSG_PORT_OPEN,
6050 PKT_INT, c->localid,
6053 //PKT_STR, <org:orgport>,
6056 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6057 ssh2_pkt_addstring(ssh, "direct-tcpip");
6058 ssh2_pkt_adduint32(ssh, c->localid);
6059 c->v.v2.locwindow = OUR_V2_WINSIZE;
6060 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6061 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6062 ssh2_pkt_addstring(ssh, hostname);
6063 ssh2_pkt_adduint32(ssh, port);
6065 * We make up values for the originator data; partly it's
6066 * too much hassle to keep track, and partly I'm not
6067 * convinced the server should be told details like that
6068 * about my local network configuration.
6070 ssh2_pkt_addstring(ssh, "client-side-connection");
6071 ssh2_pkt_adduint32(ssh, 0);
6077 static Socket ssh_socket(void *handle)
6079 Ssh ssh = (Ssh) handle;
6083 static int ssh_sendok(void *handle)
6085 Ssh ssh = (Ssh) handle;
6086 return ssh->send_ok;
6089 static int ssh_ldisc(void *handle, int option)
6091 Ssh ssh = (Ssh) handle;
6092 if (option == LD_ECHO)
6093 return ssh->echoing;
6094 if (option == LD_EDIT)
6095 return ssh->editing;
6099 static int ssh_return_exitcode(void *handle)
6101 Ssh ssh = (Ssh) handle;
6102 return ssh->exitcode;
6106 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6107 * that fails. This variable is the means by which scp.c can reach
6108 * into the SSH code and find out which one it got.
6110 extern int ssh_fallback_cmd(void *handle)
6112 Ssh ssh = (Ssh) handle;
6113 return ssh->fallback_cmd;
6116 Backend ssh_backend = {
6123 ssh_return_exitcode,