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;
564 const struct ssh2_cipher *cscipher, *sccipher;
565 void *cs_cipher_ctx, *sc_cipher_ctx;
566 const struct ssh_mac *csmac, *scmac;
567 void *cs_mac_ctx, *sc_mac_ctx;
568 const struct ssh_compress *cscomp, *sccomp;
569 const struct ssh_kex *kex;
570 const struct ssh_signkey *hostkey;
571 unsigned char v2_session_id[20];
577 int echoing, editing;
581 int term_width, term_height;
583 tree234 *channels; /* indexed by local id */
584 struct ssh_channel *mainchan; /* primary session channel */
591 SSH_STATE_BEFORE_SIZE,
597 int size_needed, eof_needed;
600 struct Packet pktout;
601 unsigned char *deferred_send_data;
602 int deferred_len, deferred_size;
605 * Gross hack: pscp will try to start SFTP but fall back to
606 * scp1 if that fails. This variable is the means by which
607 * scp.c can reach into the SSH code and find out which one it
613 * Used for username and password input.
615 char *userpass_input_buffer;
616 int userpass_input_buflen;
617 int userpass_input_bufpos;
618 int userpass_input_echo;
620 char *portfwd_strptr;
624 int v1_throttle_count;
627 int v1_stdout_throttling;
628 int v2_outgoing_sequence;
630 int ssh1_rdpkt_crstate;
631 int ssh2_rdpkt_crstate;
632 int do_ssh_init_crstate;
633 int ssh_gotdata_crstate;
634 int ssh1_protocol_crstate;
635 int do_ssh1_login_crstate;
636 int do_ssh2_transport_crstate;
637 int do_ssh2_authconn_crstate;
639 void *do_ssh_init_state;
640 void *do_ssh1_login_state;
641 void *do_ssh2_transport_state;
642 void *do_ssh2_authconn_state;
644 struct rdpkt1_state_tag rdpkt1_state;
645 struct rdpkt2_state_tag rdpkt2_state;
647 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
648 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
651 static int ssh_channelcmp(void *av, void *bv)
653 struct ssh_channel *a = (struct ssh_channel *) av;
654 struct ssh_channel *b = (struct ssh_channel *) bv;
655 if (a->localid < b->localid)
657 if (a->localid > b->localid)
661 static int ssh_channelfind(void *av, void *bv)
663 unsigned *a = (unsigned *) av;
664 struct ssh_channel *b = (struct ssh_channel *) bv;
672 static int ssh_rportcmp_ssh1(void *av, void *bv)
674 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
675 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
677 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
678 return i < 0 ? -1 : +1;
679 if (a->dport > b->dport)
681 if (a->dport < b->dport)
686 static int ssh_rportcmp_ssh2(void *av, void *bv)
688 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
689 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
691 if (a->sport > b->sport)
693 if (a->sport < b->sport)
698 static int alloc_channel_id(Ssh ssh)
700 const unsigned CHANNEL_NUMBER_OFFSET = 256;
701 unsigned low, high, mid;
703 struct ssh_channel *c;
706 * First-fit allocation of channel numbers: always pick the
707 * lowest unused one. To do this, binary-search using the
708 * counted B-tree to find the largest channel ID which is in a
709 * contiguous sequence from the beginning. (Precisely
710 * everything in that sequence must have ID equal to its tree
711 * index plus CHANNEL_NUMBER_OFFSET.)
713 tsize = count234(ssh->channels);
717 while (high - low > 1) {
718 mid = (high + low) / 2;
719 c = index234(ssh->channels, mid);
720 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
721 low = mid; /* this one is fine */
723 high = mid; /* this one is past it */
726 * Now low points to either -1, or the tree index of the
727 * largest ID in the initial sequence.
730 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
731 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
733 return low + 1 + CHANNEL_NUMBER_OFFSET;
736 static void c_write(Ssh ssh, char *buf, int len)
738 if ((flags & FLAG_STDERR)) {
740 for (i = 0; i < len; i++)
742 fputc(buf[i], stderr);
745 from_backend(ssh->frontend, 1, buf, len);
748 static void c_write_untrusted(Ssh ssh, char *buf, int len)
751 for (i = 0; i < len; i++) {
753 c_write(ssh, "\r\n", 2);
754 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
755 c_write(ssh, buf + i, 1);
759 static void c_write_str(Ssh ssh, char *buf)
761 c_write(ssh, buf, strlen(buf));
765 * Collect incoming data in the incoming packet buffer.
766 * Decipher and verify the packet when it is completely read.
767 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
768 * Update the *data and *datalen variables.
769 * Return the additional nr of bytes needed, or 0 when
770 * a complete packet is available.
772 static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
774 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
776 crBegin(ssh->ssh1_rdpkt_crstate);
781 ssh->pktin.length = 0;
783 for (st->i = st->len = 0; st->i < 4; st->i++) {
784 while ((*datalen) == 0)
786 st->len = (st->len << 8) + **data;
787 (*data)++, (*datalen)--;
790 st->pad = 8 - (st->len % 8);
791 st->biglen = st->len + st->pad;
792 ssh->pktin.length = st->len - 5;
794 if (ssh->pktin.maxlen < st->biglen) {
795 ssh->pktin.maxlen = st->biglen;
796 ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
799 st->to_read = st->biglen;
800 st->p = ssh->pktin.data;
801 while (st->to_read > 0) {
802 st->chunk = st->to_read;
803 while ((*datalen) == 0)
804 crReturn(st->to_read);
805 if (st->chunk > (*datalen))
806 st->chunk = (*datalen);
807 memcpy(st->p, *data, st->chunk);
809 *datalen -= st->chunk;
811 st->to_read -= st->chunk;
814 if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
816 bombout(("Network attack (CRC compensation) detected!"));
821 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
823 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
824 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
825 if (st->gotcrc != st->realcrc) {
826 bombout(("Incorrect CRC received on packet"));
830 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
832 if (ssh->v1_compressing) {
833 unsigned char *decompblk;
835 zlib_decompress_block(ssh->pktin.body - 1, ssh->pktin.length + 1,
836 &decompblk, &decomplen);
838 if (ssh->pktin.maxlen < st->pad + decomplen) {
839 ssh->pktin.maxlen = st->pad + decomplen;
840 ssh->pktin.data = srealloc(ssh->pktin.data,
841 ssh->pktin.maxlen + APIEXTRA);
842 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
845 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
847 ssh->pktin.length = decomplen - 1;
850 ssh->pktin.type = ssh->pktin.body[-1];
852 log_packet(PKT_INCOMING, ssh->pktin.type, ssh1_pkt_type(ssh->pktin.type),
853 ssh->pktin.body, ssh->pktin.length);
855 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
856 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
857 ssh->pktin.type == SSH1_MSG_DEBUG ||
858 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
859 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
860 long stringlen = GET_32BIT(ssh->pktin.body);
861 if (stringlen + 4 != ssh->pktin.length) {
862 bombout(("Received data packet with bogus string length"));
867 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
868 /* log debug message */
870 int stringlen = GET_32BIT(ssh->pktin.body);
871 strcpy(buf, "Remote debug message: ");
874 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
875 buf[8 + stringlen] = '\0';
878 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
883 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
884 /* log reason code in disconnect message */
886 unsigned msglen = GET_32BIT(ssh->pktin.body);
888 strcpy(buf, "Remote sent disconnect: ");
889 nowlen = strlen(buf);
890 if (msglen > sizeof(buf) - nowlen - 1)
891 msglen = sizeof(buf) - nowlen - 1;
892 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
893 buf[nowlen + msglen] = '\0';
894 /* logevent(buf); (this is now done within the bombout macro) */
895 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
902 static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
904 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
906 crBegin(ssh->ssh2_rdpkt_crstate);
910 ssh->pktin.length = 0;
912 st->cipherblk = ssh->sccipher->blksize;
915 if (st->cipherblk < 8)
918 if (ssh->pktin.maxlen < st->cipherblk) {
919 ssh->pktin.maxlen = st->cipherblk;
920 ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
924 * Acquire and decrypt the first block of the packet. This will
925 * contain the length and padding details.
927 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
928 while ((*datalen) == 0)
929 crReturn(st->cipherblk - st->i);
930 ssh->pktin.data[st->i] = *(*data)++;
935 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
936 ssh->pktin.data, st->cipherblk);
939 * Now get the length and padding figures.
941 st->len = GET_32BIT(ssh->pktin.data);
942 st->pad = ssh->pktin.data[4];
945 * _Completely_ silly lengths should be stomped on before they
946 * do us any more damage.
948 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
949 bombout(("Incoming packet was garbled on decryption"));
954 * This enables us to deduce the payload length.
956 st->payload = st->len - st->pad - 1;
958 ssh->pktin.length = st->payload + 5;
961 * So now we can work out the total packet length.
963 st->packetlen = st->len + 4;
964 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
967 * Adjust memory allocation if packet is too big.
969 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
970 ssh->pktin.maxlen = st->packetlen + st->maclen;
971 ssh->pktin.data = srealloc(ssh->pktin.data,
972 ssh->pktin.maxlen + APIEXTRA);
976 * Read and decrypt the remainder of the packet.
978 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
980 while ((*datalen) == 0)
981 crReturn(st->packetlen + st->maclen - st->i);
982 ssh->pktin.data[st->i] = *(*data)++;
985 /* Decrypt everything _except_ the MAC. */
987 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
988 ssh->pktin.data + st->cipherblk,
989 st->packetlen - st->cipherblk);
995 && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
996 st->incoming_sequence)) {
997 bombout(("Incorrect MAC received on packet"));
1000 st->incoming_sequence++; /* whether or not we MACed */
1003 * Decompress packet payload.
1006 unsigned char *newpayload;
1009 ssh->sccomp->decompress(ssh->pktin.data + 5, ssh->pktin.length - 5,
1010 &newpayload, &newlen)) {
1011 if (ssh->pktin.maxlen < newlen + 5) {
1012 ssh->pktin.maxlen = newlen + 5;
1013 ssh->pktin.data = srealloc(ssh->pktin.data,
1014 ssh->pktin.maxlen + APIEXTRA);
1016 ssh->pktin.length = 5 + newlen;
1017 memcpy(ssh->pktin.data + 5, newpayload, newlen);
1022 ssh->pktin.savedpos = 6;
1023 ssh->pktin.type = ssh->pktin.data[5];
1025 log_packet(PKT_INCOMING, ssh->pktin.type,
1026 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1027 ssh->pktin.data+6, ssh->pktin.length-6);
1029 switch (ssh->pktin.type) {
1031 * These packets we must handle instantly.
1033 case SSH2_MSG_DISCONNECT:
1035 /* log reason code in disconnect message */
1037 int reason = GET_32BIT(ssh->pktin.data + 6);
1038 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
1040 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1041 sprintf(buf, "Received disconnect message (%s)",
1042 ssh2_disconnect_reasons[reason]);
1044 sprintf(buf, "Received disconnect message (unknown type %d)",
1048 strcpy(buf, "Disconnection message text: ");
1049 nowlen = strlen(buf);
1050 if (msglen > sizeof(buf) - nowlen - 1)
1051 msglen = sizeof(buf) - nowlen - 1;
1052 memcpy(buf + nowlen, ssh->pktin.data + 14, msglen);
1053 buf[nowlen + msglen] = '\0';
1055 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1057 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1058 ssh2_disconnect_reasons[reason] : "unknown",
1063 case SSH2_MSG_IGNORE:
1065 case SSH2_MSG_DEBUG:
1067 /* log the debug message */
1069 /* int display = ssh->pktin.body[6]; */
1070 int stringlen = GET_32BIT(ssh->pktin.data+7);
1072 strcpy(buf, "Remote debug message: ");
1073 prefix = strlen(buf);
1074 if (stringlen > (int)(sizeof(buf)-prefix-1))
1075 stringlen = sizeof(buf)-prefix-1;
1076 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
1077 buf[prefix + stringlen] = '\0';
1080 goto next_packet; /* FIXME: print the debug message */
1083 * These packets we need do nothing about here.
1085 case SSH2_MSG_UNIMPLEMENTED:
1086 case SSH2_MSG_SERVICE_REQUEST:
1087 case SSH2_MSG_SERVICE_ACCEPT:
1088 case SSH2_MSG_KEXINIT:
1089 case SSH2_MSG_NEWKEYS:
1090 case SSH2_MSG_KEXDH_INIT:
1091 case SSH2_MSG_KEXDH_REPLY:
1092 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1093 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1094 case SSH2_MSG_KEX_DH_GEX_INIT:
1095 case SSH2_MSG_KEX_DH_GEX_REPLY:
1096 case SSH2_MSG_USERAUTH_REQUEST:
1097 case SSH2_MSG_USERAUTH_FAILURE:
1098 case SSH2_MSG_USERAUTH_SUCCESS:
1099 case SSH2_MSG_USERAUTH_BANNER:
1100 case SSH2_MSG_USERAUTH_PK_OK:
1101 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1102 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1103 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1104 case SSH2_MSG_GLOBAL_REQUEST:
1105 case SSH2_MSG_REQUEST_SUCCESS:
1106 case SSH2_MSG_REQUEST_FAILURE:
1107 case SSH2_MSG_CHANNEL_OPEN:
1108 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1109 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1110 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1111 case SSH2_MSG_CHANNEL_DATA:
1112 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1113 case SSH2_MSG_CHANNEL_EOF:
1114 case SSH2_MSG_CHANNEL_CLOSE:
1115 case SSH2_MSG_CHANNEL_REQUEST:
1116 case SSH2_MSG_CHANNEL_SUCCESS:
1117 case SSH2_MSG_CHANNEL_FAILURE:
1121 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1124 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1125 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1133 static void ssh1_pktout_size(Ssh ssh, int len)
1137 len += 5; /* type and CRC */
1138 pad = 8 - (len % 8);
1141 ssh->pktout.length = len - 5;
1142 if (ssh->pktout.maxlen < biglen) {
1143 ssh->pktout.maxlen = biglen;
1145 /* Allocate enough buffer space for extra block
1146 * for MS CryptEncrypt() */
1147 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
1149 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
1152 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
1155 static void s_wrpkt_start(Ssh ssh, int type, int len)
1157 ssh1_pktout_size(ssh, len);
1158 ssh->pktout.type = type;
1161 static int s_wrpkt_prepare(Ssh ssh)
1163 int pad, len, biglen, i;
1166 ssh->pktout.body[-1] = ssh->pktout.type;
1168 log_packet(PKT_OUTGOING, ssh->pktout.type, ssh1_pkt_type(ssh->pktout.type),
1169 ssh->pktout.body, ssh->pktout.length);
1171 if (ssh->v1_compressing) {
1172 unsigned char *compblk;
1174 zlib_compress_block(ssh->pktout.body - 1, ssh->pktout.length + 1,
1175 &compblk, &complen);
1176 ssh1_pktout_size(ssh, complen - 1);
1177 memcpy(ssh->pktout.body - 1, compblk, complen);
1181 len = ssh->pktout.length + 5; /* type and CRC */
1182 pad = 8 - (len % 8);
1185 for (i = 0; i < pad; i++)
1186 ssh->pktout.data[i + 4] = random_byte();
1187 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1188 PUT_32BIT(ssh->pktout.data + biglen, crc);
1189 PUT_32BIT(ssh->pktout.data, len);
1192 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
1197 static void s_wrpkt(Ssh ssh)
1200 len = s_wrpkt_prepare(ssh);
1201 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1202 if (backlog > SSH_MAX_BACKLOG)
1203 ssh_throttle_all(ssh, 1, backlog);
1206 static void s_wrpkt_defer(Ssh ssh)
1209 len = s_wrpkt_prepare(ssh);
1210 if (ssh->deferred_len + len > ssh->deferred_size) {
1211 ssh->deferred_size = ssh->deferred_len + len + 128;
1212 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1213 ssh->deferred_size);
1215 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1216 ssh->deferred_len += len;
1220 * Construct a packet with the specified contents.
1222 static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
1224 unsigned char *p, *argp, argchar;
1225 unsigned long argint;
1226 int pktlen, argtype, arglen;
1230 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1233 (void) va_arg(ap1, int);
1237 (void) va_arg(ap1, char);
1241 (void) va_arg(ap1, unsigned char *);
1242 arglen = va_arg(ap1, int);
1246 argp = va_arg(ap1, unsigned char *);
1247 arglen = strlen(argp);
1248 pktlen += 4 + arglen;
1251 bn = va_arg(ap1, Bignum);
1252 pktlen += ssh1_bignum_length(bn);
1259 s_wrpkt_start(ssh, pkttype, pktlen);
1260 p = ssh->pktout.body;
1262 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1265 argint = va_arg(ap2, int);
1266 PUT_32BIT(p, argint);
1270 argchar = va_arg(ap2, unsigned char);
1275 argp = va_arg(ap2, unsigned char *);
1276 arglen = va_arg(ap2, int);
1277 memcpy(p, argp, arglen);
1281 argp = va_arg(ap2, unsigned char *);
1282 arglen = strlen(argp);
1283 PUT_32BIT(p, arglen);
1284 memcpy(p + 4, argp, arglen);
1288 bn = va_arg(ap2, Bignum);
1289 p += ssh1_write_bignum(p, bn);
1295 static void send_packet(Ssh ssh, int pkttype, ...)
1298 va_start(ap1, pkttype);
1299 va_start(ap2, pkttype);
1300 construct_packet(ssh, pkttype, ap1, ap2);
1304 static void defer_packet(Ssh ssh, int pkttype, ...)
1307 va_start(ap1, pkttype);
1308 va_start(ap2, pkttype);
1309 construct_packet(ssh, pkttype, ap1, ap2);
1313 static int ssh_versioncmp(char *a, char *b)
1316 unsigned long av, bv;
1318 av = strtoul(a, &ae, 10);
1319 bv = strtoul(b, &be, 10);
1321 return (av < bv ? -1 : +1);
1326 av = strtoul(ae, &ae, 10);
1327 bv = strtoul(be, &be, 10);
1329 return (av < bv ? -1 : +1);
1334 * Utility routines for putting an SSH-protocol `string' and
1335 * `uint32' into a SHA state.
1338 static void sha_string(SHA_State * s, void *str, int len)
1340 unsigned char lenblk[4];
1341 PUT_32BIT(lenblk, len);
1342 SHA_Bytes(s, lenblk, 4);
1343 SHA_Bytes(s, str, len);
1346 static void sha_uint32(SHA_State * s, unsigned i)
1348 unsigned char intblk[4];
1349 PUT_32BIT(intblk, i);
1350 SHA_Bytes(s, intblk, 4);
1354 * SSH2 packet construction functions.
1356 static void ssh2_pkt_ensure(Ssh ssh, int length)
1358 if (ssh->pktout.maxlen < length) {
1359 ssh->pktout.maxlen = length + 256;
1360 ssh->pktout.data = srealloc(ssh->pktout.data,
1361 ssh->pktout.maxlen + APIEXTRA);
1362 if (!ssh->pktout.data)
1363 fatalbox("Out of memory");
1366 static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
1368 ssh->pktout.length += len;
1369 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1370 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
1372 static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
1374 ssh2_pkt_adddata(ssh, &byte, 1);
1376 static void ssh2_pkt_init(Ssh ssh, int pkt_type)
1378 ssh->pktout.length = 5;
1379 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
1381 static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
1383 ssh2_pkt_adddata(ssh, &value, 1);
1385 static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
1388 PUT_32BIT(x, value);
1389 ssh2_pkt_adddata(ssh, x, 4);
1391 static void ssh2_pkt_addstring_start(Ssh ssh)
1393 ssh2_pkt_adduint32(ssh, 0);
1394 ssh->pktout.savedpos = ssh->pktout.length;
1396 static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
1398 ssh2_pkt_adddata(ssh, data, strlen(data));
1399 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1400 ssh->pktout.length - ssh->pktout.savedpos);
1402 static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
1404 ssh2_pkt_adddata(ssh, data, len);
1405 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1406 ssh->pktout.length - ssh->pktout.savedpos);
1408 static void ssh2_pkt_addstring(Ssh ssh, char *data)
1410 ssh2_pkt_addstring_start(ssh);
1411 ssh2_pkt_addstring_str(ssh, data);
1413 static char *ssh2_mpint_fmt(Bignum b, int *len)
1416 int i, n = (bignum_bitcount(b) + 7) / 8;
1419 fatalbox("out of memory");
1421 for (i = 1; i <= n; i++)
1422 p[i] = bignum_byte(b, n - i);
1424 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1426 memmove(p, p + i, n + 1 - i);
1430 static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
1434 p = ssh2_mpint_fmt(b, &len);
1435 ssh2_pkt_addstring_start(ssh);
1436 ssh2_pkt_addstring_data(ssh, p, len);
1441 * Construct an SSH2 final-form packet: compress it, encrypt it,
1442 * put the MAC on it. Final packet, ready to be sent, is stored in
1443 * ssh->pktout.data. Total length is returned.
1445 static int ssh2_pkt_construct(Ssh ssh)
1447 int cipherblk, maclen, padding, i;
1449 log_packet(PKT_OUTGOING, ssh->pktout.data[5],
1450 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1451 ssh->pktout.data + 6, ssh->pktout.length - 6);
1454 * Compress packet payload.
1457 unsigned char *newpayload;
1460 ssh->cscomp->compress(ssh->pktout.data + 5, ssh->pktout.length - 5,
1461 &newpayload, &newlen)) {
1462 ssh->pktout.length = 5;
1463 ssh2_pkt_adddata(ssh, newpayload, newlen);
1469 * Add padding. At least four bytes, and must also bring total
1470 * length (minus MAC) up to a multiple of the block size.
1472 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1473 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1476 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1477 maclen = ssh->csmac ? ssh->csmac->len : 0;
1478 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1479 ssh->pktout.data[4] = padding;
1480 for (i = 0; i < padding; i++)
1481 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1482 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1484 ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
1485 ssh->pktout.length + padding,
1486 ssh->v2_outgoing_sequence);
1487 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1490 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1491 ssh->pktout.data, ssh->pktout.length + padding);
1493 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1494 return ssh->pktout.length + padding + maclen;
1498 * Construct and send an SSH2 packet immediately.
1500 static void ssh2_pkt_send(Ssh ssh)
1504 len = ssh2_pkt_construct(ssh);
1505 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1506 if (backlog > SSH_MAX_BACKLOG)
1507 ssh_throttle_all(ssh, 1, backlog);
1511 * Construct an SSH2 packet and add it to a deferred data block.
1512 * Useful for sending multiple packets in a single sk_write() call,
1513 * to prevent a traffic-analysing listener from being able to work
1514 * out the length of any particular packet (such as the password
1517 * Note that because SSH2 sequence-numbers its packets, this can
1518 * NOT be used as an m4-style `defer' allowing packets to be
1519 * constructed in one order and sent in another.
1521 static void ssh2_pkt_defer(Ssh ssh)
1523 int len = ssh2_pkt_construct(ssh);
1524 if (ssh->deferred_len + len > ssh->deferred_size) {
1525 ssh->deferred_size = ssh->deferred_len + len + 128;
1526 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1527 ssh->deferred_size);
1529 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1530 ssh->deferred_len += len;
1534 * Send the whole deferred data block constructed by
1535 * ssh2_pkt_defer() or SSH1's defer_packet().
1537 static void ssh_pkt_defersend(Ssh ssh)
1540 backlog = sk_write(ssh->s, ssh->deferred_send_data, ssh->deferred_len);
1541 ssh->deferred_len = ssh->deferred_size = 0;
1542 sfree(ssh->deferred_send_data);
1543 ssh->deferred_send_data = NULL;
1544 if (backlog > SSH_MAX_BACKLOG)
1545 ssh_throttle_all(ssh, 1, backlog);
1549 void bndebug(char *string, Bignum b)
1553 p = ssh2_mpint_fmt(b, &len);
1554 debug(("%s", string));
1555 for (i = 0; i < len; i++)
1556 debug((" %02x", p[i]));
1562 static void sha_mpint(SHA_State * s, Bignum b)
1566 p = ssh2_mpint_fmt(b, &len);
1567 sha_string(s, p, len);
1572 * SSH2 packet decode functions.
1574 static unsigned long ssh2_pkt_getuint32(Ssh ssh)
1576 unsigned long value;
1577 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1578 return 0; /* arrgh, no way to decline (FIXME?) */
1579 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1580 ssh->pktin.savedpos += 4;
1583 static int ssh2_pkt_getbool(Ssh ssh)
1585 unsigned long value;
1586 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
1587 return 0; /* arrgh, no way to decline (FIXME?) */
1588 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1589 ssh->pktin.savedpos++;
1592 static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
1596 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1598 *length = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1599 ssh->pktin.savedpos += 4;
1600 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
1602 *p = ssh->pktin.data + ssh->pktin.savedpos;
1603 ssh->pktin.savedpos += *length;
1605 static Bignum ssh2_pkt_getmp(Ssh ssh)
1611 ssh2_pkt_getstring(ssh, &p, &length);
1615 bombout(("internal error: Can't handle negative mpints"));
1618 b = bignum_from_bytes(p, length);
1623 * Helper function to add an SSH2 signature blob to a packet.
1624 * Expects to be shown the public key blob as well as the signature
1625 * blob. Normally works just like ssh2_pkt_addstring, but will
1626 * fiddle with the signature packet if necessary for
1627 * BUG_SSH2_RSA_PADDING.
1629 static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1630 void *sigblob_v, int sigblob_len)
1632 unsigned char *pkblob = (unsigned char *)pkblob_v;
1633 unsigned char *sigblob = (unsigned char *)sigblob_v;
1635 /* dmemdump(pkblob, pkblob_len); */
1636 /* dmemdump(sigblob, sigblob_len); */
1639 * See if this is in fact an ssh-rsa signature and a buggy
1640 * server; otherwise we can just do this the easy way.
1642 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1643 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1644 int pos, len, siglen;
1647 * Find the byte length of the modulus.
1650 pos = 4+7; /* skip over "ssh-rsa" */
1651 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1652 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1653 pos += 4; /* find modulus itself */
1654 while (len > 0 && pkblob[pos] == 0)
1656 /* debug(("modulus length is %d\n", len)); */
1659 * Now find the signature integer.
1661 pos = 4+7; /* skip over "ssh-rsa" */
1662 siglen = GET_32BIT(sigblob+pos);
1663 /* debug(("signature length is %d\n", siglen)); */
1665 if (len != siglen) {
1666 unsigned char newlen[4];
1667 ssh2_pkt_addstring_start(ssh);
1668 ssh2_pkt_addstring_data(ssh, sigblob, pos);
1669 /* dmemdump(sigblob, pos); */
1670 pos += 4; /* point to start of actual sig */
1671 PUT_32BIT(newlen, len);
1672 ssh2_pkt_addstring_data(ssh, newlen, 4);
1673 /* dmemdump(newlen, 4); */
1675 while (len-- > siglen) {
1676 ssh2_pkt_addstring_data(ssh, newlen, 1);
1677 /* dmemdump(newlen, 1); */
1679 ssh2_pkt_addstring_data(ssh, sigblob+pos, siglen);
1680 /* dmemdump(sigblob+pos, siglen); */
1684 /* Otherwise fall through and do it the easy way. */
1687 ssh2_pkt_addstring_start(ssh);
1688 ssh2_pkt_addstring_data(ssh, sigblob, sigblob_len);
1692 * Examine the remote side's version string and compare it against
1693 * a list of known buggy implementations.
1695 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1697 char *imp; /* pointer to implementation part */
1699 imp += strcspn(imp, "-");
1701 imp += strcspn(imp, "-");
1704 ssh->remote_bugs = 0;
1706 if (cfg.sshbug_ignore1 == BUG_ON ||
1707 (cfg.sshbug_ignore1 == BUG_AUTO &&
1708 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1709 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1710 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1712 * These versions don't support SSH1_MSG_IGNORE, so we have
1713 * to use a different defence against password length
1716 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1717 logevent("We believe remote version has SSH1 ignore bug");
1720 if (cfg.sshbug_plainpw1 == BUG_ON ||
1721 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1722 (!strcmp(imp, "Cisco-1.25")))) {
1724 * These versions need a plain password sent; they can't
1725 * handle having a null and a random length of data after
1728 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1729 logevent("We believe remote version needs a plain SSH1 password");
1732 if (cfg.sshbug_rsa1 == BUG_ON ||
1733 (cfg.sshbug_rsa1 == BUG_AUTO &&
1734 (!strcmp(imp, "Cisco-1.25")))) {
1736 * These versions apparently have no clue whatever about
1737 * RSA authentication and will panic and die if they see
1738 * an AUTH_RSA message.
1740 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
1741 logevent("We believe remote version can't handle RSA authentication");
1744 if (cfg.sshbug_hmac2 == BUG_ON ||
1745 (cfg.sshbug_hmac2 == BUG_AUTO &&
1746 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1747 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1748 !strncmp(imp, "2.1 ", 4)))) {
1750 * These versions have the HMAC bug.
1752 ssh->remote_bugs |= BUG_SSH2_HMAC;
1753 logevent("We believe remote version has SSH2 HMAC bug");
1756 if (cfg.sshbug_derivekey2 == BUG_ON ||
1757 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1758 (!strncmp(imp, "2.0.", 4)))) {
1760 * These versions have the key-derivation bug (failing to
1761 * include the literal shared secret in the hashes that
1762 * generate the keys).
1764 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
1765 logevent("We believe remote version has SSH2 key-derivation bug");
1768 if (cfg.sshbug_rsapad2 == BUG_ON ||
1769 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1770 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1771 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1773 * These versions have the SSH2 RSA padding bug.
1775 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1776 logevent("We believe remote version has SSH2 RSA padding bug");
1779 if (cfg.sshbug_dhgex2 == BUG_ON) {
1781 * These versions have the SSH2 DH GEX bug.
1783 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
1784 logevent("We believe remote version has SSH2 DH group exchange bug");
1788 static int do_ssh_init(Ssh ssh, unsigned char c)
1790 struct do_ssh_init_state {
1798 crState(do_ssh_init_state);
1800 crBegin(ssh->do_ssh_init_crstate);
1802 /* Search for the string "SSH-" in the input. */
1805 static const int transS[] = { 1, 2, 2, 1 };
1806 static const int transH[] = { 0, 0, 3, 0 };
1807 static const int transminus[] = { 0, 0, 0, -1 };
1809 s->i = transS[s->i];
1811 s->i = transH[s->i];
1813 s->i = transminus[s->i];
1818 crReturn(1); /* get another character */
1822 s->vstring = smalloc(s->vstrsize);
1823 strcpy(s->vstring, "SSH-");
1827 crReturn(1); /* get another char */
1828 if (s->vslen >= s->vstrsize - 1) {
1830 s->vstring = srealloc(s->vstring, s->vstrsize);
1832 s->vstring[s->vslen++] = c;
1835 s->version[s->i] = '\0';
1837 } else if (s->i < sizeof(s->version) - 1)
1838 s->version[s->i++] = c;
1839 } else if (c == '\n')
1843 ssh->agentfwd_enabled = FALSE;
1844 ssh->rdpkt2_state.incoming_sequence = 0;
1846 s->vstring[s->vslen] = 0;
1847 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1850 vlog = smalloc(20 + s->vslen);
1851 sprintf(vlog, "Server version: %s", s->vstring);
1855 ssh_detect_bugs(ssh, s->vstring);
1858 * Decide which SSH protocol version to support.
1861 /* Anything strictly below "2.0" means protocol 1 is supported. */
1862 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
1863 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1864 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
1866 if (cfg.sshprot == 0 && !s->proto1) {
1867 bombout(("SSH protocol version 1 required by user but not provided by server"));
1870 if (cfg.sshprot == 3 && !s->proto2) {
1871 bombout(("SSH protocol version 2 required by user but not provided by server"));
1875 if (s->proto2 && (cfg.sshprot >= 2 || !s->proto1)) {
1879 char verstring[80], vlog[100];
1880 sprintf(verstring, "SSH-2.0-%s", sshver);
1881 SHA_Init(&ssh->exhashbase);
1883 * Hash our version string and their version string.
1885 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1886 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
1887 sprintf(vlog, "We claim version: %s", verstring);
1889 strcat(verstring, "\n");
1890 logevent("Using SSH protocol version 2");
1891 sk_write(ssh->s, verstring, strlen(verstring));
1892 ssh->protocol = ssh2_protocol;
1894 ssh->s_rdpkt = ssh2_rdpkt;
1899 char verstring[80], vlog[100];
1900 sprintf(verstring, "SSH-%s-%s",
1901 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
1903 sprintf(vlog, "We claim version: %s", verstring);
1905 strcat(verstring, "\n");
1907 logevent("Using SSH protocol version 1");
1908 sk_write(ssh->s, verstring, strlen(verstring));
1909 ssh->protocol = ssh1_protocol;
1911 ssh->s_rdpkt = ssh1_rdpkt;
1913 ssh->state = SSH_STATE_BEFORE_SIZE;
1920 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
1922 crBegin(ssh->ssh_gotdata_crstate);
1925 * To begin with, feed the characters one by one to the
1926 * protocol initialisation / selection function do_ssh_init().
1927 * When that returns 0, we're done with the initial greeting
1928 * exchange and can move on to packet discipline.
1931 int ret; /* need not be kept across crReturn */
1933 crReturnV; /* more data please */
1934 ret = do_ssh_init(ssh, *data);
1942 * We emerge from that loop when the initial negotiation is
1943 * over and we have selected an s_rdpkt function. Now pass
1944 * everything to s_rdpkt, and then pass the resulting packets
1945 * to the proper protocol handler.
1950 while (datalen > 0) {
1951 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
1952 if (ssh->state == SSH_STATE_CLOSED) {
1955 ssh->protocol(ssh, NULL, 0, 1);
1956 if (ssh->state == SSH_STATE_CLOSED) {
1966 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1969 Ssh ssh = (Ssh) plug;
1970 ssh->state = SSH_STATE_CLOSED;
1976 /* A socket error has occurred. */
1977 logevent(error_msg);
1978 connection_fatal(error_msg);
1980 /* Otherwise, the remote side closed the connection normally. */
1985 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1987 Ssh ssh = (Ssh) plug;
1988 ssh_gotdata(ssh, data, len);
1989 if (ssh->state == SSH_STATE_CLOSED) {
1999 static void ssh_sent(Plug plug, int bufsize)
2001 Ssh ssh = (Ssh) plug;
2003 * If the send backlog on the SSH socket itself clears, we
2004 * should unthrottle the whole world if it was throttled.
2006 if (bufsize < SSH_MAX_BACKLOG)
2007 ssh_throttle_all(ssh, 0, bufsize);
2011 * Connect to specified host and port.
2012 * Returns an error message, or NULL on success.
2013 * Also places the canonical host name into `realhost'. It must be
2014 * freed by the caller.
2016 static char *connect_to_host(Ssh ssh, char *host, int port,
2017 char **realhost, int nodelay)
2019 static const struct plug_function_table fn_table = {
2029 ssh->savedhost = smalloc(1 + strlen(host));
2030 if (!ssh->savedhost)
2031 fatalbox("Out of memory");
2032 strcpy(ssh->savedhost, host);
2035 port = 22; /* default ssh port */
2036 ssh->savedport = port;
2043 sprintf(buf, "Looking up host \"%.170s\"", host);
2046 addr = sk_namelookup(host, realhost);
2047 if ((err = sk_addr_error(addr)))
2054 char buf[200], addrbuf[100];
2055 sk_getaddr(addr, addrbuf, 100);
2056 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2059 ssh->fn = &fn_table;
2060 ssh->s = new_connection(addr, *realhost, port, 0, 1, nodelay, (Plug) ssh);
2061 if ((err = sk_socket_error(ssh->s))) {
2070 * Throttle or unthrottle the SSH connection.
2072 static void ssh1_throttle(Ssh ssh, int adjust)
2074 int old_count = ssh->v1_throttle_count;
2075 ssh->v1_throttle_count += adjust;
2076 assert(ssh->v1_throttle_count >= 0);
2077 if (ssh->v1_throttle_count && !old_count) {
2078 sk_set_frozen(ssh->s, 1);
2079 } else if (!ssh->v1_throttle_count && old_count) {
2080 sk_set_frozen(ssh->s, 0);
2085 * Throttle or unthrottle _all_ local data streams (for when sends
2086 * on the SSH connection itself back up).
2088 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2091 struct ssh_channel *c;
2093 if (enable == ssh->throttled_all)
2095 ssh->throttled_all = enable;
2096 ssh->overall_bufsize = bufsize;
2099 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2101 case CHAN_MAINSESSION:
2103 * This is treated separately, outside the switch.
2107 x11_override_throttle(c->u.x11.s, enable);
2110 /* Agent channels require no buffer management. */
2113 pfd_override_throttle(c->u.x11.s, enable);
2120 * Username and password input, abstracted off into routines
2121 * reusable in several places - even between SSH1 and SSH2.
2124 /* Set up a username or password input loop on a given buffer. */
2125 void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2127 ssh->userpass_input_buffer = buffer;
2128 ssh->userpass_input_buflen = buflen;
2129 ssh->userpass_input_bufpos = 0;
2130 ssh->userpass_input_echo = echo;
2134 * Process some terminal data in the course of username/password
2135 * input. Returns >0 for success (line of input returned in
2136 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2137 * for inconclusive (keep waiting for more input please).
2139 int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2144 switch (c = *in++) {
2147 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2148 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2153 if (ssh->userpass_input_bufpos > 0) {
2154 if (ssh->userpass_input_echo)
2155 c_write_str(ssh, "\b \b");
2156 ssh->userpass_input_bufpos--;
2161 while (ssh->userpass_input_bufpos > 0) {
2162 if (ssh->userpass_input_echo)
2163 c_write_str(ssh, "\b \b");
2164 ssh->userpass_input_bufpos--;
2172 if (((c >= ' ' && c <= '~') ||
2173 ((unsigned char) c >= 160))
2174 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2175 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2176 if (ssh->userpass_input_echo)
2177 c_write(ssh, &c, 1);
2186 * Handle the key exchange and user authentication phases.
2188 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2191 unsigned char cookie[8];
2192 struct RSAKey servkey, hostkey;
2193 struct MD5Context md5c;
2194 struct do_ssh1_login_state {
2196 unsigned char *rsabuf, *keystr1, *keystr2;
2197 unsigned long supported_ciphers_mask, supported_auths_mask;
2198 int tried_publickey, tried_agent;
2199 int tis_auth_refused, ccard_auth_refused;
2200 unsigned char session_id[16];
2203 void *publickey_blob;
2204 int publickey_bloblen;
2210 unsigned char request[5], *response, *p;
2219 crState(do_ssh1_login_state);
2221 crBegin(ssh->do_ssh1_login_crstate);
2226 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2227 bombout(("Public key packet not received"));
2231 logevent("Received public keys");
2233 memcpy(cookie, ssh->pktin.body, 8);
2235 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2236 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
2239 * Log the host key fingerprint.
2243 logevent("Host key fingerprint is:");
2244 strcpy(logmsg, " ");
2245 hostkey.comment = NULL;
2246 rsa_fingerprint(logmsg + strlen(logmsg),
2247 sizeof(logmsg) - strlen(logmsg), &hostkey);
2251 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2252 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2253 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
2255 ssh->v1_local_protoflags =
2256 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2257 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2260 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2261 MD5Update(&md5c, s->keystr1, servkey.bytes);
2262 MD5Update(&md5c, ssh->pktin.body, 8);
2263 MD5Final(s->session_id, &md5c);
2265 for (i = 0; i < 32; i++)
2266 ssh->session_key[i] = random_byte();
2268 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2270 s->rsabuf = smalloc(s->len);
2272 fatalbox("Out of memory");
2275 * Verify the host key.
2279 * First format the key into a string.
2281 int len = rsastr_len(&hostkey);
2282 char fingerprint[100];
2283 char *keystr = smalloc(len);
2285 fatalbox("Out of memory");
2286 rsastr_fmt(keystr, &hostkey);
2287 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2288 verify_ssh_host_key(ssh->savedhost, ssh->savedport, "rsa", keystr,
2293 for (i = 0; i < 32; i++) {
2294 s->rsabuf[i] = ssh->session_key[i];
2296 s->rsabuf[i] ^= s->session_id[i];
2299 if (hostkey.bytes > servkey.bytes) {
2300 rsaencrypt(s->rsabuf, 32, &servkey);
2301 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2303 rsaencrypt(s->rsabuf, 32, &hostkey);
2304 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2307 logevent("Encrypted session key");
2310 int cipher_chosen = 0, warn = 0;
2311 char *cipher_string = NULL;
2313 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2314 int next_cipher = cfg.ssh_cipherlist[i];
2315 if (next_cipher == CIPHER_WARN) {
2316 /* If/when we choose a cipher, warn about it */
2318 } else if (next_cipher == CIPHER_AES) {
2319 /* XXX Probably don't need to mention this. */
2320 logevent("AES not supported in SSH1, skipping");
2322 switch (next_cipher) {
2323 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2324 cipher_string = "3DES"; break;
2325 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2326 cipher_string = "Blowfish"; break;
2327 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2328 cipher_string = "single-DES"; break;
2330 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2334 if (!cipher_chosen) {
2335 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2336 bombout(("Server violates SSH 1 protocol by not "
2337 "supporting 3DES encryption"));
2339 /* shouldn't happen */
2340 bombout(("No supported ciphers found"));
2344 /* Warn about chosen cipher if necessary. */
2346 askcipher(cipher_string, 0);
2349 switch (s->cipher_type) {
2350 case SSH_CIPHER_3DES:
2351 logevent("Using 3DES encryption");
2353 case SSH_CIPHER_DES:
2354 logevent("Using single-DES encryption");
2356 case SSH_CIPHER_BLOWFISH:
2357 logevent("Using Blowfish encryption");
2361 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2362 PKT_CHAR, s->cipher_type,
2363 PKT_DATA, cookie, 8,
2364 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2365 PKT_DATA, s->rsabuf, s->len,
2366 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2368 logevent("Trying to enable encryption...");
2372 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2373 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2375 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2376 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2379 sprintf(buf, "Initialised %.200s encryption", ssh->cipher->text_name);
2383 ssh->crcda_ctx = crcda_make_context();
2384 logevent("Installing CRC compensation attack detector");
2388 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2389 bombout(("Encryption not successfully enabled"));
2393 logevent("Successfully started encryption");
2397 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2398 if (ssh_get_line && !ssh_getline_pw_only) {
2399 if (!ssh_get_line("login as: ",
2400 s->username, sizeof(s->username), FALSE)) {
2402 * get_line failed to get a username.
2405 logevent("No username provided. Abandoning session.");
2406 ssh->state = SSH_STATE_CLOSED;
2410 int ret; /* need not be kept over crReturn */
2411 c_write_str(ssh, "login as: ");
2414 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2416 crWaitUntil(!ispkt);
2417 ret = process_userpass_input(ssh, in, inlen);
2421 c_write_str(ssh, "\r\n");
2424 strncpy(s->username, cfg.username, sizeof(s->username));
2425 s->username[sizeof(s->username)-1] = '\0';
2428 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2430 char userlog[22 + sizeof(s->username)];
2431 sprintf(userlog, "Sent username \"%s\"", s->username);
2433 if (flags & FLAG_INTERACTIVE &&
2434 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2435 strcat(userlog, "\r\n");
2436 c_write_str(ssh, userlog);
2443 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2444 /* We must not attempt PK auth. Pretend we've already tried it. */
2445 s->tried_publickey = s->tried_agent = 1;
2447 s->tried_publickey = s->tried_agent = 0;
2449 s->tis_auth_refused = s->ccard_auth_refused = 0;
2450 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2452 if (!rsakey_pubblob(cfg.keyfile,
2453 &s->publickey_blob, &s->publickey_bloblen))
2454 s->publickey_blob = NULL;
2456 s->publickey_blob = NULL;
2458 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2459 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2461 if (agent_exists() && !s->tried_agent) {
2463 * Attempt RSA authentication using Pageant.
2469 logevent("Pageant is running. Requesting keys.");
2471 /* Request the keys held by the agent. */
2472 PUT_32BIT(s->request, 1);
2473 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2474 agent_query(s->request, 5, &r, &s->responselen);
2475 s->response = (unsigned char *) r;
2476 if (s->response && s->responselen >= 5 &&
2477 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2478 s->p = s->response + 5;
2479 s->nkeys = GET_32BIT(s->p);
2483 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2486 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2489 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2492 if (s->publickey_blob &&
2493 !memcmp(s->p, s->publickey_blob,
2494 s->publickey_bloblen)) {
2495 logevent("This key matches configured key file");
2496 s->tried_publickey = 1;
2499 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2500 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2501 s->commentlen = GET_32BIT(s->p);
2504 s->p += s->commentlen;
2505 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2506 PKT_BIGNUM, s->key.modulus, PKT_END);
2508 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2509 logevent("Key refused");
2512 logevent("Received RSA challenge");
2513 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
2515 char *agentreq, *q, *ret;
2518 len = 1 + 4; /* message type, bit count */
2519 len += ssh1_bignum_length(s->key.exponent);
2520 len += ssh1_bignum_length(s->key.modulus);
2521 len += ssh1_bignum_length(s->challenge);
2522 len += 16; /* session id */
2523 len += 4; /* response format */
2524 agentreq = smalloc(4 + len);
2525 PUT_32BIT(agentreq, len);
2527 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2528 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2530 q += ssh1_write_bignum(q, s->key.exponent);
2531 q += ssh1_write_bignum(q, s->key.modulus);
2532 q += ssh1_write_bignum(q, s->challenge);
2533 memcpy(q, s->session_id, 16);
2535 PUT_32BIT(q, 1); /* response format */
2536 agent_query(agentreq, len + 4, &vret, &retlen);
2540 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2541 logevent("Sending Pageant's response");
2542 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2543 PKT_DATA, ret + 5, 16,
2547 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
2549 ("Pageant's response accepted");
2550 if (flags & FLAG_VERBOSE) {
2551 c_write_str(ssh, "Authenticated using"
2553 c_write(ssh, s->commentp,
2555 c_write_str(ssh, "\" from agent\r\n");
2560 ("Pageant's response not accepted");
2563 ("Pageant failed to answer challenge");
2567 logevent("No reply received from Pageant");
2570 freebn(s->key.exponent);
2571 freebn(s->key.modulus);
2572 freebn(s->challenge);
2580 if (*cfg.keyfile && !s->tried_publickey)
2581 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
2583 if (cfg.try_tis_auth &&
2584 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2585 !s->tis_auth_refused) {
2586 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2587 logevent("Requested TIS authentication");
2588 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
2590 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2591 logevent("TIS authentication declined");
2592 if (flags & FLAG_INTERACTIVE)
2593 c_write_str(ssh, "TIS authentication refused.\r\n");
2594 s->tis_auth_refused = 1;
2597 int challengelen = GET_32BIT(ssh->pktin.body);
2598 logevent("Received TIS challenge");
2599 if (challengelen > sizeof(s->prompt) - 1)
2600 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2601 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2602 /* Prompt heuristic comes from OpenSSH */
2603 strncpy(s->prompt + challengelen,
2604 memchr(s->prompt, '\n', challengelen) ?
2605 "": "\r\nResponse: ",
2606 (sizeof s->prompt) - challengelen);
2607 s->prompt[(sizeof s->prompt) - 1] = '\0';
2610 if (cfg.try_tis_auth &&
2611 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2612 !s->ccard_auth_refused) {
2613 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2614 logevent("Requested CryptoCard authentication");
2615 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
2617 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2618 logevent("CryptoCard authentication declined");
2619 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2620 s->ccard_auth_refused = 1;
2623 int challengelen = GET_32BIT(ssh->pktin.body);
2624 logevent("Received CryptoCard challenge");
2625 if (challengelen > sizeof(s->prompt) - 1)
2626 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2627 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2628 strncpy(s->prompt + challengelen,
2629 memchr(s->prompt, '\n', challengelen) ?
2630 "" : "\r\nResponse: ",
2631 sizeof(s->prompt) - challengelen);
2632 s->prompt[sizeof(s->prompt) - 1] = '\0';
2635 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2636 sprintf(s->prompt, "%.90s@%.90s's password: ",
2637 s->username, ssh->savedhost);
2639 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2640 char *comment = NULL;
2643 if (flags & FLAG_VERBOSE)
2644 c_write_str(ssh, "Trying public key authentication.\r\n");
2645 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2647 type = key_type(cfg.keyfile);
2648 if (type != SSH_KEYTYPE_SSH1) {
2649 sprintf(msgbuf, "Key is of wrong type (%s)",
2650 key_type_to_str(type));
2652 c_write_str(ssh, msgbuf);
2653 c_write_str(ssh, "\r\n");
2654 s->tried_publickey = 1;
2657 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2658 if (flags & FLAG_VERBOSE)
2659 c_write_str(ssh, "No passphrase required.\r\n");
2662 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
2667 * Show password prompt, having first obtained it via a TIS
2668 * or CryptoCard exchange if we're doing TIS or CryptoCard
2672 if (!ssh_get_line(s->prompt, s->password,
2673 sizeof(s->password), TRUE)) {
2675 * get_line failed to get a password (for example
2676 * because one was supplied on the command line
2677 * which has already failed to work). Terminate.
2679 send_packet(ssh, SSH1_MSG_DISCONNECT,
2680 PKT_STR, "No more passwords available to try",
2682 logevent("Unable to authenticate");
2683 connection_fatal("Unable to authenticate");
2684 ssh->state = SSH_STATE_CLOSED;
2688 /* Prompt may have come from server. We've munged it a bit, so
2689 * we know it to be zero-terminated at least once. */
2690 int ret; /* need not be saved over crReturn */
2691 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2694 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
2696 crWaitUntil(!ispkt);
2697 ret = process_userpass_input(ssh, in, inlen);
2701 c_write_str(ssh, "\r\n");
2705 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2707 * Try public key authentication with the specified
2710 s->tried_publickey = 1;
2713 int ret = loadrsakey(cfg.keyfile, &s->key, s->password);
2715 c_write_str(ssh, "Couldn't load private key from ");
2716 c_write_str(ssh, cfg.keyfile);
2717 c_write_str(ssh, ".\r\n");
2718 continue; /* go and try password */
2721 c_write_str(ssh, "Wrong passphrase.\r\n");
2722 s->tried_publickey = 0;
2723 continue; /* try again */
2728 * Send a public key attempt.
2730 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2731 PKT_BIGNUM, s->key.modulus, PKT_END);
2734 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2735 c_write_str(ssh, "Server refused our public key.\r\n");
2736 continue; /* go and try password */
2738 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2739 bombout(("Bizarre response to offer of public key"));
2745 unsigned char buffer[32];
2746 Bignum challenge, response;
2748 ssh1_read_bignum(ssh->pktin.body, &challenge);
2749 response = rsadecrypt(challenge, &s->key);
2750 freebn(s->key.private_exponent);/* burn the evidence */
2752 for (i = 0; i < 32; i++) {
2753 buffer[i] = bignum_byte(response, 31 - i);
2757 MD5Update(&md5c, buffer, 32);
2758 MD5Update(&md5c, s->session_id, 16);
2759 MD5Final(buffer, &md5c);
2761 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2762 PKT_DATA, buffer, 16, PKT_END);
2769 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2770 if (flags & FLAG_VERBOSE)
2771 c_write_str(ssh, "Failed to authenticate with"
2772 " our public key.\r\n");
2773 continue; /* go and try password */
2774 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2775 bombout(("Bizarre response to RSA authentication response"));
2779 break; /* we're through! */
2781 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2783 * Defence against traffic analysis: we send a
2784 * whole bunch of packets containing strings of
2785 * different lengths. One of these strings is the
2786 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2787 * The others are all random data in
2788 * SSH1_MSG_IGNORE packets. This way a passive
2789 * listener can't tell which is the password, and
2790 * hence can't deduce the password length.
2792 * Anybody with a password length greater than 16
2793 * bytes is going to have enough entropy in their
2794 * password that a listener won't find it _that_
2795 * much help to know how long it is. So what we'll
2798 * - if password length < 16, we send 15 packets
2799 * containing string lengths 1 through 15
2801 * - otherwise, we let N be the nearest multiple
2802 * of 8 below the password length, and send 8
2803 * packets containing string lengths N through
2804 * N+7. This won't obscure the order of
2805 * magnitude of the password length, but it will
2806 * introduce a bit of extra uncertainty.
2808 * A few servers (the old 1.2.18 through 1.2.22)
2809 * can't deal with SSH1_MSG_IGNORE. For these
2810 * servers, we need an alternative defence. We make
2811 * use of the fact that the password is interpreted
2812 * as a C string: so we can append a NUL, then some
2815 * One server (a Cisco one) can deal with neither
2816 * SSH1_MSG_IGNORE _nor_ a padded password string.
2817 * For this server we are left with no defences
2818 * against password length sniffing.
2820 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2822 * The server can deal with SSH1_MSG_IGNORE, so
2823 * we can use the primary defence.
2825 int bottom, top, pwlen, i;
2828 pwlen = strlen(s->password);
2830 bottom = 0; /* zero length passwords are OK! :-) */
2833 bottom = pwlen & ~7;
2837 assert(pwlen >= bottom && pwlen <= top);
2839 randomstr = smalloc(top + 1);
2841 for (i = bottom; i <= top; i++) {
2843 defer_packet(ssh, s->pwpkt_type,
2844 PKT_STR, s->password, PKT_END);
2846 for (j = 0; j < i; j++) {
2848 randomstr[j] = random_byte();
2849 } while (randomstr[j] == '\0');
2851 randomstr[i] = '\0';
2852 defer_packet(ssh, SSH1_MSG_IGNORE,
2853 PKT_STR, randomstr, PKT_END);
2856 logevent("Sending password with camouflage packets");
2857 ssh_pkt_defersend(ssh);
2859 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2861 * The server can't deal with SSH1_MSG_IGNORE
2862 * but can deal with padded passwords, so we
2863 * can use the secondary defence.
2869 len = strlen(s->password);
2870 if (len < sizeof(string)) {
2872 strcpy(string, s->password);
2873 len++; /* cover the zero byte */
2874 while (len < sizeof(string)) {
2875 string[len++] = (char) random_byte();
2880 logevent("Sending length-padded password");
2881 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2882 PKT_DATA, ss, len, PKT_END);
2885 * The server has _both_
2886 * BUG_CHOKES_ON_SSH1_IGNORE and
2887 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2888 * therefore nothing we can do.
2891 len = strlen(s->password);
2892 logevent("Sending unpadded password");
2893 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2894 PKT_DATA, s->password, len, PKT_END);
2897 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
2900 logevent("Sent password");
2901 memset(s->password, 0, strlen(s->password));
2903 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2904 if (flags & FLAG_VERBOSE)
2905 c_write_str(ssh, "Access denied\r\n");
2906 logevent("Authentication refused");
2907 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2908 bombout(("Strange packet received, type %d", ssh->pktin.type));
2913 logevent("Authentication successful");
2918 void sshfwd_close(struct ssh_channel *c)
2922 if (c && !c->closes) {
2924 * If the channel's remoteid is -1, we have sent
2925 * CHANNEL_OPEN for this channel, but it hasn't even been
2926 * acknowledged by the server. So we must set a close flag
2927 * on it now, and then when the server acks the channel
2928 * open, we can close it then.
2930 if (((int)c->remoteid) != -1) {
2931 if (ssh->version == 1) {
2932 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2935 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
2936 ssh2_pkt_adduint32(ssh, c->remoteid);
2940 c->closes = 1; /* sent MSG_CLOSE */
2941 if (c->type == CHAN_X11) {
2943 logevent("Forwarded X11 connection terminated");
2944 } else if (c->type == CHAN_SOCKDATA ||
2945 c->type == CHAN_SOCKDATA_DORMANT) {
2947 logevent("Forwarded port closed");
2952 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2956 if (ssh->version == 1) {
2957 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2958 PKT_INT, c->remoteid,
2959 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2961 * In SSH1 we can return 0 here - implying that forwarded
2962 * connections are never individually throttled - because
2963 * the only circumstance that can cause throttling will be
2964 * the whole SSH connection backing up, in which case
2965 * _everything_ will be throttled as a whole.
2969 ssh2_add_channel_data(c, buf, len);
2970 return ssh2_try_send(c);
2974 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2978 if (ssh->version == 1) {
2979 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2980 c->v.v1.throttling = 0;
2981 ssh1_throttle(ssh, -1);
2984 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2988 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2990 crBegin(ssh->ssh1_protocol_crstate);
2994 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
2997 if (ssh->state == SSH_STATE_CLOSED)
3000 if (cfg.agentfwd && agent_exists()) {
3001 logevent("Requesting agent forwarding");
3002 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3006 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3007 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3008 bombout(("Protocol confusion"));
3010 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3011 logevent("Agent forwarding refused");
3013 logevent("Agent forwarding enabled");
3014 ssh->agentfwd_enabled = TRUE;
3018 if (cfg.x11_forward) {
3019 char proto[20], data[64];
3020 logevent("Requesting X11 forwarding");
3021 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3022 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3023 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3024 PKT_STR, proto, PKT_STR, data,
3025 PKT_INT, 0, PKT_END);
3027 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3028 PKT_STR, proto, PKT_STR, data, PKT_END);
3033 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3034 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3035 bombout(("Protocol confusion"));
3037 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3038 logevent("X11 forwarding refused");
3040 logevent("X11 forwarding enabled");
3041 ssh->X11_fwd_enabled = TRUE;
3048 int sport,dport,sserv,dserv;
3049 char sports[256], dports[256], host[256];
3053 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3054 /* Add port forwardings. */
3055 ssh->portfwd_strptr = cfg.portfwd;
3056 while (*ssh->portfwd_strptr) {
3057 type = *ssh->portfwd_strptr++;
3059 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
3060 sports[n++] = *ssh->portfwd_strptr++;
3062 if (*ssh->portfwd_strptr == '\t')
3063 ssh->portfwd_strptr++;
3065 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
3066 host[n++] = *ssh->portfwd_strptr++;
3068 if (*ssh->portfwd_strptr == ':')
3069 ssh->portfwd_strptr++;
3071 while (*ssh->portfwd_strptr)
3072 dports[n++] = *ssh->portfwd_strptr++;
3074 ssh->portfwd_strptr++;
3075 dport = atoi(dports);
3079 se = getservbyname(dports, NULL);
3081 dport = ntohs(se->s_port);
3084 "Service lookup failed for destination port \"%s\"",
3089 sport = atoi(sports);
3093 se = getservbyname(sports, NULL);
3095 sport = ntohs(se->s_port);
3098 "Service lookup failed for source port \"%s\"",
3103 if (sport && dport) {
3105 pfd_addforward(host, dport, sport);
3106 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3107 " %s:%.*s%.*s%d%.*s",
3108 sserv ? strlen(sports) : 0, sports,
3109 sserv, "(", sport, sserv, ")",
3111 dserv ? strlen(dports) : 0, dports,
3112 dserv, "(", dport, dserv, ")");
3115 struct ssh_rportfwd *pf;
3116 pf = smalloc(sizeof(*pf));
3117 strcpy(pf->dhost, host);
3119 if (add234(ssh->rportfwds, pf) != pf) {
3121 "Duplicate remote port forwarding to %s:%d",
3126 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3127 " forward to %s:%.*s%.*s%d%.*s",
3128 sserv ? strlen(sports) : 0, sports,
3129 sserv, "(", sport, sserv, ")",
3131 dserv ? strlen(dports) : 0, dports,
3132 dserv, "(", dport, dserv, ")");
3134 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3142 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3143 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3144 bombout(("Protocol confusion"));
3146 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3147 c_write_str(ssh, "Server refused port"
3150 logevent("Remote port forwarding enabled");
3158 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
3159 PKT_STR, cfg.termtype,
3160 PKT_INT, ssh->term_height,
3161 PKT_INT, ssh->term_width,
3162 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3163 ssh->state = SSH_STATE_INTERMED;
3167 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3168 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3169 bombout(("Protocol confusion"));
3171 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3172 c_write_str(ssh, "Server refused to allocate pty\r\n");
3173 ssh->editing = ssh->echoing = 1;
3175 logevent("Allocated pty");
3177 ssh->editing = ssh->echoing = 1;
3180 if (cfg.compression) {
3181 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3185 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3186 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3187 bombout(("Protocol confusion"));
3189 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3190 c_write_str(ssh, "Server refused to compress\r\n");
3192 logevent("Started compression");
3193 ssh->v1_compressing = TRUE;
3194 zlib_compress_init();
3195 zlib_decompress_init();
3199 * Start the shell or command.
3201 * Special case: if the first-choice command is an SSH2
3202 * subsystem (hence not usable here) and the second choice
3203 * exists, we fall straight back to that.
3206 char *cmd = cfg.remote_cmd_ptr;
3208 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3209 cmd = cfg.remote_cmd_ptr2;
3210 ssh->fallback_cmd = TRUE;
3213 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3215 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
3216 logevent("Started session");
3219 ssh->state = SSH_STATE_SESSION;
3220 if (ssh->size_needed)
3221 ssh_size(ssh, ssh->term_width, ssh->term_height);
3222 if (ssh->eof_needed)
3223 ssh_special(ssh, TS_EOF);
3225 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
3227 ssh->channels = newtree234(ssh_channelcmp);
3231 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
3232 ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
3233 long len = GET_32BIT(ssh->pktin.body);
3235 from_backend(ssh->frontend,
3236 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
3237 ssh->pktin.body + 4, len);
3238 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3239 ssh->v1_stdout_throttling = 1;
3240 ssh1_throttle(ssh, +1);
3242 } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
3243 ssh->state = SSH_STATE_CLOSED;
3244 logevent("Received disconnect request");
3246 } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
3247 /* Remote side is trying to open a channel to talk to our
3248 * X-Server. Give them back a local channel number. */
3249 struct ssh_channel *c;
3251 logevent("Received X11 connect request");
3252 /* Refuse if X11 forwarding is disabled. */
3253 if (!ssh->X11_fwd_enabled) {
3254 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3255 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3256 logevent("Rejected X11 connect request");
3258 c = smalloc(sizeof(struct ssh_channel));
3261 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3262 logevent("opening X11 forward connection failed");
3264 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3265 PKT_INT, GET_32BIT(ssh->pktin.body),
3269 ("opening X11 forward connection succeeded");
3270 c->remoteid = GET_32BIT(ssh->pktin.body);
3271 c->localid = alloc_channel_id(ssh);
3273 c->v.v1.throttling = 0;
3274 c->type = CHAN_X11; /* identify channel type */
3275 add234(ssh->channels, c);
3276 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3277 PKT_INT, c->remoteid, PKT_INT,
3278 c->localid, PKT_END);
3279 logevent("Opened X11 forward channel");
3282 } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
3283 /* Remote side is trying to open a channel to talk to our
3284 * agent. Give them back a local channel number. */
3285 struct ssh_channel *c;
3287 /* Refuse if agent forwarding is disabled. */
3288 if (!ssh->agentfwd_enabled) {
3289 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3290 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3292 c = smalloc(sizeof(struct ssh_channel));
3294 c->remoteid = GET_32BIT(ssh->pktin.body);
3295 c->localid = alloc_channel_id(ssh);
3297 c->v.v1.throttling = 0;
3298 c->type = CHAN_AGENT; /* identify channel type */
3299 c->u.a.lensofar = 0;
3300 add234(ssh->channels, c);
3301 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3302 PKT_INT, c->remoteid, PKT_INT, c->localid,
3305 } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
3306 /* Remote side is trying to open a channel to talk to a
3307 * forwarded port. Give them back a local channel number. */
3308 struct ssh_channel *c;
3309 struct ssh_rportfwd pf;
3311 char host[256], buf[1024];
3313 c = smalloc(sizeof(struct ssh_channel));
3316 hostsize = GET_32BIT(ssh->pktin.body+4);
3317 for(h = host, p = ssh->pktin.body+8; hostsize != 0; hostsize--) {
3318 if (h+1 < host+sizeof(host))
3323 port = GET_32BIT(p);
3325 strcpy(pf.dhost, host);
3328 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3329 sprintf(buf, "Rejected remote port open request for %s:%d",
3332 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3333 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3335 sprintf(buf, "Received remote port open request for %s:%d",
3338 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3341 sprintf(buf, "Port open failed: %s", e);
3344 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3345 PKT_INT, GET_32BIT(ssh->pktin.body),
3348 c->remoteid = GET_32BIT(ssh->pktin.body);
3349 c->localid = alloc_channel_id(ssh);
3351 c->v.v1.throttling = 0;
3352 c->type = CHAN_SOCKDATA; /* identify channel type */
3353 add234(ssh->channels, c);
3354 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3355 PKT_INT, c->remoteid, PKT_INT,
3356 c->localid, PKT_END);
3357 logevent("Forwarded port opened successfully");
3361 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3362 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3363 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3364 struct ssh_channel *c;
3366 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3367 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3368 c->remoteid = localid;
3369 c->type = CHAN_SOCKDATA;
3370 c->v.v1.throttling = 0;
3371 pfd_confirm(c->u.pfd.s);
3374 if (c && c->closes) {
3376 * We have a pending close on this channel,
3377 * which we decided on before the server acked
3378 * the channel open. So now we know the
3379 * remoteid, we can close it again.
3381 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3382 PKT_INT, c->remoteid, PKT_END);
3385 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3386 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3387 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3388 struct ssh_channel *c;
3390 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3391 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3392 logevent("Forwarded connection refused by server");
3393 pfd_close(c->u.pfd.s);
3394 del234(ssh->channels, c);
3398 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3399 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3400 /* Remote side closes a channel. */
3401 unsigned i = GET_32BIT(ssh->pktin.body);
3402 struct ssh_channel *c;
3403 c = find234(ssh->channels, &i, ssh_channelfind);
3404 if (c && ((int)c->remoteid) != -1) {
3407 (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3409 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3410 logevent("Forwarded X11 connection terminated");
3411 assert(c->u.x11.s != NULL);
3412 x11_close(c->u.x11.s);
3415 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3416 logevent("Forwarded port closed");
3417 assert(c->u.pfd.s != NULL);
3418 pfd_close(c->u.pfd.s);
3422 c->closes |= (closetype << 2); /* seen this message */
3423 if (!(c->closes & closetype)) {
3424 send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
3426 c->closes |= closetype; /* sent it too */
3429 if (c->closes == 15) {
3430 del234(ssh->channels, c);
3434 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3435 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3436 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3439 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
3440 /* Data sent down one of our channels. */
3441 int i = GET_32BIT(ssh->pktin.body);
3442 int len = GET_32BIT(ssh->pktin.body + 4);
3443 unsigned char *p = ssh->pktin.body + 8;
3444 struct ssh_channel *c;
3445 c = find234(ssh->channels, &i, ssh_channelfind);
3450 bufsize = x11_send(c->u.x11.s, p, len);
3453 bufsize = pfd_send(c->u.pfd.s, p, len);
3456 /* Data for an agent message. Buffer it. */
3458 if (c->u.a.lensofar < 4) {
3459 int l = min(4 - c->u.a.lensofar, len);
3460 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3464 c->u.a.lensofar += l;
3466 if (c->u.a.lensofar == 4) {
3468 4 + GET_32BIT(c->u.a.msglen);
3469 c->u.a.message = smalloc(c->u.a.totallen);
3470 memcpy(c->u.a.message, c->u.a.msglen, 4);
3472 if (c->u.a.lensofar >= 4 && len > 0) {
3474 min(c->u.a.totallen - c->u.a.lensofar,
3476 memcpy(c->u.a.message + c->u.a.lensofar, p,
3480 c->u.a.lensofar += l;
3482 if (c->u.a.lensofar == c->u.a.totallen) {
3483 void *reply, *sentreply;
3485 agent_query(c->u.a.message,
3486 c->u.a.totallen, &reply,
3491 /* Fake SSH_AGENT_FAILURE. */
3492 sentreply = "\0\0\0\1\5";
3495 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3496 PKT_INT, c->remoteid,
3498 PKT_DATA, sentreply, replylen,
3502 sfree(c->u.a.message);
3503 c->u.a.lensofar = 0;
3506 bufsize = 0; /* agent channels never back up */
3509 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3510 c->v.v1.throttling = 1;
3511 ssh1_throttle(ssh, +1);
3514 } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
3515 /* may be from EXEC_SHELL on some servers */
3516 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3517 /* may be from EXEC_SHELL on some servers
3518 * if no pty is available or in other odd cases. Ignore */
3519 } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
3521 ssh->exitcode = GET_32BIT(ssh->pktin.body);
3522 sprintf(buf, "Server sent command exit status %d",
3525 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3527 * In case `helpful' firewalls or proxies tack
3528 * extra human-readable text on the end of the
3529 * session which we might mistake for another
3530 * encrypted packet, we close the session once
3531 * we've sent EXIT_CONFIRMATION.
3533 ssh->state = SSH_STATE_CLOSED;
3536 bombout(("Strange packet received: type %d", ssh->pktin.type));
3541 int len = min(inlen, 512);
3542 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
3543 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3554 * Utility routine for decoding comma-separated strings in KEXINIT.
3556 static int in_commasep_string(char *needle, char *haystack, int haylen)
3558 int needlen = strlen(needle);
3561 * Is it at the start of the string?
3563 if (haylen >= needlen && /* haystack is long enough */
3564 !memcmp(needle, haystack, needlen) && /* initial match */
3565 (haylen == needlen || haystack[needlen] == ',')
3566 /* either , or EOS follows */
3570 * If not, search for the next comma and resume after that.
3571 * If no comma found, terminate.
3573 while (haylen > 0 && *haystack != ',')
3574 haylen--, haystack++;
3577 haylen--, haystack++; /* skip over comma itself */
3582 * SSH2 key creation method.
3584 static void ssh2_mkkey(Ssh ssh, Bignum K, char *H, char *sessid, char chr,
3588 /* First 20 bytes. */
3590 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3592 SHA_Bytes(&s, H, 20);
3593 SHA_Bytes(&s, &chr, 1);
3594 SHA_Bytes(&s, sessid, 20);
3595 SHA_Final(&s, keyspace);
3596 /* Next 20 bytes. */
3598 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3600 SHA_Bytes(&s, H, 20);
3601 SHA_Bytes(&s, keyspace, 20);
3602 SHA_Final(&s, keyspace + 20);
3606 * Handle the SSH2 transport layer.
3608 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3610 struct do_ssh2_transport_state {
3611 int nbits, pbits, warn;
3612 Bignum p, g, e, f, K;
3613 int kex_init_value, kex_reply_value;
3614 const struct ssh_mac **maclist;
3616 const struct ssh2_cipher *cscipher_tobe;
3617 const struct ssh2_cipher *sccipher_tobe;
3618 const struct ssh_mac *csmac_tobe;
3619 const struct ssh_mac *scmac_tobe;
3620 const struct ssh_compress *cscomp_tobe;
3621 const struct ssh_compress *sccomp_tobe;
3622 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3623 int hostkeylen, siglen;
3624 void *hkey; /* actual host key */
3625 unsigned char exchange_hash[20];
3626 int n_preferred_ciphers;
3627 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3628 const struct ssh_compress *preferred_comp;
3631 crState(do_ssh2_transport_state);
3633 crBegin(ssh->do_ssh2_transport_crstate);
3635 s->cscipher_tobe = s->sccipher_tobe = NULL;
3636 s->csmac_tobe = s->scmac_tobe = NULL;
3637 s->cscomp_tobe = s->sccomp_tobe = NULL;
3645 * Set up the preferred ciphers. (NULL => warn below here)
3647 s->n_preferred_ciphers = 0;
3648 for (i = 0; i < CIPHER_MAX; i++) {
3649 switch (cfg.ssh_cipherlist[i]) {
3650 case CIPHER_BLOWFISH:
3651 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3654 if (cfg.ssh2_des_cbc) {
3655 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3659 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3662 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3665 /* Flag for later. Don't bother if it's the last in
3667 if (i < CIPHER_MAX - 1) {
3668 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3676 * Set up preferred compression.
3678 if (cfg.compression)
3679 s->preferred_comp = &ssh_zlib;
3681 s->preferred_comp = &ssh_comp_none;
3684 * Be prepared to work around the buggy MAC problem.
3686 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3687 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
3689 s->maclist = macs, s->nmacs = lenof(macs);
3693 int i, j, cipherstr_started;
3696 * Construct and send our key exchange packet.
3698 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3699 for (i = 0; i < 16; i++)
3700 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3701 /* List key exchange algorithms. */
3702 ssh2_pkt_addstring_start(ssh);
3703 for (i = 0; i < lenof(kex_algs); i++) {
3704 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3705 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3707 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3708 if (i < lenof(kex_algs) - 1)
3709 ssh2_pkt_addstring_str(ssh, ",");
3711 /* List server host key algorithms. */
3712 ssh2_pkt_addstring_start(ssh);
3713 for (i = 0; i < lenof(hostkey_algs); i++) {
3714 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3715 if (i < lenof(hostkey_algs) - 1)
3716 ssh2_pkt_addstring_str(ssh, ",");
3718 /* List client->server encryption algorithms. */
3719 ssh2_pkt_addstring_start(ssh);
3720 cipherstr_started = 0;
3721 for (i = 0; i < s->n_preferred_ciphers; i++) {
3722 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3723 if (!c) continue; /* warning flag */
3724 for (j = 0; j < c->nciphers; j++) {
3725 if (cipherstr_started)
3726 ssh2_pkt_addstring_str(ssh, ",");
3727 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3728 cipherstr_started = 1;
3731 /* List server->client encryption algorithms. */
3732 ssh2_pkt_addstring_start(ssh);
3733 cipherstr_started = 0;
3734 for (i = 0; i < s->n_preferred_ciphers; i++) {
3735 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3736 if (!c) continue; /* warning flag */
3737 for (j = 0; j < c->nciphers; j++) {
3738 if (cipherstr_started)
3739 ssh2_pkt_addstring_str(ssh, ",");
3740 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3741 cipherstr_started = 1;
3744 /* List client->server MAC algorithms. */
3745 ssh2_pkt_addstring_start(ssh);
3746 for (i = 0; i < s->nmacs; i++) {
3747 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3748 if (i < s->nmacs - 1)
3749 ssh2_pkt_addstring_str(ssh, ",");
3751 /* List server->client MAC algorithms. */
3752 ssh2_pkt_addstring_start(ssh);
3753 for (i = 0; i < s->nmacs; i++) {
3754 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3755 if (i < s->nmacs - 1)
3756 ssh2_pkt_addstring_str(ssh, ",");
3758 /* List client->server compression algorithms. */
3759 ssh2_pkt_addstring_start(ssh);
3760 for (i = 0; i < lenof(compressions) + 1; i++) {
3761 const struct ssh_compress *c =
3762 i == 0 ? s->preferred_comp : compressions[i - 1];
3763 ssh2_pkt_addstring_str(ssh, c->name);
3764 if (i < lenof(compressions))
3765 ssh2_pkt_addstring_str(ssh, ",");
3767 /* List server->client compression algorithms. */
3768 ssh2_pkt_addstring_start(ssh);
3769 for (i = 0; i < lenof(compressions) + 1; i++) {
3770 const struct ssh_compress *c =
3771 i == 0 ? s->preferred_comp : compressions[i - 1];
3772 ssh2_pkt_addstring_str(ssh, c->name);
3773 if (i < lenof(compressions))
3774 ssh2_pkt_addstring_str(ssh, ",");
3776 /* List client->server languages. Empty list. */
3777 ssh2_pkt_addstring_start(ssh);
3778 /* List server->client languages. Empty list. */
3779 ssh2_pkt_addstring_start(ssh);
3780 /* First KEX packet does _not_ follow, because we're not that brave. */
3781 ssh2_pkt_addbool(ssh, FALSE);
3783 ssh2_pkt_adduint32(ssh, 0);
3786 ssh->exhash = ssh->exhashbase;
3787 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
3793 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
3796 * Now examine the other side's KEXINIT to see what we're up
3803 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
3804 bombout(("expected key exchange packet from server"));
3808 ssh->hostkey = NULL;
3809 s->cscipher_tobe = NULL;
3810 s->sccipher_tobe = NULL;
3811 s->csmac_tobe = NULL;
3812 s->scmac_tobe = NULL;
3813 s->cscomp_tobe = NULL;
3814 s->sccomp_tobe = NULL;
3815 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3816 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3817 for (i = 0; i < lenof(kex_algs); i++) {
3818 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3819 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3821 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3822 ssh->kex = kex_algs[i];
3826 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3827 for (i = 0; i < lenof(hostkey_algs); i++) {
3828 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3829 ssh->hostkey = hostkey_algs[i];
3833 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3835 for (i = 0; i < s->n_preferred_ciphers; i++) {
3836 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3840 for (j = 0; j < c->nciphers; j++) {
3841 if (in_commasep_string(c->list[j]->name, str, len)) {
3842 s->cscipher_tobe = c->list[j];
3847 if (s->cscipher_tobe) {
3849 askcipher(s->cscipher_tobe->name, 1);
3853 if (!s->cscipher_tobe) {
3854 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3858 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3860 for (i = 0; i < s->n_preferred_ciphers; i++) {
3861 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3865 for (j = 0; j < c->nciphers; j++) {
3866 if (in_commasep_string(c->list[j]->name, str, len)) {
3867 s->sccipher_tobe = c->list[j];
3872 if (s->sccipher_tobe) {
3874 askcipher(s->sccipher_tobe->name, 2);
3878 if (!s->sccipher_tobe) {
3879 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3883 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3884 for (i = 0; i < s->nmacs; i++) {
3885 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3886 s->csmac_tobe = s->maclist[i];
3890 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3891 for (i = 0; i < s->nmacs; i++) {
3892 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3893 s->scmac_tobe = s->maclist[i];
3897 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3898 for (i = 0; i < lenof(compressions) + 1; i++) {
3899 const struct ssh_compress *c =
3900 i == 0 ? s->preferred_comp : compressions[i - 1];
3901 if (in_commasep_string(c->name, str, len)) {
3906 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
3907 for (i = 0; i < lenof(compressions) + 1; i++) {
3908 const struct ssh_compress *c =
3909 i == 0 ? s->preferred_comp : compressions[i - 1];
3910 if (in_commasep_string(c->name, str, len)) {
3918 * Work out the number of bits of key we will need from the key
3919 * exchange. We start with the maximum key length of either
3925 csbits = s->cscipher_tobe->keylen;
3926 scbits = s->sccipher_tobe->keylen;
3927 s->nbits = (csbits > scbits ? csbits : scbits);
3929 /* The keys only have 160-bit entropy, since they're based on
3930 * a SHA-1 hash. So cap the key size at 160 bits. */
3935 * If we're doing Diffie-Hellman group exchange, start by
3936 * requesting a group.
3938 if (ssh->kex == &ssh_diffiehellman_gex) {
3939 logevent("Doing Diffie-Hellman group exchange");
3940 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
3942 * Work out how big a DH group we will need to allow that
3945 s->pbits = 512 << ((s->nbits - 1) / 64);
3946 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
3947 ssh2_pkt_adduint32(ssh, s->pbits);
3951 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3952 bombout(("expected key exchange group packet from server"));
3955 s->p = ssh2_pkt_getmp(ssh);
3956 s->g = ssh2_pkt_getmp(ssh);
3957 ssh->kex_ctx = dh_setup_group(s->p, s->g);
3958 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3959 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3961 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3962 ssh->kex_ctx = dh_setup_group1();
3963 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
3964 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3967 logevent("Doing Diffie-Hellman key exchange");
3969 * Now generate and send e for Diffie-Hellman.
3971 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
3972 ssh2_pkt_init(ssh, s->kex_init_value);
3973 ssh2_pkt_addmp(ssh, s->e);
3977 if (ssh->pktin.type != s->kex_reply_value) {
3978 bombout(("expected key exchange reply packet from server"));
3981 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
3982 s->f = ssh2_pkt_getmp(ssh);
3983 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
3985 s->K = dh_find_K(ssh->kex_ctx, s->f);
3987 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
3988 if (ssh->kex == &ssh_diffiehellman_gex) {
3989 sha_uint32(&ssh->exhash, s->pbits);
3990 sha_mpint(&ssh->exhash, s->p);
3991 sha_mpint(&ssh->exhash, s->g);
3993 sha_mpint(&ssh->exhash, s->e);
3994 sha_mpint(&ssh->exhash, s->f);
3995 sha_mpint(&ssh->exhash, s->K);
3996 SHA_Final(&ssh->exhash, s->exchange_hash);
3998 dh_cleanup(ssh->kex_ctx);
4001 debug(("Exchange hash is:\n"));
4002 dmemdump(s->exchange_hash, 20);
4005 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4007 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4008 s->exchange_hash, 20)) {
4009 bombout(("Server's host key did not match the signature supplied"));
4014 * Authenticate remote host: verify host key. (We've already
4015 * checked the signature of the exchange hash.)
4017 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4018 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4019 verify_ssh_host_key(ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4020 s->keystr, s->fingerprint);
4021 if (s->first_kex) { /* don't bother logging this in rekeys */
4022 logevent("Host key fingerprint is:");
4023 logevent(s->fingerprint);
4025 sfree(s->fingerprint);
4027 ssh->hostkey->freekey(s->hkey);
4030 * Send SSH2_MSG_NEWKEYS.
4032 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4036 * Expect SSH2_MSG_NEWKEYS from server.
4039 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
4040 bombout(("expected new-keys packet from server"));
4045 * Create and initialise session keys.
4047 if (ssh->cs_cipher_ctx)
4048 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4049 ssh->cscipher = s->cscipher_tobe;
4050 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4052 if (ssh->sc_cipher_ctx)
4053 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4054 ssh->sccipher = s->sccipher_tobe;
4055 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4057 if (ssh->cs_mac_ctx)
4058 ssh->csmac->free_context(ssh->cs_mac_ctx);
4059 ssh->csmac = s->csmac_tobe;
4060 ssh->cs_mac_ctx = ssh->csmac->make_context();
4062 if (ssh->sc_mac_ctx)
4063 ssh->scmac->free_context(ssh->sc_mac_ctx);
4064 ssh->scmac = s->scmac_tobe;
4065 ssh->sc_mac_ctx = ssh->scmac->make_context();
4067 ssh->cscomp = s->cscomp_tobe;
4068 ssh->sccomp = s->sccomp_tobe;
4069 ssh->cscomp->compress_init();
4070 ssh->sccomp->decompress_init();
4072 * Set IVs after keys. Here we use the exchange hash from the
4073 * _first_ key exchange.
4076 unsigned char keyspace[40];
4078 memcpy(ssh->v2_session_id, s->exchange_hash,
4079 sizeof(s->exchange_hash));
4080 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4081 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4082 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4083 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4084 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4085 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4086 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4087 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4088 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4089 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4090 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4091 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4095 sprintf(buf, "Initialised %.200s client->server encryption",
4096 ssh->cscipher->text_name);
4098 sprintf(buf, "Initialised %.200s server->client encryption",
4099 ssh->sccipher->text_name);
4105 * If this is the first key exchange phase, we must pass the
4106 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4107 * wants to see it but because it will need time to initialise
4108 * itself before it sees an actual packet. In subsequent key
4109 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4110 * it would only confuse the layer above.
4112 if (!s->first_kex) {
4118 * Now we're encrypting. Begin returning 1 to the protocol main
4119 * function so that other things can run on top of the
4120 * transport. If we ever see a KEXINIT, we must go back to the
4123 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
4126 logevent("Server initiated key re-exchange");
4127 goto begin_key_exchange;
4133 * Add data to an SSH2 channel output buffer.
4135 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4138 bufchain_add(&c->v.v2.outbuffer, buf, len);
4142 * Attempt to send data on an SSH2 channel.
4144 static int ssh2_try_send(struct ssh_channel *c)
4148 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4151 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4152 if ((unsigned)len > c->v.v2.remwindow)
4153 len = c->v.v2.remwindow;
4154 if ((unsigned)len > c->v.v2.remmaxpkt)
4155 len = c->v.v2.remmaxpkt;
4156 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4157 ssh2_pkt_adduint32(ssh, c->remoteid);
4158 ssh2_pkt_addstring_start(ssh);
4159 ssh2_pkt_addstring_data(ssh, data, len);
4161 bufchain_consume(&c->v.v2.outbuffer, len);
4162 c->v.v2.remwindow -= len;
4166 * After having sent as much data as we can, return the amount
4169 return bufchain_size(&c->v.v2.outbuffer);
4173 * Potentially enlarge the window on an SSH2 channel.
4175 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4180 * Never send WINDOW_ADJUST for a channel that the remote side
4181 * already thinks it's closed; there's no point, since it won't
4182 * be sending any more data anyway.
4187 if (newwin > c->v.v2.locwindow) {
4188 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4189 ssh2_pkt_adduint32(ssh, c->remoteid);
4190 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4192 c->v.v2.locwindow = newwin;
4197 * Handle the SSH2 userauth and connection layers.
4199 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
4201 struct do_ssh2_authconn_state {
4203 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4205 AUTH_KEYBOARD_INTERACTIVE
4209 AUTH_TYPE_PUBLICKEY,
4210 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4211 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4213 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4214 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4216 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4217 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4218 int kbd_inter_running;
4220 int num_prompts, curr_prompt, echo;
4225 void *publickey_blob;
4226 int publickey_bloblen;
4227 unsigned char request[5], *response, *p;
4231 char *pkblob, *alg, *commentp;
4232 int pklen, alglen, commentlen;
4233 int siglen, retlen, len;
4234 char *q, *agentreq, *ret;
4237 crState(do_ssh2_authconn_state);
4239 crBegin(ssh->do_ssh2_authconn_crstate);
4242 * Request userauth protocol, and await a response to it.
4244 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4245 ssh2_pkt_addstring(ssh, "ssh-userauth");
4247 crWaitUntilV(ispkt);
4248 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4249 bombout(("Server refused user authentication protocol"));
4254 * We repeat this whole loop, including the username prompt,
4255 * until we manage a successful authentication. If the user
4256 * types the wrong _password_, they can be sent back to the
4257 * beginning to try another username, if this is configured on.
4258 * (If they specify a username in the config, they are never
4259 * asked, even if they do give a wrong password.)
4261 * I think this best serves the needs of
4263 * - the people who have no configuration, no keys, and just
4264 * want to try repeated (username,password) pairs until they
4265 * type both correctly
4267 * - people who have keys and configuration but occasionally
4268 * need to fall back to passwords
4270 * - people with a key held in Pageant, who might not have
4271 * logged in to a particular machine before; so they want to
4272 * type a username, and then _either_ their key will be
4273 * accepted, _or_ they will type a password. If they mistype
4274 * the username they will want to be able to get back and
4277 s->username[0] = '\0';
4278 s->got_username = FALSE;
4283 if (s->got_username && !cfg.change_username) {
4285 * We got a username last time round this loop, and
4286 * with change_username turned off we don't try to get
4289 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4290 if (ssh_get_line && !ssh_getline_pw_only) {
4291 if (!ssh_get_line("login as: ",
4292 s->username, sizeof(s->username), FALSE)) {
4294 * get_line failed to get a username.
4297 logevent("No username provided. Abandoning session.");
4298 ssh->state = SSH_STATE_CLOSED;
4302 int ret; /* need not be saved across crReturn */
4303 c_write_str(ssh, "login as: ");
4305 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
4307 crWaitUntilV(!ispkt);
4308 ret = process_userpass_input(ssh, in, inlen);
4313 c_write_str(ssh, "\r\n");
4314 s->username[strcspn(s->username, "\n\r")] = '\0';
4317 strncpy(s->username, cfg.username, sizeof(s->username));
4318 s->username[sizeof(s->username)-1] = '\0';
4319 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4320 sprintf(stuff, "Using username \"%s\".\r\n", s->username);
4321 c_write_str(ssh, stuff);
4324 s->got_username = TRUE;
4327 * Send an authentication request using method "none": (a)
4328 * just in case it succeeds, and (b) so that we know what
4329 * authentication methods we can usefully try next.
4331 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4333 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4334 ssh2_pkt_addstring(ssh, s->username);
4335 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4336 ssh2_pkt_addstring(ssh, "none"); /* method */
4338 s->type = AUTH_TYPE_NONE;
4340 s->we_are_in = FALSE;
4342 s->tried_pubkey_config = FALSE;
4343 s->tried_agent = FALSE;
4344 s->tried_keyb_inter = FALSE;
4345 s->kbd_inter_running = FALSE;
4346 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4349 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4350 keytype = key_type(cfg.keyfile);
4351 if (keytype == SSH_KEYTYPE_SSH2) {
4353 ssh2_userkey_loadpub(cfg.keyfile, NULL,
4354 &s->publickey_bloblen);
4357 logeventf("Unable to use this key file (%s)",
4358 key_type_to_str(keytype));
4359 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4360 cfg.keyfile, key_type_to_str(keytype));
4361 c_write_str(ssh, msgbuf);
4362 s->publickey_blob = NULL;
4365 s->publickey_blob = NULL;
4369 * Wait for the result of the last authentication request.
4372 crWaitUntilV(ispkt);
4373 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4377 * Don't show the banner if we're operating in
4378 * non-verbose non-interactive mode. (It's probably
4379 * a script, which means nobody will read the
4380 * banner _anyway_, and moreover the printing of
4381 * the banner will screw up processing on the
4382 * output of (say) plink.)
4384 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4385 ssh2_pkt_getstring(ssh, &banner, &size);
4387 c_write_untrusted(ssh, banner, size);
4389 crWaitUntilV(ispkt);
4391 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4392 logevent("Access granted");
4393 s->we_are_in = TRUE;
4397 if (s->kbd_inter_running &&
4398 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4400 * This is either a further set-of-prompts packet
4401 * in keyboard-interactive authentication, or it's
4402 * the same one and we came back here with `gotit'
4403 * set. In the former case, we must reset the
4404 * curr_prompt variable.
4408 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4409 bombout(("Strange packet received during authentication: type %d",
4417 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4418 * we can look at the string in it and know what we can
4419 * helpfully try next.
4421 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4424 ssh2_pkt_getstring(ssh, &methods, &methlen);
4425 s->kbd_inter_running = FALSE;
4426 if (!ssh2_pkt_getbool(ssh)) {
4428 * We have received an unequivocal Access
4429 * Denied. This can translate to a variety of
4432 * - if we'd just tried "none" authentication,
4433 * it's not worth printing anything at all
4435 * - if we'd just tried a public key _offer_,
4436 * the message should be "Server refused our
4437 * key" (or no message at all if the key
4438 * came from Pageant)
4440 * - if we'd just tried anything else, the
4441 * message really should be "Access denied".
4443 * Additionally, if we'd just tried password
4444 * authentication, we should break out of this
4445 * whole loop so as to go back to the username
4448 if (s->type == AUTH_TYPE_NONE) {
4450 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4451 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4452 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4453 c_write_str(ssh, "Server refused our key\r\n");
4454 logevent("Server refused public key");
4455 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4456 /* server declined keyboard-interactive; ignore */
4458 c_write_str(ssh, "Access denied\r\n");
4459 logevent("Access denied");
4460 if (s->type == AUTH_TYPE_PASSWORD) {
4461 s->we_are_in = FALSE;
4466 c_write_str(ssh, "Further authentication required\r\n");
4467 logevent("Further authentication required");
4471 in_commasep_string("publickey", methods, methlen);
4473 in_commasep_string("password", methods, methlen);
4474 s->can_keyb_inter = cfg.try_ki_auth &&
4475 in_commasep_string("keyboard-interactive", methods, methlen);
4479 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4482 * Most password/passphrase prompts will be
4483 * non-echoing, so we set this to 0 by default.
4484 * Exception is that some keyboard-interactive prompts
4485 * can be echoing, in which case we'll set this to 1.
4489 if (!s->method && s->can_pubkey &&
4490 agent_exists() && !s->tried_agent) {
4492 * Attempt public-key authentication using Pageant.
4497 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4498 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4500 s->tried_agent = TRUE;
4502 logevent("Pageant is running. Requesting keys.");
4504 /* Request the keys held by the agent. */
4505 PUT_32BIT(s->request, 1);
4506 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4507 agent_query(s->request, 5, &r, &s->responselen);
4508 s->response = (unsigned char *) r;
4509 if (s->response && s->responselen >= 5 &&
4510 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4511 s->p = s->response + 5;
4512 s->nkeys = GET_32BIT(s->p);
4516 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
4519 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4524 sprintf(buf, "Trying Pageant key #%d", s->keyi);
4527 s->pklen = GET_32BIT(s->p);
4529 if (s->publickey_blob &&
4530 s->pklen == s->publickey_bloblen &&
4531 !memcmp(s->p, s->publickey_blob,
4532 s->publickey_bloblen)) {
4533 logevent("This key matches configured key file");
4534 s->tried_pubkey_config = 1;
4538 s->alglen = GET_32BIT(s->pkblob);
4539 s->alg = s->pkblob + 4;
4540 s->commentlen = GET_32BIT(s->p);
4543 s->p += s->commentlen;
4544 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4545 ssh2_pkt_addstring(ssh, s->username);
4546 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4547 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4548 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4549 ssh2_pkt_addstring_start(ssh);
4550 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4551 ssh2_pkt_addstring_start(ssh);
4552 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4555 crWaitUntilV(ispkt);
4556 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4557 logevent("Key refused");
4561 if (flags & FLAG_VERBOSE) {
4562 c_write_str(ssh, "Authenticating with "
4564 c_write(ssh, s->commentp, s->commentlen);
4565 c_write_str(ssh, "\" from agent\r\n");
4569 * Server is willing to accept the key.
4570 * Construct a SIGN_REQUEST.
4572 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4573 ssh2_pkt_addstring(ssh, s->username);
4574 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4575 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4576 ssh2_pkt_addbool(ssh, TRUE);
4577 ssh2_pkt_addstring_start(ssh);
4578 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4579 ssh2_pkt_addstring_start(ssh);
4580 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4582 s->siglen = ssh->pktout.length - 5 + 4 + 20;
4583 s->len = 1; /* message type */
4584 s->len += 4 + s->pklen; /* key blob */
4585 s->len += 4 + s->siglen; /* data to sign */
4586 s->len += 4; /* flags */
4587 s->agentreq = smalloc(4 + s->len);
4588 PUT_32BIT(s->agentreq, s->len);
4589 s->q = s->agentreq + 4;
4590 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4591 PUT_32BIT(s->q, s->pklen);
4593 memcpy(s->q, s->pkblob, s->pklen);
4595 PUT_32BIT(s->q, s->siglen);
4597 /* Now the data to be signed... */
4598 PUT_32BIT(s->q, 20);
4600 memcpy(s->q, ssh->v2_session_id, 20);
4602 memcpy(s->q, ssh->pktout.data + 5,
4603 ssh->pktout.length - 5);
4604 s->q += ssh->pktout.length - 5;
4605 /* And finally the (zero) flags word. */
4607 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4611 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4612 logevent("Sending Pageant's response");
4613 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4615 GET_32BIT(s->ret + 5));
4621 ("Pageant failed to answer challenge");
4631 if (!s->method && s->can_pubkey && s->publickey_blob
4632 && !s->tried_pubkey_config) {
4633 unsigned char *pub_blob;
4634 char *algorithm, *comment;
4637 s->tried_pubkey_config = TRUE;
4639 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4640 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4643 * Try the public key supplied in the configuration.
4645 * First, offer the public blob to see if the server is
4646 * willing to accept it.
4648 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4651 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4652 ssh2_pkt_addstring(ssh, s->username);
4653 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4654 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4655 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4656 ssh2_pkt_addstring(ssh, algorithm);
4657 ssh2_pkt_addstring_start(ssh);
4658 ssh2_pkt_addstring_data(ssh, pub_blob, pub_blob_len);
4660 logevent("Offered public key"); /* FIXME */
4662 crWaitUntilV(ispkt);
4663 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4665 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4666 continue; /* key refused; give up on it */
4669 logevent("Offer of public key accepted");
4671 * Actually attempt a serious authentication using
4674 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4675 sprintf(s->pwprompt,
4676 "Passphrase for key \"%.100s\": ",
4682 c_write_str(ssh, "Authenticating with public key \"");
4683 c_write_str(ssh, comment);
4684 c_write_str(ssh, "\"\r\n");
4685 s->method = AUTH_PUBLICKEY_FILE;
4689 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4690 s->method = AUTH_KEYBOARD_INTERACTIVE;
4691 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4692 s->tried_keyb_inter = TRUE;
4694 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4695 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4697 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4698 ssh2_pkt_addstring(ssh, s->username);
4699 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4700 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4701 ssh2_pkt_addstring(ssh, ""); /* lang */
4702 ssh2_pkt_addstring(ssh, "");
4705 crWaitUntilV(ispkt);
4706 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4707 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4709 logevent("Keyboard-interactive authentication refused");
4710 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4714 s->kbd_inter_running = TRUE;
4718 if (s->kbd_inter_running) {
4719 s->method = AUTH_KEYBOARD_INTERACTIVE;
4720 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4721 s->tried_keyb_inter = TRUE;
4723 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4724 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4726 if (s->curr_prompt == 0) {
4728 * We've got a fresh USERAUTH_INFO_REQUEST.
4729 * Display header data, and start going through
4732 char *name, *inst, *lang;
4733 int name_len, inst_len, lang_len;
4735 ssh2_pkt_getstring(ssh, &name, &name_len);
4736 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4737 ssh2_pkt_getstring(ssh, &lang, &lang_len);
4739 c_write_untrusted(ssh, name, name_len);
4740 c_write_str(ssh, "\r\n");
4743 c_write_untrusted(ssh, inst, inst_len);
4744 c_write_str(ssh, "\r\n");
4746 s->num_prompts = ssh2_pkt_getuint32(ssh);
4750 * If there are prompts remaining in the packet,
4751 * display one and get a response.
4753 if (s->curr_prompt < s->num_prompts) {
4757 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
4758 if (prompt_len > 0) {
4759 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4760 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4761 prompt_len : sizeof(s->pwprompt)-1] = '\0';
4764 "<server failed to send prompt>: ");
4766 s->echo = ssh2_pkt_getbool(ssh);
4772 if (!s->method && s->can_passwd) {
4773 s->method = AUTH_PASSWORD;
4774 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4775 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4776 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4783 if (!ssh_get_line(s->pwprompt, s->password,
4784 sizeof(s->password), TRUE)) {
4786 * get_line failed to get a password (for
4787 * example because one was supplied on the
4788 * command line which has already failed to
4791 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4792 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4793 ssh2_pkt_addstring(ssh, "No more passwords available"
4795 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4797 logevent("Unable to authenticate");
4798 connection_fatal("Unable to authenticate");
4799 ssh->state = SSH_STATE_CLOSED;
4803 int ret; /* need not be saved across crReturn */
4804 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4807 setup_userpass_input(ssh, s->password,
4808 sizeof(s->password), s->echo);
4810 crWaitUntilV(!ispkt);
4811 ret = process_userpass_input(ssh, in, inlen);
4815 c_write_str(ssh, "\r\n");
4819 if (s->method == AUTH_PUBLICKEY_FILE) {
4821 * We have our passphrase. Now try the actual authentication.
4823 struct ssh2_userkey *key;
4825 key = ssh2_load_userkey(cfg.keyfile, s->password);
4826 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4827 if (key == SSH2_WRONG_PASSPHRASE) {
4828 c_write_str(ssh, "Wrong passphrase\r\n");
4829 s->tried_pubkey_config = FALSE;
4831 c_write_str(ssh, "Unable to load private key\r\n");
4832 s->tried_pubkey_config = TRUE;
4834 /* Send a spurious AUTH_NONE to return to the top. */
4835 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4836 ssh2_pkt_addstring(ssh, s->username);
4837 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4838 ssh2_pkt_addstring(ssh, "none"); /* method */
4840 s->type = AUTH_TYPE_NONE;
4842 unsigned char *pkblob, *sigblob, *sigdata;
4843 int pkblob_len, sigblob_len, sigdata_len;
4846 * We have loaded the private key and the server
4847 * has announced that it's willing to accept it.
4848 * Hallelujah. Generate a signature and send it.
4850 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4851 ssh2_pkt_addstring(ssh, s->username);
4852 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4853 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4854 ssh2_pkt_addbool(ssh, TRUE);
4855 ssh2_pkt_addstring(ssh, key->alg->name);
4856 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4857 ssh2_pkt_addstring_start(ssh);
4858 ssh2_pkt_addstring_data(ssh, pkblob, pkblob_len);
4861 * The data to be signed is:
4865 * followed by everything so far placed in the
4868 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
4869 sigdata = smalloc(sigdata_len);
4870 PUT_32BIT(sigdata, 20);
4871 memcpy(sigdata + 4, ssh->v2_session_id, 20);
4872 memcpy(sigdata + 24, ssh->pktout.data + 5,
4873 ssh->pktout.length - 5);
4874 sigblob = key->alg->sign(key->data, sigdata,
4875 sigdata_len, &sigblob_len);
4876 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
4877 sigblob, sigblob_len);
4883 s->type = AUTH_TYPE_PUBLICKEY;
4885 } else if (s->method == AUTH_PASSWORD) {
4887 * We send the password packet lumped tightly together with
4888 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4889 * string long enough to make the total length of the two
4890 * packets constant. This should ensure that a passive
4891 * listener doing traffic analyis can't work out the length
4894 * For this to work, we need an assumption about the
4895 * maximum length of the password packet. I think 256 is
4896 * pretty conservative. Anyone using a password longer than
4897 * that probably doesn't have much to worry about from
4898 * people who find out how long their password is!
4900 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4901 ssh2_pkt_addstring(ssh, s->username);
4902 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4903 ssh2_pkt_addstring(ssh, "password");
4904 ssh2_pkt_addbool(ssh, FALSE);
4905 ssh2_pkt_addstring(ssh, s->password);
4906 ssh2_pkt_defer(ssh);
4908 * We'll include a string that's an exact multiple of the
4909 * cipher block size. If the cipher is NULL for some
4910 * reason, we don't do this trick at all because we gain
4913 if (ssh->cscipher) {
4916 stringlen = (256 - ssh->deferred_len);
4917 stringlen += ssh->cscipher->blksize - 1;
4918 stringlen -= (stringlen % ssh->cscipher->blksize);
4921 * Temporarily disable actual compression,
4922 * so we can guarantee to get this string
4923 * exactly the length we want it. The
4924 * compression-disabling routine should
4925 * return an integer indicating how many
4926 * bytes we should adjust our string length
4929 stringlen -= ssh->cscomp->disable_compression();
4931 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
4932 ssh2_pkt_addstring_start(ssh);
4933 for (i = 0; i < stringlen; i++) {
4934 char c = (char) random_byte();
4935 ssh2_pkt_addstring_data(ssh, &c, 1);
4937 ssh2_pkt_defer(ssh);
4939 ssh_pkt_defersend(ssh);
4940 logevent("Sent password");
4941 s->type = AUTH_TYPE_PASSWORD;
4942 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
4943 if (s->curr_prompt == 0) {
4944 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
4945 ssh2_pkt_adduint32(ssh, s->num_prompts);
4947 if (s->need_pw) { /* only add pw if we just got one! */
4948 ssh2_pkt_addstring(ssh, s->password);
4949 memset(s->password, 0, sizeof(s->password));
4952 if (s->curr_prompt >= s->num_prompts) {
4956 * If there are prompts remaining, we set
4957 * `gotit' so that we won't attempt to get
4958 * another packet. Then we go back round the
4959 * loop and will end up retrieving another
4960 * prompt out of the existing packet. Funky or
4965 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4967 c_write_str(ssh, "No supported authentication methods"
4968 " left to try!\r\n");
4969 logevent("No supported authentications offered."
4971 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4972 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
4973 ssh2_pkt_addstring(ssh, "No supported authentication"
4974 " methods available");
4975 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4977 ssh->state = SSH_STATE_CLOSED;
4981 } while (!s->we_are_in);
4984 * Now we're authenticated for the connection protocol. The
4985 * connection protocol will automatically have started at this
4986 * point; there's no need to send SERVICE_REQUEST.
4990 * So now create a channel with a session in it.
4992 ssh->channels = newtree234(ssh_channelcmp);
4993 ssh->mainchan = smalloc(sizeof(struct ssh_channel));
4994 ssh->mainchan->ssh = ssh;
4995 ssh->mainchan->localid = alloc_channel_id(ssh);
4996 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
4997 ssh2_pkt_addstring(ssh, "session");
4998 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
4999 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
5000 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
5001 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5003 crWaitUntilV(ispkt);
5004 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5005 bombout(("Server refused to open a session"));
5007 /* FIXME: error data comes back in FAILURE packet */
5009 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
5010 bombout(("Server's channel confirmation cited wrong channel"));
5013 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
5014 ssh->mainchan->type = CHAN_MAINSESSION;
5015 ssh->mainchan->closes = 0;
5016 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5017 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5018 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5019 add234(ssh->channels, ssh->mainchan);
5020 logevent("Opened channel for session");
5023 * Potentially enable X11 forwarding.
5025 if (cfg.x11_forward) {
5026 char proto[20], data[64];
5027 logevent("Requesting X11 forwarding");
5028 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
5029 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5030 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5031 ssh2_pkt_addstring(ssh, "x11-req");
5032 ssh2_pkt_addbool(ssh, 1); /* want reply */
5033 ssh2_pkt_addbool(ssh, 0); /* many connections */
5034 ssh2_pkt_addstring(ssh, proto);
5035 ssh2_pkt_addstring(ssh, data);
5036 ssh2_pkt_adduint32(ssh, 0); /* screen number */
5040 crWaitUntilV(ispkt);
5041 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5042 unsigned i = ssh2_pkt_getuint32(ssh);
5043 struct ssh_channel *c;
5044 c = find234(ssh->channels, &i, ssh_channelfind);
5046 continue; /* nonexistent channel */
5047 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5049 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5051 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5052 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5053 bombout(("Unexpected response to X11 forwarding request:"
5054 " packet type %d", ssh->pktin.type));
5057 logevent("X11 forwarding refused");
5059 logevent("X11 forwarding enabled");
5060 ssh->X11_fwd_enabled = TRUE;
5065 * Enable port forwardings.
5070 int sport,dport,sserv,dserv;
5071 char sports[256], dports[256], host[256];
5075 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5076 /* Add port forwardings. */
5077 ssh->portfwd_strptr = cfg.portfwd;
5078 while (*ssh->portfwd_strptr) {
5079 type = *ssh->portfwd_strptr++;
5081 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
5082 sports[n++] = *ssh->portfwd_strptr++;
5084 if (*ssh->portfwd_strptr == '\t')
5085 ssh->portfwd_strptr++;
5087 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
5088 host[n++] = *ssh->portfwd_strptr++;
5090 if (*ssh->portfwd_strptr == ':')
5091 ssh->portfwd_strptr++;
5093 while (*ssh->portfwd_strptr)
5094 dports[n++] = *ssh->portfwd_strptr++;
5096 ssh->portfwd_strptr++;
5097 dport = atoi(dports);
5101 se = getservbyname(dports, NULL);
5103 dport = ntohs(se->s_port);
5106 "Service lookup failed for destination port \"%s\"",
5111 sport = atoi(sports);
5115 se = getservbyname(sports, NULL);
5117 sport = ntohs(se->s_port);
5120 "Service lookup failed for source port \"%s\"",
5125 if (sport && dport) {
5127 pfd_addforward(host, dport, sport);
5128 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
5129 " %s:%.*s%.*s%d%.*s",
5130 sserv ? strlen(sports) : 0, sports,
5131 sserv, "(", sport, sserv, ")",
5133 dserv ? strlen(dports) : 0, dports,
5134 dserv, "(", dport, dserv, ")");
5137 struct ssh_rportfwd *pf;
5138 pf = smalloc(sizeof(*pf));
5139 strcpy(pf->dhost, host);
5142 if (add234(ssh->rportfwds, pf) != pf) {
5144 "Duplicate remote port forwarding to %s:%d",
5149 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5150 " forward to %s:%.*s%.*s%d%.*s",
5151 sserv ? strlen(sports) : 0, sports,
5152 sserv, "(", sport, sserv, ")",
5154 dserv ? strlen(dports) : 0, dports,
5155 dserv, "(", dport, dserv, ")");
5157 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5158 ssh2_pkt_addstring(ssh, "tcpip-forward");
5159 ssh2_pkt_addbool(ssh, 1);/* want reply */
5160 if (cfg.rport_acceptall)
5161 ssh2_pkt_addstring(ssh, "0.0.0.0");
5163 ssh2_pkt_addstring(ssh, "127.0.0.1");
5164 ssh2_pkt_adduint32(ssh, sport);
5168 crWaitUntilV(ispkt);
5169 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5170 unsigned i = ssh2_pkt_getuint32(ssh);
5171 struct ssh_channel *c;
5172 c = find234(ssh->channels, &i, ssh_channelfind);
5174 continue;/* nonexistent channel */
5175 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5177 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5179 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5180 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5181 bombout(("Unexpected response to port "
5182 "forwarding request: packet type %d",
5186 logevent("Server refused this port forwarding");
5188 logevent("Remote port forwarding enabled");
5197 * Potentially enable agent forwarding.
5199 if (cfg.agentfwd && agent_exists()) {
5200 logevent("Requesting OpenSSH-style agent forwarding");
5201 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5202 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5203 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5204 ssh2_pkt_addbool(ssh, 1); /* want reply */
5208 crWaitUntilV(ispkt);
5209 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5210 unsigned i = ssh2_pkt_getuint32(ssh);
5211 struct ssh_channel *c;
5212 c = find234(ssh->channels, &i, ssh_channelfind);
5214 continue; /* nonexistent channel */
5215 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5217 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5219 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5220 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5221 bombout(("Unexpected response to agent forwarding request:"
5222 " packet type %d", ssh->pktin.type));
5225 logevent("Agent forwarding refused");
5227 logevent("Agent forwarding enabled");
5228 ssh->agentfwd_enabled = TRUE;
5233 * Now allocate a pty for the session.
5236 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5237 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5238 ssh2_pkt_addstring(ssh, "pty-req");
5239 ssh2_pkt_addbool(ssh, 1); /* want reply */
5240 ssh2_pkt_addstring(ssh, cfg.termtype);
5241 ssh2_pkt_adduint32(ssh, ssh->term_width);
5242 ssh2_pkt_adduint32(ssh, ssh->term_height);
5243 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5244 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5245 ssh2_pkt_addstring_start(ssh);
5246 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5248 ssh->state = SSH_STATE_INTERMED;
5251 crWaitUntilV(ispkt);
5252 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5253 unsigned i = ssh2_pkt_getuint32(ssh);
5254 struct ssh_channel *c;
5255 c = find234(ssh->channels, &i, ssh_channelfind);
5257 continue; /* nonexistent channel */
5258 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5260 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5262 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5263 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5264 bombout(("Unexpected response to pty request:"
5265 " packet type %d", ssh->pktin.type));
5268 c_write_str(ssh, "Server refused to allocate pty\r\n");
5269 ssh->editing = ssh->echoing = 1;
5271 logevent("Allocated pty");
5274 ssh->editing = ssh->echoing = 1;
5278 * Start a shell or a remote command. We may have to attempt
5279 * this twice if the config data has provided a second choice
5286 if (ssh->fallback_cmd) {
5287 subsys = cfg.ssh_subsys2;
5288 cmd = cfg.remote_cmd_ptr2;
5290 subsys = cfg.ssh_subsys;
5291 cmd = cfg.remote_cmd_ptr;
5294 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5295 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5297 ssh2_pkt_addstring(ssh, "subsystem");
5298 ssh2_pkt_addbool(ssh, 1); /* want reply */
5299 ssh2_pkt_addstring(ssh, cmd);
5301 ssh2_pkt_addstring(ssh, "exec");
5302 ssh2_pkt_addbool(ssh, 1); /* want reply */
5303 ssh2_pkt_addstring(ssh, cmd);
5305 ssh2_pkt_addstring(ssh, "shell");
5306 ssh2_pkt_addbool(ssh, 1); /* want reply */
5310 crWaitUntilV(ispkt);
5311 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5312 unsigned i = ssh2_pkt_getuint32(ssh);
5313 struct ssh_channel *c;
5314 c = find234(ssh->channels, &i, ssh_channelfind);
5316 continue; /* nonexistent channel */
5317 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5319 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5320 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5321 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5322 bombout(("Unexpected response to shell/command request:"
5323 " packet type %d", ssh->pktin.type));
5327 * We failed to start the command. If this is the
5328 * fallback command, we really are finished; if it's
5329 * not, and if the fallback command exists, try falling
5330 * back to it before complaining.
5332 if (!ssh->fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5333 logevent("Primary command failed; attempting fallback");
5334 ssh->fallback_cmd = TRUE;
5337 bombout(("Server refused to start a shell/command"));
5340 logevent("Started a shell/command");
5345 ssh->state = SSH_STATE_SESSION;
5346 if (ssh->size_needed)
5347 ssh_size(ssh, ssh->term_width, ssh->term_height);
5348 if (ssh->eof_needed)
5349 ssh_special(ssh, TS_EOF);
5354 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
5358 s->try_send = FALSE;
5360 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5361 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5364 unsigned i = ssh2_pkt_getuint32(ssh);
5365 struct ssh_channel *c;
5366 c = find234(ssh->channels, &i, ssh_channelfind);
5368 continue; /* nonexistent channel */
5369 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5370 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
5371 continue; /* extended but not stderr */
5372 ssh2_pkt_getstring(ssh, &data, &length);
5375 c->v.v2.locwindow -= length;
5377 case CHAN_MAINSESSION:
5379 from_backend(ssh->frontend, ssh->pktin.type ==
5380 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5384 bufsize = x11_send(c->u.x11.s, data, length);
5387 bufsize = pfd_send(c->u.pfd.s, data, length);
5390 while (length > 0) {
5391 if (c->u.a.lensofar < 4) {
5392 int l = min(4 - c->u.a.lensofar, length);
5393 memcpy(c->u.a.msglen + c->u.a.lensofar,
5397 c->u.a.lensofar += l;
5399 if (c->u.a.lensofar == 4) {
5401 4 + GET_32BIT(c->u.a.msglen);
5402 c->u.a.message = smalloc(c->u.a.totallen);
5403 memcpy(c->u.a.message, c->u.a.msglen, 4);
5405 if (c->u.a.lensofar >= 4 && length > 0) {
5407 min(c->u.a.totallen - c->u.a.lensofar,
5409 memcpy(c->u.a.message + c->u.a.lensofar,
5413 c->u.a.lensofar += l;
5415 if (c->u.a.lensofar == c->u.a.totallen) {
5416 void *reply, *sentreply;
5418 agent_query(c->u.a.message,
5419 c->u.a.totallen, &reply,
5424 /* Fake SSH_AGENT_FAILURE. */
5425 sentreply = "\0\0\0\1\5";
5428 ssh2_add_channel_data(c, sentreply, replylen);
5432 sfree(c->u.a.message);
5433 c->u.a.lensofar = 0;
5440 * If we are not buffering too much data,
5441 * enlarge the window again at the remote side.
5443 if (bufsize < OUR_V2_WINSIZE)
5444 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5446 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5447 unsigned i = ssh2_pkt_getuint32(ssh);
5448 struct ssh_channel *c;
5450 c = find234(ssh->channels, &i, ssh_channelfind);
5452 continue; /* nonexistent channel */
5454 if (c->type == CHAN_X11) {
5456 * Remote EOF on an X11 channel means we should
5457 * wrap up and close the channel ourselves.
5459 x11_close(c->u.x11.s);
5461 } else if (c->type == CHAN_AGENT) {
5463 } else if (c->type == CHAN_SOCKDATA) {
5464 pfd_close(c->u.pfd.s);
5467 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5468 unsigned i = ssh2_pkt_getuint32(ssh);
5469 struct ssh_channel *c;
5471 c = find234(ssh->channels, &i, ssh_channelfind);
5472 if (!c || ((int)c->remoteid) == -1) {
5473 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5474 c ? "half-open" : "nonexistent", i));
5476 /* Do pre-close processing on the channel. */
5478 case CHAN_MAINSESSION:
5479 break; /* nothing to see here, move along */
5481 if (c->u.x11.s != NULL)
5482 x11_close(c->u.x11.s);
5489 if (c->u.pfd.s != NULL)
5490 pfd_close(c->u.pfd.s);
5494 if (c->closes == 0) {
5495 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5496 ssh2_pkt_adduint32(ssh, c->remoteid);
5499 del234(ssh->channels, c);
5500 bufchain_clear(&c->v.v2.outbuffer);
5504 * See if that was the last channel left open.
5506 if (count234(ssh->channels) == 0) {
5509 * We used to send SSH_MSG_DISCONNECT here,
5510 * because I'd believed that _every_ conforming
5511 * SSH2 connection had to end with a disconnect
5512 * being sent by at least one side; apparently
5513 * I was wrong and it's perfectly OK to
5514 * unceremoniously slam the connection shut
5515 * when you're done, and indeed OpenSSH feels
5516 * this is more polite than sending a
5517 * DISCONNECT. So now we don't.
5519 logevent("All channels closed. Disconnecting");
5520 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5521 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5522 ssh2_pkt_addstring(ssh, "All open channels closed");
5523 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5526 ssh->state = SSH_STATE_CLOSED;
5529 continue; /* remote sends close; ignore (FIXME) */
5530 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5531 unsigned i = ssh2_pkt_getuint32(ssh);
5532 struct ssh_channel *c;
5533 c = find234(ssh->channels, &i, ssh_channelfind);
5535 continue; /* nonexistent channel */
5536 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5538 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5539 unsigned i = ssh2_pkt_getuint32(ssh);
5540 struct ssh_channel *c;
5541 c = find234(ssh->channels, &i, ssh_channelfind);
5543 continue; /* nonexistent channel */
5544 if (c->type != CHAN_SOCKDATA_DORMANT)
5545 continue; /* dunno why they're confirming this */
5546 c->remoteid = ssh2_pkt_getuint32(ssh);
5547 c->type = CHAN_SOCKDATA;
5548 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5549 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5551 pfd_confirm(c->u.pfd.s);
5554 * We have a pending close on this channel,
5555 * which we decided on before the server acked
5556 * the channel open. So now we know the
5557 * remoteid, we can close it again.
5559 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5560 ssh2_pkt_adduint32(ssh, c->remoteid);
5563 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5564 unsigned i = ssh2_pkt_getuint32(ssh);
5565 struct ssh_channel *c;
5566 c = find234(ssh->channels, &i, ssh_channelfind);
5568 continue; /* nonexistent channel */
5569 if (c->type != CHAN_SOCKDATA_DORMANT)
5570 continue; /* dunno why they're failing this */
5572 logevent("Forwarded connection refused by server");
5574 pfd_close(c->u.pfd.s);
5576 del234(ssh->channels, c);
5578 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5581 int typelen, want_reply;
5582 struct ssh_channel *c;
5584 localid = ssh2_pkt_getuint32(ssh);
5585 ssh2_pkt_getstring(ssh, &type, &typelen);
5586 want_reply = ssh2_pkt_getbool(ssh);
5589 * First, check that the channel exists. Otherwise,
5590 * we can instantly disconnect with a rude message.
5592 c = find234(ssh->channels, &localid, ssh_channelfind);
5595 sprintf(buf, "Received channel request for nonexistent"
5596 " channel %d", localid);
5598 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5599 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5600 ssh2_pkt_addstring(ssh, buf);
5601 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5603 connection_fatal("%s", buf);
5604 ssh->state = SSH_STATE_CLOSED;
5609 * Having got the channel number, we now look at
5610 * the request type string to see if it's something
5613 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5614 c == ssh->mainchan) {
5615 /* We recognise "exit-status" on the primary channel. */
5617 ssh->exitcode = ssh2_pkt_getuint32(ssh);
5618 sprintf(buf, "Server sent command exit status %d",
5622 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5623 ssh2_pkt_adduint32(ssh, c->remoteid);
5628 * This is a channel request we don't know
5629 * about, so we now either ignore the request
5630 * or respond with CHANNEL_FAILURE, depending
5634 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5635 ssh2_pkt_adduint32(ssh, c->remoteid);
5639 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5641 int typelen, want_reply;
5643 ssh2_pkt_getstring(ssh, &type, &typelen);
5644 want_reply = ssh2_pkt_getbool(ssh);
5647 * We currently don't support any global requests
5648 * at all, so we either ignore the request or
5649 * respond with REQUEST_FAILURE, depending on
5653 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5656 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5660 struct ssh_channel *c;
5661 unsigned remid, winsize, pktsize;
5662 ssh2_pkt_getstring(ssh, &type, &typelen);
5663 c = smalloc(sizeof(struct ssh_channel));
5666 remid = ssh2_pkt_getuint32(ssh);
5667 winsize = ssh2_pkt_getuint32(ssh);
5668 pktsize = ssh2_pkt_getuint32(ssh);
5670 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5671 if (!ssh->X11_fwd_enabled)
5672 error = "X11 forwarding is not enabled";
5673 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5675 error = "Unable to open an X11 connection";
5679 } else if (typelen == 15 &&
5680 !memcmp(type, "forwarded-tcpip", 15)) {
5681 struct ssh_rportfwd pf, *realpf;
5684 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5685 pf.sport = ssh2_pkt_getuint32(ssh);
5686 realpf = find234(ssh->rportfwds, &pf, NULL);
5687 if (realpf == NULL) {
5688 error = "Remote port is not recognised";
5690 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5693 sprintf(buf, "Received remote port open request for %s:%d",
5694 realpf->dhost, realpf->dport);
5697 sprintf(buf, "Port open failed: %s", e);
5699 error = "Port open failed";
5701 logevent("Forwarded port opened successfully");
5702 c->type = CHAN_SOCKDATA;
5705 } else if (typelen == 22 &&
5706 !memcmp(type, "auth-agent@openssh.com", 3)) {
5707 if (!ssh->agentfwd_enabled)
5708 error = "Agent forwarding is not enabled";
5710 c->type = CHAN_AGENT; /* identify channel type */
5711 c->u.a.lensofar = 0;
5714 error = "Unsupported channel type requested";
5717 c->remoteid = remid;
5719 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5720 ssh2_pkt_adduint32(ssh, c->remoteid);
5721 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5722 ssh2_pkt_addstring(ssh, error);
5723 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5727 c->localid = alloc_channel_id(ssh);
5729 c->v.v2.locwindow = OUR_V2_WINSIZE;
5730 c->v.v2.remwindow = winsize;
5731 c->v.v2.remmaxpkt = pktsize;
5732 bufchain_init(&c->v.v2.outbuffer);
5733 add234(ssh->channels, c);
5734 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5735 ssh2_pkt_adduint32(ssh, c->remoteid);
5736 ssh2_pkt_adduint32(ssh, c->localid);
5737 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5738 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5742 bombout(("Strange packet received: type %d", ssh->pktin.type));
5747 * We have spare data. Add it to the channel buffer.
5749 ssh2_add_channel_data(ssh->mainchan, in, inlen);
5754 struct ssh_channel *c;
5756 * Try to send data on all channels if we can.
5758 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5759 int bufsize = ssh2_try_send(c);
5762 case CHAN_MAINSESSION:
5763 /* stdin need not receive an unthrottle
5764 * notification since it will be polled */
5767 x11_unthrottle(c->u.x11.s);
5770 /* agent sockets are request/response and need no
5771 * buffer management */
5774 pfd_unthrottle(c->u.pfd.s);
5786 * Handle the top-level SSH2 protocol.
5788 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
5790 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
5792 do_ssh2_authconn(ssh, in, inlen, ispkt);
5796 * Called to set up the connection.
5798 * Returns an error message, or NULL on success.
5800 static char *ssh_init(void *frontend_handle, void **backend_handle,
5801 char *host, int port, char **realhost, int nodelay)
5806 ssh = smalloc(sizeof(*ssh));
5809 ssh->v1_cipher_ctx = NULL;
5810 ssh->crcda_ctx = NULL;
5811 ssh->cscipher = NULL;
5812 ssh->cs_cipher_ctx = NULL;
5813 ssh->sccipher = NULL;
5814 ssh->sc_cipher_ctx = NULL;
5816 ssh->sc_mac_ctx = NULL;
5818 ssh->sc_mac_ctx = NULL;
5822 ssh->hostkey = NULL;
5824 ssh->state = SSH_STATE_PREPACKET;
5825 ssh->size_needed = FALSE;
5826 ssh->eof_needed = FALSE;
5828 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5829 ssh->pktin = ssh->pktout = empty;
5831 ssh->deferred_send_data = NULL;
5832 ssh->deferred_len = 0;
5833 ssh->deferred_size = 0;
5834 ssh->fallback_cmd = 0;
5836 ssh->v2_outgoing_sequence = 0;
5837 ssh->ssh1_rdpkt_crstate = 0;
5838 ssh->ssh2_rdpkt_crstate = 0;
5839 ssh->do_ssh_init_crstate = 0;
5840 ssh->ssh_gotdata_crstate = 0;
5841 ssh->ssh1_protocol_crstate = 0;
5842 ssh->do_ssh1_login_crstate = 0;
5843 ssh->do_ssh2_transport_crstate = 0;
5844 ssh->do_ssh2_authconn_crstate = 0;
5845 ssh->do_ssh_init_state = NULL;
5846 ssh->do_ssh1_login_state = NULL;
5847 ssh->do_ssh2_transport_state = NULL;
5848 ssh->do_ssh2_authconn_state = NULL;
5850 *backend_handle = ssh;
5853 if (crypto_startup() == 0)
5854 return "Microsoft high encryption pack not installed!";
5857 ssh->frontend = frontend_handle;
5858 ssh->term_width = cfg.width;
5859 ssh->term_height = cfg.height;
5864 ssh->v1_throttle_count = 0;
5865 ssh->overall_bufsize = 0;
5866 ssh->fallback_cmd = 0;
5868 p = connect_to_host(ssh, host, port, realhost, nodelay);
5876 * Called to send data down the Telnet connection.
5878 static int ssh_send(void *handle, char *buf, int len)
5880 Ssh ssh = (Ssh) handle;
5882 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5885 ssh->protocol(ssh, buf, len, 0);
5887 return ssh_sendbuffer(ssh);
5891 * Called to query the current amount of buffered stdin data.
5893 static int ssh_sendbuffer(void *handle)
5895 Ssh ssh = (Ssh) handle;
5898 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5902 * If the SSH socket itself has backed up, add the total backup
5903 * size on that to any individual buffer on the stdin channel.
5906 if (ssh->throttled_all)
5907 override_value = ssh->overall_bufsize;
5909 if (ssh->version == 1) {
5910 return override_value;
5911 } else if (ssh->version == 2) {
5912 if (!ssh->mainchan || ssh->mainchan->closes > 0)
5913 return override_value;
5915 return (override_value +
5916 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5923 * Called to set the size of the window from SSH's POV.
5925 static void ssh_size(void *handle, int width, int height)
5927 Ssh ssh = (Ssh) handle;
5929 ssh->term_width = width;
5930 ssh->term_height = height;
5932 switch (ssh->state) {
5933 case SSH_STATE_BEFORE_SIZE:
5934 case SSH_STATE_PREPACKET:
5935 case SSH_STATE_CLOSED:
5936 break; /* do nothing */
5937 case SSH_STATE_INTERMED:
5938 ssh->size_needed = TRUE; /* buffer for later */
5940 case SSH_STATE_SESSION:
5944 if (ssh->version == 1) {
5945 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
5946 PKT_INT, ssh->term_height,
5947 PKT_INT, ssh->term_width,
5948 PKT_INT, 0, PKT_INT, 0, PKT_END);
5950 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5951 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5952 ssh2_pkt_addstring(ssh, "window-change");
5953 ssh2_pkt_addbool(ssh, 0);
5954 ssh2_pkt_adduint32(ssh, ssh->term_width);
5955 ssh2_pkt_adduint32(ssh, ssh->term_height);
5956 ssh2_pkt_adduint32(ssh, 0);
5957 ssh2_pkt_adduint32(ssh, 0);
5966 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5967 * can send an EOF and collect resulting output (e.g. `plink
5970 static void ssh_special(void *handle, Telnet_Special code)
5972 Ssh ssh = (Ssh) handle;
5974 if (code == TS_EOF) {
5975 if (ssh->state != SSH_STATE_SESSION) {
5977 * Buffer the EOF in case we are pre-SESSION, so we can
5978 * send it as soon as we reach SESSION.
5981 ssh->eof_needed = TRUE;
5984 if (ssh->version == 1) {
5985 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
5987 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
5988 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5991 logevent("Sent EOF message");
5992 } else if (code == TS_PING) {
5993 if (ssh->state == SSH_STATE_CLOSED
5994 || ssh->state == SSH_STATE_PREPACKET) return;
5995 if (ssh->version == 1) {
5996 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
5997 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5999 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
6000 ssh2_pkt_addstring_start(ssh);
6008 void *new_sock_channel(void *handle, Socket s)
6010 Ssh ssh = (Ssh) handle;
6011 struct ssh_channel *c;
6012 c = smalloc(sizeof(struct ssh_channel));
6016 c->remoteid = -1; /* to be set when open confirmed */
6017 c->localid = alloc_channel_id(ssh);
6019 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
6021 bufchain_init(&c->v.v2.outbuffer);
6022 add234(ssh->channels, c);
6028 * This is called when stdout/stderr (the entity to which
6029 * from_backend sends data) manages to clear some backlog.
6031 void ssh_unthrottle(void *handle, int bufsize)
6033 Ssh ssh = (Ssh) handle;
6034 if (ssh->version == 1) {
6035 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6036 ssh->v1_stdout_throttling = 0;
6037 ssh1_throttle(ssh, -1);
6040 if (ssh->mainchan && ssh->mainchan->closes == 0)
6041 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
6045 void ssh_send_port_open(void *handle, void *channel, char *hostname,
6046 int port, char *org)
6048 Ssh ssh = (Ssh) handle;
6049 struct ssh_channel *c = (struct ssh_channel *)channel;
6052 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
6055 if (ssh->version == 1) {
6056 send_packet(ssh, SSH1_MSG_PORT_OPEN,
6057 PKT_INT, c->localid,
6060 //PKT_STR, <org:orgport>,
6063 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6064 ssh2_pkt_addstring(ssh, "direct-tcpip");
6065 ssh2_pkt_adduint32(ssh, c->localid);
6066 c->v.v2.locwindow = OUR_V2_WINSIZE;
6067 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6068 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6069 ssh2_pkt_addstring(ssh, hostname);
6070 ssh2_pkt_adduint32(ssh, port);
6072 * We make up values for the originator data; partly it's
6073 * too much hassle to keep track, and partly I'm not
6074 * convinced the server should be told details like that
6075 * about my local network configuration.
6077 ssh2_pkt_addstring(ssh, "client-side-connection");
6078 ssh2_pkt_adduint32(ssh, 0);
6084 static Socket ssh_socket(void *handle)
6086 Ssh ssh = (Ssh) handle;
6090 static int ssh_sendok(void *handle)
6092 Ssh ssh = (Ssh) handle;
6093 return ssh->send_ok;
6096 static int ssh_ldisc(void *handle, int option)
6098 Ssh ssh = (Ssh) handle;
6099 if (option == LD_ECHO)
6100 return ssh->echoing;
6101 if (option == LD_EDIT)
6102 return ssh->editing;
6106 static int ssh_return_exitcode(void *handle)
6108 Ssh ssh = (Ssh) handle;
6109 return ssh->exitcode;
6113 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6114 * that fails. This variable is the means by which scp.c can reach
6115 * into the SSH code and find out which one it got.
6117 extern int ssh_fallback_cmd(void *handle)
6119 Ssh ssh = (Ssh) handle;
6120 return ssh->fallback_cmd;
6123 Backend ssh_backend = {
6130 ssh_return_exitcode,