26 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
29 #define SSH1_CMSG_USER 4 /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
38 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
39 #define SSH1_SMSG_FAILURE 15 /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
43 #define SSH1_CMSG_EOF 19 /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
55 #define SSH1_MSG_IGNORE 32 /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
68 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
69 #define SSH1_AUTH_RSA 2 /* 0x2 */
70 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
71 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
72 #define SSH1_AUTH_TIS 5 /* 0x5 */
73 #define SSH1_AUTH_CCARD 16 /* 0x10 */
75 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
76 /* Mask for protoflags we will echo back to server if seen */
77 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
79 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
80 #define SSH2_MSG_IGNORE 2 /* 0x2 */
81 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
82 #define SSH2_MSG_DEBUG 4 /* 0x4 */
83 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
84 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
85 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
86 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
87 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
88 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
89 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
90 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
91 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
92 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
93 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
94 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
95 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
96 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
97 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
98 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
99 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
100 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
101 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
102 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
103 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
104 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
105 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
106 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
107 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
108 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
109 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
110 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
111 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
112 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
113 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
114 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
115 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
116 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
117 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
118 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
119 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
120 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
121 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
122 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
123 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
126 * Packet type contexts, so that ssh2_pkt_type can correctly decode
127 * the ambiguous type numbers back into the correct type strings.
137 SSH2_PKTCTX_PUBLICKEY,
138 SSH2_PKTCTX_PASSWORD,
143 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
144 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
145 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
146 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
147 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
148 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
149 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
150 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
151 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
152 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
153 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
154 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
155 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
156 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
157 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
159 static const char *const ssh2_disconnect_reasons[] = {
161 "host not allowed to connect",
163 "key exchange failed",
164 "host authentication failed",
167 "service not available",
168 "protocol version not supported",
169 "host key not verifiable",
172 "too many connections",
173 "auth cancelled by user",
174 "no more auth methods available",
178 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
179 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
180 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
181 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
183 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
186 * Various remote-bug flags.
188 #define BUG_CHOKES_ON_SSH1_IGNORE 1
189 #define BUG_SSH2_HMAC 2
190 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
191 #define BUG_CHOKES_ON_RSA 8
192 #define BUG_SSH2_RSA_PADDING 16
193 #define BUG_SSH2_DERIVEKEY 32
194 #define BUG_SSH2_REKEY 64
195 #define BUG_SSH2_PK_SESSIONID 128
196 #define BUG_SSH2_MAXPKT 256
199 * Codes for terminal modes.
200 * Most of these are the same in SSH-1 and SSH-2.
201 * This list is derived from RFC 4254 and
204 static const struct {
205 const char* const mode;
207 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
209 /* "V" prefix discarded for special characters relative to SSH specs */
210 { "INTR", 1, TTY_OP_CHAR },
211 { "QUIT", 2, TTY_OP_CHAR },
212 { "ERASE", 3, TTY_OP_CHAR },
213 { "KILL", 4, TTY_OP_CHAR },
214 { "EOF", 5, TTY_OP_CHAR },
215 { "EOL", 6, TTY_OP_CHAR },
216 { "EOL2", 7, TTY_OP_CHAR },
217 { "START", 8, TTY_OP_CHAR },
218 { "STOP", 9, TTY_OP_CHAR },
219 { "SUSP", 10, TTY_OP_CHAR },
220 { "DSUSP", 11, TTY_OP_CHAR },
221 { "REPRINT", 12, TTY_OP_CHAR },
222 { "WERASE", 13, TTY_OP_CHAR },
223 { "LNEXT", 14, TTY_OP_CHAR },
224 { "FLUSH", 15, TTY_OP_CHAR },
225 { "SWTCH", 16, TTY_OP_CHAR },
226 { "STATUS", 17, TTY_OP_CHAR },
227 { "DISCARD", 18, TTY_OP_CHAR },
228 { "IGNPAR", 30, TTY_OP_BOOL },
229 { "PARMRK", 31, TTY_OP_BOOL },
230 { "INPCK", 32, TTY_OP_BOOL },
231 { "ISTRIP", 33, TTY_OP_BOOL },
232 { "INLCR", 34, TTY_OP_BOOL },
233 { "IGNCR", 35, TTY_OP_BOOL },
234 { "ICRNL", 36, TTY_OP_BOOL },
235 { "IUCLC", 37, TTY_OP_BOOL },
236 { "IXON", 38, TTY_OP_BOOL },
237 { "IXANY", 39, TTY_OP_BOOL },
238 { "IXOFF", 40, TTY_OP_BOOL },
239 { "IMAXBEL", 41, TTY_OP_BOOL },
240 { "ISIG", 50, TTY_OP_BOOL },
241 { "ICANON", 51, TTY_OP_BOOL },
242 { "XCASE", 52, TTY_OP_BOOL },
243 { "ECHO", 53, TTY_OP_BOOL },
244 { "ECHOE", 54, TTY_OP_BOOL },
245 { "ECHOK", 55, TTY_OP_BOOL },
246 { "ECHONL", 56, TTY_OP_BOOL },
247 { "NOFLSH", 57, TTY_OP_BOOL },
248 { "TOSTOP", 58, TTY_OP_BOOL },
249 { "IEXTEN", 59, TTY_OP_BOOL },
250 { "ECHOCTL", 60, TTY_OP_BOOL },
251 { "ECHOKE", 61, TTY_OP_BOOL },
252 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
253 { "OPOST", 70, TTY_OP_BOOL },
254 { "OLCUC", 71, TTY_OP_BOOL },
255 { "ONLCR", 72, TTY_OP_BOOL },
256 { "OCRNL", 73, TTY_OP_BOOL },
257 { "ONOCR", 74, TTY_OP_BOOL },
258 { "ONLRET", 75, TTY_OP_BOOL },
259 { "CS7", 90, TTY_OP_BOOL },
260 { "CS8", 91, TTY_OP_BOOL },
261 { "PARENB", 92, TTY_OP_BOOL },
262 { "PARODD", 93, TTY_OP_BOOL }
265 /* Miscellaneous other tty-related constants. */
266 #define SSH_TTY_OP_END 0
267 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
268 #define SSH1_TTY_OP_ISPEED 192
269 #define SSH1_TTY_OP_OSPEED 193
270 #define SSH2_TTY_OP_ISPEED 128
271 #define SSH2_TTY_OP_OSPEED 129
273 /* Helper functions for parsing tty-related config. */
274 static unsigned int ssh_tty_parse_specchar(char *s)
279 ret = ctrlparse(s, &next);
280 if (!next) ret = s[0];
282 ret = 255; /* special value meaning "don't set" */
286 static unsigned int ssh_tty_parse_boolean(char *s)
288 if (stricmp(s, "yes") == 0 ||
289 stricmp(s, "on") == 0 ||
290 stricmp(s, "true") == 0 ||
291 stricmp(s, "+") == 0)
293 else if (stricmp(s, "no") == 0 ||
294 stricmp(s, "off") == 0 ||
295 stricmp(s, "false") == 0 ||
296 stricmp(s, "-") == 0)
297 return 0; /* false */
299 return (atoi(s) != 0);
302 #define translate(x) if (type == x) return #x
303 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
304 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
305 static char *ssh1_pkt_type(int type)
307 translate(SSH1_MSG_DISCONNECT);
308 translate(SSH1_SMSG_PUBLIC_KEY);
309 translate(SSH1_CMSG_SESSION_KEY);
310 translate(SSH1_CMSG_USER);
311 translate(SSH1_CMSG_AUTH_RSA);
312 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
313 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
314 translate(SSH1_CMSG_AUTH_PASSWORD);
315 translate(SSH1_CMSG_REQUEST_PTY);
316 translate(SSH1_CMSG_WINDOW_SIZE);
317 translate(SSH1_CMSG_EXEC_SHELL);
318 translate(SSH1_CMSG_EXEC_CMD);
319 translate(SSH1_SMSG_SUCCESS);
320 translate(SSH1_SMSG_FAILURE);
321 translate(SSH1_CMSG_STDIN_DATA);
322 translate(SSH1_SMSG_STDOUT_DATA);
323 translate(SSH1_SMSG_STDERR_DATA);
324 translate(SSH1_CMSG_EOF);
325 translate(SSH1_SMSG_EXIT_STATUS);
326 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
327 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
328 translate(SSH1_MSG_CHANNEL_DATA);
329 translate(SSH1_MSG_CHANNEL_CLOSE);
330 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
331 translate(SSH1_SMSG_X11_OPEN);
332 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
333 translate(SSH1_MSG_PORT_OPEN);
334 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
335 translate(SSH1_SMSG_AGENT_OPEN);
336 translate(SSH1_MSG_IGNORE);
337 translate(SSH1_CMSG_EXIT_CONFIRMATION);
338 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
339 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
340 translate(SSH1_MSG_DEBUG);
341 translate(SSH1_CMSG_REQUEST_COMPRESSION);
342 translate(SSH1_CMSG_AUTH_TIS);
343 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
344 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
345 translate(SSH1_CMSG_AUTH_CCARD);
346 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
347 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
350 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
352 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
353 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
358 translate(SSH2_MSG_DISCONNECT);
359 translate(SSH2_MSG_IGNORE);
360 translate(SSH2_MSG_UNIMPLEMENTED);
361 translate(SSH2_MSG_DEBUG);
362 translate(SSH2_MSG_SERVICE_REQUEST);
363 translate(SSH2_MSG_SERVICE_ACCEPT);
364 translate(SSH2_MSG_KEXINIT);
365 translate(SSH2_MSG_NEWKEYS);
366 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
367 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
368 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
369 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
370 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
371 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
373 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
374 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
375 translate(SSH2_MSG_USERAUTH_REQUEST);
376 translate(SSH2_MSG_USERAUTH_FAILURE);
377 translate(SSH2_MSG_USERAUTH_SUCCESS);
378 translate(SSH2_MSG_USERAUTH_BANNER);
379 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
380 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
381 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
382 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
383 translate(SSH2_MSG_GLOBAL_REQUEST);
384 translate(SSH2_MSG_REQUEST_SUCCESS);
385 translate(SSH2_MSG_REQUEST_FAILURE);
386 translate(SSH2_MSG_CHANNEL_OPEN);
387 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
388 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
389 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
390 translate(SSH2_MSG_CHANNEL_DATA);
391 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
392 translate(SSH2_MSG_CHANNEL_EOF);
393 translate(SSH2_MSG_CHANNEL_CLOSE);
394 translate(SSH2_MSG_CHANNEL_REQUEST);
395 translate(SSH2_MSG_CHANNEL_SUCCESS);
396 translate(SSH2_MSG_CHANNEL_FAILURE);
402 /* Enumeration values for fields in SSH-1 packets */
404 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
405 /* These values are for communicating relevant semantics of
406 * fields to the packet logging code. */
407 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
411 * Coroutine mechanics for the sillier bits of the code. If these
412 * macros look impenetrable to you, you might find it helpful to
415 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
417 * which explains the theory behind these macros.
419 * In particular, if you are getting `case expression not constant'
420 * errors when building with MS Visual Studio, this is because MS's
421 * Edit and Continue debugging feature causes their compiler to
422 * violate ANSI C. To disable Edit and Continue debugging:
424 * - right-click ssh.c in the FileView
426 * - select the C/C++ tab and the General category
427 * - under `Debug info:', select anything _other_ than `Program
428 * Database for Edit and Continue'.
430 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
433 if (!ssh->t) ssh->t = snew(struct t); \
435 #define crFinish(z) } *crLine = 0; return (z); }
436 #define crFinishV } *crLine = 0; return; }
437 #define crReturn(z) \
439 *crLine =__LINE__; return (z); case __LINE__:;\
443 *crLine=__LINE__; return; case __LINE__:;\
445 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
446 #define crStopV do{ *crLine = 0; return; }while(0)
447 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
448 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
450 typedef struct ssh_tag *Ssh;
453 static struct Packet *ssh1_pkt_init(int pkt_type);
454 static struct Packet *ssh2_pkt_init(int pkt_type);
455 static void ssh_pkt_ensure(struct Packet *, int length);
456 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
457 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
458 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
459 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
460 static void ssh_pkt_addstring_start(struct Packet *);
461 static void ssh_pkt_addstring_str(struct Packet *, char *data);
462 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
463 static void ssh_pkt_addstring(struct Packet *, char *data);
464 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
465 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
466 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
467 static int ssh2_pkt_construct(Ssh, struct Packet *);
468 static void ssh2_pkt_send(Ssh, struct Packet *);
469 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
470 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
471 struct Packet *pktin);
472 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
473 struct Packet *pktin);
476 * Buffer management constants. There are several of these for
477 * various different purposes:
479 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
480 * on a local data stream before we throttle the whole SSH
481 * connection (in SSH-1 only). Throttling the whole connection is
482 * pretty drastic so we set this high in the hope it won't
485 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
486 * on the SSH connection itself before we defensively throttle
487 * _all_ local data streams. This is pretty drastic too (though
488 * thankfully unlikely in SSH-2 since the window mechanism should
489 * ensure that the server never has any need to throttle its end
490 * of the connection), so we set this high as well.
492 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
495 * - OUR_V2_BIGWIN is the window size we advertise for the only
496 * channel in a simple connection. It must be <= INT_MAX.
498 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
499 * to the remote side. This actually has nothing to do with the
500 * size of the _packet_, but is instead a limit on the amount
501 * of data we're willing to receive in a single SSH2 channel
504 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
505 * _packet_ we're prepared to cope with. It must be a multiple
506 * of the cipher block size, and must be at least 35000.
509 #define SSH1_BUFFER_LIMIT 32768
510 #define SSH_MAX_BACKLOG 32768
511 #define OUR_V2_WINSIZE 16384
512 #define OUR_V2_BIGWIN 0x7fffffff
513 #define OUR_V2_MAXPKT 0x4000UL
514 #define OUR_V2_PACKETLIMIT 0x9000UL
516 /* Maximum length of passwords/passphrases (arbitrary) */
517 #define SSH_MAX_PASSWORD_LEN 100
519 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
521 const static struct ssh_mac *macs[] = {
522 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
524 const static struct ssh_mac *buggymacs[] = {
525 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
528 static void *ssh_comp_none_init(void)
532 static void ssh_comp_none_cleanup(void *handle)
535 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
536 unsigned char **outblock, int *outlen)
540 static int ssh_comp_none_disable(void *handle)
544 const static struct ssh_compress ssh_comp_none = {
546 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
547 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
548 ssh_comp_none_disable, NULL
550 extern const struct ssh_compress ssh_zlib;
551 const static struct ssh_compress *compressions[] = {
552 &ssh_zlib, &ssh_comp_none
555 enum { /* channel types */
560 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
564 * little structure to keep track of outstanding WINDOW_ADJUSTs
572 * 2-3-4 tree storing channels.
575 Ssh ssh; /* pointer back to main context */
576 unsigned remoteid, localid;
578 /* True if we opened this channel but server hasn't confirmed. */
581 * In SSH-1, this value contains four bits:
583 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
584 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
585 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
586 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
588 * A channel is completely finished with when all four bits are set.
592 * True if this channel is causing the underlying connection to be
597 struct ssh2_data_channel {
599 unsigned remwindow, remmaxpkt;
600 /* locwindow is signed so we can cope with excess data. */
601 int locwindow, locmaxwin;
603 * remlocwin is the amount of local window that we think
604 * the remote end had available to it after it sent the
605 * last data packet or window adjust ack.
609 * These store the list of window adjusts that haven't
612 struct winadj *winadj_head, *winadj_tail;
613 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
617 struct ssh_agent_channel {
618 unsigned char *message;
619 unsigned char msglen[4];
620 unsigned lensofar, totallen;
622 struct ssh_x11_channel {
625 struct ssh_pfd_channel {
632 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
633 * use this structure in different ways, reflecting SSH-2's
634 * altogether saner approach to port forwarding.
636 * In SSH-1, you arrange a remote forwarding by sending the server
637 * the remote port number, and the local destination host:port.
638 * When a connection comes in, the server sends you back that
639 * host:port pair, and you connect to it. This is a ready-made
640 * security hole if you're not on the ball: a malicious server
641 * could send you back _any_ host:port pair, so if you trustingly
642 * connect to the address it gives you then you've just opened the
643 * entire inside of your corporate network just by connecting
644 * through it to a dodgy SSH server. Hence, we must store a list of
645 * host:port pairs we _are_ trying to forward to, and reject a
646 * connection request from the server if it's not in the list.
648 * In SSH-2, each side of the connection minds its own business and
649 * doesn't send unnecessary information to the other. You arrange a
650 * remote forwarding by sending the server just the remote port
651 * number. When a connection comes in, the server tells you which
652 * of its ports was connected to; and _you_ have to remember what
653 * local host:port pair went with that port number.
655 * Hence, in SSH-1 this structure is indexed by destination
656 * host:port pair, whereas in SSH-2 it is indexed by source port.
658 struct ssh_portfwd; /* forward declaration */
660 struct ssh_rportfwd {
661 unsigned sport, dport;
664 struct ssh_portfwd *pfrec;
666 #define free_rportfwd(pf) ( \
667 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
670 * Separately to the rportfwd tree (which is for looking up port
671 * open requests from the server), a tree of _these_ structures is
672 * used to keep track of all the currently open port forwardings,
673 * so that we can reconfigure in mid-session if the user requests
677 enum { DESTROY, KEEP, CREATE } status;
679 unsigned sport, dport;
682 struct ssh_rportfwd *remote;
686 #define free_portfwd(pf) ( \
687 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
688 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
691 long length; /* length of `data' actually used */
692 long forcepad; /* SSH-2: force padding to at least this length */
693 int type; /* only used for incoming packets */
694 unsigned long sequence; /* SSH-2 incoming sequence number */
695 unsigned char *data; /* allocated storage */
696 unsigned char *body; /* offset of payload within `data' */
697 long savedpos; /* temporary index into `data' (for strings) */
698 long maxlen; /* amount of storage allocated for `data' */
699 long encrypted_len; /* for SSH-2 total-size counting */
702 * State associated with packet logging
706 struct logblank_t *blanks;
709 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
710 struct Packet *pktin);
711 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
712 struct Packet *pktin);
713 static void ssh1_protocol_setup(Ssh ssh);
714 static void ssh2_protocol_setup(Ssh ssh);
715 static void ssh_size(void *handle, int width, int height);
716 static void ssh_special(void *handle, Telnet_Special);
717 static int ssh2_try_send(struct ssh_channel *c);
718 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
719 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
720 static void ssh2_set_window(struct ssh_channel *c, int newwin);
721 static int ssh_sendbuffer(void *handle);
722 static int ssh_do_close(Ssh ssh, int notify_exit);
723 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
724 static int ssh2_pkt_getbool(struct Packet *pkt);
725 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
726 static void ssh2_timer(void *ctx, long now);
727 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
728 struct Packet *pktin);
730 struct rdpkt1_state_tag {
731 long len, pad, biglen, to_read;
732 unsigned long realcrc, gotcrc;
736 struct Packet *pktin;
739 struct rdpkt2_state_tag {
740 long len, pad, payload, packetlen, maclen;
743 unsigned long incoming_sequence;
744 struct Packet *pktin;
747 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
748 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
750 struct queued_handler;
751 struct queued_handler {
753 chandler_fn_t handler;
755 struct queued_handler *next;
759 const struct plug_function_table *fn;
760 /* the above field _must_ be first in the structure */
770 unsigned char session_key[32];
772 int v1_remote_protoflags;
773 int v1_local_protoflags;
774 int agentfwd_enabled;
777 const struct ssh_cipher *cipher;
780 const struct ssh2_cipher *cscipher, *sccipher;
781 void *cs_cipher_ctx, *sc_cipher_ctx;
782 const struct ssh_mac *csmac, *scmac;
783 void *cs_mac_ctx, *sc_mac_ctx;
784 const struct ssh_compress *cscomp, *sccomp;
785 void *cs_comp_ctx, *sc_comp_ctx;
786 const struct ssh_kex *kex;
787 const struct ssh_signkey *hostkey;
788 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
789 int v2_session_id_len;
795 int echoing, editing;
799 int ospeed, ispeed; /* temporaries */
800 int term_width, term_height;
802 tree234 *channels; /* indexed by local id */
803 struct ssh_channel *mainchan; /* primary session channel */
804 int ncmode; /* is primary channel direct-tcpip? */
809 tree234 *rportfwds, *portfwds;
813 SSH_STATE_BEFORE_SIZE,
819 int size_needed, eof_needed;
821 struct Packet **queue;
822 int queuelen, queuesize;
824 unsigned char *deferred_send_data;
825 int deferred_len, deferred_size;
828 * Gross hack: pscp will try to start SFTP but fall back to
829 * scp1 if that fails. This variable is the means by which
830 * scp.c can reach into the SSH code and find out which one it
835 bufchain banner; /* accumulates banners during do_ssh2_authconn */
840 struct X11Display *x11disp;
843 int conn_throttle_count;
846 int v1_stdout_throttling;
847 unsigned long v2_outgoing_sequence;
849 int ssh1_rdpkt_crstate;
850 int ssh2_rdpkt_crstate;
851 int do_ssh_init_crstate;
852 int ssh_gotdata_crstate;
853 int do_ssh1_login_crstate;
854 int do_ssh1_connection_crstate;
855 int do_ssh2_transport_crstate;
856 int do_ssh2_authconn_crstate;
858 void *do_ssh_init_state;
859 void *do_ssh1_login_state;
860 void *do_ssh2_transport_state;
861 void *do_ssh2_authconn_state;
863 struct rdpkt1_state_tag rdpkt1_state;
864 struct rdpkt2_state_tag rdpkt2_state;
866 /* SSH-1 and SSH-2 use this for different things, but both use it */
867 int protocol_initial_phase_done;
869 void (*protocol) (Ssh ssh, void *vin, int inlen,
871 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
874 * We maintain a full _copy_ of a Config structure here, not
875 * merely a pointer to it. That way, when we're passed a new
876 * one for reconfiguration, we can check the differences and
877 * potentially reconfigure port forwardings etc in mid-session.
882 * Used to transfer data back from async callbacks.
884 void *agent_response;
885 int agent_response_len;
889 * The SSH connection can be set as `frozen', meaning we are
890 * not currently accepting incoming data from the network. This
891 * is slightly more serious than setting the _socket_ as
892 * frozen, because we may already have had data passed to us
893 * from the network which we need to delay processing until
894 * after the freeze is lifted, so we also need a bufchain to
898 bufchain queued_incoming_data;
901 * Dispatch table for packet types that we may have to deal
904 handler_fn_t packet_dispatch[256];
907 * Queues of one-off handler functions for success/failure
908 * indications from a request.
910 struct queued_handler *qhead, *qtail;
913 * This module deals with sending keepalives.
918 * Track incoming and outgoing data sizes and time, for
921 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
922 unsigned long max_data_size;
924 long next_rekey, last_rekey;
925 char *deferred_rekey_reason; /* points to STATIC string; don't free */
928 * Fully qualified host name, which we need if doing GSSAPI.
933 #define logevent(s) logevent(ssh->frontend, s)
935 /* logevent, only printf-formatted. */
936 static void logeventf(Ssh ssh, const char *fmt, ...)
942 buf = dupvprintf(fmt, ap);
948 #define bombout(msg) \
950 char *text = dupprintf msg; \
951 ssh_do_close(ssh, FALSE); \
953 connection_fatal(ssh->frontend, "%s", text); \
957 /* Functions to leave bits out of the SSH packet log file. */
959 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
961 if (ssh->cfg.logomitpass)
962 pkt->logmode = blanktype;
965 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
967 if (ssh->cfg.logomitdata)
968 pkt->logmode = blanktype;
971 static void end_log_omission(Ssh ssh, struct Packet *pkt)
973 pkt->logmode = PKTLOG_EMIT;
976 /* Helper function for common bits of parsing cfg.ttymodes. */
977 static void parse_ttymodes(Ssh ssh, char *modes,
978 void (*do_mode)(void *data, char *mode, char *val),
982 char *t = strchr(modes, '\t');
983 char *m = snewn(t-modes+1, char);
985 strncpy(m, modes, t-modes);
988 val = get_ttymode(ssh->frontend, m);
992 do_mode(data, m, val);
995 modes += strlen(modes) + 1;
999 static int ssh_channelcmp(void *av, void *bv)
1001 struct ssh_channel *a = (struct ssh_channel *) av;
1002 struct ssh_channel *b = (struct ssh_channel *) bv;
1003 if (a->localid < b->localid)
1005 if (a->localid > b->localid)
1009 static int ssh_channelfind(void *av, void *bv)
1011 unsigned *a = (unsigned *) av;
1012 struct ssh_channel *b = (struct ssh_channel *) bv;
1013 if (*a < b->localid)
1015 if (*a > b->localid)
1020 static int ssh_rportcmp_ssh1(void *av, void *bv)
1022 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1023 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1025 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1026 return i < 0 ? -1 : +1;
1027 if (a->dport > b->dport)
1029 if (a->dport < b->dport)
1034 static int ssh_rportcmp_ssh2(void *av, void *bv)
1036 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1037 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1039 if (a->sport > b->sport)
1041 if (a->sport < b->sport)
1047 * Special form of strcmp which can cope with NULL inputs. NULL is
1048 * defined to sort before even the empty string.
1050 static int nullstrcmp(const char *a, const char *b)
1052 if (a == NULL && b == NULL)
1058 return strcmp(a, b);
1061 static int ssh_portcmp(void *av, void *bv)
1063 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1064 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1066 if (a->type > b->type)
1068 if (a->type < b->type)
1070 if (a->addressfamily > b->addressfamily)
1072 if (a->addressfamily < b->addressfamily)
1074 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1075 return i < 0 ? -1 : +1;
1076 if (a->sport > b->sport)
1078 if (a->sport < b->sport)
1080 if (a->type != 'D') {
1081 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1082 return i < 0 ? -1 : +1;
1083 if (a->dport > b->dport)
1085 if (a->dport < b->dport)
1091 static int alloc_channel_id(Ssh ssh)
1093 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1094 unsigned low, high, mid;
1096 struct ssh_channel *c;
1099 * First-fit allocation of channel numbers: always pick the
1100 * lowest unused one. To do this, binary-search using the
1101 * counted B-tree to find the largest channel ID which is in a
1102 * contiguous sequence from the beginning. (Precisely
1103 * everything in that sequence must have ID equal to its tree
1104 * index plus CHANNEL_NUMBER_OFFSET.)
1106 tsize = count234(ssh->channels);
1110 while (high - low > 1) {
1111 mid = (high + low) / 2;
1112 c = index234(ssh->channels, mid);
1113 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1114 low = mid; /* this one is fine */
1116 high = mid; /* this one is past it */
1119 * Now low points to either -1, or the tree index of the
1120 * largest ID in the initial sequence.
1123 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1124 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1126 return low + 1 + CHANNEL_NUMBER_OFFSET;
1129 static void c_write_stderr(int trusted, const char *buf, int len)
1132 for (i = 0; i < len; i++)
1133 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1134 fputc(buf[i], stderr);
1137 static void c_write(Ssh ssh, const char *buf, int len)
1139 if (flags & FLAG_STDERR)
1140 c_write_stderr(1, buf, len);
1142 from_backend(ssh->frontend, 1, buf, len);
1145 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1147 if (flags & FLAG_STDERR)
1148 c_write_stderr(0, buf, len);
1150 from_backend_untrusted(ssh->frontend, buf, len);
1153 static void c_write_str(Ssh ssh, const char *buf)
1155 c_write(ssh, buf, strlen(buf));
1158 static void ssh_free_packet(struct Packet *pkt)
1163 static struct Packet *ssh_new_packet(void)
1165 struct Packet *pkt = snew(struct Packet);
1167 pkt->body = pkt->data = NULL;
1169 pkt->logmode = PKTLOG_EMIT;
1177 * Collect incoming data in the incoming packet buffer.
1178 * Decipher and verify the packet when it is completely read.
1179 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1180 * Update the *data and *datalen variables.
1181 * Return a Packet structure when a packet is completed.
1183 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1185 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1187 crBegin(ssh->ssh1_rdpkt_crstate);
1189 st->pktin = ssh_new_packet();
1191 st->pktin->type = 0;
1192 st->pktin->length = 0;
1194 for (st->i = st->len = 0; st->i < 4; st->i++) {
1195 while ((*datalen) == 0)
1197 st->len = (st->len << 8) + **data;
1198 (*data)++, (*datalen)--;
1201 st->pad = 8 - (st->len % 8);
1202 st->biglen = st->len + st->pad;
1203 st->pktin->length = st->len - 5;
1205 if (st->biglen < 0) {
1206 bombout(("Extremely large packet length from server suggests"
1207 " data stream corruption"));
1208 ssh_free_packet(st->pktin);
1212 st->pktin->maxlen = st->biglen;
1213 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1215 st->to_read = st->biglen;
1216 st->p = st->pktin->data;
1217 while (st->to_read > 0) {
1218 st->chunk = st->to_read;
1219 while ((*datalen) == 0)
1221 if (st->chunk > (*datalen))
1222 st->chunk = (*datalen);
1223 memcpy(st->p, *data, st->chunk);
1225 *datalen -= st->chunk;
1227 st->to_read -= st->chunk;
1230 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1231 st->biglen, NULL)) {
1232 bombout(("Network attack (CRC compensation) detected!"));
1233 ssh_free_packet(st->pktin);
1238 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1240 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1241 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1242 if (st->gotcrc != st->realcrc) {
1243 bombout(("Incorrect CRC received on packet"));
1244 ssh_free_packet(st->pktin);
1248 st->pktin->body = st->pktin->data + st->pad + 1;
1249 st->pktin->savedpos = 0;
1251 if (ssh->v1_compressing) {
1252 unsigned char *decompblk;
1254 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1255 st->pktin->body - 1, st->pktin->length + 1,
1256 &decompblk, &decomplen)) {
1257 bombout(("Zlib decompression encountered invalid data"));
1258 ssh_free_packet(st->pktin);
1262 if (st->pktin->maxlen < st->pad + decomplen) {
1263 st->pktin->maxlen = st->pad + decomplen;
1264 st->pktin->data = sresize(st->pktin->data,
1265 st->pktin->maxlen + APIEXTRA,
1267 st->pktin->body = st->pktin->data + st->pad + 1;
1270 memcpy(st->pktin->body - 1, decompblk, decomplen);
1272 st->pktin->length = decomplen - 1;
1275 st->pktin->type = st->pktin->body[-1];
1278 * Log incoming packet, possibly omitting sensitive fields.
1282 struct logblank_t blank;
1283 if (ssh->cfg.logomitdata) {
1284 int do_blank = FALSE, blank_prefix = 0;
1285 /* "Session data" packets - omit the data field */
1286 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1287 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1288 do_blank = TRUE; blank_prefix = 4;
1289 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1290 do_blank = TRUE; blank_prefix = 8;
1293 blank.offset = blank_prefix;
1294 blank.len = st->pktin->length;
1295 blank.type = PKTLOG_OMIT;
1299 log_packet(ssh->logctx,
1300 PKT_INCOMING, st->pktin->type,
1301 ssh1_pkt_type(st->pktin->type),
1302 st->pktin->body, st->pktin->length,
1303 nblanks, &blank, NULL);
1306 crFinish(st->pktin);
1309 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1311 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1313 crBegin(ssh->ssh2_rdpkt_crstate);
1315 st->pktin = ssh_new_packet();
1317 st->pktin->type = 0;
1318 st->pktin->length = 0;
1320 st->cipherblk = ssh->sccipher->blksize;
1323 if (st->cipherblk < 8)
1325 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1327 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1330 * When dealing with a CBC-mode cipher, we want to avoid the
1331 * possibility of an attacker's tweaking the ciphertext stream
1332 * so as to cause us to feed the same block to the block
1333 * cipher more than once and thus leak information
1334 * (VU#958563). The way we do this is not to take any
1335 * decisions on the basis of anything we've decrypted until
1336 * we've verified it with a MAC. That includes the packet
1337 * length, so we just read data and check the MAC repeatedly,
1338 * and when the MAC passes, see if the length we've got is
1342 /* May as well allocate the whole lot now. */
1343 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1346 /* Read an amount corresponding to the MAC. */
1347 for (st->i = 0; st->i < st->maclen; st->i++) {
1348 while ((*datalen) == 0)
1350 st->pktin->data[st->i] = *(*data)++;
1356 unsigned char seq[4];
1357 ssh->scmac->start(ssh->sc_mac_ctx);
1358 PUT_32BIT(seq, st->incoming_sequence);
1359 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1362 for (;;) { /* Once around this loop per cipher block. */
1363 /* Read another cipher-block's worth, and tack it onto the end. */
1364 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1365 while ((*datalen) == 0)
1367 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1370 /* Decrypt one more block (a little further back in the stream). */
1371 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1372 st->pktin->data + st->packetlen,
1374 /* Feed that block to the MAC. */
1375 ssh->scmac->bytes(ssh->sc_mac_ctx,
1376 st->pktin->data + st->packetlen, st->cipherblk);
1377 st->packetlen += st->cipherblk;
1378 /* See if that gives us a valid packet. */
1379 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1380 st->pktin->data + st->packetlen) &&
1381 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1383 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1384 bombout(("No valid incoming packet found"));
1385 ssh_free_packet(st->pktin);
1389 st->pktin->maxlen = st->packetlen + st->maclen;
1390 st->pktin->data = sresize(st->pktin->data,
1391 st->pktin->maxlen + APIEXTRA,
1394 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1397 * Acquire and decrypt the first block of the packet. This will
1398 * contain the length and padding details.
1400 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1401 while ((*datalen) == 0)
1403 st->pktin->data[st->i] = *(*data)++;
1408 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1409 st->pktin->data, st->cipherblk);
1412 * Now get the length figure.
1414 st->len = GET_32BIT(st->pktin->data);
1417 * _Completely_ silly lengths should be stomped on before they
1418 * do us any more damage.
1420 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1421 (st->len + 4) % st->cipherblk != 0) {
1422 bombout(("Incoming packet was garbled on decryption"));
1423 ssh_free_packet(st->pktin);
1428 * So now we can work out the total packet length.
1430 st->packetlen = st->len + 4;
1433 * Allocate memory for the rest of the packet.
1435 st->pktin->maxlen = st->packetlen + st->maclen;
1436 st->pktin->data = sresize(st->pktin->data,
1437 st->pktin->maxlen + APIEXTRA,
1441 * Read and decrypt the remainder of the packet.
1443 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1445 while ((*datalen) == 0)
1447 st->pktin->data[st->i] = *(*data)++;
1450 /* Decrypt everything _except_ the MAC. */
1452 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1453 st->pktin->data + st->cipherblk,
1454 st->packetlen - st->cipherblk);
1460 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1461 st->len + 4, st->incoming_sequence)) {
1462 bombout(("Incorrect MAC received on packet"));
1463 ssh_free_packet(st->pktin);
1467 /* Get and sanity-check the amount of random padding. */
1468 st->pad = st->pktin->data[4];
1469 if (st->pad < 4 || st->len - st->pad < 1) {
1470 bombout(("Invalid padding length on received packet"));
1471 ssh_free_packet(st->pktin);
1475 * This enables us to deduce the payload length.
1477 st->payload = st->len - st->pad - 1;
1479 st->pktin->length = st->payload + 5;
1480 st->pktin->encrypted_len = st->packetlen;
1482 st->pktin->sequence = st->incoming_sequence++;
1485 * Decompress packet payload.
1488 unsigned char *newpayload;
1491 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1492 st->pktin->data + 5, st->pktin->length - 5,
1493 &newpayload, &newlen)) {
1494 if (st->pktin->maxlen < newlen + 5) {
1495 st->pktin->maxlen = newlen + 5;
1496 st->pktin->data = sresize(st->pktin->data,
1497 st->pktin->maxlen + APIEXTRA,
1500 st->pktin->length = 5 + newlen;
1501 memcpy(st->pktin->data + 5, newpayload, newlen);
1506 st->pktin->savedpos = 6;
1507 st->pktin->body = st->pktin->data;
1508 st->pktin->type = st->pktin->data[5];
1511 * Log incoming packet, possibly omitting sensitive fields.
1515 struct logblank_t blank;
1516 if (ssh->cfg.logomitdata) {
1517 int do_blank = FALSE, blank_prefix = 0;
1518 /* "Session data" packets - omit the data field */
1519 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1520 do_blank = TRUE; blank_prefix = 8;
1521 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1522 do_blank = TRUE; blank_prefix = 12;
1525 blank.offset = blank_prefix;
1526 blank.len = (st->pktin->length-6) - blank_prefix;
1527 blank.type = PKTLOG_OMIT;
1531 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1532 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1534 st->pktin->data+6, st->pktin->length-6,
1535 nblanks, &blank, &st->pktin->sequence);
1538 crFinish(st->pktin);
1541 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1543 int pad, biglen, i, pktoffs;
1547 * XXX various versions of SC (including 8.8.4) screw up the
1548 * register allocation in this function and use the same register
1549 * (D6) for len and as a temporary, with predictable results. The
1550 * following sledgehammer prevents this.
1557 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1558 ssh1_pkt_type(pkt->data[12]),
1559 pkt->body, pkt->length - (pkt->body - pkt->data),
1560 pkt->nblanks, pkt->blanks, NULL);
1561 sfree(pkt->blanks); pkt->blanks = NULL;
1564 if (ssh->v1_compressing) {
1565 unsigned char *compblk;
1567 zlib_compress_block(ssh->cs_comp_ctx,
1568 pkt->data + 12, pkt->length - 12,
1569 &compblk, &complen);
1570 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1571 memcpy(pkt->data + 12, compblk, complen);
1573 pkt->length = complen + 12;
1576 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1578 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1579 pad = 8 - (len % 8);
1581 biglen = len + pad; /* len(padding+type+data+CRC) */
1583 for (i = pktoffs; i < 4+8; i++)
1584 pkt->data[i] = random_byte();
1585 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1586 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1587 PUT_32BIT(pkt->data + pktoffs, len);
1590 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1591 pkt->data + pktoffs + 4, biglen);
1593 if (offset_p) *offset_p = pktoffs;
1594 return biglen + 4; /* len(length+padding+type+data+CRC) */
1597 static int s_write(Ssh ssh, void *data, int len)
1600 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1602 return sk_write(ssh->s, (char *)data, len);
1605 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1607 int len, backlog, offset;
1608 len = s_wrpkt_prepare(ssh, pkt, &offset);
1609 backlog = s_write(ssh, pkt->data + offset, len);
1610 if (backlog > SSH_MAX_BACKLOG)
1611 ssh_throttle_all(ssh, 1, backlog);
1612 ssh_free_packet(pkt);
1615 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1618 len = s_wrpkt_prepare(ssh, pkt, &offset);
1619 if (ssh->deferred_len + len > ssh->deferred_size) {
1620 ssh->deferred_size = ssh->deferred_len + len + 128;
1621 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1625 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1626 pkt->data + offset, len);
1627 ssh->deferred_len += len;
1628 ssh_free_packet(pkt);
1632 * Construct a SSH-1 packet with the specified contents.
1633 * (This all-at-once interface used to be the only one, but now SSH-1
1634 * packets can also be constructed incrementally.)
1636 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1642 pkt = ssh1_pkt_init(pkttype);
1644 while ((argtype = va_arg(ap, int)) != PKT_END) {
1645 unsigned char *argp, argchar;
1647 unsigned long argint;
1650 /* Actual fields in the packet */
1652 argint = va_arg(ap, int);
1653 ssh_pkt_adduint32(pkt, argint);
1656 argchar = (unsigned char) va_arg(ap, int);
1657 ssh_pkt_addbyte(pkt, argchar);
1660 argp = va_arg(ap, unsigned char *);
1661 arglen = va_arg(ap, int);
1662 ssh_pkt_adddata(pkt, argp, arglen);
1665 sargp = va_arg(ap, char *);
1666 ssh_pkt_addstring(pkt, sargp);
1669 bn = va_arg(ap, Bignum);
1670 ssh1_pkt_addmp(pkt, bn);
1672 /* Tokens for modifications to packet logging */
1674 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1677 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1680 end_log_omission(ssh, pkt);
1688 static void send_packet(Ssh ssh, int pkttype, ...)
1692 va_start(ap, pkttype);
1693 pkt = construct_packet(ssh, pkttype, ap);
1698 static void defer_packet(Ssh ssh, int pkttype, ...)
1702 va_start(ap, pkttype);
1703 pkt = construct_packet(ssh, pkttype, ap);
1705 s_wrpkt_defer(ssh, pkt);
1708 static int ssh_versioncmp(char *a, char *b)
1711 unsigned long av, bv;
1713 av = strtoul(a, &ae, 10);
1714 bv = strtoul(b, &be, 10);
1716 return (av < bv ? -1 : +1);
1721 av = strtoul(ae, &ae, 10);
1722 bv = strtoul(be, &be, 10);
1724 return (av < bv ? -1 : +1);
1729 * Utility routines for putting an SSH-protocol `string' and
1730 * `uint32' into a hash state.
1732 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1734 unsigned char lenblk[4];
1735 PUT_32BIT(lenblk, len);
1736 h->bytes(s, lenblk, 4);
1737 h->bytes(s, str, len);
1740 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1742 unsigned char intblk[4];
1743 PUT_32BIT(intblk, i);
1744 h->bytes(s, intblk, 4);
1748 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1750 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1752 if (pkt->maxlen < length) {
1753 unsigned char *body = pkt->body;
1754 int offset = body ? body - pkt->data : 0;
1755 pkt->maxlen = length + 256;
1756 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1757 if (body) pkt->body = pkt->data + offset;
1760 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1762 if (pkt->logmode != PKTLOG_EMIT) {
1764 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1766 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1767 (pkt->body - pkt->data);
1768 pkt->blanks[pkt->nblanks-1].len = len;
1769 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1772 ssh_pkt_ensure(pkt, pkt->length);
1773 memcpy(pkt->data + pkt->length - len, data, len);
1775 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1777 ssh_pkt_adddata(pkt, &byte, 1);
1779 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1781 ssh_pkt_adddata(pkt, &value, 1);
1783 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1786 PUT_32BIT(x, value);
1787 ssh_pkt_adddata(pkt, x, 4);
1789 static void ssh_pkt_addstring_start(struct Packet *pkt)
1791 ssh_pkt_adduint32(pkt, 0);
1792 pkt->savedpos = pkt->length;
1794 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1796 ssh_pkt_adddata(pkt, data, strlen(data));
1797 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1799 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1801 ssh_pkt_adddata(pkt, data, len);
1802 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1804 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1806 ssh_pkt_addstring_start(pkt);
1807 ssh_pkt_addstring_str(pkt, data);
1809 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1811 int len = ssh1_bignum_length(b);
1812 unsigned char *data = snewn(len, unsigned char);
1813 (void) ssh1_write_bignum(data, b);
1814 ssh_pkt_adddata(pkt, data, len);
1817 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1820 int i, n = (bignum_bitcount(b) + 7) / 8;
1821 p = snewn(n + 1, unsigned char);
1823 for (i = 1; i <= n; i++)
1824 p[i] = bignum_byte(b, n - i);
1826 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1828 memmove(p, p + i, n + 1 - i);
1832 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1836 p = ssh2_mpint_fmt(b, &len);
1837 ssh_pkt_addstring_start(pkt);
1838 ssh_pkt_addstring_data(pkt, (char *)p, len);
1842 static struct Packet *ssh1_pkt_init(int pkt_type)
1844 struct Packet *pkt = ssh_new_packet();
1845 pkt->length = 4 + 8; /* space for length + max padding */
1846 ssh_pkt_addbyte(pkt, pkt_type);
1847 pkt->body = pkt->data + pkt->length;
1851 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1852 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1853 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1854 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1855 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1856 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1857 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1858 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1859 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1861 static struct Packet *ssh2_pkt_init(int pkt_type)
1863 struct Packet *pkt = ssh_new_packet();
1864 pkt->length = 5; /* space for packet length + padding length */
1866 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1867 pkt->body = pkt->data + pkt->length; /* after packet type */
1872 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1873 * put the MAC on it. Final packet, ready to be sent, is stored in
1874 * pkt->data. Total length is returned.
1876 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1878 int cipherblk, maclen, padding, i;
1881 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1882 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1883 pkt->body, pkt->length - (pkt->body - pkt->data),
1884 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1885 sfree(pkt->blanks); pkt->blanks = NULL;
1889 * Compress packet payload.
1892 unsigned char *newpayload;
1895 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1897 &newpayload, &newlen)) {
1899 ssh2_pkt_adddata(pkt, newpayload, newlen);
1905 * Add padding. At least four bytes, and must also bring total
1906 * length (minus MAC) up to a multiple of the block size.
1907 * If pkt->forcepad is set, make sure the packet is at least that size
1910 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1911 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1913 if (pkt->length + padding < pkt->forcepad)
1914 padding = pkt->forcepad - pkt->length;
1916 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1917 assert(padding <= 255);
1918 maclen = ssh->csmac ? ssh->csmac->len : 0;
1919 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1920 pkt->data[4] = padding;
1921 for (i = 0; i < padding; i++)
1922 pkt->data[pkt->length + i] = random_byte();
1923 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1925 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1926 pkt->length + padding,
1927 ssh->v2_outgoing_sequence);
1928 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1931 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1932 pkt->data, pkt->length + padding);
1934 pkt->encrypted_len = pkt->length + padding;
1936 /* Ready-to-send packet starts at pkt->data. We return length. */
1937 return pkt->length + padding + maclen;
1941 * Routines called from the main SSH code to send packets. There
1942 * are quite a few of these, because we have two separate
1943 * mechanisms for delaying the sending of packets:
1945 * - In order to send an IGNORE message and a password message in
1946 * a single fixed-length blob, we require the ability to
1947 * concatenate the encrypted forms of those two packets _into_ a
1948 * single blob and then pass it to our <network.h> transport
1949 * layer in one go. Hence, there's a deferment mechanism which
1950 * works after packet encryption.
1952 * - In order to avoid sending any connection-layer messages
1953 * during repeat key exchange, we have to queue up any such
1954 * outgoing messages _before_ they are encrypted (and in
1955 * particular before they're allocated sequence numbers), and
1956 * then send them once we've finished.
1958 * I call these mechanisms `defer' and `queue' respectively, so as
1959 * to distinguish them reasonably easily.
1961 * The functions send_noqueue() and defer_noqueue() free the packet
1962 * structure they are passed. Every outgoing packet goes through
1963 * precisely one of these functions in its life; packets passed to
1964 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1965 * these or get queued, and then when the queue is later emptied
1966 * the packets are all passed to defer_noqueue().
1968 * When using a CBC-mode cipher, it's necessary to ensure that an
1969 * attacker can't provide data to be encrypted using an IV that they
1970 * know. We ensure this by prefixing each packet that might contain
1971 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1972 * mechanism, so in this case send_noqueue() ends up redirecting to
1973 * defer_noqueue(). If you don't like this inefficiency, don't use
1977 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1978 static void ssh_pkt_defersend(Ssh);
1981 * Send an SSH-2 packet immediately, without queuing or deferring.
1983 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1987 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1988 /* We need to send two packets, so use the deferral mechanism. */
1989 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1990 ssh_pkt_defersend(ssh);
1993 len = ssh2_pkt_construct(ssh, pkt);
1994 backlog = s_write(ssh, pkt->data, len);
1995 if (backlog > SSH_MAX_BACKLOG)
1996 ssh_throttle_all(ssh, 1, backlog);
1998 ssh->outgoing_data_size += pkt->encrypted_len;
1999 if (!ssh->kex_in_progress &&
2000 ssh->max_data_size != 0 &&
2001 ssh->outgoing_data_size > ssh->max_data_size)
2002 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2004 ssh_free_packet(pkt);
2008 * Defer an SSH-2 packet.
2010 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2013 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2014 ssh->deferred_len == 0 && !noignore) {
2016 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2017 * get encrypted with a known IV.
2019 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2020 ssh2_pkt_addstring_start(ipkt);
2021 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2023 len = ssh2_pkt_construct(ssh, pkt);
2024 if (ssh->deferred_len + len > ssh->deferred_size) {
2025 ssh->deferred_size = ssh->deferred_len + len + 128;
2026 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2030 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2031 ssh->deferred_len += len;
2032 ssh->deferred_data_size += pkt->encrypted_len;
2033 ssh_free_packet(pkt);
2037 * Queue an SSH-2 packet.
2039 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2041 assert(ssh->queueing);
2043 if (ssh->queuelen >= ssh->queuesize) {
2044 ssh->queuesize = ssh->queuelen + 32;
2045 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2048 ssh->queue[ssh->queuelen++] = pkt;
2052 * Either queue or send a packet, depending on whether queueing is
2055 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2058 ssh2_pkt_queue(ssh, pkt);
2060 ssh2_pkt_send_noqueue(ssh, pkt);
2064 * Either queue or defer a packet, depending on whether queueing is
2067 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2070 ssh2_pkt_queue(ssh, pkt);
2072 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2076 * Send the whole deferred data block constructed by
2077 * ssh2_pkt_defer() or SSH-1's defer_packet().
2079 * The expected use of the defer mechanism is that you call
2080 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2081 * not currently queueing, this simply sets up deferred_send_data
2082 * and then sends it. If we _are_ currently queueing, the calls to
2083 * ssh2_pkt_defer() put the deferred packets on to the queue
2084 * instead, and therefore ssh_pkt_defersend() has no deferred data
2085 * to send. Hence, there's no need to make it conditional on
2088 static void ssh_pkt_defersend(Ssh ssh)
2091 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2092 ssh->deferred_len = ssh->deferred_size = 0;
2093 sfree(ssh->deferred_send_data);
2094 ssh->deferred_send_data = NULL;
2095 if (backlog > SSH_MAX_BACKLOG)
2096 ssh_throttle_all(ssh, 1, backlog);
2098 ssh->outgoing_data_size += ssh->deferred_data_size;
2099 if (!ssh->kex_in_progress &&
2100 ssh->max_data_size != 0 &&
2101 ssh->outgoing_data_size > ssh->max_data_size)
2102 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2103 ssh->deferred_data_size = 0;
2107 * Send a packet whose length needs to be disguised (typically
2108 * passwords or keyboard-interactive responses).
2110 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2116 * The simplest way to do this is to adjust the
2117 * variable-length padding field in the outgoing packet.
2119 * Currently compiled out, because some Cisco SSH servers
2120 * don't like excessively padded packets (bah, why's it
2123 pkt->forcepad = padsize;
2124 ssh2_pkt_send(ssh, pkt);
2129 * If we can't do that, however, an alternative approach is
2130 * to use the pkt_defer mechanism to bundle the packet
2131 * tightly together with an SSH_MSG_IGNORE such that their
2132 * combined length is a constant. So first we construct the
2133 * final form of this packet and defer its sending.
2135 ssh2_pkt_defer(ssh, pkt);
2138 * Now construct an SSH_MSG_IGNORE which includes a string
2139 * that's an exact multiple of the cipher block size. (If
2140 * the cipher is NULL so that the block size is
2141 * unavailable, we don't do this trick at all, because we
2142 * gain nothing by it.)
2144 if (ssh->cscipher) {
2147 stringlen = (256 - ssh->deferred_len);
2148 stringlen += ssh->cscipher->blksize - 1;
2149 stringlen -= (stringlen % ssh->cscipher->blksize);
2152 * Temporarily disable actual compression, so we
2153 * can guarantee to get this string exactly the
2154 * length we want it. The compression-disabling
2155 * routine should return an integer indicating how
2156 * many bytes we should adjust our string length
2160 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2162 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2163 ssh2_pkt_addstring_start(pkt);
2164 for (i = 0; i < stringlen; i++) {
2165 char c = (char) random_byte();
2166 ssh2_pkt_addstring_data(pkt, &c, 1);
2168 ssh2_pkt_defer(ssh, pkt);
2170 ssh_pkt_defersend(ssh);
2175 * Send all queued SSH-2 packets. We send them by means of
2176 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2177 * packets that needed to be lumped together.
2179 static void ssh2_pkt_queuesend(Ssh ssh)
2183 assert(!ssh->queueing);
2185 for (i = 0; i < ssh->queuelen; i++)
2186 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2189 ssh_pkt_defersend(ssh);
2193 void bndebug(char *string, Bignum b)
2197 p = ssh2_mpint_fmt(b, &len);
2198 debug(("%s", string));
2199 for (i = 0; i < len; i++)
2200 debug((" %02x", p[i]));
2206 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2210 p = ssh2_mpint_fmt(b, &len);
2211 hash_string(h, s, p, len);
2216 * Packet decode functions for both SSH-1 and SSH-2.
2218 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2220 unsigned long value;
2221 if (pkt->length - pkt->savedpos < 4)
2222 return 0; /* arrgh, no way to decline (FIXME?) */
2223 value = GET_32BIT(pkt->body + pkt->savedpos);
2227 static int ssh2_pkt_getbool(struct Packet *pkt)
2229 unsigned long value;
2230 if (pkt->length - pkt->savedpos < 1)
2231 return 0; /* arrgh, no way to decline (FIXME?) */
2232 value = pkt->body[pkt->savedpos] != 0;
2236 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2241 if (pkt->length - pkt->savedpos < 4)
2243 len = GET_32BIT(pkt->body + pkt->savedpos);
2248 if (pkt->length - pkt->savedpos < *length)
2250 *p = (char *)(pkt->body + pkt->savedpos);
2251 pkt->savedpos += *length;
2253 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2255 if (pkt->length - pkt->savedpos < length)
2257 pkt->savedpos += length;
2258 return pkt->body + (pkt->savedpos - length);
2260 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2261 unsigned char **keystr)
2265 j = makekey(pkt->body + pkt->savedpos,
2266 pkt->length - pkt->savedpos,
2273 assert(pkt->savedpos < pkt->length);
2277 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2282 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2283 pkt->length - pkt->savedpos, &b);
2291 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2297 ssh_pkt_getstring(pkt, &p, &length);
2302 b = bignum_from_bytes((unsigned char *)p, length);
2307 * Helper function to add an SSH-2 signature blob to a packet.
2308 * Expects to be shown the public key blob as well as the signature
2309 * blob. Normally works just like ssh2_pkt_addstring, but will
2310 * fiddle with the signature packet if necessary for
2311 * BUG_SSH2_RSA_PADDING.
2313 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2314 void *pkblob_v, int pkblob_len,
2315 void *sigblob_v, int sigblob_len)
2317 unsigned char *pkblob = (unsigned char *)pkblob_v;
2318 unsigned char *sigblob = (unsigned char *)sigblob_v;
2320 /* dmemdump(pkblob, pkblob_len); */
2321 /* dmemdump(sigblob, sigblob_len); */
2324 * See if this is in fact an ssh-rsa signature and a buggy
2325 * server; otherwise we can just do this the easy way.
2327 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2328 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2329 int pos, len, siglen;
2332 * Find the byte length of the modulus.
2335 pos = 4+7; /* skip over "ssh-rsa" */
2336 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2337 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2338 pos += 4; /* find modulus itself */
2339 while (len > 0 && pkblob[pos] == 0)
2341 /* debug(("modulus length is %d\n", len)); */
2344 * Now find the signature integer.
2346 pos = 4+7; /* skip over "ssh-rsa" */
2347 siglen = GET_32BIT(sigblob+pos);
2348 /* debug(("signature length is %d\n", siglen)); */
2350 if (len != siglen) {
2351 unsigned char newlen[4];
2352 ssh2_pkt_addstring_start(pkt);
2353 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2354 /* dmemdump(sigblob, pos); */
2355 pos += 4; /* point to start of actual sig */
2356 PUT_32BIT(newlen, len);
2357 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2358 /* dmemdump(newlen, 4); */
2360 while (len-- > siglen) {
2361 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2362 /* dmemdump(newlen, 1); */
2364 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2365 /* dmemdump(sigblob+pos, siglen); */
2369 /* Otherwise fall through and do it the easy way. */
2372 ssh2_pkt_addstring_start(pkt);
2373 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2377 * Examine the remote side's version string and compare it against
2378 * a list of known buggy implementations.
2380 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2382 char *imp; /* pointer to implementation part */
2384 imp += strcspn(imp, "-");
2386 imp += strcspn(imp, "-");
2389 ssh->remote_bugs = 0;
2392 * General notes on server version strings:
2393 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2394 * here -- in particular, we've heard of one that's perfectly happy
2395 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2396 * so we can't distinguish them.
2398 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2399 (ssh->cfg.sshbug_ignore1 == AUTO &&
2400 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2401 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2402 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2403 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2405 * These versions don't support SSH1_MSG_IGNORE, so we have
2406 * to use a different defence against password length
2409 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2410 logevent("We believe remote version has SSH-1 ignore bug");
2413 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2414 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2415 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2417 * These versions need a plain password sent; they can't
2418 * handle having a null and a random length of data after
2421 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2422 logevent("We believe remote version needs a plain SSH-1 password");
2425 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2426 (ssh->cfg.sshbug_rsa1 == AUTO &&
2427 (!strcmp(imp, "Cisco-1.25")))) {
2429 * These versions apparently have no clue whatever about
2430 * RSA authentication and will panic and die if they see
2431 * an AUTH_RSA message.
2433 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2434 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2437 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2438 (ssh->cfg.sshbug_hmac2 == AUTO &&
2439 !wc_match("* VShell", imp) &&
2440 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2441 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2442 wc_match("2.1 *", imp)))) {
2444 * These versions have the HMAC bug.
2446 ssh->remote_bugs |= BUG_SSH2_HMAC;
2447 logevent("We believe remote version has SSH-2 HMAC bug");
2450 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2451 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2452 !wc_match("* VShell", imp) &&
2453 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2455 * These versions have the key-derivation bug (failing to
2456 * include the literal shared secret in the hashes that
2457 * generate the keys).
2459 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2460 logevent("We believe remote version has SSH-2 key-derivation bug");
2463 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2464 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2465 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2466 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2468 * These versions have the SSH-2 RSA padding bug.
2470 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2471 logevent("We believe remote version has SSH-2 RSA padding bug");
2474 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2475 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2476 wc_match("OpenSSH_2.[0-2]*", imp))) {
2478 * These versions have the SSH-2 session-ID bug in
2479 * public-key authentication.
2481 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2482 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2485 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2486 (ssh->cfg.sshbug_rekey2 == AUTO &&
2487 (wc_match("DigiSSH_2.0", imp) ||
2488 wc_match("OpenSSH_2.[0-4]*", imp) ||
2489 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2490 wc_match("Sun_SSH_1.0", imp) ||
2491 wc_match("Sun_SSH_1.0.1", imp) ||
2492 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2493 wc_match("WeOnlyDo-*", imp)))) {
2495 * These versions have the SSH-2 rekey bug.
2497 ssh->remote_bugs |= BUG_SSH2_REKEY;
2498 logevent("We believe remote version has SSH-2 rekey bug");
2501 if (ssh->cfg.sshbug_maxpkt2 == FORCE_ON ||
2502 (ssh->cfg.sshbug_maxpkt2 == AUTO &&
2503 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2504 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2506 * This version ignores our makpkt and needs to be throttled.
2508 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2509 logevent("We believe remote version ignores SSH-2 maximum packet size");
2514 * The `software version' part of an SSH version string is required
2515 * to contain no spaces or minus signs.
2517 static void ssh_fix_verstring(char *str)
2519 /* Eat "SSH-<protoversion>-". */
2520 assert(*str == 'S'); str++;
2521 assert(*str == 'S'); str++;
2522 assert(*str == 'H'); str++;
2523 assert(*str == '-'); str++;
2524 while (*str && *str != '-') str++;
2525 assert(*str == '-'); str++;
2527 /* Convert minus signs and spaces in the remaining string into
2530 if (*str == '-' || *str == ' ')
2537 * Send an appropriate SSH version string.
2539 static void ssh_send_verstring(Ssh ssh, char *svers)
2543 if (ssh->version == 2) {
2545 * Construct a v2 version string.
2547 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2550 * Construct a v1 version string.
2552 verstring = dupprintf("SSH-%s-%s\012",
2553 (ssh_versioncmp(svers, "1.5") <= 0 ?
2558 ssh_fix_verstring(verstring);
2560 if (ssh->version == 2) {
2563 * Record our version string.
2565 len = strcspn(verstring, "\015\012");
2566 ssh->v_c = snewn(len + 1, char);
2567 memcpy(ssh->v_c, verstring, len);
2571 logeventf(ssh, "We claim version: %.*s",
2572 strcspn(verstring, "\015\012"), verstring);
2573 s_write(ssh, verstring, strlen(verstring));
2577 static int do_ssh_init(Ssh ssh, unsigned char c)
2579 struct do_ssh_init_state {
2587 crState(do_ssh_init_state);
2589 crBegin(ssh->do_ssh_init_crstate);
2591 /* Search for a line beginning with the string "SSH-" in the input. */
2593 if (c != 'S') goto no;
2595 if (c != 'S') goto no;
2597 if (c != 'H') goto no;
2599 if (c != '-') goto no;
2608 s->vstring = snewn(s->vstrsize, char);
2609 strcpy(s->vstring, "SSH-");
2613 crReturn(1); /* get another char */
2614 if (s->vslen >= s->vstrsize - 1) {
2616 s->vstring = sresize(s->vstring, s->vstrsize, char);
2618 s->vstring[s->vslen++] = c;
2621 s->version[s->i] = '\0';
2623 } else if (s->i < sizeof(s->version) - 1)
2624 s->version[s->i++] = c;
2625 } else if (c == '\012')
2629 ssh->agentfwd_enabled = FALSE;
2630 ssh->rdpkt2_state.incoming_sequence = 0;
2632 s->vstring[s->vslen] = 0;
2633 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2634 logeventf(ssh, "Server version: %s", s->vstring);
2635 ssh_detect_bugs(ssh, s->vstring);
2638 * Decide which SSH protocol version to support.
2641 /* Anything strictly below "2.0" means protocol 1 is supported. */
2642 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2643 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2644 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2646 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2647 bombout(("SSH protocol version 1 required by user but not provided by server"));
2650 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2651 bombout(("SSH protocol version 2 required by user but not provided by server"));
2655 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1))
2660 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2662 /* Send the version string, if we haven't already */
2663 if (ssh->cfg.sshprot != 3)
2664 ssh_send_verstring(ssh, s->version);
2666 if (ssh->version == 2) {
2669 * Record their version string.
2671 len = strcspn(s->vstring, "\015\012");
2672 ssh->v_s = snewn(len + 1, char);
2673 memcpy(ssh->v_s, s->vstring, len);
2677 * Initialise SSH-2 protocol.
2679 ssh->protocol = ssh2_protocol;
2680 ssh2_protocol_setup(ssh);
2681 ssh->s_rdpkt = ssh2_rdpkt;
2684 * Initialise SSH-1 protocol.
2686 ssh->protocol = ssh1_protocol;
2687 ssh1_protocol_setup(ssh);
2688 ssh->s_rdpkt = ssh1_rdpkt;
2690 if (ssh->version == 2)
2691 do_ssh2_transport(ssh, NULL, -1, NULL);
2693 update_specials_menu(ssh->frontend);
2694 ssh->state = SSH_STATE_BEFORE_SIZE;
2695 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2702 static void ssh_process_incoming_data(Ssh ssh,
2703 unsigned char **data, int *datalen)
2705 struct Packet *pktin;
2707 pktin = ssh->s_rdpkt(ssh, data, datalen);
2709 ssh->protocol(ssh, NULL, 0, pktin);
2710 ssh_free_packet(pktin);
2714 static void ssh_queue_incoming_data(Ssh ssh,
2715 unsigned char **data, int *datalen)
2717 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2722 static void ssh_process_queued_incoming_data(Ssh ssh)
2725 unsigned char *data;
2728 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2729 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2733 while (!ssh->frozen && len > 0)
2734 ssh_process_incoming_data(ssh, &data, &len);
2737 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2741 static void ssh_set_frozen(Ssh ssh, int frozen)
2744 sk_set_frozen(ssh->s, frozen);
2745 ssh->frozen = frozen;
2748 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2750 /* Log raw data, if we're in that mode. */
2752 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2755 crBegin(ssh->ssh_gotdata_crstate);
2758 * To begin with, feed the characters one by one to the
2759 * protocol initialisation / selection function do_ssh_init().
2760 * When that returns 0, we're done with the initial greeting
2761 * exchange and can move on to packet discipline.
2764 int ret; /* need not be kept across crReturn */
2766 crReturnV; /* more data please */
2767 ret = do_ssh_init(ssh, *data);
2775 * We emerge from that loop when the initial negotiation is
2776 * over and we have selected an s_rdpkt function. Now pass
2777 * everything to s_rdpkt, and then pass the resulting packets
2778 * to the proper protocol handler.
2782 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2784 ssh_queue_incoming_data(ssh, &data, &datalen);
2785 /* This uses up all data and cannot cause anything interesting
2786 * to happen; indeed, for anything to happen at all, we must
2787 * return, so break out. */
2789 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2790 /* This uses up some or all data, and may freeze the
2792 ssh_process_queued_incoming_data(ssh);
2794 /* This uses up some or all data, and may freeze the
2796 ssh_process_incoming_data(ssh, &data, &datalen);
2798 /* FIXME this is probably EBW. */
2799 if (ssh->state == SSH_STATE_CLOSED)
2802 /* We're out of data. Go and get some more. */
2808 static int ssh_do_close(Ssh ssh, int notify_exit)
2811 struct ssh_channel *c;
2813 ssh->state = SSH_STATE_CLOSED;
2814 expire_timer_context(ssh);
2819 notify_remote_exit(ssh->frontend);
2824 * Now we must shut down any port- and X-forwarded channels going
2825 * through this connection.
2827 if (ssh->channels) {
2828 while (NULL != (c = index234(ssh->channels, 0))) {
2831 x11_close(c->u.x11.s);
2834 pfd_close(c->u.pfd.s);
2837 del234(ssh->channels, c); /* moving next one to index 0 */
2838 if (ssh->version == 2)
2839 bufchain_clear(&c->v.v2.outbuffer);
2844 * Go through port-forwardings, and close any associated
2845 * listening sockets.
2847 if (ssh->portfwds) {
2848 struct ssh_portfwd *pf;
2849 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2850 /* Dispose of any listening socket. */
2852 pfd_terminate(pf->local);
2853 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2861 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2862 const char *error_msg, int error_code)
2864 Ssh ssh = (Ssh) plug;
2865 char addrbuf[256], *msg;
2867 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2870 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2872 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2878 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2881 Ssh ssh = (Ssh) plug;
2882 int need_notify = ssh_do_close(ssh, FALSE);
2885 if (!ssh->close_expected)
2886 error_msg = "Server unexpectedly closed network connection";
2888 error_msg = "Server closed network connection";
2891 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2895 notify_remote_exit(ssh->frontend);
2898 logevent(error_msg);
2899 if (!ssh->close_expected || !ssh->clean_exit)
2900 connection_fatal(ssh->frontend, "%s", error_msg);
2904 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2906 Ssh ssh = (Ssh) plug;
2907 ssh_gotdata(ssh, (unsigned char *)data, len);
2908 if (ssh->state == SSH_STATE_CLOSED) {
2909 ssh_do_close(ssh, TRUE);
2915 static void ssh_sent(Plug plug, int bufsize)
2917 Ssh ssh = (Ssh) plug;
2919 * If the send backlog on the SSH socket itself clears, we
2920 * should unthrottle the whole world if it was throttled.
2922 if (bufsize < SSH_MAX_BACKLOG)
2923 ssh_throttle_all(ssh, 0, bufsize);
2927 * Connect to specified host and port.
2928 * Returns an error message, or NULL on success.
2929 * Also places the canonical host name into `realhost'. It must be
2930 * freed by the caller.
2932 static const char *connect_to_host(Ssh ssh, char *host, int port,
2933 char **realhost, int nodelay, int keepalive)
2935 static const struct plug_function_table fn_table = {
2946 if (*ssh->cfg.loghost) {
2949 ssh->savedhost = dupstr(ssh->cfg.loghost);
2950 ssh->savedport = 22; /* default ssh port */
2953 * A colon suffix on savedhost also lets us affect
2956 * (FIXME: do something about IPv6 address literals here.)
2958 colon = strrchr(ssh->savedhost, ':');
2962 ssh->savedport = atoi(colon);
2965 ssh->savedhost = dupstr(host);
2967 port = 22; /* default ssh port */
2968 ssh->savedport = port;
2974 logeventf(ssh, "Looking up host \"%s\"%s", host,
2975 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2976 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2977 addr = name_lookup(host, port, realhost, &ssh->cfg,
2978 ssh->cfg.addressfamily);
2979 if ((err = sk_addr_error(addr)) != NULL) {
2983 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
2988 ssh->fn = &fn_table;
2989 ssh->s = new_connection(addr, *realhost, port,
2990 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2991 if ((err = sk_socket_error(ssh->s)) != NULL) {
2993 notify_remote_exit(ssh->frontend);
2998 * If the SSH version number's fixed, set it now, and if it's SSH-2,
2999 * send the version string too.
3001 if (ssh->cfg.sshprot == 0)
3003 if (ssh->cfg.sshprot == 3) {
3005 ssh_send_verstring(ssh, NULL);
3009 * loghost, if configured, overrides realhost.
3011 if (*ssh->cfg.loghost) {
3013 *realhost = dupstr(ssh->cfg.loghost);
3020 * Throttle or unthrottle the SSH connection.
3022 static void ssh_throttle_conn(Ssh ssh, int adjust)
3024 int old_count = ssh->conn_throttle_count;
3025 ssh->conn_throttle_count += adjust;
3026 assert(ssh->conn_throttle_count >= 0);
3027 if (ssh->conn_throttle_count && !old_count) {
3028 ssh_set_frozen(ssh, 1);
3029 } else if (!ssh->conn_throttle_count && old_count) {
3030 ssh_set_frozen(ssh, 0);
3035 * Throttle or unthrottle _all_ local data streams (for when sends
3036 * on the SSH connection itself back up).
3038 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3041 struct ssh_channel *c;
3043 if (enable == ssh->throttled_all)
3045 ssh->throttled_all = enable;
3046 ssh->overall_bufsize = bufsize;
3049 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3051 case CHAN_MAINSESSION:
3053 * This is treated separately, outside the switch.
3057 x11_override_throttle(c->u.x11.s, enable);
3060 /* Agent channels require no buffer management. */
3063 pfd_override_throttle(c->u.pfd.s, enable);
3069 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3071 Ssh ssh = (Ssh) sshv;
3073 ssh->agent_response = reply;
3074 ssh->agent_response_len = replylen;
3076 if (ssh->version == 1)
3077 do_ssh1_login(ssh, NULL, -1, NULL);
3079 do_ssh2_authconn(ssh, NULL, -1, NULL);
3082 static void ssh_dialog_callback(void *sshv, int ret)
3084 Ssh ssh = (Ssh) sshv;
3086 ssh->user_response = ret;
3088 if (ssh->version == 1)
3089 do_ssh1_login(ssh, NULL, -1, NULL);
3091 do_ssh2_transport(ssh, NULL, -1, NULL);
3094 * This may have unfrozen the SSH connection, so do a
3097 ssh_process_queued_incoming_data(ssh);
3100 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3102 struct ssh_channel *c = (struct ssh_channel *)cv;
3104 void *sentreply = reply;
3107 /* Fake SSH_AGENT_FAILURE. */
3108 sentreply = "\0\0\0\1\5";
3111 if (ssh->version == 2) {
3112 ssh2_add_channel_data(c, sentreply, replylen);
3115 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3116 PKT_INT, c->remoteid,
3119 PKT_DATA, sentreply, replylen,
3128 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3129 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3130 * => log `wire_reason'.
3132 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3133 int code, int clean_exit)
3137 client_reason = wire_reason;
3139 error = dupprintf("Disconnected: %s", client_reason);
3141 error = dupstr("Disconnected");
3143 if (ssh->version == 1) {
3144 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3146 } else if (ssh->version == 2) {
3147 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3148 ssh2_pkt_adduint32(pktout, code);
3149 ssh2_pkt_addstring(pktout, wire_reason);
3150 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3151 ssh2_pkt_send_noqueue(ssh, pktout);
3154 ssh->close_expected = TRUE;
3155 ssh->clean_exit = clean_exit;
3156 ssh_closing((Plug)ssh, error, 0, 0);
3161 * Handle the key exchange and user authentication phases.
3163 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3164 struct Packet *pktin)
3167 unsigned char cookie[8], *ptr;
3168 struct RSAKey servkey, hostkey;
3169 struct MD5Context md5c;
3170 struct do_ssh1_login_state {
3172 unsigned char *rsabuf, *keystr1, *keystr2;
3173 unsigned long supported_ciphers_mask, supported_auths_mask;
3174 int tried_publickey, tried_agent;
3175 int tis_auth_refused, ccard_auth_refused;
3176 unsigned char session_id[16];
3179 void *publickey_blob;
3180 int publickey_bloblen;
3181 char *publickey_comment;
3182 int publickey_encrypted;
3183 prompts_t *cur_prompt;
3186 unsigned char request[5], *response, *p;
3196 crState(do_ssh1_login_state);
3198 crBegin(ssh->do_ssh1_login_crstate);
3203 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3204 bombout(("Public key packet not received"));
3208 logevent("Received public keys");
3210 ptr = ssh_pkt_getdata(pktin, 8);
3212 bombout(("SSH-1 public key packet stopped before random cookie"));
3215 memcpy(cookie, ptr, 8);
3217 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3218 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3219 bombout(("Failed to read SSH-1 public keys from public key packet"));
3224 * Log the host key fingerprint.
3228 logevent("Host key fingerprint is:");
3229 strcpy(logmsg, " ");
3230 hostkey.comment = NULL;
3231 rsa_fingerprint(logmsg + strlen(logmsg),
3232 sizeof(logmsg) - strlen(logmsg), &hostkey);
3236 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3237 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3238 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3239 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3240 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3242 ssh->v1_local_protoflags =
3243 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3244 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3247 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3248 MD5Update(&md5c, s->keystr1, servkey.bytes);
3249 MD5Update(&md5c, cookie, 8);
3250 MD5Final(s->session_id, &md5c);
3252 for (i = 0; i < 32; i++)
3253 ssh->session_key[i] = random_byte();
3256 * Verify that the `bits' and `bytes' parameters match.
3258 if (hostkey.bits > hostkey.bytes * 8 ||
3259 servkey.bits > servkey.bytes * 8) {
3260 bombout(("SSH-1 public keys were badly formatted"));
3264 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3266 s->rsabuf = snewn(s->len, unsigned char);
3269 * Verify the host key.
3273 * First format the key into a string.
3275 int len = rsastr_len(&hostkey);
3276 char fingerprint[100];
3277 char *keystr = snewn(len, char);
3278 rsastr_fmt(keystr, &hostkey);
3279 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3281 ssh_set_frozen(ssh, 1);
3282 s->dlgret = verify_ssh_host_key(ssh->frontend,
3283 ssh->savedhost, ssh->savedport,
3284 "rsa", keystr, fingerprint,
3285 ssh_dialog_callback, ssh);
3287 if (s->dlgret < 0) {
3291 bombout(("Unexpected data from server while waiting"
3292 " for user host key response"));
3295 } while (pktin || inlen > 0);
3296 s->dlgret = ssh->user_response;
3298 ssh_set_frozen(ssh, 0);
3300 if (s->dlgret == 0) {
3301 ssh_disconnect(ssh, "User aborted at host key verification",
3307 for (i = 0; i < 32; i++) {
3308 s->rsabuf[i] = ssh->session_key[i];
3310 s->rsabuf[i] ^= s->session_id[i];
3313 if (hostkey.bytes > servkey.bytes) {
3314 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3316 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3318 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3320 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3323 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3327 logevent("Encrypted session key");
3330 int cipher_chosen = 0, warn = 0;
3331 char *cipher_string = NULL;
3333 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3334 int next_cipher = ssh->cfg.ssh_cipherlist[i];
3335 if (next_cipher == CIPHER_WARN) {
3336 /* If/when we choose a cipher, warn about it */
3338 } else if (next_cipher == CIPHER_AES) {
3339 /* XXX Probably don't need to mention this. */
3340 logevent("AES not supported in SSH-1, skipping");
3342 switch (next_cipher) {
3343 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3344 cipher_string = "3DES"; break;
3345 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3346 cipher_string = "Blowfish"; break;
3347 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3348 cipher_string = "single-DES"; break;
3350 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3354 if (!cipher_chosen) {
3355 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3356 bombout(("Server violates SSH-1 protocol by not "
3357 "supporting 3DES encryption"));
3359 /* shouldn't happen */
3360 bombout(("No supported ciphers found"));
3364 /* Warn about chosen cipher if necessary. */
3366 ssh_set_frozen(ssh, 1);
3367 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3368 ssh_dialog_callback, ssh);
3369 if (s->dlgret < 0) {
3373 bombout(("Unexpected data from server while waiting"
3374 " for user response"));
3377 } while (pktin || inlen > 0);
3378 s->dlgret = ssh->user_response;
3380 ssh_set_frozen(ssh, 0);
3381 if (s->dlgret == 0) {
3382 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3389 switch (s->cipher_type) {
3390 case SSH_CIPHER_3DES:
3391 logevent("Using 3DES encryption");
3393 case SSH_CIPHER_DES:
3394 logevent("Using single-DES encryption");
3396 case SSH_CIPHER_BLOWFISH:
3397 logevent("Using Blowfish encryption");
3401 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3402 PKT_CHAR, s->cipher_type,
3403 PKT_DATA, cookie, 8,
3404 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3405 PKT_DATA, s->rsabuf, s->len,
3406 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3408 logevent("Trying to enable encryption...");
3412 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3413 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3415 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3416 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3417 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3419 ssh->crcda_ctx = crcda_make_context();
3420 logevent("Installing CRC compensation attack detector");
3422 if (servkey.modulus) {
3423 sfree(servkey.modulus);
3424 servkey.modulus = NULL;
3426 if (servkey.exponent) {
3427 sfree(servkey.exponent);
3428 servkey.exponent = NULL;
3430 if (hostkey.modulus) {
3431 sfree(hostkey.modulus);
3432 hostkey.modulus = NULL;
3434 if (hostkey.exponent) {
3435 sfree(hostkey.exponent);
3436 hostkey.exponent = NULL;
3440 if (pktin->type != SSH1_SMSG_SUCCESS) {
3441 bombout(("Encryption not successfully enabled"));
3445 logevent("Successfully started encryption");
3447 fflush(stdout); /* FIXME eh? */
3449 if (!get_remote_username(&ssh->cfg, s->username,
3450 sizeof(s->username))) {
3451 int ret; /* need not be kept over crReturn */
3452 s->cur_prompt = new_prompts(ssh->frontend);
3453 s->cur_prompt->to_server = TRUE;
3454 s->cur_prompt->name = dupstr("SSH login name");
3455 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
3456 lenof(s->username));
3457 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3460 crWaitUntil(!pktin);
3461 ret = get_userpass_input(s->cur_prompt, in, inlen);
3466 * Failed to get a username. Terminate.
3468 free_prompts(s->cur_prompt);
3469 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3472 memcpy(s->username, s->cur_prompt->prompts[0]->result,
3473 lenof(s->username));
3474 free_prompts(s->cur_prompt);
3477 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3479 char *userlog = dupprintf("Sent username \"%s\"", s->username);
3481 if (flags & FLAG_INTERACTIVE &&
3482 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3483 c_write_str(ssh, userlog);
3484 c_write_str(ssh, "\r\n");
3492 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3493 /* We must not attempt PK auth. Pretend we've already tried it. */
3494 s->tried_publickey = s->tried_agent = 1;
3496 s->tried_publickey = s->tried_agent = 0;
3498 s->tis_auth_refused = s->ccard_auth_refused = 0;
3500 * Load the public half of any configured keyfile for later use.
3502 if (!filename_is_null(ssh->cfg.keyfile)) {
3504 logeventf(ssh, "Reading private key file \"%.150s\"",
3505 filename_to_str(&ssh->cfg.keyfile));
3506 keytype = key_type(&ssh->cfg.keyfile);
3507 if (keytype == SSH_KEYTYPE_SSH1) {
3509 if (rsakey_pubblob(&ssh->cfg.keyfile,
3510 &s->publickey_blob, &s->publickey_bloblen,
3511 &s->publickey_comment, &error)) {
3512 s->publickey_encrypted = rsakey_encrypted(&ssh->cfg.keyfile,
3516 logeventf(ssh, "Unable to load private key (%s)", error);
3517 msgbuf = dupprintf("Unable to load private key file "
3518 "\"%.150s\" (%s)\r\n",
3519 filename_to_str(&ssh->cfg.keyfile),
3521 c_write_str(ssh, msgbuf);
3523 s->publickey_blob = NULL;
3527 logeventf(ssh, "Unable to use this key file (%s)",
3528 key_type_to_str(keytype));
3529 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3531 filename_to_str(&ssh->cfg.keyfile),
3532 key_type_to_str(keytype));
3533 c_write_str(ssh, msgbuf);
3535 s->publickey_blob = NULL;
3538 s->publickey_blob = NULL;
3540 while (pktin->type == SSH1_SMSG_FAILURE) {
3541 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3543 if (ssh->cfg.tryagent && agent_exists() && !s->tried_agent) {
3545 * Attempt RSA authentication using Pageant.
3551 logevent("Pageant is running. Requesting keys.");
3553 /* Request the keys held by the agent. */
3554 PUT_32BIT(s->request, 1);
3555 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3556 if (!agent_query(s->request, 5, &r, &s->responselen,
3557 ssh_agent_callback, ssh)) {
3561 bombout(("Unexpected data from server while waiting"
3562 " for agent response"));
3565 } while (pktin || inlen > 0);
3566 r = ssh->agent_response;
3567 s->responselen = ssh->agent_response_len;
3569 s->response = (unsigned char *) r;
3570 if (s->response && s->responselen >= 5 &&
3571 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3572 s->p = s->response + 5;
3573 s->nkeys = GET_32BIT(s->p);
3575 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3576 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3577 unsigned char *pkblob = s->p;
3581 do { /* do while (0) to make breaking easy */
3582 n = ssh1_read_bignum
3583 (s->p, s->responselen-(s->p-s->response),
3588 n = ssh1_read_bignum
3589 (s->p, s->responselen-(s->p-s->response),
3594 if (s->responselen - (s->p-s->response) < 4)
3596 s->commentlen = GET_32BIT(s->p);
3598 if (s->responselen - (s->p-s->response) <
3601 s->commentp = (char *)s->p;
3602 s->p += s->commentlen;
3606 logevent("Pageant key list packet was truncated");
3610 if (s->publickey_blob) {
3611 if (!memcmp(pkblob, s->publickey_blob,
3612 s->publickey_bloblen)) {
3613 logeventf(ssh, "Pageant key #%d matches "
3614 "configured key file", s->keyi);
3615 s->tried_publickey = 1;
3617 /* Skip non-configured key */
3620 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3621 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3622 PKT_BIGNUM, s->key.modulus, PKT_END);
3624 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3625 logevent("Key refused");
3628 logevent("Received RSA challenge");
3629 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3630 bombout(("Server's RSA challenge was badly formatted"));
3635 char *agentreq, *q, *ret;
3638 len = 1 + 4; /* message type, bit count */
3639 len += ssh1_bignum_length(s->key.exponent);
3640 len += ssh1_bignum_length(s->key.modulus);
3641 len += ssh1_bignum_length(s->challenge);
3642 len += 16; /* session id */
3643 len += 4; /* response format */
3644 agentreq = snewn(4 + len, char);
3645 PUT_32BIT(agentreq, len);
3647 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3648 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3650 q += ssh1_write_bignum(q, s->key.exponent);
3651 q += ssh1_write_bignum(q, s->key.modulus);
3652 q += ssh1_write_bignum(q, s->challenge);
3653 memcpy(q, s->session_id, 16);
3655 PUT_32BIT(q, 1); /* response format */
3656 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3657 ssh_agent_callback, ssh)) {
3662 bombout(("Unexpected data from server"
3663 " while waiting for agent"
3667 } while (pktin || inlen > 0);
3668 vret = ssh->agent_response;
3669 retlen = ssh->agent_response_len;
3674 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3675 logevent("Sending Pageant's response");
3676 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3677 PKT_DATA, ret + 5, 16,
3681 if (pktin->type == SSH1_SMSG_SUCCESS) {
3683 ("Pageant's response accepted");
3684 if (flags & FLAG_VERBOSE) {
3685 c_write_str(ssh, "Authenticated using"
3687 c_write(ssh, s->commentp,
3689 c_write_str(ssh, "\" from agent\r\n");
3694 ("Pageant's response not accepted");
3697 ("Pageant failed to answer challenge");
3701 logevent("No reply received from Pageant");
3704 freebn(s->key.exponent);
3705 freebn(s->key.modulus);
3706 freebn(s->challenge);
3711 if (s->publickey_blob && !s->tried_publickey)
3712 logevent("Configured key file not in Pageant");
3717 if (s->publickey_blob && !s->tried_publickey) {
3719 * Try public key authentication with the specified
3722 int got_passphrase; /* need not be kept over crReturn */
3723 if (flags & FLAG_VERBOSE)
3724 c_write_str(ssh, "Trying public key authentication.\r\n");
3725 logeventf(ssh, "Trying public key \"%s\"",
3726 filename_to_str(&ssh->cfg.keyfile));
3727 s->tried_publickey = 1;
3728 got_passphrase = FALSE;
3729 while (!got_passphrase) {
3731 * Get a passphrase, if necessary.
3733 char *passphrase = NULL; /* only written after crReturn */
3735 if (!s->publickey_encrypted) {
3736 if (flags & FLAG_VERBOSE)
3737 c_write_str(ssh, "No passphrase required.\r\n");
3740 int ret; /* need not be kept over crReturn */
3741 s->cur_prompt = new_prompts(ssh->frontend);
3742 s->cur_prompt->to_server = FALSE;
3743 s->cur_prompt->name = dupstr("SSH key passphrase");
3744 add_prompt(s->cur_prompt,
3745 dupprintf("Passphrase for key \"%.100s\": ",
3746 s->publickey_comment),
3747 FALSE, SSH_MAX_PASSWORD_LEN);
3748 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3751 crWaitUntil(!pktin);
3752 ret = get_userpass_input(s->cur_prompt, in, inlen);
3756 /* Failed to get a passphrase. Terminate. */
3757 free_prompts(s->cur_prompt);
3758 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3762 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3763 free_prompts(s->cur_prompt);
3766 * Try decrypting key with passphrase.
3768 ret = loadrsakey(&ssh->cfg.keyfile, &s->key, passphrase,
3771 memset(passphrase, 0, strlen(passphrase));
3775 /* Correct passphrase. */
3776 got_passphrase = TRUE;
3777 } else if (ret == 0) {
3778 c_write_str(ssh, "Couldn't load private key from ");
3779 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3780 c_write_str(ssh, " (");
3781 c_write_str(ssh, error);
3782 c_write_str(ssh, ").\r\n");
3783 got_passphrase = FALSE;
3784 break; /* go and try something else */
3785 } else if (ret == -1) {
3786 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3787 got_passphrase = FALSE;
3790 assert(0 && "unexpected return from loadrsakey()");
3791 got_passphrase = FALSE; /* placate optimisers */
3795 if (got_passphrase) {
3798 * Send a public key attempt.
3800 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3801 PKT_BIGNUM, s->key.modulus, PKT_END);
3804 if (pktin->type == SSH1_SMSG_FAILURE) {
3805 c_write_str(ssh, "Server refused our public key.\r\n");
3806 continue; /* go and try something else */
3808 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3809 bombout(("Bizarre response to offer of public key"));
3815 unsigned char buffer[32];
3816 Bignum challenge, response;
3818 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3819 bombout(("Server's RSA challenge was badly formatted"));
3822 response = rsadecrypt(challenge, &s->key);
3823 freebn(s->key.private_exponent);/* burn the evidence */
3825 for (i = 0; i < 32; i++) {
3826 buffer[i] = bignum_byte(response, 31 - i);
3830 MD5Update(&md5c, buffer, 32);
3831 MD5Update(&md5c, s->session_id, 16);
3832 MD5Final(buffer, &md5c);
3834 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3835 PKT_DATA, buffer, 16, PKT_END);
3842 if (pktin->type == SSH1_SMSG_FAILURE) {
3843 if (flags & FLAG_VERBOSE)
3844 c_write_str(ssh, "Failed to authenticate with"
3845 " our public key.\r\n");
3846 continue; /* go and try something else */
3847 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3848 bombout(("Bizarre response to RSA authentication response"));
3852 break; /* we're through! */
3858 * Otherwise, try various forms of password-like authentication.
3860 s->cur_prompt = new_prompts(ssh->frontend);
3862 if (ssh->cfg.try_tis_auth &&
3863 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3864 !s->tis_auth_refused) {
3865 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3866 logevent("Requested TIS authentication");
3867 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3869 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3870 logevent("TIS authentication declined");
3871 if (flags & FLAG_INTERACTIVE)
3872 c_write_str(ssh, "TIS authentication refused.\r\n");
3873 s->tis_auth_refused = 1;
3878 char *instr_suf, *prompt;
3880 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3882 bombout(("TIS challenge packet was badly formed"));
3885 logevent("Received TIS challenge");
3886 s->cur_prompt->to_server = TRUE;
3887 s->cur_prompt->name = dupstr("SSH TIS authentication");
3888 /* Prompt heuristic comes from OpenSSH */
3889 if (memchr(challenge, '\n', challengelen)) {
3890 instr_suf = dupstr("");
3891 prompt = dupprintf("%.*s", challengelen, challenge);
3893 instr_suf = dupprintf("%.*s", challengelen, challenge);
3894 prompt = dupstr("Response: ");
3896 s->cur_prompt->instruction =
3897 dupprintf("Using TIS authentication.%s%s",
3898 (*instr_suf) ? "\n" : "",
3900 s->cur_prompt->instr_reqd = TRUE;
3901 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3905 if (ssh->cfg.try_tis_auth &&
3906 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3907 !s->ccard_auth_refused) {
3908 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3909 logevent("Requested CryptoCard authentication");
3910 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3912 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3913 logevent("CryptoCard authentication declined");
3914 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3915 s->ccard_auth_refused = 1;
3920 char *instr_suf, *prompt;
3922 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3924 bombout(("CryptoCard challenge packet was badly formed"));
3927 logevent("Received CryptoCard challenge");
3928 s->cur_prompt->to_server = TRUE;
3929 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3930 s->cur_prompt->name_reqd = FALSE;
3931 /* Prompt heuristic comes from OpenSSH */
3932 if (memchr(challenge, '\n', challengelen)) {
3933 instr_suf = dupstr("");
3934 prompt = dupprintf("%.*s", challengelen, challenge);
3936 instr_suf = dupprintf("%.*s", challengelen, challenge);
3937 prompt = dupstr("Response: ");
3939 s->cur_prompt->instruction =
3940 dupprintf("Using CryptoCard authentication.%s%s",
3941 (*instr_suf) ? "\n" : "",
3943 s->cur_prompt->instr_reqd = TRUE;
3944 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3948 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3949 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
3950 bombout(("No supported authentication methods available"));
3953 s->cur_prompt->to_server = TRUE;
3954 s->cur_prompt->name = dupstr("SSH password");
3955 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
3956 s->username, ssh->savedhost),
3957 FALSE, SSH_MAX_PASSWORD_LEN);
3961 * Show password prompt, having first obtained it via a TIS
3962 * or CryptoCard exchange if we're doing TIS or CryptoCard
3966 int ret; /* need not be kept over crReturn */
3967 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3970 crWaitUntil(!pktin);
3971 ret = get_userpass_input(s->cur_prompt, in, inlen);
3976 * Failed to get a password (for example
3977 * because one was supplied on the command line
3978 * which has already failed to work). Terminate.
3980 free_prompts(s->cur_prompt);
3981 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
3986 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3988 * Defence against traffic analysis: we send a
3989 * whole bunch of packets containing strings of
3990 * different lengths. One of these strings is the
3991 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3992 * The others are all random data in
3993 * SSH1_MSG_IGNORE packets. This way a passive
3994 * listener can't tell which is the password, and
3995 * hence can't deduce the password length.
3997 * Anybody with a password length greater than 16
3998 * bytes is going to have enough entropy in their
3999 * password that a listener won't find it _that_
4000 * much help to know how long it is. So what we'll
4003 * - if password length < 16, we send 15 packets
4004 * containing string lengths 1 through 15
4006 * - otherwise, we let N be the nearest multiple
4007 * of 8 below the password length, and send 8
4008 * packets containing string lengths N through
4009 * N+7. This won't obscure the order of
4010 * magnitude of the password length, but it will
4011 * introduce a bit of extra uncertainty.
4013 * A few servers can't deal with SSH1_MSG_IGNORE, at
4014 * least in this context. For these servers, we need
4015 * an alternative defence. We make use of the fact
4016 * that the password is interpreted as a C string:
4017 * so we can append a NUL, then some random data.
4019 * A few servers can deal with neither SSH1_MSG_IGNORE
4020 * here _nor_ a padded password string.
4021 * For these servers we are left with no defences
4022 * against password length sniffing.
4024 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4025 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4027 * The server can deal with SSH1_MSG_IGNORE, so
4028 * we can use the primary defence.
4030 int bottom, top, pwlen, i;
4033 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4035 bottom = 0; /* zero length passwords are OK! :-) */
4038 bottom = pwlen & ~7;
4042 assert(pwlen >= bottom && pwlen <= top);
4044 randomstr = snewn(top + 1, char);
4046 for (i = bottom; i <= top; i++) {
4048 defer_packet(ssh, s->pwpkt_type,
4049 PKTT_PASSWORD, PKT_STR,
4050 s->cur_prompt->prompts[0]->result,
4051 PKTT_OTHER, PKT_END);
4053 for (j = 0; j < i; j++) {
4055 randomstr[j] = random_byte();
4056 } while (randomstr[j] == '\0');
4058 randomstr[i] = '\0';
4059 defer_packet(ssh, SSH1_MSG_IGNORE,
4060 PKT_STR, randomstr, PKT_END);
4063 logevent("Sending password with camouflage packets");
4064 ssh_pkt_defersend(ssh);
4067 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4069 * The server can't deal with SSH1_MSG_IGNORE
4070 * but can deal with padded passwords, so we
4071 * can use the secondary defence.
4077 len = strlen(s->cur_prompt->prompts[0]->result);
4078 if (len < sizeof(string)) {
4080 strcpy(string, s->cur_prompt->prompts[0]->result);
4081 len++; /* cover the zero byte */
4082 while (len < sizeof(string)) {
4083 string[len++] = (char) random_byte();
4086 ss = s->cur_prompt->prompts[0]->result;
4088 logevent("Sending length-padded password");
4089 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4090 PKT_INT, len, PKT_DATA, ss, len,
4091 PKTT_OTHER, PKT_END);
4094 * The server is believed unable to cope with
4095 * any of our password camouflage methods.
4098 len = strlen(s->cur_prompt->prompts[0]->result);
4099 logevent("Sending unpadded password");
4100 send_packet(ssh, s->pwpkt_type,
4101 PKTT_PASSWORD, PKT_INT, len,
4102 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4103 PKTT_OTHER, PKT_END);
4106 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4107 PKT_STR, s->cur_prompt->prompts[0]->result,
4108 PKTT_OTHER, PKT_END);
4110 logevent("Sent password");
4111 free_prompts(s->cur_prompt);
4113 if (pktin->type == SSH1_SMSG_FAILURE) {
4114 if (flags & FLAG_VERBOSE)
4115 c_write_str(ssh, "Access denied\r\n");
4116 logevent("Authentication refused");
4117 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4118 bombout(("Strange packet received, type %d", pktin->type));
4124 if (s->publickey_blob) {
4125 sfree(s->publickey_blob);
4126 sfree(s->publickey_comment);
4129 logevent("Authentication successful");
4134 void sshfwd_close(struct ssh_channel *c)
4138 if (ssh->state == SSH_STATE_CLOSED)
4141 if (c && !c->closes) {
4143 * If halfopen is true, we have sent
4144 * CHANNEL_OPEN for this channel, but it hasn't even been
4145 * acknowledged by the server. So we must set a close flag
4146 * on it now, and then when the server acks the channel
4147 * open, we can close it then.
4150 if (ssh->version == 1) {
4151 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4154 struct Packet *pktout;
4155 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4156 ssh2_pkt_adduint32(pktout, c->remoteid);
4157 ssh2_pkt_send(ssh, pktout);
4160 c->closes = 1; /* sent MSG_CLOSE */
4161 if (c->type == CHAN_X11) {
4163 logevent("Forwarded X11 connection terminated");
4164 } else if (c->type == CHAN_SOCKDATA ||
4165 c->type == CHAN_SOCKDATA_DORMANT) {
4167 logevent("Forwarded port closed");
4172 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4176 if (ssh->state == SSH_STATE_CLOSED)
4179 if (ssh->version == 1) {
4180 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4181 PKT_INT, c->remoteid,
4182 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4183 PKTT_OTHER, PKT_END);
4185 * In SSH-1 we can return 0 here - implying that forwarded
4186 * connections are never individually throttled - because
4187 * the only circumstance that can cause throttling will be
4188 * the whole SSH connection backing up, in which case
4189 * _everything_ will be throttled as a whole.
4193 ssh2_add_channel_data(c, buf, len);
4194 return ssh2_try_send(c);
4198 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4203 if (ssh->state == SSH_STATE_CLOSED)
4206 if (ssh->version == 1) {
4207 buflimit = SSH1_BUFFER_LIMIT;
4209 buflimit = c->v.v2.locmaxwin;
4210 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4212 if (c->throttling_conn && bufsize <= buflimit) {
4213 c->throttling_conn = 0;
4214 ssh_throttle_conn(ssh, -1);
4218 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4220 struct queued_handler *qh = ssh->qhead;
4224 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4227 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4228 ssh->packet_dispatch[qh->msg1] = NULL;
4231 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4232 ssh->packet_dispatch[qh->msg2] = NULL;
4236 ssh->qhead = qh->next;
4238 if (ssh->qhead->msg1 > 0) {
4239 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4240 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4242 if (ssh->qhead->msg2 > 0) {
4243 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4244 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4247 ssh->qhead = ssh->qtail = NULL;
4248 ssh->packet_dispatch[pktin->type] = NULL;
4251 qh->handler(ssh, pktin, qh->ctx);
4256 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4257 chandler_fn_t handler, void *ctx)
4259 struct queued_handler *qh;
4261 qh = snew(struct queued_handler);
4264 qh->handler = handler;
4268 if (ssh->qtail == NULL) {
4272 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4273 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4276 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4277 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4280 ssh->qtail->next = qh;
4285 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4287 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4289 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4290 SSH2_MSG_REQUEST_SUCCESS)) {
4291 logeventf(ssh, "Remote port forwarding from %s enabled",
4294 logeventf(ssh, "Remote port forwarding from %s refused",
4297 rpf = del234(ssh->rportfwds, pf);
4303 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
4305 const char *portfwd_strptr = cfg->portfwd;
4306 struct ssh_portfwd *epf;
4309 if (!ssh->portfwds) {
4310 ssh->portfwds = newtree234(ssh_portcmp);
4313 * Go through the existing port forwardings and tag them
4314 * with status==DESTROY. Any that we want to keep will be
4315 * re-enabled (status==KEEP) as we go through the
4316 * configuration and find out which bits are the same as
4319 struct ssh_portfwd *epf;
4321 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4322 epf->status = DESTROY;
4325 while (*portfwd_strptr) {
4326 char address_family, type;
4327 int sport,dport,sserv,dserv;
4328 char sports[256], dports[256], saddr[256], host[256];
4331 address_family = 'A';
4333 if (*portfwd_strptr == 'A' ||
4334 *portfwd_strptr == '4' ||
4335 *portfwd_strptr == '6')
4336 address_family = *portfwd_strptr++;
4337 if (*portfwd_strptr == 'L' ||
4338 *portfwd_strptr == 'R' ||
4339 *portfwd_strptr == 'D')
4340 type = *portfwd_strptr++;
4345 while (*portfwd_strptr && *portfwd_strptr != '\t') {
4346 if (*portfwd_strptr == ':') {
4348 * We've seen a colon in the middle of the
4349 * source port number. This means that
4350 * everything we've seen until now is the
4351 * source _address_, so we'll move it into
4352 * saddr and start sports from the beginning
4357 if (ssh->version == 1 && type == 'R') {
4358 logeventf(ssh, "SSH-1 cannot handle remote source address "
4359 "spec \"%s\"; ignoring", sports);
4361 strcpy(saddr, sports);
4364 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
4368 if (*portfwd_strptr == '\t')
4371 while (*portfwd_strptr && *portfwd_strptr != ':') {
4372 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
4375 if (*portfwd_strptr == ':')
4378 while (*portfwd_strptr) {
4379 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
4383 dport = atoi(dports);
4387 dport = net_service_lookup(dports);
4389 logeventf(ssh, "Service lookup failed for destination"
4390 " port \"%s\"", dports);
4394 while (*portfwd_strptr) portfwd_strptr++;
4398 portfwd_strptr++; /* eat the NUL and move to next one */
4400 sport = atoi(sports);
4404 sport = net_service_lookup(sports);
4406 logeventf(ssh, "Service lookup failed for source"
4407 " port \"%s\"", sports);
4410 if (sport && dport) {
4411 /* Set up a description of the source port. */
4412 struct ssh_portfwd *pfrec, *epfrec;
4414 pfrec = snew(struct ssh_portfwd);
4416 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
4417 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4418 pfrec->sport = sport;
4419 pfrec->daddr = *host ? dupstr(host) : NULL;
4420 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4421 pfrec->dport = dport;
4422 pfrec->local = NULL;
4423 pfrec->remote = NULL;
4424 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4425 address_family == '6' ? ADDRTYPE_IPV6 :
4428 epfrec = add234(ssh->portfwds, pfrec);
4429 if (epfrec != pfrec) {
4431 * We already have a port forwarding with precisely
4432 * these parameters. Hence, no need to do anything;
4433 * simply tag the existing one as KEEP.
4435 epfrec->status = KEEP;
4436 free_portfwd(pfrec);
4438 pfrec->status = CREATE;
4444 * Now go through and destroy any port forwardings which were
4447 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4448 if (epf->status == DESTROY) {
4451 message = dupprintf("%s port forwarding from %s%s%d",
4452 epf->type == 'L' ? "local" :
4453 epf->type == 'R' ? "remote" : "dynamic",
4454 epf->saddr ? epf->saddr : "",
4455 epf->saddr ? ":" : "",
4458 if (epf->type != 'D') {
4459 char *msg2 = dupprintf("%s to %s:%d", message,
4460 epf->daddr, epf->dport);
4465 logeventf(ssh, "Cancelling %s", message);
4469 struct ssh_rportfwd *rpf = epf->remote;
4470 struct Packet *pktout;
4473 * Cancel the port forwarding at the server
4476 if (ssh->version == 1) {
4478 * We cannot cancel listening ports on the
4479 * server side in SSH-1! There's no message
4480 * to support it. Instead, we simply remove
4481 * the rportfwd record from the local end
4482 * so that any connections the server tries
4483 * to make on it are rejected.
4486 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4487 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4488 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4490 ssh2_pkt_addstring(pktout, epf->saddr);
4491 } else if (ssh->cfg.rport_acceptall) {
4492 /* XXX: ssh->cfg.rport_acceptall may not represent
4493 * what was used to open the original connection,
4494 * since it's reconfigurable. */
4495 ssh2_pkt_addstring(pktout, "0.0.0.0");
4497 ssh2_pkt_addstring(pktout, "127.0.0.1");
4499 ssh2_pkt_adduint32(pktout, epf->sport);
4500 ssh2_pkt_send(ssh, pktout);
4503 del234(ssh->rportfwds, rpf);
4505 } else if (epf->local) {
4506 pfd_terminate(epf->local);
4509 delpos234(ssh->portfwds, i);
4511 i--; /* so we don't skip one in the list */
4515 * And finally, set up any new port forwardings (status==CREATE).
4517 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4518 if (epf->status == CREATE) {
4519 char *sportdesc, *dportdesc;
4520 sportdesc = dupprintf("%s%s%s%s%d%s",
4521 epf->saddr ? epf->saddr : "",
4522 epf->saddr ? ":" : "",
4523 epf->sserv ? epf->sserv : "",
4524 epf->sserv ? "(" : "",
4526 epf->sserv ? ")" : "");
4527 if (epf->type == 'D') {
4530 dportdesc = dupprintf("%s:%s%s%d%s",
4532 epf->dserv ? epf->dserv : "",
4533 epf->dserv ? "(" : "",
4535 epf->dserv ? ")" : "");
4538 if (epf->type == 'L') {
4539 const char *err = pfd_addforward(epf->daddr, epf->dport,
4540 epf->saddr, epf->sport,
4543 epf->addressfamily);
4545 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4546 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4547 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4548 sportdesc, dportdesc,
4549 err ? " failed: " : "", err ? err : "");
4550 } else if (epf->type == 'D') {
4551 const char *err = pfd_addforward(NULL, -1,
4552 epf->saddr, epf->sport,
4555 epf->addressfamily);
4557 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4558 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4559 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4561 err ? " failed: " : "", err ? err : "");
4563 struct ssh_rportfwd *pf;
4566 * Ensure the remote port forwardings tree exists.
4568 if (!ssh->rportfwds) {
4569 if (ssh->version == 1)
4570 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4572 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4575 pf = snew(struct ssh_rportfwd);
4576 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4577 pf->dhost[lenof(pf->dhost)-1] = '\0';
4578 pf->dport = epf->dport;
4579 pf->sport = epf->sport;
4580 if (add234(ssh->rportfwds, pf) != pf) {
4581 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4582 epf->daddr, epf->dport);
4585 logeventf(ssh, "Requesting remote port %s"
4586 " forward to %s", sportdesc, dportdesc);
4588 pf->sportdesc = sportdesc;
4593 if (ssh->version == 1) {
4594 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4595 PKT_INT, epf->sport,
4596 PKT_STR, epf->daddr,
4597 PKT_INT, epf->dport,
4599 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4601 ssh_rportfwd_succfail, pf);
4603 struct Packet *pktout;
4604 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4605 ssh2_pkt_addstring(pktout, "tcpip-forward");
4606 ssh2_pkt_addbool(pktout, 1);/* want reply */
4608 ssh2_pkt_addstring(pktout, epf->saddr);
4609 } else if (cfg->rport_acceptall) {
4610 ssh2_pkt_addstring(pktout, "0.0.0.0");
4612 ssh2_pkt_addstring(pktout, "127.0.0.1");
4614 ssh2_pkt_adduint32(pktout, epf->sport);
4615 ssh2_pkt_send(ssh, pktout);
4617 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4618 SSH2_MSG_REQUEST_FAILURE,
4619 ssh_rportfwd_succfail, pf);
4628 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4631 int stringlen, bufsize;
4633 ssh_pkt_getstring(pktin, &string, &stringlen);
4634 if (string == NULL) {
4635 bombout(("Incoming terminal data packet was badly formed"));
4639 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4641 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4642 ssh->v1_stdout_throttling = 1;
4643 ssh_throttle_conn(ssh, +1);
4647 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4649 /* Remote side is trying to open a channel to talk to our
4650 * X-Server. Give them back a local channel number. */
4651 struct ssh_channel *c;
4652 int remoteid = ssh_pkt_getuint32(pktin);
4654 logevent("Received X11 connect request");
4655 /* Refuse if X11 forwarding is disabled. */
4656 if (!ssh->X11_fwd_enabled) {
4657 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4658 PKT_INT, remoteid, PKT_END);
4659 logevent("Rejected X11 connect request");
4661 c = snew(struct ssh_channel);
4664 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4665 NULL, -1, &ssh->cfg) != NULL) {
4666 logevent("Opening X11 forward connection failed");
4668 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4669 PKT_INT, remoteid, PKT_END);
4672 ("Opening X11 forward connection succeeded");
4673 c->remoteid = remoteid;
4674 c->halfopen = FALSE;
4675 c->localid = alloc_channel_id(ssh);
4677 c->throttling_conn = 0;
4678 c->type = CHAN_X11; /* identify channel type */
4679 add234(ssh->channels, c);
4680 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4681 PKT_INT, c->remoteid, PKT_INT,
4682 c->localid, PKT_END);
4683 logevent("Opened X11 forward channel");
4688 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4690 /* Remote side is trying to open a channel to talk to our
4691 * agent. Give them back a local channel number. */
4692 struct ssh_channel *c;
4693 int remoteid = ssh_pkt_getuint32(pktin);
4695 /* Refuse if agent forwarding is disabled. */
4696 if (!ssh->agentfwd_enabled) {
4697 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4698 PKT_INT, remoteid, PKT_END);
4700 c = snew(struct ssh_channel);
4702 c->remoteid = remoteid;
4703 c->halfopen = FALSE;
4704 c->localid = alloc_channel_id(ssh);
4706 c->throttling_conn = 0;
4707 c->type = CHAN_AGENT; /* identify channel type */
4708 c->u.a.lensofar = 0;
4709 add234(ssh->channels, c);
4710 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4711 PKT_INT, c->remoteid, PKT_INT, c->localid,
4716 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4718 /* Remote side is trying to open a channel to talk to a
4719 * forwarded port. Give them back a local channel number. */
4720 struct ssh_channel *c;
4721 struct ssh_rportfwd pf, *pfp;
4726 c = snew(struct ssh_channel);
4729 remoteid = ssh_pkt_getuint32(pktin);
4730 ssh_pkt_getstring(pktin, &host, &hostsize);
4731 port = ssh_pkt_getuint32(pktin);
4733 if (hostsize >= lenof(pf.dhost))
4734 hostsize = lenof(pf.dhost)-1;
4735 memcpy(pf.dhost, host, hostsize);
4736 pf.dhost[hostsize] = '\0';
4738 pfp = find234(ssh->rportfwds, &pf, NULL);
4741 logeventf(ssh, "Rejected remote port open request for %s:%d",
4743 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4744 PKT_INT, remoteid, PKT_END);
4746 logeventf(ssh, "Received remote port open request for %s:%d",
4748 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4749 c, &ssh->cfg, pfp->pfrec->addressfamily);
4751 logeventf(ssh, "Port open failed: %s", e);
4753 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4754 PKT_INT, remoteid, PKT_END);
4756 c->remoteid = remoteid;
4757 c->halfopen = FALSE;
4758 c->localid = alloc_channel_id(ssh);
4760 c->throttling_conn = 0;
4761 c->type = CHAN_SOCKDATA; /* identify channel type */
4762 add234(ssh->channels, c);
4763 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4764 PKT_INT, c->remoteid, PKT_INT,
4765 c->localid, PKT_END);
4766 logevent("Forwarded port opened successfully");
4771 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4773 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4774 unsigned int localid = ssh_pkt_getuint32(pktin);
4775 struct ssh_channel *c;
4777 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4778 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4779 c->remoteid = localid;
4780 c->halfopen = FALSE;
4781 c->type = CHAN_SOCKDATA;
4782 c->throttling_conn = 0;
4783 pfd_confirm(c->u.pfd.s);
4786 if (c && c->closes) {
4788 * We have a pending close on this channel,
4789 * which we decided on before the server acked
4790 * the channel open. So now we know the
4791 * remoteid, we can close it again.
4793 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4794 PKT_INT, c->remoteid, PKT_END);
4798 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4800 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4801 struct ssh_channel *c;
4803 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4804 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4805 logevent("Forwarded connection refused by server");
4806 pfd_close(c->u.pfd.s);
4807 del234(ssh->channels, c);
4812 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4814 /* Remote side closes a channel. */
4815 unsigned i = ssh_pkt_getuint32(pktin);
4816 struct ssh_channel *c;
4817 c = find234(ssh->channels, &i, ssh_channelfind);
4818 if (c && !c->halfopen) {
4821 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4823 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4824 logevent("Forwarded X11 connection terminated");
4825 assert(c->u.x11.s != NULL);
4826 x11_close(c->u.x11.s);
4829 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4830 logevent("Forwarded port closed");
4831 assert(c->u.pfd.s != NULL);
4832 pfd_close(c->u.pfd.s);
4836 c->closes |= (closetype << 2); /* seen this message */
4837 if (!(c->closes & closetype)) {
4838 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4840 c->closes |= closetype; /* sent it too */
4843 if (c->closes == 15) {
4844 del234(ssh->channels, c);
4848 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4849 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4850 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4855 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4857 /* Data sent down one of our channels. */
4858 int i = ssh_pkt_getuint32(pktin);
4861 struct ssh_channel *c;
4863 ssh_pkt_getstring(pktin, &p, &len);
4865 c = find234(ssh->channels, &i, ssh_channelfind);
4870 bufsize = x11_send(c->u.x11.s, p, len);
4873 bufsize = pfd_send(c->u.pfd.s, p, len);
4876 /* Data for an agent message. Buffer it. */
4878 if (c->u.a.lensofar < 4) {
4879 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4880 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4884 c->u.a.lensofar += l;
4886 if (c->u.a.lensofar == 4) {
4888 4 + GET_32BIT(c->u.a.msglen);
4889 c->u.a.message = snewn(c->u.a.totallen,
4891 memcpy(c->u.a.message, c->u.a.msglen, 4);
4893 if (c->u.a.lensofar >= 4 && len > 0) {
4895 min(c->u.a.totallen - c->u.a.lensofar,
4897 memcpy(c->u.a.message + c->u.a.lensofar, p,
4901 c->u.a.lensofar += l;
4903 if (c->u.a.lensofar == c->u.a.totallen) {
4906 if (agent_query(c->u.a.message,
4909 ssh_agentf_callback, c))
4910 ssh_agentf_callback(c, reply, replylen);
4911 sfree(c->u.a.message);
4912 c->u.a.lensofar = 0;
4915 bufsize = 0; /* agent channels never back up */
4918 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
4919 c->throttling_conn = 1;
4920 ssh_throttle_conn(ssh, +1);
4925 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4927 ssh->exitcode = ssh_pkt_getuint32(pktin);
4928 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4929 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4931 * In case `helpful' firewalls or proxies tack
4932 * extra human-readable text on the end of the
4933 * session which we might mistake for another
4934 * encrypted packet, we close the session once
4935 * we've sent EXIT_CONFIRMATION.
4937 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
4940 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4941 static void ssh1_send_ttymode(void *data, char *mode, char *val)
4943 struct Packet *pktout = (struct Packet *)data;
4945 unsigned int arg = 0;
4946 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
4947 if (i == lenof(ssh_ttymodes)) return;
4948 switch (ssh_ttymodes[i].type) {
4950 arg = ssh_tty_parse_specchar(val);
4953 arg = ssh_tty_parse_boolean(val);
4956 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
4957 ssh2_pkt_addbyte(pktout, arg);
4961 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4962 struct Packet *pktin)
4964 crBegin(ssh->do_ssh1_connection_crstate);
4966 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4967 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4968 ssh1_smsg_stdout_stderr_data;
4970 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4971 ssh1_msg_channel_open_confirmation;
4972 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4973 ssh1_msg_channel_open_failure;
4974 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4975 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4976 ssh1_msg_channel_close;
4977 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4978 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4980 if (ssh->cfg.agentfwd && agent_exists()) {
4981 logevent("Requesting agent forwarding");
4982 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4986 if (pktin->type != SSH1_SMSG_SUCCESS
4987 && pktin->type != SSH1_SMSG_FAILURE) {
4988 bombout(("Protocol confusion"));
4990 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4991 logevent("Agent forwarding refused");
4993 logevent("Agent forwarding enabled");
4994 ssh->agentfwd_enabled = TRUE;
4995 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4999 if (ssh->cfg.x11_forward &&
5000 (ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
5001 ssh->cfg.x11_auth, &ssh->cfg))) {
5002 logevent("Requesting X11 forwarding");
5004 * Note that while we blank the X authentication data here, we don't
5005 * take any special action to blank the start of an X11 channel,
5006 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5007 * without having session blanking enabled is likely to leak your
5008 * cookie into the log.
5010 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5011 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5012 PKT_STR, ssh->x11disp->remoteauthprotoname,
5014 PKT_STR, ssh->x11disp->remoteauthdatastring,
5016 PKT_INT, ssh->x11disp->screennum,
5019 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5020 PKT_STR, ssh->x11disp->remoteauthprotoname,
5022 PKT_STR, ssh->x11disp->remoteauthdatastring,
5029 if (pktin->type != SSH1_SMSG_SUCCESS
5030 && pktin->type != SSH1_SMSG_FAILURE) {
5031 bombout(("Protocol confusion"));
5033 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5034 logevent("X11 forwarding refused");
5036 logevent("X11 forwarding enabled");
5037 ssh->X11_fwd_enabled = TRUE;
5038 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5042 ssh_setup_portfwd(ssh, &ssh->cfg);
5043 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5045 if (!ssh->cfg.nopty) {
5047 /* Unpick the terminal-speed string. */
5048 /* XXX perhaps we should allow no speeds to be sent. */
5049 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5050 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
5051 /* Send the pty request. */
5052 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5053 ssh_pkt_addstring(pkt, ssh->cfg.termtype);
5054 ssh_pkt_adduint32(pkt, ssh->term_height);
5055 ssh_pkt_adduint32(pkt, ssh->term_width);
5056 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5057 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5058 parse_ttymodes(ssh, ssh->cfg.ttymodes,
5059 ssh1_send_ttymode, (void *)pkt);
5060 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5061 ssh_pkt_adduint32(pkt, ssh->ispeed);
5062 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5063 ssh_pkt_adduint32(pkt, ssh->ospeed);
5064 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5066 ssh->state = SSH_STATE_INTERMED;
5070 if (pktin->type != SSH1_SMSG_SUCCESS
5071 && pktin->type != SSH1_SMSG_FAILURE) {
5072 bombout(("Protocol confusion"));
5074 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5075 c_write_str(ssh, "Server refused to allocate pty\r\n");
5076 ssh->editing = ssh->echoing = 1;
5078 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5079 ssh->ospeed, ssh->ispeed);
5081 ssh->editing = ssh->echoing = 1;
5084 if (ssh->cfg.compression) {
5085 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5089 if (pktin->type != SSH1_SMSG_SUCCESS
5090 && pktin->type != SSH1_SMSG_FAILURE) {
5091 bombout(("Protocol confusion"));
5093 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5094 c_write_str(ssh, "Server refused to compress\r\n");
5096 logevent("Started compression");
5097 ssh->v1_compressing = TRUE;
5098 ssh->cs_comp_ctx = zlib_compress_init();
5099 logevent("Initialised zlib (RFC1950) compression");
5100 ssh->sc_comp_ctx = zlib_decompress_init();
5101 logevent("Initialised zlib (RFC1950) decompression");
5105 * Start the shell or command.
5107 * Special case: if the first-choice command is an SSH-2
5108 * subsystem (hence not usable here) and the second choice
5109 * exists, we fall straight back to that.
5112 char *cmd = ssh->cfg.remote_cmd_ptr;
5114 if (!cmd) cmd = ssh->cfg.remote_cmd;
5116 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
5117 cmd = ssh->cfg.remote_cmd_ptr2;
5118 ssh->fallback_cmd = TRUE;
5121 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5123 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5124 logevent("Started session");
5127 ssh->state = SSH_STATE_SESSION;
5128 if (ssh->size_needed)
5129 ssh_size(ssh, ssh->term_width, ssh->term_height);
5130 if (ssh->eof_needed)
5131 ssh_special(ssh, TS_EOF);
5134 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5136 ssh->channels = newtree234(ssh_channelcmp);
5140 * By this point, most incoming packets are already being
5141 * handled by the dispatch table, and we need only pay
5142 * attention to the unusual ones.
5147 if (pktin->type == SSH1_SMSG_SUCCESS) {
5148 /* may be from EXEC_SHELL on some servers */
5149 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5150 /* may be from EXEC_SHELL on some servers
5151 * if no pty is available or in other odd cases. Ignore */
5153 bombout(("Strange packet received: type %d", pktin->type));
5158 int len = min(inlen, 512);
5159 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5160 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5161 PKTT_OTHER, PKT_END);
5172 * Handle the top-level SSH-2 protocol.
5174 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5179 ssh_pkt_getstring(pktin, &msg, &msglen);
5180 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5183 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5185 /* log reason code in disconnect message */
5189 ssh_pkt_getstring(pktin, &msg, &msglen);
5190 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5193 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5195 /* Do nothing, because we're ignoring it! Duhh. */
5198 static void ssh1_protocol_setup(Ssh ssh)
5203 * Most messages are handled by the coroutines.
5205 for (i = 0; i < 256; i++)
5206 ssh->packet_dispatch[i] = NULL;
5209 * These special message types we install handlers for.
5211 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5212 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5213 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5216 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5217 struct Packet *pktin)
5219 unsigned char *in=(unsigned char*)vin;
5220 if (ssh->state == SSH_STATE_CLOSED)
5223 if (pktin && ssh->packet_dispatch[pktin->type]) {
5224 ssh->packet_dispatch[pktin->type](ssh, pktin);
5228 if (!ssh->protocol_initial_phase_done) {
5229 if (do_ssh1_login(ssh, in, inlen, pktin))
5230 ssh->protocol_initial_phase_done = TRUE;
5235 do_ssh1_connection(ssh, in, inlen, pktin);
5239 * Utility routine for decoding comma-separated strings in KEXINIT.
5241 static int in_commasep_string(char *needle, char *haystack, int haylen)
5244 if (!needle || !haystack) /* protect against null pointers */
5246 needlen = strlen(needle);
5249 * Is it at the start of the string?
5251 if (haylen >= needlen && /* haystack is long enough */
5252 !memcmp(needle, haystack, needlen) && /* initial match */
5253 (haylen == needlen || haystack[needlen] == ',')
5254 /* either , or EOS follows */
5258 * If not, search for the next comma and resume after that.
5259 * If no comma found, terminate.
5261 while (haylen > 0 && *haystack != ',')
5262 haylen--, haystack++;
5265 haylen--, haystack++; /* skip over comma itself */
5270 * Similar routine for checking whether we have the first string in a list.
5272 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5275 if (!needle || !haystack) /* protect against null pointers */
5277 needlen = strlen(needle);
5279 * Is it at the start of the string?
5281 if (haylen >= needlen && /* haystack is long enough */
5282 !memcmp(needle, haystack, needlen) && /* initial match */
5283 (haylen == needlen || haystack[needlen] == ',')
5284 /* either , or EOS follows */
5292 * SSH-2 key creation method.
5293 * (Currently assumes 2 lots of any hash are sufficient to generate
5294 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5296 #define SSH2_MKKEY_ITERS (2)
5297 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5298 unsigned char *keyspace)
5300 const struct ssh_hash *h = ssh->kex->hash;
5302 /* First hlen bytes. */
5304 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5305 hash_mpint(h, s, K);
5306 h->bytes(s, H, h->hlen);
5307 h->bytes(s, &chr, 1);
5308 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5309 h->final(s, keyspace);
5310 /* Next hlen bytes. */
5312 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5313 hash_mpint(h, s, K);
5314 h->bytes(s, H, h->hlen);
5315 h->bytes(s, keyspace, h->hlen);
5316 h->final(s, keyspace + h->hlen);
5320 * Handle the SSH-2 transport layer.
5322 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5323 struct Packet *pktin)
5325 unsigned char *in = (unsigned char *)vin;
5326 struct do_ssh2_transport_state {
5327 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5328 Bignum p, g, e, f, K;
5331 int kex_init_value, kex_reply_value;
5332 const struct ssh_mac **maclist;
5334 const struct ssh2_cipher *cscipher_tobe;
5335 const struct ssh2_cipher *sccipher_tobe;
5336 const struct ssh_mac *csmac_tobe;
5337 const struct ssh_mac *scmac_tobe;
5338 const struct ssh_compress *cscomp_tobe;
5339 const struct ssh_compress *sccomp_tobe;
5340 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5341 int hostkeylen, siglen, rsakeylen;
5342 void *hkey; /* actual host key */
5343 void *rsakey; /* for RSA kex */
5344 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5345 int n_preferred_kex;
5346 const struct ssh_kexes *preferred_kex[KEX_MAX];
5347 int n_preferred_ciphers;
5348 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5349 const struct ssh_compress *preferred_comp;
5350 int got_session_id, activated_authconn;
5351 struct Packet *pktout;
5356 crState(do_ssh2_transport_state);
5358 crBegin(ssh->do_ssh2_transport_crstate);
5360 s->cscipher_tobe = s->sccipher_tobe = NULL;
5361 s->csmac_tobe = s->scmac_tobe = NULL;
5362 s->cscomp_tobe = s->sccomp_tobe = NULL;
5364 s->got_session_id = s->activated_authconn = FALSE;
5367 * Be prepared to work around the buggy MAC problem.
5369 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5370 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5372 s->maclist = macs, s->nmacs = lenof(macs);
5375 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5377 int i, j, commalist_started;
5380 * Set up the preferred key exchange. (NULL => warn below here)
5382 s->n_preferred_kex = 0;
5383 for (i = 0; i < KEX_MAX; i++) {
5384 switch (ssh->cfg.ssh_kexlist[i]) {
5386 s->preferred_kex[s->n_preferred_kex++] =
5387 &ssh_diffiehellman_gex;
5390 s->preferred_kex[s->n_preferred_kex++] =
5391 &ssh_diffiehellman_group14;
5394 s->preferred_kex[s->n_preferred_kex++] =
5395 &ssh_diffiehellman_group1;
5398 s->preferred_kex[s->n_preferred_kex++] =
5402 /* Flag for later. Don't bother if it's the last in
5404 if (i < KEX_MAX - 1) {
5405 s->preferred_kex[s->n_preferred_kex++] = NULL;
5412 * Set up the preferred ciphers. (NULL => warn below here)
5414 s->n_preferred_ciphers = 0;
5415 for (i = 0; i < CIPHER_MAX; i++) {
5416 switch (ssh->cfg.ssh_cipherlist[i]) {
5417 case CIPHER_BLOWFISH:
5418 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5421 if (ssh->cfg.ssh2_des_cbc) {
5422 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5426 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5429 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5431 case CIPHER_ARCFOUR:
5432 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5435 /* Flag for later. Don't bother if it's the last in
5437 if (i < CIPHER_MAX - 1) {
5438 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5445 * Set up preferred compression.
5447 if (ssh->cfg.compression)
5448 s->preferred_comp = &ssh_zlib;
5450 s->preferred_comp = &ssh_comp_none;
5453 * Enable queueing of outgoing auth- or connection-layer
5454 * packets while we are in the middle of a key exchange.
5456 ssh->queueing = TRUE;
5459 * Flag that KEX is in progress.
5461 ssh->kex_in_progress = TRUE;
5464 * Construct and send our key exchange packet.
5466 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5467 for (i = 0; i < 16; i++)
5468 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5469 /* List key exchange algorithms. */
5470 ssh2_pkt_addstring_start(s->pktout);
5471 commalist_started = 0;
5472 for (i = 0; i < s->n_preferred_kex; i++) {
5473 const struct ssh_kexes *k = s->preferred_kex[i];
5474 if (!k) continue; /* warning flag */
5475 for (j = 0; j < k->nkexes; j++) {
5476 if (commalist_started)
5477 ssh2_pkt_addstring_str(s->pktout, ",");
5478 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5479 commalist_started = 1;
5482 /* List server host key algorithms. */
5483 ssh2_pkt_addstring_start(s->pktout);
5484 for (i = 0; i < lenof(hostkey_algs); i++) {
5485 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5486 if (i < lenof(hostkey_algs) - 1)
5487 ssh2_pkt_addstring_str(s->pktout, ",");
5489 /* List client->server encryption algorithms. */
5490 ssh2_pkt_addstring_start(s->pktout);
5491 commalist_started = 0;
5492 for (i = 0; i < s->n_preferred_ciphers; i++) {
5493 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5494 if (!c) continue; /* warning flag */
5495 for (j = 0; j < c->nciphers; j++) {
5496 if (commalist_started)
5497 ssh2_pkt_addstring_str(s->pktout, ",");
5498 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5499 commalist_started = 1;
5502 /* List server->client encryption algorithms. */
5503 ssh2_pkt_addstring_start(s->pktout);
5504 commalist_started = 0;
5505 for (i = 0; i < s->n_preferred_ciphers; i++) {
5506 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5507 if (!c) continue; /* warning flag */
5508 for (j = 0; j < c->nciphers; j++) {
5509 if (commalist_started)
5510 ssh2_pkt_addstring_str(s->pktout, ",");
5511 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5512 commalist_started = 1;
5515 /* List client->server MAC algorithms. */
5516 ssh2_pkt_addstring_start(s->pktout);
5517 for (i = 0; i < s->nmacs; i++) {
5518 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5519 if (i < s->nmacs - 1)
5520 ssh2_pkt_addstring_str(s->pktout, ",");
5522 /* List server->client MAC algorithms. */
5523 ssh2_pkt_addstring_start(s->pktout);
5524 for (i = 0; i < s->nmacs; i++) {
5525 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5526 if (i < s->nmacs - 1)
5527 ssh2_pkt_addstring_str(s->pktout, ",");
5529 /* List client->server compression algorithms. */
5530 ssh2_pkt_addstring_start(s->pktout);
5531 assert(lenof(compressions) > 1);
5532 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5533 for (i = 0; i < lenof(compressions); i++) {
5534 const struct ssh_compress *c = compressions[i];
5535 if (c != s->preferred_comp) {
5536 ssh2_pkt_addstring_str(s->pktout, ",");
5537 ssh2_pkt_addstring_str(s->pktout, c->name);
5540 /* List server->client compression algorithms. */
5541 ssh2_pkt_addstring_start(s->pktout);
5542 assert(lenof(compressions) > 1);
5543 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5544 for (i = 0; i < lenof(compressions); i++) {
5545 const struct ssh_compress *c = compressions[i];
5546 if (c != s->preferred_comp) {
5547 ssh2_pkt_addstring_str(s->pktout, ",");
5548 ssh2_pkt_addstring_str(s->pktout, c->name);
5551 /* List client->server languages. Empty list. */
5552 ssh2_pkt_addstring_start(s->pktout);
5553 /* List server->client languages. Empty list. */
5554 ssh2_pkt_addstring_start(s->pktout);
5555 /* First KEX packet does _not_ follow, because we're not that brave. */
5556 ssh2_pkt_addbool(s->pktout, FALSE);
5558 ssh2_pkt_adduint32(s->pktout, 0);
5561 s->our_kexinitlen = s->pktout->length - 5;
5562 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5563 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5565 ssh2_pkt_send_noqueue(ssh, s->pktout);
5571 * Now examine the other side's KEXINIT to see what we're up
5575 char *str, *preferred;
5578 if (pktin->type != SSH2_MSG_KEXINIT) {
5579 bombout(("expected key exchange packet from server"));
5583 ssh->hostkey = NULL;
5584 s->cscipher_tobe = NULL;
5585 s->sccipher_tobe = NULL;
5586 s->csmac_tobe = NULL;
5587 s->scmac_tobe = NULL;
5588 s->cscomp_tobe = NULL;
5589 s->sccomp_tobe = NULL;
5590 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5592 pktin->savedpos += 16; /* skip garbage cookie */
5593 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5596 for (i = 0; i < s->n_preferred_kex; i++) {
5597 const struct ssh_kexes *k = s->preferred_kex[i];
5601 for (j = 0; j < k->nkexes; j++) {
5602 if (!preferred) preferred = k->list[j]->name;
5603 if (in_commasep_string(k->list[j]->name, str, len)) {
5604 ssh->kex = k->list[j];
5613 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5614 str ? str : "(null)"));
5618 * Note that the server's guess is considered wrong if it doesn't match
5619 * the first algorithm in our list, even if it's still the algorithm
5622 s->guessok = first_in_commasep_string(preferred, str, len);
5623 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5624 for (i = 0; i < lenof(hostkey_algs); i++) {
5625 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5626 ssh->hostkey = hostkey_algs[i];
5630 s->guessok = s->guessok &&
5631 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5632 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5633 for (i = 0; i < s->n_preferred_ciphers; i++) {
5634 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5636 s->warn_cscipher = TRUE;
5638 for (j = 0; j < c->nciphers; j++) {
5639 if (in_commasep_string(c->list[j]->name, str, len)) {
5640 s->cscipher_tobe = c->list[j];
5645 if (s->cscipher_tobe)
5648 if (!s->cscipher_tobe) {
5649 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5650 str ? str : "(null)"));
5654 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5655 for (i = 0; i < s->n_preferred_ciphers; i++) {
5656 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5658 s->warn_sccipher = TRUE;
5660 for (j = 0; j < c->nciphers; j++) {
5661 if (in_commasep_string(c->list[j]->name, str, len)) {
5662 s->sccipher_tobe = c->list[j];
5667 if (s->sccipher_tobe)
5670 if (!s->sccipher_tobe) {
5671 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5672 str ? str : "(null)"));
5676 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5677 for (i = 0; i < s->nmacs; i++) {
5678 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5679 s->csmac_tobe = s->maclist[i];
5683 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5684 for (i = 0; i < s->nmacs; i++) {
5685 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5686 s->scmac_tobe = s->maclist[i];
5690 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5691 for (i = 0; i < lenof(compressions) + 1; i++) {
5692 const struct ssh_compress *c =
5693 i == 0 ? s->preferred_comp : compressions[i - 1];
5694 if (in_commasep_string(c->name, str, len)) {
5699 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5700 for (i = 0; i < lenof(compressions) + 1; i++) {
5701 const struct ssh_compress *c =
5702 i == 0 ? s->preferred_comp : compressions[i - 1];
5703 if (in_commasep_string(c->name, str, len)) {
5708 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5709 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5710 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5713 ssh_set_frozen(ssh, 1);
5714 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5716 ssh_dialog_callback, ssh);
5717 if (s->dlgret < 0) {
5721 bombout(("Unexpected data from server while"
5722 " waiting for user response"));
5725 } while (pktin || inlen > 0);
5726 s->dlgret = ssh->user_response;
5728 ssh_set_frozen(ssh, 0);
5729 if (s->dlgret == 0) {
5730 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5736 if (s->warn_cscipher) {
5737 ssh_set_frozen(ssh, 1);
5738 s->dlgret = askalg(ssh->frontend,
5739 "client-to-server cipher",
5740 s->cscipher_tobe->name,
5741 ssh_dialog_callback, ssh);
5742 if (s->dlgret < 0) {
5746 bombout(("Unexpected data from server while"
5747 " waiting for user response"));
5750 } while (pktin || inlen > 0);
5751 s->dlgret = ssh->user_response;
5753 ssh_set_frozen(ssh, 0);
5754 if (s->dlgret == 0) {
5755 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5761 if (s->warn_sccipher) {
5762 ssh_set_frozen(ssh, 1);
5763 s->dlgret = askalg(ssh->frontend,
5764 "server-to-client cipher",
5765 s->sccipher_tobe->name,
5766 ssh_dialog_callback, ssh);
5767 if (s->dlgret < 0) {
5771 bombout(("Unexpected data from server while"
5772 " waiting for user response"));
5775 } while (pktin || inlen > 0);
5776 s->dlgret = ssh->user_response;
5778 ssh_set_frozen(ssh, 0);
5779 if (s->dlgret == 0) {
5780 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5786 ssh->exhash = ssh->kex->hash->init();
5787 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5788 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5789 hash_string(ssh->kex->hash, ssh->exhash,
5790 s->our_kexinit, s->our_kexinitlen);
5791 sfree(s->our_kexinit);
5792 if (pktin->length > 5)
5793 hash_string(ssh->kex->hash, ssh->exhash,
5794 pktin->data + 5, pktin->length - 5);
5796 if (s->ignorepkt) /* first_kex_packet_follows */
5797 crWaitUntil(pktin); /* Ignore packet */
5800 if (ssh->kex->main_type == KEXTYPE_DH) {
5802 * Work out the number of bits of key we will need from the
5803 * key exchange. We start with the maximum key length of
5809 csbits = s->cscipher_tobe->keylen;
5810 scbits = s->sccipher_tobe->keylen;
5811 s->nbits = (csbits > scbits ? csbits : scbits);
5813 /* The keys only have hlen-bit entropy, since they're based on
5814 * a hash. So cap the key size at hlen bits. */
5815 if (s->nbits > ssh->kex->hash->hlen * 8)
5816 s->nbits = ssh->kex->hash->hlen * 8;
5819 * If we're doing Diffie-Hellman group exchange, start by
5820 * requesting a group.
5822 if (!ssh->kex->pdata) {
5823 logevent("Doing Diffie-Hellman group exchange");
5824 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5826 * Work out how big a DH group we will need to allow that
5829 s->pbits = 512 << ((s->nbits - 1) / 64);
5830 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5831 ssh2_pkt_adduint32(s->pktout, s->pbits);
5832 ssh2_pkt_send_noqueue(ssh, s->pktout);
5835 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5836 bombout(("expected key exchange group packet from server"));
5839 s->p = ssh2_pkt_getmp(pktin);
5840 s->g = ssh2_pkt_getmp(pktin);
5841 if (!s->p || !s->g) {
5842 bombout(("unable to read mp-ints from incoming group packet"));
5845 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5846 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5847 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5849 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5850 ssh->kex_ctx = dh_setup_group(ssh->kex);
5851 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5852 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5853 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5854 ssh->kex->groupname);
5857 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5858 ssh->kex->hash->text_name);
5860 * Now generate and send e for Diffie-Hellman.
5862 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5863 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5864 s->pktout = ssh2_pkt_init(s->kex_init_value);
5865 ssh2_pkt_addmp(s->pktout, s->e);
5866 ssh2_pkt_send_noqueue(ssh, s->pktout);
5868 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5870 if (pktin->type != s->kex_reply_value) {
5871 bombout(("expected key exchange reply packet from server"));
5874 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5875 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5876 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5877 s->f = ssh2_pkt_getmp(pktin);
5879 bombout(("unable to parse key exchange reply packet"));
5882 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5884 s->K = dh_find_K(ssh->kex_ctx, s->f);
5886 /* We assume everything from now on will be quick, and it might
5887 * involve user interaction. */
5888 set_busy_status(ssh->frontend, BUSY_NOT);
5890 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5891 if (!ssh->kex->pdata) {
5892 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
5893 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
5894 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
5896 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
5897 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
5899 dh_cleanup(ssh->kex_ctx);
5901 if (!ssh->kex->pdata) {
5906 logeventf(ssh, "Doing RSA key exchange with hash %s",
5907 ssh->kex->hash->text_name);
5908 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
5910 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5914 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
5915 bombout(("expected RSA public key packet from server"));
5919 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5920 hash_string(ssh->kex->hash, ssh->exhash,
5921 s->hostkeydata, s->hostkeylen);
5922 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5926 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
5927 s->rsakeydata = snewn(s->rsakeylen, char);
5928 memcpy(s->rsakeydata, keydata, s->rsakeylen);
5931 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
5933 sfree(s->rsakeydata);
5934 bombout(("unable to parse RSA public key from server"));
5938 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
5941 * Next, set up a shared secret K, of precisely KLEN -
5942 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5943 * RSA key modulus and HLEN is the bit length of the hash
5947 int klen = ssh_rsakex_klen(s->rsakey);
5948 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
5950 unsigned char *kstr1, *kstr2, *outstr;
5951 int kstr1len, kstr2len, outstrlen;
5953 s->K = bn_power_2(nbits - 1);
5955 for (i = 0; i < nbits; i++) {
5957 byte = random_byte();
5959 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
5963 * Encode this as an mpint.
5965 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
5966 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
5967 PUT_32BIT(kstr2, kstr1len);
5968 memcpy(kstr2 + 4, kstr1, kstr1len);
5971 * Encrypt it with the given RSA key.
5973 outstrlen = (klen + 7) / 8;
5974 outstr = snewn(outstrlen, unsigned char);
5975 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
5976 outstr, outstrlen, s->rsakey);
5979 * And send it off in a return packet.
5981 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
5982 ssh2_pkt_addstring_start(s->pktout);
5983 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
5984 ssh2_pkt_send_noqueue(ssh, s->pktout);
5986 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
5993 ssh_rsakex_freekey(s->rsakey);
5996 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
5997 sfree(s->rsakeydata);
5998 bombout(("expected signature packet from server"));
6002 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6004 sfree(s->rsakeydata);
6007 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6008 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6009 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6011 ssh->kex_ctx = NULL;
6014 debug(("Exchange hash is:\n"));
6015 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6019 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6020 (char *)s->exchange_hash,
6021 ssh->kex->hash->hlen)) {
6022 bombout(("Server's host key did not match the signature supplied"));
6027 * Authenticate remote host: verify host key. (We've already
6028 * checked the signature of the exchange hash.)
6030 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6031 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6032 ssh_set_frozen(ssh, 1);
6033 s->dlgret = verify_ssh_host_key(ssh->frontend,
6034 ssh->savedhost, ssh->savedport,
6035 ssh->hostkey->keytype, s->keystr,
6037 ssh_dialog_callback, ssh);
6038 if (s->dlgret < 0) {
6042 bombout(("Unexpected data from server while waiting"
6043 " for user host key response"));
6046 } while (pktin || inlen > 0);
6047 s->dlgret = ssh->user_response;
6049 ssh_set_frozen(ssh, 0);
6050 if (s->dlgret == 0) {
6051 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6055 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6056 logevent("Host key fingerprint is:");
6057 logevent(s->fingerprint);
6059 sfree(s->fingerprint);
6061 ssh->hostkey->freekey(s->hkey);
6064 * The exchange hash from the very first key exchange is also
6065 * the session id, used in session key construction and
6068 if (!s->got_session_id) {
6069 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6070 memcpy(ssh->v2_session_id, s->exchange_hash,
6071 sizeof(s->exchange_hash));
6072 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6073 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6074 s->got_session_id = TRUE;
6078 * Send SSH2_MSG_NEWKEYS.
6080 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6081 ssh2_pkt_send_noqueue(ssh, s->pktout);
6082 ssh->outgoing_data_size = 0; /* start counting from here */
6085 * We've sent client NEWKEYS, so create and initialise
6086 * client-to-server session keys.
6088 if (ssh->cs_cipher_ctx)
6089 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6090 ssh->cscipher = s->cscipher_tobe;
6091 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6093 if (ssh->cs_mac_ctx)
6094 ssh->csmac->free_context(ssh->cs_mac_ctx);
6095 ssh->csmac = s->csmac_tobe;
6096 ssh->cs_mac_ctx = ssh->csmac->make_context();
6098 if (ssh->cs_comp_ctx)
6099 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6100 ssh->cscomp = s->cscomp_tobe;
6101 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6104 * Set IVs on client-to-server keys. Here we use the exchange
6105 * hash from the _first_ key exchange.
6108 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6109 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6110 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6111 assert((ssh->cscipher->keylen+7) / 8 <=
6112 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6113 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6114 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6115 assert(ssh->cscipher->blksize <=
6116 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6117 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6118 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6119 assert(ssh->csmac->len <=
6120 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6121 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6122 memset(keyspace, 0, sizeof(keyspace));
6125 logeventf(ssh, "Initialised %.200s client->server encryption",
6126 ssh->cscipher->text_name);
6127 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6128 ssh->csmac->text_name);
6129 if (ssh->cscomp->text_name)
6130 logeventf(ssh, "Initialised %s compression",
6131 ssh->cscomp->text_name);
6134 * Now our end of the key exchange is complete, we can send all
6135 * our queued higher-layer packets.
6137 ssh->queueing = FALSE;
6138 ssh2_pkt_queuesend(ssh);
6141 * Expect SSH2_MSG_NEWKEYS from server.
6144 if (pktin->type != SSH2_MSG_NEWKEYS) {
6145 bombout(("expected new-keys packet from server"));
6148 ssh->incoming_data_size = 0; /* start counting from here */
6151 * We've seen server NEWKEYS, so create and initialise
6152 * server-to-client session keys.
6154 if (ssh->sc_cipher_ctx)
6155 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6156 ssh->sccipher = s->sccipher_tobe;
6157 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6159 if (ssh->sc_mac_ctx)
6160 ssh->scmac->free_context(ssh->sc_mac_ctx);
6161 ssh->scmac = s->scmac_tobe;
6162 ssh->sc_mac_ctx = ssh->scmac->make_context();
6164 if (ssh->sc_comp_ctx)
6165 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6166 ssh->sccomp = s->sccomp_tobe;
6167 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6170 * Set IVs on server-to-client keys. Here we use the exchange
6171 * hash from the _first_ key exchange.
6174 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6175 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6176 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6177 assert((ssh->sccipher->keylen+7) / 8 <=
6178 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6179 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6180 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6181 assert(ssh->sccipher->blksize <=
6182 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6183 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6184 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6185 assert(ssh->scmac->len <=
6186 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6187 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6188 memset(keyspace, 0, sizeof(keyspace));
6190 logeventf(ssh, "Initialised %.200s server->client encryption",
6191 ssh->sccipher->text_name);
6192 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6193 ssh->scmac->text_name);
6194 if (ssh->sccomp->text_name)
6195 logeventf(ssh, "Initialised %s decompression",
6196 ssh->sccomp->text_name);
6199 * Free shared secret.
6204 * Key exchange is over. Loop straight back round if we have a
6205 * deferred rekey reason.
6207 if (ssh->deferred_rekey_reason) {
6208 logevent(ssh->deferred_rekey_reason);
6210 ssh->deferred_rekey_reason = NULL;
6211 goto begin_key_exchange;
6215 * Otherwise, schedule a timer for our next rekey.
6217 ssh->kex_in_progress = FALSE;
6218 ssh->last_rekey = GETTICKCOUNT();
6219 if (ssh->cfg.ssh_rekey_time != 0)
6220 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6224 * If this is the first key exchange phase, we must pass the
6225 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6226 * wants to see it but because it will need time to initialise
6227 * itself before it sees an actual packet. In subsequent key
6228 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6229 * it would only confuse the layer above.
6231 if (s->activated_authconn) {
6234 s->activated_authconn = TRUE;
6237 * Now we're encrypting. Begin returning 1 to the protocol main
6238 * function so that other things can run on top of the
6239 * transport. If we ever see a KEXINIT, we must go back to the
6242 * We _also_ go back to the start if we see pktin==NULL and
6243 * inlen==-1, because this is a special signal meaning
6244 * `initiate client-driven rekey', and `in' contains a message
6245 * giving the reason for the rekey.
6247 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6248 (!pktin && inlen == -1))) {
6253 logevent("Server initiated key re-exchange");
6256 * Special case: if the server bug is set that doesn't
6257 * allow rekeying, we give a different log message and
6258 * continue waiting. (If such a server _initiates_ a rekey,
6259 * we process it anyway!)
6261 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6262 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6264 /* Reset the counters, so that at least this message doesn't
6265 * hit the event log _too_ often. */
6266 ssh->outgoing_data_size = 0;
6267 ssh->incoming_data_size = 0;
6268 if (ssh->cfg.ssh_rekey_time != 0) {
6270 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6273 goto wait_for_rekey; /* this is utterly horrid */
6275 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6278 goto begin_key_exchange;
6284 * Add data to an SSH-2 channel output buffer.
6286 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6289 bufchain_add(&c->v.v2.outbuffer, buf, len);
6293 * Attempt to send data on an SSH-2 channel.
6295 static int ssh2_try_send(struct ssh_channel *c)
6298 struct Packet *pktout;
6300 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6303 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6304 if ((unsigned)len > c->v.v2.remwindow)
6305 len = c->v.v2.remwindow;
6306 if ((unsigned)len > c->v.v2.remmaxpkt)
6307 len = c->v.v2.remmaxpkt;
6308 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6309 ssh2_pkt_adduint32(pktout, c->remoteid);
6310 ssh2_pkt_addstring_start(pktout);
6311 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6312 ssh2_pkt_addstring_data(pktout, data, len);
6313 end_log_omission(ssh, pktout);
6314 ssh2_pkt_send(ssh, pktout);
6315 bufchain_consume(&c->v.v2.outbuffer, len);
6316 c->v.v2.remwindow -= len;
6320 * After having sent as much data as we can, return the amount
6323 return bufchain_size(&c->v.v2.outbuffer);
6326 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
6330 return; /* don't send on closing channels */
6331 bufsize = ssh2_try_send(c);
6334 case CHAN_MAINSESSION:
6335 /* stdin need not receive an unthrottle
6336 * notification since it will be polled */
6339 x11_unthrottle(c->u.x11.s);
6342 /* agent sockets are request/response and need no
6343 * buffer management */
6346 pfd_unthrottle(c->u.pfd.s);
6353 * Set up most of a new ssh_channel for SSH-2.
6355 static void ssh2_channel_init(struct ssh_channel *c)
6358 c->localid = alloc_channel_id(ssh);
6360 c->throttling_conn = FALSE;
6361 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6362 ssh->cfg.ssh_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6363 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6364 c->v.v2.throttle_state = UNTHROTTLED;
6365 bufchain_init(&c->v.v2.outbuffer);
6369 * Potentially enlarge the window on an SSH-2 channel.
6371 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6376 * Never send WINDOW_ADJUST for a channel that the remote side
6377 * already thinks it's closed; there's no point, since it won't
6378 * be sending any more data anyway.
6384 * If the remote end has a habit of ignoring maxpkt, limit the
6385 * window so that it has no choice (assuming it doesn't ignore the
6388 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6389 newwin = OUR_V2_MAXPKT;
6393 * Only send a WINDOW_ADJUST if there's significantly more window
6394 * available than the other end thinks there is. This saves us
6395 * sending a WINDOW_ADJUST for every character in a shell session.
6397 * "Significant" is arbitrarily defined as half the window size.
6399 if (newwin / 2 >= c->v.v2.locwindow) {
6400 struct Packet *pktout;
6404 * In order to keep track of how much window the client
6405 * actually has available, we'd like it to acknowledge each
6406 * WINDOW_ADJUST. We can't do that directly, so we accompany
6407 * it with a CHANNEL_REQUEST that has to be acknowledged.
6409 * This is only necessary if we're opening the window wide.
6410 * If we're not, then throughput is being constrained by
6411 * something other than the maximum window size anyway.
6413 * We also only send this if the main channel has finished its
6414 * initial CHANNEL_REQUESTs and installed the default
6415 * CHANNEL_FAILURE handler, so as not to risk giving it
6416 * unexpected CHANNEL_FAILUREs.
6418 if (newwin == c->v.v2.locmaxwin &&
6419 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6420 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6421 ssh2_pkt_adduint32(pktout, c->remoteid);
6422 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6423 ssh2_pkt_addbool(pktout, TRUE);
6424 ssh2_pkt_send(ssh, pktout);
6427 * CHANNEL_FAILURE doesn't come with any indication of
6428 * what message caused it, so we have to keep track of the
6429 * outstanding CHANNEL_REQUESTs ourselves.
6431 wa = snew(struct winadj);
6432 wa->size = newwin - c->v.v2.locwindow;
6434 if (!c->v.v2.winadj_head)
6435 c->v.v2.winadj_head = wa;
6437 c->v.v2.winadj_tail->next = wa;
6438 c->v.v2.winadj_tail = wa;
6439 if (c->v.v2.throttle_state != UNTHROTTLED)
6440 c->v.v2.throttle_state = UNTHROTTLING;
6442 /* Pretend the WINDOW_ADJUST was acked immediately. */
6443 c->v.v2.remlocwin = newwin;
6444 c->v.v2.throttle_state = THROTTLED;
6446 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6447 ssh2_pkt_adduint32(pktout, c->remoteid);
6448 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6449 ssh2_pkt_send(ssh, pktout);
6450 c->v.v2.locwindow = newwin;
6455 * Find the channel associated with a message. If there's no channel,
6456 * or it's not properly open, make a noise about it and return NULL.
6458 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6460 unsigned localid = ssh_pkt_getuint32(pktin);
6461 struct ssh_channel *c;
6463 c = find234(ssh->channels, &localid, ssh_channelfind);
6465 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6466 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6467 char *buf = dupprintf("Received %s for %s channel %u",
6468 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6470 c ? "half-open" : "nonexistent", localid);
6471 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6478 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6481 * This should never get called. All channel requests are either
6482 * sent with want_reply false or are sent before this handler gets
6485 struct ssh_channel *c;
6488 c = ssh2_channel_msg(ssh, pktin);
6491 wa = c->v.v2.winadj_head;
6493 ssh_disconnect(ssh, NULL, "Received SSH_MSG_CHANNEL_SUCCESS for "
6494 "\"winadj@putty.projects.tartarus.org\"",
6495 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6497 ssh_disconnect(ssh, NULL,
6498 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6499 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6502 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6505 * The only time this should get called is for "winadj@putty"
6506 * messages sent above. All other channel requests are either
6507 * sent with want_reply false or are sent before this handler gets
6510 struct ssh_channel *c;
6513 c = ssh2_channel_msg(ssh, pktin);
6516 wa = c->v.v2.winadj_head;
6518 ssh_disconnect(ssh, NULL,
6519 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6520 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6523 c->v.v2.winadj_head = wa->next;
6524 c->v.v2.remlocwin += wa->size;
6527 * winadj messages are only sent when the window is fully open, so
6528 * if we get an ack of one, we know any pending unthrottle is
6531 if (c->v.v2.throttle_state == UNTHROTTLING)
6532 c->v.v2.throttle_state = UNTHROTTLED;
6535 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6537 struct ssh_channel *c;
6538 c = ssh2_channel_msg(ssh, pktin);
6542 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6543 ssh2_try_send_and_unthrottle(c);
6547 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6551 struct ssh_channel *c;
6552 c = ssh2_channel_msg(ssh, pktin);
6555 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6556 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6557 return; /* extended but not stderr */
6558 ssh_pkt_getstring(pktin, &data, &length);
6561 c->v.v2.locwindow -= length;
6562 c->v.v2.remlocwin -= length;
6564 case CHAN_MAINSESSION:
6566 from_backend(ssh->frontend, pktin->type ==
6567 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6571 bufsize = x11_send(c->u.x11.s, data, length);
6574 bufsize = pfd_send(c->u.pfd.s, data, length);
6577 while (length > 0) {
6578 if (c->u.a.lensofar < 4) {
6579 unsigned int l = min(4 - c->u.a.lensofar,
6581 memcpy(c->u.a.msglen + c->u.a.lensofar,
6585 c->u.a.lensofar += l;
6587 if (c->u.a.lensofar == 4) {
6589 4 + GET_32BIT(c->u.a.msglen);
6590 c->u.a.message = snewn(c->u.a.totallen,
6592 memcpy(c->u.a.message, c->u.a.msglen, 4);
6594 if (c->u.a.lensofar >= 4 && length > 0) {
6596 min(c->u.a.totallen - c->u.a.lensofar,
6598 memcpy(c->u.a.message + c->u.a.lensofar,
6602 c->u.a.lensofar += l;
6604 if (c->u.a.lensofar == c->u.a.totallen) {
6607 if (agent_query(c->u.a.message,
6610 ssh_agentf_callback, c))
6611 ssh_agentf_callback(c, reply, replylen);
6612 sfree(c->u.a.message);
6613 c->u.a.lensofar = 0;
6620 * If it looks like the remote end hit the end of its window,
6621 * and we didn't want it to do that, think about using a
6624 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6625 c->v.v2.locmaxwin < 0x40000000)
6626 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6628 * If we are not buffering too much data,
6629 * enlarge the window again at the remote side.
6630 * If we are buffering too much, we may still
6631 * need to adjust the window if the server's
6634 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6635 c->v.v2.locmaxwin - bufsize : 0);
6637 * If we're either buffering way too much data, or if we're
6638 * buffering anything at all and we're in "simple" mode,
6639 * throttle the whole channel.
6641 if ((bufsize > c->v.v2.locmaxwin ||
6642 (ssh->cfg.ssh_simple && bufsize > 0)) &&
6643 !c->throttling_conn) {
6644 c->throttling_conn = 1;
6645 ssh_throttle_conn(ssh, +1);
6650 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6652 struct ssh_channel *c;
6654 c = ssh2_channel_msg(ssh, pktin);
6658 if (c->type == CHAN_X11) {
6660 * Remote EOF on an X11 channel means we should
6661 * wrap up and close the channel ourselves.
6663 x11_close(c->u.x11.s);
6665 } else if (c->type == CHAN_AGENT) {
6667 } else if (c->type == CHAN_SOCKDATA) {
6668 pfd_close(c->u.pfd.s);
6673 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6675 struct ssh_channel *c;
6676 struct Packet *pktout;
6678 c = ssh2_channel_msg(ssh, pktin);
6681 /* Do pre-close processing on the channel. */
6683 case CHAN_MAINSESSION:
6684 ssh->mainchan = NULL;
6685 update_specials_menu(ssh->frontend);
6688 if (c->u.x11.s != NULL)
6689 x11_close(c->u.x11.s);
6696 if (c->u.pfd.s != NULL)
6697 pfd_close(c->u.pfd.s);
6701 if (c->closes == 0) {
6702 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6703 ssh2_pkt_adduint32(pktout, c->remoteid);
6704 ssh2_pkt_send(ssh, pktout);
6706 del234(ssh->channels, c);
6707 bufchain_clear(&c->v.v2.outbuffer);
6711 * See if that was the last channel left open.
6712 * (This is only our termination condition if we're
6713 * not running in -N mode.)
6715 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6717 * We used to send SSH_MSG_DISCONNECT here,
6718 * because I'd believed that _every_ conforming
6719 * SSH-2 connection had to end with a disconnect
6720 * being sent by at least one side; apparently
6721 * I was wrong and it's perfectly OK to
6722 * unceremoniously slam the connection shut
6723 * when you're done, and indeed OpenSSH feels
6724 * this is more polite than sending a
6725 * DISCONNECT. So now we don't.
6727 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6731 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6733 struct ssh_channel *c;
6734 struct Packet *pktout;
6736 c = ssh2_channel_msg(ssh, pktin);
6739 if (c->type != CHAN_SOCKDATA_DORMANT)
6740 return; /* dunno why they're confirming this */
6741 c->remoteid = ssh_pkt_getuint32(pktin);
6742 c->halfopen = FALSE;
6743 c->type = CHAN_SOCKDATA;
6744 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6745 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6747 pfd_confirm(c->u.pfd.s);
6750 * We have a pending close on this channel,
6751 * which we decided on before the server acked
6752 * the channel open. So now we know the
6753 * remoteid, we can close it again.
6755 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6756 ssh2_pkt_adduint32(pktout, c->remoteid);
6757 ssh2_pkt_send(ssh, pktout);
6761 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
6763 static const char *const reasons[] = {
6764 "<unknown reason code>",
6765 "Administratively prohibited",
6767 "Unknown channel type",
6768 "Resource shortage",
6770 unsigned reason_code;
6771 char *reason_string;
6773 struct ssh_channel *c;
6774 c = ssh2_channel_msg(ssh, pktin);
6777 if (c->type != CHAN_SOCKDATA_DORMANT)
6778 return; /* dunno why they're failing this */
6780 reason_code = ssh_pkt_getuint32(pktin);
6781 if (reason_code >= lenof(reasons))
6782 reason_code = 0; /* ensure reasons[reason_code] in range */
6783 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6784 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
6785 reasons[reason_code], reason_length, reason_string);
6787 pfd_close(c->u.pfd.s);
6789 del234(ssh->channels, c);
6793 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
6796 int typelen, want_reply;
6797 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6798 struct ssh_channel *c;
6799 struct Packet *pktout;
6801 c = ssh2_channel_msg(ssh, pktin);
6804 ssh_pkt_getstring(pktin, &type, &typelen);
6805 want_reply = ssh2_pkt_getbool(pktin);
6808 * Having got the channel number, we now look at
6809 * the request type string to see if it's something
6812 if (c == ssh->mainchan) {
6814 * We recognise "exit-status" and "exit-signal" on
6815 * the primary channel.
6817 if (typelen == 11 &&
6818 !memcmp(type, "exit-status", 11)) {
6820 ssh->exitcode = ssh_pkt_getuint32(pktin);
6821 logeventf(ssh, "Server sent command exit status %d",
6823 reply = SSH2_MSG_CHANNEL_SUCCESS;
6825 } else if (typelen == 11 &&
6826 !memcmp(type, "exit-signal", 11)) {
6828 int is_plausible = TRUE, is_int = FALSE;
6829 char *fmt_sig = "", *fmt_msg = "";
6831 int msglen = 0, core = FALSE;
6832 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6833 * provide an `int' for the signal, despite its
6834 * having been a `string' in the drafts of RFC 4254 since at
6835 * least 2001. (Fixed in session.c 1.147.) Try to
6836 * infer which we can safely parse it as. */
6838 unsigned char *p = pktin->body +
6840 long len = pktin->length - pktin->savedpos;
6841 unsigned long num = GET_32BIT(p); /* what is it? */
6842 /* If it's 0, it hardly matters; assume string */
6846 int maybe_int = FALSE, maybe_str = FALSE;
6847 #define CHECK_HYPOTHESIS(offset, result) \
6850 if (q >= 0 && q+4 <= len) { \
6851 q = q + 4 + GET_32BIT(p+q); \
6852 if (q >= 0 && q+4 <= len && \
6853 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6857 CHECK_HYPOTHESIS(4+1, maybe_int);
6858 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6859 #undef CHECK_HYPOTHESIS
6860 if (maybe_int && !maybe_str)
6862 else if (!maybe_int && maybe_str)
6865 /* Crikey. Either or neither. Panic. */
6866 is_plausible = FALSE;
6869 ssh->exitcode = 128; /* means `unknown signal' */
6872 /* Old non-standard OpenSSH. */
6873 int signum = ssh_pkt_getuint32(pktin);
6874 fmt_sig = dupprintf(" %d", signum);
6875 ssh->exitcode = 128 + signum;
6877 /* As per RFC 4254. */
6880 ssh_pkt_getstring(pktin, &sig, &siglen);
6881 /* Signal name isn't supposed to be blank, but
6882 * let's cope gracefully if it is. */
6884 fmt_sig = dupprintf(" \"%.*s\"",
6889 * Really hideous method of translating the
6890 * signal description back into a locally
6891 * meaningful number.
6896 #define TRANSLATE_SIGNAL(s) \
6897 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6898 ssh->exitcode = 128 + SIG ## s
6900 TRANSLATE_SIGNAL(ABRT);
6903 TRANSLATE_SIGNAL(ALRM);
6906 TRANSLATE_SIGNAL(FPE);
6909 TRANSLATE_SIGNAL(HUP);
6912 TRANSLATE_SIGNAL(ILL);
6915 TRANSLATE_SIGNAL(INT);
6918 TRANSLATE_SIGNAL(KILL);
6921 TRANSLATE_SIGNAL(PIPE);
6924 TRANSLATE_SIGNAL(QUIT);
6927 TRANSLATE_SIGNAL(SEGV);
6930 TRANSLATE_SIGNAL(TERM);
6933 TRANSLATE_SIGNAL(USR1);
6936 TRANSLATE_SIGNAL(USR2);
6938 #undef TRANSLATE_SIGNAL
6940 ssh->exitcode = 128;
6942 core = ssh2_pkt_getbool(pktin);
6943 ssh_pkt_getstring(pktin, &msg, &msglen);
6945 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6947 /* ignore lang tag */
6948 } /* else don't attempt to parse */
6949 logeventf(ssh, "Server exited on signal%s%s%s",
6950 fmt_sig, core ? " (core dumped)" : "",
6952 if (*fmt_sig) sfree(fmt_sig);
6953 if (*fmt_msg) sfree(fmt_msg);
6954 reply = SSH2_MSG_CHANNEL_SUCCESS;
6959 * This is a channel request we don't know
6960 * about, so we now either ignore the request
6961 * or respond with CHANNEL_FAILURE, depending
6964 reply = SSH2_MSG_CHANNEL_FAILURE;
6967 pktout = ssh2_pkt_init(reply);
6968 ssh2_pkt_adduint32(pktout, c->remoteid);
6969 ssh2_pkt_send(ssh, pktout);
6973 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6976 int typelen, want_reply;
6977 struct Packet *pktout;
6979 ssh_pkt_getstring(pktin, &type, &typelen);
6980 want_reply = ssh2_pkt_getbool(pktin);
6983 * We currently don't support any global requests
6984 * at all, so we either ignore the request or
6985 * respond with REQUEST_FAILURE, depending on
6989 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6990 ssh2_pkt_send(ssh, pktout);
6994 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7002 struct ssh_channel *c;
7003 unsigned remid, winsize, pktsize;
7004 struct Packet *pktout;
7006 ssh_pkt_getstring(pktin, &type, &typelen);
7007 c = snew(struct ssh_channel);
7010 remid = ssh_pkt_getuint32(pktin);
7011 winsize = ssh_pkt_getuint32(pktin);
7012 pktsize = ssh_pkt_getuint32(pktin);
7014 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7018 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7019 addrstr = snewn(peeraddrlen+1, char);
7020 memcpy(addrstr, peeraddr, peeraddrlen);
7021 addrstr[peeraddrlen] = '\0';
7022 peerport = ssh_pkt_getuint32(pktin);
7024 logeventf(ssh, "Received X11 connect request from %s:%d",
7027 if (!ssh->X11_fwd_enabled)
7028 error = "X11 forwarding is not enabled";
7029 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7030 addrstr, peerport, &ssh->cfg)) != NULL) {
7031 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7032 error = "Unable to open an X11 connection";
7034 logevent("Opening X11 forward connection succeeded");
7039 } else if (typelen == 15 &&
7040 !memcmp(type, "forwarded-tcpip", 15)) {
7041 struct ssh_rportfwd pf, *realpf;
7044 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7045 pf.sport = ssh_pkt_getuint32(pktin);
7046 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7047 peerport = ssh_pkt_getuint32(pktin);
7048 realpf = find234(ssh->rportfwds, &pf, NULL);
7049 logeventf(ssh, "Received remote port %d open request "
7050 "from %s:%d", pf.sport, peeraddr, peerport);
7051 if (realpf == NULL) {
7052 error = "Remote port is not recognised";
7054 const char *e = pfd_newconnect(&c->u.pfd.s,
7058 realpf->pfrec->addressfamily);
7059 logeventf(ssh, "Attempting to forward remote port to "
7060 "%s:%d", realpf->dhost, realpf->dport);
7062 logeventf(ssh, "Port open failed: %s", e);
7063 error = "Port open failed";
7065 logevent("Forwarded port opened successfully");
7066 c->type = CHAN_SOCKDATA;
7069 } else if (typelen == 22 &&
7070 !memcmp(type, "auth-agent@openssh.com", 22)) {
7071 if (!ssh->agentfwd_enabled)
7072 error = "Agent forwarding is not enabled";
7074 c->type = CHAN_AGENT; /* identify channel type */
7075 c->u.a.lensofar = 0;
7078 error = "Unsupported channel type requested";
7081 c->remoteid = remid;
7082 c->halfopen = FALSE;
7084 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7085 ssh2_pkt_adduint32(pktout, c->remoteid);
7086 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7087 ssh2_pkt_addstring(pktout, error);
7088 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7089 ssh2_pkt_send(ssh, pktout);
7090 logeventf(ssh, "Rejected channel open: %s", error);
7093 ssh2_channel_init(c);
7094 c->v.v2.remwindow = winsize;
7095 c->v.v2.remmaxpkt = pktsize;
7096 add234(ssh->channels, c);
7097 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7098 ssh2_pkt_adduint32(pktout, c->remoteid);
7099 ssh2_pkt_adduint32(pktout, c->localid);
7100 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7101 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7102 ssh2_pkt_send(ssh, pktout);
7107 * Buffer banner messages for later display at some convenient point.
7109 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7111 /* Arbitrary limit to prevent unbounded inflation of buffer */
7112 if (bufchain_size(&ssh->banner) <= 131072) {
7113 char *banner = NULL;
7115 ssh_pkt_getstring(pktin, &banner, &size);
7117 bufchain_add(&ssh->banner, banner, size);
7121 /* Helper function to deal with sending tty modes for "pty-req" */
7122 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7124 struct Packet *pktout = (struct Packet *)data;
7126 unsigned int arg = 0;
7127 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7128 if (i == lenof(ssh_ttymodes)) return;
7129 switch (ssh_ttymodes[i].type) {
7131 arg = ssh_tty_parse_specchar(val);
7134 arg = ssh_tty_parse_boolean(val);
7137 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7138 ssh2_pkt_adduint32(pktout, arg);
7142 * Handle the SSH-2 userauth and connection layers.
7144 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7145 struct Packet *pktin)
7147 struct do_ssh2_authconn_state {
7150 AUTH_TYPE_PUBLICKEY,
7151 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7152 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7155 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7156 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7158 int done_service_req;
7159 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7160 int tried_pubkey_config, done_agent;
7165 int kbd_inter_refused;
7167 prompts_t *cur_prompt;
7172 void *publickey_blob;
7173 int publickey_bloblen;
7174 int publickey_encrypted;
7175 char *publickey_algorithm;
7176 char *publickey_comment;
7177 unsigned char agent_request[5], *agent_response, *agentp;
7178 int agent_responselen;
7179 unsigned char *pkblob_in_agent;
7181 char *pkblob, *alg, *commentp;
7182 int pklen, alglen, commentlen;
7183 int siglen, retlen, len;
7184 char *q, *agentreq, *ret;
7186 int num_env, env_left, env_ok;
7187 struct Packet *pktout;
7189 Ssh_gss_ctx gss_ctx;
7190 Ssh_gss_buf gss_buf;
7191 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7192 Ssh_gss_name gss_srv_name;
7193 Ssh_gss_stat gss_stat;
7196 crState(do_ssh2_authconn_state);
7198 crBegin(ssh->do_ssh2_authconn_crstate);
7200 s->done_service_req = FALSE;
7201 s->we_are_in = FALSE;
7203 s->tried_gssapi = FALSE;
7206 if (!ssh->cfg.ssh_no_userauth) {
7208 * Request userauth protocol, and await a response to it.
7210 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7211 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7212 ssh2_pkt_send(ssh, s->pktout);
7213 crWaitUntilV(pktin);
7214 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7215 s->done_service_req = TRUE;
7217 if (!s->done_service_req) {
7219 * Request connection protocol directly, without authentication.
7221 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7222 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7223 ssh2_pkt_send(ssh, s->pktout);
7224 crWaitUntilV(pktin);
7225 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7226 s->we_are_in = TRUE; /* no auth required */
7228 bombout(("Server refused service request"));
7233 /* Arrange to be able to deal with any BANNERs that come in.
7234 * (We do this now as packets may come in during the next bit.) */
7235 bufchain_init(&ssh->banner);
7236 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7237 ssh2_msg_userauth_banner;
7240 * Misc one-time setup for authentication.
7242 s->publickey_blob = NULL;
7243 if (!s->we_are_in) {
7246 * Load the public half of any configured public key file
7249 if (!filename_is_null(ssh->cfg.keyfile)) {
7251 logeventf(ssh, "Reading private key file \"%.150s\"",
7252 filename_to_str(&ssh->cfg.keyfile));
7253 keytype = key_type(&ssh->cfg.keyfile);
7254 if (keytype == SSH_KEYTYPE_SSH2) {
7257 ssh2_userkey_loadpub(&ssh->cfg.keyfile,
7258 &s->publickey_algorithm,
7259 &s->publickey_bloblen,
7260 &s->publickey_comment, &error);
7261 if (s->publickey_blob) {
7262 s->publickey_encrypted =
7263 ssh2_userkey_encrypted(&ssh->cfg.keyfile, NULL);
7266 logeventf(ssh, "Unable to load private key (%s)",
7268 msgbuf = dupprintf("Unable to load private key file "
7269 "\"%.150s\" (%s)\r\n",
7270 filename_to_str(&ssh->cfg.keyfile),
7272 c_write_str(ssh, msgbuf);
7277 logeventf(ssh, "Unable to use this key file (%s)",
7278 key_type_to_str(keytype));
7279 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7281 filename_to_str(&ssh->cfg.keyfile),
7282 key_type_to_str(keytype));
7283 c_write_str(ssh, msgbuf);
7285 s->publickey_blob = NULL;
7290 * Find out about any keys Pageant has (but if there's a
7291 * public key configured, filter out all others).
7294 s->agent_response = NULL;
7295 s->pkblob_in_agent = NULL;
7296 if (ssh->cfg.tryagent && agent_exists()) {
7300 logevent("Pageant is running. Requesting keys.");
7302 /* Request the keys held by the agent. */
7303 PUT_32BIT(s->agent_request, 1);
7304 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7305 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7306 ssh_agent_callback, ssh)) {
7310 bombout(("Unexpected data from server while"
7311 " waiting for agent response"));
7314 } while (pktin || inlen > 0);
7315 r = ssh->agent_response;
7316 s->agent_responselen = ssh->agent_response_len;
7318 s->agent_response = (unsigned char *) r;
7319 if (s->agent_response && s->agent_responselen >= 5 &&
7320 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7323 p = s->agent_response + 5;
7324 s->nkeys = GET_32BIT(p);
7326 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7327 if (s->publickey_blob) {
7328 /* See if configured key is in agent. */
7329 for (keyi = 0; keyi < s->nkeys; keyi++) {
7330 s->pklen = GET_32BIT(p);
7331 if (s->pklen == s->publickey_bloblen &&
7332 !memcmp(p+4, s->publickey_blob,
7333 s->publickey_bloblen)) {
7334 logeventf(ssh, "Pageant key #%d matches "
7335 "configured key file", keyi);
7337 s->pkblob_in_agent = p;
7341 p += GET_32BIT(p) + 4; /* comment */
7343 if (!s->pkblob_in_agent) {
7344 logevent("Configured key file not in Pageant");
7354 * We repeat this whole loop, including the username prompt,
7355 * until we manage a successful authentication. If the user
7356 * types the wrong _password_, they can be sent back to the
7357 * beginning to try another username, if this is configured on.
7358 * (If they specify a username in the config, they are never
7359 * asked, even if they do give a wrong password.)
7361 * I think this best serves the needs of
7363 * - the people who have no configuration, no keys, and just
7364 * want to try repeated (username,password) pairs until they
7365 * type both correctly
7367 * - people who have keys and configuration but occasionally
7368 * need to fall back to passwords
7370 * - people with a key held in Pageant, who might not have
7371 * logged in to a particular machine before; so they want to
7372 * type a username, and then _either_ their key will be
7373 * accepted, _or_ they will type a password. If they mistype
7374 * the username they will want to be able to get back and
7377 s->username[0] = '\0';
7378 s->got_username = FALSE;
7379 while (!s->we_are_in) {
7383 if (s->got_username && !ssh->cfg.change_username) {
7385 * We got a username last time round this loop, and
7386 * with change_username turned off we don't try to get
7389 } else if (!get_remote_username(&ssh->cfg, s->username,
7390 sizeof(s->username))) {
7391 int ret; /* need not be kept over crReturn */
7392 s->cur_prompt = new_prompts(ssh->frontend);
7393 s->cur_prompt->to_server = TRUE;
7394 s->cur_prompt->name = dupstr("SSH login name");
7395 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
7396 lenof(s->username));
7397 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7400 crWaitUntilV(!pktin);
7401 ret = get_userpass_input(s->cur_prompt, in, inlen);
7406 * get_userpass_input() failed to get a username.
7409 free_prompts(s->cur_prompt);
7410 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7413 memcpy(s->username, s->cur_prompt->prompts[0]->result,
7414 lenof(s->username));
7415 free_prompts(s->cur_prompt);
7418 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7419 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
7420 c_write_str(ssh, stuff);
7424 s->got_username = TRUE;
7427 * Send an authentication request using method "none": (a)
7428 * just in case it succeeds, and (b) so that we know what
7429 * authentication methods we can usefully try next.
7431 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7433 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7434 ssh2_pkt_addstring(s->pktout, s->username);
7435 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7436 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7437 ssh2_pkt_send(ssh, s->pktout);
7438 s->type = AUTH_TYPE_NONE;
7440 s->we_are_in = FALSE;
7442 s->tried_pubkey_config = FALSE;
7443 s->kbd_inter_refused = FALSE;
7445 /* Reset agent request state. */
7446 s->done_agent = FALSE;
7447 if (s->agent_response) {
7448 if (s->pkblob_in_agent) {
7449 s->agentp = s->pkblob_in_agent;
7451 s->agentp = s->agent_response + 5 + 4;
7458 * Wait for the result of the last authentication request.
7461 crWaitUntilV(pktin);
7463 * Now is a convenient point to spew any banner material
7464 * that we've accumulated. (This should ensure that when
7465 * we exit the auth loop, we haven't any left to deal
7469 int size = bufchain_size(&ssh->banner);
7471 * Don't show the banner if we're operating in
7472 * non-verbose non-interactive mode. (It's probably
7473 * a script, which means nobody will read the
7474 * banner _anyway_, and moreover the printing of
7475 * the banner will screw up processing on the
7476 * output of (say) plink.)
7478 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7479 char *banner = snewn(size, char);
7480 bufchain_fetch(&ssh->banner, banner, size);
7481 c_write_untrusted(ssh, banner, size);
7484 bufchain_clear(&ssh->banner);
7486 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7487 logevent("Access granted");
7488 s->we_are_in = TRUE;
7492 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7493 bombout(("Strange packet received during authentication: "
7494 "type %d", pktin->type));
7501 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7502 * we can look at the string in it and know what we can
7503 * helpfully try next.
7505 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7508 ssh_pkt_getstring(pktin, &methods, &methlen);
7509 if (!ssh2_pkt_getbool(pktin)) {
7511 * We have received an unequivocal Access
7512 * Denied. This can translate to a variety of
7515 * - if we'd just tried "none" authentication,
7516 * it's not worth printing anything at all
7518 * - if we'd just tried a public key _offer_,
7519 * the message should be "Server refused our
7520 * key" (or no message at all if the key
7521 * came from Pageant)
7523 * - if we'd just tried anything else, the
7524 * message really should be "Access denied".
7526 * Additionally, if we'd just tried password
7527 * authentication, we should break out of this
7528 * whole loop so as to go back to the username
7529 * prompt (iff we're configured to allow
7530 * username change attempts).
7532 if (s->type == AUTH_TYPE_NONE) {
7534 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7535 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7536 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7537 c_write_str(ssh, "Server refused our key\r\n");
7538 logevent("Server refused public key");
7539 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7540 /* server declined keyboard-interactive; ignore */
7542 c_write_str(ssh, "Access denied\r\n");
7543 logevent("Access denied");
7544 if (s->type == AUTH_TYPE_PASSWORD &&
7545 ssh->cfg.change_username) {
7546 /* XXX perhaps we should allow
7547 * keyboard-interactive to do this too? */
7548 s->we_are_in = FALSE;
7553 c_write_str(ssh, "Further authentication required\r\n");
7554 logevent("Further authentication required");
7558 in_commasep_string("publickey", methods, methlen);
7560 in_commasep_string("password", methods, methlen);
7561 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
7562 in_commasep_string("keyboard-interactive", methods, methlen);
7564 s->can_gssapi = ssh->cfg.try_gssapi_auth &&
7565 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7570 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7572 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7575 * Attempt public-key authentication using a key from Pageant.
7578 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7580 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7582 /* Unpack key from agent response */
7583 s->pklen = GET_32BIT(s->agentp);
7585 s->pkblob = (char *)s->agentp;
7586 s->agentp += s->pklen;
7587 s->alglen = GET_32BIT(s->pkblob);
7588 s->alg = s->pkblob + 4;
7589 s->commentlen = GET_32BIT(s->agentp);
7591 s->commentp = (char *)s->agentp;
7592 s->agentp += s->commentlen;
7593 /* s->agentp now points at next key, if any */
7595 /* See if server will accept it */
7596 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7597 ssh2_pkt_addstring(s->pktout, s->username);
7598 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7599 /* service requested */
7600 ssh2_pkt_addstring(s->pktout, "publickey");
7602 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7603 ssh2_pkt_addstring_start(s->pktout);
7604 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7605 ssh2_pkt_addstring_start(s->pktout);
7606 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7607 ssh2_pkt_send(ssh, s->pktout);
7608 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7610 crWaitUntilV(pktin);
7611 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7613 /* Offer of key refused. */
7620 if (flags & FLAG_VERBOSE) {
7621 c_write_str(ssh, "Authenticating with "
7623 c_write(ssh, s->commentp, s->commentlen);
7624 c_write_str(ssh, "\" from agent\r\n");
7628 * Server is willing to accept the key.
7629 * Construct a SIGN_REQUEST.
7631 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7632 ssh2_pkt_addstring(s->pktout, s->username);
7633 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7634 /* service requested */
7635 ssh2_pkt_addstring(s->pktout, "publickey");
7637 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7638 ssh2_pkt_addstring_start(s->pktout);
7639 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7640 ssh2_pkt_addstring_start(s->pktout);
7641 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7643 /* Ask agent for signature. */
7644 s->siglen = s->pktout->length - 5 + 4 +
7645 ssh->v2_session_id_len;
7646 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7648 s->len = 1; /* message type */
7649 s->len += 4 + s->pklen; /* key blob */
7650 s->len += 4 + s->siglen; /* data to sign */
7651 s->len += 4; /* flags */
7652 s->agentreq = snewn(4 + s->len, char);
7653 PUT_32BIT(s->agentreq, s->len);
7654 s->q = s->agentreq + 4;
7655 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7656 PUT_32BIT(s->q, s->pklen);
7658 memcpy(s->q, s->pkblob, s->pklen);
7660 PUT_32BIT(s->q, s->siglen);
7662 /* Now the data to be signed... */
7663 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7664 PUT_32BIT(s->q, ssh->v2_session_id_len);
7667 memcpy(s->q, ssh->v2_session_id,
7668 ssh->v2_session_id_len);
7669 s->q += ssh->v2_session_id_len;
7670 memcpy(s->q, s->pktout->data + 5,
7671 s->pktout->length - 5);
7672 s->q += s->pktout->length - 5;
7673 /* And finally the (zero) flags word. */
7675 if (!agent_query(s->agentreq, s->len + 4,
7677 ssh_agent_callback, ssh)) {
7681 bombout(("Unexpected data from server"
7682 " while waiting for agent"
7686 } while (pktin || inlen > 0);
7687 vret = ssh->agent_response;
7688 s->retlen = ssh->agent_response_len;
7693 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7694 logevent("Sending Pageant's response");
7695 ssh2_add_sigblob(ssh, s->pktout,
7696 s->pkblob, s->pklen,
7698 GET_32BIT(s->ret + 5));
7699 ssh2_pkt_send(ssh, s->pktout);
7700 s->type = AUTH_TYPE_PUBLICKEY;
7702 /* FIXME: less drastic response */
7703 bombout(("Pageant failed to answer challenge"));
7709 /* Do we have any keys left to try? */
7710 if (s->pkblob_in_agent) {
7711 s->done_agent = TRUE;
7712 s->tried_pubkey_config = TRUE;
7715 if (s->keyi >= s->nkeys)
7716 s->done_agent = TRUE;
7719 } else if (s->can_pubkey && s->publickey_blob &&
7720 !s->tried_pubkey_config) {
7722 struct ssh2_userkey *key; /* not live over crReturn */
7723 char *passphrase; /* not live over crReturn */
7725 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7727 s->tried_pubkey_config = TRUE;
7730 * Try the public key supplied in the configuration.
7732 * First, offer the public blob to see if the server is
7733 * willing to accept it.
7735 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7736 ssh2_pkt_addstring(s->pktout, s->username);
7737 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7738 /* service requested */
7739 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
7740 ssh2_pkt_addbool(s->pktout, FALSE);
7741 /* no signature included */
7742 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
7743 ssh2_pkt_addstring_start(s->pktout);
7744 ssh2_pkt_addstring_data(s->pktout,
7745 (char *)s->publickey_blob,
7746 s->publickey_bloblen);
7747 ssh2_pkt_send(ssh, s->pktout);
7748 logevent("Offered public key");
7750 crWaitUntilV(pktin);
7751 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7752 /* Key refused. Give up. */
7753 s->gotit = TRUE; /* reconsider message next loop */
7754 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
7755 continue; /* process this new message */
7757 logevent("Offer of public key accepted");
7760 * Actually attempt a serious authentication using
7763 if (flags & FLAG_VERBOSE) {
7764 c_write_str(ssh, "Authenticating with public key \"");
7765 c_write_str(ssh, s->publickey_comment);
7766 c_write_str(ssh, "\"\r\n");
7770 const char *error; /* not live over crReturn */
7771 if (s->publickey_encrypted) {
7773 * Get a passphrase from the user.
7775 int ret; /* need not be kept over crReturn */
7776 s->cur_prompt = new_prompts(ssh->frontend);
7777 s->cur_prompt->to_server = FALSE;
7778 s->cur_prompt->name = dupstr("SSH key passphrase");
7779 add_prompt(s->cur_prompt,
7780 dupprintf("Passphrase for key \"%.100s\": ",
7781 s->publickey_comment),
7782 FALSE, SSH_MAX_PASSWORD_LEN);
7783 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7786 crWaitUntilV(!pktin);
7787 ret = get_userpass_input(s->cur_prompt,
7792 /* Failed to get a passphrase. Terminate. */
7793 free_prompts(s->cur_prompt);
7794 ssh_disconnect(ssh, NULL,
7795 "Unable to authenticate",
7796 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7801 dupstr(s->cur_prompt->prompts[0]->result);
7802 free_prompts(s->cur_prompt);
7804 passphrase = NULL; /* no passphrase needed */
7808 * Try decrypting the key.
7810 key = ssh2_load_userkey(&ssh->cfg.keyfile, passphrase,
7813 /* burn the evidence */
7814 memset(passphrase, 0, strlen(passphrase));
7817 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
7819 (key == SSH2_WRONG_PASSPHRASE)) {
7820 c_write_str(ssh, "Wrong passphrase\r\n");
7822 /* and loop again */
7824 c_write_str(ssh, "Unable to load private key (");
7825 c_write_str(ssh, error);
7826 c_write_str(ssh, ")\r\n");
7828 break; /* try something else */
7834 unsigned char *pkblob, *sigblob, *sigdata;
7835 int pkblob_len, sigblob_len, sigdata_len;
7839 * We have loaded the private key and the server
7840 * has announced that it's willing to accept it.
7841 * Hallelujah. Generate a signature and send it.
7843 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7844 ssh2_pkt_addstring(s->pktout, s->username);
7845 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7846 /* service requested */
7847 ssh2_pkt_addstring(s->pktout, "publickey");
7849 ssh2_pkt_addbool(s->pktout, TRUE);
7850 /* signature follows */
7851 ssh2_pkt_addstring(s->pktout, key->alg->name);
7852 pkblob = key->alg->public_blob(key->data,
7854 ssh2_pkt_addstring_start(s->pktout);
7855 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
7859 * The data to be signed is:
7863 * followed by everything so far placed in the
7866 sigdata_len = s->pktout->length - 5 + 4 +
7867 ssh->v2_session_id_len;
7868 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7870 sigdata = snewn(sigdata_len, unsigned char);
7872 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7873 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
7876 memcpy(sigdata+p, ssh->v2_session_id,
7877 ssh->v2_session_id_len);
7878 p += ssh->v2_session_id_len;
7879 memcpy(sigdata+p, s->pktout->data + 5,
7880 s->pktout->length - 5);
7881 p += s->pktout->length - 5;
7882 assert(p == sigdata_len);
7883 sigblob = key->alg->sign(key->data, (char *)sigdata,
7884 sigdata_len, &sigblob_len);
7885 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7886 sigblob, sigblob_len);
7891 ssh2_pkt_send(ssh, s->pktout);
7892 s->type = AUTH_TYPE_PUBLICKEY;
7893 key->alg->freekey(key->data);
7897 } else if (s->can_gssapi && !s->tried_gssapi) {
7899 /* GSSAPI Authentication */
7904 s->type = AUTH_TYPE_GSSAPI;
7905 s->tried_gssapi = TRUE;
7907 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
7909 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
7910 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7911 ssh2_pkt_addstring(s->pktout, s->username);
7912 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7913 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
7915 /* add mechanism info */
7916 ssh_gss_indicate_mech(&s->gss_buf);
7918 /* number of GSSAPI mechanisms */
7919 ssh2_pkt_adduint32(s->pktout,1);
7921 /* length of OID + 2 */
7922 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
7923 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
7926 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
7928 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
7930 ssh2_pkt_send(ssh, s->pktout);
7931 crWaitUntilV(pktin);
7932 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
7933 logevent("GSSAPI authentication request refused");
7937 /* check returned packet ... */
7939 ssh_pkt_getstring(pktin, &data, &len);
7940 s->gss_rcvtok.value = data;
7941 s->gss_rcvtok.length = len;
7942 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
7943 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
7944 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
7945 memcmp((char *)s->gss_rcvtok.value + 2,
7946 s->gss_buf.value,s->gss_buf.length) ) {
7947 logevent("GSSAPI authentication - wrong response from server");
7951 /* now start running */
7952 s->gss_stat = ssh_gss_import_name(ssh->fullhostname,
7954 if (s->gss_stat != SSH_GSS_OK) {
7955 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
7956 logevent("GSSAPI import name failed - Bad service name");
7958 logevent("GSSAPI import name failed");
7962 /* fetch TGT into GSS engine */
7963 s->gss_stat = ssh_gss_acquire_cred(&s->gss_ctx);
7965 if (s->gss_stat != SSH_GSS_OK) {
7966 logevent("GSSAPI authentication failed to get credentials");
7967 ssh_gss_release_name(&s->gss_srv_name);
7971 /* initial tokens are empty */
7972 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
7973 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
7975 /* now enter the loop */
7977 s->gss_stat = ssh_gss_init_sec_context(&s->gss_ctx,
7983 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
7984 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
7985 logevent("GSSAPI authentication initialisation failed");
7987 if (ssh_gss_display_status(s->gss_ctx,&s->gss_buf) == SSH_GSS_OK) {
7988 logevent(s->gss_buf.value);
7989 sfree(s->gss_buf.value);
7994 logevent("GSSAPI authentication initialised");
7996 /* Client and server now exchange tokens until GSSAPI
7997 * no longer says CONTINUE_NEEDED */
7999 if (s->gss_sndtok.length != 0) {
8000 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8001 ssh_pkt_addstring_start(s->pktout);
8002 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8003 ssh2_pkt_send(ssh, s->pktout);
8004 ssh_gss_free_tok(&s->gss_sndtok);
8007 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8008 crWaitUntilV(pktin);
8009 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8010 logevent("GSSAPI authentication - bad server response");
8011 s->gss_stat = SSH_GSS_FAILURE;
8014 ssh_pkt_getstring(pktin, &data, &len);
8015 s->gss_rcvtok.value = data;
8016 s->gss_rcvtok.length = len;
8018 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8020 if (s->gss_stat != SSH_GSS_OK) {
8021 ssh_gss_release_name(&s->gss_srv_name);
8022 ssh_gss_release_cred(&s->gss_ctx);
8025 logevent("GSSAPI authentication loop finished OK");
8027 /* Now send the MIC */
8029 s->pktout = ssh2_pkt_init(0);
8030 micoffset = s->pktout->length;
8031 ssh_pkt_addstring_start(s->pktout);
8032 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8033 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8034 ssh_pkt_addstring(s->pktout, s->username);
8035 ssh_pkt_addstring(s->pktout, "ssh-connection");
8036 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8038 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8039 s->gss_buf.length = s->pktout->length - micoffset;
8041 ssh_gss_get_mic(s->gss_ctx, &s->gss_buf, &mic);
8042 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8043 ssh_pkt_addstring_start(s->pktout);
8044 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8045 ssh2_pkt_send(ssh, s->pktout);
8046 ssh_gss_free_mic(&mic);
8050 ssh_gss_release_name(&s->gss_srv_name);
8051 ssh_gss_release_cred(&s->gss_ctx);
8054 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8057 * Keyboard-interactive authentication.
8060 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8062 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8064 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8065 ssh2_pkt_addstring(s->pktout, s->username);
8066 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8067 /* service requested */
8068 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8070 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8071 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8072 ssh2_pkt_send(ssh, s->pktout);
8074 crWaitUntilV(pktin);
8075 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8076 /* Server is not willing to do keyboard-interactive
8077 * at all (or, bizarrely but legally, accepts the
8078 * user without actually issuing any prompts).
8079 * Give up on it entirely. */
8081 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
8082 logevent("Keyboard-interactive authentication refused");
8083 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8084 s->kbd_inter_refused = TRUE; /* don't try it again */
8089 * Loop while the server continues to send INFO_REQUESTs.
8091 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8093 char *name, *inst, *lang;
8094 int name_len, inst_len, lang_len;
8098 * We've got a fresh USERAUTH_INFO_REQUEST.
8099 * Get the preamble and start building a prompt.
8101 ssh_pkt_getstring(pktin, &name, &name_len);
8102 ssh_pkt_getstring(pktin, &inst, &inst_len);
8103 ssh_pkt_getstring(pktin, &lang, &lang_len);
8104 s->cur_prompt = new_prompts(ssh->frontend);
8105 s->cur_prompt->to_server = TRUE;
8108 * Get any prompt(s) from the packet.
8110 s->num_prompts = ssh_pkt_getuint32(pktin);
8111 for (i = 0; i < s->num_prompts; i++) {
8115 static char noprompt[] =
8116 "<server failed to send prompt>: ";
8118 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8119 echo = ssh2_pkt_getbool(pktin);
8122 prompt_len = lenof(noprompt)-1;
8124 add_prompt(s->cur_prompt,
8125 dupprintf("%.*s", prompt_len, prompt),
8126 echo, SSH_MAX_PASSWORD_LEN);
8130 /* FIXME: better prefix to distinguish from
8132 s->cur_prompt->name =
8133 dupprintf("SSH server: %.*s", name_len, name);
8134 s->cur_prompt->name_reqd = TRUE;
8136 s->cur_prompt->name =
8137 dupstr("SSH server authentication");
8138 s->cur_prompt->name_reqd = FALSE;
8140 /* We add a prefix to try to make it clear that a prompt
8141 * has come from the server.
8142 * FIXME: ugly to print "Using..." in prompt _every_
8143 * time round. Can this be done more subtly? */
8144 /* Special case: for reasons best known to themselves,
8145 * some servers send k-i requests with no prompts and
8146 * nothing to display. Keep quiet in this case. */
8147 if (s->num_prompts || name_len || inst_len) {
8148 s->cur_prompt->instruction =
8149 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8150 inst_len ? "\n" : "", inst_len, inst);
8151 s->cur_prompt->instr_reqd = TRUE;
8153 s->cur_prompt->instr_reqd = FALSE;
8157 * Display any instructions, and get the user's
8161 int ret; /* not live over crReturn */
8162 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8165 crWaitUntilV(!pktin);
8166 ret = get_userpass_input(s->cur_prompt, in, inlen);
8171 * Failed to get responses. Terminate.
8173 free_prompts(s->cur_prompt);
8174 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8175 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8182 * Send the response(s) to the server.
8184 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8185 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8186 for (i=0; i < s->num_prompts; i++) {
8187 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8188 ssh2_pkt_addstring(s->pktout,
8189 s->cur_prompt->prompts[i]->result);
8190 end_log_omission(ssh, s->pktout);
8192 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8195 * Get the next packet in case it's another
8198 crWaitUntilV(pktin);
8203 * We should have SUCCESS or FAILURE now.
8207 } else if (s->can_passwd) {
8210 * Plain old password authentication.
8212 int ret; /* not live over crReturn */
8213 int changereq_first_time; /* not live over crReturn */
8215 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8217 s->cur_prompt = new_prompts(ssh->frontend);
8218 s->cur_prompt->to_server = TRUE;
8219 s->cur_prompt->name = dupstr("SSH password");
8220 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
8223 FALSE, SSH_MAX_PASSWORD_LEN);
8225 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8228 crWaitUntilV(!pktin);
8229 ret = get_userpass_input(s->cur_prompt, in, inlen);
8234 * Failed to get responses. Terminate.
8236 free_prompts(s->cur_prompt);
8237 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8238 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8243 * Squirrel away the password. (We may need it later if
8244 * asked to change it.)
8246 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8247 free_prompts(s->cur_prompt);
8250 * Send the password packet.
8252 * We pad out the password packet to 256 bytes to make
8253 * it harder for an attacker to find the length of the
8256 * Anyone using a password longer than 256 bytes
8257 * probably doesn't have much to worry about from
8258 * people who find out how long their password is!
8260 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8261 ssh2_pkt_addstring(s->pktout, s->username);
8262 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8263 /* service requested */
8264 ssh2_pkt_addstring(s->pktout, "password");
8265 ssh2_pkt_addbool(s->pktout, FALSE);
8266 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8267 ssh2_pkt_addstring(s->pktout, s->password);
8268 end_log_omission(ssh, s->pktout);
8269 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8270 logevent("Sent password");
8271 s->type = AUTH_TYPE_PASSWORD;
8274 * Wait for next packet, in case it's a password change
8277 crWaitUntilV(pktin);
8278 changereq_first_time = TRUE;
8280 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8283 * We're being asked for a new password
8284 * (perhaps not for the first time).
8285 * Loop until the server accepts it.
8288 int got_new = FALSE; /* not live over crReturn */
8289 char *prompt; /* not live over crReturn */
8290 int prompt_len; /* not live over crReturn */
8294 if (changereq_first_time)
8295 msg = "Server requested password change";
8297 msg = "Server rejected new password";
8299 c_write_str(ssh, msg);
8300 c_write_str(ssh, "\r\n");
8303 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8305 s->cur_prompt = new_prompts(ssh->frontend);
8306 s->cur_prompt->to_server = TRUE;
8307 s->cur_prompt->name = dupstr("New SSH password");
8308 s->cur_prompt->instruction =
8309 dupprintf("%.*s", prompt_len, prompt);
8310 s->cur_prompt->instr_reqd = TRUE;
8312 * There's no explicit requirement in the protocol
8313 * for the "old" passwords in the original and
8314 * password-change messages to be the same, and
8315 * apparently some Cisco kit supports password change
8316 * by the user entering a blank password originally
8317 * and the real password subsequently, so,
8318 * reluctantly, we prompt for the old password again.
8320 * (On the other hand, some servers don't even bother
8321 * to check this field.)
8323 add_prompt(s->cur_prompt,
8324 dupstr("Current password (blank for previously entered password): "),
8325 FALSE, SSH_MAX_PASSWORD_LEN);
8326 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8327 FALSE, SSH_MAX_PASSWORD_LEN);
8328 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8329 FALSE, SSH_MAX_PASSWORD_LEN);
8332 * Loop until the user manages to enter the same
8337 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8340 crWaitUntilV(!pktin);
8341 ret = get_userpass_input(s->cur_prompt, in, inlen);
8346 * Failed to get responses. Terminate.
8348 /* burn the evidence */
8349 free_prompts(s->cur_prompt);
8350 memset(s->password, 0, strlen(s->password));
8352 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8353 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8359 * If the user specified a new original password
8360 * (IYSWIM), overwrite any previously specified
8362 * (A side effect is that the user doesn't have to
8363 * re-enter it if they louse up the new password.)
8365 if (s->cur_prompt->prompts[0]->result[0]) {
8366 memset(s->password, 0, strlen(s->password));
8367 /* burn the evidence */
8370 dupstr(s->cur_prompt->prompts[0]->result);
8374 * Check the two new passwords match.
8376 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8377 s->cur_prompt->prompts[2]->result)
8380 /* They don't. Silly user. */
8381 c_write_str(ssh, "Passwords do not match\r\n");
8386 * Send the new password (along with the old one).
8387 * (see above for padding rationale)
8389 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8390 ssh2_pkt_addstring(s->pktout, s->username);
8391 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8392 /* service requested */
8393 ssh2_pkt_addstring(s->pktout, "password");
8394 ssh2_pkt_addbool(s->pktout, TRUE);
8395 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8396 ssh2_pkt_addstring(s->pktout, s->password);
8397 ssh2_pkt_addstring(s->pktout,
8398 s->cur_prompt->prompts[1]->result);
8399 free_prompts(s->cur_prompt);
8400 end_log_omission(ssh, s->pktout);
8401 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8402 logevent("Sent new password");
8405 * Now see what the server has to say about it.
8406 * (If it's CHANGEREQ again, it's not happy with the
8409 crWaitUntilV(pktin);
8410 changereq_first_time = FALSE;
8415 * We need to reexamine the current pktin at the top
8416 * of the loop. Either:
8417 * - we weren't asked to change password at all, in
8418 * which case it's a SUCCESS or FAILURE with the
8420 * - we sent a new password, and the server was
8421 * either OK with it (SUCCESS or FAILURE w/partial
8422 * success) or unhappy with the _old_ password
8423 * (FAILURE w/o partial success)
8424 * In any of these cases, we go back to the top of
8425 * the loop and start again.
8430 * We don't need the old password any more, in any
8431 * case. Burn the evidence.
8433 memset(s->password, 0, strlen(s->password));
8438 ssh_disconnect(ssh, NULL,
8439 "No supported authentication methods available",
8440 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8448 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8450 /* Clear up various bits and pieces from authentication. */
8451 if (s->publickey_blob) {
8452 sfree(s->publickey_blob);
8453 sfree(s->publickey_comment);
8455 if (s->agent_response)
8456 sfree(s->agent_response);
8459 * Now the connection protocol has started, one way or another.
8462 ssh->channels = newtree234(ssh_channelcmp);
8465 * Set up handlers for some connection protocol messages, so we
8466 * don't have to handle them repeatedly in this coroutine.
8468 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8469 ssh2_msg_channel_window_adjust;
8470 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8471 ssh2_msg_global_request;
8474 * Create the main session channel.
8476 if (ssh->cfg.ssh_no_shell) {
8477 ssh->mainchan = NULL;
8478 } else if (*ssh->cfg.ssh_nc_host) {
8480 * Just start a direct-tcpip channel and use it as the main
8483 ssh->mainchan = snew(struct ssh_channel);
8484 ssh->mainchan->ssh = ssh;
8485 ssh2_channel_init(ssh->mainchan);
8487 "Opening direct-tcpip channel to %s:%d in place of session",
8488 ssh->cfg.ssh_nc_host, ssh->cfg.ssh_nc_port);
8489 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8490 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8491 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8492 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8493 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8494 ssh2_pkt_addstring(s->pktout, ssh->cfg.ssh_nc_host);
8495 ssh2_pkt_adduint32(s->pktout, ssh->cfg.ssh_nc_port);
8497 * There's nothing meaningful to put in the originator
8498 * fields, but some servers insist on syntactically correct
8501 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8502 ssh2_pkt_adduint32(s->pktout, 0);
8503 ssh2_pkt_send(ssh, s->pktout);
8505 crWaitUntilV(pktin);
8506 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8507 bombout(("Server refused to open a direct-tcpip channel"));
8509 /* FIXME: error data comes back in FAILURE packet */
8511 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8512 bombout(("Server's channel confirmation cited wrong channel"));
8515 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8516 ssh->mainchan->halfopen = FALSE;
8517 ssh->mainchan->type = CHAN_MAINSESSION;
8518 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8519 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8520 add234(ssh->channels, ssh->mainchan);
8521 update_specials_menu(ssh->frontend);
8522 logevent("Opened direct-tcpip channel");
8525 ssh->mainchan = snew(struct ssh_channel);
8526 ssh->mainchan->ssh = ssh;
8527 ssh2_channel_init(ssh->mainchan);
8528 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8529 ssh2_pkt_addstring(s->pktout, "session");
8530 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8531 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8532 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8533 ssh2_pkt_send(ssh, s->pktout);
8534 crWaitUntilV(pktin);
8535 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8536 bombout(("Server refused to open a session"));
8538 /* FIXME: error data comes back in FAILURE packet */
8540 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8541 bombout(("Server's channel confirmation cited wrong channel"));
8544 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8545 ssh->mainchan->halfopen = FALSE;
8546 ssh->mainchan->type = CHAN_MAINSESSION;
8547 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8548 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8549 add234(ssh->channels, ssh->mainchan);
8550 update_specials_menu(ssh->frontend);
8551 logevent("Opened channel for session");
8552 ssh->ncmode = FALSE;
8556 * Now we have a channel, make dispatch table entries for
8557 * general channel-based messages.
8559 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8560 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8561 ssh2_msg_channel_data;
8562 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8563 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8564 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8565 ssh2_msg_channel_open_confirmation;
8566 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8567 ssh2_msg_channel_open_failure;
8568 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8569 ssh2_msg_channel_request;
8570 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8571 ssh2_msg_channel_open;
8573 if (ssh->mainchan && ssh->cfg.ssh_simple) {
8575 * This message indicates to the server that we promise
8576 * not to try to run any other channel in parallel with
8577 * this one, so it's safe for it to advertise a very large
8578 * window and leave the flow control to TCP.
8580 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8581 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8582 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8583 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8584 ssh2_pkt_send(ssh, s->pktout);
8588 * Potentially enable X11 forwarding.
8590 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.x11_forward &&
8591 (ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
8592 ssh->cfg.x11_auth, &ssh->cfg))) {
8593 logevent("Requesting X11 forwarding");
8594 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8595 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8596 ssh2_pkt_addstring(s->pktout, "x11-req");
8597 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8598 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8599 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8601 * Note that while we blank the X authentication data here, we don't
8602 * take any special action to blank the start of an X11 channel,
8603 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8604 * without having session blanking enabled is likely to leak your
8605 * cookie into the log.
8607 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8608 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8609 end_log_omission(ssh, s->pktout);
8610 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8611 ssh2_pkt_send(ssh, s->pktout);
8613 crWaitUntilV(pktin);
8615 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8616 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8617 bombout(("Unexpected response to X11 forwarding request:"
8618 " packet type %d", pktin->type));
8621 logevent("X11 forwarding refused");
8623 logevent("X11 forwarding enabled");
8624 ssh->X11_fwd_enabled = TRUE;
8629 * Enable port forwardings.
8631 ssh_setup_portfwd(ssh, &ssh->cfg);
8634 * Potentially enable agent forwarding.
8636 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.agentfwd && agent_exists()) {
8637 logevent("Requesting OpenSSH-style agent forwarding");
8638 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8639 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8640 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8641 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8642 ssh2_pkt_send(ssh, s->pktout);
8644 crWaitUntilV(pktin);
8646 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8647 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8648 bombout(("Unexpected response to agent forwarding request:"
8649 " packet type %d", pktin->type));
8652 logevent("Agent forwarding refused");
8654 logevent("Agent forwarding enabled");
8655 ssh->agentfwd_enabled = TRUE;
8660 * Now allocate a pty for the session.
8662 if (ssh->mainchan && !ssh->ncmode && !ssh->cfg.nopty) {
8663 /* Unpick the terminal-speed string. */
8664 /* XXX perhaps we should allow no speeds to be sent. */
8665 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8666 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
8667 /* Build the pty request. */
8668 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8669 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8670 ssh2_pkt_addstring(s->pktout, "pty-req");
8671 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8672 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
8673 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8674 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8675 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8676 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8677 ssh2_pkt_addstring_start(s->pktout);
8678 parse_ttymodes(ssh, ssh->cfg.ttymodes,
8679 ssh2_send_ttymode, (void *)s->pktout);
8680 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
8681 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
8682 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
8683 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
8684 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
8685 ssh2_pkt_send(ssh, s->pktout);
8686 ssh->state = SSH_STATE_INTERMED;
8688 crWaitUntilV(pktin);
8690 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8691 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8692 bombout(("Unexpected response to pty request:"
8693 " packet type %d", pktin->type));
8696 c_write_str(ssh, "Server refused to allocate pty\r\n");
8697 ssh->editing = ssh->echoing = 1;
8699 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8700 ssh->ospeed, ssh->ispeed);
8703 ssh->editing = ssh->echoing = 1;
8707 * Send environment variables.
8709 * Simplest thing here is to send all the requests at once, and
8710 * then wait for a whole bunch of successes or failures.
8712 if (ssh->mainchan && !ssh->ncmode && *ssh->cfg.environmt) {
8713 char *e = ssh->cfg.environmt;
8714 char *var, *varend, *val;
8720 while (*e && *e != '\t') e++;
8722 if (*e == '\t') e++;
8727 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8728 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8729 ssh2_pkt_addstring(s->pktout, "env");
8730 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8731 ssh2_pkt_addstring_start(s->pktout);
8732 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
8733 ssh2_pkt_addstring(s->pktout, val);
8734 ssh2_pkt_send(ssh, s->pktout);
8739 logeventf(ssh, "Sent %d environment variables", s->num_env);
8742 s->env_left = s->num_env;
8744 while (s->env_left > 0) {
8745 crWaitUntilV(pktin);
8747 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8748 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8749 bombout(("Unexpected response to environment request:"
8750 " packet type %d", pktin->type));
8760 if (s->env_ok == s->num_env) {
8761 logevent("All environment variables successfully set");
8762 } else if (s->env_ok == 0) {
8763 logevent("All environment variables refused");
8764 c_write_str(ssh, "Server refused to set environment variables\r\n");
8766 logeventf(ssh, "%d environment variables refused",
8767 s->num_env - s->env_ok);
8768 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8773 * Start a shell or a remote command. We may have to attempt
8774 * this twice if the config data has provided a second choice
8777 if (ssh->mainchan && !ssh->ncmode) while (1) {
8781 if (ssh->fallback_cmd) {
8782 subsys = ssh->cfg.ssh_subsys2;
8783 cmd = ssh->cfg.remote_cmd_ptr2;
8785 subsys = ssh->cfg.ssh_subsys;
8786 cmd = ssh->cfg.remote_cmd_ptr;
8787 if (!cmd) cmd = ssh->cfg.remote_cmd;
8790 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8791 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8793 ssh2_pkt_addstring(s->pktout, "subsystem");
8794 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8795 ssh2_pkt_addstring(s->pktout, cmd);
8797 ssh2_pkt_addstring(s->pktout, "exec");
8798 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8799 ssh2_pkt_addstring(s->pktout, cmd);
8801 ssh2_pkt_addstring(s->pktout, "shell");
8802 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8804 ssh2_pkt_send(ssh, s->pktout);
8806 crWaitUntilV(pktin);
8808 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8809 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8810 bombout(("Unexpected response to shell/command request:"
8811 " packet type %d", pktin->type));
8815 * We failed to start the command. If this is the
8816 * fallback command, we really are finished; if it's
8817 * not, and if the fallback command exists, try falling
8818 * back to it before complaining.
8820 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
8821 logevent("Primary command failed; attempting fallback");
8822 ssh->fallback_cmd = TRUE;
8825 bombout(("Server refused to start a shell/command"));
8828 logevent("Started a shell/command");
8833 ssh->state = SSH_STATE_SESSION;
8834 if (ssh->size_needed)
8835 ssh_size(ssh, ssh->term_width, ssh->term_height);
8836 if (ssh->eof_needed)
8837 ssh_special(ssh, TS_EOF);
8840 * All the initial channel requests are done, so install the default
8843 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
8844 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
8850 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
8855 s->try_send = FALSE;
8859 * _All_ the connection-layer packets we expect to
8860 * receive are now handled by the dispatch table.
8861 * Anything that reaches here must be bogus.
8864 bombout(("Strange packet received: type %d", pktin->type));
8866 } else if (ssh->mainchan) {
8868 * We have spare data. Add it to the channel buffer.
8870 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
8875 struct ssh_channel *c;
8877 * Try to send data on all channels if we can.
8879 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
8880 ssh2_try_send_and_unthrottle(c);
8888 * Handlers for SSH-2 messages that might arrive at any moment.
8890 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
8892 /* log reason code in disconnect message */
8896 reason = ssh_pkt_getuint32(pktin);
8897 ssh_pkt_getstring(pktin, &msg, &msglen);
8899 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
8900 buf = dupprintf("Received disconnect message (%s)",
8901 ssh2_disconnect_reasons[reason]);
8903 buf = dupprintf("Received disconnect message (unknown"
8904 " type %d)", reason);
8908 buf = dupprintf("Disconnection message text: %.*s",
8911 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
8913 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
8914 ssh2_disconnect_reasons[reason] : "unknown",
8919 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
8921 /* log the debug message */
8926 /* XXX maybe we should actually take notice of this */
8927 always_display = ssh2_pkt_getbool(pktin);
8928 ssh_pkt_getstring(pktin, &msg, &msglen);
8930 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
8933 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
8935 struct Packet *pktout;
8936 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
8937 ssh2_pkt_adduint32(pktout, pktin->sequence);
8939 * UNIMPLEMENTED messages MUST appear in the same order as the
8940 * messages they respond to. Hence, never queue them.
8942 ssh2_pkt_send_noqueue(ssh, pktout);
8946 * Handle the top-level SSH-2 protocol.
8948 static void ssh2_protocol_setup(Ssh ssh)
8953 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
8955 for (i = 0; i < 256; i++)
8956 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
8959 * Any message we actually understand, we set to NULL so that
8960 * the coroutines will get it.
8962 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
8963 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
8964 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
8965 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
8966 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
8967 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
8968 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
8969 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
8970 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
8971 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
8972 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
8973 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
8974 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
8975 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
8976 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8977 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
8978 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
8979 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
8980 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
8981 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
8982 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
8983 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
8984 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
8985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
8986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
8987 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
8988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
8989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
8990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
8991 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
8992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
8993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
8994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
8997 * These special message types we install handlers for.
8999 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9000 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9001 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9004 static void ssh2_timer(void *ctx, long now)
9008 if (ssh->state == SSH_STATE_CLOSED)
9011 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
9012 now - ssh->next_rekey >= 0) {
9013 do_ssh2_transport(ssh, "timeout", -1, NULL);
9017 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9018 struct Packet *pktin)
9020 unsigned char *in = (unsigned char *)vin;
9021 if (ssh->state == SSH_STATE_CLOSED)
9025 ssh->incoming_data_size += pktin->encrypted_len;
9026 if (!ssh->kex_in_progress &&
9027 ssh->max_data_size != 0 &&
9028 ssh->incoming_data_size > ssh->max_data_size)
9029 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9032 if (pktin && ssh->packet_dispatch[pktin->type]) {
9033 ssh->packet_dispatch[pktin->type](ssh, pktin);
9037 if (!ssh->protocol_initial_phase_done ||
9038 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9039 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9040 !ssh->protocol_initial_phase_done) {
9041 ssh->protocol_initial_phase_done = TRUE;
9043 * Allow authconn to initialise itself.
9045 do_ssh2_authconn(ssh, NULL, 0, NULL);
9048 do_ssh2_authconn(ssh, in, inlen, pktin);
9053 * Called to set up the connection.
9055 * Returns an error message, or NULL on success.
9057 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9059 char *host, int port, char **realhost, int nodelay,
9065 ssh = snew(struct ssh_tag);
9066 ssh->cfg = *cfg; /* STRUCTURE COPY */
9067 ssh->version = 0; /* when not ready yet */
9070 ssh->v1_cipher_ctx = NULL;
9071 ssh->crcda_ctx = NULL;
9072 ssh->cscipher = NULL;
9073 ssh->cs_cipher_ctx = NULL;
9074 ssh->sccipher = NULL;
9075 ssh->sc_cipher_ctx = NULL;
9077 ssh->cs_mac_ctx = NULL;
9079 ssh->sc_mac_ctx = NULL;
9081 ssh->cs_comp_ctx = NULL;
9083 ssh->sc_comp_ctx = NULL;
9085 ssh->kex_ctx = NULL;
9086 ssh->hostkey = NULL;
9088 ssh->close_expected = FALSE;
9089 ssh->clean_exit = FALSE;
9090 ssh->state = SSH_STATE_PREPACKET;
9091 ssh->size_needed = FALSE;
9092 ssh->eof_needed = FALSE;
9095 ssh->deferred_send_data = NULL;
9096 ssh->deferred_len = 0;
9097 ssh->deferred_size = 0;
9098 ssh->fallback_cmd = 0;
9099 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9100 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9101 ssh->x11disp = NULL;
9102 ssh->v1_compressing = FALSE;
9103 ssh->v2_outgoing_sequence = 0;
9104 ssh->ssh1_rdpkt_crstate = 0;
9105 ssh->ssh2_rdpkt_crstate = 0;
9106 ssh->do_ssh_init_crstate = 0;
9107 ssh->ssh_gotdata_crstate = 0;
9108 ssh->do_ssh1_connection_crstate = 0;
9109 ssh->do_ssh1_login_crstate = 0;
9110 ssh->do_ssh2_transport_crstate = 0;
9111 ssh->do_ssh2_authconn_crstate = 0;
9112 ssh->do_ssh_init_state = NULL;
9113 ssh->do_ssh1_login_state = NULL;
9114 ssh->do_ssh2_transport_state = NULL;
9115 ssh->do_ssh2_authconn_state = NULL;
9118 ssh->mainchan = NULL;
9119 ssh->throttled_all = 0;
9120 ssh->v1_stdout_throttling = 0;
9122 ssh->queuelen = ssh->queuesize = 0;
9123 ssh->queueing = FALSE;
9124 ssh->qhead = ssh->qtail = NULL;
9125 ssh->deferred_rekey_reason = NULL;
9126 bufchain_init(&ssh->queued_incoming_data);
9127 ssh->frozen = FALSE;
9129 *backend_handle = ssh;
9132 if (crypto_startup() == 0)
9133 return "Microsoft high encryption pack not installed!";
9136 ssh->frontend = frontend_handle;
9137 ssh->term_width = ssh->cfg.width;
9138 ssh->term_height = ssh->cfg.height;
9140 ssh->channels = NULL;
9141 ssh->rportfwds = NULL;
9142 ssh->portfwds = NULL;
9147 ssh->conn_throttle_count = 0;
9148 ssh->overall_bufsize = 0;
9149 ssh->fallback_cmd = 0;
9151 ssh->protocol = NULL;
9153 ssh->protocol_initial_phase_done = FALSE;
9157 ssh->incoming_data_size = ssh->outgoing_data_size =
9158 ssh->deferred_data_size = 0L;
9159 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
9160 ssh->kex_in_progress = FALSE;
9162 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9171 static void ssh_free(void *handle)
9173 Ssh ssh = (Ssh) handle;
9174 struct ssh_channel *c;
9175 struct ssh_rportfwd *pf;
9177 if (ssh->v1_cipher_ctx)
9178 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9179 if (ssh->cs_cipher_ctx)
9180 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9181 if (ssh->sc_cipher_ctx)
9182 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9183 if (ssh->cs_mac_ctx)
9184 ssh->csmac->free_context(ssh->cs_mac_ctx);
9185 if (ssh->sc_mac_ctx)
9186 ssh->scmac->free_context(ssh->sc_mac_ctx);
9187 if (ssh->cs_comp_ctx) {
9189 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9191 zlib_compress_cleanup(ssh->cs_comp_ctx);
9193 if (ssh->sc_comp_ctx) {
9195 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9197 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9200 dh_cleanup(ssh->kex_ctx);
9201 sfree(ssh->savedhost);
9203 while (ssh->queuelen-- > 0)
9204 ssh_free_packet(ssh->queue[ssh->queuelen]);
9207 while (ssh->qhead) {
9208 struct queued_handler *qh = ssh->qhead;
9209 ssh->qhead = qh->next;
9212 ssh->qhead = ssh->qtail = NULL;
9214 if (ssh->channels) {
9215 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9218 if (c->u.x11.s != NULL)
9219 x11_close(c->u.x11.s);
9222 if (c->u.pfd.s != NULL)
9223 pfd_close(c->u.pfd.s);
9228 freetree234(ssh->channels);
9229 ssh->channels = NULL;
9232 if (ssh->rportfwds) {
9233 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9235 freetree234(ssh->rportfwds);
9236 ssh->rportfwds = NULL;
9238 sfree(ssh->deferred_send_data);
9240 x11_free_display(ssh->x11disp);
9241 sfree(ssh->do_ssh_init_state);
9242 sfree(ssh->do_ssh1_login_state);
9243 sfree(ssh->do_ssh2_transport_state);
9244 sfree(ssh->do_ssh2_authconn_state);
9247 sfree(ssh->fullhostname);
9248 if (ssh->crcda_ctx) {
9249 crcda_free_context(ssh->crcda_ctx);
9250 ssh->crcda_ctx = NULL;
9253 ssh_do_close(ssh, TRUE);
9254 expire_timer_context(ssh);
9256 pinger_free(ssh->pinger);
9257 bufchain_clear(&ssh->queued_incoming_data);
9264 * Reconfigure the SSH backend.
9266 static void ssh_reconfig(void *handle, Config *cfg)
9268 Ssh ssh = (Ssh) handle;
9269 char *rekeying = NULL, rekey_mandatory = FALSE;
9270 unsigned long old_max_data_size;
9272 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
9274 ssh_setup_portfwd(ssh, cfg);
9276 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
9277 cfg->ssh_rekey_time != 0) {
9278 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
9279 long now = GETTICKCOUNT();
9281 if (new_next - now < 0) {
9282 rekeying = "timeout shortened";
9284 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9288 old_max_data_size = ssh->max_data_size;
9289 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
9290 if (old_max_data_size != ssh->max_data_size &&
9291 ssh->max_data_size != 0) {
9292 if (ssh->outgoing_data_size > ssh->max_data_size ||
9293 ssh->incoming_data_size > ssh->max_data_size)
9294 rekeying = "data limit lowered";
9297 if (ssh->cfg.compression != cfg->compression) {
9298 rekeying = "compression setting changed";
9299 rekey_mandatory = TRUE;
9302 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
9303 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
9304 sizeof(ssh->cfg.ssh_cipherlist))) {
9305 rekeying = "cipher settings changed";
9306 rekey_mandatory = TRUE;
9309 ssh->cfg = *cfg; /* STRUCTURE COPY */
9312 if (!ssh->kex_in_progress) {
9313 do_ssh2_transport(ssh, rekeying, -1, NULL);
9314 } else if (rekey_mandatory) {
9315 ssh->deferred_rekey_reason = rekeying;
9321 * Called to send data down the SSH connection.
9323 static int ssh_send(void *handle, char *buf, int len)
9325 Ssh ssh = (Ssh) handle;
9327 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9330 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9332 return ssh_sendbuffer(ssh);
9336 * Called to query the current amount of buffered stdin data.
9338 static int ssh_sendbuffer(void *handle)
9340 Ssh ssh = (Ssh) handle;
9343 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9347 * If the SSH socket itself has backed up, add the total backup
9348 * size on that to any individual buffer on the stdin channel.
9351 if (ssh->throttled_all)
9352 override_value = ssh->overall_bufsize;
9354 if (ssh->version == 1) {
9355 return override_value;
9356 } else if (ssh->version == 2) {
9357 if (!ssh->mainchan || ssh->mainchan->closes > 0)
9358 return override_value;
9360 return (override_value +
9361 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9368 * Called to set the size of the window from SSH's POV.
9370 static void ssh_size(void *handle, int width, int height)
9372 Ssh ssh = (Ssh) handle;
9373 struct Packet *pktout;
9375 ssh->term_width = width;
9376 ssh->term_height = height;
9378 switch (ssh->state) {
9379 case SSH_STATE_BEFORE_SIZE:
9380 case SSH_STATE_PREPACKET:
9381 case SSH_STATE_CLOSED:
9382 break; /* do nothing */
9383 case SSH_STATE_INTERMED:
9384 ssh->size_needed = TRUE; /* buffer for later */
9386 case SSH_STATE_SESSION:
9387 if (!ssh->cfg.nopty) {
9388 if (ssh->version == 1) {
9389 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9390 PKT_INT, ssh->term_height,
9391 PKT_INT, ssh->term_width,
9392 PKT_INT, 0, PKT_INT, 0, PKT_END);
9393 } else if (ssh->mainchan) {
9394 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9395 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9396 ssh2_pkt_addstring(pktout, "window-change");
9397 ssh2_pkt_addbool(pktout, 0);
9398 ssh2_pkt_adduint32(pktout, ssh->term_width);
9399 ssh2_pkt_adduint32(pktout, ssh->term_height);
9400 ssh2_pkt_adduint32(pktout, 0);
9401 ssh2_pkt_adduint32(pktout, 0);
9402 ssh2_pkt_send(ssh, pktout);
9410 * Return a list of the special codes that make sense in this
9413 static const struct telnet_special *ssh_get_specials(void *handle)
9415 static const struct telnet_special ssh1_ignore_special[] = {
9416 {"IGNORE message", TS_NOP}
9418 static const struct telnet_special ssh2_transport_specials[] = {
9419 {"IGNORE message", TS_NOP},
9420 {"Repeat key exchange", TS_REKEY},
9422 static const struct telnet_special ssh2_session_specials[] = {
9425 /* These are the signal names defined by RFC 4254.
9426 * They include all the ISO C signals, but are a subset of the POSIX
9427 * required signals. */
9428 {"SIGINT (Interrupt)", TS_SIGINT},
9429 {"SIGTERM (Terminate)", TS_SIGTERM},
9430 {"SIGKILL (Kill)", TS_SIGKILL},
9431 {"SIGQUIT (Quit)", TS_SIGQUIT},
9432 {"SIGHUP (Hangup)", TS_SIGHUP},
9433 {"More signals", TS_SUBMENU},
9434 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9435 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9436 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9437 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9440 static const struct telnet_special specials_end[] = {
9443 /* XXX review this length for any changes: */
9444 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
9445 lenof(ssh2_session_specials) +
9446 lenof(specials_end)];
9447 Ssh ssh = (Ssh) handle;
9449 #define ADD_SPECIALS(name) \
9451 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9452 memcpy(&ssh_specials[i], name, sizeof name); \
9456 if (ssh->version == 1) {
9457 /* Don't bother offering IGNORE if we've decided the remote
9458 * won't cope with it, since we wouldn't bother sending it if
9460 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9461 ADD_SPECIALS(ssh1_ignore_special);
9462 } else if (ssh->version == 2) {
9463 ADD_SPECIALS(ssh2_transport_specials);
9465 ADD_SPECIALS(ssh2_session_specials);
9466 } /* else we're not ready yet */
9469 ADD_SPECIALS(specials_end);
9470 return ssh_specials;
9478 * Send special codes. TS_EOF is useful for `plink', so you
9479 * can send an EOF and collect resulting output (e.g. `plink
9482 static void ssh_special(void *handle, Telnet_Special code)
9484 Ssh ssh = (Ssh) handle;
9485 struct Packet *pktout;
9487 if (code == TS_EOF) {
9488 if (ssh->state != SSH_STATE_SESSION) {
9490 * Buffer the EOF in case we are pre-SESSION, so we can
9491 * send it as soon as we reach SESSION.
9494 ssh->eof_needed = TRUE;
9497 if (ssh->version == 1) {
9498 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9499 } else if (ssh->mainchan) {
9500 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
9501 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9502 ssh2_pkt_send(ssh, pktout);
9503 ssh->send_ok = 0; /* now stop trying to read from stdin */
9505 logevent("Sent EOF message");
9506 } else if (code == TS_PING || code == TS_NOP) {
9507 if (ssh->state == SSH_STATE_CLOSED
9508 || ssh->state == SSH_STATE_PREPACKET) return;
9509 if (ssh->version == 1) {
9510 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9511 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9513 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9514 ssh2_pkt_addstring_start(pktout);
9515 ssh2_pkt_send_noqueue(ssh, pktout);
9517 } else if (code == TS_REKEY) {
9518 if (!ssh->kex_in_progress && ssh->version == 2) {
9519 do_ssh2_transport(ssh, "at user request", -1, NULL);
9521 } else if (code == TS_BRK) {
9522 if (ssh->state == SSH_STATE_CLOSED
9523 || ssh->state == SSH_STATE_PREPACKET) return;
9524 if (ssh->version == 1) {
9525 logevent("Unable to send BREAK signal in SSH-1");
9526 } else if (ssh->mainchan) {
9527 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9528 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9529 ssh2_pkt_addstring(pktout, "break");
9530 ssh2_pkt_addbool(pktout, 0);
9531 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9532 ssh2_pkt_send(ssh, pktout);
9535 /* Is is a POSIX signal? */
9536 char *signame = NULL;
9537 if (code == TS_SIGABRT) signame = "ABRT";
9538 if (code == TS_SIGALRM) signame = "ALRM";
9539 if (code == TS_SIGFPE) signame = "FPE";
9540 if (code == TS_SIGHUP) signame = "HUP";
9541 if (code == TS_SIGILL) signame = "ILL";
9542 if (code == TS_SIGINT) signame = "INT";
9543 if (code == TS_SIGKILL) signame = "KILL";
9544 if (code == TS_SIGPIPE) signame = "PIPE";
9545 if (code == TS_SIGQUIT) signame = "QUIT";
9546 if (code == TS_SIGSEGV) signame = "SEGV";
9547 if (code == TS_SIGTERM) signame = "TERM";
9548 if (code == TS_SIGUSR1) signame = "USR1";
9549 if (code == TS_SIGUSR2) signame = "USR2";
9550 /* The SSH-2 protocol does in principle support arbitrary named
9551 * signals, including signame@domain, but we don't support those. */
9553 /* It's a signal. */
9554 if (ssh->version == 2 && ssh->mainchan) {
9555 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9556 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9557 ssh2_pkt_addstring(pktout, "signal");
9558 ssh2_pkt_addbool(pktout, 0);
9559 ssh2_pkt_addstring(pktout, signame);
9560 ssh2_pkt_send(ssh, pktout);
9561 logeventf(ssh, "Sent signal SIG%s", signame);
9564 /* Never heard of it. Do nothing */
9569 void *new_sock_channel(void *handle, Socket s)
9571 Ssh ssh = (Ssh) handle;
9572 struct ssh_channel *c;
9573 c = snew(struct ssh_channel);
9576 ssh2_channel_init(c);
9578 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9580 add234(ssh->channels, c);
9585 * This is called when stdout/stderr (the entity to which
9586 * from_backend sends data) manages to clear some backlog.
9588 static void ssh_unthrottle(void *handle, int bufsize)
9590 Ssh ssh = (Ssh) handle;
9593 if (ssh->version == 1) {
9594 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9595 ssh->v1_stdout_throttling = 0;
9596 ssh_throttle_conn(ssh, -1);
9599 if (ssh->mainchan) {
9600 ssh2_set_window(ssh->mainchan,
9601 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9602 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9603 if (ssh->cfg.ssh_simple)
9606 buflimit = ssh->mainchan->v.v2.locmaxwin;
9607 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9608 ssh->mainchan->throttling_conn = 0;
9609 ssh_throttle_conn(ssh, -1);
9615 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9617 struct ssh_channel *c = (struct ssh_channel *)channel;
9619 struct Packet *pktout;
9621 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9623 if (ssh->version == 1) {
9624 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9625 PKT_INT, c->localid,
9628 /* PKT_STR, <org:orgport>, */
9631 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9632 ssh2_pkt_addstring(pktout, "direct-tcpip");
9633 ssh2_pkt_adduint32(pktout, c->localid);
9634 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9635 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9636 ssh2_pkt_addstring(pktout, hostname);
9637 ssh2_pkt_adduint32(pktout, port);
9639 * We make up values for the originator data; partly it's
9640 * too much hassle to keep track, and partly I'm not
9641 * convinced the server should be told details like that
9642 * about my local network configuration.
9643 * The "originator IP address" is syntactically a numeric
9644 * IP address, and some servers (e.g., Tectia) get upset
9645 * if it doesn't match this syntax.
9647 ssh2_pkt_addstring(pktout, "0.0.0.0");
9648 ssh2_pkt_adduint32(pktout, 0);
9649 ssh2_pkt_send(ssh, pktout);
9653 static int ssh_connected(void *handle)
9655 Ssh ssh = (Ssh) handle;
9656 return ssh->s != NULL;
9659 static int ssh_sendok(void *handle)
9661 Ssh ssh = (Ssh) handle;
9662 return ssh->send_ok;
9665 static int ssh_ldisc(void *handle, int option)
9667 Ssh ssh = (Ssh) handle;
9668 if (option == LD_ECHO)
9669 return ssh->echoing;
9670 if (option == LD_EDIT)
9671 return ssh->editing;
9675 static void ssh_provide_ldisc(void *handle, void *ldisc)
9677 Ssh ssh = (Ssh) handle;
9681 static void ssh_provide_logctx(void *handle, void *logctx)
9683 Ssh ssh = (Ssh) handle;
9684 ssh->logctx = logctx;
9687 static int ssh_return_exitcode(void *handle)
9689 Ssh ssh = (Ssh) handle;
9693 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
9697 * cfg_info for SSH is the currently running version of the
9698 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9700 static int ssh_cfg_info(void *handle)
9702 Ssh ssh = (Ssh) handle;
9703 return ssh->version;
9707 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9708 * that fails. This variable is the means by which scp.c can reach
9709 * into the SSH code and find out which one it got.
9711 extern int ssh_fallback_cmd(void *handle)
9713 Ssh ssh = (Ssh) handle;
9714 return ssh->fallback_cmd;
9717 Backend ssh_backend = {
9727 ssh_return_exitcode,