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 (s ? sk_close(s), 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
187 static int ssh_pkt_ctx = 0;
189 #define translate(x) if (type == x) return #x
190 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
191 char *ssh1_pkt_type(int type)
193 translate(SSH1_MSG_DISCONNECT);
194 translate(SSH1_SMSG_PUBLIC_KEY);
195 translate(SSH1_CMSG_SESSION_KEY);
196 translate(SSH1_CMSG_USER);
197 translate(SSH1_CMSG_AUTH_RSA);
198 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
199 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
200 translate(SSH1_CMSG_AUTH_PASSWORD);
201 translate(SSH1_CMSG_REQUEST_PTY);
202 translate(SSH1_CMSG_WINDOW_SIZE);
203 translate(SSH1_CMSG_EXEC_SHELL);
204 translate(SSH1_CMSG_EXEC_CMD);
205 translate(SSH1_SMSG_SUCCESS);
206 translate(SSH1_SMSG_FAILURE);
207 translate(SSH1_CMSG_STDIN_DATA);
208 translate(SSH1_SMSG_STDOUT_DATA);
209 translate(SSH1_SMSG_STDERR_DATA);
210 translate(SSH1_CMSG_EOF);
211 translate(SSH1_SMSG_EXIT_STATUS);
212 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
213 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
214 translate(SSH1_MSG_CHANNEL_DATA);
215 translate(SSH1_MSG_CHANNEL_CLOSE);
216 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
217 translate(SSH1_SMSG_X11_OPEN);
218 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
219 translate(SSH1_MSG_PORT_OPEN);
220 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
221 translate(SSH1_SMSG_AGENT_OPEN);
222 translate(SSH1_MSG_IGNORE);
223 translate(SSH1_CMSG_EXIT_CONFIRMATION);
224 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
225 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
226 translate(SSH1_MSG_DEBUG);
227 translate(SSH1_CMSG_REQUEST_COMPRESSION);
228 translate(SSH1_CMSG_AUTH_TIS);
229 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
230 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
231 translate(SSH1_CMSG_AUTH_CCARD);
232 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
233 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
236 char *ssh2_pkt_type(int type)
238 translate(SSH2_MSG_DISCONNECT);
239 translate(SSH2_MSG_IGNORE);
240 translate(SSH2_MSG_UNIMPLEMENTED);
241 translate(SSH2_MSG_DEBUG);
242 translate(SSH2_MSG_SERVICE_REQUEST);
243 translate(SSH2_MSG_SERVICE_ACCEPT);
244 translate(SSH2_MSG_KEXINIT);
245 translate(SSH2_MSG_NEWKEYS);
246 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
247 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
248 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
249 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
250 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
251 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
252 translate(SSH2_MSG_USERAUTH_REQUEST);
253 translate(SSH2_MSG_USERAUTH_FAILURE);
254 translate(SSH2_MSG_USERAUTH_SUCCESS);
255 translate(SSH2_MSG_USERAUTH_BANNER);
256 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
257 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
258 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
259 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
260 translate(SSH2_MSG_GLOBAL_REQUEST);
261 translate(SSH2_MSG_REQUEST_SUCCESS);
262 translate(SSH2_MSG_REQUEST_FAILURE);
263 translate(SSH2_MSG_CHANNEL_OPEN);
264 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
265 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
266 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
267 translate(SSH2_MSG_CHANNEL_DATA);
268 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
269 translate(SSH2_MSG_CHANNEL_EOF);
270 translate(SSH2_MSG_CHANNEL_CLOSE);
271 translate(SSH2_MSG_CHANNEL_REQUEST);
272 translate(SSH2_MSG_CHANNEL_SUCCESS);
273 translate(SSH2_MSG_CHANNEL_FAILURE);
279 #define GET_32BIT(cp) \
280 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
281 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
282 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
283 ((unsigned long)(unsigned char)(cp)[3]))
285 #define PUT_32BIT(cp, value) { \
286 (cp)[0] = (unsigned char)((value) >> 24); \
287 (cp)[1] = (unsigned char)((value) >> 16); \
288 (cp)[2] = (unsigned char)((value) >> 8); \
289 (cp)[3] = (unsigned char)(value); }
291 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
293 /* Coroutine mechanics for the sillier bits of the code */
294 #define crBegin1 static int crLine = 0;
295 #define crBegin2 switch(crLine) { case 0:;
296 #define crBegin crBegin1; crBegin2;
297 #define crFinish(z) } crLine = 0; return (z)
298 #define crFinishV } crLine = 0; return
299 #define crReturn(z) \
301 crLine=__LINE__; return (z); case __LINE__:;\
305 crLine=__LINE__; return; case __LINE__:;\
307 #define crStop(z) do{ crLine = 0; return (z); }while(0)
308 #define crStopV do{ crLine = 0; return; }while(0)
309 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
310 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
312 extern char *x11_init(Socket *, char *, void *);
313 extern void x11_close(Socket);
314 extern int x11_send(Socket, char *, int);
315 extern void x11_invent_auth(char *, int, char *, int);
316 extern void x11_unthrottle(Socket s);
317 extern void x11_override_throttle(Socket s, int enable);
319 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
320 extern char *pfd_addforward(char *desthost, int destport, int port);
321 extern void pfd_close(Socket s);
322 extern int pfd_send(Socket s, char *data, int len);
323 extern void pfd_confirm(Socket s);
324 extern void pfd_unthrottle(Socket s);
325 extern void pfd_override_throttle(Socket s, int enable);
327 static void ssh2_pkt_init(int pkt_type);
328 static void ssh2_pkt_addbool(unsigned char value);
329 static void ssh2_pkt_adduint32(unsigned long value);
330 static void ssh2_pkt_addstring_start(void);
331 static void ssh2_pkt_addstring_str(char *data);
332 static void ssh2_pkt_addstring_data(char *data, int len);
333 static void ssh2_pkt_addstring(char *data);
334 static char *ssh2_mpint_fmt(Bignum b, int *len);
335 static void ssh2_pkt_addmp(Bignum b);
336 static int ssh2_pkt_construct(void);
337 static void ssh2_pkt_send(void);
340 * Buffer management constants. There are several of these for
341 * various different purposes:
343 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
344 * on a local data stream before we throttle the whole SSH
345 * connection (in SSH1 only). Throttling the whole connection is
346 * pretty drastic so we set this high in the hope it won't
349 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
350 * on the SSH connection itself before we defensively throttle
351 * _all_ local data streams. This is pretty drastic too (though
352 * thankfully unlikely in SSH2 since the window mechanism should
353 * ensure that the server never has any need to throttle its end
354 * of the connection), so we set this high as well.
356 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
360 #define SSH1_BUFFER_LIMIT 32768
361 #define SSH_MAX_BACKLOG 32768
362 #define OUR_V2_WINSIZE 16384
364 const static struct ssh_kex *kex_algs[] = {
365 &ssh_diffiehellman_gex,
369 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
371 static void nullmac_key(unsigned char *key)
374 static void nullmac_generate(unsigned char *blk, int len,
378 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
382 const static struct ssh_mac ssh_mac_none = {
383 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
385 const static struct ssh_mac *macs[] = {
386 &ssh_sha1, &ssh_md5, &ssh_mac_none
388 const static struct ssh_mac *buggymacs[] = {
389 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
392 static void ssh_comp_none_init(void)
395 static int ssh_comp_none_block(unsigned char *block, int len,
396 unsigned char **outblock, int *outlen)
400 static int ssh_comp_none_disable(void)
404 const static struct ssh_compress ssh_comp_none = {
406 ssh_comp_none_init, ssh_comp_none_block,
407 ssh_comp_none_init, ssh_comp_none_block,
408 ssh_comp_none_disable
410 extern const struct ssh_compress ssh_zlib;
411 const static struct ssh_compress *compressions[] = {
412 &ssh_zlib, &ssh_comp_none
415 enum { /* channel types */
420 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
424 * 2-3-4 tree storing channels.
427 unsigned remoteid, localid;
431 struct ssh1_data_channel {
434 struct ssh2_data_channel {
436 unsigned remwindow, remmaxpkt;
441 struct ssh_agent_channel {
442 unsigned char *message;
443 unsigned char msglen[4];
444 int lensofar, totallen;
446 struct ssh_x11_channel {
449 struct ssh_pfd_channel {
456 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
457 * 2 use this structure in different ways, reflecting SSH 2's
458 * altogether saner approach to port forwarding.
460 * In SSH 1, you arrange a remote forwarding by sending the server
461 * the remote port number, and the local destination host:port.
462 * When a connection comes in, the server sends you back that
463 * host:port pair, and you connect to it. This is a ready-made
464 * security hole if you're not on the ball: a malicious server
465 * could send you back _any_ host:port pair, so if you trustingly
466 * connect to the address it gives you then you've just opened the
467 * entire inside of your corporate network just by connecting
468 * through it to a dodgy SSH server. Hence, we must store a list of
469 * host:port pairs we _are_ trying to forward to, and reject a
470 * connection request from the server if it's not in the list.
472 * In SSH 2, each side of the connection minds its own business and
473 * doesn't send unnecessary information to the other. You arrange a
474 * remote forwarding by sending the server just the remote port
475 * number. When a connection comes in, the server tells you which
476 * of its ports was connected to; and _you_ have to remember what
477 * local host:port pair went with that port number.
479 * Hence: in SSH 1 this structure stores host:port pairs we intend
480 * to allow connections to, and is indexed by those host:port
481 * pairs. In SSH 2 it stores a mapping from source port to
482 * destination host:port pair, and is indexed by source port.
484 struct ssh_rportfwd {
485 unsigned sport, dport;
498 static SHA_State exhash, exhashbase;
500 static Socket s = NULL;
502 static unsigned char session_key[32];
503 static int ssh1_compressing;
504 static int ssh1_remote_protoflags;
505 static int ssh1_local_protoflags;
506 static int ssh_agentfwd_enabled;
507 static int ssh_X11_fwd_enabled;
508 static int ssh_remote_bugs;
509 static const struct ssh_cipher *cipher = NULL;
510 static const struct ssh2_cipher *cscipher = NULL;
511 static const struct ssh2_cipher *sccipher = NULL;
512 static const struct ssh_mac *csmac = NULL;
513 static const struct ssh_mac *scmac = NULL;
514 static const struct ssh_compress *cscomp = NULL;
515 static const struct ssh_compress *sccomp = NULL;
516 static const struct ssh_kex *kex = NULL;
517 static const struct ssh_signkey *hostkey = NULL;
518 static unsigned char ssh2_session_id[20];
520 static char *savedhost;
521 static int savedport;
522 static int ssh_send_ok;
523 static int ssh_echoing, ssh_editing;
525 static tree234 *ssh_channels; /* indexed by local id */
526 static struct ssh_channel *mainchan; /* primary session channel */
527 static int ssh_exitcode = -1;
529 static tree234 *ssh_rportfwds;
533 SSH_STATE_BEFORE_SIZE,
537 } ssh_state = SSH_STATE_PREPACKET;
539 static int size_needed = FALSE, eof_needed = FALSE;
541 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
542 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
543 static unsigned char *deferred_send_data = NULL;
544 static int deferred_len = 0, deferred_size = 0;
547 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
548 * that fails. This variable is the means by which scp.c can reach
549 * into the SSH code and find out which one it got.
551 int ssh_fallback_cmd = 0;
553 static int ssh_version;
554 static int ssh1_throttle_count;
555 static int ssh_overall_bufsize;
556 static int ssh_throttled_all;
557 static int ssh1_stdout_throttling;
558 static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
559 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
560 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
561 static void ssh_size(void);
562 static void ssh_special(Telnet_Special);
563 static int ssh2_try_send(struct ssh_channel *c);
564 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
566 static void ssh_throttle_all(int enable, int bufsize);
567 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
568 static int (*s_rdpkt) (unsigned char **data, int *datalen);
569 static int ssh_sendbuffer(void);
571 static struct rdpkt1_state_tag {
572 long len, pad, biglen, to_read;
573 unsigned long realcrc, gotcrc;
579 static struct rdpkt2_state_tag {
580 long len, pad, payload, packetlen, maclen;
583 unsigned long incoming_sequence;
586 static int ssh_channelcmp(void *av, void *bv)
588 struct ssh_channel *a = (struct ssh_channel *) av;
589 struct ssh_channel *b = (struct ssh_channel *) bv;
590 if (a->localid < b->localid)
592 if (a->localid > b->localid)
596 static int ssh_channelfind(void *av, void *bv)
598 unsigned *a = (unsigned *) av;
599 struct ssh_channel *b = (struct ssh_channel *) bv;
607 static int ssh_rportcmp_ssh1(void *av, void *bv)
609 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
610 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
612 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
613 return i < 0 ? -1 : +1;
614 if (a->dport > b->dport)
616 if (a->dport < b->dport)
621 static int ssh_rportcmp_ssh2(void *av, void *bv)
623 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
624 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
626 if (a->sport > b->sport)
628 if (a->sport < b->sport)
633 static int alloc_channel_id(void)
635 const unsigned CHANNEL_NUMBER_OFFSET = 256;
636 unsigned low, high, mid;
638 struct ssh_channel *c;
641 * First-fit allocation of channel numbers: always pick the
642 * lowest unused one. To do this, binary-search using the
643 * counted B-tree to find the largest channel ID which is in a
644 * contiguous sequence from the beginning. (Precisely
645 * everything in that sequence must have ID equal to its tree
646 * index plus CHANNEL_NUMBER_OFFSET.)
648 tsize = count234(ssh_channels);
652 while (high - low > 1) {
653 mid = (high + low) / 2;
654 c = index234(ssh_channels, mid);
655 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
656 low = mid; /* this one is fine */
658 high = mid; /* this one is past it */
661 * Now low points to either -1, or the tree index of the
662 * largest ID in the initial sequence.
665 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
666 assert(NULL == find234(ssh_channels, &i, ssh_channelfind));
668 return low + 1 + CHANNEL_NUMBER_OFFSET;
671 static void c_write(char *buf, int len)
673 if ((flags & FLAG_STDERR)) {
675 for (i = 0; i < len; i++)
677 fputc(buf[i], stderr);
680 from_backend(1, buf, len);
683 static void c_write_untrusted(char *buf, int len)
686 for (i = 0; i < len; i++) {
689 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
694 static void c_write_str(char *buf)
696 c_write(buf, strlen(buf));
700 * Collect incoming data in the incoming packet buffer.
701 * Decipher and verify the packet when it is completely read.
702 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
703 * Update the *data and *datalen variables.
704 * Return the additional nr of bytes needed, or 0 when
705 * a complete packet is available.
707 static int ssh1_rdpkt(unsigned char **data, int *datalen)
709 struct rdpkt1_state_tag *st = &rdpkt1_state;
718 for (st->i = st->len = 0; st->i < 4; st->i++) {
719 while ((*datalen) == 0)
721 st->len = (st->len << 8) + **data;
722 (*data)++, (*datalen)--;
725 st->pad = 8 - (st->len % 8);
726 st->biglen = st->len + st->pad;
727 pktin.length = st->len - 5;
729 if (pktin.maxlen < st->biglen) {
730 pktin.maxlen = st->biglen;
731 pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
732 srealloc(pktin.data, st->biglen + APIEXTRA));
734 fatalbox("Out of memory");
737 st->to_read = st->biglen;
739 while (st->to_read > 0) {
740 st->chunk = st->to_read;
741 while ((*datalen) == 0)
742 crReturn(st->to_read);
743 if (st->chunk > (*datalen))
744 st->chunk = (*datalen);
745 memcpy(st->p, *data, st->chunk);
747 *datalen -= st->chunk;
749 st->to_read -= st->chunk;
752 if (cipher && detect_attack(pktin.data, st->biglen, NULL)) {
753 bombout(("Network attack (CRC compensation) detected!"));
758 cipher->decrypt(pktin.data, st->biglen);
760 st->realcrc = crc32(pktin.data, st->biglen - 4);
761 st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
762 if (st->gotcrc != st->realcrc) {
763 bombout(("Incorrect CRC received on packet"));
767 pktin.body = pktin.data + st->pad + 1;
769 if (ssh1_compressing) {
770 unsigned char *decompblk;
772 zlib_decompress_block(pktin.body - 1, pktin.length + 1,
773 &decompblk, &decomplen);
775 if (pktin.maxlen < st->pad + decomplen) {
776 pktin.maxlen = st->pad + decomplen;
777 pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
778 pktin.body = pktin.data + st->pad + 1;
780 fatalbox("Out of memory");
783 memcpy(pktin.body - 1, decompblk, decomplen);
785 pktin.length = decomplen - 1;
788 pktin.type = pktin.body[-1];
790 log_packet(PKT_INCOMING, pktin.type, ssh1_pkt_type(pktin.type),
791 pktin.body, pktin.length);
793 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
794 pktin.type == SSH1_SMSG_STDERR_DATA ||
795 pktin.type == SSH1_MSG_DEBUG ||
796 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
797 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
798 long stringlen = GET_32BIT(pktin.body);
799 if (stringlen + 4 != pktin.length) {
800 bombout(("Received data packet with bogus string length"));
805 if (pktin.type == SSH1_MSG_DEBUG) {
806 /* log debug message */
808 int stringlen = GET_32BIT(pktin.body);
809 strcpy(buf, "Remote debug message: ");
812 memcpy(buf + 8, pktin.body + 4, stringlen);
813 buf[8 + stringlen] = '\0';
816 } else if (pktin.type == SSH1_MSG_IGNORE) {
821 if (pktin.type == SSH1_MSG_DISCONNECT) {
822 /* log reason code in disconnect message */
824 unsigned msglen = GET_32BIT(pktin.body);
826 strcpy(buf, "Remote sent disconnect: ");
827 nowlen = strlen(buf);
828 if (msglen > sizeof(buf) - nowlen - 1)
829 msglen = sizeof(buf) - nowlen - 1;
830 memcpy(buf + nowlen, pktin.body + 4, msglen);
831 buf[nowlen + msglen] = '\0';
832 /* logevent(buf); (this is now done within the bombout macro) */
833 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
840 static int ssh2_rdpkt(unsigned char **data, int *datalen)
842 struct rdpkt2_state_tag *st = &rdpkt2_state;
850 st->cipherblk = sccipher->blksize;
853 if (st->cipherblk < 8)
856 if (pktin.maxlen < st->cipherblk) {
857 pktin.maxlen = st->cipherblk;
860 NULL ? smalloc(st->cipherblk +
861 APIEXTRA) : srealloc(pktin.data,
865 fatalbox("Out of memory");
869 * Acquire and decrypt the first block of the packet. This will
870 * contain the length and padding details.
872 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
873 while ((*datalen) == 0)
874 crReturn(st->cipherblk - st->i);
875 pktin.data[st->i] = *(*data)++;
880 sccipher->decrypt(pktin.data, st->cipherblk);
883 * Now get the length and padding figures.
885 st->len = GET_32BIT(pktin.data);
886 st->pad = pktin.data[4];
889 * _Completely_ silly lengths should be stomped on before they
890 * do us any more damage.
892 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
893 bombout(("Incoming packet was garbled on decryption"));
898 * This enables us to deduce the payload length.
900 st->payload = st->len - st->pad - 1;
902 pktin.length = st->payload + 5;
905 * So now we can work out the total packet length.
907 st->packetlen = st->len + 4;
908 st->maclen = scmac ? scmac->len : 0;
911 * Adjust memory allocation if packet is too big.
913 if (pktin.maxlen < st->packetlen + st->maclen) {
914 pktin.maxlen = st->packetlen + st->maclen;
917 NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
922 fatalbox("Out of memory");
926 * Read and decrypt the remainder of the packet.
928 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
930 while ((*datalen) == 0)
931 crReturn(st->packetlen + st->maclen - st->i);
932 pktin.data[st->i] = *(*data)++;
935 /* Decrypt everything _except_ the MAC. */
937 sccipher->decrypt(pktin.data + st->cipherblk,
938 st->packetlen - st->cipherblk);
944 && !scmac->verify(pktin.data, st->len + 4,
945 st->incoming_sequence)) {
946 bombout(("Incorrect MAC received on packet"));
949 st->incoming_sequence++; /* whether or not we MACed */
952 * Decompress packet payload.
955 unsigned char *newpayload;
957 if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
958 &newpayload, &newlen)) {
959 if (pktin.maxlen < newlen + 5) {
960 pktin.maxlen = newlen + 5;
963 NULL ? smalloc(pktin.maxlen +
964 APIEXTRA) : srealloc(pktin.data,
968 fatalbox("Out of memory");
970 pktin.length = 5 + newlen;
971 memcpy(pktin.data + 5, newpayload, newlen);
977 pktin.type = pktin.data[5];
979 log_packet(PKT_INCOMING, pktin.type, ssh2_pkt_type(pktin.type),
980 pktin.data+6, pktin.length-6);
982 switch (pktin.type) {
984 * These packets we must handle instantly.
986 case SSH2_MSG_DISCONNECT:
988 /* log reason code in disconnect message */
990 int reason = GET_32BIT(pktin.data + 6);
991 unsigned msglen = GET_32BIT(pktin.data + 10);
993 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
994 sprintf(buf, "Received disconnect message (%s)",
995 ssh2_disconnect_reasons[reason]);
997 sprintf(buf, "Received disconnect message (unknown type %d)",
1001 strcpy(buf, "Disconnection message text: ");
1002 nowlen = strlen(buf);
1003 if (msglen > sizeof(buf) - nowlen - 1)
1004 msglen = sizeof(buf) - nowlen - 1;
1005 memcpy(buf + nowlen, pktin.data + 14, msglen);
1006 buf[nowlen + msglen] = '\0';
1008 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1010 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1011 ssh2_disconnect_reasons[reason] : "unknown",
1016 case SSH2_MSG_IGNORE:
1018 case SSH2_MSG_DEBUG:
1020 /* log the debug message */
1022 /* int display = pktin.body[6]; */
1023 int stringlen = GET_32BIT(pktin.data+7);
1025 strcpy(buf, "Remote debug message: ");
1026 prefix = strlen(buf);
1027 if (stringlen > sizeof(buf)-prefix-1)
1028 stringlen = sizeof(buf)-prefix-1;
1029 memcpy(buf + prefix, pktin.data + 11, stringlen);
1030 buf[prefix + stringlen] = '\0';
1033 goto next_packet; /* FIXME: print the debug message */
1036 * These packets we need do nothing about here.
1038 case SSH2_MSG_UNIMPLEMENTED:
1039 case SSH2_MSG_SERVICE_REQUEST:
1040 case SSH2_MSG_SERVICE_ACCEPT:
1041 case SSH2_MSG_KEXINIT:
1042 case SSH2_MSG_NEWKEYS:
1043 case SSH2_MSG_KEXDH_INIT:
1044 case SSH2_MSG_KEXDH_REPLY:
1045 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1046 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1047 case SSH2_MSG_KEX_DH_GEX_INIT:
1048 case SSH2_MSG_KEX_DH_GEX_REPLY:
1049 case SSH2_MSG_USERAUTH_REQUEST:
1050 case SSH2_MSG_USERAUTH_FAILURE:
1051 case SSH2_MSG_USERAUTH_SUCCESS:
1052 case SSH2_MSG_USERAUTH_BANNER:
1053 case SSH2_MSG_USERAUTH_PK_OK:
1054 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1055 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1056 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1057 case SSH2_MSG_GLOBAL_REQUEST:
1058 case SSH2_MSG_REQUEST_SUCCESS:
1059 case SSH2_MSG_REQUEST_FAILURE:
1060 case SSH2_MSG_CHANNEL_OPEN:
1061 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1062 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1063 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1064 case SSH2_MSG_CHANNEL_DATA:
1065 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1066 case SSH2_MSG_CHANNEL_EOF:
1067 case SSH2_MSG_CHANNEL_CLOSE:
1068 case SSH2_MSG_CHANNEL_REQUEST:
1069 case SSH2_MSG_CHANNEL_SUCCESS:
1070 case SSH2_MSG_CHANNEL_FAILURE:
1074 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1077 ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
1078 ssh2_pkt_adduint32(st->incoming_sequence - 1);
1086 static void ssh1_pktout_size(int len)
1090 len += 5; /* type and CRC */
1091 pad = 8 - (len % 8);
1094 pktout.length = len - 5;
1095 if (pktout.maxlen < biglen) {
1096 pktout.maxlen = biglen;
1098 /* Allocate enough buffer space for extra block
1099 * for MS CryptEncrypt() */
1100 pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
1101 srealloc(pktout.data, biglen + 12));
1103 pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
1104 srealloc(pktout.data, biglen + 4));
1107 fatalbox("Out of memory");
1109 pktout.body = pktout.data + 4 + pad + 1;
1112 static void s_wrpkt_start(int type, int len)
1114 ssh1_pktout_size(len);
1118 static int s_wrpkt_prepare(void)
1120 int pad, len, biglen, i;
1123 pktout.body[-1] = pktout.type;
1125 log_packet(PKT_OUTGOING, pktout.type, ssh1_pkt_type(pktout.type),
1126 pktout.body, pktout.length);
1128 if (ssh1_compressing) {
1129 unsigned char *compblk;
1131 zlib_compress_block(pktout.body - 1, pktout.length + 1,
1132 &compblk, &complen);
1133 ssh1_pktout_size(complen - 1);
1134 memcpy(pktout.body - 1, compblk, complen);
1138 len = pktout.length + 5; /* type and CRC */
1139 pad = 8 - (len % 8);
1142 for (i = 0; i < pad; i++)
1143 pktout.data[i + 4] = random_byte();
1144 crc = crc32(pktout.data + 4, biglen - 4);
1145 PUT_32BIT(pktout.data + biglen, crc);
1146 PUT_32BIT(pktout.data, len);
1149 cipher->encrypt(pktout.data + 4, biglen);
1154 static void s_wrpkt(void)
1157 len = s_wrpkt_prepare();
1158 backlog = sk_write(s, pktout.data, len);
1159 if (backlog > SSH_MAX_BACKLOG)
1160 ssh_throttle_all(1, backlog);
1163 static void s_wrpkt_defer(void)
1166 len = s_wrpkt_prepare();
1167 if (deferred_len + len > deferred_size) {
1168 deferred_size = deferred_len + len + 128;
1169 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1171 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1172 deferred_len += len;
1176 * Construct a packet with the specified contents.
1178 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
1180 unsigned char *p, *argp, argchar;
1181 unsigned long argint;
1182 int pktlen, argtype, arglen;
1186 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1189 (void) va_arg(ap1, int);
1193 (void) va_arg(ap1, char);
1197 (void) va_arg(ap1, unsigned char *);
1198 arglen = va_arg(ap1, int);
1202 argp = va_arg(ap1, unsigned char *);
1203 arglen = strlen(argp);
1204 pktlen += 4 + arglen;
1207 bn = va_arg(ap1, Bignum);
1208 pktlen += ssh1_bignum_length(bn);
1215 s_wrpkt_start(pkttype, pktlen);
1218 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1221 argint = va_arg(ap2, int);
1222 PUT_32BIT(p, argint);
1226 argchar = va_arg(ap2, unsigned char);
1231 argp = va_arg(ap2, unsigned char *);
1232 arglen = va_arg(ap2, int);
1233 memcpy(p, argp, arglen);
1237 argp = va_arg(ap2, unsigned char *);
1238 arglen = strlen(argp);
1239 PUT_32BIT(p, arglen);
1240 memcpy(p + 4, argp, arglen);
1244 bn = va_arg(ap2, Bignum);
1245 p += ssh1_write_bignum(p, bn);
1251 static void send_packet(int pkttype, ...)
1254 va_start(ap1, pkttype);
1255 va_start(ap2, pkttype);
1256 construct_packet(pkttype, ap1, ap2);
1260 static void defer_packet(int pkttype, ...)
1263 va_start(ap1, pkttype);
1264 va_start(ap2, pkttype);
1265 construct_packet(pkttype, ap1, ap2);
1269 static int ssh_versioncmp(char *a, char *b)
1272 unsigned long av, bv;
1274 av = strtoul(a, &ae, 10);
1275 bv = strtoul(b, &be, 10);
1277 return (av < bv ? -1 : +1);
1282 av = strtoul(ae, &ae, 10);
1283 bv = strtoul(be, &be, 10);
1285 return (av < bv ? -1 : +1);
1291 * Utility routines for putting an SSH-protocol `string' and
1292 * `uint32' into a SHA state.
1295 static void sha_string(SHA_State * s, void *str, int len)
1297 unsigned char lenblk[4];
1298 PUT_32BIT(lenblk, len);
1299 SHA_Bytes(s, lenblk, 4);
1300 SHA_Bytes(s, str, len);
1303 static void sha_uint32(SHA_State * s, unsigned i)
1305 unsigned char intblk[4];
1306 PUT_32BIT(intblk, i);
1307 SHA_Bytes(s, intblk, 4);
1311 * SSH2 packet construction functions.
1313 static void ssh2_pkt_ensure(int length)
1315 if (pktout.maxlen < length) {
1316 pktout.maxlen = length + 256;
1319 NULL ? smalloc(pktout.maxlen +
1320 APIEXTRA) : srealloc(pktout.data,
1324 fatalbox("Out of memory");
1327 static void ssh2_pkt_adddata(void *data, int len)
1329 pktout.length += len;
1330 ssh2_pkt_ensure(pktout.length);
1331 memcpy(pktout.data + pktout.length - len, data, len);
1333 static void ssh2_pkt_addbyte(unsigned char byte)
1335 ssh2_pkt_adddata(&byte, 1);
1337 static void ssh2_pkt_init(int pkt_type)
1340 ssh2_pkt_addbyte((unsigned char) pkt_type);
1342 static void ssh2_pkt_addbool(unsigned char value)
1344 ssh2_pkt_adddata(&value, 1);
1346 static void ssh2_pkt_adduint32(unsigned long value)
1349 PUT_32BIT(x, value);
1350 ssh2_pkt_adddata(x, 4);
1352 static void ssh2_pkt_addstring_start(void)
1354 ssh2_pkt_adduint32(0);
1355 pktout.savedpos = pktout.length;
1357 static void ssh2_pkt_addstring_str(char *data)
1359 ssh2_pkt_adddata(data, strlen(data));
1360 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1361 pktout.length - pktout.savedpos);
1363 static void ssh2_pkt_addstring_data(char *data, int len)
1365 ssh2_pkt_adddata(data, len);
1366 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1367 pktout.length - pktout.savedpos);
1369 static void ssh2_pkt_addstring(char *data)
1371 ssh2_pkt_addstring_start();
1372 ssh2_pkt_addstring_str(data);
1374 static char *ssh2_mpint_fmt(Bignum b, int *len)
1377 int i, n = (bignum_bitcount(b) + 7) / 8;
1380 fatalbox("out of memory");
1382 for (i = 1; i <= n; i++)
1383 p[i] = bignum_byte(b, n - i);
1385 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1387 memmove(p, p + i, n + 1 - i);
1391 static void ssh2_pkt_addmp(Bignum b)
1395 p = ssh2_mpint_fmt(b, &len);
1396 ssh2_pkt_addstring_start();
1397 ssh2_pkt_addstring_data(p, len);
1402 * Construct an SSH2 final-form packet: compress it, encrypt it,
1403 * put the MAC on it. Final packet, ready to be sent, is stored in
1404 * pktout.data. Total length is returned.
1406 static int ssh2_pkt_construct(void)
1408 int cipherblk, maclen, padding, i;
1409 static unsigned long outgoing_sequence = 0;
1411 log_packet(PKT_OUTGOING, pktout.data[5], ssh2_pkt_type(pktout.data[5]),
1412 pktout.data + 6, pktout.length - 6);
1415 * Compress packet payload.
1418 unsigned char *newpayload;
1420 if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1421 &newpayload, &newlen)) {
1423 ssh2_pkt_adddata(newpayload, newlen);
1429 * Add padding. At least four bytes, and must also bring total
1430 * length (minus MAC) up to a multiple of the block size.
1432 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
1433 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1436 (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1437 maclen = csmac ? csmac->len : 0;
1438 ssh2_pkt_ensure(pktout.length + padding + maclen);
1439 pktout.data[4] = padding;
1440 for (i = 0; i < padding; i++)
1441 pktout.data[pktout.length + i] = random_byte();
1442 PUT_32BIT(pktout.data, pktout.length + padding - 4);
1444 csmac->generate(pktout.data, pktout.length + padding,
1446 outgoing_sequence++; /* whether or not we MACed */
1449 cscipher->encrypt(pktout.data, pktout.length + padding);
1451 /* Ready-to-send packet starts at pktout.data. We return length. */
1452 return pktout.length + padding + maclen;
1456 * Construct and send an SSH2 packet immediately.
1458 static void ssh2_pkt_send(void)
1462 len = ssh2_pkt_construct();
1463 backlog = sk_write(s, pktout.data, len);
1464 if (backlog > SSH_MAX_BACKLOG)
1465 ssh_throttle_all(1, backlog);
1469 * Construct an SSH2 packet and add it to a deferred data block.
1470 * Useful for sending multiple packets in a single sk_write() call,
1471 * to prevent a traffic-analysing listener from being able to work
1472 * out the length of any particular packet (such as the password
1475 * Note that because SSH2 sequence-numbers its packets, this can
1476 * NOT be used as an m4-style `defer' allowing packets to be
1477 * constructed in one order and sent in another.
1479 static void ssh2_pkt_defer(void)
1481 int len = ssh2_pkt_construct();
1482 if (deferred_len + len > deferred_size) {
1483 deferred_size = deferred_len + len + 128;
1484 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1486 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1487 deferred_len += len;
1491 * Send the whole deferred data block constructed by
1492 * ssh2_pkt_defer() or SSH1's defer_packet().
1494 static void ssh_pkt_defersend(void)
1497 backlog = sk_write(s, deferred_send_data, deferred_len);
1498 deferred_len = deferred_size = 0;
1499 sfree(deferred_send_data);
1500 deferred_send_data = NULL;
1501 if (backlog > SSH_MAX_BACKLOG)
1502 ssh_throttle_all(1, backlog);
1506 void bndebug(char *string, Bignum b)
1510 p = ssh2_mpint_fmt(b, &len);
1511 debug(("%s", string));
1512 for (i = 0; i < len; i++)
1513 debug((" %02x", p[i]));
1519 static void sha_mpint(SHA_State * s, Bignum b)
1523 p = ssh2_mpint_fmt(b, &len);
1524 sha_string(s, p, len);
1529 * SSH2 packet decode functions.
1531 static unsigned long ssh2_pkt_getuint32(void)
1533 unsigned long value;
1534 if (pktin.length - pktin.savedpos < 4)
1535 return 0; /* arrgh, no way to decline (FIXME?) */
1536 value = GET_32BIT(pktin.data + pktin.savedpos);
1537 pktin.savedpos += 4;
1540 static int ssh2_pkt_getbool(void)
1542 unsigned long value;
1543 if (pktin.length - pktin.savedpos < 1)
1544 return 0; /* arrgh, no way to decline (FIXME?) */
1545 value = pktin.data[pktin.savedpos] != 0;
1549 static void ssh2_pkt_getstring(char **p, int *length)
1553 if (pktin.length - pktin.savedpos < 4)
1555 *length = GET_32BIT(pktin.data + pktin.savedpos);
1556 pktin.savedpos += 4;
1557 if (pktin.length - pktin.savedpos < *length)
1559 *p = pktin.data + pktin.savedpos;
1560 pktin.savedpos += *length;
1562 static Bignum ssh2_pkt_getmp(void)
1568 ssh2_pkt_getstring(&p, &length);
1572 bombout(("internal error: Can't handle negative mpints"));
1575 b = bignum_from_bytes(p, length);
1580 * Helper function to add an SSH2 signature blob to a packet.
1581 * Expects to be shown the public key blob as well as the signature
1582 * blob. Normally works just like ssh2_pkt_addstring, but will
1583 * fiddle with the signature packet if necessary for
1584 * BUG_SSH2_RSA_PADDING.
1586 static void ssh2_add_sigblob(void *pkblob_v, int pkblob_len,
1587 void *sigblob_v, int sigblob_len)
1589 unsigned char *pkblob = (unsigned char *)pkblob_v;
1590 unsigned char *sigblob = (unsigned char *)sigblob_v;
1592 /* dmemdump(pkblob, pkblob_len); */
1593 /* dmemdump(sigblob, sigblob_len); */
1596 * See if this is in fact an ssh-rsa signature and a buggy
1597 * server; otherwise we can just do this the easy way.
1599 if ((ssh_remote_bugs & BUG_SSH2_RSA_PADDING) &&
1600 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1601 int pos, len, siglen;
1604 * Find the byte length of the modulus.
1607 pos = 4+7; /* skip over "ssh-rsa" */
1608 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1609 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1610 pos += 4; /* find modulus itself */
1611 while (len > 0 && pkblob[pos] == 0)
1613 /* debug(("modulus length is %d\n", len)); */
1616 * Now find the signature integer.
1618 pos = 4+7; /* skip over "ssh-rsa" */
1619 siglen = GET_32BIT(sigblob+pos);
1620 /* debug(("signature length is %d\n", siglen)); */
1622 if (len != siglen) {
1623 unsigned char newlen[4];
1624 ssh2_pkt_addstring_start();
1625 ssh2_pkt_addstring_data(sigblob, pos);
1626 /* dmemdump(sigblob, pos); */
1627 pos += 4; /* point to start of actual sig */
1628 PUT_32BIT(newlen, len);
1629 ssh2_pkt_addstring_data(newlen, 4);
1630 /* dmemdump(newlen, 4); */
1632 while (len-- > siglen) {
1633 ssh2_pkt_addstring_data(newlen, 1);
1634 /* dmemdump(newlen, 1); */
1636 ssh2_pkt_addstring_data(sigblob+pos, siglen);
1637 /* dmemdump(sigblob+pos, siglen); */
1641 /* Otherwise fall through and do it the easy way. */
1644 ssh2_pkt_addstring_start();
1645 ssh2_pkt_addstring_data(sigblob, sigblob_len);
1649 * Examine the remote side's version string and compare it against
1650 * a list of known buggy implementations.
1652 static void ssh_detect_bugs(char *vstring)
1654 char *imp; /* pointer to implementation part */
1656 imp += strcspn(imp, "-");
1658 imp += strcspn(imp, "-");
1661 ssh_remote_bugs = 0;
1663 if (cfg.sshbug_ignore1 == BUG_ON ||
1664 (cfg.sshbug_ignore1 == BUG_AUTO &&
1665 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1666 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1667 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1669 * These versions don't support SSH1_MSG_IGNORE, so we have
1670 * to use a different defence against password length
1673 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1674 logevent("We believe remote version has SSH1 ignore bug");
1677 if (cfg.sshbug_plainpw1 == BUG_ON ||
1678 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1679 (!strcmp(imp, "Cisco-1.25")))) {
1681 * These versions need a plain password sent; they can't
1682 * handle having a null and a random length of data after
1685 ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1686 logevent("We believe remote version needs a plain SSH1 password");
1689 if (cfg.sshbug_rsa1 == BUG_ON ||
1690 (cfg.sshbug_rsa1 == BUG_AUTO &&
1691 (!strcmp(imp, "Cisco-1.25")))) {
1693 * These versions apparently have no clue whatever about
1694 * RSA authentication and will panic and die if they see
1695 * an AUTH_RSA message.
1697 ssh_remote_bugs |= BUG_CHOKES_ON_RSA;
1698 logevent("We believe remote version can't handle RSA authentication");
1701 if (cfg.sshbug_hmac2 == BUG_ON ||
1702 (cfg.sshbug_hmac2 == BUG_AUTO &&
1703 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1704 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1705 !strncmp(imp, "2.1 ", 4)))) {
1707 * These versions have the HMAC bug.
1709 ssh_remote_bugs |= BUG_SSH2_HMAC;
1710 logevent("We believe remote version has SSH2 HMAC bug");
1713 if (cfg.sshbug_derivekey2 == BUG_ON ||
1714 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1715 (!strncmp(imp, "2.0.", 4)))) {
1717 * These versions have the key-derivation bug (failing to
1718 * include the literal shared secret in the hashes that
1719 * generate the keys).
1721 ssh_remote_bugs |= BUG_SSH2_DERIVEKEY;
1722 logevent("We believe remote version has SSH2 key-derivation bug");
1725 if (cfg.sshbug_rsapad2 == BUG_ON ||
1726 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1727 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1728 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1730 * These versions have the SSH2 RSA padding bug.
1732 ssh_remote_bugs |= BUG_SSH2_RSA_PADDING;
1733 logevent("We believe remote version has SSH2 RSA padding bug");
1737 static int do_ssh_init(unsigned char c)
1740 static char version[10];
1741 static char *vstring;
1742 static int vstrsize;
1745 static int proto1, proto2;
1749 /* Search for the string "SSH-" in the input. */
1752 static const int transS[] = { 1, 2, 2, 1 };
1753 static const int transH[] = { 0, 0, 3, 0 };
1754 static const int transminus[] = { 0, 0, 0, -1 };
1765 crReturn(1); /* get another character */
1769 vstring = smalloc(vstrsize);
1770 strcpy(vstring, "SSH-");
1774 crReturn(1); /* get another char */
1775 if (vslen >= vstrsize - 1) {
1777 vstring = srealloc(vstring, vstrsize);
1779 vstring[vslen++] = c;
1784 } else if (i < sizeof(version) - 1)
1786 } else if (c == '\n')
1790 ssh_agentfwd_enabled = FALSE;
1791 rdpkt2_state.incoming_sequence = 0;
1794 vlog = smalloc(20 + vslen);
1795 vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1796 sprintf(vlog, "Server version: %s", vstring);
1798 ssh_detect_bugs(vstring);
1802 * Decide which SSH protocol version to support.
1805 /* Anything strictly below "2.0" means protocol 1 is supported. */
1806 proto1 = ssh_versioncmp(version, "2.0") < 0;
1807 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1808 proto2 = ssh_versioncmp(version, "1.99") >= 0;
1810 if (cfg.sshprot == 0 && !proto1) {
1811 bombout(("SSH protocol version 1 required by user but not provided by server"));
1814 if (cfg.sshprot == 3 && !proto2) {
1815 bombout(("SSH protocol version 2 required by user but not provided by server"));
1819 if (proto2 && (cfg.sshprot >= 2 || !proto1)) {
1823 char verstring[80], vlog[100];
1824 sprintf(verstring, "SSH-2.0-%s", sshver);
1825 SHA_Init(&exhashbase);
1827 * Hash our version string and their version string.
1829 sha_string(&exhashbase, verstring, strlen(verstring));
1830 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1831 sprintf(vlog, "We claim version: %s", verstring);
1833 strcat(verstring, "\n");
1834 logevent("Using SSH protocol version 2");
1835 sk_write(s, verstring, strlen(verstring));
1836 ssh_protocol = ssh2_protocol;
1838 s_rdpkt = ssh2_rdpkt;
1843 char verstring[80], vlog[100];
1844 sprintf(verstring, "SSH-%s-%s",
1845 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1847 sprintf(vlog, "We claim version: %s", verstring);
1849 strcat(verstring, "\n");
1851 logevent("Using SSH protocol version 1");
1852 sk_write(s, verstring, strlen(verstring));
1853 ssh_protocol = ssh1_protocol;
1855 s_rdpkt = ssh1_rdpkt;
1857 ssh_state = SSH_STATE_BEFORE_SIZE;
1864 static void ssh_gotdata(unsigned char *data, int datalen)
1869 * To begin with, feed the characters one by one to the
1870 * protocol initialisation / selection function do_ssh_init().
1871 * When that returns 0, we're done with the initial greeting
1872 * exchange and can move on to packet discipline.
1877 crReturnV; /* more data please */
1878 ret = do_ssh_init(*data);
1886 * We emerge from that loop when the initial negotiation is
1887 * over and we have selected an s_rdpkt function. Now pass
1888 * everything to s_rdpkt, and then pass the resulting packets
1889 * to the proper protocol handler.
1894 while (datalen > 0) {
1895 if (s_rdpkt(&data, &datalen) == 0) {
1896 if (ssh_state == SSH_STATE_CLOSED) {
1899 ssh_protocol(NULL, 0, 1);
1900 if (ssh_state == SSH_STATE_CLOSED) {
1910 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1913 ssh_state = SSH_STATE_CLOSED;
1919 /* A socket error has occurred. */
1920 logevent(error_msg);
1921 connection_fatal(error_msg);
1923 /* Otherwise, the remote side closed the connection normally. */
1928 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1930 ssh_gotdata(data, len);
1931 if (ssh_state == SSH_STATE_CLOSED) {
1941 static void ssh_sent(Plug plug, int bufsize)
1944 * If the send backlog on the SSH socket itself clears, we
1945 * should unthrottle the whole world if it was throttled.
1947 if (bufsize < SSH_MAX_BACKLOG)
1948 ssh_throttle_all(0, bufsize);
1952 * Connect to specified host and port.
1953 * Returns an error message, or NULL on success.
1954 * Also places the canonical host name into `realhost'. It must be
1955 * freed by the caller.
1957 static char *connect_to_host(char *host, int port, char **realhost, int nodelay)
1959 static struct plug_function_table fn_table = {
1964 }, *fn_table_ptr = &fn_table;
1973 savedhost = smalloc(1 + strlen(host));
1975 fatalbox("Out of memory");
1976 strcpy(savedhost, host);
1979 port = 22; /* default ssh port */
1994 sprintf(buf, "Looking up host \"%.170s\"", host);
1997 addr = sk_namelookup(host, realhost);
1998 if ((err = sk_addr_error(addr)))
2002 *realhost = strdup(FWhost);
2009 char buf[200], addrbuf[100];
2010 sk_getaddr(addr, addrbuf, 100);
2011 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2014 s = new_connection(addr, *realhost, port, 0, 1, nodelay, &fn_table_ptr);
2015 if ((err = sk_socket_error(s))) {
2021 sk_write(s, "connect ", 8);
2022 sk_write(s, FWhost, strlen(FWhost));
2025 sprintf(buf, " %d\n", FWport);
2026 sk_write(s, buf, strlen(buf));
2034 * Throttle or unthrottle the SSH connection.
2036 static void ssh1_throttle(int adjust)
2038 int old_count = ssh1_throttle_count;
2039 ssh1_throttle_count += adjust;
2040 assert(ssh1_throttle_count >= 0);
2041 if (ssh1_throttle_count && !old_count) {
2042 sk_set_frozen(s, 1);
2043 } else if (!ssh1_throttle_count && old_count) {
2044 sk_set_frozen(s, 0);
2049 * Throttle or unthrottle _all_ local data streams (for when sends
2050 * on the SSH connection itself back up).
2052 static void ssh_throttle_all(int enable, int bufsize)
2055 struct ssh_channel *c;
2057 if (enable == ssh_throttled_all)
2059 ssh_throttled_all = enable;
2060 ssh_overall_bufsize = bufsize;
2063 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
2065 case CHAN_MAINSESSION:
2067 * This is treated separately, outside the switch.
2071 x11_override_throttle(c->u.x11.s, enable);
2074 /* Agent channels require no buffer management. */
2077 pfd_override_throttle(c->u.x11.s, enable);
2084 * Username and password input, abstracted off into reusable
2085 * routines (hopefully even reusable between SSH1 and SSH2!).
2087 static char *ssh_userpass_input_buffer;
2088 static int ssh_userpass_input_buflen;
2089 static int ssh_userpass_input_bufpos;
2090 static int ssh_userpass_input_echo;
2092 /* Set up a username or password input loop on a given buffer. */
2093 void setup_userpass_input(char *buffer, int buflen, int echo)
2095 ssh_userpass_input_buffer = buffer;
2096 ssh_userpass_input_buflen = buflen;
2097 ssh_userpass_input_bufpos = 0;
2098 ssh_userpass_input_echo = echo;
2102 * Process some terminal data in the course of username/password
2103 * input. Returns >0 for success (line of input returned in
2104 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2105 * for inconclusive (keep waiting for more input please).
2107 int process_userpass_input(unsigned char *in, int inlen)
2112 switch (c = *in++) {
2115 ssh_userpass_input_buffer[ssh_userpass_input_bufpos] = 0;
2116 ssh_userpass_input_buffer[ssh_userpass_input_buflen-1] = 0;
2121 if (ssh_userpass_input_bufpos > 0) {
2122 if (ssh_userpass_input_echo)
2123 c_write_str("\b \b");
2124 ssh_userpass_input_bufpos--;
2129 while (ssh_userpass_input_bufpos > 0) {
2130 if (ssh_userpass_input_echo)
2131 c_write_str("\b \b");
2132 ssh_userpass_input_bufpos--;
2140 if (((c >= ' ' && c <= '~') ||
2141 ((unsigned char) c >= 160))
2142 && ssh_userpass_input_bufpos < ssh_userpass_input_buflen-1) {
2143 ssh_userpass_input_buffer[ssh_userpass_input_bufpos++] = c;
2144 if (ssh_userpass_input_echo)
2154 * Handle the key exchange and user authentication phases.
2156 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
2160 static unsigned char *rsabuf, *keystr1, *keystr2;
2161 unsigned char cookie[8];
2162 struct RSAKey servkey, hostkey;
2163 struct MD5Context md5c;
2164 static unsigned long supported_ciphers_mask, supported_auths_mask;
2165 static int tried_publickey, tried_agent;
2166 static int tis_auth_refused, ccard_auth_refused;
2167 static unsigned char session_id[16];
2168 static int cipher_type;
2169 static char username[100];
2170 static void *publickey_blob;
2171 int publickey_bloblen;
2178 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2179 bombout(("Public key packet not received"));
2183 logevent("Received public keys");
2185 memcpy(cookie, pktin.body, 8);
2187 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
2188 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
2191 * Log the host key fingerprint.
2195 logevent("Host key fingerprint is:");
2196 strcpy(logmsg, " ");
2197 hostkey.comment = NULL;
2198 rsa_fingerprint(logmsg + strlen(logmsg),
2199 sizeof(logmsg) - strlen(logmsg), &hostkey);
2203 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
2204 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
2205 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
2207 ssh1_local_protoflags =
2208 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2209 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2212 MD5Update(&md5c, keystr2, hostkey.bytes);
2213 MD5Update(&md5c, keystr1, servkey.bytes);
2214 MD5Update(&md5c, pktin.body, 8);
2215 MD5Final(session_id, &md5c);
2217 for (i = 0; i < 32; i++)
2218 session_key[i] = random_byte();
2220 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2222 rsabuf = smalloc(len);
2224 fatalbox("Out of memory");
2227 * Verify the host key.
2231 * First format the key into a string.
2233 int len = rsastr_len(&hostkey);
2234 char fingerprint[100];
2235 char *keystr = smalloc(len);
2237 fatalbox("Out of memory");
2238 rsastr_fmt(keystr, &hostkey);
2239 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2240 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
2245 for (i = 0; i < 32; i++) {
2246 rsabuf[i] = session_key[i];
2248 rsabuf[i] ^= session_id[i];
2251 if (hostkey.bytes > servkey.bytes) {
2252 rsaencrypt(rsabuf, 32, &servkey);
2253 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
2255 rsaencrypt(rsabuf, 32, &hostkey);
2256 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
2259 logevent("Encrypted session key");
2262 int cipher_chosen = 0, warn = 0;
2263 char *cipher_string = NULL;
2264 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2265 int next_cipher = cfg.ssh_cipherlist[i];
2266 if (next_cipher == CIPHER_WARN) {
2267 /* If/when we choose a cipher, warn about it */
2269 } else if (next_cipher == CIPHER_AES) {
2270 /* XXX Probably don't need to mention this. */
2271 logevent("AES not supported in SSH1, skipping");
2273 switch (next_cipher) {
2274 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
2275 cipher_string = "3DES"; break;
2276 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
2277 cipher_string = "Blowfish"; break;
2278 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
2279 cipher_string = "single-DES"; break;
2281 if (supported_ciphers_mask & (1 << cipher_type))
2285 if (!cipher_chosen) {
2286 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2287 bombout(("Server violates SSH 1 protocol by not "
2288 "supporting 3DES encryption"));
2290 /* shouldn't happen */
2291 bombout(("No supported ciphers found"));
2295 /* Warn about chosen cipher if necessary. */
2297 askcipher(cipher_string, 0);
2300 switch (cipher_type) {
2301 case SSH_CIPHER_3DES:
2302 logevent("Using 3DES encryption");
2304 case SSH_CIPHER_DES:
2305 logevent("Using single-DES encryption");
2307 case SSH_CIPHER_BLOWFISH:
2308 logevent("Using Blowfish encryption");
2312 send_packet(SSH1_CMSG_SESSION_KEY,
2313 PKT_CHAR, cipher_type,
2314 PKT_DATA, cookie, 8,
2315 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
2316 PKT_DATA, rsabuf, len,
2317 PKT_INT, ssh1_local_protoflags, PKT_END);
2319 logevent("Trying to enable encryption...");
2323 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2324 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
2325 cipher->sesskey(session_key);
2329 if (pktin.type != SSH1_SMSG_SUCCESS) {
2330 bombout(("Encryption not successfully enabled"));
2334 logevent("Successfully started encryption");
2338 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2339 if (ssh_get_line && !ssh_getline_pw_only) {
2340 if (!ssh_get_line("login as: ",
2341 username, sizeof(username), FALSE)) {
2343 * get_line failed to get a username.
2346 logevent("No username provided. Abandoning session.");
2347 ssh_state = SSH_STATE_CLOSED;
2352 c_write_str("login as: ");
2355 setup_userpass_input(username, sizeof(username), 1);
2357 crWaitUntil(!ispkt);
2358 ret = process_userpass_input(in, inlen);
2362 c_write_str("\r\n");
2365 strncpy(username, cfg.username, sizeof(username));
2366 username[sizeof(username)-1] = '\0';
2369 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2371 char userlog[22 + sizeof(username)];
2372 sprintf(userlog, "Sent username \"%s\"", username);
2374 if (flags & FLAG_INTERACTIVE &&
2375 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2376 strcat(userlog, "\r\n");
2377 c_write_str(userlog);
2384 if ((ssh_remote_bugs & BUG_CHOKES_ON_RSA)) {
2385 /* We must not attempt PK auth. Pretend we've already tried it. */
2386 tried_publickey = tried_agent = 1;
2388 tried_publickey = tried_agent = 0;
2390 tis_auth_refused = ccard_auth_refused = 0;
2391 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2393 if (!rsakey_pubblob(cfg.keyfile, &publickey_blob, &publickey_bloblen))
2394 publickey_blob = NULL;
2396 publickey_blob = NULL;
2398 while (pktin.type == SSH1_SMSG_FAILURE) {
2399 static char password[100];
2400 static char prompt[200];
2403 static int pwpkt_type;
2404 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2406 if (agent_exists() && !tried_agent) {
2408 * Attempt RSA authentication using Pageant.
2410 static unsigned char request[5], *response, *p;
2411 static int responselen;
2412 static int i, nkeys;
2413 static int authed = FALSE;
2417 logevent("Pageant is running. Requesting keys.");
2419 /* Request the keys held by the agent. */
2420 PUT_32BIT(request, 1);
2421 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2422 agent_query(request, 5, &r, &responselen);
2423 response = (unsigned char *) r;
2424 if (response && responselen >= 5 &&
2425 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2427 nkeys = GET_32BIT(p);
2431 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2434 for (i = 0; i < nkeys; i++) {
2435 static struct RSAKey key;
2436 static Bignum challenge;
2437 static char *commentp;
2438 static int commentlen;
2442 sprintf(buf, "Trying Pageant key #%d", i);
2445 if (publickey_blob &&
2446 !memcmp(p, publickey_blob, publickey_bloblen)) {
2447 logevent("This key matches configured key file");
2448 tried_publickey = 1;
2451 p += ssh1_read_bignum(p, &key.exponent);
2452 p += ssh1_read_bignum(p, &key.modulus);
2453 commentlen = GET_32BIT(p);
2457 send_packet(SSH1_CMSG_AUTH_RSA,
2458 PKT_BIGNUM, key.modulus, PKT_END);
2460 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2461 logevent("Key refused");
2464 logevent("Received RSA challenge");
2465 ssh1_read_bignum(pktin.body, &challenge);
2467 char *agentreq, *q, *ret;
2470 len = 1 + 4; /* message type, bit count */
2471 len += ssh1_bignum_length(key.exponent);
2472 len += ssh1_bignum_length(key.modulus);
2473 len += ssh1_bignum_length(challenge);
2474 len += 16; /* session id */
2475 len += 4; /* response format */
2476 agentreq = smalloc(4 + len);
2477 PUT_32BIT(agentreq, len);
2479 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2480 PUT_32BIT(q, bignum_bitcount(key.modulus));
2482 q += ssh1_write_bignum(q, key.exponent);
2483 q += ssh1_write_bignum(q, key.modulus);
2484 q += ssh1_write_bignum(q, challenge);
2485 memcpy(q, session_id, 16);
2487 PUT_32BIT(q, 1); /* response format */
2488 agent_query(agentreq, len + 4, &vret, &retlen);
2492 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2493 logevent("Sending Pageant's response");
2494 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2495 PKT_DATA, ret + 5, 16,
2499 if (pktin.type == SSH1_SMSG_SUCCESS) {
2501 ("Pageant's response accepted");
2502 if (flags & FLAG_VERBOSE) {
2504 ("Authenticated using RSA key \"");
2505 c_write(commentp, commentlen);
2506 c_write_str("\" from agent\r\n");
2511 ("Pageant's response not accepted");
2514 ("Pageant failed to answer challenge");
2518 logevent("No reply received from Pageant");
2521 freebn(key.exponent);
2522 freebn(key.modulus);
2531 if (*cfg.keyfile && !tried_publickey)
2532 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2534 if (cfg.try_tis_auth &&
2535 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2536 !tis_auth_refused) {
2537 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2538 logevent("Requested TIS authentication");
2539 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2541 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2542 logevent("TIS authentication declined");
2543 if (flags & FLAG_INTERACTIVE)
2544 c_write_str("TIS authentication refused.\r\n");
2545 tis_auth_refused = 1;
2548 int challengelen = ((pktin.body[0] << 24) |
2549 (pktin.body[1] << 16) |
2550 (pktin.body[2] << 8) |
2552 logevent("Received TIS challenge");
2553 if (challengelen > sizeof(prompt) - 1)
2554 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2555 memcpy(prompt, pktin.body + 4, challengelen);
2556 /* Prompt heuristic comes from OpenSSH */
2557 strncpy(prompt + challengelen,
2558 memchr(prompt, '\n', challengelen) ?
2559 "": "\r\nResponse: ",
2560 (sizeof prompt) - challengelen);
2561 prompt[(sizeof prompt) - 1] = '\0';
2564 if (cfg.try_tis_auth &&
2565 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2566 !ccard_auth_refused) {
2567 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2568 logevent("Requested CryptoCard authentication");
2569 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2571 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2572 logevent("CryptoCard authentication declined");
2573 c_write_str("CryptoCard authentication refused.\r\n");
2574 ccard_auth_refused = 1;
2577 int challengelen = ((pktin.body[0] << 24) |
2578 (pktin.body[1] << 16) |
2579 (pktin.body[2] << 8) |
2581 logevent("Received CryptoCard challenge");
2582 if (challengelen > sizeof(prompt) - 1)
2583 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2584 memcpy(prompt, pktin.body + 4, challengelen);
2585 strncpy(prompt + challengelen,
2586 memchr(prompt, '\n', challengelen) ?
2587 "" : "\r\nResponse: ",
2588 sizeof(prompt) - challengelen);
2589 prompt[sizeof(prompt) - 1] = '\0';
2592 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2593 sprintf(prompt, "%.90s@%.90s's password: ",
2594 username, savedhost);
2596 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2597 char *comment = NULL;
2600 if (flags & FLAG_VERBOSE)
2601 c_write_str("Trying public key authentication.\r\n");
2602 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2604 type = key_type(cfg.keyfile);
2605 if (type != SSH_KEYTYPE_SSH1) {
2606 sprintf(msgbuf, "Key is of wrong type (%s)",
2607 key_type_to_str(type));
2609 c_write_str(msgbuf);
2610 c_write_str("\r\n");
2611 tried_publickey = 1;
2614 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2615 if (flags & FLAG_VERBOSE)
2616 c_write_str("No passphrase required.\r\n");
2619 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2624 * Show password prompt, having first obtained it via a TIS
2625 * or CryptoCard exchange if we're doing TIS or CryptoCard
2629 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2631 * get_line failed to get a password (for example
2632 * because one was supplied on the command line
2633 * which has already failed to work). Terminate.
2635 send_packet(SSH1_MSG_DISCONNECT,
2636 PKT_STR, "No more passwords available to try",
2638 logevent("Unable to authenticate");
2639 connection_fatal("Unable to authenticate");
2640 ssh_state = SSH_STATE_CLOSED;
2644 /* Prompt may have come from server. We've munged it a bit, so
2645 * we know it to be zero-terminated at least once. */
2647 c_write_untrusted(prompt, strlen(prompt));
2650 setup_userpass_input(password, sizeof(password), 0);
2652 crWaitUntil(!ispkt);
2653 ret = process_userpass_input(in, inlen);
2657 c_write_str("\r\n");
2661 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2663 * Try public key authentication with the specified
2666 static struct RSAKey pubkey;
2667 static Bignum challenge, response;
2669 static unsigned char buffer[32];
2671 tried_publickey = 1;
2672 i = loadrsakey(cfg.keyfile, &pubkey, password);
2674 c_write_str("Couldn't load private key from ");
2675 c_write_str(cfg.keyfile);
2676 c_write_str(".\r\n");
2677 continue; /* go and try password */
2680 c_write_str("Wrong passphrase.\r\n");
2681 tried_publickey = 0;
2682 continue; /* try again */
2686 * Send a public key attempt.
2688 send_packet(SSH1_CMSG_AUTH_RSA,
2689 PKT_BIGNUM, pubkey.modulus, PKT_END);
2692 if (pktin.type == SSH1_SMSG_FAILURE) {
2693 c_write_str("Server refused our public key.\r\n");
2694 continue; /* go and try password */
2696 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2697 bombout(("Bizarre response to offer of public key"));
2700 ssh1_read_bignum(pktin.body, &challenge);
2701 response = rsadecrypt(challenge, &pubkey);
2702 freebn(pubkey.private_exponent); /* burn the evidence */
2704 for (i = 0; i < 32; i++) {
2705 buffer[i] = bignum_byte(response, 31 - i);
2709 MD5Update(&md5c, buffer, 32);
2710 MD5Update(&md5c, session_id, 16);
2711 MD5Final(buffer, &md5c);
2713 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2714 PKT_DATA, buffer, 16, PKT_END);
2717 if (pktin.type == SSH1_SMSG_FAILURE) {
2718 if (flags & FLAG_VERBOSE)
2720 ("Failed to authenticate with our public key.\r\n");
2721 continue; /* go and try password */
2722 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2724 ("Bizarre response to RSA authentication response"));
2728 break; /* we're through! */
2730 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2732 * Defence against traffic analysis: we send a
2733 * whole bunch of packets containing strings of
2734 * different lengths. One of these strings is the
2735 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2736 * The others are all random data in
2737 * SSH1_MSG_IGNORE packets. This way a passive
2738 * listener can't tell which is the password, and
2739 * hence can't deduce the password length.
2741 * Anybody with a password length greater than 16
2742 * bytes is going to have enough entropy in their
2743 * password that a listener won't find it _that_
2744 * much help to know how long it is. So what we'll
2747 * - if password length < 16, we send 15 packets
2748 * containing string lengths 1 through 15
2750 * - otherwise, we let N be the nearest multiple
2751 * of 8 below the password length, and send 8
2752 * packets containing string lengths N through
2753 * N+7. This won't obscure the order of
2754 * magnitude of the password length, but it will
2755 * introduce a bit of extra uncertainty.
2757 * A few servers (the old 1.2.18 through 1.2.22)
2758 * can't deal with SSH1_MSG_IGNORE. For these
2759 * servers, we need an alternative defence. We make
2760 * use of the fact that the password is interpreted
2761 * as a C string: so we can append a NUL, then some
2764 * One server (a Cisco one) can deal with neither
2765 * SSH1_MSG_IGNORE _nor_ a padded password string.
2766 * For this server we are left with no defences
2767 * against password length sniffing.
2769 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2771 * The server can deal with SSH1_MSG_IGNORE, so
2772 * we can use the primary defence.
2774 int bottom, top, pwlen, i;
2777 pwlen = strlen(password);
2779 bottom = 0; /* zero length passwords are OK! :-) */
2782 bottom = pwlen & ~7;
2786 assert(pwlen >= bottom && pwlen <= top);
2788 randomstr = smalloc(top + 1);
2790 for (i = bottom; i <= top; i++) {
2792 defer_packet(pwpkt_type, PKT_STR, password,
2795 for (j = 0; j < i; j++) {
2797 randomstr[j] = random_byte();
2798 } while (randomstr[j] == '\0');
2800 randomstr[i] = '\0';
2801 defer_packet(SSH1_MSG_IGNORE,
2802 PKT_STR, randomstr, PKT_END);
2805 logevent("Sending password with camouflage packets");
2806 ssh_pkt_defersend();
2808 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2810 * The server can't deal with SSH1_MSG_IGNORE
2811 * but can deal with padded passwords, so we
2812 * can use the secondary defence.
2818 len = strlen(password);
2819 if (len < sizeof(string)) {
2821 strcpy(string, password);
2822 len++; /* cover the zero byte */
2823 while (len < sizeof(string)) {
2824 string[len++] = (char) random_byte();
2829 logevent("Sending length-padded password");
2830 send_packet(pwpkt_type, PKT_INT, len,
2831 PKT_DATA, s, len, PKT_END);
2834 * The server has _both_
2835 * BUG_CHOKES_ON_SSH1_IGNORE and
2836 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2837 * therefore nothing we can do.
2840 len = strlen(password);
2841 logevent("Sending unpadded password");
2842 send_packet(pwpkt_type, PKT_INT, len,
2843 PKT_DATA, password, len, PKT_END);
2846 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2849 logevent("Sent password");
2850 memset(password, 0, strlen(password));
2852 if (pktin.type == SSH1_SMSG_FAILURE) {
2853 if (flags & FLAG_VERBOSE)
2854 c_write_str("Access denied\r\n");
2855 logevent("Authentication refused");
2856 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2857 logevent("Received disconnect request");
2858 ssh_state = SSH_STATE_CLOSED;
2860 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2861 bombout(("Strange packet received, type %d", pktin.type));
2866 logevent("Authentication successful");
2871 void sshfwd_close(struct ssh_channel *c)
2873 if (c && !c->closes) {
2875 * If the channel's remoteid is -1, we have sent
2876 * CHANNEL_OPEN for this channel, but it hasn't even been
2877 * acknowledged by the server. So we must set a close flag
2878 * on it now, and then when the server acks the channel
2879 * open, we can close it then.
2881 if (((int)c->remoteid) != -1) {
2882 if (ssh_version == 1) {
2883 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2886 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2887 ssh2_pkt_adduint32(c->remoteid);
2892 if (c->type == CHAN_X11) {
2894 logevent("Forwarded X11 connection terminated");
2895 } else if (c->type == CHAN_SOCKDATA ||
2896 c->type == CHAN_SOCKDATA_DORMANT) {
2898 logevent("Forwarded port closed");
2903 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2905 if (ssh_version == 1) {
2906 send_packet(SSH1_MSG_CHANNEL_DATA,
2907 PKT_INT, c->remoteid,
2908 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2910 * In SSH1 we can return 0 here - implying that forwarded
2911 * connections are never individually throttled - because
2912 * the only circumstance that can cause throttling will be
2913 * the whole SSH connection backing up, in which case
2914 * _everything_ will be throttled as a whole.
2918 ssh2_add_channel_data(c, buf, len);
2919 return ssh2_try_send(c);
2923 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2925 if (ssh_version == 1) {
2926 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2927 c->v.v1.throttling = 0;
2931 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2935 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2941 while (!do_ssh1_login(in, inlen, ispkt)) {
2944 if (ssh_state == SSH_STATE_CLOSED)
2947 if (cfg.agentfwd && agent_exists()) {
2948 logevent("Requesting agent forwarding");
2949 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2953 if (pktin.type != SSH1_SMSG_SUCCESS
2954 && pktin.type != SSH1_SMSG_FAILURE) {
2955 bombout(("Protocol confusion"));
2957 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2958 logevent("Agent forwarding refused");
2960 logevent("Agent forwarding enabled");
2961 ssh_agentfwd_enabled = TRUE;
2965 if (cfg.x11_forward) {
2966 char proto[20], data[64];
2967 logevent("Requesting X11 forwarding");
2968 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2969 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2970 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2971 PKT_STR, proto, PKT_STR, data,
2972 PKT_INT, 0, PKT_END);
2974 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2975 PKT_STR, proto, PKT_STR, data, PKT_END);
2980 if (pktin.type != SSH1_SMSG_SUCCESS
2981 && pktin.type != SSH1_SMSG_FAILURE) {
2982 bombout(("Protocol confusion"));
2984 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2985 logevent("X11 forwarding refused");
2987 logevent("X11 forwarding enabled");
2988 ssh_X11_fwd_enabled = TRUE;
2996 int sport,dport,sserv,dserv;
2997 char sports[256], dports[256], host[256];
3001 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
3002 /* Add port forwardings. */
3007 while (*e && *e != '\t')
3013 while (*e && *e != ':')
3023 dport = atoi(dports);
3027 se = getservbyname(dports, NULL);
3029 dport = ntohs(se->s_port);
3032 "Service lookup failed for destination port \"%s\"",
3037 sport = atoi(sports);
3041 se = getservbyname(sports, NULL);
3043 sport = ntohs(se->s_port);
3046 "Service lookup failed for source port \"%s\"",
3051 if (sport && dport) {
3053 pfd_addforward(host, dport, sport);
3054 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3055 " %s:%.*s%.*s%d%.*s",
3056 sserv ? strlen(sports) : 0, sports,
3057 sserv, "(", sport, sserv, ")",
3059 dserv ? strlen(dports) : 0, dports,
3060 dserv, "(", dport, dserv, ")");
3063 struct ssh_rportfwd *pf;
3064 pf = smalloc(sizeof(*pf));
3065 strcpy(pf->dhost, host);
3067 if (add234(ssh_rportfwds, pf) != pf) {
3069 "Duplicate remote port forwarding to %s:%d",
3074 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3075 " forward to %s:%.*s%.*s%d%.*s",
3076 sserv ? strlen(sports) : 0, sports,
3077 sserv, "(", sport, sserv, ")",
3079 dserv ? strlen(dports) : 0, dports,
3080 dserv, "(", dport, dserv, ")");
3082 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
3090 if (pktin.type != SSH1_SMSG_SUCCESS
3091 && pktin.type != SSH1_SMSG_FAILURE) {
3092 bombout(("Protocol confusion"));
3094 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3095 c_write_str("Server refused port forwarding\r\n");
3096 ssh_editing = ssh_echoing = 1;
3098 logevent("Remote port forwarding enabled");
3106 send_packet(SSH1_CMSG_REQUEST_PTY,
3107 PKT_STR, cfg.termtype,
3108 PKT_INT, rows, PKT_INT, cols,
3109 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3110 ssh_state = SSH_STATE_INTERMED;
3114 if (pktin.type != SSH1_SMSG_SUCCESS
3115 && pktin.type != SSH1_SMSG_FAILURE) {
3116 bombout(("Protocol confusion"));
3118 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3119 c_write_str("Server refused to allocate pty\r\n");
3120 ssh_editing = ssh_echoing = 1;
3122 logevent("Allocated pty");
3124 ssh_editing = ssh_echoing = 1;
3127 if (cfg.compression) {
3128 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3132 if (pktin.type != SSH1_SMSG_SUCCESS
3133 && pktin.type != SSH1_SMSG_FAILURE) {
3134 bombout(("Protocol confusion"));
3136 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3137 c_write_str("Server refused to compress\r\n");
3139 logevent("Started compression");
3140 ssh1_compressing = TRUE;
3141 zlib_compress_init();
3142 zlib_decompress_init();
3146 * Start the shell or command.
3148 * Special case: if the first-choice command is an SSH2
3149 * subsystem (hence not usable here) and the second choice
3150 * exists, we fall straight back to that.
3153 char *cmd = cfg.remote_cmd_ptr;
3155 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3156 cmd = cfg.remote_cmd_ptr2;
3157 ssh_fallback_cmd = TRUE;
3160 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3162 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
3163 logevent("Started session");
3166 ssh_state = SSH_STATE_SESSION;
3170 ssh_special(TS_EOF);
3172 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
3174 ssh_channels = newtree234(ssh_channelcmp);
3178 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
3179 pktin.type == SSH1_SMSG_STDERR_DATA) {
3180 long len = GET_32BIT(pktin.body);
3182 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
3183 pktin.body + 4, len);
3184 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3185 ssh1_stdout_throttling = 1;
3188 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
3189 ssh_state = SSH_STATE_CLOSED;
3190 logevent("Received disconnect request");
3192 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
3193 /* Remote side is trying to open a channel to talk to our
3194 * X-Server. Give them back a local channel number. */
3195 struct ssh_channel *c;
3197 logevent("Received X11 connect request");
3198 /* Refuse if X11 forwarding is disabled. */
3199 if (!ssh_X11_fwd_enabled) {
3200 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3201 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3202 logevent("Rejected X11 connect request");
3204 c = smalloc(sizeof(struct ssh_channel));
3206 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3207 logevent("opening X11 forward connection failed");
3209 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3210 PKT_INT, GET_32BIT(pktin.body),
3214 ("opening X11 forward connection succeeded");
3215 c->remoteid = GET_32BIT(pktin.body);
3216 c->localid = alloc_channel_id();
3218 c->v.v1.throttling = 0;
3219 c->type = CHAN_X11; /* identify channel type */
3220 add234(ssh_channels, c);
3221 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3222 PKT_INT, c->remoteid, PKT_INT,
3223 c->localid, PKT_END);
3224 logevent("Opened X11 forward channel");
3227 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
3228 /* Remote side is trying to open a channel to talk to our
3229 * agent. Give them back a local channel number. */
3230 struct ssh_channel *c;
3232 /* Refuse if agent forwarding is disabled. */
3233 if (!ssh_agentfwd_enabled) {
3234 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3235 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3237 c = smalloc(sizeof(struct ssh_channel));
3238 c->remoteid = GET_32BIT(pktin.body);
3239 c->localid = alloc_channel_id();
3241 c->v.v1.throttling = 0;
3242 c->type = CHAN_AGENT; /* identify channel type */
3243 c->u.a.lensofar = 0;
3244 add234(ssh_channels, c);
3245 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3246 PKT_INT, c->remoteid, PKT_INT, c->localid,
3249 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
3250 /* Remote side is trying to open a channel to talk to a
3251 * forwarded port. Give them back a local channel number. */
3252 struct ssh_channel *c;
3253 struct ssh_rportfwd pf;
3255 char host[256], buf[1024];
3257 c = smalloc(sizeof(struct ssh_channel));
3259 hostsize = GET_32BIT(pktin.body+4);
3260 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
3261 if (h+1 < host+sizeof(host))
3266 port = GET_32BIT(p);
3268 strcpy(pf.dhost, host);
3271 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
3272 sprintf(buf, "Rejected remote port open request for %s:%d",
3275 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3276 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3278 sprintf(buf, "Received remote port open request for %s:%d",
3281 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3284 sprintf(buf, "Port open failed: %s", e);
3287 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3288 PKT_INT, GET_32BIT(pktin.body),
3291 c->remoteid = GET_32BIT(pktin.body);
3292 c->localid = alloc_channel_id();
3294 c->v.v1.throttling = 0;
3295 c->type = CHAN_SOCKDATA; /* identify channel type */
3296 add234(ssh_channels, c);
3297 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3298 PKT_INT, c->remoteid, PKT_INT,
3299 c->localid, PKT_END);
3300 logevent("Forwarded port opened successfully");
3304 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3305 unsigned int remoteid = GET_32BIT(pktin.body);
3306 unsigned int localid = GET_32BIT(pktin.body+4);
3307 struct ssh_channel *c;
3309 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3310 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3311 c->remoteid = localid;
3312 c->type = CHAN_SOCKDATA;
3313 c->v.v1.throttling = 0;
3314 pfd_confirm(c->u.pfd.s);
3317 if (c && c->closes) {
3319 * We have a pending close on this channel,
3320 * which we decided on before the server acked
3321 * the channel open. So now we know the
3322 * remoteid, we can close it again.
3324 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3328 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3329 unsigned int remoteid = GET_32BIT(pktin.body);
3330 unsigned int localid = GET_32BIT(pktin.body+4);
3331 struct ssh_channel *c;
3333 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3334 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3335 logevent("Forwarded connection refused by server");
3336 pfd_close(c->u.pfd.s);
3337 del234(ssh_channels, c);
3341 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3342 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3343 /* Remote side closes a channel. */
3344 unsigned i = GET_32BIT(pktin.body);
3345 struct ssh_channel *c;
3346 c = find234(ssh_channels, &i, ssh_channelfind);
3350 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3351 if (!(c->closes & closetype))
3352 send_packet(pktin.type, PKT_INT, c->remoteid,
3354 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3355 logevent("Forwarded X11 connection terminated");
3356 assert(c->u.x11.s != NULL);
3357 x11_close(c->u.x11.s);
3360 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3361 logevent("Forwarded port closed");
3362 assert(c->u.pfd.s != NULL);
3363 pfd_close(c->u.pfd.s);
3366 c->closes |= closetype;
3367 if (c->closes == 3) {
3368 del234(ssh_channels, c);
3372 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
3373 /* Data sent down one of our channels. */
3374 int i = GET_32BIT(pktin.body);
3375 int len = GET_32BIT(pktin.body + 4);
3376 unsigned char *p = pktin.body + 8;
3377 struct ssh_channel *c;
3378 c = find234(ssh_channels, &i, ssh_channelfind);
3383 bufsize = x11_send(c->u.x11.s, p, len);
3386 bufsize = pfd_send(c->u.pfd.s, p, len);
3389 /* Data for an agent message. Buffer it. */
3391 if (c->u.a.lensofar < 4) {
3392 int l = min(4 - c->u.a.lensofar, len);
3393 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3397 c->u.a.lensofar += l;
3399 if (c->u.a.lensofar == 4) {
3401 4 + GET_32BIT(c->u.a.msglen);
3402 c->u.a.message = smalloc(c->u.a.totallen);
3403 memcpy(c->u.a.message, c->u.a.msglen, 4);
3405 if (c->u.a.lensofar >= 4 && len > 0) {
3407 min(c->u.a.totallen - c->u.a.lensofar,
3409 memcpy(c->u.a.message + c->u.a.lensofar, p,
3413 c->u.a.lensofar += l;
3415 if (c->u.a.lensofar == c->u.a.totallen) {
3416 void *reply, *sentreply;
3418 agent_query(c->u.a.message,
3419 c->u.a.totallen, &reply,
3424 /* Fake SSH_AGENT_FAILURE. */
3425 sentreply = "\0\0\0\1\5";
3428 send_packet(SSH1_MSG_CHANNEL_DATA,
3429 PKT_INT, c->remoteid,
3431 PKT_DATA, sentreply, replylen,
3435 sfree(c->u.a.message);
3436 c->u.a.lensofar = 0;
3439 bufsize = 0; /* agent channels never back up */
3442 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3443 c->v.v1.throttling = 1;
3447 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3448 /* may be from EXEC_SHELL on some servers */
3449 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3450 /* may be from EXEC_SHELL on some servers
3451 * if no pty is available or in other odd cases. Ignore */
3452 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3454 ssh_exitcode = GET_32BIT(pktin.body);
3455 sprintf(buf, "Server sent command exit status %d",
3458 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3460 * In case `helpful' firewalls or proxies tack
3461 * extra human-readable text on the end of the
3462 * session which we might mistake for another
3463 * encrypted packet, we close the session once
3464 * we've sent EXIT_CONFIRMATION.
3466 ssh_state = SSH_STATE_CLOSED;
3469 bombout(("Strange packet received: type %d", pktin.type));
3474 int len = min(inlen, 512);
3475 send_packet(SSH1_CMSG_STDIN_DATA,
3476 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3487 * Utility routine for decoding comma-separated strings in KEXINIT.
3489 static int in_commasep_string(char *needle, char *haystack, int haylen)
3491 int needlen = strlen(needle);
3494 * Is it at the start of the string?
3496 if (haylen >= needlen && /* haystack is long enough */
3497 !memcmp(needle, haystack, needlen) && /* initial match */
3498 (haylen == needlen || haystack[needlen] == ',')
3499 /* either , or EOS follows */
3503 * If not, search for the next comma and resume after that.
3504 * If no comma found, terminate.
3506 while (haylen > 0 && *haystack != ',')
3507 haylen--, haystack++;
3510 haylen--, haystack++; /* skip over comma itself */
3515 * SSH2 key creation method.
3517 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3521 /* First 20 bytes. */
3523 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3525 SHA_Bytes(&s, H, 20);
3526 SHA_Bytes(&s, &chr, 1);
3527 SHA_Bytes(&s, sessid, 20);
3528 SHA_Final(&s, keyspace);
3529 /* Next 20 bytes. */
3531 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3533 SHA_Bytes(&s, H, 20);
3534 SHA_Bytes(&s, keyspace, 20);
3535 SHA_Final(&s, keyspace + 20);
3539 * Handle the SSH2 transport layer.
3541 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3543 static int i, j, len, nbits, pbits, warn;
3545 static Bignum p, g, e, f, K;
3546 static int kex_init_value, kex_reply_value;
3547 static const struct ssh_mac **maclist;
3549 static const struct ssh2_cipher *cscipher_tobe = NULL;
3550 static const struct ssh2_cipher *sccipher_tobe = NULL;
3551 static const struct ssh_mac *csmac_tobe = NULL;
3552 static const struct ssh_mac *scmac_tobe = NULL;
3553 static const struct ssh_compress *cscomp_tobe = NULL;
3554 static const struct ssh_compress *sccomp_tobe = NULL;
3555 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3556 static int hostkeylen, siglen;
3557 static void *hkey; /* actual host key */
3558 static unsigned char exchange_hash[20];
3559 static unsigned char keyspace[40];
3560 static int n_preferred_ciphers;
3561 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3562 static const struct ssh_compress *preferred_comp;
3563 static int cipherstr_started;
3564 static int first_kex;
3571 * Set up the preferred ciphers. (NULL => warn below here)
3573 n_preferred_ciphers = 0;
3574 for (i = 0; i < CIPHER_MAX; i++) {
3575 switch (cfg.ssh_cipherlist[i]) {
3576 case CIPHER_BLOWFISH:
3577 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3578 n_preferred_ciphers++;
3581 if (cfg.ssh2_des_cbc) {
3582 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3583 n_preferred_ciphers++;
3587 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3588 n_preferred_ciphers++;
3591 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3592 n_preferred_ciphers++;
3595 /* Flag for later. Don't bother if it's the last in
3597 if (i < CIPHER_MAX - 1) {
3598 preferred_ciphers[n_preferred_ciphers] = NULL;
3599 n_preferred_ciphers++;
3606 * Set up preferred compression.
3608 if (cfg.compression)
3609 preferred_comp = &ssh_zlib;
3611 preferred_comp = &ssh_comp_none;
3614 * Be prepared to work around the buggy MAC problem.
3616 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3617 maclist = buggymacs, nmacs = lenof(buggymacs);
3619 maclist = macs, nmacs = lenof(macs);
3623 * Construct and send our key exchange packet.
3625 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3626 for (i = 0; i < 16; i++)
3627 ssh2_pkt_addbyte((unsigned char) random_byte());
3628 /* List key exchange algorithms. */
3629 ssh2_pkt_addstring_start();
3630 for (i = 0; i < lenof(kex_algs); i++) {
3631 ssh2_pkt_addstring_str(kex_algs[i]->name);
3632 if (i < lenof(kex_algs) - 1)
3633 ssh2_pkt_addstring_str(",");
3635 /* List server host key algorithms. */
3636 ssh2_pkt_addstring_start();
3637 for (i = 0; i < lenof(hostkey_algs); i++) {
3638 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3639 if (i < lenof(hostkey_algs) - 1)
3640 ssh2_pkt_addstring_str(",");
3642 /* List client->server encryption algorithms. */
3643 ssh2_pkt_addstring_start();
3644 cipherstr_started = 0;
3645 for (i = 0; i < n_preferred_ciphers; i++) {
3646 const struct ssh2_ciphers *c = preferred_ciphers[i];
3647 if (!c) continue; /* warning flag */
3648 for (j = 0; j < c->nciphers; j++) {
3649 if (cipherstr_started)
3650 ssh2_pkt_addstring_str(",");
3651 ssh2_pkt_addstring_str(c->list[j]->name);
3652 cipherstr_started = 1;
3655 /* List server->client encryption algorithms. */
3656 ssh2_pkt_addstring_start();
3657 cipherstr_started = 0;
3658 for (i = 0; i < n_preferred_ciphers; i++) {
3659 const struct ssh2_ciphers *c = preferred_ciphers[i];
3660 if (!c) continue; /* warning flag */
3661 for (j = 0; j < c->nciphers; j++) {
3662 if (cipherstr_started)
3663 ssh2_pkt_addstring_str(",");
3664 ssh2_pkt_addstring_str(c->list[j]->name);
3665 cipherstr_started = 1;
3668 /* List client->server MAC algorithms. */
3669 ssh2_pkt_addstring_start();
3670 for (i = 0; i < nmacs; i++) {
3671 ssh2_pkt_addstring_str(maclist[i]->name);
3673 ssh2_pkt_addstring_str(",");
3675 /* List server->client MAC algorithms. */
3676 ssh2_pkt_addstring_start();
3677 for (i = 0; i < nmacs; i++) {
3678 ssh2_pkt_addstring_str(maclist[i]->name);
3680 ssh2_pkt_addstring_str(",");
3682 /* List client->server compression algorithms. */
3683 ssh2_pkt_addstring_start();
3684 for (i = 0; i < lenof(compressions) + 1; i++) {
3685 const struct ssh_compress *c =
3686 i == 0 ? preferred_comp : compressions[i - 1];
3687 ssh2_pkt_addstring_str(c->name);
3688 if (i < lenof(compressions))
3689 ssh2_pkt_addstring_str(",");
3691 /* List server->client compression algorithms. */
3692 ssh2_pkt_addstring_start();
3693 for (i = 0; i < lenof(compressions) + 1; i++) {
3694 const struct ssh_compress *c =
3695 i == 0 ? preferred_comp : compressions[i - 1];
3696 ssh2_pkt_addstring_str(c->name);
3697 if (i < lenof(compressions))
3698 ssh2_pkt_addstring_str(",");
3700 /* List client->server languages. Empty list. */
3701 ssh2_pkt_addstring_start();
3702 /* List server->client languages. Empty list. */
3703 ssh2_pkt_addstring_start();
3704 /* First KEX packet does _not_ follow, because we're not that brave. */
3705 ssh2_pkt_addbool(FALSE);
3707 ssh2_pkt_adduint32(0);
3709 exhash = exhashbase;
3710 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3716 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3719 * Now examine the other side's KEXINIT to see what we're up
3722 if (pktin.type != SSH2_MSG_KEXINIT) {
3723 bombout(("expected key exchange packet from server"));
3728 cscipher_tobe = NULL;
3729 sccipher_tobe = NULL;
3734 pktin.savedpos += 16; /* skip garbage cookie */
3735 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3736 for (i = 0; i < lenof(kex_algs); i++) {
3737 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3742 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3743 for (i = 0; i < lenof(hostkey_algs); i++) {
3744 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3745 hostkey = hostkey_algs[i];
3749 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3751 for (i = 0; i < n_preferred_ciphers; i++) {
3752 const struct ssh2_ciphers *c = preferred_ciphers[i];
3756 for (j = 0; j < c->nciphers; j++) {
3757 if (in_commasep_string(c->list[j]->name, str, len)) {
3758 cscipher_tobe = c->list[j];
3763 if (cscipher_tobe) {
3765 askcipher(cscipher_tobe->name, 1);
3769 if (!cscipher_tobe) {
3770 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3774 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3776 for (i = 0; i < n_preferred_ciphers; i++) {
3777 const struct ssh2_ciphers *c = preferred_ciphers[i];
3781 for (j = 0; j < c->nciphers; j++) {
3782 if (in_commasep_string(c->list[j]->name, str, len)) {
3783 sccipher_tobe = c->list[j];
3788 if (sccipher_tobe) {
3790 askcipher(sccipher_tobe->name, 2);
3794 if (!sccipher_tobe) {
3795 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3799 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3800 for (i = 0; i < nmacs; i++) {
3801 if (in_commasep_string(maclist[i]->name, str, len)) {
3802 csmac_tobe = maclist[i];
3806 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3807 for (i = 0; i < nmacs; i++) {
3808 if (in_commasep_string(maclist[i]->name, str, len)) {
3809 scmac_tobe = maclist[i];
3813 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3814 for (i = 0; i < lenof(compressions) + 1; i++) {
3815 const struct ssh_compress *c =
3816 i == 0 ? preferred_comp : compressions[i - 1];
3817 if (in_commasep_string(c->name, str, len)) {
3822 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3823 for (i = 0; i < lenof(compressions) + 1; i++) {
3824 const struct ssh_compress *c =
3825 i == 0 ? preferred_comp : compressions[i - 1];
3826 if (in_commasep_string(c->name, str, len)) {
3833 * Work out the number of bits of key we will need from the key
3834 * exchange. We start with the maximum key length of either
3840 csbits = cscipher_tobe->keylen;
3841 scbits = sccipher_tobe->keylen;
3842 nbits = (csbits > scbits ? csbits : scbits);
3844 /* The keys only have 160-bit entropy, since they're based on
3845 * a SHA-1 hash. So cap the key size at 160 bits. */
3850 * If we're doing Diffie-Hellman group exchange, start by
3851 * requesting a group.
3853 if (kex == &ssh_diffiehellman_gex) {
3854 logevent("Doing Diffie-Hellman group exchange");
3855 ssh_pkt_ctx |= SSH2_PKTCTX_DHGEX;
3857 * Work out how big a DH group we will need to allow that
3860 pbits = 512 << ((nbits - 1) / 64);
3861 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3862 ssh2_pkt_adduint32(pbits);
3866 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3867 bombout(("expected key exchange group packet from server"));
3870 p = ssh2_pkt_getmp();
3871 g = ssh2_pkt_getmp();
3872 dh_setup_group(p, g);
3873 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3874 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3876 ssh_pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3878 kex_init_value = SSH2_MSG_KEXDH_INIT;
3879 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3882 logevent("Doing Diffie-Hellman key exchange");
3884 * Now generate and send e for Diffie-Hellman.
3886 e = dh_create_e(nbits * 2);
3887 ssh2_pkt_init(kex_init_value);
3892 if (pktin.type != kex_reply_value) {
3893 bombout(("expected key exchange reply packet from server"));
3896 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3897 f = ssh2_pkt_getmp();
3898 ssh2_pkt_getstring(&sigdata, &siglen);
3902 sha_string(&exhash, hostkeydata, hostkeylen);
3903 if (kex == &ssh_diffiehellman_gex) {
3904 sha_uint32(&exhash, pbits);
3905 sha_mpint(&exhash, p);
3906 sha_mpint(&exhash, g);
3908 sha_mpint(&exhash, e);
3909 sha_mpint(&exhash, f);
3910 sha_mpint(&exhash, K);
3911 SHA_Final(&exhash, exchange_hash);
3916 debug(("Exchange hash is:\n"));
3917 dmemdump(exchange_hash, 20);
3920 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3922 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3923 bombout(("Server's host key did not match the signature supplied"));
3928 * Authenticate remote host: verify host key. (We've already
3929 * checked the signature of the exchange hash.)
3931 keystr = hostkey->fmtkey(hkey);
3932 fingerprint = hostkey->fingerprint(hkey);
3933 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3934 keystr, fingerprint);
3935 if (first_kex) { /* don't bother logging this in rekeys */
3936 logevent("Host key fingerprint is:");
3937 logevent(fingerprint);
3941 hostkey->freekey(hkey);
3944 * Send SSH2_MSG_NEWKEYS.
3946 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3950 * Expect SSH2_MSG_NEWKEYS from server.
3953 if (pktin.type != SSH2_MSG_NEWKEYS) {
3954 bombout(("expected new-keys packet from server"));
3959 * Create and initialise session keys.
3961 cscipher = cscipher_tobe;
3962 sccipher = sccipher_tobe;
3965 cscomp = cscomp_tobe;
3966 sccomp = sccomp_tobe;
3967 cscomp->compress_init();
3968 sccomp->decompress_init();
3970 * Set IVs after keys. Here we use the exchange hash from the
3971 * _first_ key exchange.
3974 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3975 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3976 cscipher->setcskey(keyspace);
3977 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3978 sccipher->setsckey(keyspace);
3979 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
3980 cscipher->setcsiv(keyspace);
3981 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
3982 sccipher->setsciv(keyspace);
3983 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
3984 csmac->setcskey(keyspace);
3985 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
3986 scmac->setsckey(keyspace);
3989 * If this is the first key exchange phase, we must pass the
3990 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3991 * wants to see it but because it will need time to initialise
3992 * itself before it sees an actual packet. In subsequent key
3993 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3994 * it would only confuse the layer above.
4002 * Now we're encrypting. Begin returning 1 to the protocol main
4003 * function so that other things can run on top of the
4004 * transport. If we ever see a KEXINIT, we must go back to the
4007 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
4010 logevent("Server initiated key re-exchange");
4011 goto begin_key_exchange;
4017 * Add data to an SSH2 channel output buffer.
4019 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4022 bufchain_add(&c->v.v2.outbuffer, buf, len);
4026 * Attempt to send data on an SSH2 channel.
4028 static int ssh2_try_send(struct ssh_channel *c)
4030 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4033 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4034 if ((unsigned)len > c->v.v2.remwindow)
4035 len = c->v.v2.remwindow;
4036 if ((unsigned)len > c->v.v2.remmaxpkt)
4037 len = c->v.v2.remmaxpkt;
4038 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4039 ssh2_pkt_adduint32(c->remoteid);
4040 ssh2_pkt_addstring_start();
4041 ssh2_pkt_addstring_data(data, len);
4043 bufchain_consume(&c->v.v2.outbuffer, len);
4044 c->v.v2.remwindow -= len;
4048 * After having sent as much data as we can, return the amount
4051 return bufchain_size(&c->v.v2.outbuffer);
4055 * Potentially enlarge the window on an SSH2 channel.
4057 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4060 * Never send WINDOW_ADJUST for a channel that the remote side
4061 * already thinks it's closed; there's no point, since it won't
4062 * be sending any more data anyway.
4067 if (newwin > c->v.v2.locwindow) {
4068 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4069 ssh2_pkt_adduint32(c->remoteid);
4070 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
4072 c->v.v2.locwindow = newwin;
4077 * Handle the SSH2 userauth and connection layers.
4079 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
4082 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4084 AUTH_KEYBOARD_INTERACTIVE
4088 AUTH_TYPE_PUBLICKEY,
4089 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4090 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4092 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4093 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4095 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4096 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
4097 static int kbd_inter_running;
4098 static int we_are_in;
4099 static int num_prompts, curr_prompt, echo;
4100 static char username[100];
4101 static int got_username;
4102 static char pwprompt[200];
4103 static char password[100];
4104 static void *publickey_blob;
4105 static int publickey_bloblen;
4110 * Request userauth protocol, and await a response to it.
4112 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
4113 ssh2_pkt_addstring("ssh-userauth");
4115 crWaitUntilV(ispkt);
4116 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4117 bombout(("Server refused user authentication protocol"));
4122 * We repeat this whole loop, including the username prompt,
4123 * until we manage a successful authentication. If the user
4124 * types the wrong _password_, they are sent back to the
4125 * beginning to try another username. (If they specify a
4126 * username in the config, they are never asked, even if they
4127 * do give a wrong password.)
4129 * I think this best serves the needs of
4131 * - the people who have no configuration, no keys, and just
4132 * want to try repeated (username,password) pairs until they
4133 * type both correctly
4135 * - people who have keys and configuration but occasionally
4136 * need to fall back to passwords
4138 * - people with a key held in Pageant, who might not have
4139 * logged in to a particular machine before; so they want to
4140 * type a username, and then _either_ their key will be
4141 * accepted, _or_ they will type a password. If they mistype
4142 * the username they will want to be able to get back and
4146 got_username = FALSE;
4151 if (got_username && !cfg.change_username) {
4153 * We got a username last time round this loop, and
4154 * with change_username turned off we don't try to get
4157 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4158 if (ssh_get_line && !ssh_getline_pw_only) {
4159 if (!ssh_get_line("login as: ",
4160 username, sizeof(username), FALSE)) {
4162 * get_line failed to get a username.
4165 logevent("No username provided. Abandoning session.");
4166 ssh_state = SSH_STATE_CLOSED;
4171 c_write_str("login as: ");
4173 setup_userpass_input(username, sizeof(username), 1);
4175 crWaitUntilV(!ispkt);
4176 ret = process_userpass_input(in, inlen);
4181 c_write_str("\r\n");
4182 username[strcspn(username, "\n\r")] = '\0';
4185 strncpy(username, cfg.username, sizeof(username));
4186 username[sizeof(username)-1] = '\0';
4187 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4188 sprintf(stuff, "Using username \"%s\".\r\n", username);
4192 got_username = TRUE;
4195 * Send an authentication request using method "none": (a)
4196 * just in case it succeeds, and (b) so that we know what
4197 * authentication methods we can usefully try next.
4199 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4201 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4202 ssh2_pkt_addstring(username);
4203 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4204 ssh2_pkt_addstring("none"); /* method */
4206 type = AUTH_TYPE_NONE;
4210 tried_pubkey_config = FALSE;
4211 tried_agent = FALSE;
4212 tried_keyb_inter = FALSE;
4213 kbd_inter_running = FALSE;
4214 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4217 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4218 keytype = key_type(cfg.keyfile);
4219 if (keytype == SSH_KEYTYPE_SSH2)
4220 publickey_blob = ssh2_userkey_loadpub(cfg.keyfile, NULL,
4221 &publickey_bloblen);
4224 logeventf("Unable to use this key file (%s)",
4225 key_type_to_str(keytype));
4226 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4227 cfg.keyfile, key_type_to_str(keytype));
4228 c_write_str(msgbuf);
4229 publickey_blob = NULL;
4232 publickey_blob = NULL;
4236 * Wait for the result of the last authentication request.
4239 crWaitUntilV(ispkt);
4240 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4244 * Don't show the banner if we're operating in
4245 * non-verbose non-interactive mode. (It's probably
4246 * a script, which means nobody will read the
4247 * banner _anyway_, and moreover the printing of
4248 * the banner will screw up processing on the
4249 * output of (say) plink.)
4251 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4252 ssh2_pkt_getstring(&banner, &size);
4254 c_write_untrusted(banner, size);
4256 crWaitUntilV(ispkt);
4258 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4259 logevent("Access granted");
4264 if (kbd_inter_running &&
4265 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4267 * This is either a further set-of-prompts packet
4268 * in keyboard-interactive authentication, or it's
4269 * the same one and we came back here with `gotit'
4270 * set. In the former case, we must reset the
4271 * curr_prompt variable.
4275 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4276 bombout(("Strange packet received during authentication: type %d",
4284 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4285 * we can look at the string in it and know what we can
4286 * helpfully try next.
4288 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4291 ssh2_pkt_getstring(&methods, &methlen);
4292 kbd_inter_running = FALSE;
4293 if (!ssh2_pkt_getbool()) {
4295 * We have received an unequivocal Access
4296 * Denied. This can translate to a variety of
4299 * - if we'd just tried "none" authentication,
4300 * it's not worth printing anything at all
4302 * - if we'd just tried a public key _offer_,
4303 * the message should be "Server refused our
4304 * key" (or no message at all if the key
4305 * came from Pageant)
4307 * - if we'd just tried anything else, the
4308 * message really should be "Access denied".
4310 * Additionally, if we'd just tried password
4311 * authentication, we should break out of this
4312 * whole loop so as to go back to the username
4315 if (type == AUTH_TYPE_NONE) {
4317 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4318 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4319 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4320 c_write_str("Server refused our key\r\n");
4321 logevent("Server refused public key");
4322 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4323 /* server declined keyboard-interactive; ignore */
4325 c_write_str("Access denied\r\n");
4326 logevent("Access denied");
4327 if (type == AUTH_TYPE_PASSWORD) {
4333 c_write_str("Further authentication required\r\n");
4334 logevent("Further authentication required");
4338 in_commasep_string("publickey", methods, methlen);
4340 in_commasep_string("password", methods, methlen);
4341 can_keyb_inter = cfg.try_ki_auth &&
4342 in_commasep_string("keyboard-interactive", methods, methlen);
4346 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4349 * Most password/passphrase prompts will be
4350 * non-echoing, so we set this to 0 by default.
4351 * Exception is that some keyboard-interactive prompts
4352 * can be echoing, in which case we'll set this to 1.
4356 if (!method && can_pubkey && agent_exists() && !tried_agent) {
4358 * Attempt public-key authentication using Pageant.
4360 static unsigned char request[5], *response, *p;
4361 static int responselen;
4362 static int i, nkeys;
4363 static int authed = FALSE;
4366 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4367 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4371 logevent("Pageant is running. Requesting keys.");
4373 /* Request the keys held by the agent. */
4374 PUT_32BIT(request, 1);
4375 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4376 agent_query(request, 5, &r, &responselen);
4377 response = (unsigned char *) r;
4378 if (response && responselen >= 5 &&
4379 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4381 nkeys = GET_32BIT(p);
4385 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
4388 for (i = 0; i < nkeys; i++) {
4389 static char *pkblob, *alg, *commentp;
4390 static int pklen, alglen, commentlen;
4391 static int siglen, retlen, len;
4392 static char *q, *agentreq, *ret;
4397 sprintf(buf, "Trying Pageant key #%d", i);
4400 pklen = GET_32BIT(p);
4402 if (publickey_blob &&
4403 pklen == publickey_bloblen &&
4404 !memcmp(p, publickey_blob, publickey_bloblen)) {
4405 logevent("This key matches configured key file");
4406 tried_pubkey_config = 1;
4410 alglen = GET_32BIT(pkblob);
4412 commentlen = GET_32BIT(p);
4416 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4417 ssh2_pkt_addstring(username);
4418 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4419 ssh2_pkt_addstring("publickey"); /* method */
4420 ssh2_pkt_addbool(FALSE); /* no signature included */
4421 ssh2_pkt_addstring_start();
4422 ssh2_pkt_addstring_data(alg, alglen);
4423 ssh2_pkt_addstring_start();
4424 ssh2_pkt_addstring_data(pkblob, pklen);
4427 crWaitUntilV(ispkt);
4428 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4429 logevent("Key refused");
4433 if (flags & FLAG_VERBOSE) {
4435 ("Authenticating with public key \"");
4436 c_write(commentp, commentlen);
4437 c_write_str("\" from agent\r\n");
4441 * Server is willing to accept the key.
4442 * Construct a SIGN_REQUEST.
4444 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4445 ssh2_pkt_addstring(username);
4446 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4447 ssh2_pkt_addstring("publickey"); /* method */
4448 ssh2_pkt_addbool(TRUE);
4449 ssh2_pkt_addstring_start();
4450 ssh2_pkt_addstring_data(alg, alglen);
4451 ssh2_pkt_addstring_start();
4452 ssh2_pkt_addstring_data(pkblob, pklen);
4454 siglen = pktout.length - 5 + 4 + 20;
4455 len = 1; /* message type */
4456 len += 4 + pklen; /* key blob */
4457 len += 4 + siglen; /* data to sign */
4458 len += 4; /* flags */
4459 agentreq = smalloc(4 + len);
4460 PUT_32BIT(agentreq, len);
4462 *q++ = SSH2_AGENTC_SIGN_REQUEST;
4463 PUT_32BIT(q, pklen);
4465 memcpy(q, pkblob, pklen);
4467 PUT_32BIT(q, siglen);
4469 /* Now the data to be signed... */
4472 memcpy(q, ssh2_session_id, 20);
4474 memcpy(q, pktout.data + 5, pktout.length - 5);
4475 q += pktout.length - 5;
4476 /* And finally the (zero) flags word. */
4478 agent_query(agentreq, len + 4, &vret, &retlen);
4482 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4483 logevent("Sending Pageant's response");
4484 ssh2_add_sigblob(pkblob, pklen,
4485 ret + 9, GET_32BIT(ret + 5));
4491 ("Pageant failed to answer challenge");
4501 if (!method && can_pubkey && publickey_blob
4502 && !tried_pubkey_config) {
4503 unsigned char *pub_blob;
4504 char *algorithm, *comment;
4507 tried_pubkey_config = TRUE;
4509 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4510 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4513 * Try the public key supplied in the configuration.
4515 * First, offer the public blob to see if the server is
4516 * willing to accept it.
4518 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4521 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4522 ssh2_pkt_addstring(username);
4523 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4524 ssh2_pkt_addstring("publickey"); /* method */
4525 ssh2_pkt_addbool(FALSE); /* no signature included */
4526 ssh2_pkt_addstring(algorithm);
4527 ssh2_pkt_addstring_start();
4528 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4530 logevent("Offered public key"); /* FIXME */
4532 crWaitUntilV(ispkt);
4533 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4535 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4536 continue; /* key refused; give up on it */
4539 logevent("Offer of public key accepted");
4541 * Actually attempt a serious authentication using
4544 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4546 "Passphrase for key \"%.100s\": ",
4552 c_write_str("Authenticating with public key \"");
4553 c_write_str(comment);
4554 c_write_str("\"\r\n");
4555 method = AUTH_PUBLICKEY_FILE;
4559 if (!method && can_keyb_inter && !tried_keyb_inter) {
4560 method = AUTH_KEYBOARD_INTERACTIVE;
4561 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4562 tried_keyb_inter = TRUE;
4564 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4565 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4567 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4568 ssh2_pkt_addstring(username);
4569 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4570 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4571 ssh2_pkt_addstring(""); /* lang */
4572 ssh2_pkt_addstring("");
4575 crWaitUntilV(ispkt);
4576 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4577 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4579 logevent("Keyboard-interactive authentication refused");
4580 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4584 kbd_inter_running = TRUE;
4588 if (kbd_inter_running) {
4589 method = AUTH_KEYBOARD_INTERACTIVE;
4590 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4591 tried_keyb_inter = TRUE;
4593 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4594 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4596 if (curr_prompt == 0) {
4598 * We've got a fresh USERAUTH_INFO_REQUEST.
4599 * Display header data, and start going through
4602 char *name, *inst, *lang;
4603 int name_len, inst_len, lang_len;
4605 ssh2_pkt_getstring(&name, &name_len);
4606 ssh2_pkt_getstring(&inst, &inst_len);
4607 ssh2_pkt_getstring(&lang, &lang_len);
4609 c_write_untrusted(name, name_len);
4610 c_write_str("\r\n");
4613 c_write_untrusted(inst, inst_len);
4614 c_write_str("\r\n");
4616 num_prompts = ssh2_pkt_getuint32();
4620 * If there are prompts remaining in the packet,
4621 * display one and get a response.
4623 if (curr_prompt < num_prompts) {
4627 ssh2_pkt_getstring(&prompt, &prompt_len);
4628 if (prompt_len > 0) {
4629 strncpy(pwprompt, prompt, sizeof(pwprompt));
4630 pwprompt[prompt_len < sizeof(pwprompt) ?
4631 prompt_len : sizeof(pwprompt)-1] = '\0';
4634 "<server failed to send prompt>: ");
4636 echo = ssh2_pkt_getbool();
4642 if (!method && can_passwd) {
4643 method = AUTH_PASSWORD;
4644 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4645 ssh_pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4646 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4653 if (!ssh_get_line(pwprompt, password,
4654 sizeof(password), TRUE)) {
4656 * get_line failed to get a password (for
4657 * example because one was supplied on the
4658 * command line which has already failed to
4661 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4662 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4664 ("No more passwords available to try");
4665 ssh2_pkt_addstring("en"); /* language tag */
4667 logevent("Unable to authenticate");
4668 connection_fatal("Unable to authenticate");
4669 ssh_state = SSH_STATE_CLOSED;
4674 c_write_untrusted(pwprompt, strlen(pwprompt));
4677 setup_userpass_input(password, sizeof(password), echo);
4679 crWaitUntilV(!ispkt);
4680 ret = process_userpass_input(in, inlen);
4684 c_write_str("\r\n");
4688 if (method == AUTH_PUBLICKEY_FILE) {
4690 * We have our passphrase. Now try the actual authentication.
4692 struct ssh2_userkey *key;
4694 key = ssh2_load_userkey(cfg.keyfile, password);
4695 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4696 if (key == SSH2_WRONG_PASSPHRASE) {
4697 c_write_str("Wrong passphrase\r\n");
4698 tried_pubkey_config = FALSE;
4700 c_write_str("Unable to load private key\r\n");
4701 tried_pubkey_config = TRUE;
4703 /* Send a spurious AUTH_NONE to return to the top. */
4704 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4705 ssh2_pkt_addstring(username);
4706 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4707 ssh2_pkt_addstring("none"); /* method */
4709 type = AUTH_TYPE_NONE;
4711 unsigned char *pkblob, *sigblob, *sigdata;
4712 int pkblob_len, sigblob_len, sigdata_len;
4715 * We have loaded the private key and the server
4716 * has announced that it's willing to accept it.
4717 * Hallelujah. Generate a signature and send it.
4719 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4720 ssh2_pkt_addstring(username);
4721 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4722 ssh2_pkt_addstring("publickey"); /* method */
4723 ssh2_pkt_addbool(TRUE);
4724 ssh2_pkt_addstring(key->alg->name);
4725 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4726 ssh2_pkt_addstring_start();
4727 ssh2_pkt_addstring_data(pkblob, pkblob_len);
4730 * The data to be signed is:
4734 * followed by everything so far placed in the
4737 sigdata_len = pktout.length - 5 + 4 + 20;
4738 sigdata = smalloc(sigdata_len);
4739 PUT_32BIT(sigdata, 20);
4740 memcpy(sigdata + 4, ssh2_session_id, 20);
4741 memcpy(sigdata + 24, pktout.data + 5,
4743 sigblob = key->alg->sign(key->data, sigdata,
4744 sigdata_len, &sigblob_len);
4745 ssh2_add_sigblob(pkblob, pkblob_len,
4746 sigblob, sigblob_len);
4752 type = AUTH_TYPE_PUBLICKEY;
4754 } else if (method == AUTH_PASSWORD) {
4756 * We send the password packet lumped tightly together with
4757 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4758 * string long enough to make the total length of the two
4759 * packets constant. This should ensure that a passive
4760 * listener doing traffic analyis can't work out the length
4763 * For this to work, we need an assumption about the
4764 * maximum length of the password packet. I think 256 is
4765 * pretty conservative. Anyone using a password longer than
4766 * that probably doesn't have much to worry about from
4767 * people who find out how long their password is!
4769 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4770 ssh2_pkt_addstring(username);
4771 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4772 ssh2_pkt_addstring("password");
4773 ssh2_pkt_addbool(FALSE);
4774 ssh2_pkt_addstring(password);
4777 * We'll include a string that's an exact multiple of the
4778 * cipher block size. If the cipher is NULL for some
4779 * reason, we don't do this trick at all because we gain
4785 stringlen = (256 - deferred_len);
4786 stringlen += cscipher->blksize - 1;
4787 stringlen -= (stringlen % cscipher->blksize);
4790 * Temporarily disable actual compression,
4791 * so we can guarantee to get this string
4792 * exactly the length we want it. The
4793 * compression-disabling routine should
4794 * return an integer indicating how many
4795 * bytes we should adjust our string length
4798 stringlen -= cscomp->disable_compression();
4800 ssh2_pkt_init(SSH2_MSG_IGNORE);
4801 ssh2_pkt_addstring_start();
4802 for (i = 0; i < stringlen; i++) {
4803 char c = (char) random_byte();
4804 ssh2_pkt_addstring_data(&c, 1);
4808 ssh_pkt_defersend();
4809 logevent("Sent password");
4810 type = AUTH_TYPE_PASSWORD;
4811 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4812 if (curr_prompt == 0) {
4813 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4814 ssh2_pkt_adduint32(num_prompts);
4816 if (need_pw) { /* only add pw if we just got one! */
4817 ssh2_pkt_addstring(password);
4818 memset(password, 0, sizeof(password));
4821 if (curr_prompt >= num_prompts) {
4825 * If there are prompts remaining, we set
4826 * `gotit' so that we won't attempt to get
4827 * another packet. Then we go back round the
4828 * loop and will end up retrieving another
4829 * prompt out of the existing packet. Funky or
4834 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4837 ("No supported authentication methods left to try!\r\n");
4839 ("No supported authentications offered. Disconnecting");
4840 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4841 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4843 ("No supported authentication methods available");
4844 ssh2_pkt_addstring("en"); /* language tag */
4846 ssh_state = SSH_STATE_CLOSED;
4850 } while (!we_are_in);
4853 * Now we're authenticated for the connection protocol. The
4854 * connection protocol will automatically have started at this
4855 * point; there's no need to send SERVICE_REQUEST.
4859 * So now create a channel with a session in it.
4861 ssh_channels = newtree234(ssh_channelcmp);
4862 mainchan = smalloc(sizeof(struct ssh_channel));
4863 mainchan->localid = alloc_channel_id();
4864 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4865 ssh2_pkt_addstring("session");
4866 ssh2_pkt_adduint32(mainchan->localid);
4867 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4868 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4869 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4871 crWaitUntilV(ispkt);
4872 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4873 bombout(("Server refused to open a session"));
4875 /* FIXME: error data comes back in FAILURE packet */
4877 if (ssh2_pkt_getuint32() != mainchan->localid) {
4878 bombout(("Server's channel confirmation cited wrong channel"));
4881 mainchan->remoteid = ssh2_pkt_getuint32();
4882 mainchan->type = CHAN_MAINSESSION;
4883 mainchan->closes = 0;
4884 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4885 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4886 bufchain_init(&mainchan->v.v2.outbuffer);
4887 add234(ssh_channels, mainchan);
4888 logevent("Opened channel for session");
4891 * Potentially enable X11 forwarding.
4893 if (cfg.x11_forward) {
4894 char proto[20], data[64];
4895 logevent("Requesting X11 forwarding");
4896 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4897 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4898 ssh2_pkt_adduint32(mainchan->remoteid);
4899 ssh2_pkt_addstring("x11-req");
4900 ssh2_pkt_addbool(1); /* want reply */
4901 ssh2_pkt_addbool(0); /* many connections */
4902 ssh2_pkt_addstring(proto);
4903 ssh2_pkt_addstring(data);
4904 ssh2_pkt_adduint32(0); /* screen number */
4908 crWaitUntilV(ispkt);
4909 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4910 unsigned i = ssh2_pkt_getuint32();
4911 struct ssh_channel *c;
4912 c = find234(ssh_channels, &i, ssh_channelfind);
4914 continue; /* nonexistent channel */
4915 c->v.v2.remwindow += ssh2_pkt_getuint32();
4917 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4919 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4920 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4921 bombout(("Unexpected response to X11 forwarding request:"
4922 " packet type %d", pktin.type));
4925 logevent("X11 forwarding refused");
4927 logevent("X11 forwarding enabled");
4928 ssh_X11_fwd_enabled = TRUE;
4933 * Enable port forwardings.
4936 static char *e; /* preserve across crReturn */
4939 int sport,dport,sserv,dserv;
4940 char sports[256], dports[256], host[256];
4944 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4945 /* Add port forwardings. */
4950 while (*e && *e != '\t')
4956 while (*e && *e != ':')
4966 dport = atoi(dports);
4970 se = getservbyname(dports, NULL);
4972 dport = ntohs(se->s_port);
4975 "Service lookup failed for destination port \"%s\"",
4980 sport = atoi(sports);
4984 se = getservbyname(sports, NULL);
4986 sport = ntohs(se->s_port);
4989 "Service lookup failed for source port \"%s\"",
4994 if (sport && dport) {
4996 pfd_addforward(host, dport, sport);
4997 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
4998 " %s:%.*s%.*s%d%.*s",
4999 sserv ? strlen(sports) : 0, sports,
5000 sserv, "(", sport, sserv, ")",
5002 dserv ? strlen(dports) : 0, dports,
5003 dserv, "(", dport, dserv, ")");
5006 struct ssh_rportfwd *pf;
5007 pf = smalloc(sizeof(*pf));
5008 strcpy(pf->dhost, host);
5011 if (add234(ssh_rportfwds, pf) != pf) {
5013 "Duplicate remote port forwarding to %s:%d",
5018 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5019 " forward to %s:%.*s%.*s%d%.*s",
5020 sserv ? strlen(sports) : 0, sports,
5021 sserv, "(", sport, sserv, ")",
5023 dserv ? strlen(dports) : 0, dports,
5024 dserv, "(", dport, dserv, ")");
5026 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5027 ssh2_pkt_addstring("tcpip-forward");
5028 ssh2_pkt_addbool(1);/* want reply */
5029 if (cfg.rport_acceptall)
5030 ssh2_pkt_addstring("0.0.0.0");
5032 ssh2_pkt_addstring("127.0.0.1");
5033 ssh2_pkt_adduint32(sport);
5037 crWaitUntilV(ispkt);
5038 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5039 unsigned i = ssh2_pkt_getuint32();
5040 struct ssh_channel *c;
5041 c = find234(ssh_channels, &i, ssh_channelfind);
5043 continue;/* nonexistent channel */
5044 c->v.v2.remwindow += ssh2_pkt_getuint32();
5046 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5048 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5049 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5050 bombout(("Unexpected response to port "
5051 "forwarding request: packet type %d",
5055 logevent("Server refused this port forwarding");
5057 logevent("Remote port forwarding enabled");
5066 * Potentially enable agent forwarding.
5068 if (cfg.agentfwd && agent_exists()) {
5069 logevent("Requesting OpenSSH-style agent forwarding");
5070 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5071 ssh2_pkt_adduint32(mainchan->remoteid);
5072 ssh2_pkt_addstring("auth-agent-req@openssh.com");
5073 ssh2_pkt_addbool(1); /* want reply */
5077 crWaitUntilV(ispkt);
5078 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5079 unsigned i = ssh2_pkt_getuint32();
5080 struct ssh_channel *c;
5081 c = find234(ssh_channels, &i, ssh_channelfind);
5083 continue; /* nonexistent channel */
5084 c->v.v2.remwindow += ssh2_pkt_getuint32();
5086 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5088 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5089 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5090 bombout(("Unexpected response to agent forwarding request:"
5091 " packet type %d", pktin.type));
5094 logevent("Agent forwarding refused");
5096 logevent("Agent forwarding enabled");
5097 ssh_agentfwd_enabled = TRUE;
5102 * Now allocate a pty for the session.
5105 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5106 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5107 ssh2_pkt_addstring("pty-req");
5108 ssh2_pkt_addbool(1); /* want reply */
5109 ssh2_pkt_addstring(cfg.termtype);
5110 ssh2_pkt_adduint32(cols);
5111 ssh2_pkt_adduint32(rows);
5112 ssh2_pkt_adduint32(0); /* pixel width */
5113 ssh2_pkt_adduint32(0); /* pixel height */
5114 ssh2_pkt_addstring_start();
5115 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
5117 ssh_state = SSH_STATE_INTERMED;
5120 crWaitUntilV(ispkt);
5121 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5122 unsigned i = ssh2_pkt_getuint32();
5123 struct ssh_channel *c;
5124 c = find234(ssh_channels, &i, ssh_channelfind);
5126 continue; /* nonexistent channel */
5127 c->v.v2.remwindow += ssh2_pkt_getuint32();
5129 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5131 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5132 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5133 bombout(("Unexpected response to pty request:"
5134 " packet type %d", pktin.type));
5137 c_write_str("Server refused to allocate pty\r\n");
5138 ssh_editing = ssh_echoing = 1;
5140 logevent("Allocated pty");
5143 ssh_editing = ssh_echoing = 1;
5147 * Start a shell or a remote command. We may have to attempt
5148 * this twice if the config data has provided a second choice
5155 if (ssh_fallback_cmd) {
5156 subsys = cfg.ssh_subsys2;
5157 cmd = cfg.remote_cmd_ptr2;
5159 subsys = cfg.ssh_subsys;
5160 cmd = cfg.remote_cmd_ptr;
5163 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5164 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5166 ssh2_pkt_addstring("subsystem");
5167 ssh2_pkt_addbool(1); /* want reply */
5168 ssh2_pkt_addstring(cmd);
5170 ssh2_pkt_addstring("exec");
5171 ssh2_pkt_addbool(1); /* want reply */
5172 ssh2_pkt_addstring(cmd);
5174 ssh2_pkt_addstring("shell");
5175 ssh2_pkt_addbool(1); /* want reply */
5179 crWaitUntilV(ispkt);
5180 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5181 unsigned i = ssh2_pkt_getuint32();
5182 struct ssh_channel *c;
5183 c = find234(ssh_channels, &i, ssh_channelfind);
5185 continue; /* nonexistent channel */
5186 c->v.v2.remwindow += ssh2_pkt_getuint32();
5188 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5189 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5190 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5191 bombout(("Unexpected response to shell/command request:"
5192 " packet type %d", pktin.type));
5196 * We failed to start the command. If this is the
5197 * fallback command, we really are finished; if it's
5198 * not, and if the fallback command exists, try falling
5199 * back to it before complaining.
5201 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5202 logevent("Primary command failed; attempting fallback");
5203 ssh_fallback_cmd = TRUE;
5206 bombout(("Server refused to start a shell/command"));
5209 logevent("Started a shell/command");
5214 ssh_state = SSH_STATE_SESSION;
5218 ssh_special(TS_EOF);
5223 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
5226 static int try_send;
5230 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
5231 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5234 unsigned i = ssh2_pkt_getuint32();
5235 struct ssh_channel *c;
5236 c = find234(ssh_channels, &i, ssh_channelfind);
5238 continue; /* nonexistent channel */
5239 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5240 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
5241 continue; /* extended but not stderr */
5242 ssh2_pkt_getstring(&data, &length);
5245 c->v.v2.locwindow -= length;
5247 case CHAN_MAINSESSION:
5249 from_backend(pktin.type ==
5250 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5254 bufsize = x11_send(c->u.x11.s, data, length);
5257 bufsize = pfd_send(c->u.pfd.s, data, length);
5260 while (length > 0) {
5261 if (c->u.a.lensofar < 4) {
5262 int l = min(4 - c->u.a.lensofar, length);
5263 memcpy(c->u.a.msglen + c->u.a.lensofar,
5267 c->u.a.lensofar += l;
5269 if (c->u.a.lensofar == 4) {
5271 4 + GET_32BIT(c->u.a.msglen);
5272 c->u.a.message = smalloc(c->u.a.totallen);
5273 memcpy(c->u.a.message, c->u.a.msglen, 4);
5275 if (c->u.a.lensofar >= 4 && length > 0) {
5277 min(c->u.a.totallen - c->u.a.lensofar,
5279 memcpy(c->u.a.message + c->u.a.lensofar,
5283 c->u.a.lensofar += l;
5285 if (c->u.a.lensofar == c->u.a.totallen) {
5286 void *reply, *sentreply;
5288 agent_query(c->u.a.message,
5289 c->u.a.totallen, &reply,
5294 /* Fake SSH_AGENT_FAILURE. */
5295 sentreply = "\0\0\0\1\5";
5298 ssh2_add_channel_data(c, sentreply,
5303 sfree(c->u.a.message);
5304 c->u.a.lensofar = 0;
5311 * If we are not buffering too much data,
5312 * enlarge the window again at the remote side.
5314 if (bufsize < OUR_V2_WINSIZE)
5315 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5317 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
5318 ssh_state = SSH_STATE_CLOSED;
5319 logevent("Received disconnect message");
5321 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
5322 unsigned i = ssh2_pkt_getuint32();
5323 struct ssh_channel *c;
5325 c = find234(ssh_channels, &i, ssh_channelfind);
5327 continue; /* nonexistent channel */
5329 if (c->type == CHAN_X11) {
5331 * Remote EOF on an X11 channel means we should
5332 * wrap up and close the channel ourselves.
5334 x11_close(c->u.x11.s);
5336 } else if (c->type == CHAN_AGENT) {
5338 } else if (c->type == CHAN_SOCKDATA) {
5339 pfd_close(c->u.pfd.s);
5342 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5343 unsigned i = ssh2_pkt_getuint32();
5344 struct ssh_channel *c;
5346 c = find234(ssh_channels, &i, ssh_channelfind);
5348 continue; /* nonexistent channel */
5349 /* Do pre-close processing on the channel. */
5351 case CHAN_MAINSESSION:
5352 break; /* nothing to see here, move along */
5354 if (c->u.x11.s != NULL)
5355 x11_close(c->u.x11.s);
5362 if (c->u.pfd.s != NULL)
5363 pfd_close(c->u.pfd.s);
5367 if (c->closes == 0) {
5368 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5369 ssh2_pkt_adduint32(c->remoteid);
5372 del234(ssh_channels, c);
5373 bufchain_clear(&c->v.v2.outbuffer);
5377 * See if that was the last channel left open.
5379 if (count234(ssh_channels) == 0) {
5382 * We used to send SSH_MSG_DISCONNECT here,
5383 * because I'd believed that _every_ conforming
5384 * SSH2 connection had to end with a disconnect
5385 * being sent by at least one side; apparently
5386 * I was wrong and it's perfectly OK to
5387 * unceremoniously slam the connection shut
5388 * when you're done, and indeed OpenSSH feels
5389 * this is more polite than sending a
5390 * DISCONNECT. So now we don't.
5392 logevent("All channels closed. Disconnecting");
5393 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5394 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5395 ssh2_pkt_addstring("All open channels closed");
5396 ssh2_pkt_addstring("en"); /* language tag */
5399 ssh_state = SSH_STATE_CLOSED;
5402 continue; /* remote sends close; ignore (FIXME) */
5403 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5404 unsigned i = ssh2_pkt_getuint32();
5405 struct ssh_channel *c;
5406 c = find234(ssh_channels, &i, ssh_channelfind);
5408 continue; /* nonexistent channel */
5409 c->v.v2.remwindow += ssh2_pkt_getuint32();
5411 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5412 unsigned i = ssh2_pkt_getuint32();
5413 struct ssh_channel *c;
5414 c = find234(ssh_channels, &i, ssh_channelfind);
5416 continue; /* nonexistent channel */
5417 if (c->type != CHAN_SOCKDATA_DORMANT)
5418 continue; /* dunno why they're confirming this */
5419 c->remoteid = ssh2_pkt_getuint32();
5420 c->type = CHAN_SOCKDATA;
5421 c->v.v2.remwindow = ssh2_pkt_getuint32();
5422 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
5424 pfd_confirm(c->u.pfd.s);
5427 * We have a pending close on this channel,
5428 * which we decided on before the server acked
5429 * the channel open. So now we know the
5430 * remoteid, we can close it again.
5432 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5433 ssh2_pkt_adduint32(c->remoteid);
5436 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5437 unsigned i = ssh2_pkt_getuint32();
5438 struct ssh_channel *c;
5439 c = find234(ssh_channels, &i, ssh_channelfind);
5441 continue; /* nonexistent channel */
5442 if (c->type != CHAN_SOCKDATA_DORMANT)
5443 continue; /* dunno why they're failing this */
5445 logevent("Forwarded connection refused by server");
5447 pfd_close(c->u.pfd.s);
5449 del234(ssh_channels, c);
5451 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5454 int typelen, want_reply;
5455 struct ssh_channel *c;
5457 localid = ssh2_pkt_getuint32();
5458 ssh2_pkt_getstring(&type, &typelen);
5459 want_reply = ssh2_pkt_getbool();
5462 * First, check that the channel exists. Otherwise,
5463 * we can instantly disconnect with a rude message.
5465 c = find234(ssh_channels, &localid, ssh_channelfind);
5468 sprintf(buf, "Received channel request for nonexistent"
5469 " channel %d", localid);
5471 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5472 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5473 ssh2_pkt_addstring(buf);
5474 ssh2_pkt_addstring("en"); /* language tag */
5476 connection_fatal("%s", buf);
5477 ssh_state = SSH_STATE_CLOSED;
5482 * Having got the channel number, we now look at
5483 * the request type string to see if it's something
5486 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5488 /* We recognise "exit-status" on the primary channel. */
5490 ssh_exitcode = ssh2_pkt_getuint32();
5491 sprintf(buf, "Server sent command exit status %d",
5495 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS);
5496 ssh2_pkt_adduint32(c->remoteid);
5501 * This is a channel request we don't know
5502 * about, so we now either ignore the request
5503 * or respond with CHANNEL_FAILURE, depending
5507 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
5508 ssh2_pkt_adduint32(c->remoteid);
5512 } else if (pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5514 int typelen, want_reply;
5516 ssh2_pkt_getstring(&type, &typelen);
5517 want_reply = ssh2_pkt_getbool();
5520 * We currently don't support any global requests
5521 * at all, so we either ignore the request or
5522 * respond with REQUEST_FAILURE, depending on
5526 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5529 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5533 struct ssh_channel *c;
5534 unsigned remid, winsize, pktsize;
5535 ssh2_pkt_getstring(&type, &typelen);
5536 c = smalloc(sizeof(struct ssh_channel));
5538 remid = ssh2_pkt_getuint32();
5539 winsize = ssh2_pkt_getuint32();
5540 pktsize = ssh2_pkt_getuint32();
5542 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5543 if (!ssh_X11_fwd_enabled)
5544 error = "X11 forwarding is not enabled";
5545 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5547 error = "Unable to open an X11 connection";
5551 } else if (typelen == 15 &&
5552 !memcmp(type, "forwarded-tcpip", 15)) {
5553 struct ssh_rportfwd pf, *realpf;
5556 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
5557 pf.sport = ssh2_pkt_getuint32();
5558 realpf = find234(ssh_rportfwds, &pf, NULL);
5559 if (realpf == NULL) {
5560 error = "Remote port is not recognised";
5562 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5565 sprintf(buf, "Received remote port open request for %s:%d",
5566 realpf->dhost, realpf->dport);
5569 sprintf(buf, "Port open failed: %s", e);
5571 error = "Port open failed";
5573 logevent("Forwarded port opened successfully");
5574 c->type = CHAN_SOCKDATA;
5577 } else if (typelen == 22 &&
5578 !memcmp(type, "auth-agent@openssh.com", 3)) {
5579 if (!ssh_agentfwd_enabled)
5580 error = "Agent forwarding is not enabled";
5582 c->type = CHAN_AGENT; /* identify channel type */
5583 c->u.a.lensofar = 0;
5586 error = "Unsupported channel type requested";
5589 c->remoteid = remid;
5591 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5592 ssh2_pkt_adduint32(c->remoteid);
5593 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5594 ssh2_pkt_addstring(error);
5595 ssh2_pkt_addstring("en"); /* language tag */
5599 c->localid = alloc_channel_id();
5601 c->v.v2.locwindow = OUR_V2_WINSIZE;
5602 c->v.v2.remwindow = winsize;
5603 c->v.v2.remmaxpkt = pktsize;
5604 bufchain_init(&c->v.v2.outbuffer);
5605 add234(ssh_channels, c);
5606 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5607 ssh2_pkt_adduint32(c->remoteid);
5608 ssh2_pkt_adduint32(c->localid);
5609 ssh2_pkt_adduint32(c->v.v2.locwindow);
5610 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5614 bombout(("Strange packet received: type %d", pktin.type));
5619 * We have spare data. Add it to the channel buffer.
5621 ssh2_add_channel_data(mainchan, in, inlen);
5626 struct ssh_channel *c;
5628 * Try to send data on all channels if we can.
5630 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5631 int bufsize = ssh2_try_send(c);
5634 case CHAN_MAINSESSION:
5635 /* stdin need not receive an unthrottle
5636 * notification since it will be polled */
5639 x11_unthrottle(c->u.x11.s);
5642 /* agent sockets are request/response and need no
5643 * buffer management */
5646 pfd_unthrottle(c->u.pfd.s);
5658 * Handle the top-level SSH2 protocol.
5660 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5662 if (do_ssh2_transport(in, inlen, ispkt) == 0)
5664 do_ssh2_authconn(in, inlen, ispkt);
5668 * Called to set up the connection.
5670 * Returns an error message, or NULL on success.
5672 static char *ssh_init(char *host, int port, char **realhost, int nodelay)
5677 if (crypto_startup() == 0)
5678 return "Microsoft high encryption pack not installed!";
5684 ssh1_throttle_count = 0;
5685 ssh_overall_bufsize = 0;
5686 ssh_fallback_cmd = 0;
5688 p = connect_to_host(host, port, realhost, nodelay);
5696 * Called to send data down the Telnet connection.
5698 static int ssh_send(char *buf, int len)
5700 if (s == NULL || ssh_protocol == NULL)
5703 ssh_protocol(buf, len, 0);
5705 return ssh_sendbuffer();
5709 * Called to query the current amount of buffered stdin data.
5711 static int ssh_sendbuffer(void)
5715 if (s == NULL || ssh_protocol == NULL)
5719 * If the SSH socket itself has backed up, add the total backup
5720 * size on that to any individual buffer on the stdin channel.
5723 if (ssh_throttled_all)
5724 override_value = ssh_overall_bufsize;
5726 if (ssh_version == 1) {
5727 return override_value;
5728 } else if (ssh_version == 2) {
5729 if (!mainchan || mainchan->closes > 0)
5730 return override_value;
5732 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5739 * Called to set the size of the window from SSH's POV.
5741 static void ssh_size(void)
5743 switch (ssh_state) {
5744 case SSH_STATE_BEFORE_SIZE:
5745 case SSH_STATE_PREPACKET:
5746 case SSH_STATE_CLOSED:
5747 break; /* do nothing */
5748 case SSH_STATE_INTERMED:
5749 size_needed = TRUE; /* buffer for later */
5751 case SSH_STATE_SESSION:
5753 if (ssh_version == 1) {
5754 send_packet(SSH1_CMSG_WINDOW_SIZE,
5755 PKT_INT, rows, PKT_INT, cols,
5756 PKT_INT, 0, PKT_INT, 0, PKT_END);
5758 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5759 ssh2_pkt_adduint32(mainchan->remoteid);
5760 ssh2_pkt_addstring("window-change");
5761 ssh2_pkt_addbool(0);
5762 ssh2_pkt_adduint32(cols);
5763 ssh2_pkt_adduint32(rows);
5764 ssh2_pkt_adduint32(0);
5765 ssh2_pkt_adduint32(0);
5774 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5775 * can send an EOF and collect resulting output (e.g. `plink
5778 static void ssh_special(Telnet_Special code)
5780 if (code == TS_EOF) {
5781 if (ssh_state != SSH_STATE_SESSION) {
5783 * Buffer the EOF in case we are pre-SESSION, so we can
5784 * send it as soon as we reach SESSION.
5790 if (ssh_version == 1) {
5791 send_packet(SSH1_CMSG_EOF, PKT_END);
5793 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5794 ssh2_pkt_adduint32(mainchan->remoteid);
5797 logevent("Sent EOF message");
5798 } else if (code == TS_PING) {
5799 if (ssh_state == SSH_STATE_CLOSED
5800 || ssh_state == SSH_STATE_PREPACKET) return;
5801 if (ssh_version == 1) {
5802 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
5803 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5805 ssh2_pkt_init(SSH2_MSG_IGNORE);
5806 ssh2_pkt_addstring_start();
5814 void *new_sock_channel(Socket s)
5816 struct ssh_channel *c;
5817 c = smalloc(sizeof(struct ssh_channel));
5820 c->remoteid = -1; /* to be set when open confirmed */
5821 c->localid = alloc_channel_id();
5823 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5825 bufchain_init(&c->v.v2.outbuffer);
5826 add234(ssh_channels, c);
5832 * This is called when stdout/stderr (the entity to which
5833 * from_backend sends data) manages to clear some backlog.
5835 void ssh_unthrottle(int bufsize)
5837 if (ssh_version == 1) {
5838 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5839 ssh1_stdout_throttling = 0;
5843 if (mainchan && mainchan->closes == 0)
5844 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5848 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5850 struct ssh_channel *c = (struct ssh_channel *)channel;
5853 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5856 if (ssh_version == 1) {
5857 send_packet(SSH1_MSG_PORT_OPEN,
5858 PKT_INT, c->localid,
5861 //PKT_STR, <org:orgport>,
5864 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5865 ssh2_pkt_addstring("direct-tcpip");
5866 ssh2_pkt_adduint32(c->localid);
5867 c->v.v2.locwindow = OUR_V2_WINSIZE;
5868 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5869 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5870 ssh2_pkt_addstring(hostname);
5871 ssh2_pkt_adduint32(port);
5873 * We make up values for the originator data; partly it's
5874 * too much hassle to keep track, and partly I'm not
5875 * convinced the server should be told details like that
5876 * about my local network configuration.
5878 ssh2_pkt_addstring("client-side-connection");
5879 ssh2_pkt_adduint32(0);
5885 static Socket ssh_socket(void)
5890 static int ssh_sendok(void)
5895 static int ssh_ldisc(int option)
5897 if (option == LD_ECHO)
5899 if (option == LD_EDIT)
5904 static int ssh_return_exitcode(void)
5906 return ssh_exitcode;
5909 Backend ssh_backend = {
5916 ssh_return_exitcode,