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: ");
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 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1664 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1665 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")) {
1667 * These versions don't support SSH1_MSG_IGNORE, so we have
1668 * to use a different defence against password length
1671 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1672 logevent("We believe remote version has SSH1 ignore bug");
1675 if (!strcmp(imp, "Cisco-1.25")) {
1677 * These versions need a plain password sent; they can't
1678 * handle having a null and a random length of data after
1681 ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1682 logevent("We believe remote version needs a plain SSH1 password");
1685 if (!strcmp(imp, "Cisco-1.25")) {
1687 * These versions apparently have no clue whatever about
1688 * RSA authentication and will panic and die if they see
1689 * an AUTH_RSA message.
1691 ssh_remote_bugs |= BUG_CHOKES_ON_RSA;
1692 logevent("We believe remote version can't handle RSA authentication");
1695 if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1696 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1697 !strncmp(imp, "2.1 ", 4)) {
1699 * These versions have the HMAC bug.
1701 ssh_remote_bugs |= BUG_SSH2_HMAC;
1702 logevent("We believe remote version has SSH2 HMAC bug");
1705 if (!strncmp(imp, "2.0.", 4)) {
1707 * These versions have the key-derivation bug (failing to
1708 * include the literal shared secret in the hashes that
1709 * generate the keys).
1711 ssh_remote_bugs |= BUG_SSH2_DERIVEKEY;
1712 logevent("We believe remote version has SSH2 key-derivation bug");
1715 if ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1716 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')) {
1718 * These versions have the SSH2 RSA padding bug.
1720 ssh_remote_bugs |= BUG_SSH2_RSA_PADDING;
1721 logevent("We believe remote version has SSH2 RSA padding bug");
1725 static int do_ssh_init(unsigned char c)
1728 static char version[10];
1729 static char *vstring;
1730 static int vstrsize;
1733 static int proto1, proto2;
1737 /* Search for the string "SSH-" in the input. */
1740 static const int transS[] = { 1, 2, 2, 1 };
1741 static const int transH[] = { 0, 0, 3, 0 };
1742 static const int transminus[] = { 0, 0, 0, -1 };
1753 crReturn(1); /* get another character */
1757 vstring = smalloc(vstrsize);
1758 strcpy(vstring, "SSH-");
1762 crReturn(1); /* get another char */
1763 if (vslen >= vstrsize - 1) {
1765 vstring = srealloc(vstring, vstrsize);
1767 vstring[vslen++] = c;
1772 } else if (i < sizeof(version) - 1)
1774 } else if (c == '\n')
1778 ssh_agentfwd_enabled = FALSE;
1779 rdpkt2_state.incoming_sequence = 0;
1782 vlog = smalloc(20 + vslen);
1783 vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1784 sprintf(vlog, "Server version: %s", vstring);
1786 ssh_detect_bugs(vstring);
1790 * Decide which SSH protocol version to support.
1793 /* Anything strictly below "2.0" means protocol 1 is supported. */
1794 proto1 = ssh_versioncmp(version, "2.0") < 0;
1795 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1796 proto2 = ssh_versioncmp(version, "1.99") >= 0;
1798 if (cfg.sshprot == 0 && !proto1) {
1799 bombout(("SSH protocol version 1 required by user but not provided by server"));
1802 if (cfg.sshprot == 3 && !proto2) {
1803 bombout(("SSH protocol version 2 required by user but not provided by server"));
1807 if (proto2 && (cfg.sshprot >= 2 || !proto1)) {
1811 char verstring[80], vlog[100];
1812 sprintf(verstring, "SSH-2.0-%s", sshver);
1813 SHA_Init(&exhashbase);
1815 * Hash our version string and their version string.
1817 sha_string(&exhashbase, verstring, strlen(verstring));
1818 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1819 sprintf(vlog, "We claim version: %s", verstring);
1821 strcat(verstring, "\n");
1822 logevent("Using SSH protocol version 2");
1823 sk_write(s, verstring, strlen(verstring));
1824 ssh_protocol = ssh2_protocol;
1826 s_rdpkt = ssh2_rdpkt;
1831 char verstring[80], vlog[100];
1832 sprintf(verstring, "SSH-%s-%s",
1833 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1835 sprintf(vlog, "We claim version: %s", verstring);
1837 strcat(verstring, "\n");
1839 logevent("Using SSH protocol version 1");
1840 sk_write(s, verstring, strlen(verstring));
1841 ssh_protocol = ssh1_protocol;
1843 s_rdpkt = ssh1_rdpkt;
1845 ssh_state = SSH_STATE_BEFORE_SIZE;
1852 static void ssh_gotdata(unsigned char *data, int datalen)
1857 * To begin with, feed the characters one by one to the
1858 * protocol initialisation / selection function do_ssh_init().
1859 * When that returns 0, we're done with the initial greeting
1860 * exchange and can move on to packet discipline.
1865 crReturnV; /* more data please */
1866 ret = do_ssh_init(*data);
1874 * We emerge from that loop when the initial negotiation is
1875 * over and we have selected an s_rdpkt function. Now pass
1876 * everything to s_rdpkt, and then pass the resulting packets
1877 * to the proper protocol handler.
1882 while (datalen > 0) {
1883 if (s_rdpkt(&data, &datalen) == 0) {
1884 if (ssh_state == SSH_STATE_CLOSED) {
1887 ssh_protocol(NULL, 0, 1);
1888 if (ssh_state == SSH_STATE_CLOSED) {
1898 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1901 ssh_state = SSH_STATE_CLOSED;
1907 /* A socket error has occurred. */
1908 logevent(error_msg);
1909 connection_fatal(error_msg);
1911 /* Otherwise, the remote side closed the connection normally. */
1916 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1918 ssh_gotdata(data, len);
1919 if (ssh_state == SSH_STATE_CLOSED) {
1929 static void ssh_sent(Plug plug, int bufsize)
1932 * If the send backlog on the SSH socket itself clears, we
1933 * should unthrottle the whole world if it was throttled.
1935 if (bufsize < SSH_MAX_BACKLOG)
1936 ssh_throttle_all(0, bufsize);
1940 * Connect to specified host and port.
1941 * Returns an error message, or NULL on success.
1942 * Also places the canonical host name into `realhost'. It must be
1943 * freed by the caller.
1945 static char *connect_to_host(char *host, int port, char **realhost, int nodelay)
1947 static struct plug_function_table fn_table = {
1952 }, *fn_table_ptr = &fn_table;
1961 savedhost = smalloc(1 + strlen(host));
1963 fatalbox("Out of memory");
1964 strcpy(savedhost, host);
1967 port = 22; /* default ssh port */
1982 sprintf(buf, "Looking up host \"%.170s\"", host);
1985 addr = sk_namelookup(host, realhost);
1986 if ((err = sk_addr_error(addr)))
1990 *realhost = strdup(FWhost);
1997 char buf[200], addrbuf[100];
1998 sk_getaddr(addr, addrbuf, 100);
1999 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2002 s = new_connection(addr, *realhost, port, 0, 1, nodelay, &fn_table_ptr);
2003 if ((err = sk_socket_error(s))) {
2009 sk_write(s, "connect ", 8);
2010 sk_write(s, FWhost, strlen(FWhost));
2013 sprintf(buf, " %d\n", FWport);
2014 sk_write(s, buf, strlen(buf));
2022 * Throttle or unthrottle the SSH connection.
2024 static void ssh1_throttle(int adjust)
2026 int old_count = ssh1_throttle_count;
2027 ssh1_throttle_count += adjust;
2028 assert(ssh1_throttle_count >= 0);
2029 if (ssh1_throttle_count && !old_count) {
2030 sk_set_frozen(s, 1);
2031 } else if (!ssh1_throttle_count && old_count) {
2032 sk_set_frozen(s, 0);
2037 * Throttle or unthrottle _all_ local data streams (for when sends
2038 * on the SSH connection itself back up).
2040 static void ssh_throttle_all(int enable, int bufsize)
2043 struct ssh_channel *c;
2045 if (enable == ssh_throttled_all)
2047 ssh_throttled_all = enable;
2048 ssh_overall_bufsize = bufsize;
2051 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
2053 case CHAN_MAINSESSION:
2055 * This is treated separately, outside the switch.
2059 x11_override_throttle(c->u.x11.s, enable);
2062 /* Agent channels require no buffer management. */
2065 pfd_override_throttle(c->u.x11.s, enable);
2072 * Username and password input, abstracted off into reusable
2073 * routines (hopefully even reusable between SSH1 and SSH2!).
2075 static char *ssh_userpass_input_buffer;
2076 static int ssh_userpass_input_buflen;
2077 static int ssh_userpass_input_bufpos;
2078 static int ssh_userpass_input_echo;
2080 /* Set up a username or password input loop on a given buffer. */
2081 void setup_userpass_input(char *buffer, int buflen, int echo)
2083 ssh_userpass_input_buffer = buffer;
2084 ssh_userpass_input_buflen = buflen;
2085 ssh_userpass_input_bufpos = 0;
2086 ssh_userpass_input_echo = echo;
2090 * Process some terminal data in the course of username/password
2091 * input. Returns >0 for success (line of input returned in
2092 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2093 * for inconclusive (keep waiting for more input please).
2095 int process_userpass_input(unsigned char *in, int inlen)
2100 switch (c = *in++) {
2103 ssh_userpass_input_buffer[ssh_userpass_input_bufpos] = 0;
2104 ssh_userpass_input_buffer[ssh_userpass_input_buflen-1] = 0;
2109 if (ssh_userpass_input_bufpos > 0) {
2110 if (ssh_userpass_input_echo)
2111 c_write_str("\b \b");
2112 ssh_userpass_input_bufpos--;
2117 while (ssh_userpass_input_bufpos > 0) {
2118 if (ssh_userpass_input_echo)
2119 c_write_str("\b \b");
2120 ssh_userpass_input_bufpos--;
2128 if (((c >= ' ' && c <= '~') ||
2129 ((unsigned char) c >= 160))
2130 && ssh_userpass_input_bufpos < ssh_userpass_input_buflen-1) {
2131 ssh_userpass_input_buffer[ssh_userpass_input_bufpos++] = c;
2132 if (ssh_userpass_input_echo)
2142 * Handle the key exchange and user authentication phases.
2144 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
2148 static unsigned char *rsabuf, *keystr1, *keystr2;
2149 unsigned char cookie[8];
2150 struct RSAKey servkey, hostkey;
2151 struct MD5Context md5c;
2152 static unsigned long supported_ciphers_mask, supported_auths_mask;
2153 static int tried_publickey, tried_agent;
2154 static int tis_auth_refused, ccard_auth_refused;
2155 static unsigned char session_id[16];
2156 static int cipher_type;
2157 static char username[100];
2158 static void *publickey_blob;
2159 int publickey_bloblen;
2166 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2167 bombout(("Public key packet not received"));
2171 logevent("Received public keys");
2173 memcpy(cookie, pktin.body, 8);
2175 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
2176 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
2179 * Log the host key fingerprint.
2183 logevent("Host key fingerprint is:");
2184 strcpy(logmsg, " ");
2185 hostkey.comment = NULL;
2186 rsa_fingerprint(logmsg + strlen(logmsg),
2187 sizeof(logmsg) - strlen(logmsg), &hostkey);
2191 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
2192 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
2193 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
2195 ssh1_local_protoflags =
2196 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2197 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2200 MD5Update(&md5c, keystr2, hostkey.bytes);
2201 MD5Update(&md5c, keystr1, servkey.bytes);
2202 MD5Update(&md5c, pktin.body, 8);
2203 MD5Final(session_id, &md5c);
2205 for (i = 0; i < 32; i++)
2206 session_key[i] = random_byte();
2208 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2210 rsabuf = smalloc(len);
2212 fatalbox("Out of memory");
2215 * Verify the host key.
2219 * First format the key into a string.
2221 int len = rsastr_len(&hostkey);
2222 char fingerprint[100];
2223 char *keystr = smalloc(len);
2225 fatalbox("Out of memory");
2226 rsastr_fmt(keystr, &hostkey);
2227 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2228 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
2233 for (i = 0; i < 32; i++) {
2234 rsabuf[i] = session_key[i];
2236 rsabuf[i] ^= session_id[i];
2239 if (hostkey.bytes > servkey.bytes) {
2240 rsaencrypt(rsabuf, 32, &servkey);
2241 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
2243 rsaencrypt(rsabuf, 32, &hostkey);
2244 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
2247 logevent("Encrypted session key");
2250 int cipher_chosen = 0, warn = 0;
2251 char *cipher_string = NULL;
2252 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2253 int next_cipher = cfg.ssh_cipherlist[i];
2254 if (next_cipher == CIPHER_WARN) {
2255 /* If/when we choose a cipher, warn about it */
2257 } else if (next_cipher == CIPHER_AES) {
2258 /* XXX Probably don't need to mention this. */
2259 logevent("AES not supported in SSH1, skipping");
2261 switch (next_cipher) {
2262 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
2263 cipher_string = "3DES"; break;
2264 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
2265 cipher_string = "Blowfish"; break;
2266 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
2267 cipher_string = "single-DES"; break;
2269 if (supported_ciphers_mask & (1 << cipher_type))
2273 if (!cipher_chosen) {
2274 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2275 bombout(("Server violates SSH 1 protocol by not "
2276 "supporting 3DES encryption"));
2278 /* shouldn't happen */
2279 bombout(("No supported ciphers found"));
2283 /* Warn about chosen cipher if necessary. */
2285 askcipher(cipher_string, 0);
2288 switch (cipher_type) {
2289 case SSH_CIPHER_3DES:
2290 logevent("Using 3DES encryption");
2292 case SSH_CIPHER_DES:
2293 logevent("Using single-DES encryption");
2295 case SSH_CIPHER_BLOWFISH:
2296 logevent("Using Blowfish encryption");
2300 send_packet(SSH1_CMSG_SESSION_KEY,
2301 PKT_CHAR, cipher_type,
2302 PKT_DATA, cookie, 8,
2303 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
2304 PKT_DATA, rsabuf, len,
2305 PKT_INT, ssh1_local_protoflags, PKT_END);
2307 logevent("Trying to enable encryption...");
2311 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2312 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
2313 cipher->sesskey(session_key);
2317 if (pktin.type != SSH1_SMSG_SUCCESS) {
2318 bombout(("Encryption not successfully enabled"));
2322 logevent("Successfully started encryption");
2326 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2327 if (ssh_get_line && !ssh_getline_pw_only) {
2328 if (!ssh_get_line("login as: ",
2329 username, sizeof(username), FALSE)) {
2331 * get_line failed to get a username.
2334 logevent("No username provided. Abandoning session.");
2335 ssh_state = SSH_STATE_CLOSED;
2340 c_write_str("login as: ");
2343 setup_userpass_input(username, sizeof(username), 1);
2345 crWaitUntil(!ispkt);
2346 ret = process_userpass_input(in, inlen);
2350 c_write_str("\r\n");
2353 strncpy(username, cfg.username, 99);
2354 username[99] = '\0';
2357 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2359 char userlog[22 + sizeof(username)];
2360 sprintf(userlog, "Sent username \"%s\"", username);
2362 if (flags & FLAG_INTERACTIVE &&
2363 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2364 strcat(userlog, "\r\n");
2365 c_write_str(userlog);
2372 if ((ssh_remote_bugs & BUG_CHOKES_ON_RSA)) {
2373 /* We must not attempt PK auth. Pretend we've already tried it. */
2374 tried_publickey = tried_agent = 1;
2376 tried_publickey = tried_agent = 0;
2378 tis_auth_refused = ccard_auth_refused = 0;
2379 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2381 if (!rsakey_pubblob(cfg.keyfile, &publickey_blob, &publickey_bloblen))
2382 publickey_blob = NULL;
2384 publickey_blob = NULL;
2386 while (pktin.type == SSH1_SMSG_FAILURE) {
2387 static char password[100];
2388 static char prompt[200];
2391 static int pwpkt_type;
2392 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2394 if (agent_exists() && !tried_agent) {
2396 * Attempt RSA authentication using Pageant.
2398 static unsigned char request[5], *response, *p;
2399 static int responselen;
2400 static int i, nkeys;
2401 static int authed = FALSE;
2405 logevent("Pageant is running. Requesting keys.");
2407 /* Request the keys held by the agent. */
2408 PUT_32BIT(request, 1);
2409 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2410 agent_query(request, 5, &r, &responselen);
2411 response = (unsigned char *) r;
2412 if (response && responselen >= 5 &&
2413 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2415 nkeys = GET_32BIT(p);
2419 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2422 for (i = 0; i < nkeys; i++) {
2423 static struct RSAKey key;
2424 static Bignum challenge;
2425 static char *commentp;
2426 static int commentlen;
2430 sprintf(buf, "Trying Pageant key #%d", i);
2433 if (publickey_blob &&
2434 !memcmp(p, publickey_blob, publickey_bloblen)) {
2435 logevent("This key matches configured key file");
2436 tried_publickey = 1;
2439 p += ssh1_read_bignum(p, &key.exponent);
2440 p += ssh1_read_bignum(p, &key.modulus);
2441 commentlen = GET_32BIT(p);
2445 send_packet(SSH1_CMSG_AUTH_RSA,
2446 PKT_BIGNUM, key.modulus, PKT_END);
2448 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2449 logevent("Key refused");
2452 logevent("Received RSA challenge");
2453 ssh1_read_bignum(pktin.body, &challenge);
2455 char *agentreq, *q, *ret;
2458 len = 1 + 4; /* message type, bit count */
2459 len += ssh1_bignum_length(key.exponent);
2460 len += ssh1_bignum_length(key.modulus);
2461 len += ssh1_bignum_length(challenge);
2462 len += 16; /* session id */
2463 len += 4; /* response format */
2464 agentreq = smalloc(4 + len);
2465 PUT_32BIT(agentreq, len);
2467 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2468 PUT_32BIT(q, bignum_bitcount(key.modulus));
2470 q += ssh1_write_bignum(q, key.exponent);
2471 q += ssh1_write_bignum(q, key.modulus);
2472 q += ssh1_write_bignum(q, challenge);
2473 memcpy(q, session_id, 16);
2475 PUT_32BIT(q, 1); /* response format */
2476 agent_query(agentreq, len + 4, &vret, &retlen);
2480 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2481 logevent("Sending Pageant's response");
2482 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2483 PKT_DATA, ret + 5, 16,
2487 if (pktin.type == SSH1_SMSG_SUCCESS) {
2489 ("Pageant's response accepted");
2490 if (flags & FLAG_VERBOSE) {
2492 ("Authenticated using RSA key \"");
2493 c_write(commentp, commentlen);
2494 c_write_str("\" from agent\r\n");
2499 ("Pageant's response not accepted");
2502 ("Pageant failed to answer challenge");
2506 logevent("No reply received from Pageant");
2509 freebn(key.exponent);
2510 freebn(key.modulus);
2519 if (*cfg.keyfile && !tried_publickey)
2520 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2522 if (cfg.try_tis_auth &&
2523 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2524 !tis_auth_refused) {
2525 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2526 logevent("Requested TIS authentication");
2527 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2529 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2530 logevent("TIS authentication declined");
2531 if (flags & FLAG_INTERACTIVE)
2532 c_write_str("TIS authentication refused.\r\n");
2533 tis_auth_refused = 1;
2536 int challengelen = ((pktin.body[0] << 24) |
2537 (pktin.body[1] << 16) |
2538 (pktin.body[2] << 8) |
2540 logevent("Received TIS challenge");
2541 if (challengelen > sizeof(prompt) - 1)
2542 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2543 memcpy(prompt, pktin.body + 4, challengelen);
2544 /* Prompt heuristic comes from OpenSSH */
2545 strncpy(prompt + challengelen,
2546 memchr(prompt, '\n', challengelen) ?
2547 "": "\r\nResponse: ",
2548 (sizeof prompt) - challengelen);
2549 prompt[(sizeof prompt) - 1] = '\0';
2552 if (cfg.try_tis_auth &&
2553 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2554 !ccard_auth_refused) {
2555 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2556 logevent("Requested CryptoCard authentication");
2557 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2559 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2560 logevent("CryptoCard authentication declined");
2561 c_write_str("CryptoCard authentication refused.\r\n");
2562 ccard_auth_refused = 1;
2565 int challengelen = ((pktin.body[0] << 24) |
2566 (pktin.body[1] << 16) |
2567 (pktin.body[2] << 8) |
2569 logevent("Received CryptoCard challenge");
2570 if (challengelen > sizeof(prompt) - 1)
2571 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2572 memcpy(prompt, pktin.body + 4, challengelen);
2573 strncpy(prompt + challengelen,
2574 memchr(prompt, '\n', challengelen) ?
2575 "" : "\r\nResponse: ",
2576 sizeof(prompt) - challengelen);
2577 prompt[sizeof(prompt) - 1] = '\0';
2580 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2581 sprintf(prompt, "%.90s@%.90s's password: ",
2582 username, savedhost);
2584 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2585 char *comment = NULL;
2588 if (flags & FLAG_VERBOSE)
2589 c_write_str("Trying public key authentication.\r\n");
2590 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2592 type = key_type(cfg.keyfile);
2593 if (type != SSH_KEYTYPE_SSH1) {
2594 sprintf(msgbuf, "Key is of wrong type (%s)",
2595 key_type_to_str(type));
2597 c_write_str(msgbuf);
2598 c_write_str("\r\n");
2599 tried_publickey = 1;
2602 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2603 if (flags & FLAG_VERBOSE)
2604 c_write_str("No passphrase required.\r\n");
2607 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2612 * Show password prompt, having first obtained it via a TIS
2613 * or CryptoCard exchange if we're doing TIS or CryptoCard
2617 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2619 * get_line failed to get a password (for example
2620 * because one was supplied on the command line
2621 * which has already failed to work). Terminate.
2623 send_packet(SSH1_MSG_DISCONNECT,
2624 PKT_STR, "No more passwords available to try",
2626 logevent("Unable to authenticate");
2627 connection_fatal("Unable to authenticate");
2628 ssh_state = SSH_STATE_CLOSED;
2632 /* Prompt may have come from server. We've munged it a bit, so
2633 * we know it to be zero-terminated at least once. */
2635 c_write_untrusted(prompt, strlen(prompt));
2638 setup_userpass_input(password, sizeof(password), 0);
2640 crWaitUntil(!ispkt);
2641 ret = process_userpass_input(in, inlen);
2645 c_write_str("\r\n");
2649 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2651 * Try public key authentication with the specified
2654 static struct RSAKey pubkey;
2655 static Bignum challenge, response;
2657 static unsigned char buffer[32];
2659 tried_publickey = 1;
2660 i = loadrsakey(cfg.keyfile, &pubkey, password);
2662 c_write_str("Couldn't load private key from ");
2663 c_write_str(cfg.keyfile);
2664 c_write_str(".\r\n");
2665 continue; /* go and try password */
2668 c_write_str("Wrong passphrase.\r\n");
2669 tried_publickey = 0;
2670 continue; /* try again */
2674 * Send a public key attempt.
2676 send_packet(SSH1_CMSG_AUTH_RSA,
2677 PKT_BIGNUM, pubkey.modulus, PKT_END);
2680 if (pktin.type == SSH1_SMSG_FAILURE) {
2681 c_write_str("Server refused our public key.\r\n");
2682 continue; /* go and try password */
2684 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2685 bombout(("Bizarre response to offer of public key"));
2688 ssh1_read_bignum(pktin.body, &challenge);
2689 response = rsadecrypt(challenge, &pubkey);
2690 freebn(pubkey.private_exponent); /* burn the evidence */
2692 for (i = 0; i < 32; i++) {
2693 buffer[i] = bignum_byte(response, 31 - i);
2697 MD5Update(&md5c, buffer, 32);
2698 MD5Update(&md5c, session_id, 16);
2699 MD5Final(buffer, &md5c);
2701 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2702 PKT_DATA, buffer, 16, PKT_END);
2705 if (pktin.type == SSH1_SMSG_FAILURE) {
2706 if (flags & FLAG_VERBOSE)
2708 ("Failed to authenticate with our public key.\r\n");
2709 continue; /* go and try password */
2710 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2712 ("Bizarre response to RSA authentication response"));
2716 break; /* we're through! */
2718 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2720 * Defence against traffic analysis: we send a
2721 * whole bunch of packets containing strings of
2722 * different lengths. One of these strings is the
2723 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2724 * The others are all random data in
2725 * SSH1_MSG_IGNORE packets. This way a passive
2726 * listener can't tell which is the password, and
2727 * hence can't deduce the password length.
2729 * Anybody with a password length greater than 16
2730 * bytes is going to have enough entropy in their
2731 * password that a listener won't find it _that_
2732 * much help to know how long it is. So what we'll
2735 * - if password length < 16, we send 15 packets
2736 * containing string lengths 1 through 15
2738 * - otherwise, we let N be the nearest multiple
2739 * of 8 below the password length, and send 8
2740 * packets containing string lengths N through
2741 * N+7. This won't obscure the order of
2742 * magnitude of the password length, but it will
2743 * introduce a bit of extra uncertainty.
2745 * A few servers (the old 1.2.18 through 1.2.22)
2746 * can't deal with SSH1_MSG_IGNORE. For these
2747 * servers, we need an alternative defence. We make
2748 * use of the fact that the password is interpreted
2749 * as a C string: so we can append a NUL, then some
2752 * One server (a Cisco one) can deal with neither
2753 * SSH1_MSG_IGNORE _nor_ a padded password string.
2754 * For this server we are left with no defences
2755 * against password length sniffing.
2757 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2759 * The server can deal with SSH1_MSG_IGNORE, so
2760 * we can use the primary defence.
2762 int bottom, top, pwlen, i;
2765 pwlen = strlen(password);
2767 bottom = 0; /* zero length passwords are OK! :-) */
2770 bottom = pwlen & ~7;
2774 assert(pwlen >= bottom && pwlen <= top);
2776 randomstr = smalloc(top + 1);
2778 for (i = bottom; i <= top; i++) {
2780 defer_packet(pwpkt_type, PKT_STR, password,
2783 for (j = 0; j < i; j++) {
2785 randomstr[j] = random_byte();
2786 } while (randomstr[j] == '\0');
2788 randomstr[i] = '\0';
2789 defer_packet(SSH1_MSG_IGNORE,
2790 PKT_STR, randomstr, PKT_END);
2793 logevent("Sending password with camouflage packets");
2794 ssh_pkt_defersend();
2796 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2798 * The server can't deal with SSH1_MSG_IGNORE
2799 * but can deal with padded passwords, so we
2800 * can use the secondary defence.
2806 len = strlen(password);
2807 if (len < sizeof(string)) {
2809 strcpy(string, password);
2810 len++; /* cover the zero byte */
2811 while (len < sizeof(string)) {
2812 string[len++] = (char) random_byte();
2817 logevent("Sending length-padded password");
2818 send_packet(pwpkt_type, PKT_INT, len,
2819 PKT_DATA, s, len, PKT_END);
2822 * The server has _both_
2823 * BUG_CHOKES_ON_SSH1_IGNORE and
2824 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2825 * therefore nothing we can do.
2828 len = strlen(password);
2829 logevent("Sending unpadded password");
2830 send_packet(pwpkt_type, PKT_INT, len,
2831 PKT_DATA, password, len, PKT_END);
2834 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2837 logevent("Sent password");
2838 memset(password, 0, strlen(password));
2840 if (pktin.type == SSH1_SMSG_FAILURE) {
2841 if (flags & FLAG_VERBOSE)
2842 c_write_str("Access denied\r\n");
2843 logevent("Authentication refused");
2844 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2845 logevent("Received disconnect request");
2846 ssh_state = SSH_STATE_CLOSED;
2848 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2849 bombout(("Strange packet received, type %d", pktin.type));
2854 logevent("Authentication successful");
2859 void sshfwd_close(struct ssh_channel *c)
2861 if (c && !c->closes) {
2863 * If the channel's remoteid is -1, we have sent
2864 * CHANNEL_OPEN for this channel, but it hasn't even been
2865 * acknowledged by the server. So we must set a close flag
2866 * on it now, and then when the server acks the channel
2867 * open, we can close it then.
2869 if (((int)c->remoteid) != -1) {
2870 if (ssh_version == 1) {
2871 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2874 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2875 ssh2_pkt_adduint32(c->remoteid);
2880 if (c->type == CHAN_X11) {
2882 logevent("Forwarded X11 connection terminated");
2883 } else if (c->type == CHAN_SOCKDATA ||
2884 c->type == CHAN_SOCKDATA_DORMANT) {
2886 logevent("Forwarded port closed");
2891 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2893 if (ssh_version == 1) {
2894 send_packet(SSH1_MSG_CHANNEL_DATA,
2895 PKT_INT, c->remoteid,
2896 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2898 * In SSH1 we can return 0 here - implying that forwarded
2899 * connections are never individually throttled - because
2900 * the only circumstance that can cause throttling will be
2901 * the whole SSH connection backing up, in which case
2902 * _everything_ will be throttled as a whole.
2906 ssh2_add_channel_data(c, buf, len);
2907 return ssh2_try_send(c);
2911 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2913 if (ssh_version == 1) {
2914 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2915 c->v.v1.throttling = 0;
2919 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2923 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2929 while (!do_ssh1_login(in, inlen, ispkt)) {
2932 if (ssh_state == SSH_STATE_CLOSED)
2935 if (cfg.agentfwd && agent_exists()) {
2936 logevent("Requesting agent forwarding");
2937 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2941 if (pktin.type != SSH1_SMSG_SUCCESS
2942 && pktin.type != SSH1_SMSG_FAILURE) {
2943 bombout(("Protocol confusion"));
2945 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2946 logevent("Agent forwarding refused");
2948 logevent("Agent forwarding enabled");
2949 ssh_agentfwd_enabled = TRUE;
2953 if (cfg.x11_forward) {
2954 char proto[20], data[64];
2955 logevent("Requesting X11 forwarding");
2956 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2957 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2958 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2959 PKT_STR, proto, PKT_STR, data,
2960 PKT_INT, 0, PKT_END);
2962 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2963 PKT_STR, proto, PKT_STR, data, PKT_END);
2968 if (pktin.type != SSH1_SMSG_SUCCESS
2969 && pktin.type != SSH1_SMSG_FAILURE) {
2970 bombout(("Protocol confusion"));
2972 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2973 logevent("X11 forwarding refused");
2975 logevent("X11 forwarding enabled");
2976 ssh_X11_fwd_enabled = TRUE;
2984 int sport,dport,sserv,dserv;
2985 char sports[256], dports[256], host[256];
2989 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
2990 /* Add port forwardings. */
2995 while (*e && *e != '\t')
3001 while (*e && *e != ':')
3011 dport = atoi(dports);
3015 se = getservbyname(dports, NULL);
3017 dport = ntohs(se->s_port);
3020 "Service lookup failed for destination port \"%s\"",
3025 sport = atoi(sports);
3029 se = getservbyname(sports, NULL);
3031 sport = ntohs(se->s_port);
3034 "Service lookup failed for source port \"%s\"",
3039 if (sport && dport) {
3041 pfd_addforward(host, dport, sport);
3042 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3043 " %s:%.*s%.*s%d%.*s",
3044 sserv ? strlen(sports) : 0, sports,
3045 sserv, "(", sport, sserv, ")",
3047 dserv ? strlen(dports) : 0, dports,
3048 dserv, "(", dport, dserv, ")");
3051 struct ssh_rportfwd *pf;
3052 pf = smalloc(sizeof(*pf));
3053 strcpy(pf->dhost, host);
3055 if (add234(ssh_rportfwds, pf) != pf) {
3057 "Duplicate remote port forwarding to %s:%d",
3062 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3063 " forward to %s:%.*s%.*s%d%.*s",
3064 sserv ? strlen(sports) : 0, sports,
3065 sserv, "(", sport, sserv, ")",
3067 dserv ? strlen(dports) : 0, dports,
3068 dserv, "(", dport, dserv, ")");
3070 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
3078 if (pktin.type != SSH1_SMSG_SUCCESS
3079 && pktin.type != SSH1_SMSG_FAILURE) {
3080 bombout(("Protocol confusion"));
3082 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3083 c_write_str("Server refused port forwarding\r\n");
3084 ssh_editing = ssh_echoing = 1;
3086 logevent("Remote port forwarding enabled");
3094 send_packet(SSH1_CMSG_REQUEST_PTY,
3095 PKT_STR, cfg.termtype,
3096 PKT_INT, rows, PKT_INT, cols,
3097 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3098 ssh_state = SSH_STATE_INTERMED;
3102 if (pktin.type != SSH1_SMSG_SUCCESS
3103 && pktin.type != SSH1_SMSG_FAILURE) {
3104 bombout(("Protocol confusion"));
3106 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3107 c_write_str("Server refused to allocate pty\r\n");
3108 ssh_editing = ssh_echoing = 1;
3110 logevent("Allocated pty");
3112 ssh_editing = ssh_echoing = 1;
3115 if (cfg.compression) {
3116 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3120 if (pktin.type != SSH1_SMSG_SUCCESS
3121 && pktin.type != SSH1_SMSG_FAILURE) {
3122 bombout(("Protocol confusion"));
3124 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3125 c_write_str("Server refused to compress\r\n");
3127 logevent("Started compression");
3128 ssh1_compressing = TRUE;
3129 zlib_compress_init();
3130 zlib_decompress_init();
3134 * Start the shell or command.
3136 * Special case: if the first-choice command is an SSH2
3137 * subsystem (hence not usable here) and the second choice
3138 * exists, we fall straight back to that.
3141 char *cmd = cfg.remote_cmd_ptr;
3143 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3144 cmd = cfg.remote_cmd_ptr2;
3145 ssh_fallback_cmd = TRUE;
3148 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3150 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
3151 logevent("Started session");
3154 ssh_state = SSH_STATE_SESSION;
3158 ssh_special(TS_EOF);
3160 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
3162 ssh_channels = newtree234(ssh_channelcmp);
3166 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
3167 pktin.type == SSH1_SMSG_STDERR_DATA) {
3168 long len = GET_32BIT(pktin.body);
3170 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
3171 pktin.body + 4, len);
3172 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3173 ssh1_stdout_throttling = 1;
3176 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
3177 ssh_state = SSH_STATE_CLOSED;
3178 logevent("Received disconnect request");
3180 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
3181 /* Remote side is trying to open a channel to talk to our
3182 * X-Server. Give them back a local channel number. */
3183 struct ssh_channel *c;
3185 logevent("Received X11 connect request");
3186 /* Refuse if X11 forwarding is disabled. */
3187 if (!ssh_X11_fwd_enabled) {
3188 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3189 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3190 logevent("Rejected X11 connect request");
3192 c = smalloc(sizeof(struct ssh_channel));
3194 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3195 logevent("opening X11 forward connection failed");
3197 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3198 PKT_INT, GET_32BIT(pktin.body),
3202 ("opening X11 forward connection succeeded");
3203 c->remoteid = GET_32BIT(pktin.body);
3204 c->localid = alloc_channel_id();
3206 c->v.v1.throttling = 0;
3207 c->type = CHAN_X11; /* identify channel type */
3208 add234(ssh_channels, c);
3209 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3210 PKT_INT, c->remoteid, PKT_INT,
3211 c->localid, PKT_END);
3212 logevent("Opened X11 forward channel");
3215 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
3216 /* Remote side is trying to open a channel to talk to our
3217 * agent. Give them back a local channel number. */
3218 struct ssh_channel *c;
3220 /* Refuse if agent forwarding is disabled. */
3221 if (!ssh_agentfwd_enabled) {
3222 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3223 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3225 c = smalloc(sizeof(struct ssh_channel));
3226 c->remoteid = GET_32BIT(pktin.body);
3227 c->localid = alloc_channel_id();
3229 c->v.v1.throttling = 0;
3230 c->type = CHAN_AGENT; /* identify channel type */
3231 c->u.a.lensofar = 0;
3232 add234(ssh_channels, c);
3233 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3234 PKT_INT, c->remoteid, PKT_INT, c->localid,
3237 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
3238 /* Remote side is trying to open a channel to talk to a
3239 * forwarded port. Give them back a local channel number. */
3240 struct ssh_channel *c;
3241 struct ssh_rportfwd pf;
3243 char host[256], buf[1024];
3245 c = smalloc(sizeof(struct ssh_channel));
3247 hostsize = GET_32BIT(pktin.body+4);
3248 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
3249 if (h+1 < host+sizeof(host))
3254 port = GET_32BIT(p);
3256 strcpy(pf.dhost, host);
3259 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
3260 sprintf(buf, "Rejected remote port open request for %s:%d",
3263 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3264 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3266 sprintf(buf, "Received remote port open request for %s:%d",
3269 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3272 sprintf(buf, "Port open failed: %s", e);
3275 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3276 PKT_INT, GET_32BIT(pktin.body),
3279 c->remoteid = GET_32BIT(pktin.body);
3280 c->localid = alloc_channel_id();
3282 c->v.v1.throttling = 0;
3283 c->type = CHAN_SOCKDATA; /* identify channel type */
3284 add234(ssh_channels, c);
3285 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3286 PKT_INT, c->remoteid, PKT_INT,
3287 c->localid, PKT_END);
3288 logevent("Forwarded port opened successfully");
3292 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3293 unsigned int remoteid = GET_32BIT(pktin.body);
3294 unsigned int localid = GET_32BIT(pktin.body+4);
3295 struct ssh_channel *c;
3297 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3298 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3299 c->remoteid = localid;
3300 c->type = CHAN_SOCKDATA;
3301 c->v.v1.throttling = 0;
3302 pfd_confirm(c->u.pfd.s);
3305 if (c && c->closes) {
3307 * We have a pending close on this channel,
3308 * which we decided on before the server acked
3309 * the channel open. So now we know the
3310 * remoteid, we can close it again.
3312 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3316 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3317 unsigned int remoteid = GET_32BIT(pktin.body);
3318 unsigned int localid = GET_32BIT(pktin.body+4);
3319 struct ssh_channel *c;
3321 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3322 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3323 logevent("Forwarded connection refused by server");
3324 pfd_close(c->u.pfd.s);
3325 del234(ssh_channels, c);
3329 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3330 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3331 /* Remote side closes a channel. */
3332 unsigned i = GET_32BIT(pktin.body);
3333 struct ssh_channel *c;
3334 c = find234(ssh_channels, &i, ssh_channelfind);
3338 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3339 if (!(c->closes & closetype))
3340 send_packet(pktin.type, PKT_INT, c->remoteid,
3342 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3343 logevent("Forwarded X11 connection terminated");
3344 assert(c->u.x11.s != NULL);
3345 x11_close(c->u.x11.s);
3348 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3349 logevent("Forwarded port closed");
3350 assert(c->u.pfd.s != NULL);
3351 pfd_close(c->u.pfd.s);
3354 c->closes |= closetype;
3355 if (c->closes == 3) {
3356 del234(ssh_channels, c);
3360 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
3361 /* Data sent down one of our channels. */
3362 int i = GET_32BIT(pktin.body);
3363 int len = GET_32BIT(pktin.body + 4);
3364 unsigned char *p = pktin.body + 8;
3365 struct ssh_channel *c;
3366 c = find234(ssh_channels, &i, ssh_channelfind);
3371 bufsize = x11_send(c->u.x11.s, p, len);
3374 bufsize = pfd_send(c->u.pfd.s, p, len);
3377 /* Data for an agent message. Buffer it. */
3379 if (c->u.a.lensofar < 4) {
3380 int l = min(4 - c->u.a.lensofar, len);
3381 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3385 c->u.a.lensofar += l;
3387 if (c->u.a.lensofar == 4) {
3389 4 + GET_32BIT(c->u.a.msglen);
3390 c->u.a.message = smalloc(c->u.a.totallen);
3391 memcpy(c->u.a.message, c->u.a.msglen, 4);
3393 if (c->u.a.lensofar >= 4 && len > 0) {
3395 min(c->u.a.totallen - c->u.a.lensofar,
3397 memcpy(c->u.a.message + c->u.a.lensofar, p,
3401 c->u.a.lensofar += l;
3403 if (c->u.a.lensofar == c->u.a.totallen) {
3404 void *reply, *sentreply;
3406 agent_query(c->u.a.message,
3407 c->u.a.totallen, &reply,
3412 /* Fake SSH_AGENT_FAILURE. */
3413 sentreply = "\0\0\0\1\5";
3416 send_packet(SSH1_MSG_CHANNEL_DATA,
3417 PKT_INT, c->remoteid,
3419 PKT_DATA, sentreply, replylen,
3423 sfree(c->u.a.message);
3424 c->u.a.lensofar = 0;
3427 bufsize = 0; /* agent channels never back up */
3430 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3431 c->v.v1.throttling = 1;
3435 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3436 /* may be from EXEC_SHELL on some servers */
3437 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3438 /* may be from EXEC_SHELL on some servers
3439 * if no pty is available or in other odd cases. Ignore */
3440 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3442 ssh_exitcode = GET_32BIT(pktin.body);
3443 sprintf(buf, "Server sent command exit status %d",
3446 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3448 * In case `helpful' firewalls or proxies tack
3449 * extra human-readable text on the end of the
3450 * session which we might mistake for another
3451 * encrypted packet, we close the session once
3452 * we've sent EXIT_CONFIRMATION.
3454 ssh_state = SSH_STATE_CLOSED;
3457 bombout(("Strange packet received: type %d", pktin.type));
3462 int len = min(inlen, 512);
3463 send_packet(SSH1_CMSG_STDIN_DATA,
3464 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3475 * Utility routine for decoding comma-separated strings in KEXINIT.
3477 static int in_commasep_string(char *needle, char *haystack, int haylen)
3479 int needlen = strlen(needle);
3482 * Is it at the start of the string?
3484 if (haylen >= needlen && /* haystack is long enough */
3485 !memcmp(needle, haystack, needlen) && /* initial match */
3486 (haylen == needlen || haystack[needlen] == ',')
3487 /* either , or EOS follows */
3491 * If not, search for the next comma and resume after that.
3492 * If no comma found, terminate.
3494 while (haylen > 0 && *haystack != ',')
3495 haylen--, haystack++;
3498 haylen--, haystack++; /* skip over comma itself */
3503 * SSH2 key creation method.
3505 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3509 /* First 20 bytes. */
3511 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3513 SHA_Bytes(&s, H, 20);
3514 SHA_Bytes(&s, &chr, 1);
3515 SHA_Bytes(&s, sessid, 20);
3516 SHA_Final(&s, keyspace);
3517 /* Next 20 bytes. */
3519 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3521 SHA_Bytes(&s, H, 20);
3522 SHA_Bytes(&s, keyspace, 20);
3523 SHA_Final(&s, keyspace + 20);
3527 * Handle the SSH2 transport layer.
3529 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3531 static int i, j, len, nbits, pbits, warn;
3533 static Bignum p, g, e, f, K;
3534 static int kex_init_value, kex_reply_value;
3535 static const struct ssh_mac **maclist;
3537 static const struct ssh2_cipher *cscipher_tobe = NULL;
3538 static const struct ssh2_cipher *sccipher_tobe = NULL;
3539 static const struct ssh_mac *csmac_tobe = NULL;
3540 static const struct ssh_mac *scmac_tobe = NULL;
3541 static const struct ssh_compress *cscomp_tobe = NULL;
3542 static const struct ssh_compress *sccomp_tobe = NULL;
3543 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3544 static int hostkeylen, siglen;
3545 static void *hkey; /* actual host key */
3546 static unsigned char exchange_hash[20];
3547 static unsigned char keyspace[40];
3548 static int n_preferred_ciphers;
3549 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3550 static const struct ssh_compress *preferred_comp;
3551 static int cipherstr_started;
3552 static int first_kex;
3559 * Set up the preferred ciphers. (NULL => warn below here)
3561 n_preferred_ciphers = 0;
3562 for (i = 0; i < CIPHER_MAX; i++) {
3563 switch (cfg.ssh_cipherlist[i]) {
3564 case CIPHER_BLOWFISH:
3565 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3566 n_preferred_ciphers++;
3569 if (cfg.ssh2_des_cbc) {
3570 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3571 n_preferred_ciphers++;
3575 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3576 n_preferred_ciphers++;
3579 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3580 n_preferred_ciphers++;
3583 /* Flag for later. Don't bother if it's the last in
3585 if (i < CIPHER_MAX - 1) {
3586 preferred_ciphers[n_preferred_ciphers] = NULL;
3587 n_preferred_ciphers++;
3594 * Set up preferred compression.
3596 if (cfg.compression)
3597 preferred_comp = &ssh_zlib;
3599 preferred_comp = &ssh_comp_none;
3602 * Be prepared to work around the buggy MAC problem.
3604 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3605 maclist = buggymacs, nmacs = lenof(buggymacs);
3607 maclist = macs, nmacs = lenof(macs);
3611 * Construct and send our key exchange packet.
3613 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3614 for (i = 0; i < 16; i++)
3615 ssh2_pkt_addbyte((unsigned char) random_byte());
3616 /* List key exchange algorithms. */
3617 ssh2_pkt_addstring_start();
3618 for (i = 0; i < lenof(kex_algs); i++) {
3619 ssh2_pkt_addstring_str(kex_algs[i]->name);
3620 if (i < lenof(kex_algs) - 1)
3621 ssh2_pkt_addstring_str(",");
3623 /* List server host key algorithms. */
3624 ssh2_pkt_addstring_start();
3625 for (i = 0; i < lenof(hostkey_algs); i++) {
3626 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3627 if (i < lenof(hostkey_algs) - 1)
3628 ssh2_pkt_addstring_str(",");
3630 /* List client->server encryption algorithms. */
3631 ssh2_pkt_addstring_start();
3632 cipherstr_started = 0;
3633 for (i = 0; i < n_preferred_ciphers; i++) {
3634 const struct ssh2_ciphers *c = preferred_ciphers[i];
3635 if (!c) continue; /* warning flag */
3636 for (j = 0; j < c->nciphers; j++) {
3637 if (cipherstr_started)
3638 ssh2_pkt_addstring_str(",");
3639 ssh2_pkt_addstring_str(c->list[j]->name);
3640 cipherstr_started = 1;
3643 /* List server->client encryption algorithms. */
3644 ssh2_pkt_addstring_start();
3645 cipherstr_started = 0;
3646 for (i = 0; i < n_preferred_ciphers; i++) {
3647 const struct ssh2_ciphers *c = preferred_ciphers[i];
3648 if (!c) continue; /* warning flag */
3649 for (j = 0; j < c->nciphers; j++) {
3650 if (cipherstr_started)
3651 ssh2_pkt_addstring_str(",");
3652 ssh2_pkt_addstring_str(c->list[j]->name);
3653 cipherstr_started = 1;
3656 /* List client->server MAC algorithms. */
3657 ssh2_pkt_addstring_start();
3658 for (i = 0; i < nmacs; i++) {
3659 ssh2_pkt_addstring_str(maclist[i]->name);
3661 ssh2_pkt_addstring_str(",");
3663 /* List server->client MAC algorithms. */
3664 ssh2_pkt_addstring_start();
3665 for (i = 0; i < nmacs; i++) {
3666 ssh2_pkt_addstring_str(maclist[i]->name);
3668 ssh2_pkt_addstring_str(",");
3670 /* List client->server compression algorithms. */
3671 ssh2_pkt_addstring_start();
3672 for (i = 0; i < lenof(compressions) + 1; i++) {
3673 const struct ssh_compress *c =
3674 i == 0 ? preferred_comp : compressions[i - 1];
3675 ssh2_pkt_addstring_str(c->name);
3676 if (i < lenof(compressions))
3677 ssh2_pkt_addstring_str(",");
3679 /* List server->client compression algorithms. */
3680 ssh2_pkt_addstring_start();
3681 for (i = 0; i < lenof(compressions) + 1; i++) {
3682 const struct ssh_compress *c =
3683 i == 0 ? preferred_comp : compressions[i - 1];
3684 ssh2_pkt_addstring_str(c->name);
3685 if (i < lenof(compressions))
3686 ssh2_pkt_addstring_str(",");
3688 /* List client->server languages. Empty list. */
3689 ssh2_pkt_addstring_start();
3690 /* List server->client languages. Empty list. */
3691 ssh2_pkt_addstring_start();
3692 /* First KEX packet does _not_ follow, because we're not that brave. */
3693 ssh2_pkt_addbool(FALSE);
3695 ssh2_pkt_adduint32(0);
3697 exhash = exhashbase;
3698 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3704 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3707 * Now examine the other side's KEXINIT to see what we're up
3710 if (pktin.type != SSH2_MSG_KEXINIT) {
3711 bombout(("expected key exchange packet from server"));
3716 cscipher_tobe = NULL;
3717 sccipher_tobe = NULL;
3722 pktin.savedpos += 16; /* skip garbage cookie */
3723 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3724 for (i = 0; i < lenof(kex_algs); i++) {
3725 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3730 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3731 for (i = 0; i < lenof(hostkey_algs); i++) {
3732 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3733 hostkey = hostkey_algs[i];
3737 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3739 for (i = 0; i < n_preferred_ciphers; i++) {
3740 const struct ssh2_ciphers *c = preferred_ciphers[i];
3744 for (j = 0; j < c->nciphers; j++) {
3745 if (in_commasep_string(c->list[j]->name, str, len)) {
3746 cscipher_tobe = c->list[j];
3751 if (cscipher_tobe) {
3753 askcipher(cscipher_tobe->name, 1);
3757 if (!cscipher_tobe) {
3758 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3762 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3764 for (i = 0; i < n_preferred_ciphers; i++) {
3765 const struct ssh2_ciphers *c = preferred_ciphers[i];
3769 for (j = 0; j < c->nciphers; j++) {
3770 if (in_commasep_string(c->list[j]->name, str, len)) {
3771 sccipher_tobe = c->list[j];
3776 if (sccipher_tobe) {
3778 askcipher(sccipher_tobe->name, 2);
3782 if (!sccipher_tobe) {
3783 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3787 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3788 for (i = 0; i < nmacs; i++) {
3789 if (in_commasep_string(maclist[i]->name, str, len)) {
3790 csmac_tobe = maclist[i];
3794 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3795 for (i = 0; i < nmacs; i++) {
3796 if (in_commasep_string(maclist[i]->name, str, len)) {
3797 scmac_tobe = maclist[i];
3801 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3802 for (i = 0; i < lenof(compressions) + 1; i++) {
3803 const struct ssh_compress *c =
3804 i == 0 ? preferred_comp : compressions[i - 1];
3805 if (in_commasep_string(c->name, str, len)) {
3810 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3811 for (i = 0; i < lenof(compressions) + 1; i++) {
3812 const struct ssh_compress *c =
3813 i == 0 ? preferred_comp : compressions[i - 1];
3814 if (in_commasep_string(c->name, str, len)) {
3821 * Work out the number of bits of key we will need from the key
3822 * exchange. We start with the maximum key length of either
3828 csbits = cscipher_tobe->keylen;
3829 scbits = sccipher_tobe->keylen;
3830 nbits = (csbits > scbits ? csbits : scbits);
3832 /* The keys only have 160-bit entropy, since they're based on
3833 * a SHA-1 hash. So cap the key size at 160 bits. */
3838 * If we're doing Diffie-Hellman group exchange, start by
3839 * requesting a group.
3841 if (kex == &ssh_diffiehellman_gex) {
3842 logevent("Doing Diffie-Hellman group exchange");
3843 ssh_pkt_ctx |= SSH2_PKTCTX_DHGEX;
3845 * Work out how big a DH group we will need to allow that
3848 pbits = 512 << ((nbits - 1) / 64);
3849 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3850 ssh2_pkt_adduint32(pbits);
3854 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3855 bombout(("expected key exchange group packet from server"));
3858 p = ssh2_pkt_getmp();
3859 g = ssh2_pkt_getmp();
3860 dh_setup_group(p, g);
3861 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3862 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3864 ssh_pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3866 kex_init_value = SSH2_MSG_KEXDH_INIT;
3867 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3870 logevent("Doing Diffie-Hellman key exchange");
3872 * Now generate and send e for Diffie-Hellman.
3874 e = dh_create_e(nbits * 2);
3875 ssh2_pkt_init(kex_init_value);
3880 if (pktin.type != kex_reply_value) {
3881 bombout(("expected key exchange reply packet from server"));
3884 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3885 f = ssh2_pkt_getmp();
3886 ssh2_pkt_getstring(&sigdata, &siglen);
3890 sha_string(&exhash, hostkeydata, hostkeylen);
3891 if (kex == &ssh_diffiehellman_gex) {
3892 sha_uint32(&exhash, pbits);
3893 sha_mpint(&exhash, p);
3894 sha_mpint(&exhash, g);
3896 sha_mpint(&exhash, e);
3897 sha_mpint(&exhash, f);
3898 sha_mpint(&exhash, K);
3899 SHA_Final(&exhash, exchange_hash);
3904 debug(("Exchange hash is:\n"));
3905 dmemdump(exchange_hash, 20);
3908 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3910 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3911 bombout(("Server's host key did not match the signature supplied"));
3916 * Authenticate remote host: verify host key. (We've already
3917 * checked the signature of the exchange hash.)
3919 keystr = hostkey->fmtkey(hkey);
3920 fingerprint = hostkey->fingerprint(hkey);
3921 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3922 keystr, fingerprint);
3923 if (first_kex) { /* don't bother logging this in rekeys */
3924 logevent("Host key fingerprint is:");
3925 logevent(fingerprint);
3929 hostkey->freekey(hkey);
3932 * Send SSH2_MSG_NEWKEYS.
3934 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3938 * Expect SSH2_MSG_NEWKEYS from server.
3941 if (pktin.type != SSH2_MSG_NEWKEYS) {
3942 bombout(("expected new-keys packet from server"));
3947 * Create and initialise session keys.
3949 cscipher = cscipher_tobe;
3950 sccipher = sccipher_tobe;
3953 cscomp = cscomp_tobe;
3954 sccomp = sccomp_tobe;
3955 cscomp->compress_init();
3956 sccomp->decompress_init();
3958 * Set IVs after keys. Here we use the exchange hash from the
3959 * _first_ key exchange.
3962 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3963 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3964 cscipher->setcskey(keyspace);
3965 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3966 sccipher->setsckey(keyspace);
3967 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
3968 cscipher->setcsiv(keyspace);
3969 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
3970 sccipher->setsciv(keyspace);
3971 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
3972 csmac->setcskey(keyspace);
3973 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
3974 scmac->setsckey(keyspace);
3977 * If this is the first key exchange phase, we must pass the
3978 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3979 * wants to see it but because it will need time to initialise
3980 * itself before it sees an actual packet. In subsequent key
3981 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3982 * it would only confuse the layer above.
3990 * Now we're encrypting. Begin returning 1 to the protocol main
3991 * function so that other things can run on top of the
3992 * transport. If we ever see a KEXINIT, we must go back to the
3995 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
3998 logevent("Server initiated key re-exchange");
3999 goto begin_key_exchange;
4005 * Add data to an SSH2 channel output buffer.
4007 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4010 bufchain_add(&c->v.v2.outbuffer, buf, len);
4014 * Attempt to send data on an SSH2 channel.
4016 static int ssh2_try_send(struct ssh_channel *c)
4018 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4021 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4022 if ((unsigned)len > c->v.v2.remwindow)
4023 len = c->v.v2.remwindow;
4024 if ((unsigned)len > c->v.v2.remmaxpkt)
4025 len = c->v.v2.remmaxpkt;
4026 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4027 ssh2_pkt_adduint32(c->remoteid);
4028 ssh2_pkt_addstring_start();
4029 ssh2_pkt_addstring_data(data, len);
4031 bufchain_consume(&c->v.v2.outbuffer, len);
4032 c->v.v2.remwindow -= len;
4036 * After having sent as much data as we can, return the amount
4039 return bufchain_size(&c->v.v2.outbuffer);
4043 * Potentially enlarge the window on an SSH2 channel.
4045 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4048 * Never send WINDOW_ADJUST for a channel that the remote side
4049 * already thinks it's closed; there's no point, since it won't
4050 * be sending any more data anyway.
4055 if (newwin > c->v.v2.locwindow) {
4056 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4057 ssh2_pkt_adduint32(c->remoteid);
4058 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
4060 c->v.v2.locwindow = newwin;
4065 * Handle the SSH2 userauth and connection layers.
4067 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
4070 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4072 AUTH_KEYBOARD_INTERACTIVE
4076 AUTH_TYPE_PUBLICKEY,
4077 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4078 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4080 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4081 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4083 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4084 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
4085 static int kbd_inter_running;
4086 static int we_are_in;
4087 static int num_prompts, curr_prompt, echo;
4088 static char username[100];
4089 static int got_username;
4090 static char pwprompt[200];
4091 static char password[100];
4092 static void *publickey_blob;
4093 static int publickey_bloblen;
4098 * Request userauth protocol, and await a response to it.
4100 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
4101 ssh2_pkt_addstring("ssh-userauth");
4103 crWaitUntilV(ispkt);
4104 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4105 bombout(("Server refused user authentication protocol"));
4110 * We repeat this whole loop, including the username prompt,
4111 * until we manage a successful authentication. If the user
4112 * types the wrong _password_, they are sent back to the
4113 * beginning to try another username. (If they specify a
4114 * username in the config, they are never asked, even if they
4115 * do give a wrong password.)
4117 * I think this best serves the needs of
4119 * - the people who have no configuration, no keys, and just
4120 * want to try repeated (username,password) pairs until they
4121 * type both correctly
4123 * - people who have keys and configuration but occasionally
4124 * need to fall back to passwords
4126 * - people with a key held in Pageant, who might not have
4127 * logged in to a particular machine before; so they want to
4128 * type a username, and then _either_ their key will be
4129 * accepted, _or_ they will type a password. If they mistype
4130 * the username they will want to be able to get back and
4134 got_username = FALSE;
4139 if (got_username && !cfg.change_username) {
4141 * We got a username last time round this loop, and
4142 * with change_username turned off we don't try to get
4145 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4146 if (ssh_get_line && !ssh_getline_pw_only) {
4147 if (!ssh_get_line("login as: ",
4148 username, sizeof(username), FALSE)) {
4150 * get_line failed to get a username.
4153 logevent("No username provided. Abandoning session.");
4154 ssh_state = SSH_STATE_CLOSED;
4159 c_write_str("login as: ");
4161 setup_userpass_input(username, sizeof(username), 1);
4163 crWaitUntilV(!ispkt);
4164 ret = process_userpass_input(in, inlen);
4169 c_write_str("\r\n");
4170 username[strcspn(username, "\n\r")] = '\0';
4173 strncpy(username, cfg.username, 99);
4174 username[99] = '\0';
4175 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4176 sprintf(stuff, "Using username \"%s\".\r\n", username);
4180 got_username = TRUE;
4183 * Send an authentication request using method "none": (a)
4184 * just in case it succeeds, and (b) so that we know what
4185 * authentication methods we can usefully try next.
4187 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4189 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4190 ssh2_pkt_addstring(username);
4191 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4192 ssh2_pkt_addstring("none"); /* method */
4194 type = AUTH_TYPE_NONE;
4198 tried_pubkey_config = FALSE;
4199 tried_agent = FALSE;
4200 tried_keyb_inter = FALSE;
4201 kbd_inter_running = FALSE;
4202 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4205 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4206 keytype = key_type(cfg.keyfile);
4207 if (keytype == SSH_KEYTYPE_SSH2)
4208 publickey_blob = ssh2_userkey_loadpub(cfg.keyfile, NULL,
4209 &publickey_bloblen);
4212 logeventf("Unable to use this key file (%s)",
4213 key_type_to_str(keytype));
4214 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4215 cfg.keyfile, key_type_to_str(keytype));
4216 c_write_str(msgbuf);
4217 publickey_blob = NULL;
4220 publickey_blob = NULL;
4224 * Wait for the result of the last authentication request.
4227 crWaitUntilV(ispkt);
4228 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4232 * Don't show the banner if we're operating in
4233 * non-verbose non-interactive mode. (It's probably
4234 * a script, which means nobody will read the
4235 * banner _anyway_, and moreover the printing of
4236 * the banner will screw up processing on the
4237 * output of (say) plink.)
4239 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4240 ssh2_pkt_getstring(&banner, &size);
4242 c_write_untrusted(banner, size);
4244 crWaitUntilV(ispkt);
4246 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4247 logevent("Access granted");
4252 if (kbd_inter_running &&
4253 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4255 * This is either a further set-of-prompts packet
4256 * in keyboard-interactive authentication, or it's
4257 * the same one and we came back here with `gotit'
4258 * set. In the former case, we must reset the
4259 * curr_prompt variable.
4263 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4264 bombout(("Strange packet received during authentication: type %d",
4272 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4273 * we can look at the string in it and know what we can
4274 * helpfully try next.
4276 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4279 ssh2_pkt_getstring(&methods, &methlen);
4280 kbd_inter_running = FALSE;
4281 if (!ssh2_pkt_getbool()) {
4283 * We have received an unequivocal Access
4284 * Denied. This can translate to a variety of
4287 * - if we'd just tried "none" authentication,
4288 * it's not worth printing anything at all
4290 * - if we'd just tried a public key _offer_,
4291 * the message should be "Server refused our
4292 * key" (or no message at all if the key
4293 * came from Pageant)
4295 * - if we'd just tried anything else, the
4296 * message really should be "Access denied".
4298 * Additionally, if we'd just tried password
4299 * authentication, we should break out of this
4300 * whole loop so as to go back to the username
4303 if (type == AUTH_TYPE_NONE) {
4305 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4306 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4307 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4308 c_write_str("Server refused our key\r\n");
4309 logevent("Server refused public key");
4310 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4311 /* server declined keyboard-interactive; ignore */
4313 c_write_str("Access denied\r\n");
4314 logevent("Access denied");
4315 if (type == AUTH_TYPE_PASSWORD) {
4321 c_write_str("Further authentication required\r\n");
4322 logevent("Further authentication required");
4326 in_commasep_string("publickey", methods, methlen);
4328 in_commasep_string("password", methods, methlen);
4329 can_keyb_inter = cfg.try_ki_auth &&
4330 in_commasep_string("keyboard-interactive", methods, methlen);
4334 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4337 * Most password/passphrase prompts will be
4338 * non-echoing, so we set this to 0 by default.
4339 * Exception is that some keyboard-interactive prompts
4340 * can be echoing, in which case we'll set this to 1.
4344 if (!method && can_pubkey && agent_exists() && !tried_agent) {
4346 * Attempt public-key authentication using Pageant.
4348 static unsigned char request[5], *response, *p;
4349 static int responselen;
4350 static int i, nkeys;
4351 static int authed = FALSE;
4354 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4355 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4359 logevent("Pageant is running. Requesting keys.");
4361 /* Request the keys held by the agent. */
4362 PUT_32BIT(request, 1);
4363 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4364 agent_query(request, 5, &r, &responselen);
4365 response = (unsigned char *) r;
4366 if (response && responselen >= 5 &&
4367 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4369 nkeys = GET_32BIT(p);
4373 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
4376 for (i = 0; i < nkeys; i++) {
4377 static char *pkblob, *alg, *commentp;
4378 static int pklen, alglen, commentlen;
4379 static int siglen, retlen, len;
4380 static char *q, *agentreq, *ret;
4385 sprintf(buf, "Trying Pageant key #%d", i);
4388 pklen = GET_32BIT(p);
4390 if (publickey_blob &&
4391 pklen == publickey_bloblen &&
4392 !memcmp(p, publickey_blob, publickey_bloblen)) {
4393 logevent("This key matches configured key file");
4394 tried_pubkey_config = 1;
4398 alglen = GET_32BIT(pkblob);
4400 commentlen = GET_32BIT(p);
4404 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4405 ssh2_pkt_addstring(username);
4406 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4407 ssh2_pkt_addstring("publickey"); /* method */
4408 ssh2_pkt_addbool(FALSE); /* no signature included */
4409 ssh2_pkt_addstring_start();
4410 ssh2_pkt_addstring_data(alg, alglen);
4411 ssh2_pkt_addstring_start();
4412 ssh2_pkt_addstring_data(pkblob, pklen);
4415 crWaitUntilV(ispkt);
4416 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4417 logevent("Key refused");
4421 if (flags & FLAG_VERBOSE) {
4423 ("Authenticating with public key \"");
4424 c_write(commentp, commentlen);
4425 c_write_str("\" from agent\r\n");
4429 * Server is willing to accept the key.
4430 * Construct a SIGN_REQUEST.
4432 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4433 ssh2_pkt_addstring(username);
4434 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4435 ssh2_pkt_addstring("publickey"); /* method */
4436 ssh2_pkt_addbool(TRUE);
4437 ssh2_pkt_addstring_start();
4438 ssh2_pkt_addstring_data(alg, alglen);
4439 ssh2_pkt_addstring_start();
4440 ssh2_pkt_addstring_data(pkblob, pklen);
4442 siglen = pktout.length - 5 + 4 + 20;
4443 len = 1; /* message type */
4444 len += 4 + pklen; /* key blob */
4445 len += 4 + siglen; /* data to sign */
4446 len += 4; /* flags */
4447 agentreq = smalloc(4 + len);
4448 PUT_32BIT(agentreq, len);
4450 *q++ = SSH2_AGENTC_SIGN_REQUEST;
4451 PUT_32BIT(q, pklen);
4453 memcpy(q, pkblob, pklen);
4455 PUT_32BIT(q, siglen);
4457 /* Now the data to be signed... */
4460 memcpy(q, ssh2_session_id, 20);
4462 memcpy(q, pktout.data + 5, pktout.length - 5);
4463 q += pktout.length - 5;
4464 /* And finally the (zero) flags word. */
4466 agent_query(agentreq, len + 4, &vret, &retlen);
4470 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4471 logevent("Sending Pageant's response");
4472 ssh2_add_sigblob(pkblob, pklen,
4473 ret + 9, GET_32BIT(ret + 5));
4479 ("Pageant failed to answer challenge");
4489 if (!method && can_pubkey && publickey_blob
4490 && !tried_pubkey_config) {
4491 unsigned char *pub_blob;
4492 char *algorithm, *comment;
4495 tried_pubkey_config = TRUE;
4497 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4498 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4501 * Try the public key supplied in the configuration.
4503 * First, offer the public blob to see if the server is
4504 * willing to accept it.
4506 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4509 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4510 ssh2_pkt_addstring(username);
4511 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4512 ssh2_pkt_addstring("publickey"); /* method */
4513 ssh2_pkt_addbool(FALSE); /* no signature included */
4514 ssh2_pkt_addstring(algorithm);
4515 ssh2_pkt_addstring_start();
4516 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4518 logevent("Offered public key"); /* FIXME */
4520 crWaitUntilV(ispkt);
4521 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4523 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4524 continue; /* key refused; give up on it */
4527 logevent("Offer of public key accepted");
4529 * Actually attempt a serious authentication using
4532 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4534 "Passphrase for key \"%.100s\": ",
4540 c_write_str("Authenticating with public key \"");
4541 c_write_str(comment);
4542 c_write_str("\"\r\n");
4543 method = AUTH_PUBLICKEY_FILE;
4547 if (!method && can_keyb_inter && !tried_keyb_inter) {
4548 method = AUTH_KEYBOARD_INTERACTIVE;
4549 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4550 tried_keyb_inter = TRUE;
4552 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4553 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4555 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4556 ssh2_pkt_addstring(username);
4557 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4558 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4559 ssh2_pkt_addstring(""); /* lang */
4560 ssh2_pkt_addstring("");
4563 crWaitUntilV(ispkt);
4564 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4565 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4567 logevent("Keyboard-interactive authentication refused");
4568 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4572 kbd_inter_running = TRUE;
4576 if (kbd_inter_running) {
4577 method = AUTH_KEYBOARD_INTERACTIVE;
4578 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4579 tried_keyb_inter = TRUE;
4581 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4582 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4584 if (curr_prompt == 0) {
4586 * We've got a fresh USERAUTH_INFO_REQUEST.
4587 * Display header data, and start going through
4590 char *name, *inst, *lang;
4591 int name_len, inst_len, lang_len;
4593 ssh2_pkt_getstring(&name, &name_len);
4594 ssh2_pkt_getstring(&inst, &inst_len);
4595 ssh2_pkt_getstring(&lang, &lang_len);
4597 c_write_untrusted(name, name_len);
4598 c_write_str("\r\n");
4601 c_write_untrusted(inst, inst_len);
4602 c_write_str("\r\n");
4604 num_prompts = ssh2_pkt_getuint32();
4608 * If there are prompts remaining in the packet,
4609 * display one and get a response.
4611 if (curr_prompt < num_prompts) {
4615 ssh2_pkt_getstring(&prompt, &prompt_len);
4616 if (prompt_len > 0) {
4617 strncpy(pwprompt, prompt, sizeof(pwprompt));
4618 pwprompt[prompt_len < sizeof(pwprompt) ?
4619 prompt_len : sizeof(pwprompt)-1] = '\0';
4622 "<server failed to send prompt>: ");
4624 echo = ssh2_pkt_getbool();
4630 if (!method && can_passwd) {
4631 method = AUTH_PASSWORD;
4632 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4633 ssh_pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4634 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4641 if (!ssh_get_line(pwprompt, password,
4642 sizeof(password), TRUE)) {
4644 * get_line failed to get a password (for
4645 * example because one was supplied on the
4646 * command line which has already failed to
4649 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4650 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4652 ("No more passwords available to try");
4653 ssh2_pkt_addstring("en"); /* language tag */
4655 logevent("Unable to authenticate");
4656 connection_fatal("Unable to authenticate");
4657 ssh_state = SSH_STATE_CLOSED;
4662 c_write_untrusted(pwprompt, strlen(pwprompt));
4665 setup_userpass_input(password, sizeof(password), echo);
4667 crWaitUntilV(!ispkt);
4668 ret = process_userpass_input(in, inlen);
4672 c_write_str("\r\n");
4676 if (method == AUTH_PUBLICKEY_FILE) {
4678 * We have our passphrase. Now try the actual authentication.
4680 struct ssh2_userkey *key;
4682 key = ssh2_load_userkey(cfg.keyfile, password);
4683 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4684 if (key == SSH2_WRONG_PASSPHRASE) {
4685 c_write_str("Wrong passphrase\r\n");
4686 tried_pubkey_config = FALSE;
4688 c_write_str("Unable to load private key\r\n");
4689 tried_pubkey_config = TRUE;
4691 /* Send a spurious AUTH_NONE to return to the top. */
4692 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4693 ssh2_pkt_addstring(username);
4694 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4695 ssh2_pkt_addstring("none"); /* method */
4697 type = AUTH_TYPE_NONE;
4699 unsigned char *pkblob, *sigblob, *sigdata;
4700 int pkblob_len, sigblob_len, sigdata_len;
4703 * We have loaded the private key and the server
4704 * has announced that it's willing to accept it.
4705 * Hallelujah. Generate a signature and send it.
4707 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4708 ssh2_pkt_addstring(username);
4709 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4710 ssh2_pkt_addstring("publickey"); /* method */
4711 ssh2_pkt_addbool(TRUE);
4712 ssh2_pkt_addstring(key->alg->name);
4713 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4714 ssh2_pkt_addstring_start();
4715 ssh2_pkt_addstring_data(pkblob, pkblob_len);
4718 * The data to be signed is:
4722 * followed by everything so far placed in the
4725 sigdata_len = pktout.length - 5 + 4 + 20;
4726 sigdata = smalloc(sigdata_len);
4727 PUT_32BIT(sigdata, 20);
4728 memcpy(sigdata + 4, ssh2_session_id, 20);
4729 memcpy(sigdata + 24, pktout.data + 5,
4731 sigblob = key->alg->sign(key->data, sigdata,
4732 sigdata_len, &sigblob_len);
4733 ssh2_add_sigblob(pkblob, pkblob_len,
4734 sigblob, sigblob_len);
4740 type = AUTH_TYPE_PUBLICKEY;
4742 } else if (method == AUTH_PASSWORD) {
4744 * We send the password packet lumped tightly together with
4745 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4746 * string long enough to make the total length of the two
4747 * packets constant. This should ensure that a passive
4748 * listener doing traffic analyis can't work out the length
4751 * For this to work, we need an assumption about the
4752 * maximum length of the password packet. I think 256 is
4753 * pretty conservative. Anyone using a password longer than
4754 * that probably doesn't have much to worry about from
4755 * people who find out how long their password is!
4757 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4758 ssh2_pkt_addstring(username);
4759 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4760 ssh2_pkt_addstring("password");
4761 ssh2_pkt_addbool(FALSE);
4762 ssh2_pkt_addstring(password);
4765 * We'll include a string that's an exact multiple of the
4766 * cipher block size. If the cipher is NULL for some
4767 * reason, we don't do this trick at all because we gain
4773 stringlen = (256 - deferred_len);
4774 stringlen += cscipher->blksize - 1;
4775 stringlen -= (stringlen % cscipher->blksize);
4778 * Temporarily disable actual compression,
4779 * so we can guarantee to get this string
4780 * exactly the length we want it. The
4781 * compression-disabling routine should
4782 * return an integer indicating how many
4783 * bytes we should adjust our string length
4786 stringlen -= cscomp->disable_compression();
4788 ssh2_pkt_init(SSH2_MSG_IGNORE);
4789 ssh2_pkt_addstring_start();
4790 for (i = 0; i < stringlen; i++) {
4791 char c = (char) random_byte();
4792 ssh2_pkt_addstring_data(&c, 1);
4796 ssh_pkt_defersend();
4797 logevent("Sent password");
4798 type = AUTH_TYPE_PASSWORD;
4799 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4800 if (curr_prompt == 0) {
4801 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4802 ssh2_pkt_adduint32(num_prompts);
4804 if (need_pw) { /* only add pw if we just got one! */
4805 ssh2_pkt_addstring(password);
4806 memset(password, 0, sizeof(password));
4809 if (curr_prompt >= num_prompts) {
4813 * If there are prompts remaining, we set
4814 * `gotit' so that we won't attempt to get
4815 * another packet. Then we go back round the
4816 * loop and will end up retrieving another
4817 * prompt out of the existing packet. Funky or
4822 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4825 ("No supported authentication methods left to try!\r\n");
4827 ("No supported authentications offered. Disconnecting");
4828 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4829 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4831 ("No supported authentication methods available");
4832 ssh2_pkt_addstring("en"); /* language tag */
4834 ssh_state = SSH_STATE_CLOSED;
4838 } while (!we_are_in);
4841 * Now we're authenticated for the connection protocol. The
4842 * connection protocol will automatically have started at this
4843 * point; there's no need to send SERVICE_REQUEST.
4847 * So now create a channel with a session in it.
4849 ssh_channels = newtree234(ssh_channelcmp);
4850 mainchan = smalloc(sizeof(struct ssh_channel));
4851 mainchan->localid = alloc_channel_id();
4852 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4853 ssh2_pkt_addstring("session");
4854 ssh2_pkt_adduint32(mainchan->localid);
4855 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4856 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4857 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4859 crWaitUntilV(ispkt);
4860 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4861 bombout(("Server refused to open a session"));
4863 /* FIXME: error data comes back in FAILURE packet */
4865 if (ssh2_pkt_getuint32() != mainchan->localid) {
4866 bombout(("Server's channel confirmation cited wrong channel"));
4869 mainchan->remoteid = ssh2_pkt_getuint32();
4870 mainchan->type = CHAN_MAINSESSION;
4871 mainchan->closes = 0;
4872 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4873 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4874 bufchain_init(&mainchan->v.v2.outbuffer);
4875 add234(ssh_channels, mainchan);
4876 logevent("Opened channel for session");
4879 * Potentially enable X11 forwarding.
4881 if (cfg.x11_forward) {
4882 char proto[20], data[64];
4883 logevent("Requesting X11 forwarding");
4884 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4885 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4886 ssh2_pkt_adduint32(mainchan->remoteid);
4887 ssh2_pkt_addstring("x11-req");
4888 ssh2_pkt_addbool(1); /* want reply */
4889 ssh2_pkt_addbool(0); /* many connections */
4890 ssh2_pkt_addstring(proto);
4891 ssh2_pkt_addstring(data);
4892 ssh2_pkt_adduint32(0); /* screen number */
4896 crWaitUntilV(ispkt);
4897 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4898 unsigned i = ssh2_pkt_getuint32();
4899 struct ssh_channel *c;
4900 c = find234(ssh_channels, &i, ssh_channelfind);
4902 continue; /* nonexistent channel */
4903 c->v.v2.remwindow += ssh2_pkt_getuint32();
4905 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4907 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4908 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4909 bombout(("Unexpected response to X11 forwarding request:"
4910 " packet type %d", pktin.type));
4913 logevent("X11 forwarding refused");
4915 logevent("X11 forwarding enabled");
4916 ssh_X11_fwd_enabled = TRUE;
4921 * Enable port forwardings.
4924 static char *e; /* preserve across crReturn */
4927 int sport,dport,sserv,dserv;
4928 char sports[256], dports[256], host[256];
4932 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4933 /* Add port forwardings. */
4938 while (*e && *e != '\t')
4944 while (*e && *e != ':')
4954 dport = atoi(dports);
4958 se = getservbyname(dports, NULL);
4960 dport = ntohs(se->s_port);
4963 "Service lookup failed for destination port \"%s\"",
4968 sport = atoi(sports);
4972 se = getservbyname(sports, NULL);
4974 sport = ntohs(se->s_port);
4977 "Service lookup failed for source port \"%s\"",
4982 if (sport && dport) {
4984 pfd_addforward(host, dport, sport);
4985 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
4986 " %s:%.*s%.*s%d%.*s",
4987 sserv ? strlen(sports) : 0, sports,
4988 sserv, "(", sport, sserv, ")",
4990 dserv ? strlen(dports) : 0, dports,
4991 dserv, "(", dport, dserv, ")");
4994 struct ssh_rportfwd *pf;
4995 pf = smalloc(sizeof(*pf));
4996 strcpy(pf->dhost, host);
4999 if (add234(ssh_rportfwds, pf) != pf) {
5001 "Duplicate remote port forwarding to %s:%d",
5006 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5007 " forward to %s:%.*s%.*s%d%.*s",
5008 sserv ? strlen(sports) : 0, sports,
5009 sserv, "(", sport, sserv, ")",
5011 dserv ? strlen(dports) : 0, dports,
5012 dserv, "(", dport, dserv, ")");
5014 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5015 ssh2_pkt_addstring("tcpip-forward");
5016 ssh2_pkt_addbool(1);/* want reply */
5017 if (cfg.rport_acceptall)
5018 ssh2_pkt_addstring("0.0.0.0");
5020 ssh2_pkt_addstring("127.0.0.1");
5021 ssh2_pkt_adduint32(sport);
5025 crWaitUntilV(ispkt);
5026 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5027 unsigned i = ssh2_pkt_getuint32();
5028 struct ssh_channel *c;
5029 c = find234(ssh_channels, &i, ssh_channelfind);
5031 continue;/* nonexistent channel */
5032 c->v.v2.remwindow += ssh2_pkt_getuint32();
5034 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5036 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5037 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5038 bombout(("Unexpected response to port "
5039 "forwarding request: packet type %d",
5043 logevent("Server refused this port forwarding");
5045 logevent("Remote port forwarding enabled");
5054 * Potentially enable agent forwarding.
5056 if (cfg.agentfwd && agent_exists()) {
5057 logevent("Requesting OpenSSH-style agent forwarding");
5058 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5059 ssh2_pkt_adduint32(mainchan->remoteid);
5060 ssh2_pkt_addstring("auth-agent-req@openssh.com");
5061 ssh2_pkt_addbool(1); /* want reply */
5065 crWaitUntilV(ispkt);
5066 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5067 unsigned i = ssh2_pkt_getuint32();
5068 struct ssh_channel *c;
5069 c = find234(ssh_channels, &i, ssh_channelfind);
5071 continue; /* nonexistent channel */
5072 c->v.v2.remwindow += ssh2_pkt_getuint32();
5074 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5076 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5077 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5078 bombout(("Unexpected response to agent forwarding request:"
5079 " packet type %d", pktin.type));
5082 logevent("Agent forwarding refused");
5084 logevent("Agent forwarding enabled");
5085 ssh_agentfwd_enabled = TRUE;
5090 * Now allocate a pty for the session.
5093 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5094 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5095 ssh2_pkt_addstring("pty-req");
5096 ssh2_pkt_addbool(1); /* want reply */
5097 ssh2_pkt_addstring(cfg.termtype);
5098 ssh2_pkt_adduint32(cols);
5099 ssh2_pkt_adduint32(rows);
5100 ssh2_pkt_adduint32(0); /* pixel width */
5101 ssh2_pkt_adduint32(0); /* pixel height */
5102 ssh2_pkt_addstring_start();
5103 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
5105 ssh_state = SSH_STATE_INTERMED;
5108 crWaitUntilV(ispkt);
5109 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5110 unsigned i = ssh2_pkt_getuint32();
5111 struct ssh_channel *c;
5112 c = find234(ssh_channels, &i, ssh_channelfind);
5114 continue; /* nonexistent channel */
5115 c->v.v2.remwindow += ssh2_pkt_getuint32();
5117 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5119 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5120 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5121 bombout(("Unexpected response to pty request:"
5122 " packet type %d", pktin.type));
5125 c_write_str("Server refused to allocate pty\r\n");
5126 ssh_editing = ssh_echoing = 1;
5128 logevent("Allocated pty");
5131 ssh_editing = ssh_echoing = 1;
5135 * Start a shell or a remote command. We may have to attempt
5136 * this twice if the config data has provided a second choice
5143 if (ssh_fallback_cmd) {
5144 subsys = cfg.ssh_subsys2;
5145 cmd = cfg.remote_cmd_ptr2;
5147 subsys = cfg.ssh_subsys;
5148 cmd = cfg.remote_cmd_ptr;
5151 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5152 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5154 ssh2_pkt_addstring("subsystem");
5155 ssh2_pkt_addbool(1); /* want reply */
5156 ssh2_pkt_addstring(cmd);
5158 ssh2_pkt_addstring("exec");
5159 ssh2_pkt_addbool(1); /* want reply */
5160 ssh2_pkt_addstring(cmd);
5162 ssh2_pkt_addstring("shell");
5163 ssh2_pkt_addbool(1); /* want reply */
5167 crWaitUntilV(ispkt);
5168 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5169 unsigned i = ssh2_pkt_getuint32();
5170 struct ssh_channel *c;
5171 c = find234(ssh_channels, &i, ssh_channelfind);
5173 continue; /* nonexistent channel */
5174 c->v.v2.remwindow += ssh2_pkt_getuint32();
5176 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5177 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5178 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5179 bombout(("Unexpected response to shell/command request:"
5180 " packet type %d", pktin.type));
5184 * We failed to start the command. If this is the
5185 * fallback command, we really are finished; if it's
5186 * not, and if the fallback command exists, try falling
5187 * back to it before complaining.
5189 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5190 logevent("Primary command failed; attempting fallback");
5191 ssh_fallback_cmd = TRUE;
5194 bombout(("Server refused to start a shell/command"));
5197 logevent("Started a shell/command");
5202 ssh_state = SSH_STATE_SESSION;
5206 ssh_special(TS_EOF);
5211 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
5214 static int try_send;
5218 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
5219 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5222 unsigned i = ssh2_pkt_getuint32();
5223 struct ssh_channel *c;
5224 c = find234(ssh_channels, &i, ssh_channelfind);
5226 continue; /* nonexistent channel */
5227 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5228 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
5229 continue; /* extended but not stderr */
5230 ssh2_pkt_getstring(&data, &length);
5233 c->v.v2.locwindow -= length;
5235 case CHAN_MAINSESSION:
5237 from_backend(pktin.type ==
5238 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5242 bufsize = x11_send(c->u.x11.s, data, length);
5245 bufsize = pfd_send(c->u.pfd.s, data, length);
5248 while (length > 0) {
5249 if (c->u.a.lensofar < 4) {
5250 int l = min(4 - c->u.a.lensofar, length);
5251 memcpy(c->u.a.msglen + c->u.a.lensofar,
5255 c->u.a.lensofar += l;
5257 if (c->u.a.lensofar == 4) {
5259 4 + GET_32BIT(c->u.a.msglen);
5260 c->u.a.message = smalloc(c->u.a.totallen);
5261 memcpy(c->u.a.message, c->u.a.msglen, 4);
5263 if (c->u.a.lensofar >= 4 && length > 0) {
5265 min(c->u.a.totallen - c->u.a.lensofar,
5267 memcpy(c->u.a.message + c->u.a.lensofar,
5271 c->u.a.lensofar += l;
5273 if (c->u.a.lensofar == c->u.a.totallen) {
5274 void *reply, *sentreply;
5276 agent_query(c->u.a.message,
5277 c->u.a.totallen, &reply,
5282 /* Fake SSH_AGENT_FAILURE. */
5283 sentreply = "\0\0\0\1\5";
5286 ssh2_add_channel_data(c, sentreply,
5291 sfree(c->u.a.message);
5292 c->u.a.lensofar = 0;
5299 * If we are not buffering too much data,
5300 * enlarge the window again at the remote side.
5302 if (bufsize < OUR_V2_WINSIZE)
5303 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5305 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
5306 ssh_state = SSH_STATE_CLOSED;
5307 logevent("Received disconnect message");
5309 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
5310 unsigned i = ssh2_pkt_getuint32();
5311 struct ssh_channel *c;
5313 c = find234(ssh_channels, &i, ssh_channelfind);
5315 continue; /* nonexistent channel */
5317 if (c->type == CHAN_X11) {
5319 * Remote EOF on an X11 channel means we should
5320 * wrap up and close the channel ourselves.
5322 x11_close(c->u.x11.s);
5324 } else if (c->type == CHAN_AGENT) {
5326 } else if (c->type == CHAN_SOCKDATA) {
5327 pfd_close(c->u.pfd.s);
5330 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5331 unsigned i = ssh2_pkt_getuint32();
5332 struct ssh_channel *c;
5334 c = find234(ssh_channels, &i, ssh_channelfind);
5336 continue; /* nonexistent channel */
5337 /* Do pre-close processing on the channel. */
5339 case CHAN_MAINSESSION:
5340 break; /* nothing to see here, move along */
5342 if (c->u.x11.s != NULL)
5343 x11_close(c->u.x11.s);
5350 if (c->u.pfd.s != NULL)
5351 pfd_close(c->u.pfd.s);
5355 if (c->closes == 0) {
5356 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5357 ssh2_pkt_adduint32(c->remoteid);
5360 del234(ssh_channels, c);
5361 bufchain_clear(&c->v.v2.outbuffer);
5365 * See if that was the last channel left open.
5367 if (count234(ssh_channels) == 0) {
5370 * We used to send SSH_MSG_DISCONNECT here,
5371 * because I'd believed that _every_ conforming
5372 * SSH2 connection had to end with a disconnect
5373 * being sent by at least one side; apparently
5374 * I was wrong and it's perfectly OK to
5375 * unceremoniously slam the connection shut
5376 * when you're done, and indeed OpenSSH feels
5377 * this is more polite than sending a
5378 * DISCONNECT. So now we don't.
5380 logevent("All channels closed. Disconnecting");
5381 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5382 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5383 ssh2_pkt_addstring("All open channels closed");
5384 ssh2_pkt_addstring("en"); /* language tag */
5387 ssh_state = SSH_STATE_CLOSED;
5390 continue; /* remote sends close; ignore (FIXME) */
5391 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5392 unsigned i = ssh2_pkt_getuint32();
5393 struct ssh_channel *c;
5394 c = find234(ssh_channels, &i, ssh_channelfind);
5396 continue; /* nonexistent channel */
5397 c->v.v2.remwindow += ssh2_pkt_getuint32();
5399 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5400 unsigned i = ssh2_pkt_getuint32();
5401 struct ssh_channel *c;
5402 c = find234(ssh_channels, &i, ssh_channelfind);
5404 continue; /* nonexistent channel */
5405 if (c->type != CHAN_SOCKDATA_DORMANT)
5406 continue; /* dunno why they're confirming this */
5407 c->remoteid = ssh2_pkt_getuint32();
5408 c->type = CHAN_SOCKDATA;
5409 c->v.v2.remwindow = ssh2_pkt_getuint32();
5410 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
5412 pfd_confirm(c->u.pfd.s);
5415 * We have a pending close on this channel,
5416 * which we decided on before the server acked
5417 * the channel open. So now we know the
5418 * remoteid, we can close it again.
5420 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5421 ssh2_pkt_adduint32(c->remoteid);
5424 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5425 unsigned i = ssh2_pkt_getuint32();
5426 struct ssh_channel *c;
5427 c = find234(ssh_channels, &i, ssh_channelfind);
5429 continue; /* nonexistent channel */
5430 if (c->type != CHAN_SOCKDATA_DORMANT)
5431 continue; /* dunno why they're failing this */
5433 logevent("Forwarded connection refused by server");
5435 pfd_close(c->u.pfd.s);
5437 del234(ssh_channels, c);
5439 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5442 int typelen, want_reply;
5443 struct ssh_channel *c;
5445 localid = ssh2_pkt_getuint32();
5446 ssh2_pkt_getstring(&type, &typelen);
5447 want_reply = ssh2_pkt_getbool();
5450 * First, check that the channel exists. Otherwise,
5451 * we can instantly disconnect with a rude message.
5453 c = find234(ssh_channels, &localid, ssh_channelfind);
5456 sprintf(buf, "Received channel request for nonexistent"
5457 " channel %d", localid);
5459 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5460 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5461 ssh2_pkt_addstring(buf);
5462 ssh2_pkt_addstring("en"); /* language tag */
5464 connection_fatal("%s", buf);
5465 ssh_state = SSH_STATE_CLOSED;
5470 * Having got the channel number, we now look at
5471 * the request type string to see if it's something
5474 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5476 /* We recognise "exit-status" on the primary channel. */
5478 ssh_exitcode = ssh2_pkt_getuint32();
5479 sprintf(buf, "Server sent command exit status %d",
5483 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS);
5484 ssh2_pkt_adduint32(c->remoteid);
5489 * This is a channel request we don't know
5490 * about, so we now either ignore the request
5491 * or respond with CHANNEL_FAILURE, depending
5495 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
5496 ssh2_pkt_adduint32(c->remoteid);
5500 } else if (pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5502 int typelen, want_reply;
5504 ssh2_pkt_getstring(&type, &typelen);
5505 want_reply = ssh2_pkt_getbool();
5508 * We currently don't support any global requests
5509 * at all, so we either ignore the request or
5510 * respond with REQUEST_FAILURE, depending on
5514 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5517 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5521 struct ssh_channel *c;
5522 unsigned remid, winsize, pktsize;
5523 ssh2_pkt_getstring(&type, &typelen);
5524 c = smalloc(sizeof(struct ssh_channel));
5526 remid = ssh2_pkt_getuint32();
5527 winsize = ssh2_pkt_getuint32();
5528 pktsize = ssh2_pkt_getuint32();
5530 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5531 if (!ssh_X11_fwd_enabled)
5532 error = "X11 forwarding is not enabled";
5533 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5535 error = "Unable to open an X11 connection";
5539 } else if (typelen == 15 &&
5540 !memcmp(type, "forwarded-tcpip", 15)) {
5541 struct ssh_rportfwd pf, *realpf;
5544 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
5545 pf.sport = ssh2_pkt_getuint32();
5546 realpf = find234(ssh_rportfwds, &pf, NULL);
5547 if (realpf == NULL) {
5548 error = "Remote port is not recognised";
5550 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5553 sprintf(buf, "Received remote port open request for %s:%d",
5554 realpf->dhost, realpf->dport);
5557 sprintf(buf, "Port open failed: %s", e);
5559 error = "Port open failed";
5561 logevent("Forwarded port opened successfully");
5562 c->type = CHAN_SOCKDATA;
5565 } else if (typelen == 22 &&
5566 !memcmp(type, "auth-agent@openssh.com", 3)) {
5567 if (!ssh_agentfwd_enabled)
5568 error = "Agent forwarding is not enabled";
5570 c->type = CHAN_AGENT; /* identify channel type */
5571 c->u.a.lensofar = 0;
5574 error = "Unsupported channel type requested";
5577 c->remoteid = remid;
5579 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5580 ssh2_pkt_adduint32(c->remoteid);
5581 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5582 ssh2_pkt_addstring(error);
5583 ssh2_pkt_addstring("en"); /* language tag */
5587 c->localid = alloc_channel_id();
5589 c->v.v2.locwindow = OUR_V2_WINSIZE;
5590 c->v.v2.remwindow = winsize;
5591 c->v.v2.remmaxpkt = pktsize;
5592 bufchain_init(&c->v.v2.outbuffer);
5593 add234(ssh_channels, c);
5594 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5595 ssh2_pkt_adduint32(c->remoteid);
5596 ssh2_pkt_adduint32(c->localid);
5597 ssh2_pkt_adduint32(c->v.v2.locwindow);
5598 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5602 bombout(("Strange packet received: type %d", pktin.type));
5607 * We have spare data. Add it to the channel buffer.
5609 ssh2_add_channel_data(mainchan, in, inlen);
5614 struct ssh_channel *c;
5616 * Try to send data on all channels if we can.
5618 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5619 int bufsize = ssh2_try_send(c);
5622 case CHAN_MAINSESSION:
5623 /* stdin need not receive an unthrottle
5624 * notification since it will be polled */
5627 x11_unthrottle(c->u.x11.s);
5630 /* agent sockets are request/response and need no
5631 * buffer management */
5634 pfd_unthrottle(c->u.pfd.s);
5646 * Handle the top-level SSH2 protocol.
5648 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5650 if (do_ssh2_transport(in, inlen, ispkt) == 0)
5652 do_ssh2_authconn(in, inlen, ispkt);
5656 * Called to set up the connection.
5658 * Returns an error message, or NULL on success.
5660 static char *ssh_init(char *host, int port, char **realhost, int nodelay)
5665 if (crypto_startup() == 0)
5666 return "Microsoft high encryption pack not installed!";
5672 ssh1_throttle_count = 0;
5673 ssh_overall_bufsize = 0;
5674 ssh_fallback_cmd = 0;
5676 p = connect_to_host(host, port, realhost, nodelay);
5684 * Called to send data down the Telnet connection.
5686 static int ssh_send(char *buf, int len)
5688 if (s == NULL || ssh_protocol == NULL)
5691 ssh_protocol(buf, len, 0);
5693 return ssh_sendbuffer();
5697 * Called to query the current amount of buffered stdin data.
5699 static int ssh_sendbuffer(void)
5703 if (s == NULL || ssh_protocol == NULL)
5707 * If the SSH socket itself has backed up, add the total backup
5708 * size on that to any individual buffer on the stdin channel.
5711 if (ssh_throttled_all)
5712 override_value = ssh_overall_bufsize;
5714 if (ssh_version == 1) {
5715 return override_value;
5716 } else if (ssh_version == 2) {
5717 if (!mainchan || mainchan->closes > 0)
5718 return override_value;
5720 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5727 * Called to set the size of the window from SSH's POV.
5729 static void ssh_size(void)
5731 switch (ssh_state) {
5732 case SSH_STATE_BEFORE_SIZE:
5733 case SSH_STATE_PREPACKET:
5734 case SSH_STATE_CLOSED:
5735 break; /* do nothing */
5736 case SSH_STATE_INTERMED:
5737 size_needed = TRUE; /* buffer for later */
5739 case SSH_STATE_SESSION:
5741 if (ssh_version == 1) {
5742 send_packet(SSH1_CMSG_WINDOW_SIZE,
5743 PKT_INT, rows, PKT_INT, cols,
5744 PKT_INT, 0, PKT_INT, 0, PKT_END);
5746 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5747 ssh2_pkt_adduint32(mainchan->remoteid);
5748 ssh2_pkt_addstring("window-change");
5749 ssh2_pkt_addbool(0);
5750 ssh2_pkt_adduint32(cols);
5751 ssh2_pkt_adduint32(rows);
5752 ssh2_pkt_adduint32(0);
5753 ssh2_pkt_adduint32(0);
5762 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5763 * can send an EOF and collect resulting output (e.g. `plink
5766 static void ssh_special(Telnet_Special code)
5768 if (code == TS_EOF) {
5769 if (ssh_state != SSH_STATE_SESSION) {
5771 * Buffer the EOF in case we are pre-SESSION, so we can
5772 * send it as soon as we reach SESSION.
5778 if (ssh_version == 1) {
5779 send_packet(SSH1_CMSG_EOF, PKT_END);
5781 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5782 ssh2_pkt_adduint32(mainchan->remoteid);
5785 logevent("Sent EOF message");
5786 } else if (code == TS_PING) {
5787 if (ssh_state == SSH_STATE_CLOSED
5788 || ssh_state == SSH_STATE_PREPACKET) return;
5789 if (ssh_version == 1) {
5790 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5792 ssh2_pkt_init(SSH2_MSG_IGNORE);
5793 ssh2_pkt_addstring_start();
5801 void *new_sock_channel(Socket s)
5803 struct ssh_channel *c;
5804 c = smalloc(sizeof(struct ssh_channel));
5807 c->remoteid = -1; /* to be set when open confirmed */
5808 c->localid = alloc_channel_id();
5810 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5812 bufchain_init(&c->v.v2.outbuffer);
5813 add234(ssh_channels, c);
5819 * This is called when stdout/stderr (the entity to which
5820 * from_backend sends data) manages to clear some backlog.
5822 void ssh_unthrottle(int bufsize)
5824 if (ssh_version == 1) {
5825 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5826 ssh1_stdout_throttling = 0;
5830 if (mainchan && mainchan->closes == 0)
5831 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5835 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5837 struct ssh_channel *c = (struct ssh_channel *)channel;
5840 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5843 if (ssh_version == 1) {
5844 send_packet(SSH1_MSG_PORT_OPEN,
5845 PKT_INT, c->localid,
5848 //PKT_STR, <org:orgport>,
5851 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5852 ssh2_pkt_addstring("direct-tcpip");
5853 ssh2_pkt_adduint32(c->localid);
5854 c->v.v2.locwindow = OUR_V2_WINSIZE;
5855 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5856 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5857 ssh2_pkt_addstring(hostname);
5858 ssh2_pkt_adduint32(port);
5860 * We make up values for the originator data; partly it's
5861 * too much hassle to keep track, and partly I'm not
5862 * convinced the server should be told details like that
5863 * about my local network configuration.
5865 ssh2_pkt_addstring("client-side-connection");
5866 ssh2_pkt_adduint32(0);
5872 static Socket ssh_socket(void)
5877 static int ssh_sendok(void)
5882 static int ssh_ldisc(int option)
5884 if (option == LD_ECHO)
5886 if (option == LD_EDIT)
5891 static int ssh_return_exitcode(void)
5893 return ssh_exitcode;
5896 Backend ssh_backend = {
5903 ssh_return_exitcode,