23 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
24 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
25 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
26 #define SSH1_CMSG_USER 4 /* 0x4 */
27 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
28 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
29 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
30 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
31 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
32 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
33 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
34 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
35 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
36 #define SSH1_SMSG_FAILURE 15 /* 0xf */
37 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
38 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
39 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
40 #define SSH1_CMSG_EOF 19 /* 0x13 */
41 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
42 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
43 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
44 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
45 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
46 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
47 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
48 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
49 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
50 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
51 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
52 #define SSH1_MSG_IGNORE 32 /* 0x20 */
53 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
54 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
55 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
56 #define SSH1_MSG_DEBUG 36 /* 0x24 */
57 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
58 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
59 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
60 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
61 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
62 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
63 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
65 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
66 #define SSH1_AUTH_RSA 2 /* 0x2 */
67 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
68 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
69 #define SSH1_AUTH_TIS 5 /* 0x5 */
70 #define SSH1_AUTH_CCARD 16 /* 0x10 */
72 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
73 /* Mask for protoflags we will echo back to server if seen */
74 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
76 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
77 #define SSH2_MSG_IGNORE 2 /* 0x2 */
78 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
79 #define SSH2_MSG_DEBUG 4 /* 0x4 */
80 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
81 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
82 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
83 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
84 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
85 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
86 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
87 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
88 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
89 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
90 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
91 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
92 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
93 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
94 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
95 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
96 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
97 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
98 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
100 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
101 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
102 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
103 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
104 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
105 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
106 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
107 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
108 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
109 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
110 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
111 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
112 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
113 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
114 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
117 * Packet type contexts, so that ssh2_pkt_type can correctly decode
118 * the ambiguous type numbers back into the correct type strings.
128 SSH2_PKTCTX_PUBLICKEY,
129 SSH2_PKTCTX_PASSWORD,
133 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
134 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
135 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
136 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
137 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
138 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
139 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
140 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
141 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
142 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
143 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
144 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
145 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
146 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
147 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
149 static const char *const ssh2_disconnect_reasons[] = {
151 "host not allowed to connect",
153 "key exchange failed",
154 "host authentication failed",
157 "service not available",
158 "protocol version not supported",
159 "host key not verifiable",
162 "too many connections",
163 "auth cancelled by user",
164 "no more auth methods available",
168 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
169 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
170 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
171 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
173 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
176 * Various remote-bug flags.
178 #define BUG_CHOKES_ON_SSH1_IGNORE 1
179 #define BUG_SSH2_HMAC 2
180 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
181 #define BUG_CHOKES_ON_RSA 8
182 #define BUG_SSH2_RSA_PADDING 16
183 #define BUG_SSH2_DERIVEKEY 32
184 #define BUG_SSH2_REKEY 64
185 #define BUG_SSH2_PK_SESSIONID 128
188 * Codes for terminal modes.
189 * Most of these are the same in SSH-1 and SSH-2.
190 * This list is derived from RFC 4254 and
193 static const struct {
194 const char* const mode;
196 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
198 /* "V" prefix discarded for special characters relative to SSH specs */
199 { "INTR", 1, TTY_OP_CHAR },
200 { "QUIT", 2, TTY_OP_CHAR },
201 { "ERASE", 3, TTY_OP_CHAR },
202 { "KILL", 4, TTY_OP_CHAR },
203 { "EOF", 5, TTY_OP_CHAR },
204 { "EOL", 6, TTY_OP_CHAR },
205 { "EOL2", 7, TTY_OP_CHAR },
206 { "START", 8, TTY_OP_CHAR },
207 { "STOP", 9, TTY_OP_CHAR },
208 { "SUSP", 10, TTY_OP_CHAR },
209 { "DSUSP", 11, TTY_OP_CHAR },
210 { "REPRINT", 12, TTY_OP_CHAR },
211 { "WERASE", 13, TTY_OP_CHAR },
212 { "LNEXT", 14, TTY_OP_CHAR },
213 { "FLUSH", 15, TTY_OP_CHAR },
214 { "SWTCH", 16, TTY_OP_CHAR },
215 { "STATUS", 17, TTY_OP_CHAR },
216 { "DISCARD", 18, TTY_OP_CHAR },
217 { "IGNPAR", 30, TTY_OP_BOOL },
218 { "PARMRK", 31, TTY_OP_BOOL },
219 { "INPCK", 32, TTY_OP_BOOL },
220 { "ISTRIP", 33, TTY_OP_BOOL },
221 { "INLCR", 34, TTY_OP_BOOL },
222 { "IGNCR", 35, TTY_OP_BOOL },
223 { "ICRNL", 36, TTY_OP_BOOL },
224 { "IUCLC", 37, TTY_OP_BOOL },
225 { "IXON", 38, TTY_OP_BOOL },
226 { "IXANY", 39, TTY_OP_BOOL },
227 { "IXOFF", 40, TTY_OP_BOOL },
228 { "IMAXBEL", 41, TTY_OP_BOOL },
229 { "ISIG", 50, TTY_OP_BOOL },
230 { "ICANON", 51, TTY_OP_BOOL },
231 { "XCASE", 52, TTY_OP_BOOL },
232 { "ECHO", 53, TTY_OP_BOOL },
233 { "ECHOE", 54, TTY_OP_BOOL },
234 { "ECHOK", 55, TTY_OP_BOOL },
235 { "ECHONL", 56, TTY_OP_BOOL },
236 { "NOFLSH", 57, TTY_OP_BOOL },
237 { "TOSTOP", 58, TTY_OP_BOOL },
238 { "IEXTEN", 59, TTY_OP_BOOL },
239 { "ECHOCTL", 60, TTY_OP_BOOL },
240 { "ECHOKE", 61, TTY_OP_BOOL },
241 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
242 { "OPOST", 70, TTY_OP_BOOL },
243 { "OLCUC", 71, TTY_OP_BOOL },
244 { "ONLCR", 72, TTY_OP_BOOL },
245 { "OCRNL", 73, TTY_OP_BOOL },
246 { "ONOCR", 74, TTY_OP_BOOL },
247 { "ONLRET", 75, TTY_OP_BOOL },
248 { "CS7", 90, TTY_OP_BOOL },
249 { "CS8", 91, TTY_OP_BOOL },
250 { "PARENB", 92, TTY_OP_BOOL },
251 { "PARODD", 93, TTY_OP_BOOL }
254 /* Miscellaneous other tty-related constants. */
255 #define SSH_TTY_OP_END 0
256 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
257 #define SSH1_TTY_OP_ISPEED 192
258 #define SSH1_TTY_OP_OSPEED 193
259 #define SSH2_TTY_OP_ISPEED 128
260 #define SSH2_TTY_OP_OSPEED 129
262 /* Helper functions for parsing tty-related config. */
263 static unsigned int ssh_tty_parse_specchar(char *s)
268 ret = ctrlparse(s, &next);
269 if (!next) ret = s[0];
271 ret = 255; /* special value meaning "don't set" */
275 static unsigned int ssh_tty_parse_boolean(char *s)
277 if (stricmp(s, "yes") == 0 ||
278 stricmp(s, "on") == 0 ||
279 stricmp(s, "true") == 0 ||
280 stricmp(s, "+") == 0)
282 else if (stricmp(s, "no") == 0 ||
283 stricmp(s, "off") == 0 ||
284 stricmp(s, "false") == 0 ||
285 stricmp(s, "-") == 0)
286 return 0; /* false */
288 return (atoi(s) != 0);
291 #define translate(x) if (type == x) return #x
292 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
293 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
294 static char *ssh1_pkt_type(int type)
296 translate(SSH1_MSG_DISCONNECT);
297 translate(SSH1_SMSG_PUBLIC_KEY);
298 translate(SSH1_CMSG_SESSION_KEY);
299 translate(SSH1_CMSG_USER);
300 translate(SSH1_CMSG_AUTH_RSA);
301 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
302 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
303 translate(SSH1_CMSG_AUTH_PASSWORD);
304 translate(SSH1_CMSG_REQUEST_PTY);
305 translate(SSH1_CMSG_WINDOW_SIZE);
306 translate(SSH1_CMSG_EXEC_SHELL);
307 translate(SSH1_CMSG_EXEC_CMD);
308 translate(SSH1_SMSG_SUCCESS);
309 translate(SSH1_SMSG_FAILURE);
310 translate(SSH1_CMSG_STDIN_DATA);
311 translate(SSH1_SMSG_STDOUT_DATA);
312 translate(SSH1_SMSG_STDERR_DATA);
313 translate(SSH1_CMSG_EOF);
314 translate(SSH1_SMSG_EXIT_STATUS);
315 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
316 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
317 translate(SSH1_MSG_CHANNEL_DATA);
318 translate(SSH1_MSG_CHANNEL_CLOSE);
319 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
320 translate(SSH1_SMSG_X11_OPEN);
321 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
322 translate(SSH1_MSG_PORT_OPEN);
323 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
324 translate(SSH1_SMSG_AGENT_OPEN);
325 translate(SSH1_MSG_IGNORE);
326 translate(SSH1_CMSG_EXIT_CONFIRMATION);
327 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
328 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
329 translate(SSH1_MSG_DEBUG);
330 translate(SSH1_CMSG_REQUEST_COMPRESSION);
331 translate(SSH1_CMSG_AUTH_TIS);
332 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
333 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
334 translate(SSH1_CMSG_AUTH_CCARD);
335 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
336 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
339 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
341 translate(SSH2_MSG_DISCONNECT);
342 translate(SSH2_MSG_IGNORE);
343 translate(SSH2_MSG_UNIMPLEMENTED);
344 translate(SSH2_MSG_DEBUG);
345 translate(SSH2_MSG_SERVICE_REQUEST);
346 translate(SSH2_MSG_SERVICE_ACCEPT);
347 translate(SSH2_MSG_KEXINIT);
348 translate(SSH2_MSG_NEWKEYS);
349 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
350 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
351 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
352 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
353 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
354 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
355 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
356 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
357 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
358 translate(SSH2_MSG_USERAUTH_REQUEST);
359 translate(SSH2_MSG_USERAUTH_FAILURE);
360 translate(SSH2_MSG_USERAUTH_SUCCESS);
361 translate(SSH2_MSG_USERAUTH_BANNER);
362 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
363 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
364 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
365 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
366 translate(SSH2_MSG_GLOBAL_REQUEST);
367 translate(SSH2_MSG_REQUEST_SUCCESS);
368 translate(SSH2_MSG_REQUEST_FAILURE);
369 translate(SSH2_MSG_CHANNEL_OPEN);
370 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
371 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
372 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
373 translate(SSH2_MSG_CHANNEL_DATA);
374 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
375 translate(SSH2_MSG_CHANNEL_EOF);
376 translate(SSH2_MSG_CHANNEL_CLOSE);
377 translate(SSH2_MSG_CHANNEL_REQUEST);
378 translate(SSH2_MSG_CHANNEL_SUCCESS);
379 translate(SSH2_MSG_CHANNEL_FAILURE);
385 /* Enumeration values for fields in SSH-1 packets */
387 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
388 /* These values are for communicating relevant semantics of
389 * fields to the packet logging code. */
390 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
394 * Coroutine mechanics for the sillier bits of the code. If these
395 * macros look impenetrable to you, you might find it helpful to
398 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
400 * which explains the theory behind these macros.
402 * In particular, if you are getting `case expression not constant'
403 * errors when building with MS Visual Studio, this is because MS's
404 * Edit and Continue debugging feature causes their compiler to
405 * violate ANSI C. To disable Edit and Continue debugging:
407 * - right-click ssh.c in the FileView
409 * - select the C/C++ tab and the General category
410 * - under `Debug info:', select anything _other_ than `Program
411 * Database for Edit and Continue'.
413 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
416 if (!ssh->t) ssh->t = snew(struct t); \
418 #define crFinish(z) } *crLine = 0; return (z); }
419 #define crFinishV } *crLine = 0; return; }
420 #define crReturn(z) \
422 *crLine =__LINE__; return (z); case __LINE__:;\
426 *crLine=__LINE__; return; case __LINE__:;\
428 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
429 #define crStopV do{ *crLine = 0; return; }while(0)
430 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
431 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
433 typedef struct ssh_tag *Ssh;
436 static struct Packet *ssh1_pkt_init(int pkt_type);
437 static struct Packet *ssh2_pkt_init(int pkt_type);
438 static void ssh_pkt_ensure(struct Packet *, int length);
439 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
440 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
441 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
442 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
443 static void ssh_pkt_addstring_start(struct Packet *);
444 static void ssh_pkt_addstring_str(struct Packet *, char *data);
445 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
446 static void ssh_pkt_addstring(struct Packet *, char *data);
447 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
448 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
449 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
450 static int ssh2_pkt_construct(Ssh, struct Packet *);
451 static void ssh2_pkt_send(Ssh, struct Packet *);
452 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
453 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
454 struct Packet *pktin);
455 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
456 struct Packet *pktin);
459 * Buffer management constants. There are several of these for
460 * various different purposes:
462 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
463 * on a local data stream before we throttle the whole SSH
464 * connection (in SSH-1 only). Throttling the whole connection is
465 * pretty drastic so we set this high in the hope it won't
468 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
469 * on the SSH connection itself before we defensively throttle
470 * _all_ local data streams. This is pretty drastic too (though
471 * thankfully unlikely in SSH-2 since the window mechanism should
472 * ensure that the server never has any need to throttle its end
473 * of the connection), so we set this high as well.
475 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
478 * - OUR_V2_BIGWIN is the window size we advertise for the only
479 * channel in a simple connection. It must be <= INT_MAX.
482 #define SSH1_BUFFER_LIMIT 32768
483 #define SSH_MAX_BACKLOG 32768
484 #define OUR_V2_WINSIZE 16384
485 #define OUR_V2_BIGWIN 0x7fffffff
486 #define OUR_V2_MAXPKT 0x4000UL
488 /* Maximum length of passwords/passphrases (arbitrary) */
489 #define SSH_MAX_PASSWORD_LEN 100
491 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
493 const static struct ssh_mac *macs[] = {
494 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
496 const static struct ssh_mac *buggymacs[] = {
497 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
500 static void *ssh_comp_none_init(void)
504 static void ssh_comp_none_cleanup(void *handle)
507 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
508 unsigned char **outblock, int *outlen)
512 static int ssh_comp_none_disable(void *handle)
516 const static struct ssh_compress ssh_comp_none = {
518 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
519 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
520 ssh_comp_none_disable, NULL
522 extern const struct ssh_compress ssh_zlib;
523 const static struct ssh_compress *compressions[] = {
524 &ssh_zlib, &ssh_comp_none
527 enum { /* channel types */
532 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
536 * little structure to keep track of outstanding WINDOW_ADJUSTs
544 * 2-3-4 tree storing channels.
547 Ssh ssh; /* pointer back to main context */
548 unsigned remoteid, localid;
550 /* True if we opened this channel but server hasn't confirmed. */
553 * In SSH-1, this value contains four bits:
555 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
556 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
557 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
558 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
560 * A channel is completely finished with when all four bits are set.
564 * True if this channel is causing the underlying connection to be
569 struct ssh2_data_channel {
571 unsigned remwindow, remmaxpkt;
572 /* locwindow is signed so we can cope with excess data. */
573 int locwindow, locmaxwin;
575 * remlocwin is the amount of local window that we think
576 * the remote end had available to it after it sent the
577 * last data packet or window adjust ack.
581 * These store the list of window adjusts that haven't
584 struct winadj *winadj_head, *winadj_tail;
585 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
589 struct ssh_agent_channel {
590 unsigned char *message;
591 unsigned char msglen[4];
592 unsigned lensofar, totallen;
594 struct ssh_x11_channel {
597 struct ssh_pfd_channel {
604 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
605 * use this structure in different ways, reflecting SSH-2's
606 * altogether saner approach to port forwarding.
608 * In SSH-1, you arrange a remote forwarding by sending the server
609 * the remote port number, and the local destination host:port.
610 * When a connection comes in, the server sends you back that
611 * host:port pair, and you connect to it. This is a ready-made
612 * security hole if you're not on the ball: a malicious server
613 * could send you back _any_ host:port pair, so if you trustingly
614 * connect to the address it gives you then you've just opened the
615 * entire inside of your corporate network just by connecting
616 * through it to a dodgy SSH server. Hence, we must store a list of
617 * host:port pairs we _are_ trying to forward to, and reject a
618 * connection request from the server if it's not in the list.
620 * In SSH-2, each side of the connection minds its own business and
621 * doesn't send unnecessary information to the other. You arrange a
622 * remote forwarding by sending the server just the remote port
623 * number. When a connection comes in, the server tells you which
624 * of its ports was connected to; and _you_ have to remember what
625 * local host:port pair went with that port number.
627 * Hence, in SSH-1 this structure is indexed by destination
628 * host:port pair, whereas in SSH-2 it is indexed by source port.
630 struct ssh_portfwd; /* forward declaration */
632 struct ssh_rportfwd {
633 unsigned sport, dport;
636 struct ssh_portfwd *pfrec;
638 #define free_rportfwd(pf) ( \
639 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
642 * Separately to the rportfwd tree (which is for looking up port
643 * open requests from the server), a tree of _these_ structures is
644 * used to keep track of all the currently open port forwardings,
645 * so that we can reconfigure in mid-session if the user requests
649 enum { DESTROY, KEEP, CREATE } status;
651 unsigned sport, dport;
654 struct ssh_rportfwd *remote;
658 #define free_portfwd(pf) ( \
659 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
660 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
663 long length; /* length of `data' actually used */
664 long forcepad; /* SSH-2: force padding to at least this length */
665 int type; /* only used for incoming packets */
666 unsigned long sequence; /* SSH-2 incoming sequence number */
667 unsigned char *data; /* allocated storage */
668 unsigned char *body; /* offset of payload within `data' */
669 long savedpos; /* temporary index into `data' (for strings) */
670 long maxlen; /* amount of storage allocated for `data' */
671 long encrypted_len; /* for SSH-2 total-size counting */
674 * State associated with packet logging
678 struct logblank_t *blanks;
681 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
682 struct Packet *pktin);
683 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
684 struct Packet *pktin);
685 static void ssh1_protocol_setup(Ssh ssh);
686 static void ssh2_protocol_setup(Ssh ssh);
687 static void ssh_size(void *handle, int width, int height);
688 static void ssh_special(void *handle, Telnet_Special);
689 static int ssh2_try_send(struct ssh_channel *c);
690 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
691 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
692 static void ssh2_set_window(struct ssh_channel *c, int newwin);
693 static int ssh_sendbuffer(void *handle);
694 static int ssh_do_close(Ssh ssh, int notify_exit);
695 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
696 static int ssh2_pkt_getbool(struct Packet *pkt);
697 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
698 static void ssh2_timer(void *ctx, long now);
699 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
700 struct Packet *pktin);
702 struct rdpkt1_state_tag {
703 long len, pad, biglen, to_read;
704 unsigned long realcrc, gotcrc;
708 struct Packet *pktin;
711 struct rdpkt2_state_tag {
712 long len, pad, payload, packetlen, maclen;
715 unsigned long incoming_sequence;
716 struct Packet *pktin;
719 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
720 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
722 struct queued_handler;
723 struct queued_handler {
725 chandler_fn_t handler;
727 struct queued_handler *next;
731 const struct plug_function_table *fn;
732 /* the above field _must_ be first in the structure */
742 unsigned char session_key[32];
744 int v1_remote_protoflags;
745 int v1_local_protoflags;
746 int agentfwd_enabled;
749 const struct ssh_cipher *cipher;
752 const struct ssh2_cipher *cscipher, *sccipher;
753 void *cs_cipher_ctx, *sc_cipher_ctx;
754 const struct ssh_mac *csmac, *scmac;
755 void *cs_mac_ctx, *sc_mac_ctx;
756 const struct ssh_compress *cscomp, *sccomp;
757 void *cs_comp_ctx, *sc_comp_ctx;
758 const struct ssh_kex *kex;
759 const struct ssh_signkey *hostkey;
760 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
761 int v2_session_id_len;
767 int echoing, editing;
771 int ospeed, ispeed; /* temporaries */
772 int term_width, term_height;
774 tree234 *channels; /* indexed by local id */
775 struct ssh_channel *mainchan; /* primary session channel */
776 int ncmode; /* is primary channel direct-tcpip? */
781 tree234 *rportfwds, *portfwds;
785 SSH_STATE_BEFORE_SIZE,
791 int size_needed, eof_needed;
793 struct Packet **queue;
794 int queuelen, queuesize;
796 unsigned char *deferred_send_data;
797 int deferred_len, deferred_size;
800 * Gross hack: pscp will try to start SFTP but fall back to
801 * scp1 if that fails. This variable is the means by which
802 * scp.c can reach into the SSH code and find out which one it
807 bufchain banner; /* accumulates banners during do_ssh2_authconn */
815 int conn_throttle_count;
818 int v1_stdout_throttling;
819 unsigned long v2_outgoing_sequence;
821 int ssh1_rdpkt_crstate;
822 int ssh2_rdpkt_crstate;
823 int do_ssh_init_crstate;
824 int ssh_gotdata_crstate;
825 int do_ssh1_login_crstate;
826 int do_ssh1_connection_crstate;
827 int do_ssh2_transport_crstate;
828 int do_ssh2_authconn_crstate;
830 void *do_ssh_init_state;
831 void *do_ssh1_login_state;
832 void *do_ssh2_transport_state;
833 void *do_ssh2_authconn_state;
835 struct rdpkt1_state_tag rdpkt1_state;
836 struct rdpkt2_state_tag rdpkt2_state;
838 /* SSH-1 and SSH-2 use this for different things, but both use it */
839 int protocol_initial_phase_done;
841 void (*protocol) (Ssh ssh, void *vin, int inlen,
843 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
846 * We maintain a full _copy_ of a Config structure here, not
847 * merely a pointer to it. That way, when we're passed a new
848 * one for reconfiguration, we can check the differences and
849 * potentially reconfigure port forwardings etc in mid-session.
854 * Used to transfer data back from async callbacks.
856 void *agent_response;
857 int agent_response_len;
861 * The SSH connection can be set as `frozen', meaning we are
862 * not currently accepting incoming data from the network. This
863 * is slightly more serious than setting the _socket_ as
864 * frozen, because we may already have had data passed to us
865 * from the network which we need to delay processing until
866 * after the freeze is lifted, so we also need a bufchain to
870 bufchain queued_incoming_data;
873 * Dispatch table for packet types that we may have to deal
876 handler_fn_t packet_dispatch[256];
879 * Queues of one-off handler functions for success/failure
880 * indications from a request.
882 struct queued_handler *qhead, *qtail;
885 * This module deals with sending keepalives.
890 * Track incoming and outgoing data sizes and time, for
893 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
894 unsigned long max_data_size;
896 long next_rekey, last_rekey;
897 char *deferred_rekey_reason; /* points to STATIC string; don't free */
900 #define logevent(s) logevent(ssh->frontend, s)
902 /* logevent, only printf-formatted. */
903 static void logeventf(Ssh ssh, const char *fmt, ...)
909 buf = dupvprintf(fmt, ap);
915 #define bombout(msg) \
917 char *text = dupprintf msg; \
918 ssh_do_close(ssh, FALSE); \
920 connection_fatal(ssh->frontend, "%s", text); \
924 /* Functions to leave bits out of the SSH packet log file. */
926 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
928 if (ssh->cfg.logomitpass)
929 pkt->logmode = blanktype;
932 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
934 if (ssh->cfg.logomitdata)
935 pkt->logmode = blanktype;
938 static void end_log_omission(Ssh ssh, struct Packet *pkt)
940 pkt->logmode = PKTLOG_EMIT;
943 /* Helper function for common bits of parsing cfg.ttymodes. */
944 static void parse_ttymodes(Ssh ssh, char *modes,
945 void (*do_mode)(void *data, char *mode, char *val),
949 char *t = strchr(modes, '\t');
950 char *m = snewn(t-modes+1, char);
952 strncpy(m, modes, t-modes);
955 val = get_ttymode(ssh->frontend, m);
959 do_mode(data, m, val);
962 modes += strlen(modes) + 1;
966 static int ssh_channelcmp(void *av, void *bv)
968 struct ssh_channel *a = (struct ssh_channel *) av;
969 struct ssh_channel *b = (struct ssh_channel *) bv;
970 if (a->localid < b->localid)
972 if (a->localid > b->localid)
976 static int ssh_channelfind(void *av, void *bv)
978 unsigned *a = (unsigned *) av;
979 struct ssh_channel *b = (struct ssh_channel *) bv;
987 static int ssh_rportcmp_ssh1(void *av, void *bv)
989 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
990 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
992 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
993 return i < 0 ? -1 : +1;
994 if (a->dport > b->dport)
996 if (a->dport < b->dport)
1001 static int ssh_rportcmp_ssh2(void *av, void *bv)
1003 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1004 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1006 if (a->sport > b->sport)
1008 if (a->sport < b->sport)
1014 * Special form of strcmp which can cope with NULL inputs. NULL is
1015 * defined to sort before even the empty string.
1017 static int nullstrcmp(const char *a, const char *b)
1019 if (a == NULL && b == NULL)
1025 return strcmp(a, b);
1028 static int ssh_portcmp(void *av, void *bv)
1030 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1031 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1033 if (a->type > b->type)
1035 if (a->type < b->type)
1037 if (a->addressfamily > b->addressfamily)
1039 if (a->addressfamily < b->addressfamily)
1041 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1042 return i < 0 ? -1 : +1;
1043 if (a->sport > b->sport)
1045 if (a->sport < b->sport)
1047 if (a->type != 'D') {
1048 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1049 return i < 0 ? -1 : +1;
1050 if (a->dport > b->dport)
1052 if (a->dport < b->dport)
1058 static int alloc_channel_id(Ssh ssh)
1060 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1061 unsigned low, high, mid;
1063 struct ssh_channel *c;
1066 * First-fit allocation of channel numbers: always pick the
1067 * lowest unused one. To do this, binary-search using the
1068 * counted B-tree to find the largest channel ID which is in a
1069 * contiguous sequence from the beginning. (Precisely
1070 * everything in that sequence must have ID equal to its tree
1071 * index plus CHANNEL_NUMBER_OFFSET.)
1073 tsize = count234(ssh->channels);
1077 while (high - low > 1) {
1078 mid = (high + low) / 2;
1079 c = index234(ssh->channels, mid);
1080 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1081 low = mid; /* this one is fine */
1083 high = mid; /* this one is past it */
1086 * Now low points to either -1, or the tree index of the
1087 * largest ID in the initial sequence.
1090 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1091 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1093 return low + 1 + CHANNEL_NUMBER_OFFSET;
1096 static void c_write_stderr(int trusted, const char *buf, int len)
1099 for (i = 0; i < len; i++)
1100 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1101 fputc(buf[i], stderr);
1104 static void c_write(Ssh ssh, const char *buf, int len)
1106 if (flags & FLAG_STDERR)
1107 c_write_stderr(1, buf, len);
1109 from_backend(ssh->frontend, 1, buf, len);
1112 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1114 if (flags & FLAG_STDERR)
1115 c_write_stderr(0, buf, len);
1117 from_backend_untrusted(ssh->frontend, buf, len);
1120 static void c_write_str(Ssh ssh, const char *buf)
1122 c_write(ssh, buf, strlen(buf));
1125 static void ssh_free_packet(struct Packet *pkt)
1130 static struct Packet *ssh_new_packet(void)
1132 struct Packet *pkt = snew(struct Packet);
1134 pkt->body = pkt->data = NULL;
1136 pkt->logmode = PKTLOG_EMIT;
1144 * Collect incoming data in the incoming packet buffer.
1145 * Decipher and verify the packet when it is completely read.
1146 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1147 * Update the *data and *datalen variables.
1148 * Return a Packet structure when a packet is completed.
1150 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1152 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1154 crBegin(ssh->ssh1_rdpkt_crstate);
1156 st->pktin = ssh_new_packet();
1158 st->pktin->type = 0;
1159 st->pktin->length = 0;
1161 for (st->i = st->len = 0; st->i < 4; st->i++) {
1162 while ((*datalen) == 0)
1164 st->len = (st->len << 8) + **data;
1165 (*data)++, (*datalen)--;
1168 st->pad = 8 - (st->len % 8);
1169 st->biglen = st->len + st->pad;
1170 st->pktin->length = st->len - 5;
1172 if (st->biglen < 0) {
1173 bombout(("Extremely large packet length from server suggests"
1174 " data stream corruption"));
1175 ssh_free_packet(st->pktin);
1179 st->pktin->maxlen = st->biglen;
1180 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1182 st->to_read = st->biglen;
1183 st->p = st->pktin->data;
1184 while (st->to_read > 0) {
1185 st->chunk = st->to_read;
1186 while ((*datalen) == 0)
1188 if (st->chunk > (*datalen))
1189 st->chunk = (*datalen);
1190 memcpy(st->p, *data, st->chunk);
1192 *datalen -= st->chunk;
1194 st->to_read -= st->chunk;
1197 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1198 st->biglen, NULL)) {
1199 bombout(("Network attack (CRC compensation) detected!"));
1200 ssh_free_packet(st->pktin);
1205 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1207 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1208 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1209 if (st->gotcrc != st->realcrc) {
1210 bombout(("Incorrect CRC received on packet"));
1211 ssh_free_packet(st->pktin);
1215 st->pktin->body = st->pktin->data + st->pad + 1;
1216 st->pktin->savedpos = 0;
1218 if (ssh->v1_compressing) {
1219 unsigned char *decompblk;
1221 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1222 st->pktin->body - 1, st->pktin->length + 1,
1223 &decompblk, &decomplen)) {
1224 bombout(("Zlib decompression encountered invalid data"));
1225 ssh_free_packet(st->pktin);
1229 if (st->pktin->maxlen < st->pad + decomplen) {
1230 st->pktin->maxlen = st->pad + decomplen;
1231 st->pktin->data = sresize(st->pktin->data,
1232 st->pktin->maxlen + APIEXTRA,
1234 st->pktin->body = st->pktin->data + st->pad + 1;
1237 memcpy(st->pktin->body - 1, decompblk, decomplen);
1239 st->pktin->length = decomplen - 1;
1242 st->pktin->type = st->pktin->body[-1];
1245 * Log incoming packet, possibly omitting sensitive fields.
1249 struct logblank_t blank;
1250 if (ssh->cfg.logomitdata) {
1251 int do_blank = FALSE, blank_prefix = 0;
1252 /* "Session data" packets - omit the data field */
1253 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1254 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1255 do_blank = TRUE; blank_prefix = 4;
1256 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1257 do_blank = TRUE; blank_prefix = 8;
1260 blank.offset = blank_prefix;
1261 blank.len = st->pktin->length;
1262 blank.type = PKTLOG_OMIT;
1266 log_packet(ssh->logctx,
1267 PKT_INCOMING, st->pktin->type,
1268 ssh1_pkt_type(st->pktin->type),
1269 st->pktin->body, st->pktin->length,
1273 crFinish(st->pktin);
1276 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1278 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1280 crBegin(ssh->ssh2_rdpkt_crstate);
1282 st->pktin = ssh_new_packet();
1284 st->pktin->type = 0;
1285 st->pktin->length = 0;
1287 st->cipherblk = ssh->sccipher->blksize;
1290 if (st->cipherblk < 8)
1293 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1296 * Acquire and decrypt the first block of the packet. This will
1297 * contain the length and padding details.
1299 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1300 while ((*datalen) == 0)
1302 st->pktin->data[st->i] = *(*data)++;
1307 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1308 st->pktin->data, st->cipherblk);
1311 * Now get the length and padding figures.
1313 st->len = GET_32BIT(st->pktin->data);
1314 st->pad = st->pktin->data[4];
1317 * _Completely_ silly lengths should be stomped on before they
1318 * do us any more damage.
1320 if (st->len < 0 || st->len > 35000 || st->pad < 4 ||
1321 st->len - st->pad < 1 || (st->len + 4) % st->cipherblk != 0) {
1322 bombout(("Incoming packet was garbled on decryption"));
1323 ssh_free_packet(st->pktin);
1328 * This enables us to deduce the payload length.
1330 st->payload = st->len - st->pad - 1;
1332 st->pktin->length = st->payload + 5;
1335 * So now we can work out the total packet length.
1337 st->packetlen = st->len + 4;
1338 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1341 * Allocate memory for the rest of the packet.
1343 st->pktin->maxlen = st->packetlen + st->maclen;
1344 st->pktin->data = sresize(st->pktin->data,
1345 st->pktin->maxlen + APIEXTRA,
1349 * Read and decrypt the remainder of the packet.
1351 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1353 while ((*datalen) == 0)
1355 st->pktin->data[st->i] = *(*data)++;
1358 /* Decrypt everything _except_ the MAC. */
1360 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1361 st->pktin->data + st->cipherblk,
1362 st->packetlen - st->cipherblk);
1364 st->pktin->encrypted_len = st->packetlen;
1370 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1371 st->incoming_sequence)) {
1372 bombout(("Incorrect MAC received on packet"));
1373 ssh_free_packet(st->pktin);
1377 st->pktin->sequence = st->incoming_sequence++;
1380 * Decompress packet payload.
1383 unsigned char *newpayload;
1386 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1387 st->pktin->data + 5, st->pktin->length - 5,
1388 &newpayload, &newlen)) {
1389 if (st->pktin->maxlen < newlen + 5) {
1390 st->pktin->maxlen = newlen + 5;
1391 st->pktin->data = sresize(st->pktin->data,
1392 st->pktin->maxlen + APIEXTRA,
1395 st->pktin->length = 5 + newlen;
1396 memcpy(st->pktin->data + 5, newpayload, newlen);
1401 st->pktin->savedpos = 6;
1402 st->pktin->body = st->pktin->data;
1403 st->pktin->type = st->pktin->data[5];
1406 * Log incoming packet, possibly omitting sensitive fields.
1410 struct logblank_t blank;
1411 if (ssh->cfg.logomitdata) {
1412 int do_blank = FALSE, blank_prefix = 0;
1413 /* "Session data" packets - omit the data field */
1414 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1415 do_blank = TRUE; blank_prefix = 8;
1416 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1417 do_blank = TRUE; blank_prefix = 12;
1420 blank.offset = blank_prefix;
1421 blank.len = (st->pktin->length-6) - blank_prefix;
1422 blank.type = PKTLOG_OMIT;
1426 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1427 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1429 st->pktin->data+6, st->pktin->length-6,
1433 crFinish(st->pktin);
1436 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1438 int pad, biglen, i, pktoffs;
1442 * XXX various versions of SC (including 8.8.4) screw up the
1443 * register allocation in this function and use the same register
1444 * (D6) for len and as a temporary, with predictable results. The
1445 * following sledgehammer prevents this.
1452 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1453 ssh1_pkt_type(pkt->data[12]),
1454 pkt->body, pkt->length - (pkt->body - pkt->data),
1455 pkt->nblanks, pkt->blanks);
1456 sfree(pkt->blanks); pkt->blanks = NULL;
1459 if (ssh->v1_compressing) {
1460 unsigned char *compblk;
1462 zlib_compress_block(ssh->cs_comp_ctx,
1463 pkt->data + 12, pkt->length - 12,
1464 &compblk, &complen);
1465 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1466 memcpy(pkt->data + 12, compblk, complen);
1468 pkt->length = complen + 12;
1471 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1473 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1474 pad = 8 - (len % 8);
1476 biglen = len + pad; /* len(padding+type+data+CRC) */
1478 for (i = pktoffs; i < 4+8; i++)
1479 pkt->data[i] = random_byte();
1480 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1481 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1482 PUT_32BIT(pkt->data + pktoffs, len);
1485 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1486 pkt->data + pktoffs + 4, biglen);
1488 if (offset_p) *offset_p = pktoffs;
1489 return biglen + 4; /* len(length+padding+type+data+CRC) */
1492 static int s_write(Ssh ssh, void *data, int len)
1495 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len, 0, NULL);
1496 return sk_write(ssh->s, (char *)data, len);
1499 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1501 int len, backlog, offset;
1502 len = s_wrpkt_prepare(ssh, pkt, &offset);
1503 backlog = s_write(ssh, pkt->data + offset, len);
1504 if (backlog > SSH_MAX_BACKLOG)
1505 ssh_throttle_all(ssh, 1, backlog);
1506 ssh_free_packet(pkt);
1509 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1512 len = s_wrpkt_prepare(ssh, pkt, &offset);
1513 if (ssh->deferred_len + len > ssh->deferred_size) {
1514 ssh->deferred_size = ssh->deferred_len + len + 128;
1515 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1519 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1520 pkt->data + offset, len);
1521 ssh->deferred_len += len;
1522 ssh_free_packet(pkt);
1526 * Construct a SSH-1 packet with the specified contents.
1527 * (This all-at-once interface used to be the only one, but now SSH-1
1528 * packets can also be constructed incrementally.)
1530 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1536 pkt = ssh1_pkt_init(pkttype);
1538 while ((argtype = va_arg(ap, int)) != PKT_END) {
1539 unsigned char *argp, argchar;
1541 unsigned long argint;
1544 /* Actual fields in the packet */
1546 argint = va_arg(ap, int);
1547 ssh_pkt_adduint32(pkt, argint);
1550 argchar = (unsigned char) va_arg(ap, int);
1551 ssh_pkt_addbyte(pkt, argchar);
1554 argp = va_arg(ap, unsigned char *);
1555 arglen = va_arg(ap, int);
1556 ssh_pkt_adddata(pkt, argp, arglen);
1559 sargp = va_arg(ap, char *);
1560 ssh_pkt_addstring(pkt, sargp);
1563 bn = va_arg(ap, Bignum);
1564 ssh1_pkt_addmp(pkt, bn);
1566 /* Tokens for modifications to packet logging */
1568 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1571 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1574 end_log_omission(ssh, pkt);
1582 static void send_packet(Ssh ssh, int pkttype, ...)
1586 va_start(ap, pkttype);
1587 pkt = construct_packet(ssh, pkttype, ap);
1592 static void defer_packet(Ssh ssh, int pkttype, ...)
1596 va_start(ap, pkttype);
1597 pkt = construct_packet(ssh, pkttype, ap);
1599 s_wrpkt_defer(ssh, pkt);
1602 static int ssh_versioncmp(char *a, char *b)
1605 unsigned long av, bv;
1607 av = strtoul(a, &ae, 10);
1608 bv = strtoul(b, &be, 10);
1610 return (av < bv ? -1 : +1);
1615 av = strtoul(ae, &ae, 10);
1616 bv = strtoul(be, &be, 10);
1618 return (av < bv ? -1 : +1);
1623 * Utility routines for putting an SSH-protocol `string' and
1624 * `uint32' into a hash state.
1626 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1628 unsigned char lenblk[4];
1629 PUT_32BIT(lenblk, len);
1630 h->bytes(s, lenblk, 4);
1631 h->bytes(s, str, len);
1634 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1636 unsigned char intblk[4];
1637 PUT_32BIT(intblk, i);
1638 h->bytes(s, intblk, 4);
1642 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1644 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1646 if (pkt->maxlen < length) {
1647 unsigned char *body = pkt->body;
1648 int offset = body ? body - pkt->data : 0;
1649 pkt->maxlen = length + 256;
1650 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1651 if (body) pkt->body = pkt->data + offset;
1654 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1656 if (pkt->logmode != PKTLOG_EMIT) {
1658 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1660 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1661 (pkt->body - pkt->data);
1662 pkt->blanks[pkt->nblanks-1].len = len;
1663 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1666 ssh_pkt_ensure(pkt, pkt->length);
1667 memcpy(pkt->data + pkt->length - len, data, len);
1669 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1671 ssh_pkt_adddata(pkt, &byte, 1);
1673 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1675 ssh_pkt_adddata(pkt, &value, 1);
1677 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1680 PUT_32BIT(x, value);
1681 ssh_pkt_adddata(pkt, x, 4);
1683 static void ssh_pkt_addstring_start(struct Packet *pkt)
1685 ssh_pkt_adduint32(pkt, 0);
1686 pkt->savedpos = pkt->length;
1688 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1690 ssh_pkt_adddata(pkt, data, strlen(data));
1691 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1693 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1695 ssh_pkt_adddata(pkt, data, len);
1696 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1698 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1700 ssh_pkt_addstring_start(pkt);
1701 ssh_pkt_addstring_str(pkt, data);
1703 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1705 int len = ssh1_bignum_length(b);
1706 unsigned char *data = snewn(len, unsigned char);
1707 (void) ssh1_write_bignum(data, b);
1708 ssh_pkt_adddata(pkt, data, len);
1711 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1714 int i, n = (bignum_bitcount(b) + 7) / 8;
1715 p = snewn(n + 1, unsigned char);
1717 for (i = 1; i <= n; i++)
1718 p[i] = bignum_byte(b, n - i);
1720 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1722 memmove(p, p + i, n + 1 - i);
1726 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1730 p = ssh2_mpint_fmt(b, &len);
1731 ssh_pkt_addstring_start(pkt);
1732 ssh_pkt_addstring_data(pkt, (char *)p, len);
1736 static struct Packet *ssh1_pkt_init(int pkt_type)
1738 struct Packet *pkt = ssh_new_packet();
1739 pkt->length = 4 + 8; /* space for length + max padding */
1740 ssh_pkt_addbyte(pkt, pkt_type);
1741 pkt->body = pkt->data + pkt->length;
1745 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1746 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1747 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1748 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1749 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1750 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1751 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1752 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1753 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1755 static struct Packet *ssh2_pkt_init(int pkt_type)
1757 struct Packet *pkt = ssh_new_packet();
1758 pkt->length = 5; /* space for packet length + padding length */
1760 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1761 pkt->body = pkt->data + pkt->length; /* after packet type */
1766 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1767 * put the MAC on it. Final packet, ready to be sent, is stored in
1768 * pkt->data. Total length is returned.
1770 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1772 int cipherblk, maclen, padding, i;
1775 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1776 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1777 pkt->body, pkt->length - (pkt->body - pkt->data),
1778 pkt->nblanks, pkt->blanks);
1779 sfree(pkt->blanks); pkt->blanks = NULL;
1783 * Compress packet payload.
1786 unsigned char *newpayload;
1789 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1791 &newpayload, &newlen)) {
1793 ssh2_pkt_adddata(pkt, newpayload, newlen);
1799 * Add padding. At least four bytes, and must also bring total
1800 * length (minus MAC) up to a multiple of the block size.
1801 * If pkt->forcepad is set, make sure the packet is at least that size
1804 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1805 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1807 if (pkt->length + padding < pkt->forcepad)
1808 padding = pkt->forcepad - pkt->length;
1810 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1811 assert(padding <= 255);
1812 maclen = ssh->csmac ? ssh->csmac->len : 0;
1813 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1814 pkt->data[4] = padding;
1815 for (i = 0; i < padding; i++)
1816 pkt->data[pkt->length + i] = random_byte();
1817 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1819 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1820 pkt->length + padding,
1821 ssh->v2_outgoing_sequence);
1822 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1825 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1826 pkt->data, pkt->length + padding);
1828 pkt->encrypted_len = pkt->length + padding;
1830 /* Ready-to-send packet starts at pkt->data. We return length. */
1831 return pkt->length + padding + maclen;
1835 * Routines called from the main SSH code to send packets. There
1836 * are quite a few of these, because we have two separate
1837 * mechanisms for delaying the sending of packets:
1839 * - In order to send an IGNORE message and a password message in
1840 * a single fixed-length blob, we require the ability to
1841 * concatenate the encrypted forms of those two packets _into_ a
1842 * single blob and then pass it to our <network.h> transport
1843 * layer in one go. Hence, there's a deferment mechanism which
1844 * works after packet encryption.
1846 * - In order to avoid sending any connection-layer messages
1847 * during repeat key exchange, we have to queue up any such
1848 * outgoing messages _before_ they are encrypted (and in
1849 * particular before they're allocated sequence numbers), and
1850 * then send them once we've finished.
1852 * I call these mechanisms `defer' and `queue' respectively, so as
1853 * to distinguish them reasonably easily.
1855 * The functions send_noqueue() and defer_noqueue() free the packet
1856 * structure they are passed. Every outgoing packet goes through
1857 * precisely one of these functions in its life; packets passed to
1858 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1859 * these or get queued, and then when the queue is later emptied
1860 * the packets are all passed to defer_noqueue().
1862 * When using a CBC-mode cipher, it's necessary to ensure that an
1863 * attacker can't provide data to be encrypted using an IV that they
1864 * know. We ensure this by prefixing each packet that might contain
1865 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1866 * mechanism, so in this case send_noqueue() ends up redirecting to
1867 * defer_noqueue(). If you don't like this inefficiency, don't use
1871 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1872 static void ssh_pkt_defersend(Ssh);
1875 * Send an SSH-2 packet immediately, without queuing or deferring.
1877 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1881 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1882 /* We need to send two packets, so use the deferral mechanism. */
1883 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1884 ssh_pkt_defersend(ssh);
1887 len = ssh2_pkt_construct(ssh, pkt);
1888 backlog = s_write(ssh, pkt->data, len);
1889 if (backlog > SSH_MAX_BACKLOG)
1890 ssh_throttle_all(ssh, 1, backlog);
1892 ssh->outgoing_data_size += pkt->encrypted_len;
1893 if (!ssh->kex_in_progress &&
1894 ssh->max_data_size != 0 &&
1895 ssh->outgoing_data_size > ssh->max_data_size)
1896 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1898 ssh_free_packet(pkt);
1902 * Defer an SSH-2 packet.
1904 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
1907 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
1908 ssh->deferred_len == 0 && !noignore) {
1910 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1911 * get encrypted with a known IV.
1913 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
1914 ssh2_pkt_addstring_start(ipkt);
1915 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
1917 len = ssh2_pkt_construct(ssh, pkt);
1918 if (ssh->deferred_len + len > ssh->deferred_size) {
1919 ssh->deferred_size = ssh->deferred_len + len + 128;
1920 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1924 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1925 ssh->deferred_len += len;
1926 ssh->deferred_data_size += pkt->encrypted_len;
1927 ssh_free_packet(pkt);
1931 * Queue an SSH-2 packet.
1933 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1935 assert(ssh->queueing);
1937 if (ssh->queuelen >= ssh->queuesize) {
1938 ssh->queuesize = ssh->queuelen + 32;
1939 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1942 ssh->queue[ssh->queuelen++] = pkt;
1946 * Either queue or send a packet, depending on whether queueing is
1949 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1952 ssh2_pkt_queue(ssh, pkt);
1954 ssh2_pkt_send_noqueue(ssh, pkt);
1958 * Either queue or defer a packet, depending on whether queueing is
1961 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1964 ssh2_pkt_queue(ssh, pkt);
1966 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1970 * Send the whole deferred data block constructed by
1971 * ssh2_pkt_defer() or SSH-1's defer_packet().
1973 * The expected use of the defer mechanism is that you call
1974 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1975 * not currently queueing, this simply sets up deferred_send_data
1976 * and then sends it. If we _are_ currently queueing, the calls to
1977 * ssh2_pkt_defer() put the deferred packets on to the queue
1978 * instead, and therefore ssh_pkt_defersend() has no deferred data
1979 * to send. Hence, there's no need to make it conditional on
1982 static void ssh_pkt_defersend(Ssh ssh)
1985 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
1986 ssh->deferred_len = ssh->deferred_size = 0;
1987 sfree(ssh->deferred_send_data);
1988 ssh->deferred_send_data = NULL;
1989 if (backlog > SSH_MAX_BACKLOG)
1990 ssh_throttle_all(ssh, 1, backlog);
1992 ssh->outgoing_data_size += ssh->deferred_data_size;
1993 if (!ssh->kex_in_progress &&
1994 ssh->max_data_size != 0 &&
1995 ssh->outgoing_data_size > ssh->max_data_size)
1996 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1997 ssh->deferred_data_size = 0;
2001 * Send a packet whose length needs to be disguised (typically
2002 * passwords or keyboard-interactive responses).
2004 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2010 * The simplest way to do this is to adjust the
2011 * variable-length padding field in the outgoing packet.
2013 * Currently compiled out, because some Cisco SSH servers
2014 * don't like excessively padded packets (bah, why's it
2017 pkt->forcepad = padsize;
2018 ssh2_pkt_send(ssh, pkt);
2023 * If we can't do that, however, an alternative approach is
2024 * to use the pkt_defer mechanism to bundle the packet
2025 * tightly together with an SSH_MSG_IGNORE such that their
2026 * combined length is a constant. So first we construct the
2027 * final form of this packet and defer its sending.
2029 ssh2_pkt_defer(ssh, pkt);
2032 * Now construct an SSH_MSG_IGNORE which includes a string
2033 * that's an exact multiple of the cipher block size. (If
2034 * the cipher is NULL so that the block size is
2035 * unavailable, we don't do this trick at all, because we
2036 * gain nothing by it.)
2038 if (ssh->cscipher) {
2041 stringlen = (256 - ssh->deferred_len);
2042 stringlen += ssh->cscipher->blksize - 1;
2043 stringlen -= (stringlen % ssh->cscipher->blksize);
2046 * Temporarily disable actual compression, so we
2047 * can guarantee to get this string exactly the
2048 * length we want it. The compression-disabling
2049 * routine should return an integer indicating how
2050 * many bytes we should adjust our string length
2054 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2056 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2057 ssh2_pkt_addstring_start(pkt);
2058 for (i = 0; i < stringlen; i++) {
2059 char c = (char) random_byte();
2060 ssh2_pkt_addstring_data(pkt, &c, 1);
2062 ssh2_pkt_defer(ssh, pkt);
2064 ssh_pkt_defersend(ssh);
2069 * Send all queued SSH-2 packets. We send them by means of
2070 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2071 * packets that needed to be lumped together.
2073 static void ssh2_pkt_queuesend(Ssh ssh)
2077 assert(!ssh->queueing);
2079 for (i = 0; i < ssh->queuelen; i++)
2080 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2083 ssh_pkt_defersend(ssh);
2087 void bndebug(char *string, Bignum b)
2091 p = ssh2_mpint_fmt(b, &len);
2092 debug(("%s", string));
2093 for (i = 0; i < len; i++)
2094 debug((" %02x", p[i]));
2100 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2104 p = ssh2_mpint_fmt(b, &len);
2105 hash_string(h, s, p, len);
2110 * Packet decode functions for both SSH-1 and SSH-2.
2112 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2114 unsigned long value;
2115 if (pkt->length - pkt->savedpos < 4)
2116 return 0; /* arrgh, no way to decline (FIXME?) */
2117 value = GET_32BIT(pkt->body + pkt->savedpos);
2121 static int ssh2_pkt_getbool(struct Packet *pkt)
2123 unsigned long value;
2124 if (pkt->length - pkt->savedpos < 1)
2125 return 0; /* arrgh, no way to decline (FIXME?) */
2126 value = pkt->body[pkt->savedpos] != 0;
2130 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2135 if (pkt->length - pkt->savedpos < 4)
2137 len = GET_32BIT(pkt->body + pkt->savedpos);
2142 if (pkt->length - pkt->savedpos < *length)
2144 *p = (char *)(pkt->body + pkt->savedpos);
2145 pkt->savedpos += *length;
2147 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2149 if (pkt->length - pkt->savedpos < length)
2151 pkt->savedpos += length;
2152 return pkt->body + (pkt->savedpos - length);
2154 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2155 unsigned char **keystr)
2159 j = makekey(pkt->body + pkt->savedpos,
2160 pkt->length - pkt->savedpos,
2167 assert(pkt->savedpos < pkt->length);
2171 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2176 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2177 pkt->length - pkt->savedpos, &b);
2185 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2191 ssh_pkt_getstring(pkt, &p, &length);
2196 b = bignum_from_bytes((unsigned char *)p, length);
2201 * Helper function to add an SSH-2 signature blob to a packet.
2202 * Expects to be shown the public key blob as well as the signature
2203 * blob. Normally works just like ssh2_pkt_addstring, but will
2204 * fiddle with the signature packet if necessary for
2205 * BUG_SSH2_RSA_PADDING.
2207 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2208 void *pkblob_v, int pkblob_len,
2209 void *sigblob_v, int sigblob_len)
2211 unsigned char *pkblob = (unsigned char *)pkblob_v;
2212 unsigned char *sigblob = (unsigned char *)sigblob_v;
2214 /* dmemdump(pkblob, pkblob_len); */
2215 /* dmemdump(sigblob, sigblob_len); */
2218 * See if this is in fact an ssh-rsa signature and a buggy
2219 * server; otherwise we can just do this the easy way.
2221 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2222 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2223 int pos, len, siglen;
2226 * Find the byte length of the modulus.
2229 pos = 4+7; /* skip over "ssh-rsa" */
2230 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2231 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2232 pos += 4; /* find modulus itself */
2233 while (len > 0 && pkblob[pos] == 0)
2235 /* debug(("modulus length is %d\n", len)); */
2238 * Now find the signature integer.
2240 pos = 4+7; /* skip over "ssh-rsa" */
2241 siglen = GET_32BIT(sigblob+pos);
2242 /* debug(("signature length is %d\n", siglen)); */
2244 if (len != siglen) {
2245 unsigned char newlen[4];
2246 ssh2_pkt_addstring_start(pkt);
2247 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2248 /* dmemdump(sigblob, pos); */
2249 pos += 4; /* point to start of actual sig */
2250 PUT_32BIT(newlen, len);
2251 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2252 /* dmemdump(newlen, 4); */
2254 while (len-- > siglen) {
2255 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2256 /* dmemdump(newlen, 1); */
2258 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2259 /* dmemdump(sigblob+pos, siglen); */
2263 /* Otherwise fall through and do it the easy way. */
2266 ssh2_pkt_addstring_start(pkt);
2267 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2271 * Examine the remote side's version string and compare it against
2272 * a list of known buggy implementations.
2274 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2276 char *imp; /* pointer to implementation part */
2278 imp += strcspn(imp, "-");
2280 imp += strcspn(imp, "-");
2283 ssh->remote_bugs = 0;
2286 * General notes on server version strings:
2287 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2288 * here -- in particular, we've heard of one that's perfectly happy
2289 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2290 * so we can't distinguish them.
2292 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2293 (ssh->cfg.sshbug_ignore1 == AUTO &&
2294 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2295 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2296 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2297 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2299 * These versions don't support SSH1_MSG_IGNORE, so we have
2300 * to use a different defence against password length
2303 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2304 logevent("We believe remote version has SSH-1 ignore bug");
2307 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2308 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2309 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2311 * These versions need a plain password sent; they can't
2312 * handle having a null and a random length of data after
2315 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2316 logevent("We believe remote version needs a plain SSH-1 password");
2319 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2320 (ssh->cfg.sshbug_rsa1 == AUTO &&
2321 (!strcmp(imp, "Cisco-1.25")))) {
2323 * These versions apparently have no clue whatever about
2324 * RSA authentication and will panic and die if they see
2325 * an AUTH_RSA message.
2327 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2328 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2331 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2332 (ssh->cfg.sshbug_hmac2 == AUTO &&
2333 !wc_match("* VShell", imp) &&
2334 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2335 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2336 wc_match("2.1 *", imp)))) {
2338 * These versions have the HMAC bug.
2340 ssh->remote_bugs |= BUG_SSH2_HMAC;
2341 logevent("We believe remote version has SSH-2 HMAC bug");
2344 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2345 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2346 !wc_match("* VShell", imp) &&
2347 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2349 * These versions have the key-derivation bug (failing to
2350 * include the literal shared secret in the hashes that
2351 * generate the keys).
2353 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2354 logevent("We believe remote version has SSH-2 key-derivation bug");
2357 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2358 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2359 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2360 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2362 * These versions have the SSH-2 RSA padding bug.
2364 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2365 logevent("We believe remote version has SSH-2 RSA padding bug");
2368 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2369 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2370 wc_match("OpenSSH_2.[0-2]*", imp))) {
2372 * These versions have the SSH-2 session-ID bug in
2373 * public-key authentication.
2375 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2376 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2379 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2380 (ssh->cfg.sshbug_rekey2 == AUTO &&
2381 (wc_match("DigiSSH_2.0", imp) ||
2382 wc_match("OpenSSH_2.[0-4]*", imp) ||
2383 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2384 wc_match("Sun_SSH_1.0", imp) ||
2385 wc_match("Sun_SSH_1.0.1", imp) ||
2386 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2387 wc_match("WeOnlyDo-*", imp)))) {
2389 * These versions have the SSH-2 rekey bug.
2391 ssh->remote_bugs |= BUG_SSH2_REKEY;
2392 logevent("We believe remote version has SSH-2 rekey bug");
2397 * The `software version' part of an SSH version string is required
2398 * to contain no spaces or minus signs.
2400 static void ssh_fix_verstring(char *str)
2402 /* Eat "SSH-<protoversion>-". */
2403 assert(*str == 'S'); str++;
2404 assert(*str == 'S'); str++;
2405 assert(*str == 'H'); str++;
2406 assert(*str == '-'); str++;
2407 while (*str && *str != '-') str++;
2408 assert(*str == '-'); str++;
2410 /* Convert minus signs and spaces in the remaining string into
2413 if (*str == '-' || *str == ' ')
2420 * Send an appropriate SSH version string.
2422 static void ssh_send_verstring(Ssh ssh, char *svers)
2426 if (ssh->version == 2) {
2428 * Construct a v2 version string.
2430 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2433 * Construct a v1 version string.
2435 verstring = dupprintf("SSH-%s-%s\012",
2436 (ssh_versioncmp(svers, "1.5") <= 0 ?
2441 ssh_fix_verstring(verstring);
2443 if (ssh->version == 2) {
2446 * Record our version string.
2448 len = strcspn(verstring, "\015\012");
2449 ssh->v_c = snewn(len + 1, char);
2450 memcpy(ssh->v_c, verstring, len);
2454 logeventf(ssh, "We claim version: %.*s",
2455 strcspn(verstring, "\015\012"), verstring);
2456 s_write(ssh, verstring, strlen(verstring));
2460 static int do_ssh_init(Ssh ssh, unsigned char c)
2462 struct do_ssh_init_state {
2470 crState(do_ssh_init_state);
2472 crBegin(ssh->do_ssh_init_crstate);
2474 /* Search for a line beginning with the string "SSH-" in the input. */
2476 if (c != 'S') goto no;
2478 if (c != 'S') goto no;
2480 if (c != 'H') goto no;
2482 if (c != '-') goto no;
2491 s->vstring = snewn(s->vstrsize, char);
2492 strcpy(s->vstring, "SSH-");
2496 crReturn(1); /* get another char */
2497 if (s->vslen >= s->vstrsize - 1) {
2499 s->vstring = sresize(s->vstring, s->vstrsize, char);
2501 s->vstring[s->vslen++] = c;
2504 s->version[s->i] = '\0';
2506 } else if (s->i < sizeof(s->version) - 1)
2507 s->version[s->i++] = c;
2508 } else if (c == '\012')
2512 ssh->agentfwd_enabled = FALSE;
2513 ssh->rdpkt2_state.incoming_sequence = 0;
2515 s->vstring[s->vslen] = 0;
2516 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2517 logeventf(ssh, "Server version: %s", s->vstring);
2518 ssh_detect_bugs(ssh, s->vstring);
2521 * Decide which SSH protocol version to support.
2524 /* Anything strictly below "2.0" means protocol 1 is supported. */
2525 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2526 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2527 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2529 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2530 bombout(("SSH protocol version 1 required by user but not provided by server"));
2533 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2534 bombout(("SSH protocol version 2 required by user but not provided by server"));
2538 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1))
2543 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2545 /* Send the version string, if we haven't already */
2546 if (ssh->cfg.sshprot != 3)
2547 ssh_send_verstring(ssh, s->version);
2549 if (ssh->version == 2) {
2552 * Record their version string.
2554 len = strcspn(s->vstring, "\015\012");
2555 ssh->v_s = snewn(len + 1, char);
2556 memcpy(ssh->v_s, s->vstring, len);
2560 * Initialise SSH-2 protocol.
2562 ssh->protocol = ssh2_protocol;
2563 ssh2_protocol_setup(ssh);
2564 ssh->s_rdpkt = ssh2_rdpkt;
2567 * Initialise SSH-1 protocol.
2569 ssh->protocol = ssh1_protocol;
2570 ssh1_protocol_setup(ssh);
2571 ssh->s_rdpkt = ssh1_rdpkt;
2573 if (ssh->version == 2)
2574 do_ssh2_transport(ssh, NULL, -1, NULL);
2576 update_specials_menu(ssh->frontend);
2577 ssh->state = SSH_STATE_BEFORE_SIZE;
2578 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2585 static void ssh_process_incoming_data(Ssh ssh,
2586 unsigned char **data, int *datalen)
2588 struct Packet *pktin;
2590 pktin = ssh->s_rdpkt(ssh, data, datalen);
2592 ssh->protocol(ssh, NULL, 0, pktin);
2593 ssh_free_packet(pktin);
2597 static void ssh_queue_incoming_data(Ssh ssh,
2598 unsigned char **data, int *datalen)
2600 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2605 static void ssh_process_queued_incoming_data(Ssh ssh)
2608 unsigned char *data;
2611 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2612 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2616 while (!ssh->frozen && len > 0)
2617 ssh_process_incoming_data(ssh, &data, &len);
2620 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2624 static void ssh_set_frozen(Ssh ssh, int frozen)
2627 sk_set_frozen(ssh->s, frozen);
2628 ssh->frozen = frozen;
2631 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2633 /* Log raw data, if we're in that mode. */
2635 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2638 crBegin(ssh->ssh_gotdata_crstate);
2641 * To begin with, feed the characters one by one to the
2642 * protocol initialisation / selection function do_ssh_init().
2643 * When that returns 0, we're done with the initial greeting
2644 * exchange and can move on to packet discipline.
2647 int ret; /* need not be kept across crReturn */
2649 crReturnV; /* more data please */
2650 ret = do_ssh_init(ssh, *data);
2658 * We emerge from that loop when the initial negotiation is
2659 * over and we have selected an s_rdpkt function. Now pass
2660 * everything to s_rdpkt, and then pass the resulting packets
2661 * to the proper protocol handler.
2665 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2667 ssh_queue_incoming_data(ssh, &data, &datalen);
2668 /* This uses up all data and cannot cause anything interesting
2669 * to happen; indeed, for anything to happen at all, we must
2670 * return, so break out. */
2672 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2673 /* This uses up some or all data, and may freeze the
2675 ssh_process_queued_incoming_data(ssh);
2677 /* This uses up some or all data, and may freeze the
2679 ssh_process_incoming_data(ssh, &data, &datalen);
2681 /* FIXME this is probably EBW. */
2682 if (ssh->state == SSH_STATE_CLOSED)
2685 /* We're out of data. Go and get some more. */
2691 static int ssh_do_close(Ssh ssh, int notify_exit)
2694 struct ssh_channel *c;
2696 ssh->state = SSH_STATE_CLOSED;
2697 expire_timer_context(ssh);
2702 notify_remote_exit(ssh->frontend);
2707 * Now we must shut down any port- and X-forwarded channels going
2708 * through this connection.
2710 if (ssh->channels) {
2711 while (NULL != (c = index234(ssh->channels, 0))) {
2714 x11_close(c->u.x11.s);
2717 pfd_close(c->u.pfd.s);
2720 del234(ssh->channels, c); /* moving next one to index 0 */
2721 if (ssh->version == 2)
2722 bufchain_clear(&c->v.v2.outbuffer);
2727 * Go through port-forwardings, and close any associated
2728 * listening sockets.
2730 if (ssh->portfwds) {
2731 struct ssh_portfwd *pf;
2732 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2733 /* Dispose of any listening socket. */
2735 pfd_terminate(pf->local);
2736 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2744 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2745 const char *error_msg, int error_code)
2747 Ssh ssh = (Ssh) plug;
2748 char addrbuf[256], *msg;
2750 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2753 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2755 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2761 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2764 Ssh ssh = (Ssh) plug;
2765 int need_notify = ssh_do_close(ssh, FALSE);
2768 if (!ssh->close_expected)
2769 error_msg = "Server unexpectedly closed network connection";
2771 error_msg = "Server closed network connection";
2774 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2778 notify_remote_exit(ssh->frontend);
2781 logevent(error_msg);
2782 if (!ssh->close_expected || !ssh->clean_exit)
2783 connection_fatal(ssh->frontend, "%s", error_msg);
2787 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2789 Ssh ssh = (Ssh) plug;
2790 ssh_gotdata(ssh, (unsigned char *)data, len);
2791 if (ssh->state == SSH_STATE_CLOSED) {
2792 ssh_do_close(ssh, TRUE);
2798 static void ssh_sent(Plug plug, int bufsize)
2800 Ssh ssh = (Ssh) plug;
2802 * If the send backlog on the SSH socket itself clears, we
2803 * should unthrottle the whole world if it was throttled.
2805 if (bufsize < SSH_MAX_BACKLOG)
2806 ssh_throttle_all(ssh, 0, bufsize);
2810 * Connect to specified host and port.
2811 * Returns an error message, or NULL on success.
2812 * Also places the canonical host name into `realhost'. It must be
2813 * freed by the caller.
2815 static const char *connect_to_host(Ssh ssh, char *host, int port,
2816 char **realhost, int nodelay, int keepalive)
2818 static const struct plug_function_table fn_table = {
2829 ssh->savedhost = snewn(1 + strlen(host), char);
2830 strcpy(ssh->savedhost, host);
2833 port = 22; /* default ssh port */
2834 ssh->savedport = port;
2839 logeventf(ssh, "Looking up host \"%s\"%s", host,
2840 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2841 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2842 addr = name_lookup(host, port, realhost, &ssh->cfg,
2843 ssh->cfg.addressfamily);
2844 if ((err = sk_addr_error(addr)) != NULL) {
2852 ssh->fn = &fn_table;
2853 ssh->s = new_connection(addr, *realhost, port,
2854 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2855 if ((err = sk_socket_error(ssh->s)) != NULL) {
2857 notify_remote_exit(ssh->frontend);
2862 * If the SSH version number's fixed, set it now, and if it's SSH-2,
2863 * send the version string too.
2865 if (ssh->cfg.sshprot == 0)
2867 if (ssh->cfg.sshprot == 3) {
2869 ssh_send_verstring(ssh, NULL);
2876 * Throttle or unthrottle the SSH connection.
2878 static void ssh_throttle_conn(Ssh ssh, int adjust)
2880 int old_count = ssh->conn_throttle_count;
2881 ssh->conn_throttle_count += adjust;
2882 assert(ssh->conn_throttle_count >= 0);
2883 if (ssh->conn_throttle_count && !old_count) {
2884 ssh_set_frozen(ssh, 1);
2885 } else if (!ssh->conn_throttle_count && old_count) {
2886 ssh_set_frozen(ssh, 0);
2891 * Throttle or unthrottle _all_ local data streams (for when sends
2892 * on the SSH connection itself back up).
2894 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2897 struct ssh_channel *c;
2899 if (enable == ssh->throttled_all)
2901 ssh->throttled_all = enable;
2902 ssh->overall_bufsize = bufsize;
2905 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2907 case CHAN_MAINSESSION:
2909 * This is treated separately, outside the switch.
2913 x11_override_throttle(c->u.x11.s, enable);
2916 /* Agent channels require no buffer management. */
2919 pfd_override_throttle(c->u.pfd.s, enable);
2925 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2927 Ssh ssh = (Ssh) sshv;
2929 ssh->agent_response = reply;
2930 ssh->agent_response_len = replylen;
2932 if (ssh->version == 1)
2933 do_ssh1_login(ssh, NULL, -1, NULL);
2935 do_ssh2_authconn(ssh, NULL, -1, NULL);
2938 static void ssh_dialog_callback(void *sshv, int ret)
2940 Ssh ssh = (Ssh) sshv;
2942 ssh->user_response = ret;
2944 if (ssh->version == 1)
2945 do_ssh1_login(ssh, NULL, -1, NULL);
2947 do_ssh2_transport(ssh, NULL, -1, NULL);
2950 * This may have unfrozen the SSH connection, so do a
2953 ssh_process_queued_incoming_data(ssh);
2956 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2958 struct ssh_channel *c = (struct ssh_channel *)cv;
2960 void *sentreply = reply;
2963 /* Fake SSH_AGENT_FAILURE. */
2964 sentreply = "\0\0\0\1\5";
2967 if (ssh->version == 2) {
2968 ssh2_add_channel_data(c, sentreply, replylen);
2971 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2972 PKT_INT, c->remoteid,
2975 PKT_DATA, sentreply, replylen,
2984 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
2985 * non-NULL, otherwise just close the connection. `client_reason' == NULL
2986 * => log `wire_reason'.
2988 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
2989 int code, int clean_exit)
2993 client_reason = wire_reason;
2995 error = dupprintf("Disconnected: %s", client_reason);
2997 error = dupstr("Disconnected");
2999 if (ssh->version == 1) {
3000 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3002 } else if (ssh->version == 2) {
3003 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3004 ssh2_pkt_adduint32(pktout, code);
3005 ssh2_pkt_addstring(pktout, wire_reason);
3006 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3007 ssh2_pkt_send_noqueue(ssh, pktout);
3010 ssh->close_expected = TRUE;
3011 ssh->clean_exit = clean_exit;
3012 ssh_closing((Plug)ssh, error, 0, 0);
3017 * Handle the key exchange and user authentication phases.
3019 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3020 struct Packet *pktin)
3023 unsigned char cookie[8], *ptr;
3024 struct RSAKey servkey, hostkey;
3025 struct MD5Context md5c;
3026 struct do_ssh1_login_state {
3028 unsigned char *rsabuf, *keystr1, *keystr2;
3029 unsigned long supported_ciphers_mask, supported_auths_mask;
3030 int tried_publickey, tried_agent;
3031 int tis_auth_refused, ccard_auth_refused;
3032 unsigned char session_id[16];
3035 void *publickey_blob;
3036 int publickey_bloblen;
3037 char *publickey_comment;
3038 int publickey_encrypted;
3039 prompts_t *cur_prompt;
3042 unsigned char request[5], *response, *p;
3052 crState(do_ssh1_login_state);
3054 crBegin(ssh->do_ssh1_login_crstate);
3059 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3060 bombout(("Public key packet not received"));
3064 logevent("Received public keys");
3066 ptr = ssh_pkt_getdata(pktin, 8);
3068 bombout(("SSH-1 public key packet stopped before random cookie"));
3071 memcpy(cookie, ptr, 8);
3073 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3074 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3075 bombout(("Failed to read SSH-1 public keys from public key packet"));
3080 * Log the host key fingerprint.
3084 logevent("Host key fingerprint is:");
3085 strcpy(logmsg, " ");
3086 hostkey.comment = NULL;
3087 rsa_fingerprint(logmsg + strlen(logmsg),
3088 sizeof(logmsg) - strlen(logmsg), &hostkey);
3092 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3093 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3094 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3095 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3096 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3098 ssh->v1_local_protoflags =
3099 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3100 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3103 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3104 MD5Update(&md5c, s->keystr1, servkey.bytes);
3105 MD5Update(&md5c, cookie, 8);
3106 MD5Final(s->session_id, &md5c);
3108 for (i = 0; i < 32; i++)
3109 ssh->session_key[i] = random_byte();
3112 * Verify that the `bits' and `bytes' parameters match.
3114 if (hostkey.bits > hostkey.bytes * 8 ||
3115 servkey.bits > servkey.bytes * 8) {
3116 bombout(("SSH-1 public keys were badly formatted"));
3120 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3122 s->rsabuf = snewn(s->len, unsigned char);
3125 * Verify the host key.
3129 * First format the key into a string.
3131 int len = rsastr_len(&hostkey);
3132 char fingerprint[100];
3133 char *keystr = snewn(len, char);
3134 rsastr_fmt(keystr, &hostkey);
3135 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3137 ssh_set_frozen(ssh, 1);
3138 s->dlgret = verify_ssh_host_key(ssh->frontend,
3139 ssh->savedhost, ssh->savedport,
3140 "rsa", keystr, fingerprint,
3141 ssh_dialog_callback, ssh);
3143 if (s->dlgret < 0) {
3147 bombout(("Unexpected data from server while waiting"
3148 " for user host key response"));
3151 } while (pktin || inlen > 0);
3152 s->dlgret = ssh->user_response;
3154 ssh_set_frozen(ssh, 0);
3156 if (s->dlgret == 0) {
3157 ssh_disconnect(ssh, "User aborted at host key verification",
3163 for (i = 0; i < 32; i++) {
3164 s->rsabuf[i] = ssh->session_key[i];
3166 s->rsabuf[i] ^= s->session_id[i];
3169 if (hostkey.bytes > servkey.bytes) {
3170 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3172 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3174 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3176 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3179 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3183 logevent("Encrypted session key");
3186 int cipher_chosen = 0, warn = 0;
3187 char *cipher_string = NULL;
3189 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3190 int next_cipher = ssh->cfg.ssh_cipherlist[i];
3191 if (next_cipher == CIPHER_WARN) {
3192 /* If/when we choose a cipher, warn about it */
3194 } else if (next_cipher == CIPHER_AES) {
3195 /* XXX Probably don't need to mention this. */
3196 logevent("AES not supported in SSH-1, skipping");
3198 switch (next_cipher) {
3199 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3200 cipher_string = "3DES"; break;
3201 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3202 cipher_string = "Blowfish"; break;
3203 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3204 cipher_string = "single-DES"; break;
3206 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3210 if (!cipher_chosen) {
3211 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3212 bombout(("Server violates SSH-1 protocol by not "
3213 "supporting 3DES encryption"));
3215 /* shouldn't happen */
3216 bombout(("No supported ciphers found"));
3220 /* Warn about chosen cipher if necessary. */
3222 ssh_set_frozen(ssh, 1);
3223 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3224 ssh_dialog_callback, ssh);
3225 if (s->dlgret < 0) {
3229 bombout(("Unexpected data from server while waiting"
3230 " for user response"));
3233 } while (pktin || inlen > 0);
3234 s->dlgret = ssh->user_response;
3236 ssh_set_frozen(ssh, 0);
3237 if (s->dlgret == 0) {
3238 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3245 switch (s->cipher_type) {
3246 case SSH_CIPHER_3DES:
3247 logevent("Using 3DES encryption");
3249 case SSH_CIPHER_DES:
3250 logevent("Using single-DES encryption");
3252 case SSH_CIPHER_BLOWFISH:
3253 logevent("Using Blowfish encryption");
3257 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3258 PKT_CHAR, s->cipher_type,
3259 PKT_DATA, cookie, 8,
3260 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3261 PKT_DATA, s->rsabuf, s->len,
3262 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3264 logevent("Trying to enable encryption...");
3268 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3269 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3271 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3272 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3273 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3275 ssh->crcda_ctx = crcda_make_context();
3276 logevent("Installing CRC compensation attack detector");
3278 if (servkey.modulus) {
3279 sfree(servkey.modulus);
3280 servkey.modulus = NULL;
3282 if (servkey.exponent) {
3283 sfree(servkey.exponent);
3284 servkey.exponent = NULL;
3286 if (hostkey.modulus) {
3287 sfree(hostkey.modulus);
3288 hostkey.modulus = NULL;
3290 if (hostkey.exponent) {
3291 sfree(hostkey.exponent);
3292 hostkey.exponent = NULL;
3296 if (pktin->type != SSH1_SMSG_SUCCESS) {
3297 bombout(("Encryption not successfully enabled"));
3301 logevent("Successfully started encryption");
3303 fflush(stdout); /* FIXME eh? */
3305 if (!*ssh->cfg.username) {
3306 int ret; /* need not be kept over crReturn */
3307 s->cur_prompt = new_prompts(ssh->frontend);
3308 s->cur_prompt->to_server = TRUE;
3309 s->cur_prompt->name = dupstr("SSH login name");
3310 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
3311 lenof(s->username));
3312 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3315 crWaitUntil(!pktin);
3316 ret = get_userpass_input(s->cur_prompt, in, inlen);
3321 * Failed to get a username. Terminate.
3323 free_prompts(s->cur_prompt);
3324 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3327 memcpy(s->username, s->cur_prompt->prompts[0]->result,
3328 lenof(s->username));
3329 free_prompts(s->cur_prompt);
3331 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
3332 s->username[sizeof(s->username)-1] = '\0';
3335 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3337 char *userlog = dupprintf("Sent username \"%s\"", s->username);
3339 if (flags & FLAG_INTERACTIVE &&
3340 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3341 c_write_str(ssh, userlog);
3342 c_write_str(ssh, "\r\n");
3350 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3351 /* We must not attempt PK auth. Pretend we've already tried it. */
3352 s->tried_publickey = s->tried_agent = 1;
3354 s->tried_publickey = s->tried_agent = 0;
3356 s->tis_auth_refused = s->ccard_auth_refused = 0;
3358 * Load the public half of any configured keyfile for later use.
3360 if (!filename_is_null(ssh->cfg.keyfile)) {
3362 logeventf(ssh, "Reading private key file \"%.150s\"",
3363 filename_to_str(&ssh->cfg.keyfile));
3364 keytype = key_type(&ssh->cfg.keyfile);
3365 if (keytype == SSH_KEYTYPE_SSH1) {
3367 if (rsakey_pubblob(&ssh->cfg.keyfile,
3368 &s->publickey_blob, &s->publickey_bloblen,
3369 &s->publickey_comment, &error)) {
3370 s->publickey_encrypted = rsakey_encrypted(&ssh->cfg.keyfile,
3374 logeventf(ssh, "Unable to load private key (%s)", error);
3375 msgbuf = dupprintf("Unable to load private key file "
3376 "\"%.150s\" (%s)\r\n",
3377 filename_to_str(&ssh->cfg.keyfile),
3379 c_write_str(ssh, msgbuf);
3381 s->publickey_blob = NULL;
3385 logeventf(ssh, "Unable to use this key file (%s)",
3386 key_type_to_str(keytype));
3387 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3389 filename_to_str(&ssh->cfg.keyfile),
3390 key_type_to_str(keytype));
3391 c_write_str(ssh, msgbuf);
3393 s->publickey_blob = NULL;
3396 s->publickey_blob = NULL;
3398 while (pktin->type == SSH1_SMSG_FAILURE) {
3399 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3401 if (ssh->cfg.tryagent && agent_exists() && !s->tried_agent) {
3403 * Attempt RSA authentication using Pageant.
3409 logevent("Pageant is running. Requesting keys.");
3411 /* Request the keys held by the agent. */
3412 PUT_32BIT(s->request, 1);
3413 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3414 if (!agent_query(s->request, 5, &r, &s->responselen,
3415 ssh_agent_callback, ssh)) {
3419 bombout(("Unexpected data from server while waiting"
3420 " for agent response"));
3423 } while (pktin || inlen > 0);
3424 r = ssh->agent_response;
3425 s->responselen = ssh->agent_response_len;
3427 s->response = (unsigned char *) r;
3428 if (s->response && s->responselen >= 5 &&
3429 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3430 s->p = s->response + 5;
3431 s->nkeys = GET_32BIT(s->p);
3433 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3434 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3435 unsigned char *pkblob = s->p;
3439 do { /* do while (0) to make breaking easy */
3440 n = ssh1_read_bignum
3441 (s->p, s->responselen-(s->p-s->response),
3446 n = ssh1_read_bignum
3447 (s->p, s->responselen-(s->p-s->response),
3452 if (s->responselen - (s->p-s->response) < 4)
3454 s->commentlen = GET_32BIT(s->p);
3456 if (s->responselen - (s->p-s->response) <
3459 s->commentp = (char *)s->p;
3460 s->p += s->commentlen;
3464 logevent("Pageant key list packet was truncated");
3468 if (s->publickey_blob) {
3469 if (!memcmp(pkblob, s->publickey_blob,
3470 s->publickey_bloblen)) {
3471 logeventf(ssh, "Pageant key #%d matches "
3472 "configured key file", s->keyi);
3473 s->tried_publickey = 1;
3475 /* Skip non-configured key */
3478 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3479 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3480 PKT_BIGNUM, s->key.modulus, PKT_END);
3482 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3483 logevent("Key refused");
3486 logevent("Received RSA challenge");
3487 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3488 bombout(("Server's RSA challenge was badly formatted"));
3493 char *agentreq, *q, *ret;
3496 len = 1 + 4; /* message type, bit count */
3497 len += ssh1_bignum_length(s->key.exponent);
3498 len += ssh1_bignum_length(s->key.modulus);
3499 len += ssh1_bignum_length(s->challenge);
3500 len += 16; /* session id */
3501 len += 4; /* response format */
3502 agentreq = snewn(4 + len, char);
3503 PUT_32BIT(agentreq, len);
3505 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3506 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3508 q += ssh1_write_bignum(q, s->key.exponent);
3509 q += ssh1_write_bignum(q, s->key.modulus);
3510 q += ssh1_write_bignum(q, s->challenge);
3511 memcpy(q, s->session_id, 16);
3513 PUT_32BIT(q, 1); /* response format */
3514 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3515 ssh_agent_callback, ssh)) {
3520 bombout(("Unexpected data from server"
3521 " while waiting for agent"
3525 } while (pktin || inlen > 0);
3526 vret = ssh->agent_response;
3527 retlen = ssh->agent_response_len;
3532 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3533 logevent("Sending Pageant's response");
3534 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3535 PKT_DATA, ret + 5, 16,
3539 if (pktin->type == SSH1_SMSG_SUCCESS) {
3541 ("Pageant's response accepted");
3542 if (flags & FLAG_VERBOSE) {
3543 c_write_str(ssh, "Authenticated using"
3545 c_write(ssh, s->commentp,
3547 c_write_str(ssh, "\" from agent\r\n");
3552 ("Pageant's response not accepted");
3555 ("Pageant failed to answer challenge");
3559 logevent("No reply received from Pageant");
3562 freebn(s->key.exponent);
3563 freebn(s->key.modulus);
3564 freebn(s->challenge);
3569 if (s->publickey_blob && !s->tried_publickey)
3570 logevent("Configured key file not in Pageant");
3575 if (s->publickey_blob && !s->tried_publickey) {
3577 * Try public key authentication with the specified
3580 int got_passphrase; /* need not be kept over crReturn */
3581 if (flags & FLAG_VERBOSE)
3582 c_write_str(ssh, "Trying public key authentication.\r\n");
3583 logeventf(ssh, "Trying public key \"%s\"",
3584 filename_to_str(&ssh->cfg.keyfile));
3585 s->tried_publickey = 1;
3586 got_passphrase = FALSE;
3587 while (!got_passphrase) {
3589 * Get a passphrase, if necessary.
3591 char *passphrase = NULL; /* only written after crReturn */
3593 if (!s->publickey_encrypted) {
3594 if (flags & FLAG_VERBOSE)
3595 c_write_str(ssh, "No passphrase required.\r\n");
3598 int ret; /* need not be kept over crReturn */
3599 s->cur_prompt = new_prompts(ssh->frontend);
3600 s->cur_prompt->to_server = FALSE;
3601 s->cur_prompt->name = dupstr("SSH key passphrase");
3602 add_prompt(s->cur_prompt,
3603 dupprintf("Passphrase for key \"%.100s\": ",
3604 s->publickey_comment),
3605 FALSE, SSH_MAX_PASSWORD_LEN);
3606 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3609 crWaitUntil(!pktin);
3610 ret = get_userpass_input(s->cur_prompt, in, inlen);
3614 /* Failed to get a passphrase. Terminate. */
3615 free_prompts(s->cur_prompt);
3616 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3620 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3621 free_prompts(s->cur_prompt);
3624 * Try decrypting key with passphrase.
3626 ret = loadrsakey(&ssh->cfg.keyfile, &s->key, passphrase,
3629 memset(passphrase, 0, strlen(passphrase));
3633 /* Correct passphrase. */
3634 got_passphrase = TRUE;
3635 } else if (ret == 0) {
3636 c_write_str(ssh, "Couldn't load private key from ");
3637 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3638 c_write_str(ssh, " (");
3639 c_write_str(ssh, error);
3640 c_write_str(ssh, ").\r\n");
3641 got_passphrase = FALSE;
3642 break; /* go and try something else */
3643 } else if (ret == -1) {
3644 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3645 got_passphrase = FALSE;
3648 assert(0 && "unexpected return from loadrsakey()");
3649 got_passphrase = FALSE; /* placate optimisers */
3653 if (got_passphrase) {
3656 * Send a public key attempt.
3658 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3659 PKT_BIGNUM, s->key.modulus, PKT_END);
3662 if (pktin->type == SSH1_SMSG_FAILURE) {
3663 c_write_str(ssh, "Server refused our public key.\r\n");
3664 continue; /* go and try something else */
3666 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3667 bombout(("Bizarre response to offer of public key"));
3673 unsigned char buffer[32];
3674 Bignum challenge, response;
3676 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3677 bombout(("Server's RSA challenge was badly formatted"));
3680 response = rsadecrypt(challenge, &s->key);
3681 freebn(s->key.private_exponent);/* burn the evidence */
3683 for (i = 0; i < 32; i++) {
3684 buffer[i] = bignum_byte(response, 31 - i);
3688 MD5Update(&md5c, buffer, 32);
3689 MD5Update(&md5c, s->session_id, 16);
3690 MD5Final(buffer, &md5c);
3692 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3693 PKT_DATA, buffer, 16, PKT_END);
3700 if (pktin->type == SSH1_SMSG_FAILURE) {
3701 if (flags & FLAG_VERBOSE)
3702 c_write_str(ssh, "Failed to authenticate with"
3703 " our public key.\r\n");
3704 continue; /* go and try something else */
3705 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3706 bombout(("Bizarre response to RSA authentication response"));
3710 break; /* we're through! */
3716 * Otherwise, try various forms of password-like authentication.
3718 s->cur_prompt = new_prompts(ssh->frontend);
3720 if (ssh->cfg.try_tis_auth &&
3721 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3722 !s->tis_auth_refused) {
3723 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3724 logevent("Requested TIS authentication");
3725 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3727 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3728 logevent("TIS authentication declined");
3729 if (flags & FLAG_INTERACTIVE)
3730 c_write_str(ssh, "TIS authentication refused.\r\n");
3731 s->tis_auth_refused = 1;
3736 char *instr_suf, *prompt;
3738 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3740 bombout(("TIS challenge packet was badly formed"));
3743 logevent("Received TIS challenge");
3744 s->cur_prompt->to_server = TRUE;
3745 s->cur_prompt->name = dupstr("SSH TIS authentication");
3746 /* Prompt heuristic comes from OpenSSH */
3747 if (memchr(challenge, '\n', challengelen)) {
3748 instr_suf = dupstr("");
3749 prompt = dupprintf("%.*s", challengelen, challenge);
3751 instr_suf = dupprintf("%.*s", challengelen, challenge);
3752 prompt = dupstr("Response: ");
3754 s->cur_prompt->instruction =
3755 dupprintf("Using TIS authentication.%s%s",
3756 (*instr_suf) ? "\n" : "",
3758 s->cur_prompt->instr_reqd = TRUE;
3759 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3763 if (ssh->cfg.try_tis_auth &&
3764 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3765 !s->ccard_auth_refused) {
3766 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3767 logevent("Requested CryptoCard authentication");
3768 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3770 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3771 logevent("CryptoCard authentication declined");
3772 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3773 s->ccard_auth_refused = 1;
3778 char *instr_suf, *prompt;
3780 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3782 bombout(("CryptoCard challenge packet was badly formed"));
3785 logevent("Received CryptoCard challenge");
3786 s->cur_prompt->to_server = TRUE;
3787 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3788 s->cur_prompt->name_reqd = FALSE;
3789 /* Prompt heuristic comes from OpenSSH */
3790 if (memchr(challenge, '\n', challengelen)) {
3791 instr_suf = dupstr("");
3792 prompt = dupprintf("%.*s", challengelen, challenge);
3794 instr_suf = dupprintf("%.*s", challengelen, challenge);
3795 prompt = dupstr("Response: ");
3797 s->cur_prompt->instruction =
3798 dupprintf("Using CryptoCard authentication.%s%s",
3799 (*instr_suf) ? "\n" : "",
3801 s->cur_prompt->instr_reqd = TRUE;
3802 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3806 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3807 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
3808 bombout(("No supported authentication methods available"));
3811 s->cur_prompt->to_server = TRUE;
3812 s->cur_prompt->name = dupstr("SSH password");
3813 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
3814 s->username, ssh->savedhost),
3815 FALSE, SSH_MAX_PASSWORD_LEN);
3819 * Show password prompt, having first obtained it via a TIS
3820 * or CryptoCard exchange if we're doing TIS or CryptoCard
3824 int ret; /* need not be kept over crReturn */
3825 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3828 crWaitUntil(!pktin);
3829 ret = get_userpass_input(s->cur_prompt, in, inlen);
3834 * Failed to get a password (for example
3835 * because one was supplied on the command line
3836 * which has already failed to work). Terminate.
3838 free_prompts(s->cur_prompt);
3839 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
3844 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3846 * Defence against traffic analysis: we send a
3847 * whole bunch of packets containing strings of
3848 * different lengths. One of these strings is the
3849 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3850 * The others are all random data in
3851 * SSH1_MSG_IGNORE packets. This way a passive
3852 * listener can't tell which is the password, and
3853 * hence can't deduce the password length.
3855 * Anybody with a password length greater than 16
3856 * bytes is going to have enough entropy in their
3857 * password that a listener won't find it _that_
3858 * much help to know how long it is. So what we'll
3861 * - if password length < 16, we send 15 packets
3862 * containing string lengths 1 through 15
3864 * - otherwise, we let N be the nearest multiple
3865 * of 8 below the password length, and send 8
3866 * packets containing string lengths N through
3867 * N+7. This won't obscure the order of
3868 * magnitude of the password length, but it will
3869 * introduce a bit of extra uncertainty.
3871 * A few servers can't deal with SSH1_MSG_IGNORE, at
3872 * least in this context. For these servers, we need
3873 * an alternative defence. We make use of the fact
3874 * that the password is interpreted as a C string:
3875 * so we can append a NUL, then some random data.
3877 * A few servers can deal with neither SSH1_MSG_IGNORE
3878 * here _nor_ a padded password string.
3879 * For these servers we are left with no defences
3880 * against password length sniffing.
3882 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
3883 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3885 * The server can deal with SSH1_MSG_IGNORE, so
3886 * we can use the primary defence.
3888 int bottom, top, pwlen, i;
3891 pwlen = strlen(s->cur_prompt->prompts[0]->result);
3893 bottom = 0; /* zero length passwords are OK! :-) */
3896 bottom = pwlen & ~7;
3900 assert(pwlen >= bottom && pwlen <= top);
3902 randomstr = snewn(top + 1, char);
3904 for (i = bottom; i <= top; i++) {
3906 defer_packet(ssh, s->pwpkt_type,
3907 PKTT_PASSWORD, PKT_STR,
3908 s->cur_prompt->prompts[0]->result,
3909 PKTT_OTHER, PKT_END);
3911 for (j = 0; j < i; j++) {
3913 randomstr[j] = random_byte();
3914 } while (randomstr[j] == '\0');
3916 randomstr[i] = '\0';
3917 defer_packet(ssh, SSH1_MSG_IGNORE,
3918 PKT_STR, randomstr, PKT_END);
3921 logevent("Sending password with camouflage packets");
3922 ssh_pkt_defersend(ssh);
3925 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3927 * The server can't deal with SSH1_MSG_IGNORE
3928 * but can deal with padded passwords, so we
3929 * can use the secondary defence.
3935 len = strlen(s->cur_prompt->prompts[0]->result);
3936 if (len < sizeof(string)) {
3938 strcpy(string, s->cur_prompt->prompts[0]->result);
3939 len++; /* cover the zero byte */
3940 while (len < sizeof(string)) {
3941 string[len++] = (char) random_byte();
3944 ss = s->cur_prompt->prompts[0]->result;
3946 logevent("Sending length-padded password");
3947 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3948 PKT_INT, len, PKT_DATA, ss, len,
3949 PKTT_OTHER, PKT_END);
3952 * The server is believed unable to cope with
3953 * any of our password camouflage methods.
3956 len = strlen(s->cur_prompt->prompts[0]->result);
3957 logevent("Sending unpadded password");
3958 send_packet(ssh, s->pwpkt_type,
3959 PKTT_PASSWORD, PKT_INT, len,
3960 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
3961 PKTT_OTHER, PKT_END);
3964 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3965 PKT_STR, s->cur_prompt->prompts[0]->result,
3966 PKTT_OTHER, PKT_END);
3968 logevent("Sent password");
3969 free_prompts(s->cur_prompt);
3971 if (pktin->type == SSH1_SMSG_FAILURE) {
3972 if (flags & FLAG_VERBOSE)
3973 c_write_str(ssh, "Access denied\r\n");
3974 logevent("Authentication refused");
3975 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3976 bombout(("Strange packet received, type %d", pktin->type));
3982 if (s->publickey_blob) {
3983 sfree(s->publickey_blob);
3984 sfree(s->publickey_comment);
3987 logevent("Authentication successful");
3992 void sshfwd_close(struct ssh_channel *c)
3996 if (ssh->state == SSH_STATE_CLOSED)
3999 if (c && !c->closes) {
4001 * If halfopen is true, we have sent
4002 * CHANNEL_OPEN for this channel, but it hasn't even been
4003 * acknowledged by the server. So we must set a close flag
4004 * on it now, and then when the server acks the channel
4005 * open, we can close it then.
4008 if (ssh->version == 1) {
4009 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4012 struct Packet *pktout;
4013 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4014 ssh2_pkt_adduint32(pktout, c->remoteid);
4015 ssh2_pkt_send(ssh, pktout);
4018 c->closes = 1; /* sent MSG_CLOSE */
4019 if (c->type == CHAN_X11) {
4021 logevent("Forwarded X11 connection terminated");
4022 } else if (c->type == CHAN_SOCKDATA ||
4023 c->type == CHAN_SOCKDATA_DORMANT) {
4025 logevent("Forwarded port closed");
4030 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4034 if (ssh->state == SSH_STATE_CLOSED)
4037 if (ssh->version == 1) {
4038 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4039 PKT_INT, c->remoteid,
4040 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4041 PKTT_OTHER, PKT_END);
4043 * In SSH-1 we can return 0 here - implying that forwarded
4044 * connections are never individually throttled - because
4045 * the only circumstance that can cause throttling will be
4046 * the whole SSH connection backing up, in which case
4047 * _everything_ will be throttled as a whole.
4051 ssh2_add_channel_data(c, buf, len);
4052 return ssh2_try_send(c);
4056 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4061 if (ssh->state == SSH_STATE_CLOSED)
4064 if (ssh->version == 1) {
4065 buflimit = SSH1_BUFFER_LIMIT;
4067 buflimit = c->v.v2.locmaxwin;
4068 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4070 if (c->throttling_conn && bufsize <= buflimit) {
4071 c->throttling_conn = 0;
4072 ssh_throttle_conn(ssh, -1);
4076 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4078 struct queued_handler *qh = ssh->qhead;
4082 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4085 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4086 ssh->packet_dispatch[qh->msg1] = NULL;
4089 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4090 ssh->packet_dispatch[qh->msg2] = NULL;
4094 ssh->qhead = qh->next;
4096 if (ssh->qhead->msg1 > 0) {
4097 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4098 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4100 if (ssh->qhead->msg2 > 0) {
4101 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4102 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4105 ssh->qhead = ssh->qtail = NULL;
4106 ssh->packet_dispatch[pktin->type] = NULL;
4109 qh->handler(ssh, pktin, qh->ctx);
4114 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4115 chandler_fn_t handler, void *ctx)
4117 struct queued_handler *qh;
4119 qh = snew(struct queued_handler);
4122 qh->handler = handler;
4126 if (ssh->qtail == NULL) {
4130 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4131 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4134 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4135 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4138 ssh->qtail->next = qh;
4143 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4145 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4147 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4148 SSH2_MSG_REQUEST_SUCCESS)) {
4149 logeventf(ssh, "Remote port forwarding from %s enabled",
4152 logeventf(ssh, "Remote port forwarding from %s refused",
4155 rpf = del234(ssh->rportfwds, pf);
4161 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
4163 const char *portfwd_strptr = cfg->portfwd;
4164 struct ssh_portfwd *epf;
4167 if (!ssh->portfwds) {
4168 ssh->portfwds = newtree234(ssh_portcmp);
4171 * Go through the existing port forwardings and tag them
4172 * with status==DESTROY. Any that we want to keep will be
4173 * re-enabled (status==KEEP) as we go through the
4174 * configuration and find out which bits are the same as
4177 struct ssh_portfwd *epf;
4179 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4180 epf->status = DESTROY;
4183 while (*portfwd_strptr) {
4184 char address_family, type;
4185 int sport,dport,sserv,dserv;
4186 char sports[256], dports[256], saddr[256], host[256];
4189 address_family = 'A';
4191 if (*portfwd_strptr == 'A' ||
4192 *portfwd_strptr == '4' ||
4193 *portfwd_strptr == '6')
4194 address_family = *portfwd_strptr++;
4195 if (*portfwd_strptr == 'L' ||
4196 *portfwd_strptr == 'R' ||
4197 *portfwd_strptr == 'D')
4198 type = *portfwd_strptr++;
4203 while (*portfwd_strptr && *portfwd_strptr != '\t') {
4204 if (*portfwd_strptr == ':') {
4206 * We've seen a colon in the middle of the
4207 * source port number. This means that
4208 * everything we've seen until now is the
4209 * source _address_, so we'll move it into
4210 * saddr and start sports from the beginning
4215 if (ssh->version == 1 && type == 'R') {
4216 logeventf(ssh, "SSH-1 cannot handle remote source address "
4217 "spec \"%s\"; ignoring", sports);
4219 strcpy(saddr, sports);
4222 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
4226 if (*portfwd_strptr == '\t')
4229 while (*portfwd_strptr && *portfwd_strptr != ':') {
4230 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
4233 if (*portfwd_strptr == ':')
4236 while (*portfwd_strptr) {
4237 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
4241 dport = atoi(dports);
4245 dport = net_service_lookup(dports);
4247 logeventf(ssh, "Service lookup failed for destination"
4248 " port \"%s\"", dports);
4252 while (*portfwd_strptr) portfwd_strptr++;
4256 portfwd_strptr++; /* eat the NUL and move to next one */
4258 sport = atoi(sports);
4262 sport = net_service_lookup(sports);
4264 logeventf(ssh, "Service lookup failed for source"
4265 " port \"%s\"", sports);
4268 if (sport && dport) {
4269 /* Set up a description of the source port. */
4270 struct ssh_portfwd *pfrec, *epfrec;
4272 pfrec = snew(struct ssh_portfwd);
4274 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
4275 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4276 pfrec->sport = sport;
4277 pfrec->daddr = *host ? dupstr(host) : NULL;
4278 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4279 pfrec->dport = dport;
4280 pfrec->local = NULL;
4281 pfrec->remote = NULL;
4282 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4283 address_family == '6' ? ADDRTYPE_IPV6 :
4286 epfrec = add234(ssh->portfwds, pfrec);
4287 if (epfrec != pfrec) {
4289 * We already have a port forwarding with precisely
4290 * these parameters. Hence, no need to do anything;
4291 * simply tag the existing one as KEEP.
4293 epfrec->status = KEEP;
4294 free_portfwd(pfrec);
4296 pfrec->status = CREATE;
4302 * Now go through and destroy any port forwardings which were
4305 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4306 if (epf->status == DESTROY) {
4309 message = dupprintf("%s port forwarding from %s%s%d",
4310 epf->type == 'L' ? "local" :
4311 epf->type == 'R' ? "remote" : "dynamic",
4312 epf->saddr ? epf->saddr : "",
4313 epf->saddr ? ":" : "",
4316 if (epf->type != 'D') {
4317 char *msg2 = dupprintf("%s to %s:%d", message,
4318 epf->daddr, epf->dport);
4323 logeventf(ssh, "Cancelling %s", message);
4327 struct ssh_rportfwd *rpf = epf->remote;
4328 struct Packet *pktout;
4331 * Cancel the port forwarding at the server
4334 if (ssh->version == 1) {
4336 * We cannot cancel listening ports on the
4337 * server side in SSH-1! There's no message
4338 * to support it. Instead, we simply remove
4339 * the rportfwd record from the local end
4340 * so that any connections the server tries
4341 * to make on it are rejected.
4344 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4345 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4346 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4348 ssh2_pkt_addstring(pktout, epf->saddr);
4349 } else if (ssh->cfg.rport_acceptall) {
4350 /* XXX: ssh->cfg.rport_acceptall may not represent
4351 * what was used to open the original connection,
4352 * since it's reconfigurable. */
4353 ssh2_pkt_addstring(pktout, "0.0.0.0");
4355 ssh2_pkt_addstring(pktout, "127.0.0.1");
4357 ssh2_pkt_adduint32(pktout, epf->sport);
4358 ssh2_pkt_send(ssh, pktout);
4361 del234(ssh->rportfwds, rpf);
4363 } else if (epf->local) {
4364 pfd_terminate(epf->local);
4367 delpos234(ssh->portfwds, i);
4369 i--; /* so we don't skip one in the list */
4373 * And finally, set up any new port forwardings (status==CREATE).
4375 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4376 if (epf->status == CREATE) {
4377 char *sportdesc, *dportdesc;
4378 sportdesc = dupprintf("%s%s%s%s%d%s",
4379 epf->saddr ? epf->saddr : "",
4380 epf->saddr ? ":" : "",
4381 epf->sserv ? epf->sserv : "",
4382 epf->sserv ? "(" : "",
4384 epf->sserv ? ")" : "");
4385 if (epf->type == 'D') {
4388 dportdesc = dupprintf("%s:%s%s%d%s",
4390 epf->dserv ? epf->dserv : "",
4391 epf->dserv ? "(" : "",
4393 epf->dserv ? ")" : "");
4396 if (epf->type == 'L') {
4397 const char *err = pfd_addforward(epf->daddr, epf->dport,
4398 epf->saddr, epf->sport,
4401 epf->addressfamily);
4403 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4404 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4405 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4406 sportdesc, dportdesc,
4407 err ? " failed: " : "", err ? err : "");
4408 } else if (epf->type == 'D') {
4409 const char *err = pfd_addforward(NULL, -1,
4410 epf->saddr, epf->sport,
4413 epf->addressfamily);
4415 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4416 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4417 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4419 err ? " failed: " : "", err ? err : "");
4421 struct ssh_rportfwd *pf;
4424 * Ensure the remote port forwardings tree exists.
4426 if (!ssh->rportfwds) {
4427 if (ssh->version == 1)
4428 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4430 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4433 pf = snew(struct ssh_rportfwd);
4434 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4435 pf->dhost[lenof(pf->dhost)-1] = '\0';
4436 pf->dport = epf->dport;
4437 pf->sport = epf->sport;
4438 if (add234(ssh->rportfwds, pf) != pf) {
4439 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4440 epf->daddr, epf->dport);
4443 logeventf(ssh, "Requesting remote port %s"
4444 " forward to %s", sportdesc, dportdesc);
4446 pf->sportdesc = sportdesc;
4451 if (ssh->version == 1) {
4452 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4453 PKT_INT, epf->sport,
4454 PKT_STR, epf->daddr,
4455 PKT_INT, epf->dport,
4457 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4459 ssh_rportfwd_succfail, pf);
4461 struct Packet *pktout;
4462 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4463 ssh2_pkt_addstring(pktout, "tcpip-forward");
4464 ssh2_pkt_addbool(pktout, 1);/* want reply */
4466 ssh2_pkt_addstring(pktout, epf->saddr);
4467 } else if (cfg->rport_acceptall) {
4468 ssh2_pkt_addstring(pktout, "0.0.0.0");
4470 ssh2_pkt_addstring(pktout, "127.0.0.1");
4472 ssh2_pkt_adduint32(pktout, epf->sport);
4473 ssh2_pkt_send(ssh, pktout);
4475 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4476 SSH2_MSG_REQUEST_FAILURE,
4477 ssh_rportfwd_succfail, pf);
4486 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4489 int stringlen, bufsize;
4491 ssh_pkt_getstring(pktin, &string, &stringlen);
4492 if (string == NULL) {
4493 bombout(("Incoming terminal data packet was badly formed"));
4497 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4499 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4500 ssh->v1_stdout_throttling = 1;
4501 ssh_throttle_conn(ssh, +1);
4505 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4507 /* Remote side is trying to open a channel to talk to our
4508 * X-Server. Give them back a local channel number. */
4509 struct ssh_channel *c;
4510 int remoteid = ssh_pkt_getuint32(pktin);
4512 logevent("Received X11 connect request");
4513 /* Refuse if X11 forwarding is disabled. */
4514 if (!ssh->X11_fwd_enabled) {
4515 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4516 PKT_INT, remoteid, PKT_END);
4517 logevent("Rejected X11 connect request");
4519 c = snew(struct ssh_channel);
4522 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
4523 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
4524 logevent("Opening X11 forward connection failed");
4526 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4527 PKT_INT, remoteid, PKT_END);
4530 ("Opening X11 forward connection succeeded");
4531 c->remoteid = remoteid;
4532 c->halfopen = FALSE;
4533 c->localid = alloc_channel_id(ssh);
4535 c->throttling_conn = 0;
4536 c->type = CHAN_X11; /* identify channel type */
4537 add234(ssh->channels, c);
4538 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4539 PKT_INT, c->remoteid, PKT_INT,
4540 c->localid, PKT_END);
4541 logevent("Opened X11 forward channel");
4546 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4548 /* Remote side is trying to open a channel to talk to our
4549 * agent. Give them back a local channel number. */
4550 struct ssh_channel *c;
4551 int remoteid = ssh_pkt_getuint32(pktin);
4553 /* Refuse if agent forwarding is disabled. */
4554 if (!ssh->agentfwd_enabled) {
4555 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4556 PKT_INT, remoteid, PKT_END);
4558 c = snew(struct ssh_channel);
4560 c->remoteid = remoteid;
4561 c->halfopen = FALSE;
4562 c->localid = alloc_channel_id(ssh);
4564 c->throttling_conn = 0;
4565 c->type = CHAN_AGENT; /* identify channel type */
4566 c->u.a.lensofar = 0;
4567 add234(ssh->channels, c);
4568 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4569 PKT_INT, c->remoteid, PKT_INT, c->localid,
4574 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4576 /* Remote side is trying to open a channel to talk to a
4577 * forwarded port. Give them back a local channel number. */
4578 struct ssh_channel *c;
4579 struct ssh_rportfwd pf, *pfp;
4584 c = snew(struct ssh_channel);
4587 remoteid = ssh_pkt_getuint32(pktin);
4588 ssh_pkt_getstring(pktin, &host, &hostsize);
4589 port = ssh_pkt_getuint32(pktin);
4591 if (hostsize >= lenof(pf.dhost))
4592 hostsize = lenof(pf.dhost)-1;
4593 memcpy(pf.dhost, host, hostsize);
4594 pf.dhost[hostsize] = '\0';
4596 pfp = find234(ssh->rportfwds, &pf, NULL);
4599 logeventf(ssh, "Rejected remote port open request for %s:%d",
4601 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4602 PKT_INT, remoteid, PKT_END);
4604 logeventf(ssh, "Received remote port open request for %s:%d",
4606 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4607 c, &ssh->cfg, pfp->pfrec->addressfamily);
4609 logeventf(ssh, "Port open failed: %s", e);
4611 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4612 PKT_INT, remoteid, PKT_END);
4614 c->remoteid = remoteid;
4615 c->halfopen = FALSE;
4616 c->localid = alloc_channel_id(ssh);
4618 c->throttling_conn = 0;
4619 c->type = CHAN_SOCKDATA; /* identify channel type */
4620 add234(ssh->channels, c);
4621 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4622 PKT_INT, c->remoteid, PKT_INT,
4623 c->localid, PKT_END);
4624 logevent("Forwarded port opened successfully");
4629 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4631 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4632 unsigned int localid = ssh_pkt_getuint32(pktin);
4633 struct ssh_channel *c;
4635 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4636 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4637 c->remoteid = localid;
4638 c->halfopen = FALSE;
4639 c->type = CHAN_SOCKDATA;
4640 c->throttling_conn = 0;
4641 pfd_confirm(c->u.pfd.s);
4644 if (c && c->closes) {
4646 * We have a pending close on this channel,
4647 * which we decided on before the server acked
4648 * the channel open. So now we know the
4649 * remoteid, we can close it again.
4651 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4652 PKT_INT, c->remoteid, PKT_END);
4656 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4658 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4659 struct ssh_channel *c;
4661 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4662 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4663 logevent("Forwarded connection refused by server");
4664 pfd_close(c->u.pfd.s);
4665 del234(ssh->channels, c);
4670 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4672 /* Remote side closes a channel. */
4673 unsigned i = ssh_pkt_getuint32(pktin);
4674 struct ssh_channel *c;
4675 c = find234(ssh->channels, &i, ssh_channelfind);
4676 if (c && !c->halfopen) {
4679 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4681 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4682 logevent("Forwarded X11 connection terminated");
4683 assert(c->u.x11.s != NULL);
4684 x11_close(c->u.x11.s);
4687 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4688 logevent("Forwarded port closed");
4689 assert(c->u.pfd.s != NULL);
4690 pfd_close(c->u.pfd.s);
4694 c->closes |= (closetype << 2); /* seen this message */
4695 if (!(c->closes & closetype)) {
4696 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4698 c->closes |= closetype; /* sent it too */
4701 if (c->closes == 15) {
4702 del234(ssh->channels, c);
4706 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4707 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4708 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4713 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4715 /* Data sent down one of our channels. */
4716 int i = ssh_pkt_getuint32(pktin);
4719 struct ssh_channel *c;
4721 ssh_pkt_getstring(pktin, &p, &len);
4723 c = find234(ssh->channels, &i, ssh_channelfind);
4728 bufsize = x11_send(c->u.x11.s, p, len);
4731 bufsize = pfd_send(c->u.pfd.s, p, len);
4734 /* Data for an agent message. Buffer it. */
4736 if (c->u.a.lensofar < 4) {
4737 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4738 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4742 c->u.a.lensofar += l;
4744 if (c->u.a.lensofar == 4) {
4746 4 + GET_32BIT(c->u.a.msglen);
4747 c->u.a.message = snewn(c->u.a.totallen,
4749 memcpy(c->u.a.message, c->u.a.msglen, 4);
4751 if (c->u.a.lensofar >= 4 && len > 0) {
4753 min(c->u.a.totallen - c->u.a.lensofar,
4755 memcpy(c->u.a.message + c->u.a.lensofar, p,
4759 c->u.a.lensofar += l;
4761 if (c->u.a.lensofar == c->u.a.totallen) {
4764 if (agent_query(c->u.a.message,
4767 ssh_agentf_callback, c))
4768 ssh_agentf_callback(c, reply, replylen);
4769 sfree(c->u.a.message);
4770 c->u.a.lensofar = 0;
4773 bufsize = 0; /* agent channels never back up */
4776 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
4777 c->throttling_conn = 1;
4778 ssh_throttle_conn(ssh, +1);
4783 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4785 ssh->exitcode = ssh_pkt_getuint32(pktin);
4786 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4787 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4789 * In case `helpful' firewalls or proxies tack
4790 * extra human-readable text on the end of the
4791 * session which we might mistake for another
4792 * encrypted packet, we close the session once
4793 * we've sent EXIT_CONFIRMATION.
4795 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
4798 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4799 static void ssh1_send_ttymode(void *data, char *mode, char *val)
4801 struct Packet *pktout = (struct Packet *)data;
4803 unsigned int arg = 0;
4804 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
4805 if (i == lenof(ssh_ttymodes)) return;
4806 switch (ssh_ttymodes[i].type) {
4808 arg = ssh_tty_parse_specchar(val);
4811 arg = ssh_tty_parse_boolean(val);
4814 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
4815 ssh2_pkt_addbyte(pktout, arg);
4819 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4820 struct Packet *pktin)
4822 crBegin(ssh->do_ssh1_connection_crstate);
4824 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4825 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4826 ssh1_smsg_stdout_stderr_data;
4828 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4829 ssh1_msg_channel_open_confirmation;
4830 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4831 ssh1_msg_channel_open_failure;
4832 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4833 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4834 ssh1_msg_channel_close;
4835 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4836 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4838 if (ssh->cfg.agentfwd && agent_exists()) {
4839 logevent("Requesting agent forwarding");
4840 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4844 if (pktin->type != SSH1_SMSG_SUCCESS
4845 && pktin->type != SSH1_SMSG_FAILURE) {
4846 bombout(("Protocol confusion"));
4848 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4849 logevent("Agent forwarding refused");
4851 logevent("Agent forwarding enabled");
4852 ssh->agentfwd_enabled = TRUE;
4853 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4857 if (ssh->cfg.x11_forward) {
4858 char proto[20], data[64];
4859 logevent("Requesting X11 forwarding");
4860 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
4861 data, sizeof(data), ssh->cfg.x11_auth);
4862 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
4864 * Note that while we blank the X authentication data here, we don't
4865 * take any special action to blank the start of an X11 channel,
4866 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
4867 * without having session blanking enabled is likely to leak your
4868 * cookie into the log.
4870 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4871 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4873 PKTT_PASSWORD, PKT_STR, data, PKTT_OTHER,
4874 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
4877 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4879 PKTT_PASSWORD, PKT_STR, data, PKTT_OTHER, PKT_END);
4884 if (pktin->type != SSH1_SMSG_SUCCESS
4885 && pktin->type != SSH1_SMSG_FAILURE) {
4886 bombout(("Protocol confusion"));
4888 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4889 logevent("X11 forwarding refused");
4891 logevent("X11 forwarding enabled");
4892 ssh->X11_fwd_enabled = TRUE;
4893 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4897 ssh_setup_portfwd(ssh, &ssh->cfg);
4898 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4900 if (!ssh->cfg.nopty) {
4902 /* Unpick the terminal-speed string. */
4903 /* XXX perhaps we should allow no speeds to be sent. */
4904 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4905 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4906 /* Send the pty request. */
4907 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
4908 ssh_pkt_addstring(pkt, ssh->cfg.termtype);
4909 ssh_pkt_adduint32(pkt, ssh->term_height);
4910 ssh_pkt_adduint32(pkt, ssh->term_width);
4911 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
4912 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
4913 parse_ttymodes(ssh, ssh->cfg.ttymodes,
4914 ssh1_send_ttymode, (void *)pkt);
4915 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
4916 ssh_pkt_adduint32(pkt, ssh->ispeed);
4917 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
4918 ssh_pkt_adduint32(pkt, ssh->ospeed);
4919 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
4921 ssh->state = SSH_STATE_INTERMED;
4925 if (pktin->type != SSH1_SMSG_SUCCESS
4926 && pktin->type != SSH1_SMSG_FAILURE) {
4927 bombout(("Protocol confusion"));
4929 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4930 c_write_str(ssh, "Server refused to allocate pty\r\n");
4931 ssh->editing = ssh->echoing = 1;
4933 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4934 ssh->ospeed, ssh->ispeed);
4936 ssh->editing = ssh->echoing = 1;
4939 if (ssh->cfg.compression) {
4940 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4944 if (pktin->type != SSH1_SMSG_SUCCESS
4945 && pktin->type != SSH1_SMSG_FAILURE) {
4946 bombout(("Protocol confusion"));
4948 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4949 c_write_str(ssh, "Server refused to compress\r\n");
4951 logevent("Started compression");
4952 ssh->v1_compressing = TRUE;
4953 ssh->cs_comp_ctx = zlib_compress_init();
4954 logevent("Initialised zlib (RFC1950) compression");
4955 ssh->sc_comp_ctx = zlib_decompress_init();
4956 logevent("Initialised zlib (RFC1950) decompression");
4960 * Start the shell or command.
4962 * Special case: if the first-choice command is an SSH-2
4963 * subsystem (hence not usable here) and the second choice
4964 * exists, we fall straight back to that.
4967 char *cmd = ssh->cfg.remote_cmd_ptr;
4969 if (!cmd) cmd = ssh->cfg.remote_cmd;
4971 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4972 cmd = ssh->cfg.remote_cmd_ptr2;
4973 ssh->fallback_cmd = TRUE;
4976 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4978 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4979 logevent("Started session");
4982 ssh->state = SSH_STATE_SESSION;
4983 if (ssh->size_needed)
4984 ssh_size(ssh, ssh->term_width, ssh->term_height);
4985 if (ssh->eof_needed)
4986 ssh_special(ssh, TS_EOF);
4989 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4991 ssh->channels = newtree234(ssh_channelcmp);
4995 * By this point, most incoming packets are already being
4996 * handled by the dispatch table, and we need only pay
4997 * attention to the unusual ones.
5002 if (pktin->type == SSH1_SMSG_SUCCESS) {
5003 /* may be from EXEC_SHELL on some servers */
5004 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5005 /* may be from EXEC_SHELL on some servers
5006 * if no pty is available or in other odd cases. Ignore */
5008 bombout(("Strange packet received: type %d", pktin->type));
5013 int len = min(inlen, 512);
5014 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5015 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5016 PKTT_OTHER, PKT_END);
5027 * Handle the top-level SSH-2 protocol.
5029 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5034 ssh_pkt_getstring(pktin, &msg, &msglen);
5035 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5038 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5040 /* log reason code in disconnect message */
5044 ssh_pkt_getstring(pktin, &msg, &msglen);
5045 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5048 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5050 /* Do nothing, because we're ignoring it! Duhh. */
5053 static void ssh1_protocol_setup(Ssh ssh)
5058 * Most messages are handled by the coroutines.
5060 for (i = 0; i < 256; i++)
5061 ssh->packet_dispatch[i] = NULL;
5064 * These special message types we install handlers for.
5066 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5067 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5068 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5071 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5072 struct Packet *pktin)
5074 unsigned char *in=(unsigned char*)vin;
5075 if (ssh->state == SSH_STATE_CLOSED)
5078 if (pktin && ssh->packet_dispatch[pktin->type]) {
5079 ssh->packet_dispatch[pktin->type](ssh, pktin);
5083 if (!ssh->protocol_initial_phase_done) {
5084 if (do_ssh1_login(ssh, in, inlen, pktin))
5085 ssh->protocol_initial_phase_done = TRUE;
5090 do_ssh1_connection(ssh, in, inlen, pktin);
5094 * Utility routine for decoding comma-separated strings in KEXINIT.
5096 static int in_commasep_string(char *needle, char *haystack, int haylen)
5099 if (!needle || !haystack) /* protect against null pointers */
5101 needlen = strlen(needle);
5104 * Is it at the start of the string?
5106 if (haylen >= needlen && /* haystack is long enough */
5107 !memcmp(needle, haystack, needlen) && /* initial match */
5108 (haylen == needlen || haystack[needlen] == ',')
5109 /* either , or EOS follows */
5113 * If not, search for the next comma and resume after that.
5114 * If no comma found, terminate.
5116 while (haylen > 0 && *haystack != ',')
5117 haylen--, haystack++;
5120 haylen--, haystack++; /* skip over comma itself */
5125 * Similar routine for checking whether we have the first string in a list.
5127 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5130 if (!needle || !haystack) /* protect against null pointers */
5132 needlen = strlen(needle);
5134 * Is it at the start of the string?
5136 if (haylen >= needlen && /* haystack is long enough */
5137 !memcmp(needle, haystack, needlen) && /* initial match */
5138 (haylen == needlen || haystack[needlen] == ',')
5139 /* either , or EOS follows */
5147 * SSH-2 key creation method.
5148 * (Currently assumes 2 lots of any hash are sufficient to generate
5149 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5151 #define SSH2_MKKEY_ITERS (2)
5152 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5153 unsigned char *keyspace)
5155 const struct ssh_hash *h = ssh->kex->hash;
5157 /* First hlen bytes. */
5159 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5160 hash_mpint(h, s, K);
5161 h->bytes(s, H, h->hlen);
5162 h->bytes(s, &chr, 1);
5163 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5164 h->final(s, keyspace);
5165 /* Next hlen bytes. */
5167 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5168 hash_mpint(h, s, K);
5169 h->bytes(s, H, h->hlen);
5170 h->bytes(s, keyspace, h->hlen);
5171 h->final(s, keyspace + h->hlen);
5175 * Handle the SSH-2 transport layer.
5177 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5178 struct Packet *pktin)
5180 unsigned char *in = (unsigned char *)vin;
5181 struct do_ssh2_transport_state {
5182 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5183 Bignum p, g, e, f, K;
5186 int kex_init_value, kex_reply_value;
5187 const struct ssh_mac **maclist;
5189 const struct ssh2_cipher *cscipher_tobe;
5190 const struct ssh2_cipher *sccipher_tobe;
5191 const struct ssh_mac *csmac_tobe;
5192 const struct ssh_mac *scmac_tobe;
5193 const struct ssh_compress *cscomp_tobe;
5194 const struct ssh_compress *sccomp_tobe;
5195 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5196 int hostkeylen, siglen, rsakeylen;
5197 void *hkey; /* actual host key */
5198 void *rsakey; /* for RSA kex */
5199 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5200 int n_preferred_kex;
5201 const struct ssh_kexes *preferred_kex[KEX_MAX];
5202 int n_preferred_ciphers;
5203 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5204 const struct ssh_compress *preferred_comp;
5205 int got_session_id, activated_authconn;
5206 struct Packet *pktout;
5211 crState(do_ssh2_transport_state);
5213 crBegin(ssh->do_ssh2_transport_crstate);
5215 s->cscipher_tobe = s->sccipher_tobe = NULL;
5216 s->csmac_tobe = s->scmac_tobe = NULL;
5217 s->cscomp_tobe = s->sccomp_tobe = NULL;
5219 s->got_session_id = s->activated_authconn = FALSE;
5222 * Be prepared to work around the buggy MAC problem.
5224 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5225 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5227 s->maclist = macs, s->nmacs = lenof(macs);
5230 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5232 int i, j, commalist_started;
5235 * Set up the preferred key exchange. (NULL => warn below here)
5237 s->n_preferred_kex = 0;
5238 for (i = 0; i < KEX_MAX; i++) {
5239 switch (ssh->cfg.ssh_kexlist[i]) {
5241 s->preferred_kex[s->n_preferred_kex++] =
5242 &ssh_diffiehellman_gex;
5245 s->preferred_kex[s->n_preferred_kex++] =
5246 &ssh_diffiehellman_group14;
5249 s->preferred_kex[s->n_preferred_kex++] =
5250 &ssh_diffiehellman_group1;
5253 s->preferred_kex[s->n_preferred_kex++] =
5257 /* Flag for later. Don't bother if it's the last in
5259 if (i < KEX_MAX - 1) {
5260 s->preferred_kex[s->n_preferred_kex++] = NULL;
5267 * Set up the preferred ciphers. (NULL => warn below here)
5269 s->n_preferred_ciphers = 0;
5270 for (i = 0; i < CIPHER_MAX; i++) {
5271 switch (ssh->cfg.ssh_cipherlist[i]) {
5272 case CIPHER_BLOWFISH:
5273 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5276 if (ssh->cfg.ssh2_des_cbc) {
5277 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5281 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5284 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5286 case CIPHER_ARCFOUR:
5287 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5290 /* Flag for later. Don't bother if it's the last in
5292 if (i < CIPHER_MAX - 1) {
5293 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5300 * Set up preferred compression.
5302 if (ssh->cfg.compression)
5303 s->preferred_comp = &ssh_zlib;
5305 s->preferred_comp = &ssh_comp_none;
5308 * Enable queueing of outgoing auth- or connection-layer
5309 * packets while we are in the middle of a key exchange.
5311 ssh->queueing = TRUE;
5314 * Flag that KEX is in progress.
5316 ssh->kex_in_progress = TRUE;
5319 * Construct and send our key exchange packet.
5321 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5322 for (i = 0; i < 16; i++)
5323 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5324 /* List key exchange algorithms. */
5325 ssh2_pkt_addstring_start(s->pktout);
5326 commalist_started = 0;
5327 for (i = 0; i < s->n_preferred_kex; i++) {
5328 const struct ssh_kexes *k = s->preferred_kex[i];
5329 if (!k) continue; /* warning flag */
5330 for (j = 0; j < k->nkexes; j++) {
5331 if (commalist_started)
5332 ssh2_pkt_addstring_str(s->pktout, ",");
5333 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5334 commalist_started = 1;
5337 /* List server host key algorithms. */
5338 ssh2_pkt_addstring_start(s->pktout);
5339 for (i = 0; i < lenof(hostkey_algs); i++) {
5340 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5341 if (i < lenof(hostkey_algs) - 1)
5342 ssh2_pkt_addstring_str(s->pktout, ",");
5344 /* List client->server encryption algorithms. */
5345 ssh2_pkt_addstring_start(s->pktout);
5346 commalist_started = 0;
5347 for (i = 0; i < s->n_preferred_ciphers; i++) {
5348 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5349 if (!c) continue; /* warning flag */
5350 for (j = 0; j < c->nciphers; j++) {
5351 if (commalist_started)
5352 ssh2_pkt_addstring_str(s->pktout, ",");
5353 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5354 commalist_started = 1;
5357 /* List server->client encryption algorithms. */
5358 ssh2_pkt_addstring_start(s->pktout);
5359 commalist_started = 0;
5360 for (i = 0; i < s->n_preferred_ciphers; i++) {
5361 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5362 if (!c) continue; /* warning flag */
5363 for (j = 0; j < c->nciphers; j++) {
5364 if (commalist_started)
5365 ssh2_pkt_addstring_str(s->pktout, ",");
5366 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5367 commalist_started = 1;
5370 /* List client->server MAC algorithms. */
5371 ssh2_pkt_addstring_start(s->pktout);
5372 for (i = 0; i < s->nmacs; i++) {
5373 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5374 if (i < s->nmacs - 1)
5375 ssh2_pkt_addstring_str(s->pktout, ",");
5377 /* List server->client MAC algorithms. */
5378 ssh2_pkt_addstring_start(s->pktout);
5379 for (i = 0; i < s->nmacs; i++) {
5380 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5381 if (i < s->nmacs - 1)
5382 ssh2_pkt_addstring_str(s->pktout, ",");
5384 /* List client->server compression algorithms. */
5385 ssh2_pkt_addstring_start(s->pktout);
5386 assert(lenof(compressions) > 1);
5387 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5388 for (i = 0; i < lenof(compressions); i++) {
5389 const struct ssh_compress *c = compressions[i];
5390 if (c != s->preferred_comp) {
5391 ssh2_pkt_addstring_str(s->pktout, ",");
5392 ssh2_pkt_addstring_str(s->pktout, c->name);
5395 /* List server->client compression algorithms. */
5396 ssh2_pkt_addstring_start(s->pktout);
5397 assert(lenof(compressions) > 1);
5398 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5399 for (i = 0; i < lenof(compressions); i++) {
5400 const struct ssh_compress *c = compressions[i];
5401 if (c != s->preferred_comp) {
5402 ssh2_pkt_addstring_str(s->pktout, ",");
5403 ssh2_pkt_addstring_str(s->pktout, c->name);
5406 /* List client->server languages. Empty list. */
5407 ssh2_pkt_addstring_start(s->pktout);
5408 /* List server->client languages. Empty list. */
5409 ssh2_pkt_addstring_start(s->pktout);
5410 /* First KEX packet does _not_ follow, because we're not that brave. */
5411 ssh2_pkt_addbool(s->pktout, FALSE);
5413 ssh2_pkt_adduint32(s->pktout, 0);
5416 s->our_kexinitlen = s->pktout->length - 5;
5417 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5418 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5420 ssh2_pkt_send_noqueue(ssh, s->pktout);
5426 * Now examine the other side's KEXINIT to see what we're up
5430 char *str, *preferred;
5433 if (pktin->type != SSH2_MSG_KEXINIT) {
5434 bombout(("expected key exchange packet from server"));
5438 ssh->hostkey = NULL;
5439 s->cscipher_tobe = NULL;
5440 s->sccipher_tobe = NULL;
5441 s->csmac_tobe = NULL;
5442 s->scmac_tobe = NULL;
5443 s->cscomp_tobe = NULL;
5444 s->sccomp_tobe = NULL;
5445 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5447 pktin->savedpos += 16; /* skip garbage cookie */
5448 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5451 for (i = 0; i < s->n_preferred_kex; i++) {
5452 const struct ssh_kexes *k = s->preferred_kex[i];
5456 for (j = 0; j < k->nkexes; j++) {
5457 if (!preferred) preferred = k->list[j]->name;
5458 if (in_commasep_string(k->list[j]->name, str, len)) {
5459 ssh->kex = k->list[j];
5468 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5469 str ? str : "(null)"));
5473 * Note that the server's guess is considered wrong if it doesn't match
5474 * the first algorithm in our list, even if it's still the algorithm
5477 s->guessok = first_in_commasep_string(preferred, str, len);
5478 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5479 for (i = 0; i < lenof(hostkey_algs); i++) {
5480 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5481 ssh->hostkey = hostkey_algs[i];
5485 s->guessok = s->guessok &&
5486 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5487 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5488 for (i = 0; i < s->n_preferred_ciphers; i++) {
5489 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5491 s->warn_cscipher = TRUE;
5493 for (j = 0; j < c->nciphers; j++) {
5494 if (in_commasep_string(c->list[j]->name, str, len)) {
5495 s->cscipher_tobe = c->list[j];
5500 if (s->cscipher_tobe)
5503 if (!s->cscipher_tobe) {
5504 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5505 str ? str : "(null)"));
5509 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5510 for (i = 0; i < s->n_preferred_ciphers; i++) {
5511 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5513 s->warn_sccipher = TRUE;
5515 for (j = 0; j < c->nciphers; j++) {
5516 if (in_commasep_string(c->list[j]->name, str, len)) {
5517 s->sccipher_tobe = c->list[j];
5522 if (s->sccipher_tobe)
5525 if (!s->sccipher_tobe) {
5526 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5527 str ? str : "(null)"));
5531 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5532 for (i = 0; i < s->nmacs; i++) {
5533 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5534 s->csmac_tobe = s->maclist[i];
5538 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5539 for (i = 0; i < s->nmacs; i++) {
5540 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5541 s->scmac_tobe = s->maclist[i];
5545 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5546 for (i = 0; i < lenof(compressions) + 1; i++) {
5547 const struct ssh_compress *c =
5548 i == 0 ? s->preferred_comp : compressions[i - 1];
5549 if (in_commasep_string(c->name, str, len)) {
5554 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5555 for (i = 0; i < lenof(compressions) + 1; i++) {
5556 const struct ssh_compress *c =
5557 i == 0 ? s->preferred_comp : compressions[i - 1];
5558 if (in_commasep_string(c->name, str, len)) {
5563 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5564 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5565 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5568 ssh_set_frozen(ssh, 1);
5569 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5571 ssh_dialog_callback, ssh);
5572 if (s->dlgret < 0) {
5576 bombout(("Unexpected data from server while"
5577 " waiting for user response"));
5580 } while (pktin || inlen > 0);
5581 s->dlgret = ssh->user_response;
5583 ssh_set_frozen(ssh, 0);
5584 if (s->dlgret == 0) {
5585 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5591 if (s->warn_cscipher) {
5592 ssh_set_frozen(ssh, 1);
5593 s->dlgret = askalg(ssh->frontend,
5594 "client-to-server cipher",
5595 s->cscipher_tobe->name,
5596 ssh_dialog_callback, ssh);
5597 if (s->dlgret < 0) {
5601 bombout(("Unexpected data from server while"
5602 " waiting for user response"));
5605 } while (pktin || inlen > 0);
5606 s->dlgret = ssh->user_response;
5608 ssh_set_frozen(ssh, 0);
5609 if (s->dlgret == 0) {
5610 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5616 if (s->warn_sccipher) {
5617 ssh_set_frozen(ssh, 1);
5618 s->dlgret = askalg(ssh->frontend,
5619 "server-to-client cipher",
5620 s->sccipher_tobe->name,
5621 ssh_dialog_callback, ssh);
5622 if (s->dlgret < 0) {
5626 bombout(("Unexpected data from server while"
5627 " waiting for user response"));
5630 } while (pktin || inlen > 0);
5631 s->dlgret = ssh->user_response;
5633 ssh_set_frozen(ssh, 0);
5634 if (s->dlgret == 0) {
5635 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5641 ssh->exhash = ssh->kex->hash->init();
5642 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5643 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5644 hash_string(ssh->kex->hash, ssh->exhash,
5645 s->our_kexinit, s->our_kexinitlen);
5646 sfree(s->our_kexinit);
5647 if (pktin->length > 5)
5648 hash_string(ssh->kex->hash, ssh->exhash,
5649 pktin->data + 5, pktin->length - 5);
5651 if (s->ignorepkt) /* first_kex_packet_follows */
5652 crWaitUntil(pktin); /* Ignore packet */
5655 if (ssh->kex->main_type == KEXTYPE_DH) {
5657 * Work out the number of bits of key we will need from the
5658 * key exchange. We start with the maximum key length of
5664 csbits = s->cscipher_tobe->keylen;
5665 scbits = s->sccipher_tobe->keylen;
5666 s->nbits = (csbits > scbits ? csbits : scbits);
5668 /* The keys only have hlen-bit entropy, since they're based on
5669 * a hash. So cap the key size at hlen bits. */
5670 if (s->nbits > ssh->kex->hash->hlen * 8)
5671 s->nbits = ssh->kex->hash->hlen * 8;
5674 * If we're doing Diffie-Hellman group exchange, start by
5675 * requesting a group.
5677 if (!ssh->kex->pdata) {
5678 logevent("Doing Diffie-Hellman group exchange");
5679 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5681 * Work out how big a DH group we will need to allow that
5684 s->pbits = 512 << ((s->nbits - 1) / 64);
5685 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5686 ssh2_pkt_adduint32(s->pktout, s->pbits);
5687 ssh2_pkt_send_noqueue(ssh, s->pktout);
5690 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5691 bombout(("expected key exchange group packet from server"));
5694 s->p = ssh2_pkt_getmp(pktin);
5695 s->g = ssh2_pkt_getmp(pktin);
5696 if (!s->p || !s->g) {
5697 bombout(("unable to read mp-ints from incoming group packet"));
5700 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5701 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5702 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5704 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5705 ssh->kex_ctx = dh_setup_group(ssh->kex);
5706 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5707 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5708 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5709 ssh->kex->groupname);
5712 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5713 ssh->kex->hash->text_name);
5715 * Now generate and send e for Diffie-Hellman.
5717 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5718 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5719 s->pktout = ssh2_pkt_init(s->kex_init_value);
5720 ssh2_pkt_addmp(s->pktout, s->e);
5721 ssh2_pkt_send_noqueue(ssh, s->pktout);
5723 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5725 if (pktin->type != s->kex_reply_value) {
5726 bombout(("expected key exchange reply packet from server"));
5729 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5730 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5731 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5732 s->f = ssh2_pkt_getmp(pktin);
5734 bombout(("unable to parse key exchange reply packet"));
5737 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5739 s->K = dh_find_K(ssh->kex_ctx, s->f);
5741 /* We assume everything from now on will be quick, and it might
5742 * involve user interaction. */
5743 set_busy_status(ssh->frontend, BUSY_NOT);
5745 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5746 if (!ssh->kex->pdata) {
5747 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
5748 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
5749 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
5751 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
5752 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
5754 dh_cleanup(ssh->kex_ctx);
5756 if (!ssh->kex->pdata) {
5761 logeventf(ssh, "Doing RSA key exchange with hash %s",
5762 ssh->kex->hash->text_name);
5763 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
5765 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5769 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
5770 bombout(("expected RSA public key packet from server"));
5774 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5775 hash_string(ssh->kex->hash, ssh->exhash,
5776 s->hostkeydata, s->hostkeylen);
5777 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5781 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
5782 s->rsakeydata = snewn(s->rsakeylen, char);
5783 memcpy(s->rsakeydata, keydata, s->rsakeylen);
5786 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
5788 sfree(s->rsakeydata);
5789 bombout(("unable to parse RSA public key from server"));
5793 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
5796 * Next, set up a shared secret K, of precisely KLEN -
5797 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5798 * RSA key modulus and HLEN is the bit length of the hash
5802 int klen = ssh_rsakex_klen(s->rsakey);
5803 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
5805 unsigned char *kstr1, *kstr2, *outstr;
5806 int kstr1len, kstr2len, outstrlen;
5808 s->K = bn_power_2(nbits - 1);
5810 for (i = 0; i < nbits; i++) {
5812 byte = random_byte();
5814 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
5818 * Encode this as an mpint.
5820 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
5821 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
5822 PUT_32BIT(kstr2, kstr1len);
5823 memcpy(kstr2 + 4, kstr1, kstr1len);
5826 * Encrypt it with the given RSA key.
5828 outstrlen = (klen + 7) / 8;
5829 outstr = snewn(outstrlen, unsigned char);
5830 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
5831 outstr, outstrlen, s->rsakey);
5834 * And send it off in a return packet.
5836 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
5837 ssh2_pkt_addstring_start(s->pktout);
5838 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
5839 ssh2_pkt_send_noqueue(ssh, s->pktout);
5841 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
5848 ssh_rsakex_freekey(s->rsakey);
5851 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
5852 sfree(s->rsakeydata);
5853 bombout(("expected signature packet from server"));
5857 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5859 sfree(s->rsakeydata);
5862 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
5863 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
5864 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
5866 ssh->kex_ctx = NULL;
5869 debug(("Exchange hash is:\n"));
5870 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
5874 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5875 (char *)s->exchange_hash,
5876 ssh->kex->hash->hlen)) {
5877 bombout(("Server's host key did not match the signature supplied"));
5882 * Authenticate remote host: verify host key. (We've already
5883 * checked the signature of the exchange hash.)
5885 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5886 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5887 ssh_set_frozen(ssh, 1);
5888 s->dlgret = verify_ssh_host_key(ssh->frontend,
5889 ssh->savedhost, ssh->savedport,
5890 ssh->hostkey->keytype, s->keystr,
5892 ssh_dialog_callback, ssh);
5893 if (s->dlgret < 0) {
5897 bombout(("Unexpected data from server while waiting"
5898 " for user host key response"));
5901 } while (pktin || inlen > 0);
5902 s->dlgret = ssh->user_response;
5904 ssh_set_frozen(ssh, 0);
5905 if (s->dlgret == 0) {
5906 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
5910 if (!s->got_session_id) { /* don't bother logging this in rekeys */
5911 logevent("Host key fingerprint is:");
5912 logevent(s->fingerprint);
5914 sfree(s->fingerprint);
5916 ssh->hostkey->freekey(s->hkey);
5919 * The exchange hash from the very first key exchange is also
5920 * the session id, used in session key construction and
5923 if (!s->got_session_id) {
5924 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
5925 memcpy(ssh->v2_session_id, s->exchange_hash,
5926 sizeof(s->exchange_hash));
5927 ssh->v2_session_id_len = ssh->kex->hash->hlen;
5928 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
5929 s->got_session_id = TRUE;
5933 * Send SSH2_MSG_NEWKEYS.
5935 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5936 ssh2_pkt_send_noqueue(ssh, s->pktout);
5937 ssh->outgoing_data_size = 0; /* start counting from here */
5940 * We've sent client NEWKEYS, so create and initialise
5941 * client-to-server session keys.
5943 if (ssh->cs_cipher_ctx)
5944 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5945 ssh->cscipher = s->cscipher_tobe;
5946 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5948 if (ssh->cs_mac_ctx)
5949 ssh->csmac->free_context(ssh->cs_mac_ctx);
5950 ssh->csmac = s->csmac_tobe;
5951 ssh->cs_mac_ctx = ssh->csmac->make_context();
5953 if (ssh->cs_comp_ctx)
5954 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5955 ssh->cscomp = s->cscomp_tobe;
5956 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5959 * Set IVs on client-to-server keys. Here we use the exchange
5960 * hash from the _first_ key exchange.
5963 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
5964 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5965 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
5966 assert((ssh->cscipher->keylen+7) / 8 <=
5967 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5968 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5969 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
5970 assert(ssh->cscipher->blksize <=
5971 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5972 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5973 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
5974 assert(ssh->csmac->len <=
5975 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5976 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5977 memset(keyspace, 0, sizeof(keyspace));
5980 logeventf(ssh, "Initialised %.200s client->server encryption",
5981 ssh->cscipher->text_name);
5982 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5983 ssh->csmac->text_name);
5984 if (ssh->cscomp->text_name)
5985 logeventf(ssh, "Initialised %s compression",
5986 ssh->cscomp->text_name);
5989 * Now our end of the key exchange is complete, we can send all
5990 * our queued higher-layer packets.
5992 ssh->queueing = FALSE;
5993 ssh2_pkt_queuesend(ssh);
5996 * Expect SSH2_MSG_NEWKEYS from server.
5999 if (pktin->type != SSH2_MSG_NEWKEYS) {
6000 bombout(("expected new-keys packet from server"));
6003 ssh->incoming_data_size = 0; /* start counting from here */
6006 * We've seen server NEWKEYS, so create and initialise
6007 * server-to-client session keys.
6009 if (ssh->sc_cipher_ctx)
6010 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6011 ssh->sccipher = s->sccipher_tobe;
6012 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6014 if (ssh->sc_mac_ctx)
6015 ssh->scmac->free_context(ssh->sc_mac_ctx);
6016 ssh->scmac = s->scmac_tobe;
6017 ssh->sc_mac_ctx = ssh->scmac->make_context();
6019 if (ssh->sc_comp_ctx)
6020 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6021 ssh->sccomp = s->sccomp_tobe;
6022 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6025 * Set IVs on server-to-client keys. Here we use the exchange
6026 * hash from the _first_ key exchange.
6029 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6030 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6031 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6032 assert((ssh->sccipher->keylen+7) / 8 <=
6033 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6034 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6035 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6036 assert(ssh->sccipher->blksize <=
6037 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6038 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6039 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6040 assert(ssh->scmac->len <=
6041 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6042 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6043 memset(keyspace, 0, sizeof(keyspace));
6045 logeventf(ssh, "Initialised %.200s server->client encryption",
6046 ssh->sccipher->text_name);
6047 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6048 ssh->scmac->text_name);
6049 if (ssh->sccomp->text_name)
6050 logeventf(ssh, "Initialised %s decompression",
6051 ssh->sccomp->text_name);
6054 * Free shared secret.
6059 * Key exchange is over. Loop straight back round if we have a
6060 * deferred rekey reason.
6062 if (ssh->deferred_rekey_reason) {
6063 logevent(ssh->deferred_rekey_reason);
6065 ssh->deferred_rekey_reason = NULL;
6066 goto begin_key_exchange;
6070 * Otherwise, schedule a timer for our next rekey.
6072 ssh->kex_in_progress = FALSE;
6073 ssh->last_rekey = GETTICKCOUNT();
6074 if (ssh->cfg.ssh_rekey_time != 0)
6075 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6079 * If this is the first key exchange phase, we must pass the
6080 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6081 * wants to see it but because it will need time to initialise
6082 * itself before it sees an actual packet. In subsequent key
6083 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6084 * it would only confuse the layer above.
6086 if (s->activated_authconn) {
6089 s->activated_authconn = TRUE;
6092 * Now we're encrypting. Begin returning 1 to the protocol main
6093 * function so that other things can run on top of the
6094 * transport. If we ever see a KEXINIT, we must go back to the
6097 * We _also_ go back to the start if we see pktin==NULL and
6098 * inlen==-1, because this is a special signal meaning
6099 * `initiate client-driven rekey', and `in' contains a message
6100 * giving the reason for the rekey.
6102 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6103 (!pktin && inlen == -1))) {
6108 logevent("Server initiated key re-exchange");
6111 * Special case: if the server bug is set that doesn't
6112 * allow rekeying, we give a different log message and
6113 * continue waiting. (If such a server _initiates_ a rekey,
6114 * we process it anyway!)
6116 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6117 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6119 /* Reset the counters, so that at least this message doesn't
6120 * hit the event log _too_ often. */
6121 ssh->outgoing_data_size = 0;
6122 ssh->incoming_data_size = 0;
6123 if (ssh->cfg.ssh_rekey_time != 0) {
6125 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6128 goto wait_for_rekey; /* this is utterly horrid */
6130 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6133 goto begin_key_exchange;
6139 * Add data to an SSH-2 channel output buffer.
6141 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6144 bufchain_add(&c->v.v2.outbuffer, buf, len);
6148 * Attempt to send data on an SSH-2 channel.
6150 static int ssh2_try_send(struct ssh_channel *c)
6153 struct Packet *pktout;
6155 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6158 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6159 if ((unsigned)len > c->v.v2.remwindow)
6160 len = c->v.v2.remwindow;
6161 if ((unsigned)len > c->v.v2.remmaxpkt)
6162 len = c->v.v2.remmaxpkt;
6163 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6164 ssh2_pkt_adduint32(pktout, c->remoteid);
6165 ssh2_pkt_addstring_start(pktout);
6166 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6167 ssh2_pkt_addstring_data(pktout, data, len);
6168 end_log_omission(ssh, pktout);
6169 ssh2_pkt_send(ssh, pktout);
6170 bufchain_consume(&c->v.v2.outbuffer, len);
6171 c->v.v2.remwindow -= len;
6175 * After having sent as much data as we can, return the amount
6178 return bufchain_size(&c->v.v2.outbuffer);
6181 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
6185 return; /* don't send on closing channels */
6186 bufsize = ssh2_try_send(c);
6189 case CHAN_MAINSESSION:
6190 /* stdin need not receive an unthrottle
6191 * notification since it will be polled */
6194 x11_unthrottle(c->u.x11.s);
6197 /* agent sockets are request/response and need no
6198 * buffer management */
6201 pfd_unthrottle(c->u.pfd.s);
6208 * Set up most of a new ssh_channel for SSH-2.
6210 static void ssh2_channel_init(struct ssh_channel *c)
6213 c->localid = alloc_channel_id(ssh);
6215 c->throttling_conn = FALSE;
6216 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6217 ssh->cfg.ssh_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6218 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6219 c->v.v2.throttle_state = UNTHROTTLED;
6220 bufchain_init(&c->v.v2.outbuffer);
6224 * Potentially enlarge the window on an SSH-2 channel.
6226 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6231 * Never send WINDOW_ADJUST for a channel that the remote side
6232 * already thinks it's closed; there's no point, since it won't
6233 * be sending any more data anyway.
6239 * Only send a WINDOW_ADJUST if there's significantly more window
6240 * available than the other end thinks there is. This saves us
6241 * sending a WINDOW_ADJUST for every character in a shell session.
6243 * "Significant" is arbitrarily defined as half the window size.
6245 if (newwin / 2 >= c->v.v2.locwindow) {
6246 struct Packet *pktout;
6250 * In order to keep track of how much window the client
6251 * actually has available, we'd like it to acknowledge each
6252 * WINDOW_ADJUST. We can't do that directly, so we accompany
6253 * it with a CHANNEL_REQUEST that has to be acknowledged.
6255 * This is only necessary if we're opening the window wide.
6256 * If we're not, then throughput is being constrained by
6257 * something other than the maximum window size anyway.
6259 * We also only send this if the main channel has finished its
6260 * initial CHANNEL_REQUESTs and installed the default
6261 * CHANNEL_FAILURE handler, so as not to risk giving it
6262 * unexpected CHANNEL_FAILUREs.
6264 if (newwin == c->v.v2.locmaxwin &&
6265 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6266 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6267 ssh2_pkt_adduint32(pktout, c->remoteid);
6268 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6269 ssh2_pkt_addbool(pktout, TRUE);
6270 ssh2_pkt_send(ssh, pktout);
6273 * CHANNEL_FAILURE doesn't come with any indication of
6274 * what message caused it, so we have to keep track of the
6275 * outstanding CHANNEL_REQUESTs ourselves.
6277 wa = snew(struct winadj);
6278 wa->size = newwin - c->v.v2.locwindow;
6280 if (!c->v.v2.winadj_head)
6281 c->v.v2.winadj_head = wa;
6283 c->v.v2.winadj_tail->next = wa;
6284 c->v.v2.winadj_tail = wa;
6285 if (c->v.v2.throttle_state != UNTHROTTLED)
6286 c->v.v2.throttle_state = UNTHROTTLING;
6288 /* Pretend the WINDOW_ADJUST was acked immediately. */
6289 c->v.v2.remlocwin = newwin;
6290 c->v.v2.throttle_state = THROTTLED;
6292 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6293 ssh2_pkt_adduint32(pktout, c->remoteid);
6294 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6295 ssh2_pkt_send(ssh, pktout);
6296 c->v.v2.locwindow = newwin;
6301 * Find the channel associated with a message. If there's no channel,
6302 * or it's not properly open, make a noise about it and return NULL.
6304 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6306 unsigned localid = ssh_pkt_getuint32(pktin);
6307 struct ssh_channel *c;
6309 c = find234(ssh->channels, &localid, ssh_channelfind);
6311 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6312 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6313 char *buf = dupprintf("Received %s for %s channel %u",
6314 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6316 c ? "half-open" : "nonexistent", localid);
6317 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6324 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6327 * This should never get called. All channel requests are either
6328 * sent with want_reply false or are sent before this handler gets
6331 struct ssh_channel *c;
6334 c = ssh2_channel_msg(ssh, pktin);
6337 wa = c->v.v2.winadj_head;
6339 ssh_disconnect(ssh, NULL, "Received SSH_MSG_CHANNEL_SUCCESS for "
6340 "\"winadj@putty.projects.tartarus.org\"",
6341 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6343 ssh_disconnect(ssh, NULL,
6344 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6345 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6348 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6351 * The only time this should get called is for "winadj@putty"
6352 * messages sent above. All other channel requests are either
6353 * sent with want_reply false or are sent before this handler gets
6356 struct ssh_channel *c;
6359 c = ssh2_channel_msg(ssh, pktin);
6362 wa = c->v.v2.winadj_head;
6364 ssh_disconnect(ssh, NULL,
6365 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6366 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6369 c->v.v2.winadj_head = wa->next;
6370 c->v.v2.remlocwin += wa->size;
6373 * winadj messages are only sent when the window is fully open, so
6374 * if we get an ack of one, we know any pending unthrottle is
6377 if (c->v.v2.throttle_state == UNTHROTTLING)
6378 c->v.v2.throttle_state = UNTHROTTLED;
6381 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6383 struct ssh_channel *c;
6384 c = ssh2_channel_msg(ssh, pktin);
6388 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6389 ssh2_try_send_and_unthrottle(c);
6393 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6397 struct ssh_channel *c;
6398 c = ssh2_channel_msg(ssh, pktin);
6401 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6402 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6403 return; /* extended but not stderr */
6404 ssh_pkt_getstring(pktin, &data, &length);
6407 c->v.v2.locwindow -= length;
6408 c->v.v2.remlocwin -= length;
6410 case CHAN_MAINSESSION:
6412 from_backend(ssh->frontend, pktin->type ==
6413 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6417 bufsize = x11_send(c->u.x11.s, data, length);
6420 bufsize = pfd_send(c->u.pfd.s, data, length);
6423 while (length > 0) {
6424 if (c->u.a.lensofar < 4) {
6425 unsigned int l = min(4 - c->u.a.lensofar,
6427 memcpy(c->u.a.msglen + c->u.a.lensofar,
6431 c->u.a.lensofar += l;
6433 if (c->u.a.lensofar == 4) {
6435 4 + GET_32BIT(c->u.a.msglen);
6436 c->u.a.message = snewn(c->u.a.totallen,
6438 memcpy(c->u.a.message, c->u.a.msglen, 4);
6440 if (c->u.a.lensofar >= 4 && length > 0) {
6442 min(c->u.a.totallen - c->u.a.lensofar,
6444 memcpy(c->u.a.message + c->u.a.lensofar,
6448 c->u.a.lensofar += l;
6450 if (c->u.a.lensofar == c->u.a.totallen) {
6453 if (agent_query(c->u.a.message,
6456 ssh_agentf_callback, c))
6457 ssh_agentf_callback(c, reply, replylen);
6458 sfree(c->u.a.message);
6459 c->u.a.lensofar = 0;
6466 * If it looks like the remote end hit the end of its window,
6467 * and we didn't want it to do that, think about using a
6470 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6471 c->v.v2.locmaxwin < 0x40000000)
6472 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6474 * If we are not buffering too much data,
6475 * enlarge the window again at the remote side.
6476 * If we are buffering too much, we may still
6477 * need to adjust the window if the server's
6480 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6481 c->v.v2.locmaxwin - bufsize : 0);
6483 * If we're either buffering way too much data, or if we're
6484 * buffering anything at all and we're in "simple" mode,
6485 * throttle the whole channel.
6487 if ((bufsize > c->v.v2.locmaxwin ||
6488 (ssh->cfg.ssh_simple && bufsize > 0)) &&
6489 !c->throttling_conn) {
6490 c->throttling_conn = 1;
6491 ssh_throttle_conn(ssh, +1);
6496 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6498 struct ssh_channel *c;
6500 c = ssh2_channel_msg(ssh, pktin);
6504 if (c->type == CHAN_X11) {
6506 * Remote EOF on an X11 channel means we should
6507 * wrap up and close the channel ourselves.
6509 x11_close(c->u.x11.s);
6511 } else if (c->type == CHAN_AGENT) {
6513 } else if (c->type == CHAN_SOCKDATA) {
6514 pfd_close(c->u.pfd.s);
6519 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6521 struct ssh_channel *c;
6522 struct Packet *pktout;
6524 c = ssh2_channel_msg(ssh, pktin);
6527 /* Do pre-close processing on the channel. */
6529 case CHAN_MAINSESSION:
6530 ssh->mainchan = NULL;
6531 update_specials_menu(ssh->frontend);
6534 if (c->u.x11.s != NULL)
6535 x11_close(c->u.x11.s);
6542 if (c->u.pfd.s != NULL)
6543 pfd_close(c->u.pfd.s);
6547 if (c->closes == 0) {
6548 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6549 ssh2_pkt_adduint32(pktout, c->remoteid);
6550 ssh2_pkt_send(ssh, pktout);
6552 del234(ssh->channels, c);
6553 bufchain_clear(&c->v.v2.outbuffer);
6557 * See if that was the last channel left open.
6558 * (This is only our termination condition if we're
6559 * not running in -N mode.)
6561 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6563 * We used to send SSH_MSG_DISCONNECT here,
6564 * because I'd believed that _every_ conforming
6565 * SSH-2 connection had to end with a disconnect
6566 * being sent by at least one side; apparently
6567 * I was wrong and it's perfectly OK to
6568 * unceremoniously slam the connection shut
6569 * when you're done, and indeed OpenSSH feels
6570 * this is more polite than sending a
6571 * DISCONNECT. So now we don't.
6573 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6577 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6579 struct ssh_channel *c;
6580 struct Packet *pktout;
6582 c = ssh2_channel_msg(ssh, pktin);
6585 if (c->type != CHAN_SOCKDATA_DORMANT)
6586 return; /* dunno why they're confirming this */
6587 c->remoteid = ssh_pkt_getuint32(pktin);
6588 c->halfopen = FALSE;
6589 c->type = CHAN_SOCKDATA;
6590 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6591 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6593 pfd_confirm(c->u.pfd.s);
6596 * We have a pending close on this channel,
6597 * which we decided on before the server acked
6598 * the channel open. So now we know the
6599 * remoteid, we can close it again.
6601 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6602 ssh2_pkt_adduint32(pktout, c->remoteid);
6603 ssh2_pkt_send(ssh, pktout);
6607 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
6609 static const char *const reasons[] = {
6610 "<unknown reason code>",
6611 "Administratively prohibited",
6613 "Unknown channel type",
6614 "Resource shortage",
6616 unsigned reason_code;
6617 char *reason_string;
6619 struct ssh_channel *c;
6620 c = ssh2_channel_msg(ssh, pktin);
6623 if (c->type != CHAN_SOCKDATA_DORMANT)
6624 return; /* dunno why they're failing this */
6626 reason_code = ssh_pkt_getuint32(pktin);
6627 if (reason_code >= lenof(reasons))
6628 reason_code = 0; /* ensure reasons[reason_code] in range */
6629 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6630 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
6631 reasons[reason_code], reason_length, reason_string);
6633 pfd_close(c->u.pfd.s);
6635 del234(ssh->channels, c);
6639 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
6642 int typelen, want_reply;
6643 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6644 struct ssh_channel *c;
6645 struct Packet *pktout;
6647 c = ssh2_channel_msg(ssh, pktin);
6650 ssh_pkt_getstring(pktin, &type, &typelen);
6651 want_reply = ssh2_pkt_getbool(pktin);
6654 * Having got the channel number, we now look at
6655 * the request type string to see if it's something
6658 if (c == ssh->mainchan) {
6660 * We recognise "exit-status" and "exit-signal" on
6661 * the primary channel.
6663 if (typelen == 11 &&
6664 !memcmp(type, "exit-status", 11)) {
6666 ssh->exitcode = ssh_pkt_getuint32(pktin);
6667 logeventf(ssh, "Server sent command exit status %d",
6669 reply = SSH2_MSG_CHANNEL_SUCCESS;
6671 } else if (typelen == 11 &&
6672 !memcmp(type, "exit-signal", 11)) {
6674 int is_plausible = TRUE, is_int = FALSE;
6675 char *fmt_sig = "", *fmt_msg = "";
6677 int msglen = 0, core = FALSE;
6678 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6679 * provide an `int' for the signal, despite its
6680 * having been a `string' in the drafts of RFC 4254 since at
6681 * least 2001. (Fixed in session.c 1.147.) Try to
6682 * infer which we can safely parse it as. */
6684 unsigned char *p = pktin->body +
6686 long len = pktin->length - pktin->savedpos;
6687 unsigned long num = GET_32BIT(p); /* what is it? */
6688 /* If it's 0, it hardly matters; assume string */
6692 int maybe_int = FALSE, maybe_str = FALSE;
6693 #define CHECK_HYPOTHESIS(offset, result) \
6696 if (q >= 0 && q+4 <= len) { \
6697 q = q + 4 + GET_32BIT(p+q); \
6698 if (q >= 0 && q+4 <= len && \
6699 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6703 CHECK_HYPOTHESIS(4+1, maybe_int);
6704 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6705 #undef CHECK_HYPOTHESIS
6706 if (maybe_int && !maybe_str)
6708 else if (!maybe_int && maybe_str)
6711 /* Crikey. Either or neither. Panic. */
6712 is_plausible = FALSE;
6715 ssh->exitcode = 128; /* means `unknown signal' */
6718 /* Old non-standard OpenSSH. */
6719 int signum = ssh_pkt_getuint32(pktin);
6720 fmt_sig = dupprintf(" %d", signum);
6721 ssh->exitcode = 128 + signum;
6723 /* As per RFC 4254. */
6726 ssh_pkt_getstring(pktin, &sig, &siglen);
6727 /* Signal name isn't supposed to be blank, but
6728 * let's cope gracefully if it is. */
6730 fmt_sig = dupprintf(" \"%.*s\"",
6735 * Really hideous method of translating the
6736 * signal description back into a locally
6737 * meaningful number.
6742 #define TRANSLATE_SIGNAL(s) \
6743 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6744 ssh->exitcode = 128 + SIG ## s
6746 TRANSLATE_SIGNAL(ABRT);
6749 TRANSLATE_SIGNAL(ALRM);
6752 TRANSLATE_SIGNAL(FPE);
6755 TRANSLATE_SIGNAL(HUP);
6758 TRANSLATE_SIGNAL(ILL);
6761 TRANSLATE_SIGNAL(INT);
6764 TRANSLATE_SIGNAL(KILL);
6767 TRANSLATE_SIGNAL(PIPE);
6770 TRANSLATE_SIGNAL(QUIT);
6773 TRANSLATE_SIGNAL(SEGV);
6776 TRANSLATE_SIGNAL(TERM);
6779 TRANSLATE_SIGNAL(USR1);
6782 TRANSLATE_SIGNAL(USR2);
6784 #undef TRANSLATE_SIGNAL
6786 ssh->exitcode = 128;
6788 core = ssh2_pkt_getbool(pktin);
6789 ssh_pkt_getstring(pktin, &msg, &msglen);
6791 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6793 /* ignore lang tag */
6794 } /* else don't attempt to parse */
6795 logeventf(ssh, "Server exited on signal%s%s%s",
6796 fmt_sig, core ? " (core dumped)" : "",
6798 if (*fmt_sig) sfree(fmt_sig);
6799 if (*fmt_msg) sfree(fmt_msg);
6800 reply = SSH2_MSG_CHANNEL_SUCCESS;
6805 * This is a channel request we don't know
6806 * about, so we now either ignore the request
6807 * or respond with CHANNEL_FAILURE, depending
6810 reply = SSH2_MSG_CHANNEL_FAILURE;
6813 pktout = ssh2_pkt_init(reply);
6814 ssh2_pkt_adduint32(pktout, c->remoteid);
6815 ssh2_pkt_send(ssh, pktout);
6819 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6822 int typelen, want_reply;
6823 struct Packet *pktout;
6825 ssh_pkt_getstring(pktin, &type, &typelen);
6826 want_reply = ssh2_pkt_getbool(pktin);
6829 * We currently don't support any global requests
6830 * at all, so we either ignore the request or
6831 * respond with REQUEST_FAILURE, depending on
6835 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6836 ssh2_pkt_send(ssh, pktout);
6840 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
6848 struct ssh_channel *c;
6849 unsigned remid, winsize, pktsize;
6850 struct Packet *pktout;
6852 ssh_pkt_getstring(pktin, &type, &typelen);
6853 c = snew(struct ssh_channel);
6856 remid = ssh_pkt_getuint32(pktin);
6857 winsize = ssh_pkt_getuint32(pktin);
6858 pktsize = ssh_pkt_getuint32(pktin);
6860 if (typelen == 3 && !memcmp(type, "x11", 3)) {
6863 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6864 addrstr = snewn(peeraddrlen+1, char);
6865 memcpy(addrstr, peeraddr, peeraddrlen);
6866 addrstr[peeraddrlen] = '\0';
6867 peerport = ssh_pkt_getuint32(pktin);
6869 logeventf(ssh, "Received X11 connect request from %s:%d",
6872 if (!ssh->X11_fwd_enabled)
6873 error = "X11 forwarding is not enabled";
6874 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
6875 ssh->x11auth, addrstr, peerport,
6876 &ssh->cfg) != NULL) {
6877 error = "Unable to open an X11 connection";
6879 logevent("Opening X11 forward connection succeeded");
6884 } else if (typelen == 15 &&
6885 !memcmp(type, "forwarded-tcpip", 15)) {
6886 struct ssh_rportfwd pf, *realpf;
6889 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6890 pf.sport = ssh_pkt_getuint32(pktin);
6891 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6892 peerport = ssh_pkt_getuint32(pktin);
6893 realpf = find234(ssh->rportfwds, &pf, NULL);
6894 logeventf(ssh, "Received remote port %d open request "
6895 "from %s:%d", pf.sport, peeraddr, peerport);
6896 if (realpf == NULL) {
6897 error = "Remote port is not recognised";
6899 const char *e = pfd_newconnect(&c->u.pfd.s,
6903 realpf->pfrec->addressfamily);
6904 logeventf(ssh, "Attempting to forward remote port to "
6905 "%s:%d", realpf->dhost, realpf->dport);
6907 logeventf(ssh, "Port open failed: %s", e);
6908 error = "Port open failed";
6910 logevent("Forwarded port opened successfully");
6911 c->type = CHAN_SOCKDATA;
6914 } else if (typelen == 22 &&
6915 !memcmp(type, "auth-agent@openssh.com", 22)) {
6916 if (!ssh->agentfwd_enabled)
6917 error = "Agent forwarding is not enabled";
6919 c->type = CHAN_AGENT; /* identify channel type */
6920 c->u.a.lensofar = 0;
6923 error = "Unsupported channel type requested";
6926 c->remoteid = remid;
6927 c->halfopen = FALSE;
6929 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6930 ssh2_pkt_adduint32(pktout, c->remoteid);
6931 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
6932 ssh2_pkt_addstring(pktout, error);
6933 ssh2_pkt_addstring(pktout, "en"); /* language tag */
6934 ssh2_pkt_send(ssh, pktout);
6935 logeventf(ssh, "Rejected channel open: %s", error);
6938 ssh2_channel_init(c);
6939 c->v.v2.remwindow = winsize;
6940 c->v.v2.remmaxpkt = pktsize;
6941 add234(ssh->channels, c);
6942 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
6943 ssh2_pkt_adduint32(pktout, c->remoteid);
6944 ssh2_pkt_adduint32(pktout, c->localid);
6945 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
6946 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6947 ssh2_pkt_send(ssh, pktout);
6952 * Buffer banner messages for later display at some convenient point.
6954 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
6956 /* Arbitrary limit to prevent unbounded inflation of buffer */
6957 if (bufchain_size(&ssh->banner) <= 131072) {
6958 char *banner = NULL;
6960 ssh_pkt_getstring(pktin, &banner, &size);
6962 bufchain_add(&ssh->banner, banner, size);
6966 /* Helper function to deal with sending tty modes for "pty-req" */
6967 static void ssh2_send_ttymode(void *data, char *mode, char *val)
6969 struct Packet *pktout = (struct Packet *)data;
6971 unsigned int arg = 0;
6972 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
6973 if (i == lenof(ssh_ttymodes)) return;
6974 switch (ssh_ttymodes[i].type) {
6976 arg = ssh_tty_parse_specchar(val);
6979 arg = ssh_tty_parse_boolean(val);
6982 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
6983 ssh2_pkt_adduint32(pktout, arg);
6987 * Handle the SSH-2 userauth and connection layers.
6989 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
6990 struct Packet *pktin)
6992 struct do_ssh2_authconn_state {
6995 AUTH_TYPE_PUBLICKEY,
6996 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
6997 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
6999 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7000 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7002 int done_service_req;
7003 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7004 int tried_pubkey_config, done_agent;
7005 int kbd_inter_refused;
7007 prompts_t *cur_prompt;
7012 void *publickey_blob;
7013 int publickey_bloblen;
7014 int publickey_encrypted;
7015 char *publickey_algorithm;
7016 char *publickey_comment;
7017 unsigned char agent_request[5], *agent_response, *agentp;
7018 int agent_responselen;
7019 unsigned char *pkblob_in_agent;
7021 char *pkblob, *alg, *commentp;
7022 int pklen, alglen, commentlen;
7023 int siglen, retlen, len;
7024 char *q, *agentreq, *ret;
7026 int num_env, env_left, env_ok;
7027 struct Packet *pktout;
7029 crState(do_ssh2_authconn_state);
7031 crBegin(ssh->do_ssh2_authconn_crstate);
7033 s->done_service_req = FALSE;
7034 s->we_are_in = FALSE;
7035 if (!ssh->cfg.ssh_no_userauth) {
7037 * Request userauth protocol, and await a response to it.
7039 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7040 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7041 ssh2_pkt_send(ssh, s->pktout);
7042 crWaitUntilV(pktin);
7043 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7044 s->done_service_req = TRUE;
7046 if (!s->done_service_req) {
7048 * Request connection protocol directly, without authentication.
7050 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7051 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7052 ssh2_pkt_send(ssh, s->pktout);
7053 crWaitUntilV(pktin);
7054 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7055 s->we_are_in = TRUE; /* no auth required */
7057 bombout(("Server refused service request"));
7062 /* Arrange to be able to deal with any BANNERs that come in.
7063 * (We do this now as packets may come in during the next bit.) */
7064 bufchain_init(&ssh->banner);
7065 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7066 ssh2_msg_userauth_banner;
7069 * Misc one-time setup for authentication.
7071 s->publickey_blob = NULL;
7072 if (!s->we_are_in) {
7075 * Load the public half of any configured public key file
7078 if (!filename_is_null(ssh->cfg.keyfile)) {
7080 logeventf(ssh, "Reading private key file \"%.150s\"",
7081 filename_to_str(&ssh->cfg.keyfile));
7082 keytype = key_type(&ssh->cfg.keyfile);
7083 if (keytype == SSH_KEYTYPE_SSH2) {
7086 ssh2_userkey_loadpub(&ssh->cfg.keyfile,
7087 &s->publickey_algorithm,
7088 &s->publickey_bloblen,
7089 &s->publickey_comment, &error);
7090 if (s->publickey_blob) {
7091 s->publickey_encrypted =
7092 ssh2_userkey_encrypted(&ssh->cfg.keyfile, NULL);
7095 logeventf(ssh, "Unable to load private key (%s)",
7097 msgbuf = dupprintf("Unable to load private key file "
7098 "\"%.150s\" (%s)\r\n",
7099 filename_to_str(&ssh->cfg.keyfile),
7101 c_write_str(ssh, msgbuf);
7106 logeventf(ssh, "Unable to use this key file (%s)",
7107 key_type_to_str(keytype));
7108 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7110 filename_to_str(&ssh->cfg.keyfile),
7111 key_type_to_str(keytype));
7112 c_write_str(ssh, msgbuf);
7114 s->publickey_blob = NULL;
7119 * Find out about any keys Pageant has (but if there's a
7120 * public key configured, filter out all others).
7123 s->agent_response = NULL;
7124 s->pkblob_in_agent = NULL;
7125 if (ssh->cfg.tryagent && agent_exists()) {
7129 logevent("Pageant is running. Requesting keys.");
7131 /* Request the keys held by the agent. */
7132 PUT_32BIT(s->agent_request, 1);
7133 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7134 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7135 ssh_agent_callback, ssh)) {
7139 bombout(("Unexpected data from server while"
7140 " waiting for agent response"));
7143 } while (pktin || inlen > 0);
7144 r = ssh->agent_response;
7145 s->agent_responselen = ssh->agent_response_len;
7147 s->agent_response = (unsigned char *) r;
7148 if (s->agent_response && s->agent_responselen >= 5 &&
7149 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7152 p = s->agent_response + 5;
7153 s->nkeys = GET_32BIT(p);
7155 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7156 if (s->publickey_blob) {
7157 /* See if configured key is in agent. */
7158 for (keyi = 0; keyi < s->nkeys; keyi++) {
7159 s->pklen = GET_32BIT(p);
7160 if (s->pklen == s->publickey_bloblen &&
7161 !memcmp(p+4, s->publickey_blob,
7162 s->publickey_bloblen)) {
7163 logeventf(ssh, "Pageant key #%d matches "
7164 "configured key file", keyi);
7166 s->pkblob_in_agent = p;
7170 p += GET_32BIT(p) + 4; /* comment */
7172 if (!s->pkblob_in_agent) {
7173 logevent("Configured key file not in Pageant");
7183 * We repeat this whole loop, including the username prompt,
7184 * until we manage a successful authentication. If the user
7185 * types the wrong _password_, they can be sent back to the
7186 * beginning to try another username, if this is configured on.
7187 * (If they specify a username in the config, they are never
7188 * asked, even if they do give a wrong password.)
7190 * I think this best serves the needs of
7192 * - the people who have no configuration, no keys, and just
7193 * want to try repeated (username,password) pairs until they
7194 * type both correctly
7196 * - people who have keys and configuration but occasionally
7197 * need to fall back to passwords
7199 * - people with a key held in Pageant, who might not have
7200 * logged in to a particular machine before; so they want to
7201 * type a username, and then _either_ their key will be
7202 * accepted, _or_ they will type a password. If they mistype
7203 * the username they will want to be able to get back and
7206 s->username[0] = '\0';
7207 s->got_username = FALSE;
7208 while (!s->we_are_in) {
7212 if (s->got_username && !ssh->cfg.change_username) {
7214 * We got a username last time round this loop, and
7215 * with change_username turned off we don't try to get
7218 } else if (!*ssh->cfg.username) {
7219 int ret; /* need not be kept over crReturn */
7220 s->cur_prompt = new_prompts(ssh->frontend);
7221 s->cur_prompt->to_server = TRUE;
7222 s->cur_prompt->name = dupstr("SSH login name");
7223 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
7224 lenof(s->username));
7225 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7228 crWaitUntilV(!pktin);
7229 ret = get_userpass_input(s->cur_prompt, in, inlen);
7234 * get_userpass_input() failed to get a username.
7237 free_prompts(s->cur_prompt);
7238 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7241 memcpy(s->username, s->cur_prompt->prompts[0]->result,
7242 lenof(s->username));
7243 free_prompts(s->cur_prompt);
7246 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
7247 s->username[sizeof(s->username)-1] = '\0';
7248 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7249 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
7250 c_write_str(ssh, stuff);
7254 s->got_username = TRUE;
7257 * Send an authentication request using method "none": (a)
7258 * just in case it succeeds, and (b) so that we know what
7259 * authentication methods we can usefully try next.
7261 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7263 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7264 ssh2_pkt_addstring(s->pktout, s->username);
7265 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7266 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7267 ssh2_pkt_send(ssh, s->pktout);
7268 s->type = AUTH_TYPE_NONE;
7270 s->we_are_in = FALSE;
7272 s->tried_pubkey_config = FALSE;
7273 s->kbd_inter_refused = FALSE;
7275 /* Reset agent request state. */
7276 s->done_agent = FALSE;
7277 if (s->agent_response) {
7278 if (s->pkblob_in_agent) {
7279 s->agentp = s->pkblob_in_agent;
7281 s->agentp = s->agent_response + 5 + 4;
7288 * Wait for the result of the last authentication request.
7291 crWaitUntilV(pktin);
7293 * Now is a convenient point to spew any banner material
7294 * that we've accumulated. (This should ensure that when
7295 * we exit the auth loop, we haven't any left to deal
7299 int size = bufchain_size(&ssh->banner);
7301 * Don't show the banner if we're operating in
7302 * non-verbose non-interactive mode. (It's probably
7303 * a script, which means nobody will read the
7304 * banner _anyway_, and moreover the printing of
7305 * the banner will screw up processing on the
7306 * output of (say) plink.)
7308 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7309 char *banner = snewn(size, char);
7310 bufchain_fetch(&ssh->banner, banner, size);
7311 c_write_untrusted(ssh, banner, size);
7314 bufchain_clear(&ssh->banner);
7316 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7317 logevent("Access granted");
7318 s->we_are_in = TRUE;
7322 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
7323 bombout(("Strange packet received during authentication: "
7324 "type %d", pktin->type));
7331 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7332 * we can look at the string in it and know what we can
7333 * helpfully try next.
7335 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7338 ssh_pkt_getstring(pktin, &methods, &methlen);
7339 if (!ssh2_pkt_getbool(pktin)) {
7341 * We have received an unequivocal Access
7342 * Denied. This can translate to a variety of
7345 * - if we'd just tried "none" authentication,
7346 * it's not worth printing anything at all
7348 * - if we'd just tried a public key _offer_,
7349 * the message should be "Server refused our
7350 * key" (or no message at all if the key
7351 * came from Pageant)
7353 * - if we'd just tried anything else, the
7354 * message really should be "Access denied".
7356 * Additionally, if we'd just tried password
7357 * authentication, we should break out of this
7358 * whole loop so as to go back to the username
7359 * prompt (iff we're configured to allow
7360 * username change attempts).
7362 if (s->type == AUTH_TYPE_NONE) {
7364 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7365 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7366 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7367 c_write_str(ssh, "Server refused our key\r\n");
7368 logevent("Server refused public key");
7369 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7370 /* server declined keyboard-interactive; ignore */
7372 c_write_str(ssh, "Access denied\r\n");
7373 logevent("Access denied");
7374 if (s->type == AUTH_TYPE_PASSWORD &&
7375 ssh->cfg.change_username) {
7376 /* XXX perhaps we should allow
7377 * keyboard-interactive to do this too? */
7378 s->we_are_in = FALSE;
7383 c_write_str(ssh, "Further authentication required\r\n");
7384 logevent("Further authentication required");
7388 in_commasep_string("publickey", methods, methlen);
7390 in_commasep_string("password", methods, methlen);
7391 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
7392 in_commasep_string("keyboard-interactive", methods, methlen);
7395 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7397 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7400 * Attempt public-key authentication using a key from Pageant.
7403 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7405 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7407 /* Unpack key from agent response */
7408 s->pklen = GET_32BIT(s->agentp);
7410 s->pkblob = (char *)s->agentp;
7411 s->agentp += s->pklen;
7412 s->alglen = GET_32BIT(s->pkblob);
7413 s->alg = s->pkblob + 4;
7414 s->commentlen = GET_32BIT(s->agentp);
7416 s->commentp = (char *)s->agentp;
7417 s->agentp += s->commentlen;
7418 /* s->agentp now points at next key, if any */
7420 /* See if server will accept it */
7421 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7422 ssh2_pkt_addstring(s->pktout, s->username);
7423 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7424 /* service requested */
7425 ssh2_pkt_addstring(s->pktout, "publickey");
7427 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7428 ssh2_pkt_addstring_start(s->pktout);
7429 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7430 ssh2_pkt_addstring_start(s->pktout);
7431 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7432 ssh2_pkt_send(ssh, s->pktout);
7433 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7435 crWaitUntilV(pktin);
7436 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7438 /* Offer of key refused. */
7445 if (flags & FLAG_VERBOSE) {
7446 c_write_str(ssh, "Authenticating with "
7448 c_write(ssh, s->commentp, s->commentlen);
7449 c_write_str(ssh, "\" from agent\r\n");
7453 * Server is willing to accept the key.
7454 * Construct a SIGN_REQUEST.
7456 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7457 ssh2_pkt_addstring(s->pktout, s->username);
7458 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7459 /* service requested */
7460 ssh2_pkt_addstring(s->pktout, "publickey");
7462 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7463 ssh2_pkt_addstring_start(s->pktout);
7464 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7465 ssh2_pkt_addstring_start(s->pktout);
7466 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7468 /* Ask agent for signature. */
7469 s->siglen = s->pktout->length - 5 + 4 +
7470 ssh->v2_session_id_len;
7471 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7473 s->len = 1; /* message type */
7474 s->len += 4 + s->pklen; /* key blob */
7475 s->len += 4 + s->siglen; /* data to sign */
7476 s->len += 4; /* flags */
7477 s->agentreq = snewn(4 + s->len, char);
7478 PUT_32BIT(s->agentreq, s->len);
7479 s->q = s->agentreq + 4;
7480 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7481 PUT_32BIT(s->q, s->pklen);
7483 memcpy(s->q, s->pkblob, s->pklen);
7485 PUT_32BIT(s->q, s->siglen);
7487 /* Now the data to be signed... */
7488 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7489 PUT_32BIT(s->q, ssh->v2_session_id_len);
7492 memcpy(s->q, ssh->v2_session_id,
7493 ssh->v2_session_id_len);
7494 s->q += ssh->v2_session_id_len;
7495 memcpy(s->q, s->pktout->data + 5,
7496 s->pktout->length - 5);
7497 s->q += s->pktout->length - 5;
7498 /* And finally the (zero) flags word. */
7500 if (!agent_query(s->agentreq, s->len + 4,
7502 ssh_agent_callback, ssh)) {
7506 bombout(("Unexpected data from server"
7507 " while waiting for agent"
7511 } while (pktin || inlen > 0);
7512 vret = ssh->agent_response;
7513 s->retlen = ssh->agent_response_len;
7518 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7519 logevent("Sending Pageant's response");
7520 ssh2_add_sigblob(ssh, s->pktout,
7521 s->pkblob, s->pklen,
7523 GET_32BIT(s->ret + 5));
7524 ssh2_pkt_send(ssh, s->pktout);
7525 s->type = AUTH_TYPE_PUBLICKEY;
7527 /* FIXME: less drastic response */
7528 bombout(("Pageant failed to answer challenge"));
7534 /* Do we have any keys left to try? */
7535 if (s->pkblob_in_agent) {
7536 s->done_agent = TRUE;
7537 s->tried_pubkey_config = TRUE;
7540 if (s->keyi >= s->nkeys)
7541 s->done_agent = TRUE;
7544 } else if (s->can_pubkey && s->publickey_blob &&
7545 !s->tried_pubkey_config) {
7547 struct ssh2_userkey *key; /* not live over crReturn */
7548 char *passphrase; /* not live over crReturn */
7550 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7552 s->tried_pubkey_config = TRUE;
7555 * Try the public key supplied in the configuration.
7557 * First, offer the public blob to see if the server is
7558 * willing to accept it.
7560 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7561 ssh2_pkt_addstring(s->pktout, s->username);
7562 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7563 /* service requested */
7564 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
7565 ssh2_pkt_addbool(s->pktout, FALSE);
7566 /* no signature included */
7567 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
7568 ssh2_pkt_addstring_start(s->pktout);
7569 ssh2_pkt_addstring_data(s->pktout,
7570 (char *)s->publickey_blob,
7571 s->publickey_bloblen);
7572 ssh2_pkt_send(ssh, s->pktout);
7573 logevent("Offered public key");
7575 crWaitUntilV(pktin);
7576 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7577 /* Key refused. Give up. */
7578 s->gotit = TRUE; /* reconsider message next loop */
7579 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
7580 continue; /* process this new message */
7582 logevent("Offer of public key accepted");
7585 * Actually attempt a serious authentication using
7588 if (flags & FLAG_VERBOSE) {
7589 c_write_str(ssh, "Authenticating with public key \"");
7590 c_write_str(ssh, s->publickey_comment);
7591 c_write_str(ssh, "\"\r\n");
7595 const char *error; /* not live over crReturn */
7596 if (s->publickey_encrypted) {
7598 * Get a passphrase from the user.
7600 int ret; /* need not be kept over crReturn */
7601 s->cur_prompt = new_prompts(ssh->frontend);
7602 s->cur_prompt->to_server = FALSE;
7603 s->cur_prompt->name = dupstr("SSH key passphrase");
7604 add_prompt(s->cur_prompt,
7605 dupprintf("Passphrase for key \"%.100s\": ",
7606 s->publickey_comment),
7607 FALSE, SSH_MAX_PASSWORD_LEN);
7608 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7611 crWaitUntilV(!pktin);
7612 ret = get_userpass_input(s->cur_prompt,
7617 /* Failed to get a passphrase. Terminate. */
7618 free_prompts(s->cur_prompt);
7619 ssh_disconnect(ssh, NULL,
7620 "Unable to authenticate",
7621 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7626 dupstr(s->cur_prompt->prompts[0]->result);
7627 free_prompts(s->cur_prompt);
7629 passphrase = NULL; /* no passphrase needed */
7633 * Try decrypting the key.
7635 key = ssh2_load_userkey(&ssh->cfg.keyfile, passphrase,
7638 /* burn the evidence */
7639 memset(passphrase, 0, strlen(passphrase));
7642 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
7644 (key == SSH2_WRONG_PASSPHRASE)) {
7645 c_write_str(ssh, "Wrong passphrase\r\n");
7647 /* and loop again */
7649 c_write_str(ssh, "Unable to load private key (");
7650 c_write_str(ssh, error);
7651 c_write_str(ssh, ")\r\n");
7653 break; /* try something else */
7659 unsigned char *pkblob, *sigblob, *sigdata;
7660 int pkblob_len, sigblob_len, sigdata_len;
7664 * We have loaded the private key and the server
7665 * has announced that it's willing to accept it.
7666 * Hallelujah. Generate a signature and send it.
7668 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7669 ssh2_pkt_addstring(s->pktout, s->username);
7670 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7671 /* service requested */
7672 ssh2_pkt_addstring(s->pktout, "publickey");
7674 ssh2_pkt_addbool(s->pktout, TRUE);
7675 /* signature follows */
7676 ssh2_pkt_addstring(s->pktout, key->alg->name);
7677 pkblob = key->alg->public_blob(key->data,
7679 ssh2_pkt_addstring_start(s->pktout);
7680 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
7684 * The data to be signed is:
7688 * followed by everything so far placed in the
7691 sigdata_len = s->pktout->length - 5 + 4 +
7692 ssh->v2_session_id_len;
7693 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7695 sigdata = snewn(sigdata_len, unsigned char);
7697 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7698 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
7701 memcpy(sigdata+p, ssh->v2_session_id,
7702 ssh->v2_session_id_len);
7703 p += ssh->v2_session_id_len;
7704 memcpy(sigdata+p, s->pktout->data + 5,
7705 s->pktout->length - 5);
7706 p += s->pktout->length - 5;
7707 assert(p == sigdata_len);
7708 sigblob = key->alg->sign(key->data, (char *)sigdata,
7709 sigdata_len, &sigblob_len);
7710 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7711 sigblob, sigblob_len);
7716 ssh2_pkt_send(ssh, s->pktout);
7717 s->type = AUTH_TYPE_PUBLICKEY;
7718 key->alg->freekey(key->data);
7721 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
7724 * Keyboard-interactive authentication.
7727 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
7729 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
7731 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7732 ssh2_pkt_addstring(s->pktout, s->username);
7733 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7734 /* service requested */
7735 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
7737 ssh2_pkt_addstring(s->pktout, ""); /* lang */
7738 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
7739 ssh2_pkt_send(ssh, s->pktout);
7741 crWaitUntilV(pktin);
7742 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
7743 /* Server is not willing to do keyboard-interactive
7744 * at all (or, bizarrely but legally, accepts the
7745 * user without actually issuing any prompts).
7746 * Give up on it entirely. */
7748 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
7749 logevent("Keyboard-interactive authentication refused");
7750 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
7751 s->kbd_inter_refused = TRUE; /* don't try it again */
7756 * Loop while the server continues to send INFO_REQUESTs.
7758 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
7760 char *name, *inst, *lang;
7761 int name_len, inst_len, lang_len;
7765 * We've got a fresh USERAUTH_INFO_REQUEST.
7766 * Get the preamble and start building a prompt.
7768 ssh_pkt_getstring(pktin, &name, &name_len);
7769 ssh_pkt_getstring(pktin, &inst, &inst_len);
7770 ssh_pkt_getstring(pktin, &lang, &lang_len);
7771 s->cur_prompt = new_prompts(ssh->frontend);
7772 s->cur_prompt->to_server = TRUE;
7774 /* FIXME: better prefix to distinguish from
7776 s->cur_prompt->name =
7777 dupprintf("SSH server: %.*s", name_len, name);
7778 s->cur_prompt->name_reqd = TRUE;
7780 s->cur_prompt->name =
7781 dupstr("SSH server authentication");
7782 s->cur_prompt->name_reqd = FALSE;
7784 /* FIXME: ugly to print "Using..." in prompt _every_
7785 * time round. Can this be done more subtly? */
7786 s->cur_prompt->instruction =
7787 dupprintf("Using keyboard-interactive authentication.%s%.*s",
7788 inst_len ? "\n" : "", inst_len, inst);
7789 s->cur_prompt->instr_reqd = TRUE;
7792 * Get the prompts from the packet.
7794 s->num_prompts = ssh_pkt_getuint32(pktin);
7795 for (i = 0; i < s->num_prompts; i++) {
7799 static char noprompt[] =
7800 "<server failed to send prompt>: ";
7802 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
7803 echo = ssh2_pkt_getbool(pktin);
7806 prompt_len = lenof(noprompt)-1;
7808 add_prompt(s->cur_prompt,
7809 dupprintf("%.*s", prompt_len, prompt),
7810 echo, SSH_MAX_PASSWORD_LEN);
7814 * Get the user's responses.
7816 if (s->num_prompts) {
7817 int ret; /* not live over crReturn */
7818 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7821 crWaitUntilV(!pktin);
7822 ret = get_userpass_input(s->cur_prompt, in, inlen);
7827 * Failed to get responses. Terminate.
7829 free_prompts(s->cur_prompt);
7830 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7831 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7838 * Send the responses to the server.
7840 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
7841 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
7842 for (i=0; i < s->num_prompts; i++) {
7843 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7844 ssh2_pkt_addstring(s->pktout,
7845 s->cur_prompt->prompts[i]->result);
7846 end_log_omission(ssh, s->pktout);
7848 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7851 * Get the next packet in case it's another
7854 crWaitUntilV(pktin);
7859 * We should have SUCCESS or FAILURE now.
7863 } else if (s->can_passwd) {
7866 * Plain old password authentication.
7868 int ret; /* not live over crReturn */
7869 int changereq_first_time; /* not live over crReturn */
7871 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
7873 s->cur_prompt = new_prompts(ssh->frontend);
7874 s->cur_prompt->to_server = TRUE;
7875 s->cur_prompt->name = dupstr("SSH password");
7876 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
7879 FALSE, SSH_MAX_PASSWORD_LEN);
7881 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7884 crWaitUntilV(!pktin);
7885 ret = get_userpass_input(s->cur_prompt, in, inlen);
7890 * Failed to get responses. Terminate.
7892 free_prompts(s->cur_prompt);
7893 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7894 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7899 * Squirrel away the password. (We may need it later if
7900 * asked to change it.)
7902 s->password = dupstr(s->cur_prompt->prompts[0]->result);
7903 free_prompts(s->cur_prompt);
7906 * Send the password packet.
7908 * We pad out the password packet to 256 bytes to make
7909 * it harder for an attacker to find the length of the
7912 * Anyone using a password longer than 256 bytes
7913 * probably doesn't have much to worry about from
7914 * people who find out how long their password is!
7916 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7917 ssh2_pkt_addstring(s->pktout, s->username);
7918 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7919 /* service requested */
7920 ssh2_pkt_addstring(s->pktout, "password");
7921 ssh2_pkt_addbool(s->pktout, FALSE);
7922 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7923 ssh2_pkt_addstring(s->pktout, s->password);
7924 end_log_omission(ssh, s->pktout);
7925 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7926 logevent("Sent password");
7927 s->type = AUTH_TYPE_PASSWORD;
7930 * Wait for next packet, in case it's a password change
7933 crWaitUntilV(pktin);
7934 changereq_first_time = TRUE;
7936 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
7939 * We're being asked for a new password
7940 * (perhaps not for the first time).
7941 * Loop until the server accepts it.
7944 int got_new = FALSE; /* not live over crReturn */
7945 char *prompt; /* not live over crReturn */
7946 int prompt_len; /* not live over crReturn */
7950 if (changereq_first_time)
7951 msg = "Server requested password change";
7953 msg = "Server rejected new password";
7955 c_write_str(ssh, msg);
7956 c_write_str(ssh, "\r\n");
7959 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
7961 s->cur_prompt = new_prompts(ssh->frontend);
7962 s->cur_prompt->to_server = TRUE;
7963 s->cur_prompt->name = dupstr("New SSH password");
7964 s->cur_prompt->instruction =
7965 dupprintf("%.*s", prompt_len, prompt);
7966 s->cur_prompt->instr_reqd = TRUE;
7968 * There's no explicit requirement in the protocol
7969 * for the "old" passwords in the original and
7970 * password-change messages to be the same, and
7971 * apparently some Cisco kit supports password change
7972 * by the user entering a blank password originally
7973 * and the real password subsequently, so,
7974 * reluctantly, we prompt for the old password again.
7976 * (On the other hand, some servers don't even bother
7977 * to check this field.)
7979 add_prompt(s->cur_prompt,
7980 dupstr("Current password (blank for previously entered password): "),
7981 FALSE, SSH_MAX_PASSWORD_LEN);
7982 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
7983 FALSE, SSH_MAX_PASSWORD_LEN);
7984 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
7985 FALSE, SSH_MAX_PASSWORD_LEN);
7988 * Loop until the user manages to enter the same
7993 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7996 crWaitUntilV(!pktin);
7997 ret = get_userpass_input(s->cur_prompt, in, inlen);
8002 * Failed to get responses. Terminate.
8004 /* burn the evidence */
8005 free_prompts(s->cur_prompt);
8006 memset(s->password, 0, strlen(s->password));
8008 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8009 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8015 * If the user specified a new original password
8016 * (IYSWIM), overwrite any previously specified
8018 * (A side effect is that the user doesn't have to
8019 * re-enter it if they louse up the new password.)
8021 if (s->cur_prompt->prompts[0]->result[0]) {
8022 memset(s->password, 0, strlen(s->password));
8023 /* burn the evidence */
8026 dupstr(s->cur_prompt->prompts[0]->result);
8030 * Check the two new passwords match.
8032 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8033 s->cur_prompt->prompts[2]->result)
8036 /* They don't. Silly user. */
8037 c_write_str(ssh, "Passwords do not match\r\n");
8042 * Send the new password (along with the old one).
8043 * (see above for padding rationale)
8045 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8046 ssh2_pkt_addstring(s->pktout, s->username);
8047 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8048 /* service requested */
8049 ssh2_pkt_addstring(s->pktout, "password");
8050 ssh2_pkt_addbool(s->pktout, TRUE);
8051 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8052 ssh2_pkt_addstring(s->pktout, s->password);
8053 ssh2_pkt_addstring(s->pktout,
8054 s->cur_prompt->prompts[1]->result);
8055 free_prompts(s->cur_prompt);
8056 end_log_omission(ssh, s->pktout);
8057 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8058 logevent("Sent new password");
8061 * Now see what the server has to say about it.
8062 * (If it's CHANGEREQ again, it's not happy with the
8065 crWaitUntilV(pktin);
8066 changereq_first_time = FALSE;
8071 * We need to reexamine the current pktin at the top
8072 * of the loop. Either:
8073 * - we weren't asked to change password at all, in
8074 * which case it's a SUCCESS or FAILURE with the
8076 * - we sent a new password, and the server was
8077 * either OK with it (SUCCESS or FAILURE w/partial
8078 * success) or unhappy with the _old_ password
8079 * (FAILURE w/o partial success)
8080 * In any of these cases, we go back to the top of
8081 * the loop and start again.
8086 * We don't need the old password any more, in any
8087 * case. Burn the evidence.
8089 memset(s->password, 0, strlen(s->password));
8094 ssh_disconnect(ssh, NULL,
8095 "No supported authentication methods available",
8096 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8104 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8106 /* Clear up various bits and pieces from authentication. */
8107 if (s->publickey_blob) {
8108 sfree(s->publickey_blob);
8109 sfree(s->publickey_comment);
8111 if (s->agent_response)
8112 sfree(s->agent_response);
8115 * Now the connection protocol has started, one way or another.
8118 ssh->channels = newtree234(ssh_channelcmp);
8121 * Set up handlers for some connection protocol messages, so we
8122 * don't have to handle them repeatedly in this coroutine.
8124 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8125 ssh2_msg_channel_window_adjust;
8126 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8127 ssh2_msg_global_request;
8130 * Create the main session channel.
8132 if (ssh->cfg.ssh_no_shell) {
8133 ssh->mainchan = NULL;
8134 } else if (*ssh->cfg.ssh_nc_host) {
8136 * Just start a direct-tcpip channel and use it as the main
8139 ssh->mainchan = snew(struct ssh_channel);
8140 ssh->mainchan->ssh = ssh;
8141 ssh2_channel_init(ssh->mainchan);
8143 "Opening direct-tcpip channel to %s:%d in place of session",
8144 ssh->cfg.ssh_nc_host, ssh->cfg.ssh_nc_port);
8145 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8146 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8147 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8148 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8149 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8150 ssh2_pkt_addstring(s->pktout, ssh->cfg.ssh_nc_host);
8151 ssh2_pkt_adduint32(s->pktout, ssh->cfg.ssh_nc_port);
8153 * There's nothing meaningful to put in the originator
8154 * fields, but some servers insist on syntactically correct
8157 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8158 ssh2_pkt_adduint32(s->pktout, 0);
8159 ssh2_pkt_send(ssh, s->pktout);
8161 crWaitUntilV(pktin);
8162 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8163 bombout(("Server refused to open a direct-tcpip channel"));
8165 /* FIXME: error data comes back in FAILURE packet */
8167 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8168 bombout(("Server's channel confirmation cited wrong channel"));
8171 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8172 ssh->mainchan->halfopen = FALSE;
8173 ssh->mainchan->type = CHAN_MAINSESSION;
8174 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8175 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8176 add234(ssh->channels, ssh->mainchan);
8177 update_specials_menu(ssh->frontend);
8178 logevent("Opened direct-tcpip channel");
8181 ssh->mainchan = snew(struct ssh_channel);
8182 ssh->mainchan->ssh = ssh;
8183 ssh2_channel_init(ssh->mainchan);
8184 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8185 ssh2_pkt_addstring(s->pktout, "session");
8186 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8187 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8188 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8189 ssh2_pkt_send(ssh, s->pktout);
8190 crWaitUntilV(pktin);
8191 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8192 bombout(("Server refused to open a session"));
8194 /* FIXME: error data comes back in FAILURE packet */
8196 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8197 bombout(("Server's channel confirmation cited wrong channel"));
8200 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8201 ssh->mainchan->halfopen = FALSE;
8202 ssh->mainchan->type = CHAN_MAINSESSION;
8203 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8204 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8205 add234(ssh->channels, ssh->mainchan);
8206 update_specials_menu(ssh->frontend);
8207 logevent("Opened channel for session");
8208 ssh->ncmode = FALSE;
8212 * Now we have a channel, make dispatch table entries for
8213 * general channel-based messages.
8215 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8216 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8217 ssh2_msg_channel_data;
8218 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8219 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8220 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8221 ssh2_msg_channel_open_confirmation;
8222 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8223 ssh2_msg_channel_open_failure;
8224 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8225 ssh2_msg_channel_request;
8226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8227 ssh2_msg_channel_open;
8229 if (ssh->cfg.ssh_simple) {
8231 * This message indicates to the server that we promise
8232 * not to try to run any other channel in parallel with
8233 * this one, so it's safe for it to advertise a very large
8234 * window and leave the flow control to TCP.
8236 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8237 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8238 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8239 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8240 ssh2_pkt_send(ssh, s->pktout);
8244 * Potentially enable X11 forwarding.
8246 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.x11_forward) {
8247 char proto[20], data[64];
8248 logevent("Requesting X11 forwarding");
8249 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
8250 data, sizeof(data), ssh->cfg.x11_auth);
8251 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
8252 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8253 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8254 ssh2_pkt_addstring(s->pktout, "x11-req");
8255 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8256 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8257 ssh2_pkt_addstring(s->pktout, proto);
8259 * Note that while we blank the X authentication data here, we don't
8260 * take any special action to blank the start of an X11 channel,
8261 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8262 * without having session blanking enabled is likely to leak your
8263 * cookie into the log.
8265 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8266 ssh2_pkt_addstring(s->pktout, data);
8267 end_log_omission(ssh, s->pktout);
8268 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
8269 ssh2_pkt_send(ssh, s->pktout);
8271 crWaitUntilV(pktin);
8273 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8274 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8275 bombout(("Unexpected response to X11 forwarding request:"
8276 " packet type %d", pktin->type));
8279 logevent("X11 forwarding refused");
8281 logevent("X11 forwarding enabled");
8282 ssh->X11_fwd_enabled = TRUE;
8287 * Enable port forwardings.
8289 ssh_setup_portfwd(ssh, &ssh->cfg);
8292 * Potentially enable agent forwarding.
8294 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.agentfwd && agent_exists()) {
8295 logevent("Requesting OpenSSH-style agent forwarding");
8296 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8297 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8298 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8299 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8300 ssh2_pkt_send(ssh, s->pktout);
8302 crWaitUntilV(pktin);
8304 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8305 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8306 bombout(("Unexpected response to agent forwarding request:"
8307 " packet type %d", pktin->type));
8310 logevent("Agent forwarding refused");
8312 logevent("Agent forwarding enabled");
8313 ssh->agentfwd_enabled = TRUE;
8318 * Now allocate a pty for the session.
8320 if (ssh->mainchan && !ssh->ncmode && !ssh->cfg.nopty) {
8321 /* Unpick the terminal-speed string. */
8322 /* XXX perhaps we should allow no speeds to be sent. */
8323 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8324 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
8325 /* Build the pty request. */
8326 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8327 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8328 ssh2_pkt_addstring(s->pktout, "pty-req");
8329 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8330 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
8331 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8332 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8333 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8334 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8335 ssh2_pkt_addstring_start(s->pktout);
8336 parse_ttymodes(ssh, ssh->cfg.ttymodes,
8337 ssh2_send_ttymode, (void *)s->pktout);
8338 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
8339 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
8340 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
8341 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
8342 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
8343 ssh2_pkt_send(ssh, s->pktout);
8344 ssh->state = SSH_STATE_INTERMED;
8346 crWaitUntilV(pktin);
8348 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8349 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8350 bombout(("Unexpected response to pty request:"
8351 " packet type %d", pktin->type));
8354 c_write_str(ssh, "Server refused to allocate pty\r\n");
8355 ssh->editing = ssh->echoing = 1;
8357 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8358 ssh->ospeed, ssh->ispeed);
8361 ssh->editing = ssh->echoing = 1;
8365 * Send environment variables.
8367 * Simplest thing here is to send all the requests at once, and
8368 * then wait for a whole bunch of successes or failures.
8370 if (ssh->mainchan && !ssh->ncmode && *ssh->cfg.environmt) {
8371 char *e = ssh->cfg.environmt;
8372 char *var, *varend, *val;
8378 while (*e && *e != '\t') e++;
8380 if (*e == '\t') e++;
8385 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8386 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8387 ssh2_pkt_addstring(s->pktout, "env");
8388 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8389 ssh2_pkt_addstring_start(s->pktout);
8390 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
8391 ssh2_pkt_addstring(s->pktout, val);
8392 ssh2_pkt_send(ssh, s->pktout);
8397 logeventf(ssh, "Sent %d environment variables", s->num_env);
8400 s->env_left = s->num_env;
8402 while (s->env_left > 0) {
8403 crWaitUntilV(pktin);
8405 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8406 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8407 bombout(("Unexpected response to environment request:"
8408 " packet type %d", pktin->type));
8418 if (s->env_ok == s->num_env) {
8419 logevent("All environment variables successfully set");
8420 } else if (s->env_ok == 0) {
8421 logevent("All environment variables refused");
8422 c_write_str(ssh, "Server refused to set environment variables\r\n");
8424 logeventf(ssh, "%d environment variables refused",
8425 s->num_env - s->env_ok);
8426 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8431 * Start a shell or a remote command. We may have to attempt
8432 * this twice if the config data has provided a second choice
8435 if (ssh->mainchan && !ssh->ncmode) while (1) {
8439 if (ssh->fallback_cmd) {
8440 subsys = ssh->cfg.ssh_subsys2;
8441 cmd = ssh->cfg.remote_cmd_ptr2;
8443 subsys = ssh->cfg.ssh_subsys;
8444 cmd = ssh->cfg.remote_cmd_ptr;
8445 if (!cmd) cmd = ssh->cfg.remote_cmd;
8448 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8449 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8451 ssh2_pkt_addstring(s->pktout, "subsystem");
8452 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8453 ssh2_pkt_addstring(s->pktout, cmd);
8455 ssh2_pkt_addstring(s->pktout, "exec");
8456 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8457 ssh2_pkt_addstring(s->pktout, cmd);
8459 ssh2_pkt_addstring(s->pktout, "shell");
8460 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8462 ssh2_pkt_send(ssh, s->pktout);
8464 crWaitUntilV(pktin);
8466 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8467 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8468 bombout(("Unexpected response to shell/command request:"
8469 " packet type %d", pktin->type));
8473 * We failed to start the command. If this is the
8474 * fallback command, we really are finished; if it's
8475 * not, and if the fallback command exists, try falling
8476 * back to it before complaining.
8478 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
8479 logevent("Primary command failed; attempting fallback");
8480 ssh->fallback_cmd = TRUE;
8483 bombout(("Server refused to start a shell/command"));
8486 logevent("Started a shell/command");
8491 ssh->state = SSH_STATE_SESSION;
8492 if (ssh->size_needed)
8493 ssh_size(ssh, ssh->term_width, ssh->term_height);
8494 if (ssh->eof_needed)
8495 ssh_special(ssh, TS_EOF);
8498 * All the initial channel requests are done, so install the default
8501 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
8502 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
8508 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
8513 s->try_send = FALSE;
8517 * _All_ the connection-layer packets we expect to
8518 * receive are now handled by the dispatch table.
8519 * Anything that reaches here must be bogus.
8522 bombout(("Strange packet received: type %d", pktin->type));
8524 } else if (ssh->mainchan) {
8526 * We have spare data. Add it to the channel buffer.
8528 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
8533 struct ssh_channel *c;
8535 * Try to send data on all channels if we can.
8537 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
8538 ssh2_try_send_and_unthrottle(c);
8546 * Handlers for SSH-2 messages that might arrive at any moment.
8548 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
8550 /* log reason code in disconnect message */
8552 int nowlen, reason, msglen;
8554 reason = ssh_pkt_getuint32(pktin);
8555 ssh_pkt_getstring(pktin, &msg, &msglen);
8557 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
8558 buf = dupprintf("Received disconnect message (%s)",
8559 ssh2_disconnect_reasons[reason]);
8561 buf = dupprintf("Received disconnect message (unknown"
8562 " type %d)", reason);
8566 buf = dupprintf("Disconnection message text: %n%.*s",
8567 &nowlen, msglen, msg);
8569 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
8571 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
8572 ssh2_disconnect_reasons[reason] : "unknown",
8577 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
8579 /* log the debug message */
8584 /* XXX maybe we should actually take notice of this */
8585 always_display = ssh2_pkt_getbool(pktin);
8586 ssh_pkt_getstring(pktin, &msg, &msglen);
8588 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
8591 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
8593 struct Packet *pktout;
8594 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
8595 ssh2_pkt_adduint32(pktout, pktin->sequence);
8597 * UNIMPLEMENTED messages MUST appear in the same order as the
8598 * messages they respond to. Hence, never queue them.
8600 ssh2_pkt_send_noqueue(ssh, pktout);
8604 * Handle the top-level SSH-2 protocol.
8606 static void ssh2_protocol_setup(Ssh ssh)
8611 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
8613 for (i = 0; i < 256; i++)
8614 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
8617 * Any message we actually understand, we set to NULL so that
8618 * the coroutines will get it.
8620 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
8621 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
8622 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
8623 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
8624 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
8625 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
8626 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
8627 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
8628 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
8629 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
8630 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
8631 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
8632 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
8633 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
8634 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8635 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
8636 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
8637 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
8638 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
8639 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
8640 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
8641 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
8642 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
8643 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
8644 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
8645 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
8646 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
8647 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
8648 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
8649 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
8650 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
8651 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
8652 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
8655 * These special message types we install handlers for.
8657 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
8658 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
8659 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
8662 static void ssh2_timer(void *ctx, long now)
8666 if (ssh->state == SSH_STATE_CLOSED)
8669 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
8670 now - ssh->next_rekey >= 0) {
8671 do_ssh2_transport(ssh, "timeout", -1, NULL);
8675 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
8676 struct Packet *pktin)
8678 unsigned char *in = (unsigned char *)vin;
8679 if (ssh->state == SSH_STATE_CLOSED)
8683 ssh->incoming_data_size += pktin->encrypted_len;
8684 if (!ssh->kex_in_progress &&
8685 ssh->max_data_size != 0 &&
8686 ssh->incoming_data_size > ssh->max_data_size)
8687 do_ssh2_transport(ssh, "too much data received", -1, NULL);
8690 if (pktin && ssh->packet_dispatch[pktin->type]) {
8691 ssh->packet_dispatch[pktin->type](ssh, pktin);
8695 if (!ssh->protocol_initial_phase_done ||
8696 (pktin && pktin->type >= 20 && pktin->type < 50)) {
8697 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
8698 !ssh->protocol_initial_phase_done) {
8699 ssh->protocol_initial_phase_done = TRUE;
8701 * Allow authconn to initialise itself.
8703 do_ssh2_authconn(ssh, NULL, 0, NULL);
8706 do_ssh2_authconn(ssh, in, inlen, pktin);
8711 * Called to set up the connection.
8713 * Returns an error message, or NULL on success.
8715 static const char *ssh_init(void *frontend_handle, void **backend_handle,
8717 char *host, int port, char **realhost, int nodelay,
8723 ssh = snew(struct ssh_tag);
8724 ssh->cfg = *cfg; /* STRUCTURE COPY */
8725 ssh->version = 0; /* when not ready yet */
8728 ssh->v1_cipher_ctx = NULL;
8729 ssh->crcda_ctx = NULL;
8730 ssh->cscipher = NULL;
8731 ssh->cs_cipher_ctx = NULL;
8732 ssh->sccipher = NULL;
8733 ssh->sc_cipher_ctx = NULL;
8735 ssh->cs_mac_ctx = NULL;
8737 ssh->sc_mac_ctx = NULL;
8739 ssh->cs_comp_ctx = NULL;
8741 ssh->sc_comp_ctx = NULL;
8743 ssh->kex_ctx = NULL;
8744 ssh->hostkey = NULL;
8746 ssh->close_expected = FALSE;
8747 ssh->clean_exit = FALSE;
8748 ssh->state = SSH_STATE_PREPACKET;
8749 ssh->size_needed = FALSE;
8750 ssh->eof_needed = FALSE;
8753 ssh->deferred_send_data = NULL;
8754 ssh->deferred_len = 0;
8755 ssh->deferred_size = 0;
8756 ssh->fallback_cmd = 0;
8757 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
8758 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8759 ssh->x11auth = NULL;
8760 ssh->v1_compressing = FALSE;
8761 ssh->v2_outgoing_sequence = 0;
8762 ssh->ssh1_rdpkt_crstate = 0;
8763 ssh->ssh2_rdpkt_crstate = 0;
8764 ssh->do_ssh_init_crstate = 0;
8765 ssh->ssh_gotdata_crstate = 0;
8766 ssh->do_ssh1_connection_crstate = 0;
8767 ssh->do_ssh1_login_crstate = 0;
8768 ssh->do_ssh2_transport_crstate = 0;
8769 ssh->do_ssh2_authconn_crstate = 0;
8770 ssh->do_ssh_init_state = NULL;
8771 ssh->do_ssh1_login_state = NULL;
8772 ssh->do_ssh2_transport_state = NULL;
8773 ssh->do_ssh2_authconn_state = NULL;
8776 ssh->mainchan = NULL;
8777 ssh->throttled_all = 0;
8778 ssh->v1_stdout_throttling = 0;
8780 ssh->queuelen = ssh->queuesize = 0;
8781 ssh->queueing = FALSE;
8782 ssh->qhead = ssh->qtail = NULL;
8783 ssh->deferred_rekey_reason = NULL;
8784 bufchain_init(&ssh->queued_incoming_data);
8785 ssh->frozen = FALSE;
8787 *backend_handle = ssh;
8790 if (crypto_startup() == 0)
8791 return "Microsoft high encryption pack not installed!";
8794 ssh->frontend = frontend_handle;
8795 ssh->term_width = ssh->cfg.width;
8796 ssh->term_height = ssh->cfg.height;
8798 ssh->channels = NULL;
8799 ssh->rportfwds = NULL;
8800 ssh->portfwds = NULL;
8805 ssh->conn_throttle_count = 0;
8806 ssh->overall_bufsize = 0;
8807 ssh->fallback_cmd = 0;
8809 ssh->protocol = NULL;
8811 ssh->protocol_initial_phase_done = FALSE;
8815 ssh->incoming_data_size = ssh->outgoing_data_size =
8816 ssh->deferred_data_size = 0L;
8817 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
8818 ssh->kex_in_progress = FALSE;
8820 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
8829 static void ssh_free(void *handle)
8831 Ssh ssh = (Ssh) handle;
8832 struct ssh_channel *c;
8833 struct ssh_rportfwd *pf;
8835 if (ssh->v1_cipher_ctx)
8836 ssh->cipher->free_context(ssh->v1_cipher_ctx);
8837 if (ssh->cs_cipher_ctx)
8838 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
8839 if (ssh->sc_cipher_ctx)
8840 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
8841 if (ssh->cs_mac_ctx)
8842 ssh->csmac->free_context(ssh->cs_mac_ctx);
8843 if (ssh->sc_mac_ctx)
8844 ssh->scmac->free_context(ssh->sc_mac_ctx);
8845 if (ssh->cs_comp_ctx) {
8847 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
8849 zlib_compress_cleanup(ssh->cs_comp_ctx);
8851 if (ssh->sc_comp_ctx) {
8853 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
8855 zlib_decompress_cleanup(ssh->sc_comp_ctx);
8858 dh_cleanup(ssh->kex_ctx);
8859 sfree(ssh->savedhost);
8861 while (ssh->queuelen-- > 0)
8862 ssh_free_packet(ssh->queue[ssh->queuelen]);
8865 while (ssh->qhead) {
8866 struct queued_handler *qh = ssh->qhead;
8867 ssh->qhead = qh->next;
8870 ssh->qhead = ssh->qtail = NULL;
8872 if (ssh->channels) {
8873 while ((c = delpos234(ssh->channels, 0)) != NULL) {
8876 if (c->u.x11.s != NULL)
8877 x11_close(c->u.x11.s);
8880 if (c->u.pfd.s != NULL)
8881 pfd_close(c->u.pfd.s);
8886 freetree234(ssh->channels);
8887 ssh->channels = NULL;
8890 if (ssh->rportfwds) {
8891 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
8893 freetree234(ssh->rportfwds);
8894 ssh->rportfwds = NULL;
8896 sfree(ssh->deferred_send_data);
8898 x11_free_auth(ssh->x11auth);
8899 sfree(ssh->do_ssh_init_state);
8900 sfree(ssh->do_ssh1_login_state);
8901 sfree(ssh->do_ssh2_transport_state);
8902 sfree(ssh->do_ssh2_authconn_state);
8905 if (ssh->crcda_ctx) {
8906 crcda_free_context(ssh->crcda_ctx);
8907 ssh->crcda_ctx = NULL;
8910 ssh_do_close(ssh, TRUE);
8911 expire_timer_context(ssh);
8913 pinger_free(ssh->pinger);
8914 bufchain_clear(&ssh->queued_incoming_data);
8921 * Reconfigure the SSH backend.
8923 static void ssh_reconfig(void *handle, Config *cfg)
8925 Ssh ssh = (Ssh) handle;
8926 char *rekeying = NULL, rekey_mandatory = FALSE;
8927 unsigned long old_max_data_size;
8929 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
8931 ssh_setup_portfwd(ssh, cfg);
8933 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
8934 cfg->ssh_rekey_time != 0) {
8935 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
8936 long now = GETTICKCOUNT();
8938 if (new_next - now < 0) {
8939 rekeying = "timeout shortened";
8941 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
8945 old_max_data_size = ssh->max_data_size;
8946 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
8947 if (old_max_data_size != ssh->max_data_size &&
8948 ssh->max_data_size != 0) {
8949 if (ssh->outgoing_data_size > ssh->max_data_size ||
8950 ssh->incoming_data_size > ssh->max_data_size)
8951 rekeying = "data limit lowered";
8954 if (ssh->cfg.compression != cfg->compression) {
8955 rekeying = "compression setting changed";
8956 rekey_mandatory = TRUE;
8959 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
8960 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
8961 sizeof(ssh->cfg.ssh_cipherlist))) {
8962 rekeying = "cipher settings changed";
8963 rekey_mandatory = TRUE;
8966 ssh->cfg = *cfg; /* STRUCTURE COPY */
8969 if (!ssh->kex_in_progress) {
8970 do_ssh2_transport(ssh, rekeying, -1, NULL);
8971 } else if (rekey_mandatory) {
8972 ssh->deferred_rekey_reason = rekeying;
8978 * Called to send data down the SSH connection.
8980 static int ssh_send(void *handle, char *buf, int len)
8982 Ssh ssh = (Ssh) handle;
8984 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
8987 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
8989 return ssh_sendbuffer(ssh);
8993 * Called to query the current amount of buffered stdin data.
8995 static int ssh_sendbuffer(void *handle)
8997 Ssh ssh = (Ssh) handle;
9000 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9004 * If the SSH socket itself has backed up, add the total backup
9005 * size on that to any individual buffer on the stdin channel.
9008 if (ssh->throttled_all)
9009 override_value = ssh->overall_bufsize;
9011 if (ssh->version == 1) {
9012 return override_value;
9013 } else if (ssh->version == 2) {
9014 if (!ssh->mainchan || ssh->mainchan->closes > 0)
9015 return override_value;
9017 return (override_value +
9018 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9025 * Called to set the size of the window from SSH's POV.
9027 static void ssh_size(void *handle, int width, int height)
9029 Ssh ssh = (Ssh) handle;
9030 struct Packet *pktout;
9032 ssh->term_width = width;
9033 ssh->term_height = height;
9035 switch (ssh->state) {
9036 case SSH_STATE_BEFORE_SIZE:
9037 case SSH_STATE_PREPACKET:
9038 case SSH_STATE_CLOSED:
9039 break; /* do nothing */
9040 case SSH_STATE_INTERMED:
9041 ssh->size_needed = TRUE; /* buffer for later */
9043 case SSH_STATE_SESSION:
9044 if (!ssh->cfg.nopty) {
9045 if (ssh->version == 1) {
9046 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9047 PKT_INT, ssh->term_height,
9048 PKT_INT, ssh->term_width,
9049 PKT_INT, 0, PKT_INT, 0, PKT_END);
9050 } else if (ssh->mainchan) {
9051 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9052 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9053 ssh2_pkt_addstring(pktout, "window-change");
9054 ssh2_pkt_addbool(pktout, 0);
9055 ssh2_pkt_adduint32(pktout, ssh->term_width);
9056 ssh2_pkt_adduint32(pktout, ssh->term_height);
9057 ssh2_pkt_adduint32(pktout, 0);
9058 ssh2_pkt_adduint32(pktout, 0);
9059 ssh2_pkt_send(ssh, pktout);
9067 * Return a list of the special codes that make sense in this
9070 static const struct telnet_special *ssh_get_specials(void *handle)
9072 static const struct telnet_special ssh1_ignore_special[] = {
9073 {"IGNORE message", TS_NOP}
9075 static const struct telnet_special ssh2_transport_specials[] = {
9076 {"IGNORE message", TS_NOP},
9077 {"Repeat key exchange", TS_REKEY},
9079 static const struct telnet_special ssh2_session_specials[] = {
9082 /* These are the signal names defined by RFC 4254.
9083 * They include all the ISO C signals, but are a subset of the POSIX
9084 * required signals. */
9085 {"SIGINT (Interrupt)", TS_SIGINT},
9086 {"SIGTERM (Terminate)", TS_SIGTERM},
9087 {"SIGKILL (Kill)", TS_SIGKILL},
9088 {"SIGQUIT (Quit)", TS_SIGQUIT},
9089 {"SIGHUP (Hangup)", TS_SIGHUP},
9090 {"More signals", TS_SUBMENU},
9091 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9092 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9093 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9094 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9097 static const struct telnet_special specials_end[] = {
9100 /* XXX review this length for any changes: */
9101 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
9102 lenof(ssh2_session_specials) +
9103 lenof(specials_end)];
9104 Ssh ssh = (Ssh) handle;
9106 #define ADD_SPECIALS(name) \
9108 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9109 memcpy(&ssh_specials[i], name, sizeof name); \
9113 if (ssh->version == 1) {
9114 /* Don't bother offering IGNORE if we've decided the remote
9115 * won't cope with it, since we wouldn't bother sending it if
9117 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9118 ADD_SPECIALS(ssh1_ignore_special);
9119 } else if (ssh->version == 2) {
9120 ADD_SPECIALS(ssh2_transport_specials);
9122 ADD_SPECIALS(ssh2_session_specials);
9123 } /* else we're not ready yet */
9126 ADD_SPECIALS(specials_end);
9127 return ssh_specials;
9135 * Send special codes. TS_EOF is useful for `plink', so you
9136 * can send an EOF and collect resulting output (e.g. `plink
9139 static void ssh_special(void *handle, Telnet_Special code)
9141 Ssh ssh = (Ssh) handle;
9142 struct Packet *pktout;
9144 if (code == TS_EOF) {
9145 if (ssh->state != SSH_STATE_SESSION) {
9147 * Buffer the EOF in case we are pre-SESSION, so we can
9148 * send it as soon as we reach SESSION.
9151 ssh->eof_needed = TRUE;
9154 if (ssh->version == 1) {
9155 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9156 } else if (ssh->mainchan) {
9157 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
9158 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9159 ssh2_pkt_send(ssh, pktout);
9160 ssh->send_ok = 0; /* now stop trying to read from stdin */
9162 logevent("Sent EOF message");
9163 } else if (code == TS_PING || code == TS_NOP) {
9164 if (ssh->state == SSH_STATE_CLOSED
9165 || ssh->state == SSH_STATE_PREPACKET) return;
9166 if (ssh->version == 1) {
9167 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9168 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9170 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9171 ssh2_pkt_addstring_start(pktout);
9172 ssh2_pkt_send_noqueue(ssh, pktout);
9174 } else if (code == TS_REKEY) {
9175 if (!ssh->kex_in_progress && ssh->version == 2) {
9176 do_ssh2_transport(ssh, "at user request", -1, NULL);
9178 } else if (code == TS_BRK) {
9179 if (ssh->state == SSH_STATE_CLOSED
9180 || ssh->state == SSH_STATE_PREPACKET) return;
9181 if (ssh->version == 1) {
9182 logevent("Unable to send BREAK signal in SSH-1");
9183 } else if (ssh->mainchan) {
9184 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9185 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9186 ssh2_pkt_addstring(pktout, "break");
9187 ssh2_pkt_addbool(pktout, 0);
9188 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9189 ssh2_pkt_send(ssh, pktout);
9192 /* Is is a POSIX signal? */
9193 char *signame = NULL;
9194 if (code == TS_SIGABRT) signame = "ABRT";
9195 if (code == TS_SIGALRM) signame = "ALRM";
9196 if (code == TS_SIGFPE) signame = "FPE";
9197 if (code == TS_SIGHUP) signame = "HUP";
9198 if (code == TS_SIGILL) signame = "ILL";
9199 if (code == TS_SIGINT) signame = "INT";
9200 if (code == TS_SIGKILL) signame = "KILL";
9201 if (code == TS_SIGPIPE) signame = "PIPE";
9202 if (code == TS_SIGQUIT) signame = "QUIT";
9203 if (code == TS_SIGSEGV) signame = "SEGV";
9204 if (code == TS_SIGTERM) signame = "TERM";
9205 if (code == TS_SIGUSR1) signame = "USR1";
9206 if (code == TS_SIGUSR2) signame = "USR2";
9207 /* The SSH-2 protocol does in principle support arbitrary named
9208 * signals, including signame@domain, but we don't support those. */
9210 /* It's a signal. */
9211 if (ssh->version == 2 && ssh->mainchan) {
9212 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9213 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9214 ssh2_pkt_addstring(pktout, "signal");
9215 ssh2_pkt_addbool(pktout, 0);
9216 ssh2_pkt_addstring(pktout, signame);
9217 ssh2_pkt_send(ssh, pktout);
9218 logeventf(ssh, "Sent signal SIG%s", signame);
9221 /* Never heard of it. Do nothing */
9226 void *new_sock_channel(void *handle, Socket s)
9228 Ssh ssh = (Ssh) handle;
9229 struct ssh_channel *c;
9230 c = snew(struct ssh_channel);
9233 ssh2_channel_init(c);
9235 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9237 add234(ssh->channels, c);
9242 * This is called when stdout/stderr (the entity to which
9243 * from_backend sends data) manages to clear some backlog.
9245 static void ssh_unthrottle(void *handle, int bufsize)
9247 Ssh ssh = (Ssh) handle;
9250 if (ssh->version == 1) {
9251 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9252 ssh->v1_stdout_throttling = 0;
9253 ssh_throttle_conn(ssh, -1);
9256 if (ssh->mainchan) {
9257 ssh2_set_window(ssh->mainchan,
9258 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9259 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9260 if (ssh->cfg.ssh_simple)
9263 buflimit = ssh->mainchan->v.v2.locmaxwin;
9264 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9265 ssh->mainchan->throttling_conn = 0;
9266 ssh_throttle_conn(ssh, -1);
9272 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9274 struct ssh_channel *c = (struct ssh_channel *)channel;
9276 struct Packet *pktout;
9278 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9280 if (ssh->version == 1) {
9281 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9282 PKT_INT, c->localid,
9285 /* PKT_STR, <org:orgport>, */
9288 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9289 ssh2_pkt_addstring(pktout, "direct-tcpip");
9290 ssh2_pkt_adduint32(pktout, c->localid);
9291 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9292 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9293 ssh2_pkt_addstring(pktout, hostname);
9294 ssh2_pkt_adduint32(pktout, port);
9296 * We make up values for the originator data; partly it's
9297 * too much hassle to keep track, and partly I'm not
9298 * convinced the server should be told details like that
9299 * about my local network configuration.
9300 * The "originator IP address" is syntactically a numeric
9301 * IP address, and some servers (e.g., Tectia) get upset
9302 * if it doesn't match this syntax.
9304 ssh2_pkt_addstring(pktout, "0.0.0.0");
9305 ssh2_pkt_adduint32(pktout, 0);
9306 ssh2_pkt_send(ssh, pktout);
9310 static int ssh_connected(void *handle)
9312 Ssh ssh = (Ssh) handle;
9313 return ssh->s != NULL;
9316 static int ssh_sendok(void *handle)
9318 Ssh ssh = (Ssh) handle;
9319 return ssh->send_ok;
9322 static int ssh_ldisc(void *handle, int option)
9324 Ssh ssh = (Ssh) handle;
9325 if (option == LD_ECHO)
9326 return ssh->echoing;
9327 if (option == LD_EDIT)
9328 return ssh->editing;
9332 static void ssh_provide_ldisc(void *handle, void *ldisc)
9334 Ssh ssh = (Ssh) handle;
9338 static void ssh_provide_logctx(void *handle, void *logctx)
9340 Ssh ssh = (Ssh) handle;
9341 ssh->logctx = logctx;
9344 static int ssh_return_exitcode(void *handle)
9346 Ssh ssh = (Ssh) handle;
9350 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
9354 * cfg_info for SSH is the currently running version of the
9355 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9357 static int ssh_cfg_info(void *handle)
9359 Ssh ssh = (Ssh) handle;
9360 return ssh->version;
9364 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9365 * that fails. This variable is the means by which scp.c can reach
9366 * into the SSH code and find out which one it got.
9368 extern int ssh_fallback_cmd(void *handle)
9370 Ssh ssh = (Ssh) handle;
9371 return ssh->fallback_cmd;
9374 Backend ssh_backend = {
9384 ssh_return_exitcode,