27 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
28 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
29 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
30 #define SSH1_CMSG_USER 4 /* 0x4 */
31 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
32 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
33 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
34 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
35 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
36 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
37 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
38 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
39 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
40 #define SSH1_SMSG_FAILURE 15 /* 0xf */
41 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
42 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
43 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
44 #define SSH1_CMSG_EOF 19 /* 0x13 */
45 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
46 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
47 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
48 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
49 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
50 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
51 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
52 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
53 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
54 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
55 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
56 #define SSH1_MSG_IGNORE 32 /* 0x20 */
57 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
58 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
59 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
60 #define SSH1_MSG_DEBUG 36 /* 0x24 */
61 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
62 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
63 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
64 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
65 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
66 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
67 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
69 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
70 #define SSH1_AUTH_RSA 2 /* 0x2 */
71 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
72 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
73 #define SSH1_AUTH_TIS 5 /* 0x5 */
74 #define SSH1_AUTH_CCARD 16 /* 0x10 */
76 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
77 /* Mask for protoflags we will echo back to server if seen */
78 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
91 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
92 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
93 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
94 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
95 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
96 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
97 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
98 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
99 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
100 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
101 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
102 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
103 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
104 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
105 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
106 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
107 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
108 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
109 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
110 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
111 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
112 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
113 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
114 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
115 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
116 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
117 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
118 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
119 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
120 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
121 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
122 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
123 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
124 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
138 SSH2_PKTCTX_PUBLICKEY,
139 SSH2_PKTCTX_PASSWORD,
144 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
145 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
146 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
147 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
148 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
149 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
150 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
151 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
152 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
153 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
154 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
155 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
156 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
157 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
158 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
160 static const char *const ssh2_disconnect_reasons[] = {
162 "host not allowed to connect",
164 "key exchange failed",
165 "host authentication failed",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
179 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
180 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
181 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
182 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
184 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
187 * Various remote-bug flags.
189 #define BUG_CHOKES_ON_SSH1_IGNORE 1
190 #define BUG_SSH2_HMAC 2
191 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
192 #define BUG_CHOKES_ON_RSA 8
193 #define BUG_SSH2_RSA_PADDING 16
194 #define BUG_SSH2_DERIVEKEY 32
195 #define BUG_SSH2_REKEY 64
196 #define BUG_SSH2_PK_SESSIONID 128
197 #define BUG_SSH2_MAXPKT 256
198 #define BUG_CHOKES_ON_SSH2_IGNORE 512
201 * Codes for terminal modes.
202 * Most of these are the same in SSH-1 and SSH-2.
203 * This list is derived from RFC 4254 and
206 static const struct {
207 const char* const mode;
209 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
211 /* "V" prefix discarded for special characters relative to SSH specs */
212 { "INTR", 1, TTY_OP_CHAR },
213 { "QUIT", 2, TTY_OP_CHAR },
214 { "ERASE", 3, TTY_OP_CHAR },
215 { "KILL", 4, TTY_OP_CHAR },
216 { "EOF", 5, TTY_OP_CHAR },
217 { "EOL", 6, TTY_OP_CHAR },
218 { "EOL2", 7, TTY_OP_CHAR },
219 { "START", 8, TTY_OP_CHAR },
220 { "STOP", 9, TTY_OP_CHAR },
221 { "SUSP", 10, TTY_OP_CHAR },
222 { "DSUSP", 11, TTY_OP_CHAR },
223 { "REPRINT", 12, TTY_OP_CHAR },
224 { "WERASE", 13, TTY_OP_CHAR },
225 { "LNEXT", 14, TTY_OP_CHAR },
226 { "FLUSH", 15, TTY_OP_CHAR },
227 { "SWTCH", 16, TTY_OP_CHAR },
228 { "STATUS", 17, TTY_OP_CHAR },
229 { "DISCARD", 18, TTY_OP_CHAR },
230 { "IGNPAR", 30, TTY_OP_BOOL },
231 { "PARMRK", 31, TTY_OP_BOOL },
232 { "INPCK", 32, TTY_OP_BOOL },
233 { "ISTRIP", 33, TTY_OP_BOOL },
234 { "INLCR", 34, TTY_OP_BOOL },
235 { "IGNCR", 35, TTY_OP_BOOL },
236 { "ICRNL", 36, TTY_OP_BOOL },
237 { "IUCLC", 37, TTY_OP_BOOL },
238 { "IXON", 38, TTY_OP_BOOL },
239 { "IXANY", 39, TTY_OP_BOOL },
240 { "IXOFF", 40, TTY_OP_BOOL },
241 { "IMAXBEL", 41, TTY_OP_BOOL },
242 { "ISIG", 50, TTY_OP_BOOL },
243 { "ICANON", 51, TTY_OP_BOOL },
244 { "XCASE", 52, TTY_OP_BOOL },
245 { "ECHO", 53, TTY_OP_BOOL },
246 { "ECHOE", 54, TTY_OP_BOOL },
247 { "ECHOK", 55, TTY_OP_BOOL },
248 { "ECHONL", 56, TTY_OP_BOOL },
249 { "NOFLSH", 57, TTY_OP_BOOL },
250 { "TOSTOP", 58, TTY_OP_BOOL },
251 { "IEXTEN", 59, TTY_OP_BOOL },
252 { "ECHOCTL", 60, TTY_OP_BOOL },
253 { "ECHOKE", 61, TTY_OP_BOOL },
254 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
255 { "OPOST", 70, TTY_OP_BOOL },
256 { "OLCUC", 71, TTY_OP_BOOL },
257 { "ONLCR", 72, TTY_OP_BOOL },
258 { "OCRNL", 73, TTY_OP_BOOL },
259 { "ONOCR", 74, TTY_OP_BOOL },
260 { "ONLRET", 75, TTY_OP_BOOL },
261 { "CS7", 90, TTY_OP_BOOL },
262 { "CS8", 91, TTY_OP_BOOL },
263 { "PARENB", 92, TTY_OP_BOOL },
264 { "PARODD", 93, TTY_OP_BOOL }
267 /* Miscellaneous other tty-related constants. */
268 #define SSH_TTY_OP_END 0
269 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
270 #define SSH1_TTY_OP_ISPEED 192
271 #define SSH1_TTY_OP_OSPEED 193
272 #define SSH2_TTY_OP_ISPEED 128
273 #define SSH2_TTY_OP_OSPEED 129
275 /* Helper functions for parsing tty-related config. */
276 static unsigned int ssh_tty_parse_specchar(char *s)
281 ret = ctrlparse(s, &next);
282 if (!next) ret = s[0];
284 ret = 255; /* special value meaning "don't set" */
288 static unsigned int ssh_tty_parse_boolean(char *s)
290 if (stricmp(s, "yes") == 0 ||
291 stricmp(s, "on") == 0 ||
292 stricmp(s, "true") == 0 ||
293 stricmp(s, "+") == 0)
295 else if (stricmp(s, "no") == 0 ||
296 stricmp(s, "off") == 0 ||
297 stricmp(s, "false") == 0 ||
298 stricmp(s, "-") == 0)
299 return 0; /* false */
301 return (atoi(s) != 0);
304 #define translate(x) if (type == x) return #x
305 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
306 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
307 static char *ssh1_pkt_type(int type)
309 translate(SSH1_MSG_DISCONNECT);
310 translate(SSH1_SMSG_PUBLIC_KEY);
311 translate(SSH1_CMSG_SESSION_KEY);
312 translate(SSH1_CMSG_USER);
313 translate(SSH1_CMSG_AUTH_RSA);
314 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
315 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
316 translate(SSH1_CMSG_AUTH_PASSWORD);
317 translate(SSH1_CMSG_REQUEST_PTY);
318 translate(SSH1_CMSG_WINDOW_SIZE);
319 translate(SSH1_CMSG_EXEC_SHELL);
320 translate(SSH1_CMSG_EXEC_CMD);
321 translate(SSH1_SMSG_SUCCESS);
322 translate(SSH1_SMSG_FAILURE);
323 translate(SSH1_CMSG_STDIN_DATA);
324 translate(SSH1_SMSG_STDOUT_DATA);
325 translate(SSH1_SMSG_STDERR_DATA);
326 translate(SSH1_CMSG_EOF);
327 translate(SSH1_SMSG_EXIT_STATUS);
328 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
329 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
330 translate(SSH1_MSG_CHANNEL_DATA);
331 translate(SSH1_MSG_CHANNEL_CLOSE);
332 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
333 translate(SSH1_SMSG_X11_OPEN);
334 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
335 translate(SSH1_MSG_PORT_OPEN);
336 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
337 translate(SSH1_SMSG_AGENT_OPEN);
338 translate(SSH1_MSG_IGNORE);
339 translate(SSH1_CMSG_EXIT_CONFIRMATION);
340 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
341 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
342 translate(SSH1_MSG_DEBUG);
343 translate(SSH1_CMSG_REQUEST_COMPRESSION);
344 translate(SSH1_CMSG_AUTH_TIS);
345 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
346 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
347 translate(SSH1_CMSG_AUTH_CCARD);
348 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
349 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
352 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
360 translate(SSH2_MSG_DISCONNECT);
361 translate(SSH2_MSG_IGNORE);
362 translate(SSH2_MSG_UNIMPLEMENTED);
363 translate(SSH2_MSG_DEBUG);
364 translate(SSH2_MSG_SERVICE_REQUEST);
365 translate(SSH2_MSG_SERVICE_ACCEPT);
366 translate(SSH2_MSG_KEXINIT);
367 translate(SSH2_MSG_NEWKEYS);
368 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
369 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
371 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
375 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
377 translate(SSH2_MSG_USERAUTH_REQUEST);
378 translate(SSH2_MSG_USERAUTH_FAILURE);
379 translate(SSH2_MSG_USERAUTH_SUCCESS);
380 translate(SSH2_MSG_USERAUTH_BANNER);
381 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
382 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
383 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
384 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
385 translate(SSH2_MSG_GLOBAL_REQUEST);
386 translate(SSH2_MSG_REQUEST_SUCCESS);
387 translate(SSH2_MSG_REQUEST_FAILURE);
388 translate(SSH2_MSG_CHANNEL_OPEN);
389 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
390 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
391 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
392 translate(SSH2_MSG_CHANNEL_DATA);
393 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
394 translate(SSH2_MSG_CHANNEL_EOF);
395 translate(SSH2_MSG_CHANNEL_CLOSE);
396 translate(SSH2_MSG_CHANNEL_REQUEST);
397 translate(SSH2_MSG_CHANNEL_SUCCESS);
398 translate(SSH2_MSG_CHANNEL_FAILURE);
404 /* Enumeration values for fields in SSH-1 packets */
406 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
407 /* These values are for communicating relevant semantics of
408 * fields to the packet logging code. */
409 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
413 * Coroutine mechanics for the sillier bits of the code. If these
414 * macros look impenetrable to you, you might find it helpful to
417 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
419 * which explains the theory behind these macros.
421 * In particular, if you are getting `case expression not constant'
422 * errors when building with MS Visual Studio, this is because MS's
423 * Edit and Continue debugging feature causes their compiler to
424 * violate ANSI C. To disable Edit and Continue debugging:
426 * - right-click ssh.c in the FileView
428 * - select the C/C++ tab and the General category
429 * - under `Debug info:', select anything _other_ than `Program
430 * Database for Edit and Continue'.
432 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
435 if (!ssh->t) ssh->t = snew(struct t); \
437 #define crFinish(z) } *crLine = 0; return (z); }
438 #define crFinishV } *crLine = 0; return; }
439 #define crReturn(z) \
441 *crLine =__LINE__; return (z); case __LINE__:;\
445 *crLine=__LINE__; return; case __LINE__:;\
447 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
448 #define crStopV do{ *crLine = 0; return; }while(0)
449 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
450 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
452 typedef struct ssh_tag *Ssh;
455 static struct Packet *ssh1_pkt_init(int pkt_type);
456 static struct Packet *ssh2_pkt_init(int pkt_type);
457 static void ssh_pkt_ensure(struct Packet *, int length);
458 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
459 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
460 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
461 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
462 static void ssh_pkt_addstring_start(struct Packet *);
463 static void ssh_pkt_addstring_str(struct Packet *, char *data);
464 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
465 static void ssh_pkt_addstring(struct Packet *, char *data);
466 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
467 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
468 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
469 static int ssh2_pkt_construct(Ssh, struct Packet *);
470 static void ssh2_pkt_send(Ssh, struct Packet *);
471 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
472 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
473 struct Packet *pktin);
474 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
475 struct Packet *pktin);
478 * Buffer management constants. There are several of these for
479 * various different purposes:
481 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
482 * on a local data stream before we throttle the whole SSH
483 * connection (in SSH-1 only). Throttling the whole connection is
484 * pretty drastic so we set this high in the hope it won't
487 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
488 * on the SSH connection itself before we defensively throttle
489 * _all_ local data streams. This is pretty drastic too (though
490 * thankfully unlikely in SSH-2 since the window mechanism should
491 * ensure that the server never has any need to throttle its end
492 * of the connection), so we set this high as well.
494 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
497 * - OUR_V2_BIGWIN is the window size we advertise for the only
498 * channel in a simple connection. It must be <= INT_MAX.
500 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
501 * to the remote side. This actually has nothing to do with the
502 * size of the _packet_, but is instead a limit on the amount
503 * of data we're willing to receive in a single SSH2 channel
506 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
507 * _packet_ we're prepared to cope with. It must be a multiple
508 * of the cipher block size, and must be at least 35000.
511 #define SSH1_BUFFER_LIMIT 32768
512 #define SSH_MAX_BACKLOG 32768
513 #define OUR_V2_WINSIZE 16384
514 #define OUR_V2_BIGWIN 0x7fffffff
515 #define OUR_V2_MAXPKT 0x4000UL
516 #define OUR_V2_PACKETLIMIT 0x9000UL
518 /* Maximum length of passwords/passphrases (arbitrary) */
519 #define SSH_MAX_PASSWORD_LEN 100
521 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
523 const static struct ssh_mac *macs[] = {
524 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
526 const static struct ssh_mac *buggymacs[] = {
527 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
530 static void *ssh_comp_none_init(void)
534 static void ssh_comp_none_cleanup(void *handle)
537 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
538 unsigned char **outblock, int *outlen)
542 static int ssh_comp_none_disable(void *handle)
546 const static struct ssh_compress ssh_comp_none = {
548 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
549 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
550 ssh_comp_none_disable, NULL
552 extern const struct ssh_compress ssh_zlib;
553 const static struct ssh_compress *compressions[] = {
554 &ssh_zlib, &ssh_comp_none
557 enum { /* channel types */
562 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
566 * little structure to keep track of outstanding WINDOW_ADJUSTs
574 * 2-3-4 tree storing channels.
577 Ssh ssh; /* pointer back to main context */
578 unsigned remoteid, localid;
580 /* True if we opened this channel but server hasn't confirmed. */
583 * In SSH-1, this value contains four bits:
585 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
586 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
587 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
588 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
590 * A channel is completely finished with when all four bits are set.
594 * True if this channel is causing the underlying connection to be
599 struct ssh2_data_channel {
601 unsigned remwindow, remmaxpkt;
602 /* locwindow is signed so we can cope with excess data. */
603 int locwindow, locmaxwin;
605 * remlocwin is the amount of local window that we think
606 * the remote end had available to it after it sent the
607 * last data packet or window adjust ack.
611 * These store the list of window adjusts that haven't
614 struct winadj *winadj_head, *winadj_tail;
615 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
619 struct ssh_agent_channel {
620 unsigned char *message;
621 unsigned char msglen[4];
622 unsigned lensofar, totallen;
624 struct ssh_x11_channel {
627 struct ssh_pfd_channel {
634 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
635 * use this structure in different ways, reflecting SSH-2's
636 * altogether saner approach to port forwarding.
638 * In SSH-1, you arrange a remote forwarding by sending the server
639 * the remote port number, and the local destination host:port.
640 * When a connection comes in, the server sends you back that
641 * host:port pair, and you connect to it. This is a ready-made
642 * security hole if you're not on the ball: a malicious server
643 * could send you back _any_ host:port pair, so if you trustingly
644 * connect to the address it gives you then you've just opened the
645 * entire inside of your corporate network just by connecting
646 * through it to a dodgy SSH server. Hence, we must store a list of
647 * host:port pairs we _are_ trying to forward to, and reject a
648 * connection request from the server if it's not in the list.
650 * In SSH-2, each side of the connection minds its own business and
651 * doesn't send unnecessary information to the other. You arrange a
652 * remote forwarding by sending the server just the remote port
653 * number. When a connection comes in, the server tells you which
654 * of its ports was connected to; and _you_ have to remember what
655 * local host:port pair went with that port number.
657 * Hence, in SSH-1 this structure is indexed by destination
658 * host:port pair, whereas in SSH-2 it is indexed by source port.
660 struct ssh_portfwd; /* forward declaration */
662 struct ssh_rportfwd {
663 unsigned sport, dport;
666 struct ssh_portfwd *pfrec;
668 #define free_rportfwd(pf) ( \
669 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
672 * Separately to the rportfwd tree (which is for looking up port
673 * open requests from the server), a tree of _these_ structures is
674 * used to keep track of all the currently open port forwardings,
675 * so that we can reconfigure in mid-session if the user requests
679 enum { DESTROY, KEEP, CREATE } status;
681 unsigned sport, dport;
684 struct ssh_rportfwd *remote;
688 #define free_portfwd(pf) ( \
689 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
690 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
693 long length; /* length of `data' actually used */
694 long forcepad; /* SSH-2: force padding to at least this length */
695 int type; /* only used for incoming packets */
696 unsigned long sequence; /* SSH-2 incoming sequence number */
697 unsigned char *data; /* allocated storage */
698 unsigned char *body; /* offset of payload within `data' */
699 long savedpos; /* temporary index into `data' (for strings) */
700 long maxlen; /* amount of storage allocated for `data' */
701 long encrypted_len; /* for SSH-2 total-size counting */
704 * State associated with packet logging
708 struct logblank_t *blanks;
711 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
712 struct Packet *pktin);
713 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
714 struct Packet *pktin);
715 static void ssh1_protocol_setup(Ssh ssh);
716 static void ssh2_protocol_setup(Ssh ssh);
717 static void ssh_size(void *handle, int width, int height);
718 static void ssh_special(void *handle, Telnet_Special);
719 static int ssh2_try_send(struct ssh_channel *c);
720 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
721 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
722 static void ssh2_set_window(struct ssh_channel *c, int newwin);
723 static int ssh_sendbuffer(void *handle);
724 static int ssh_do_close(Ssh ssh, int notify_exit);
725 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
726 static int ssh2_pkt_getbool(struct Packet *pkt);
727 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
728 static void ssh2_timer(void *ctx, long now);
729 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
730 struct Packet *pktin);
732 struct rdpkt1_state_tag {
733 long len, pad, biglen, to_read;
734 unsigned long realcrc, gotcrc;
738 struct Packet *pktin;
741 struct rdpkt2_state_tag {
742 long len, pad, payload, packetlen, maclen;
745 unsigned long incoming_sequence;
746 struct Packet *pktin;
749 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
750 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
752 struct queued_handler;
753 struct queued_handler {
755 chandler_fn_t handler;
757 struct queued_handler *next;
761 const struct plug_function_table *fn;
762 /* the above field _must_ be first in the structure */
772 unsigned char session_key[32];
774 int v1_remote_protoflags;
775 int v1_local_protoflags;
776 int agentfwd_enabled;
779 const struct ssh_cipher *cipher;
782 const struct ssh2_cipher *cscipher, *sccipher;
783 void *cs_cipher_ctx, *sc_cipher_ctx;
784 const struct ssh_mac *csmac, *scmac;
785 void *cs_mac_ctx, *sc_mac_ctx;
786 const struct ssh_compress *cscomp, *sccomp;
787 void *cs_comp_ctx, *sc_comp_ctx;
788 const struct ssh_kex *kex;
789 const struct ssh_signkey *hostkey;
790 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
791 int v2_session_id_len;
797 int echoing, editing;
801 int ospeed, ispeed; /* temporaries */
802 int term_width, term_height;
804 tree234 *channels; /* indexed by local id */
805 struct ssh_channel *mainchan; /* primary session channel */
806 int ncmode; /* is primary channel direct-tcpip? */
811 tree234 *rportfwds, *portfwds;
815 SSH_STATE_BEFORE_SIZE,
821 int size_needed, eof_needed;
823 struct Packet **queue;
824 int queuelen, queuesize;
826 unsigned char *deferred_send_data;
827 int deferred_len, deferred_size;
830 * Gross hack: pscp will try to start SFTP but fall back to
831 * scp1 if that fails. This variable is the means by which
832 * scp.c can reach into the SSH code and find out which one it
837 bufchain banner; /* accumulates banners during do_ssh2_authconn */
842 struct X11Display *x11disp;
845 int conn_throttle_count;
848 int v1_stdout_throttling;
849 unsigned long v2_outgoing_sequence;
851 int ssh1_rdpkt_crstate;
852 int ssh2_rdpkt_crstate;
853 int do_ssh_init_crstate;
854 int ssh_gotdata_crstate;
855 int do_ssh1_login_crstate;
856 int do_ssh1_connection_crstate;
857 int do_ssh2_transport_crstate;
858 int do_ssh2_authconn_crstate;
860 void *do_ssh_init_state;
861 void *do_ssh1_login_state;
862 void *do_ssh2_transport_state;
863 void *do_ssh2_authconn_state;
865 struct rdpkt1_state_tag rdpkt1_state;
866 struct rdpkt2_state_tag rdpkt2_state;
868 /* SSH-1 and SSH-2 use this for different things, but both use it */
869 int protocol_initial_phase_done;
871 void (*protocol) (Ssh ssh, void *vin, int inlen,
873 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
876 * We maintain a full _copy_ of a Config structure here, not
877 * merely a pointer to it. That way, when we're passed a new
878 * one for reconfiguration, we can check the differences and
879 * potentially reconfigure port forwardings etc in mid-session.
884 * Used to transfer data back from async callbacks.
886 void *agent_response;
887 int agent_response_len;
891 * The SSH connection can be set as `frozen', meaning we are
892 * not currently accepting incoming data from the network. This
893 * is slightly more serious than setting the _socket_ as
894 * frozen, because we may already have had data passed to us
895 * from the network which we need to delay processing until
896 * after the freeze is lifted, so we also need a bufchain to
900 bufchain queued_incoming_data;
903 * Dispatch table for packet types that we may have to deal
906 handler_fn_t packet_dispatch[256];
909 * Queues of one-off handler functions for success/failure
910 * indications from a request.
912 struct queued_handler *qhead, *qtail;
915 * This module deals with sending keepalives.
920 * Track incoming and outgoing data sizes and time, for
923 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
924 unsigned long max_data_size;
926 long next_rekey, last_rekey;
927 char *deferred_rekey_reason; /* points to STATIC string; don't free */
930 * Fully qualified host name, which we need if doing GSSAPI.
935 #define logevent(s) logevent(ssh->frontend, s)
937 /* logevent, only printf-formatted. */
938 static void logeventf(Ssh ssh, const char *fmt, ...)
944 buf = dupvprintf(fmt, ap);
950 #define bombout(msg) \
952 char *text = dupprintf msg; \
953 ssh_do_close(ssh, FALSE); \
955 connection_fatal(ssh->frontend, "%s", text); \
959 /* Functions to leave bits out of the SSH packet log file. */
961 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
963 if (ssh->cfg.logomitpass)
964 pkt->logmode = blanktype;
967 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
969 if (ssh->cfg.logomitdata)
970 pkt->logmode = blanktype;
973 static void end_log_omission(Ssh ssh, struct Packet *pkt)
975 pkt->logmode = PKTLOG_EMIT;
978 /* Helper function for common bits of parsing cfg.ttymodes. */
979 static void parse_ttymodes(Ssh ssh, char *modes,
980 void (*do_mode)(void *data, char *mode, char *val),
984 char *t = strchr(modes, '\t');
985 char *m = snewn(t-modes+1, char);
987 strncpy(m, modes, t-modes);
990 val = get_ttymode(ssh->frontend, m);
994 do_mode(data, m, val);
997 modes += strlen(modes) + 1;
1001 static int ssh_channelcmp(void *av, void *bv)
1003 struct ssh_channel *a = (struct ssh_channel *) av;
1004 struct ssh_channel *b = (struct ssh_channel *) bv;
1005 if (a->localid < b->localid)
1007 if (a->localid > b->localid)
1011 static int ssh_channelfind(void *av, void *bv)
1013 unsigned *a = (unsigned *) av;
1014 struct ssh_channel *b = (struct ssh_channel *) bv;
1015 if (*a < b->localid)
1017 if (*a > b->localid)
1022 static int ssh_rportcmp_ssh1(void *av, void *bv)
1024 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1025 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1027 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1028 return i < 0 ? -1 : +1;
1029 if (a->dport > b->dport)
1031 if (a->dport < b->dport)
1036 static int ssh_rportcmp_ssh2(void *av, void *bv)
1038 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1039 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1041 if (a->sport > b->sport)
1043 if (a->sport < b->sport)
1049 * Special form of strcmp which can cope with NULL inputs. NULL is
1050 * defined to sort before even the empty string.
1052 static int nullstrcmp(const char *a, const char *b)
1054 if (a == NULL && b == NULL)
1060 return strcmp(a, b);
1063 static int ssh_portcmp(void *av, void *bv)
1065 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1066 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1068 if (a->type > b->type)
1070 if (a->type < b->type)
1072 if (a->addressfamily > b->addressfamily)
1074 if (a->addressfamily < b->addressfamily)
1076 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1077 return i < 0 ? -1 : +1;
1078 if (a->sport > b->sport)
1080 if (a->sport < b->sport)
1082 if (a->type != 'D') {
1083 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1084 return i < 0 ? -1 : +1;
1085 if (a->dport > b->dport)
1087 if (a->dport < b->dport)
1093 static int alloc_channel_id(Ssh ssh)
1095 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1096 unsigned low, high, mid;
1098 struct ssh_channel *c;
1101 * First-fit allocation of channel numbers: always pick the
1102 * lowest unused one. To do this, binary-search using the
1103 * counted B-tree to find the largest channel ID which is in a
1104 * contiguous sequence from the beginning. (Precisely
1105 * everything in that sequence must have ID equal to its tree
1106 * index plus CHANNEL_NUMBER_OFFSET.)
1108 tsize = count234(ssh->channels);
1112 while (high - low > 1) {
1113 mid = (high + low) / 2;
1114 c = index234(ssh->channels, mid);
1115 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1116 low = mid; /* this one is fine */
1118 high = mid; /* this one is past it */
1121 * Now low points to either -1, or the tree index of the
1122 * largest ID in the initial sequence.
1125 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1126 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1128 return low + 1 + CHANNEL_NUMBER_OFFSET;
1131 static void c_write_stderr(int trusted, const char *buf, int len)
1134 for (i = 0; i < len; i++)
1135 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1136 fputc(buf[i], stderr);
1139 static void c_write(Ssh ssh, const char *buf, int len)
1141 if (flags & FLAG_STDERR)
1142 c_write_stderr(1, buf, len);
1144 from_backend(ssh->frontend, 1, buf, len);
1147 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1149 if (flags & FLAG_STDERR)
1150 c_write_stderr(0, buf, len);
1152 from_backend_untrusted(ssh->frontend, buf, len);
1155 static void c_write_str(Ssh ssh, const char *buf)
1157 c_write(ssh, buf, strlen(buf));
1160 static void ssh_free_packet(struct Packet *pkt)
1165 static struct Packet *ssh_new_packet(void)
1167 struct Packet *pkt = snew(struct Packet);
1169 pkt->body = pkt->data = NULL;
1171 pkt->logmode = PKTLOG_EMIT;
1179 * Collect incoming data in the incoming packet buffer.
1180 * Decipher and verify the packet when it is completely read.
1181 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1182 * Update the *data and *datalen variables.
1183 * Return a Packet structure when a packet is completed.
1185 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1187 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1189 crBegin(ssh->ssh1_rdpkt_crstate);
1191 st->pktin = ssh_new_packet();
1193 st->pktin->type = 0;
1194 st->pktin->length = 0;
1196 for (st->i = st->len = 0; st->i < 4; st->i++) {
1197 while ((*datalen) == 0)
1199 st->len = (st->len << 8) + **data;
1200 (*data)++, (*datalen)--;
1203 st->pad = 8 - (st->len % 8);
1204 st->biglen = st->len + st->pad;
1205 st->pktin->length = st->len - 5;
1207 if (st->biglen < 0) {
1208 bombout(("Extremely large packet length from server suggests"
1209 " data stream corruption"));
1210 ssh_free_packet(st->pktin);
1214 st->pktin->maxlen = st->biglen;
1215 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1217 st->to_read = st->biglen;
1218 st->p = st->pktin->data;
1219 while (st->to_read > 0) {
1220 st->chunk = st->to_read;
1221 while ((*datalen) == 0)
1223 if (st->chunk > (*datalen))
1224 st->chunk = (*datalen);
1225 memcpy(st->p, *data, st->chunk);
1227 *datalen -= st->chunk;
1229 st->to_read -= st->chunk;
1232 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1233 st->biglen, NULL)) {
1234 bombout(("Network attack (CRC compensation) detected!"));
1235 ssh_free_packet(st->pktin);
1240 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1242 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1243 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1244 if (st->gotcrc != st->realcrc) {
1245 bombout(("Incorrect CRC received on packet"));
1246 ssh_free_packet(st->pktin);
1250 st->pktin->body = st->pktin->data + st->pad + 1;
1251 st->pktin->savedpos = 0;
1253 if (ssh->v1_compressing) {
1254 unsigned char *decompblk;
1256 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1257 st->pktin->body - 1, st->pktin->length + 1,
1258 &decompblk, &decomplen)) {
1259 bombout(("Zlib decompression encountered invalid data"));
1260 ssh_free_packet(st->pktin);
1264 if (st->pktin->maxlen < st->pad + decomplen) {
1265 st->pktin->maxlen = st->pad + decomplen;
1266 st->pktin->data = sresize(st->pktin->data,
1267 st->pktin->maxlen + APIEXTRA,
1269 st->pktin->body = st->pktin->data + st->pad + 1;
1272 memcpy(st->pktin->body - 1, decompblk, decomplen);
1274 st->pktin->length = decomplen - 1;
1277 st->pktin->type = st->pktin->body[-1];
1280 * Log incoming packet, possibly omitting sensitive fields.
1284 struct logblank_t blank;
1285 if (ssh->cfg.logomitdata) {
1286 int do_blank = FALSE, blank_prefix = 0;
1287 /* "Session data" packets - omit the data field */
1288 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1289 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1290 do_blank = TRUE; blank_prefix = 4;
1291 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1292 do_blank = TRUE; blank_prefix = 8;
1295 blank.offset = blank_prefix;
1296 blank.len = st->pktin->length;
1297 blank.type = PKTLOG_OMIT;
1301 log_packet(ssh->logctx,
1302 PKT_INCOMING, st->pktin->type,
1303 ssh1_pkt_type(st->pktin->type),
1304 st->pktin->body, st->pktin->length,
1305 nblanks, &blank, NULL);
1308 crFinish(st->pktin);
1311 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1313 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1315 crBegin(ssh->ssh2_rdpkt_crstate);
1317 st->pktin = ssh_new_packet();
1319 st->pktin->type = 0;
1320 st->pktin->length = 0;
1322 st->cipherblk = ssh->sccipher->blksize;
1325 if (st->cipherblk < 8)
1327 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1329 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1332 * When dealing with a CBC-mode cipher, we want to avoid the
1333 * possibility of an attacker's tweaking the ciphertext stream
1334 * so as to cause us to feed the same block to the block
1335 * cipher more than once and thus leak information
1336 * (VU#958563). The way we do this is not to take any
1337 * decisions on the basis of anything we've decrypted until
1338 * we've verified it with a MAC. That includes the packet
1339 * length, so we just read data and check the MAC repeatedly,
1340 * and when the MAC passes, see if the length we've got is
1344 /* May as well allocate the whole lot now. */
1345 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1348 /* Read an amount corresponding to the MAC. */
1349 for (st->i = 0; st->i < st->maclen; st->i++) {
1350 while ((*datalen) == 0)
1352 st->pktin->data[st->i] = *(*data)++;
1358 unsigned char seq[4];
1359 ssh->scmac->start(ssh->sc_mac_ctx);
1360 PUT_32BIT(seq, st->incoming_sequence);
1361 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1364 for (;;) { /* Once around this loop per cipher block. */
1365 /* Read another cipher-block's worth, and tack it onto the end. */
1366 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1367 while ((*datalen) == 0)
1369 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1372 /* Decrypt one more block (a little further back in the stream). */
1373 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1374 st->pktin->data + st->packetlen,
1376 /* Feed that block to the MAC. */
1377 ssh->scmac->bytes(ssh->sc_mac_ctx,
1378 st->pktin->data + st->packetlen, st->cipherblk);
1379 st->packetlen += st->cipherblk;
1380 /* See if that gives us a valid packet. */
1381 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1382 st->pktin->data + st->packetlen) &&
1383 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1385 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1386 bombout(("No valid incoming packet found"));
1387 ssh_free_packet(st->pktin);
1391 st->pktin->maxlen = st->packetlen + st->maclen;
1392 st->pktin->data = sresize(st->pktin->data,
1393 st->pktin->maxlen + APIEXTRA,
1396 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1399 * Acquire and decrypt the first block of the packet. This will
1400 * contain the length and padding details.
1402 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1403 while ((*datalen) == 0)
1405 st->pktin->data[st->i] = *(*data)++;
1410 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1411 st->pktin->data, st->cipherblk);
1414 * Now get the length figure.
1416 st->len = GET_32BIT(st->pktin->data);
1419 * _Completely_ silly lengths should be stomped on before they
1420 * do us any more damage.
1422 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1423 (st->len + 4) % st->cipherblk != 0) {
1424 bombout(("Incoming packet was garbled on decryption"));
1425 ssh_free_packet(st->pktin);
1430 * So now we can work out the total packet length.
1432 st->packetlen = st->len + 4;
1435 * Allocate memory for the rest of the packet.
1437 st->pktin->maxlen = st->packetlen + st->maclen;
1438 st->pktin->data = sresize(st->pktin->data,
1439 st->pktin->maxlen + APIEXTRA,
1443 * Read and decrypt the remainder of the packet.
1445 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1447 while ((*datalen) == 0)
1449 st->pktin->data[st->i] = *(*data)++;
1452 /* Decrypt everything _except_ the MAC. */
1454 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1455 st->pktin->data + st->cipherblk,
1456 st->packetlen - st->cipherblk);
1462 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1463 st->len + 4, st->incoming_sequence)) {
1464 bombout(("Incorrect MAC received on packet"));
1465 ssh_free_packet(st->pktin);
1469 /* Get and sanity-check the amount of random padding. */
1470 st->pad = st->pktin->data[4];
1471 if (st->pad < 4 || st->len - st->pad < 1) {
1472 bombout(("Invalid padding length on received packet"));
1473 ssh_free_packet(st->pktin);
1477 * This enables us to deduce the payload length.
1479 st->payload = st->len - st->pad - 1;
1481 st->pktin->length = st->payload + 5;
1482 st->pktin->encrypted_len = st->packetlen;
1484 st->pktin->sequence = st->incoming_sequence++;
1487 * Decompress packet payload.
1490 unsigned char *newpayload;
1493 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1494 st->pktin->data + 5, st->pktin->length - 5,
1495 &newpayload, &newlen)) {
1496 if (st->pktin->maxlen < newlen + 5) {
1497 st->pktin->maxlen = newlen + 5;
1498 st->pktin->data = sresize(st->pktin->data,
1499 st->pktin->maxlen + APIEXTRA,
1502 st->pktin->length = 5 + newlen;
1503 memcpy(st->pktin->data + 5, newpayload, newlen);
1508 st->pktin->savedpos = 6;
1509 st->pktin->body = st->pktin->data;
1510 st->pktin->type = st->pktin->data[5];
1513 * Log incoming packet, possibly omitting sensitive fields.
1517 struct logblank_t blank;
1518 if (ssh->cfg.logomitdata) {
1519 int do_blank = FALSE, blank_prefix = 0;
1520 /* "Session data" packets - omit the data field */
1521 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1522 do_blank = TRUE; blank_prefix = 8;
1523 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1524 do_blank = TRUE; blank_prefix = 12;
1527 blank.offset = blank_prefix;
1528 blank.len = (st->pktin->length-6) - blank_prefix;
1529 blank.type = PKTLOG_OMIT;
1533 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1534 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1536 st->pktin->data+6, st->pktin->length-6,
1537 nblanks, &blank, &st->pktin->sequence);
1540 crFinish(st->pktin);
1543 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1545 int pad, biglen, i, pktoffs;
1549 * XXX various versions of SC (including 8.8.4) screw up the
1550 * register allocation in this function and use the same register
1551 * (D6) for len and as a temporary, with predictable results. The
1552 * following sledgehammer prevents this.
1559 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1560 ssh1_pkt_type(pkt->data[12]),
1561 pkt->body, pkt->length - (pkt->body - pkt->data),
1562 pkt->nblanks, pkt->blanks, NULL);
1563 sfree(pkt->blanks); pkt->blanks = NULL;
1566 if (ssh->v1_compressing) {
1567 unsigned char *compblk;
1569 zlib_compress_block(ssh->cs_comp_ctx,
1570 pkt->data + 12, pkt->length - 12,
1571 &compblk, &complen);
1572 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1573 memcpy(pkt->data + 12, compblk, complen);
1575 pkt->length = complen + 12;
1578 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1580 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1581 pad = 8 - (len % 8);
1583 biglen = len + pad; /* len(padding+type+data+CRC) */
1585 for (i = pktoffs; i < 4+8; i++)
1586 pkt->data[i] = random_byte();
1587 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1588 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1589 PUT_32BIT(pkt->data + pktoffs, len);
1592 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1593 pkt->data + pktoffs + 4, biglen);
1595 if (offset_p) *offset_p = pktoffs;
1596 return biglen + 4; /* len(length+padding+type+data+CRC) */
1599 static int s_write(Ssh ssh, void *data, int len)
1602 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1604 return sk_write(ssh->s, (char *)data, len);
1607 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1609 int len, backlog, offset;
1610 len = s_wrpkt_prepare(ssh, pkt, &offset);
1611 backlog = s_write(ssh, pkt->data + offset, len);
1612 if (backlog > SSH_MAX_BACKLOG)
1613 ssh_throttle_all(ssh, 1, backlog);
1614 ssh_free_packet(pkt);
1617 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1620 len = s_wrpkt_prepare(ssh, pkt, &offset);
1621 if (ssh->deferred_len + len > ssh->deferred_size) {
1622 ssh->deferred_size = ssh->deferred_len + len + 128;
1623 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1627 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1628 pkt->data + offset, len);
1629 ssh->deferred_len += len;
1630 ssh_free_packet(pkt);
1634 * Construct a SSH-1 packet with the specified contents.
1635 * (This all-at-once interface used to be the only one, but now SSH-1
1636 * packets can also be constructed incrementally.)
1638 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1644 pkt = ssh1_pkt_init(pkttype);
1646 while ((argtype = va_arg(ap, int)) != PKT_END) {
1647 unsigned char *argp, argchar;
1649 unsigned long argint;
1652 /* Actual fields in the packet */
1654 argint = va_arg(ap, int);
1655 ssh_pkt_adduint32(pkt, argint);
1658 argchar = (unsigned char) va_arg(ap, int);
1659 ssh_pkt_addbyte(pkt, argchar);
1662 argp = va_arg(ap, unsigned char *);
1663 arglen = va_arg(ap, int);
1664 ssh_pkt_adddata(pkt, argp, arglen);
1667 sargp = va_arg(ap, char *);
1668 ssh_pkt_addstring(pkt, sargp);
1671 bn = va_arg(ap, Bignum);
1672 ssh1_pkt_addmp(pkt, bn);
1674 /* Tokens for modifications to packet logging */
1676 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1679 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1682 end_log_omission(ssh, pkt);
1690 static void send_packet(Ssh ssh, int pkttype, ...)
1694 va_start(ap, pkttype);
1695 pkt = construct_packet(ssh, pkttype, ap);
1700 static void defer_packet(Ssh ssh, int pkttype, ...)
1704 va_start(ap, pkttype);
1705 pkt = construct_packet(ssh, pkttype, ap);
1707 s_wrpkt_defer(ssh, pkt);
1710 static int ssh_versioncmp(char *a, char *b)
1713 unsigned long av, bv;
1715 av = strtoul(a, &ae, 10);
1716 bv = strtoul(b, &be, 10);
1718 return (av < bv ? -1 : +1);
1723 av = strtoul(ae, &ae, 10);
1724 bv = strtoul(be, &be, 10);
1726 return (av < bv ? -1 : +1);
1731 * Utility routines for putting an SSH-protocol `string' and
1732 * `uint32' into a hash state.
1734 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1736 unsigned char lenblk[4];
1737 PUT_32BIT(lenblk, len);
1738 h->bytes(s, lenblk, 4);
1739 h->bytes(s, str, len);
1742 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1744 unsigned char intblk[4];
1745 PUT_32BIT(intblk, i);
1746 h->bytes(s, intblk, 4);
1750 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1752 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1754 if (pkt->maxlen < length) {
1755 unsigned char *body = pkt->body;
1756 int offset = body ? body - pkt->data : 0;
1757 pkt->maxlen = length + 256;
1758 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1759 if (body) pkt->body = pkt->data + offset;
1762 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1764 if (pkt->logmode != PKTLOG_EMIT) {
1766 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1768 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1769 (pkt->body - pkt->data);
1770 pkt->blanks[pkt->nblanks-1].len = len;
1771 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1774 ssh_pkt_ensure(pkt, pkt->length);
1775 memcpy(pkt->data + pkt->length - len, data, len);
1777 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1779 ssh_pkt_adddata(pkt, &byte, 1);
1781 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1783 ssh_pkt_adddata(pkt, &value, 1);
1785 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1788 PUT_32BIT(x, value);
1789 ssh_pkt_adddata(pkt, x, 4);
1791 static void ssh_pkt_addstring_start(struct Packet *pkt)
1793 ssh_pkt_adduint32(pkt, 0);
1794 pkt->savedpos = pkt->length;
1796 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1798 ssh_pkt_adddata(pkt, data, strlen(data));
1799 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1801 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1803 ssh_pkt_adddata(pkt, data, len);
1804 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1806 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1808 ssh_pkt_addstring_start(pkt);
1809 ssh_pkt_addstring_str(pkt, data);
1811 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1813 int len = ssh1_bignum_length(b);
1814 unsigned char *data = snewn(len, unsigned char);
1815 (void) ssh1_write_bignum(data, b);
1816 ssh_pkt_adddata(pkt, data, len);
1819 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1822 int i, n = (bignum_bitcount(b) + 7) / 8;
1823 p = snewn(n + 1, unsigned char);
1825 for (i = 1; i <= n; i++)
1826 p[i] = bignum_byte(b, n - i);
1828 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1830 memmove(p, p + i, n + 1 - i);
1834 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1838 p = ssh2_mpint_fmt(b, &len);
1839 ssh_pkt_addstring_start(pkt);
1840 ssh_pkt_addstring_data(pkt, (char *)p, len);
1844 static struct Packet *ssh1_pkt_init(int pkt_type)
1846 struct Packet *pkt = ssh_new_packet();
1847 pkt->length = 4 + 8; /* space for length + max padding */
1848 ssh_pkt_addbyte(pkt, pkt_type);
1849 pkt->body = pkt->data + pkt->length;
1853 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1854 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1855 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1856 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1857 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1858 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1859 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1860 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1861 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1863 static struct Packet *ssh2_pkt_init(int pkt_type)
1865 struct Packet *pkt = ssh_new_packet();
1866 pkt->length = 5; /* space for packet length + padding length */
1868 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1869 pkt->body = pkt->data + pkt->length; /* after packet type */
1874 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1875 * put the MAC on it. Final packet, ready to be sent, is stored in
1876 * pkt->data. Total length is returned.
1878 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1880 int cipherblk, maclen, padding, i;
1883 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1884 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1885 pkt->body, pkt->length - (pkt->body - pkt->data),
1886 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1887 sfree(pkt->blanks); pkt->blanks = NULL;
1891 * Compress packet payload.
1894 unsigned char *newpayload;
1897 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1899 &newpayload, &newlen)) {
1901 ssh2_pkt_adddata(pkt, newpayload, newlen);
1907 * Add padding. At least four bytes, and must also bring total
1908 * length (minus MAC) up to a multiple of the block size.
1909 * If pkt->forcepad is set, make sure the packet is at least that size
1912 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1913 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1915 if (pkt->length + padding < pkt->forcepad)
1916 padding = pkt->forcepad - pkt->length;
1918 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1919 assert(padding <= 255);
1920 maclen = ssh->csmac ? ssh->csmac->len : 0;
1921 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1922 pkt->data[4] = padding;
1923 for (i = 0; i < padding; i++)
1924 pkt->data[pkt->length + i] = random_byte();
1925 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1927 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1928 pkt->length + padding,
1929 ssh->v2_outgoing_sequence);
1930 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1933 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1934 pkt->data, pkt->length + padding);
1936 pkt->encrypted_len = pkt->length + padding;
1938 /* Ready-to-send packet starts at pkt->data. We return length. */
1939 return pkt->length + padding + maclen;
1943 * Routines called from the main SSH code to send packets. There
1944 * are quite a few of these, because we have two separate
1945 * mechanisms for delaying the sending of packets:
1947 * - In order to send an IGNORE message and a password message in
1948 * a single fixed-length blob, we require the ability to
1949 * concatenate the encrypted forms of those two packets _into_ a
1950 * single blob and then pass it to our <network.h> transport
1951 * layer in one go. Hence, there's a deferment mechanism which
1952 * works after packet encryption.
1954 * - In order to avoid sending any connection-layer messages
1955 * during repeat key exchange, we have to queue up any such
1956 * outgoing messages _before_ they are encrypted (and in
1957 * particular before they're allocated sequence numbers), and
1958 * then send them once we've finished.
1960 * I call these mechanisms `defer' and `queue' respectively, so as
1961 * to distinguish them reasonably easily.
1963 * The functions send_noqueue() and defer_noqueue() free the packet
1964 * structure they are passed. Every outgoing packet goes through
1965 * precisely one of these functions in its life; packets passed to
1966 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1967 * these or get queued, and then when the queue is later emptied
1968 * the packets are all passed to defer_noqueue().
1970 * When using a CBC-mode cipher, it's necessary to ensure that an
1971 * attacker can't provide data to be encrypted using an IV that they
1972 * know. We ensure this by prefixing each packet that might contain
1973 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1974 * mechanism, so in this case send_noqueue() ends up redirecting to
1975 * defer_noqueue(). If you don't like this inefficiency, don't use
1979 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1980 static void ssh_pkt_defersend(Ssh);
1983 * Send an SSH-2 packet immediately, without queuing or deferring.
1985 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1989 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1990 /* We need to send two packets, so use the deferral mechanism. */
1991 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1992 ssh_pkt_defersend(ssh);
1995 len = ssh2_pkt_construct(ssh, pkt);
1996 backlog = s_write(ssh, pkt->data, len);
1997 if (backlog > SSH_MAX_BACKLOG)
1998 ssh_throttle_all(ssh, 1, backlog);
2000 ssh->outgoing_data_size += pkt->encrypted_len;
2001 if (!ssh->kex_in_progress &&
2002 ssh->max_data_size != 0 &&
2003 ssh->outgoing_data_size > ssh->max_data_size)
2004 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2006 ssh_free_packet(pkt);
2010 * Defer an SSH-2 packet.
2012 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2015 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2016 ssh->deferred_len == 0 && !noignore &&
2017 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2019 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2020 * get encrypted with a known IV.
2022 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2023 ssh2_pkt_addstring_start(ipkt);
2024 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2026 len = ssh2_pkt_construct(ssh, pkt);
2027 if (ssh->deferred_len + len > ssh->deferred_size) {
2028 ssh->deferred_size = ssh->deferred_len + len + 128;
2029 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2033 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2034 ssh->deferred_len += len;
2035 ssh->deferred_data_size += pkt->encrypted_len;
2036 ssh_free_packet(pkt);
2040 * Queue an SSH-2 packet.
2042 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2044 assert(ssh->queueing);
2046 if (ssh->queuelen >= ssh->queuesize) {
2047 ssh->queuesize = ssh->queuelen + 32;
2048 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2051 ssh->queue[ssh->queuelen++] = pkt;
2055 * Either queue or send a packet, depending on whether queueing is
2058 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2061 ssh2_pkt_queue(ssh, pkt);
2063 ssh2_pkt_send_noqueue(ssh, pkt);
2067 * Either queue or defer a packet, depending on whether queueing is
2070 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2073 ssh2_pkt_queue(ssh, pkt);
2075 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2079 * Send the whole deferred data block constructed by
2080 * ssh2_pkt_defer() or SSH-1's defer_packet().
2082 * The expected use of the defer mechanism is that you call
2083 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2084 * not currently queueing, this simply sets up deferred_send_data
2085 * and then sends it. If we _are_ currently queueing, the calls to
2086 * ssh2_pkt_defer() put the deferred packets on to the queue
2087 * instead, and therefore ssh_pkt_defersend() has no deferred data
2088 * to send. Hence, there's no need to make it conditional on
2091 static void ssh_pkt_defersend(Ssh ssh)
2094 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2095 ssh->deferred_len = ssh->deferred_size = 0;
2096 sfree(ssh->deferred_send_data);
2097 ssh->deferred_send_data = NULL;
2098 if (backlog > SSH_MAX_BACKLOG)
2099 ssh_throttle_all(ssh, 1, backlog);
2101 ssh->outgoing_data_size += ssh->deferred_data_size;
2102 if (!ssh->kex_in_progress &&
2103 ssh->max_data_size != 0 &&
2104 ssh->outgoing_data_size > ssh->max_data_size)
2105 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2106 ssh->deferred_data_size = 0;
2110 * Send a packet whose length needs to be disguised (typically
2111 * passwords or keyboard-interactive responses).
2113 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2119 * The simplest way to do this is to adjust the
2120 * variable-length padding field in the outgoing packet.
2122 * Currently compiled out, because some Cisco SSH servers
2123 * don't like excessively padded packets (bah, why's it
2126 pkt->forcepad = padsize;
2127 ssh2_pkt_send(ssh, pkt);
2132 * If we can't do that, however, an alternative approach is
2133 * to use the pkt_defer mechanism to bundle the packet
2134 * tightly together with an SSH_MSG_IGNORE such that their
2135 * combined length is a constant. So first we construct the
2136 * final form of this packet and defer its sending.
2138 ssh2_pkt_defer(ssh, pkt);
2141 * Now construct an SSH_MSG_IGNORE which includes a string
2142 * that's an exact multiple of the cipher block size. (If
2143 * the cipher is NULL so that the block size is
2144 * unavailable, we don't do this trick at all, because we
2145 * gain nothing by it.)
2147 if (ssh->cscipher &&
2148 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2151 stringlen = (256 - ssh->deferred_len);
2152 stringlen += ssh->cscipher->blksize - 1;
2153 stringlen -= (stringlen % ssh->cscipher->blksize);
2156 * Temporarily disable actual compression, so we
2157 * can guarantee to get this string exactly the
2158 * length we want it. The compression-disabling
2159 * routine should return an integer indicating how
2160 * many bytes we should adjust our string length
2164 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2166 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2167 ssh2_pkt_addstring_start(pkt);
2168 for (i = 0; i < stringlen; i++) {
2169 char c = (char) random_byte();
2170 ssh2_pkt_addstring_data(pkt, &c, 1);
2172 ssh2_pkt_defer(ssh, pkt);
2174 ssh_pkt_defersend(ssh);
2179 * Send all queued SSH-2 packets. We send them by means of
2180 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2181 * packets that needed to be lumped together.
2183 static void ssh2_pkt_queuesend(Ssh ssh)
2187 assert(!ssh->queueing);
2189 for (i = 0; i < ssh->queuelen; i++)
2190 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2193 ssh_pkt_defersend(ssh);
2197 void bndebug(char *string, Bignum b)
2201 p = ssh2_mpint_fmt(b, &len);
2202 debug(("%s", string));
2203 for (i = 0; i < len; i++)
2204 debug((" %02x", p[i]));
2210 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2214 p = ssh2_mpint_fmt(b, &len);
2215 hash_string(h, s, p, len);
2220 * Packet decode functions for both SSH-1 and SSH-2.
2222 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2224 unsigned long value;
2225 if (pkt->length - pkt->savedpos < 4)
2226 return 0; /* arrgh, no way to decline (FIXME?) */
2227 value = GET_32BIT(pkt->body + pkt->savedpos);
2231 static int ssh2_pkt_getbool(struct Packet *pkt)
2233 unsigned long value;
2234 if (pkt->length - pkt->savedpos < 1)
2235 return 0; /* arrgh, no way to decline (FIXME?) */
2236 value = pkt->body[pkt->savedpos] != 0;
2240 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2245 if (pkt->length - pkt->savedpos < 4)
2247 len = GET_32BIT(pkt->body + pkt->savedpos);
2252 if (pkt->length - pkt->savedpos < *length)
2254 *p = (char *)(pkt->body + pkt->savedpos);
2255 pkt->savedpos += *length;
2257 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2259 if (pkt->length - pkt->savedpos < length)
2261 pkt->savedpos += length;
2262 return pkt->body + (pkt->savedpos - length);
2264 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2265 unsigned char **keystr)
2269 j = makekey(pkt->body + pkt->savedpos,
2270 pkt->length - pkt->savedpos,
2277 assert(pkt->savedpos < pkt->length);
2281 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2286 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2287 pkt->length - pkt->savedpos, &b);
2295 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2301 ssh_pkt_getstring(pkt, &p, &length);
2306 b = bignum_from_bytes((unsigned char *)p, length);
2311 * Helper function to add an SSH-2 signature blob to a packet.
2312 * Expects to be shown the public key blob as well as the signature
2313 * blob. Normally works just like ssh2_pkt_addstring, but will
2314 * fiddle with the signature packet if necessary for
2315 * BUG_SSH2_RSA_PADDING.
2317 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2318 void *pkblob_v, int pkblob_len,
2319 void *sigblob_v, int sigblob_len)
2321 unsigned char *pkblob = (unsigned char *)pkblob_v;
2322 unsigned char *sigblob = (unsigned char *)sigblob_v;
2324 /* dmemdump(pkblob, pkblob_len); */
2325 /* dmemdump(sigblob, sigblob_len); */
2328 * See if this is in fact an ssh-rsa signature and a buggy
2329 * server; otherwise we can just do this the easy way.
2331 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2332 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2333 int pos, len, siglen;
2336 * Find the byte length of the modulus.
2339 pos = 4+7; /* skip over "ssh-rsa" */
2340 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2341 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2342 pos += 4; /* find modulus itself */
2343 while (len > 0 && pkblob[pos] == 0)
2345 /* debug(("modulus length is %d\n", len)); */
2348 * Now find the signature integer.
2350 pos = 4+7; /* skip over "ssh-rsa" */
2351 siglen = GET_32BIT(sigblob+pos);
2352 /* debug(("signature length is %d\n", siglen)); */
2354 if (len != siglen) {
2355 unsigned char newlen[4];
2356 ssh2_pkt_addstring_start(pkt);
2357 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2358 /* dmemdump(sigblob, pos); */
2359 pos += 4; /* point to start of actual sig */
2360 PUT_32BIT(newlen, len);
2361 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2362 /* dmemdump(newlen, 4); */
2364 while (len-- > siglen) {
2365 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2366 /* dmemdump(newlen, 1); */
2368 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2369 /* dmemdump(sigblob+pos, siglen); */
2373 /* Otherwise fall through and do it the easy way. */
2376 ssh2_pkt_addstring_start(pkt);
2377 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2381 * Examine the remote side's version string and compare it against
2382 * a list of known buggy implementations.
2384 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2386 char *imp; /* pointer to implementation part */
2388 imp += strcspn(imp, "-");
2390 imp += strcspn(imp, "-");
2393 ssh->remote_bugs = 0;
2396 * General notes on server version strings:
2397 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2398 * here -- in particular, we've heard of one that's perfectly happy
2399 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2400 * so we can't distinguish them.
2402 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2403 (ssh->cfg.sshbug_ignore1 == AUTO &&
2404 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2405 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2406 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2407 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2409 * These versions don't support SSH1_MSG_IGNORE, so we have
2410 * to use a different defence against password length
2413 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2414 logevent("We believe remote version has SSH-1 ignore bug");
2417 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2418 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2419 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2421 * These versions need a plain password sent; they can't
2422 * handle having a null and a random length of data after
2425 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2426 logevent("We believe remote version needs a plain SSH-1 password");
2429 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2430 (ssh->cfg.sshbug_rsa1 == AUTO &&
2431 (!strcmp(imp, "Cisco-1.25")))) {
2433 * These versions apparently have no clue whatever about
2434 * RSA authentication and will panic and die if they see
2435 * an AUTH_RSA message.
2437 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2438 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2441 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2442 (ssh->cfg.sshbug_hmac2 == AUTO &&
2443 !wc_match("* VShell", imp) &&
2444 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2445 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2446 wc_match("2.1 *", imp)))) {
2448 * These versions have the HMAC bug.
2450 ssh->remote_bugs |= BUG_SSH2_HMAC;
2451 logevent("We believe remote version has SSH-2 HMAC bug");
2454 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2455 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2456 !wc_match("* VShell", imp) &&
2457 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2459 * These versions have the key-derivation bug (failing to
2460 * include the literal shared secret in the hashes that
2461 * generate the keys).
2463 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2464 logevent("We believe remote version has SSH-2 key-derivation bug");
2467 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2468 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2469 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2470 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2472 * These versions have the SSH-2 RSA padding bug.
2474 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2475 logevent("We believe remote version has SSH-2 RSA padding bug");
2478 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2479 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2480 wc_match("OpenSSH_2.[0-2]*", imp))) {
2482 * These versions have the SSH-2 session-ID bug in
2483 * public-key authentication.
2485 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2486 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2489 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2490 (ssh->cfg.sshbug_rekey2 == AUTO &&
2491 (wc_match("DigiSSH_2.0", imp) ||
2492 wc_match("OpenSSH_2.[0-4]*", imp) ||
2493 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2494 wc_match("Sun_SSH_1.0", imp) ||
2495 wc_match("Sun_SSH_1.0.1", imp) ||
2496 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2497 wc_match("WeOnlyDo-*", imp)))) {
2499 * These versions have the SSH-2 rekey bug.
2501 ssh->remote_bugs |= BUG_SSH2_REKEY;
2502 logevent("We believe remote version has SSH-2 rekey bug");
2505 if (ssh->cfg.sshbug_maxpkt2 == FORCE_ON ||
2506 (ssh->cfg.sshbug_maxpkt2 == AUTO &&
2507 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2508 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2510 * This version ignores our makpkt and needs to be throttled.
2512 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2513 logevent("We believe remote version ignores SSH-2 maximum packet size");
2516 if (ssh->cfg.sshbug_ignore2 == FORCE_ON) {
2518 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2519 * none detected automatically.
2521 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2522 logevent("We believe remote version has SSH-2 ignore bug");
2527 * The `software version' part of an SSH version string is required
2528 * to contain no spaces or minus signs.
2530 static void ssh_fix_verstring(char *str)
2532 /* Eat "SSH-<protoversion>-". */
2533 assert(*str == 'S'); str++;
2534 assert(*str == 'S'); str++;
2535 assert(*str == 'H'); str++;
2536 assert(*str == '-'); str++;
2537 while (*str && *str != '-') str++;
2538 assert(*str == '-'); str++;
2540 /* Convert minus signs and spaces in the remaining string into
2543 if (*str == '-' || *str == ' ')
2550 * Send an appropriate SSH version string.
2552 static void ssh_send_verstring(Ssh ssh, char *svers)
2556 if (ssh->version == 2) {
2558 * Construct a v2 version string.
2560 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2563 * Construct a v1 version string.
2565 verstring = dupprintf("SSH-%s-%s\012",
2566 (ssh_versioncmp(svers, "1.5") <= 0 ?
2571 ssh_fix_verstring(verstring);
2573 if (ssh->version == 2) {
2576 * Record our version string.
2578 len = strcspn(verstring, "\015\012");
2579 ssh->v_c = snewn(len + 1, char);
2580 memcpy(ssh->v_c, verstring, len);
2584 logeventf(ssh, "We claim version: %.*s",
2585 strcspn(verstring, "\015\012"), verstring);
2586 s_write(ssh, verstring, strlen(verstring));
2590 static int do_ssh_init(Ssh ssh, unsigned char c)
2592 struct do_ssh_init_state {
2600 crState(do_ssh_init_state);
2602 crBegin(ssh->do_ssh_init_crstate);
2604 /* Search for a line beginning with the string "SSH-" in the input. */
2606 if (c != 'S') goto no;
2608 if (c != 'S') goto no;
2610 if (c != 'H') goto no;
2612 if (c != '-') goto no;
2621 s->vstring = snewn(s->vstrsize, char);
2622 strcpy(s->vstring, "SSH-");
2626 crReturn(1); /* get another char */
2627 if (s->vslen >= s->vstrsize - 1) {
2629 s->vstring = sresize(s->vstring, s->vstrsize, char);
2631 s->vstring[s->vslen++] = c;
2634 s->version[s->i] = '\0';
2636 } else if (s->i < sizeof(s->version) - 1)
2637 s->version[s->i++] = c;
2638 } else if (c == '\012')
2642 ssh->agentfwd_enabled = FALSE;
2643 ssh->rdpkt2_state.incoming_sequence = 0;
2645 s->vstring[s->vslen] = 0;
2646 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2647 logeventf(ssh, "Server version: %s", s->vstring);
2648 ssh_detect_bugs(ssh, s->vstring);
2651 * Decide which SSH protocol version to support.
2654 /* Anything strictly below "2.0" means protocol 1 is supported. */
2655 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2656 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2657 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2659 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2660 bombout(("SSH protocol version 1 required by user but not provided by server"));
2663 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2664 bombout(("SSH protocol version 2 required by user but not provided by server"));
2668 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1))
2673 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2675 /* Send the version string, if we haven't already */
2676 if (ssh->cfg.sshprot != 3)
2677 ssh_send_verstring(ssh, s->version);
2679 if (ssh->version == 2) {
2682 * Record their version string.
2684 len = strcspn(s->vstring, "\015\012");
2685 ssh->v_s = snewn(len + 1, char);
2686 memcpy(ssh->v_s, s->vstring, len);
2690 * Initialise SSH-2 protocol.
2692 ssh->protocol = ssh2_protocol;
2693 ssh2_protocol_setup(ssh);
2694 ssh->s_rdpkt = ssh2_rdpkt;
2697 * Initialise SSH-1 protocol.
2699 ssh->protocol = ssh1_protocol;
2700 ssh1_protocol_setup(ssh);
2701 ssh->s_rdpkt = ssh1_rdpkt;
2703 if (ssh->version == 2)
2704 do_ssh2_transport(ssh, NULL, -1, NULL);
2706 update_specials_menu(ssh->frontend);
2707 ssh->state = SSH_STATE_BEFORE_SIZE;
2708 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2715 static void ssh_process_incoming_data(Ssh ssh,
2716 unsigned char **data, int *datalen)
2718 struct Packet *pktin;
2720 pktin = ssh->s_rdpkt(ssh, data, datalen);
2722 ssh->protocol(ssh, NULL, 0, pktin);
2723 ssh_free_packet(pktin);
2727 static void ssh_queue_incoming_data(Ssh ssh,
2728 unsigned char **data, int *datalen)
2730 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2735 static void ssh_process_queued_incoming_data(Ssh ssh)
2738 unsigned char *data;
2741 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2742 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2746 while (!ssh->frozen && len > 0)
2747 ssh_process_incoming_data(ssh, &data, &len);
2750 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2754 static void ssh_set_frozen(Ssh ssh, int frozen)
2757 sk_set_frozen(ssh->s, frozen);
2758 ssh->frozen = frozen;
2761 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2763 /* Log raw data, if we're in that mode. */
2765 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2768 crBegin(ssh->ssh_gotdata_crstate);
2771 * To begin with, feed the characters one by one to the
2772 * protocol initialisation / selection function do_ssh_init().
2773 * When that returns 0, we're done with the initial greeting
2774 * exchange and can move on to packet discipline.
2777 int ret; /* need not be kept across crReturn */
2779 crReturnV; /* more data please */
2780 ret = do_ssh_init(ssh, *data);
2788 * We emerge from that loop when the initial negotiation is
2789 * over and we have selected an s_rdpkt function. Now pass
2790 * everything to s_rdpkt, and then pass the resulting packets
2791 * to the proper protocol handler.
2795 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2797 ssh_queue_incoming_data(ssh, &data, &datalen);
2798 /* This uses up all data and cannot cause anything interesting
2799 * to happen; indeed, for anything to happen at all, we must
2800 * return, so break out. */
2802 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2803 /* This uses up some or all data, and may freeze the
2805 ssh_process_queued_incoming_data(ssh);
2807 /* This uses up some or all data, and may freeze the
2809 ssh_process_incoming_data(ssh, &data, &datalen);
2811 /* FIXME this is probably EBW. */
2812 if (ssh->state == SSH_STATE_CLOSED)
2815 /* We're out of data. Go and get some more. */
2821 static int ssh_do_close(Ssh ssh, int notify_exit)
2824 struct ssh_channel *c;
2826 ssh->state = SSH_STATE_CLOSED;
2827 expire_timer_context(ssh);
2832 notify_remote_exit(ssh->frontend);
2837 * Now we must shut down any port- and X-forwarded channels going
2838 * through this connection.
2840 if (ssh->channels) {
2841 while (NULL != (c = index234(ssh->channels, 0))) {
2844 x11_close(c->u.x11.s);
2847 pfd_close(c->u.pfd.s);
2850 del234(ssh->channels, c); /* moving next one to index 0 */
2851 if (ssh->version == 2)
2852 bufchain_clear(&c->v.v2.outbuffer);
2857 * Go through port-forwardings, and close any associated
2858 * listening sockets.
2860 if (ssh->portfwds) {
2861 struct ssh_portfwd *pf;
2862 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2863 /* Dispose of any listening socket. */
2865 pfd_terminate(pf->local);
2866 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2869 freetree234(ssh->portfwds);
2870 ssh->portfwds = NULL;
2876 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2877 const char *error_msg, int error_code)
2879 Ssh ssh = (Ssh) plug;
2880 char addrbuf[256], *msg;
2882 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2885 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2887 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2893 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2896 Ssh ssh = (Ssh) plug;
2897 int need_notify = ssh_do_close(ssh, FALSE);
2900 if (!ssh->close_expected)
2901 error_msg = "Server unexpectedly closed network connection";
2903 error_msg = "Server closed network connection";
2906 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2910 notify_remote_exit(ssh->frontend);
2913 logevent(error_msg);
2914 if (!ssh->close_expected || !ssh->clean_exit)
2915 connection_fatal(ssh->frontend, "%s", error_msg);
2919 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2921 Ssh ssh = (Ssh) plug;
2922 ssh_gotdata(ssh, (unsigned char *)data, len);
2923 if (ssh->state == SSH_STATE_CLOSED) {
2924 ssh_do_close(ssh, TRUE);
2930 static void ssh_sent(Plug plug, int bufsize)
2932 Ssh ssh = (Ssh) plug;
2934 * If the send backlog on the SSH socket itself clears, we
2935 * should unthrottle the whole world if it was throttled.
2937 if (bufsize < SSH_MAX_BACKLOG)
2938 ssh_throttle_all(ssh, 0, bufsize);
2942 * Connect to specified host and port.
2943 * Returns an error message, or NULL on success.
2944 * Also places the canonical host name into `realhost'. It must be
2945 * freed by the caller.
2947 static const char *connect_to_host(Ssh ssh, char *host, int port,
2948 char **realhost, int nodelay, int keepalive)
2950 static const struct plug_function_table fn_table = {
2961 if (*ssh->cfg.loghost) {
2964 ssh->savedhost = dupstr(ssh->cfg.loghost);
2965 ssh->savedport = 22; /* default ssh port */
2968 * A colon suffix on savedhost also lets us affect
2971 * (FIXME: do something about IPv6 address literals here.)
2973 colon = strrchr(ssh->savedhost, ':');
2977 ssh->savedport = atoi(colon);
2980 ssh->savedhost = dupstr(host);
2982 port = 22; /* default ssh port */
2983 ssh->savedport = port;
2989 logeventf(ssh, "Looking up host \"%s\"%s", host,
2990 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2991 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2992 addr = name_lookup(host, port, realhost, &ssh->cfg,
2993 ssh->cfg.addressfamily);
2994 if ((err = sk_addr_error(addr)) != NULL) {
2998 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3003 ssh->fn = &fn_table;
3004 ssh->s = new_connection(addr, *realhost, port,
3005 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
3006 if ((err = sk_socket_error(ssh->s)) != NULL) {
3008 notify_remote_exit(ssh->frontend);
3013 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3014 * send the version string too.
3016 if (ssh->cfg.sshprot == 0)
3018 if (ssh->cfg.sshprot == 3) {
3020 ssh_send_verstring(ssh, NULL);
3024 * loghost, if configured, overrides realhost.
3026 if (*ssh->cfg.loghost) {
3028 *realhost = dupstr(ssh->cfg.loghost);
3035 * Throttle or unthrottle the SSH connection.
3037 static void ssh_throttle_conn(Ssh ssh, int adjust)
3039 int old_count = ssh->conn_throttle_count;
3040 ssh->conn_throttle_count += adjust;
3041 assert(ssh->conn_throttle_count >= 0);
3042 if (ssh->conn_throttle_count && !old_count) {
3043 ssh_set_frozen(ssh, 1);
3044 } else if (!ssh->conn_throttle_count && old_count) {
3045 ssh_set_frozen(ssh, 0);
3050 * Throttle or unthrottle _all_ local data streams (for when sends
3051 * on the SSH connection itself back up).
3053 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3056 struct ssh_channel *c;
3058 if (enable == ssh->throttled_all)
3060 ssh->throttled_all = enable;
3061 ssh->overall_bufsize = bufsize;
3064 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3066 case CHAN_MAINSESSION:
3068 * This is treated separately, outside the switch.
3072 x11_override_throttle(c->u.x11.s, enable);
3075 /* Agent channels require no buffer management. */
3078 pfd_override_throttle(c->u.pfd.s, enable);
3084 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3086 Ssh ssh = (Ssh) sshv;
3088 ssh->agent_response = reply;
3089 ssh->agent_response_len = replylen;
3091 if (ssh->version == 1)
3092 do_ssh1_login(ssh, NULL, -1, NULL);
3094 do_ssh2_authconn(ssh, NULL, -1, NULL);
3097 static void ssh_dialog_callback(void *sshv, int ret)
3099 Ssh ssh = (Ssh) sshv;
3101 ssh->user_response = ret;
3103 if (ssh->version == 1)
3104 do_ssh1_login(ssh, NULL, -1, NULL);
3106 do_ssh2_transport(ssh, NULL, -1, NULL);
3109 * This may have unfrozen the SSH connection, so do a
3112 ssh_process_queued_incoming_data(ssh);
3115 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3117 struct ssh_channel *c = (struct ssh_channel *)cv;
3119 void *sentreply = reply;
3122 /* Fake SSH_AGENT_FAILURE. */
3123 sentreply = "\0\0\0\1\5";
3126 if (ssh->version == 2) {
3127 ssh2_add_channel_data(c, sentreply, replylen);
3130 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3131 PKT_INT, c->remoteid,
3134 PKT_DATA, sentreply, replylen,
3143 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3144 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3145 * => log `wire_reason'.
3147 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3148 int code, int clean_exit)
3152 client_reason = wire_reason;
3154 error = dupprintf("Disconnected: %s", client_reason);
3156 error = dupstr("Disconnected");
3158 if (ssh->version == 1) {
3159 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3161 } else if (ssh->version == 2) {
3162 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3163 ssh2_pkt_adduint32(pktout, code);
3164 ssh2_pkt_addstring(pktout, wire_reason);
3165 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3166 ssh2_pkt_send_noqueue(ssh, pktout);
3169 ssh->close_expected = TRUE;
3170 ssh->clean_exit = clean_exit;
3171 ssh_closing((Plug)ssh, error, 0, 0);
3176 * Handle the key exchange and user authentication phases.
3178 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3179 struct Packet *pktin)
3182 unsigned char cookie[8], *ptr;
3183 struct RSAKey servkey, hostkey;
3184 struct MD5Context md5c;
3185 struct do_ssh1_login_state {
3187 unsigned char *rsabuf, *keystr1, *keystr2;
3188 unsigned long supported_ciphers_mask, supported_auths_mask;
3189 int tried_publickey, tried_agent;
3190 int tis_auth_refused, ccard_auth_refused;
3191 unsigned char session_id[16];
3194 void *publickey_blob;
3195 int publickey_bloblen;
3196 char *publickey_comment;
3197 int publickey_encrypted;
3198 prompts_t *cur_prompt;
3201 unsigned char request[5], *response, *p;
3211 crState(do_ssh1_login_state);
3213 crBegin(ssh->do_ssh1_login_crstate);
3218 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3219 bombout(("Public key packet not received"));
3223 logevent("Received public keys");
3225 ptr = ssh_pkt_getdata(pktin, 8);
3227 bombout(("SSH-1 public key packet stopped before random cookie"));
3230 memcpy(cookie, ptr, 8);
3232 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3233 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3234 bombout(("Failed to read SSH-1 public keys from public key packet"));
3239 * Log the host key fingerprint.
3243 logevent("Host key fingerprint is:");
3244 strcpy(logmsg, " ");
3245 hostkey.comment = NULL;
3246 rsa_fingerprint(logmsg + strlen(logmsg),
3247 sizeof(logmsg) - strlen(logmsg), &hostkey);
3251 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3252 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3253 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3254 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3255 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3257 ssh->v1_local_protoflags =
3258 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3259 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3262 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3263 MD5Update(&md5c, s->keystr1, servkey.bytes);
3264 MD5Update(&md5c, cookie, 8);
3265 MD5Final(s->session_id, &md5c);
3267 for (i = 0; i < 32; i++)
3268 ssh->session_key[i] = random_byte();
3271 * Verify that the `bits' and `bytes' parameters match.
3273 if (hostkey.bits > hostkey.bytes * 8 ||
3274 servkey.bits > servkey.bytes * 8) {
3275 bombout(("SSH-1 public keys were badly formatted"));
3279 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3281 s->rsabuf = snewn(s->len, unsigned char);
3284 * Verify the host key.
3288 * First format the key into a string.
3290 int len = rsastr_len(&hostkey);
3291 char fingerprint[100];
3292 char *keystr = snewn(len, char);
3293 rsastr_fmt(keystr, &hostkey);
3294 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3296 ssh_set_frozen(ssh, 1);
3297 s->dlgret = verify_ssh_host_key(ssh->frontend,
3298 ssh->savedhost, ssh->savedport,
3299 "rsa", keystr, fingerprint,
3300 ssh_dialog_callback, ssh);
3302 if (s->dlgret < 0) {
3306 bombout(("Unexpected data from server while waiting"
3307 " for user host key response"));
3310 } while (pktin || inlen > 0);
3311 s->dlgret = ssh->user_response;
3313 ssh_set_frozen(ssh, 0);
3315 if (s->dlgret == 0) {
3316 ssh_disconnect(ssh, "User aborted at host key verification",
3322 for (i = 0; i < 32; i++) {
3323 s->rsabuf[i] = ssh->session_key[i];
3325 s->rsabuf[i] ^= s->session_id[i];
3328 if (hostkey.bytes > servkey.bytes) {
3329 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3331 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3333 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3335 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3338 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3342 logevent("Encrypted session key");
3345 int cipher_chosen = 0, warn = 0;
3346 char *cipher_string = NULL;
3348 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3349 int next_cipher = ssh->cfg.ssh_cipherlist[i];
3350 if (next_cipher == CIPHER_WARN) {
3351 /* If/when we choose a cipher, warn about it */
3353 } else if (next_cipher == CIPHER_AES) {
3354 /* XXX Probably don't need to mention this. */
3355 logevent("AES not supported in SSH-1, skipping");
3357 switch (next_cipher) {
3358 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3359 cipher_string = "3DES"; break;
3360 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3361 cipher_string = "Blowfish"; break;
3362 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3363 cipher_string = "single-DES"; break;
3365 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3369 if (!cipher_chosen) {
3370 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3371 bombout(("Server violates SSH-1 protocol by not "
3372 "supporting 3DES encryption"));
3374 /* shouldn't happen */
3375 bombout(("No supported ciphers found"));
3379 /* Warn about chosen cipher if necessary. */
3381 ssh_set_frozen(ssh, 1);
3382 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3383 ssh_dialog_callback, ssh);
3384 if (s->dlgret < 0) {
3388 bombout(("Unexpected data from server while waiting"
3389 " for user response"));
3392 } while (pktin || inlen > 0);
3393 s->dlgret = ssh->user_response;
3395 ssh_set_frozen(ssh, 0);
3396 if (s->dlgret == 0) {
3397 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3404 switch (s->cipher_type) {
3405 case SSH_CIPHER_3DES:
3406 logevent("Using 3DES encryption");
3408 case SSH_CIPHER_DES:
3409 logevent("Using single-DES encryption");
3411 case SSH_CIPHER_BLOWFISH:
3412 logevent("Using Blowfish encryption");
3416 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3417 PKT_CHAR, s->cipher_type,
3418 PKT_DATA, cookie, 8,
3419 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3420 PKT_DATA, s->rsabuf, s->len,
3421 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3423 logevent("Trying to enable encryption...");
3427 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3428 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3430 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3431 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3432 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3434 ssh->crcda_ctx = crcda_make_context();
3435 logevent("Installing CRC compensation attack detector");
3437 if (servkey.modulus) {
3438 sfree(servkey.modulus);
3439 servkey.modulus = NULL;
3441 if (servkey.exponent) {
3442 sfree(servkey.exponent);
3443 servkey.exponent = NULL;
3445 if (hostkey.modulus) {
3446 sfree(hostkey.modulus);
3447 hostkey.modulus = NULL;
3449 if (hostkey.exponent) {
3450 sfree(hostkey.exponent);
3451 hostkey.exponent = NULL;
3455 if (pktin->type != SSH1_SMSG_SUCCESS) {
3456 bombout(("Encryption not successfully enabled"));
3460 logevent("Successfully started encryption");
3462 fflush(stdout); /* FIXME eh? */
3464 if (!get_remote_username(&ssh->cfg, s->username,
3465 sizeof(s->username))) {
3466 int ret; /* need not be kept over crReturn */
3467 s->cur_prompt = new_prompts(ssh->frontend);
3468 s->cur_prompt->to_server = TRUE;
3469 s->cur_prompt->name = dupstr("SSH login name");
3470 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
3471 lenof(s->username));
3472 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3475 crWaitUntil(!pktin);
3476 ret = get_userpass_input(s->cur_prompt, in, inlen);
3481 * Failed to get a username. Terminate.
3483 free_prompts(s->cur_prompt);
3484 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3487 memcpy(s->username, s->cur_prompt->prompts[0]->result,
3488 lenof(s->username));
3489 free_prompts(s->cur_prompt);
3492 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3494 char *userlog = dupprintf("Sent username \"%s\"", s->username);
3496 if (flags & FLAG_INTERACTIVE &&
3497 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3498 c_write_str(ssh, userlog);
3499 c_write_str(ssh, "\r\n");
3507 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3508 /* We must not attempt PK auth. Pretend we've already tried it. */
3509 s->tried_publickey = s->tried_agent = 1;
3511 s->tried_publickey = s->tried_agent = 0;
3513 s->tis_auth_refused = s->ccard_auth_refused = 0;
3515 * Load the public half of any configured keyfile for later use.
3517 if (!filename_is_null(ssh->cfg.keyfile)) {
3519 logeventf(ssh, "Reading private key file \"%.150s\"",
3520 filename_to_str(&ssh->cfg.keyfile));
3521 keytype = key_type(&ssh->cfg.keyfile);
3522 if (keytype == SSH_KEYTYPE_SSH1) {
3524 if (rsakey_pubblob(&ssh->cfg.keyfile,
3525 &s->publickey_blob, &s->publickey_bloblen,
3526 &s->publickey_comment, &error)) {
3527 s->publickey_encrypted = rsakey_encrypted(&ssh->cfg.keyfile,
3531 logeventf(ssh, "Unable to load private key (%s)", error);
3532 msgbuf = dupprintf("Unable to load private key file "
3533 "\"%.150s\" (%s)\r\n",
3534 filename_to_str(&ssh->cfg.keyfile),
3536 c_write_str(ssh, msgbuf);
3538 s->publickey_blob = NULL;
3542 logeventf(ssh, "Unable to use this key file (%s)",
3543 key_type_to_str(keytype));
3544 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3546 filename_to_str(&ssh->cfg.keyfile),
3547 key_type_to_str(keytype));
3548 c_write_str(ssh, msgbuf);
3550 s->publickey_blob = NULL;
3553 s->publickey_blob = NULL;
3555 while (pktin->type == SSH1_SMSG_FAILURE) {
3556 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3558 if (ssh->cfg.tryagent && agent_exists() && !s->tried_agent) {
3560 * Attempt RSA authentication using Pageant.
3566 logevent("Pageant is running. Requesting keys.");
3568 /* Request the keys held by the agent. */
3569 PUT_32BIT(s->request, 1);
3570 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3571 if (!agent_query(s->request, 5, &r, &s->responselen,
3572 ssh_agent_callback, ssh)) {
3576 bombout(("Unexpected data from server while waiting"
3577 " for agent response"));
3580 } while (pktin || inlen > 0);
3581 r = ssh->agent_response;
3582 s->responselen = ssh->agent_response_len;
3584 s->response = (unsigned char *) r;
3585 if (s->response && s->responselen >= 5 &&
3586 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3587 s->p = s->response + 5;
3588 s->nkeys = GET_32BIT(s->p);
3590 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3591 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3592 unsigned char *pkblob = s->p;
3596 do { /* do while (0) to make breaking easy */
3597 n = ssh1_read_bignum
3598 (s->p, s->responselen-(s->p-s->response),
3603 n = ssh1_read_bignum
3604 (s->p, s->responselen-(s->p-s->response),
3609 if (s->responselen - (s->p-s->response) < 4)
3611 s->commentlen = GET_32BIT(s->p);
3613 if (s->responselen - (s->p-s->response) <
3616 s->commentp = (char *)s->p;
3617 s->p += s->commentlen;
3621 logevent("Pageant key list packet was truncated");
3625 if (s->publickey_blob) {
3626 if (!memcmp(pkblob, s->publickey_blob,
3627 s->publickey_bloblen)) {
3628 logeventf(ssh, "Pageant key #%d matches "
3629 "configured key file", s->keyi);
3630 s->tried_publickey = 1;
3632 /* Skip non-configured key */
3635 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3636 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3637 PKT_BIGNUM, s->key.modulus, PKT_END);
3639 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3640 logevent("Key refused");
3643 logevent("Received RSA challenge");
3644 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3645 bombout(("Server's RSA challenge was badly formatted"));
3650 char *agentreq, *q, *ret;
3653 len = 1 + 4; /* message type, bit count */
3654 len += ssh1_bignum_length(s->key.exponent);
3655 len += ssh1_bignum_length(s->key.modulus);
3656 len += ssh1_bignum_length(s->challenge);
3657 len += 16; /* session id */
3658 len += 4; /* response format */
3659 agentreq = snewn(4 + len, char);
3660 PUT_32BIT(agentreq, len);
3662 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3663 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3665 q += ssh1_write_bignum(q, s->key.exponent);
3666 q += ssh1_write_bignum(q, s->key.modulus);
3667 q += ssh1_write_bignum(q, s->challenge);
3668 memcpy(q, s->session_id, 16);
3670 PUT_32BIT(q, 1); /* response format */
3671 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3672 ssh_agent_callback, ssh)) {
3677 bombout(("Unexpected data from server"
3678 " while waiting for agent"
3682 } while (pktin || inlen > 0);
3683 vret = ssh->agent_response;
3684 retlen = ssh->agent_response_len;
3689 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3690 logevent("Sending Pageant's response");
3691 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3692 PKT_DATA, ret + 5, 16,
3696 if (pktin->type == SSH1_SMSG_SUCCESS) {
3698 ("Pageant's response accepted");
3699 if (flags & FLAG_VERBOSE) {
3700 c_write_str(ssh, "Authenticated using"
3702 c_write(ssh, s->commentp,
3704 c_write_str(ssh, "\" from agent\r\n");
3709 ("Pageant's response not accepted");
3712 ("Pageant failed to answer challenge");
3716 logevent("No reply received from Pageant");
3719 freebn(s->key.exponent);
3720 freebn(s->key.modulus);
3721 freebn(s->challenge);
3726 if (s->publickey_blob && !s->tried_publickey)
3727 logevent("Configured key file not in Pageant");
3732 if (s->publickey_blob && !s->tried_publickey) {
3734 * Try public key authentication with the specified
3737 int got_passphrase; /* need not be kept over crReturn */
3738 if (flags & FLAG_VERBOSE)
3739 c_write_str(ssh, "Trying public key authentication.\r\n");
3740 logeventf(ssh, "Trying public key \"%s\"",
3741 filename_to_str(&ssh->cfg.keyfile));
3742 s->tried_publickey = 1;
3743 got_passphrase = FALSE;
3744 while (!got_passphrase) {
3746 * Get a passphrase, if necessary.
3748 char *passphrase = NULL; /* only written after crReturn */
3750 if (!s->publickey_encrypted) {
3751 if (flags & FLAG_VERBOSE)
3752 c_write_str(ssh, "No passphrase required.\r\n");
3755 int ret; /* need not be kept over crReturn */
3756 s->cur_prompt = new_prompts(ssh->frontend);
3757 s->cur_prompt->to_server = FALSE;
3758 s->cur_prompt->name = dupstr("SSH key passphrase");
3759 add_prompt(s->cur_prompt,
3760 dupprintf("Passphrase for key \"%.100s\": ",
3761 s->publickey_comment),
3762 FALSE, SSH_MAX_PASSWORD_LEN);
3763 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3766 crWaitUntil(!pktin);
3767 ret = get_userpass_input(s->cur_prompt, in, inlen);
3771 /* Failed to get a passphrase. Terminate. */
3772 free_prompts(s->cur_prompt);
3773 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3777 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3778 free_prompts(s->cur_prompt);
3781 * Try decrypting key with passphrase.
3783 ret = loadrsakey(&ssh->cfg.keyfile, &s->key, passphrase,
3786 memset(passphrase, 0, strlen(passphrase));
3790 /* Correct passphrase. */
3791 got_passphrase = TRUE;
3792 } else if (ret == 0) {
3793 c_write_str(ssh, "Couldn't load private key from ");
3794 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3795 c_write_str(ssh, " (");
3796 c_write_str(ssh, error);
3797 c_write_str(ssh, ").\r\n");
3798 got_passphrase = FALSE;
3799 break; /* go and try something else */
3800 } else if (ret == -1) {
3801 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3802 got_passphrase = FALSE;
3805 assert(0 && "unexpected return from loadrsakey()");
3806 got_passphrase = FALSE; /* placate optimisers */
3810 if (got_passphrase) {
3813 * Send a public key attempt.
3815 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3816 PKT_BIGNUM, s->key.modulus, PKT_END);
3819 if (pktin->type == SSH1_SMSG_FAILURE) {
3820 c_write_str(ssh, "Server refused our public key.\r\n");
3821 continue; /* go and try something else */
3823 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3824 bombout(("Bizarre response to offer of public key"));
3830 unsigned char buffer[32];
3831 Bignum challenge, response;
3833 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3834 bombout(("Server's RSA challenge was badly formatted"));
3837 response = rsadecrypt(challenge, &s->key);
3838 freebn(s->key.private_exponent);/* burn the evidence */
3840 for (i = 0; i < 32; i++) {
3841 buffer[i] = bignum_byte(response, 31 - i);
3845 MD5Update(&md5c, buffer, 32);
3846 MD5Update(&md5c, s->session_id, 16);
3847 MD5Final(buffer, &md5c);
3849 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3850 PKT_DATA, buffer, 16, PKT_END);
3857 if (pktin->type == SSH1_SMSG_FAILURE) {
3858 if (flags & FLAG_VERBOSE)
3859 c_write_str(ssh, "Failed to authenticate with"
3860 " our public key.\r\n");
3861 continue; /* go and try something else */
3862 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3863 bombout(("Bizarre response to RSA authentication response"));
3867 break; /* we're through! */
3873 * Otherwise, try various forms of password-like authentication.
3875 s->cur_prompt = new_prompts(ssh->frontend);
3877 if (ssh->cfg.try_tis_auth &&
3878 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3879 !s->tis_auth_refused) {
3880 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3881 logevent("Requested TIS authentication");
3882 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3884 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3885 logevent("TIS authentication declined");
3886 if (flags & FLAG_INTERACTIVE)
3887 c_write_str(ssh, "TIS authentication refused.\r\n");
3888 s->tis_auth_refused = 1;
3893 char *instr_suf, *prompt;
3895 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3897 bombout(("TIS challenge packet was badly formed"));
3900 logevent("Received TIS challenge");
3901 s->cur_prompt->to_server = TRUE;
3902 s->cur_prompt->name = dupstr("SSH TIS authentication");
3903 /* Prompt heuristic comes from OpenSSH */
3904 if (memchr(challenge, '\n', challengelen)) {
3905 instr_suf = dupstr("");
3906 prompt = dupprintf("%.*s", challengelen, challenge);
3908 instr_suf = dupprintf("%.*s", challengelen, challenge);
3909 prompt = dupstr("Response: ");
3911 s->cur_prompt->instruction =
3912 dupprintf("Using TIS authentication.%s%s",
3913 (*instr_suf) ? "\n" : "",
3915 s->cur_prompt->instr_reqd = TRUE;
3916 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3920 if (ssh->cfg.try_tis_auth &&
3921 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3922 !s->ccard_auth_refused) {
3923 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3924 logevent("Requested CryptoCard authentication");
3925 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3927 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3928 logevent("CryptoCard authentication declined");
3929 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3930 s->ccard_auth_refused = 1;
3935 char *instr_suf, *prompt;
3937 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3939 bombout(("CryptoCard challenge packet was badly formed"));
3942 logevent("Received CryptoCard challenge");
3943 s->cur_prompt->to_server = TRUE;
3944 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3945 s->cur_prompt->name_reqd = FALSE;
3946 /* Prompt heuristic comes from OpenSSH */
3947 if (memchr(challenge, '\n', challengelen)) {
3948 instr_suf = dupstr("");
3949 prompt = dupprintf("%.*s", challengelen, challenge);
3951 instr_suf = dupprintf("%.*s", challengelen, challenge);
3952 prompt = dupstr("Response: ");
3954 s->cur_prompt->instruction =
3955 dupprintf("Using CryptoCard authentication.%s%s",
3956 (*instr_suf) ? "\n" : "",
3958 s->cur_prompt->instr_reqd = TRUE;
3959 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3963 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3964 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
3965 bombout(("No supported authentication methods available"));
3968 s->cur_prompt->to_server = TRUE;
3969 s->cur_prompt->name = dupstr("SSH password");
3970 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
3971 s->username, ssh->savedhost),
3972 FALSE, SSH_MAX_PASSWORD_LEN);
3976 * Show password prompt, having first obtained it via a TIS
3977 * or CryptoCard exchange if we're doing TIS or CryptoCard
3981 int ret; /* need not be kept over crReturn */
3982 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3985 crWaitUntil(!pktin);
3986 ret = get_userpass_input(s->cur_prompt, in, inlen);
3991 * Failed to get a password (for example
3992 * because one was supplied on the command line
3993 * which has already failed to work). Terminate.
3995 free_prompts(s->cur_prompt);
3996 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4001 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4003 * Defence against traffic analysis: we send a
4004 * whole bunch of packets containing strings of
4005 * different lengths. One of these strings is the
4006 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4007 * The others are all random data in
4008 * SSH1_MSG_IGNORE packets. This way a passive
4009 * listener can't tell which is the password, and
4010 * hence can't deduce the password length.
4012 * Anybody with a password length greater than 16
4013 * bytes is going to have enough entropy in their
4014 * password that a listener won't find it _that_
4015 * much help to know how long it is. So what we'll
4018 * - if password length < 16, we send 15 packets
4019 * containing string lengths 1 through 15
4021 * - otherwise, we let N be the nearest multiple
4022 * of 8 below the password length, and send 8
4023 * packets containing string lengths N through
4024 * N+7. This won't obscure the order of
4025 * magnitude of the password length, but it will
4026 * introduce a bit of extra uncertainty.
4028 * A few servers can't deal with SSH1_MSG_IGNORE, at
4029 * least in this context. For these servers, we need
4030 * an alternative defence. We make use of the fact
4031 * that the password is interpreted as a C string:
4032 * so we can append a NUL, then some random data.
4034 * A few servers can deal with neither SSH1_MSG_IGNORE
4035 * here _nor_ a padded password string.
4036 * For these servers we are left with no defences
4037 * against password length sniffing.
4039 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4040 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4042 * The server can deal with SSH1_MSG_IGNORE, so
4043 * we can use the primary defence.
4045 int bottom, top, pwlen, i;
4048 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4050 bottom = 0; /* zero length passwords are OK! :-) */
4053 bottom = pwlen & ~7;
4057 assert(pwlen >= bottom && pwlen <= top);
4059 randomstr = snewn(top + 1, char);
4061 for (i = bottom; i <= top; i++) {
4063 defer_packet(ssh, s->pwpkt_type,
4064 PKTT_PASSWORD, PKT_STR,
4065 s->cur_prompt->prompts[0]->result,
4066 PKTT_OTHER, PKT_END);
4068 for (j = 0; j < i; j++) {
4070 randomstr[j] = random_byte();
4071 } while (randomstr[j] == '\0');
4073 randomstr[i] = '\0';
4074 defer_packet(ssh, SSH1_MSG_IGNORE,
4075 PKT_STR, randomstr, PKT_END);
4078 logevent("Sending password with camouflage packets");
4079 ssh_pkt_defersend(ssh);
4082 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4084 * The server can't deal with SSH1_MSG_IGNORE
4085 * but can deal with padded passwords, so we
4086 * can use the secondary defence.
4092 len = strlen(s->cur_prompt->prompts[0]->result);
4093 if (len < sizeof(string)) {
4095 strcpy(string, s->cur_prompt->prompts[0]->result);
4096 len++; /* cover the zero byte */
4097 while (len < sizeof(string)) {
4098 string[len++] = (char) random_byte();
4101 ss = s->cur_prompt->prompts[0]->result;
4103 logevent("Sending length-padded password");
4104 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4105 PKT_INT, len, PKT_DATA, ss, len,
4106 PKTT_OTHER, PKT_END);
4109 * The server is believed unable to cope with
4110 * any of our password camouflage methods.
4113 len = strlen(s->cur_prompt->prompts[0]->result);
4114 logevent("Sending unpadded password");
4115 send_packet(ssh, s->pwpkt_type,
4116 PKTT_PASSWORD, PKT_INT, len,
4117 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4118 PKTT_OTHER, PKT_END);
4121 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4122 PKT_STR, s->cur_prompt->prompts[0]->result,
4123 PKTT_OTHER, PKT_END);
4125 logevent("Sent password");
4126 free_prompts(s->cur_prompt);
4128 if (pktin->type == SSH1_SMSG_FAILURE) {
4129 if (flags & FLAG_VERBOSE)
4130 c_write_str(ssh, "Access denied\r\n");
4131 logevent("Authentication refused");
4132 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4133 bombout(("Strange packet received, type %d", pktin->type));
4139 if (s->publickey_blob) {
4140 sfree(s->publickey_blob);
4141 sfree(s->publickey_comment);
4144 logevent("Authentication successful");
4149 void sshfwd_close(struct ssh_channel *c)
4153 if (ssh->state == SSH_STATE_CLOSED)
4156 if (c && !c->closes) {
4158 * If halfopen is true, we have sent
4159 * CHANNEL_OPEN for this channel, but it hasn't even been
4160 * acknowledged by the server. So we must set a close flag
4161 * on it now, and then when the server acks the channel
4162 * open, we can close it then.
4165 if (ssh->version == 1) {
4166 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4169 struct Packet *pktout;
4170 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4171 ssh2_pkt_adduint32(pktout, c->remoteid);
4172 ssh2_pkt_send(ssh, pktout);
4175 c->closes = 1; /* sent MSG_CLOSE */
4176 if (c->type == CHAN_X11) {
4178 logevent("Forwarded X11 connection terminated");
4179 } else if (c->type == CHAN_SOCKDATA ||
4180 c->type == CHAN_SOCKDATA_DORMANT) {
4182 logevent("Forwarded port closed");
4187 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4191 if (ssh->state == SSH_STATE_CLOSED)
4194 if (ssh->version == 1) {
4195 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4196 PKT_INT, c->remoteid,
4197 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4198 PKTT_OTHER, PKT_END);
4200 * In SSH-1 we can return 0 here - implying that forwarded
4201 * connections are never individually throttled - because
4202 * the only circumstance that can cause throttling will be
4203 * the whole SSH connection backing up, in which case
4204 * _everything_ will be throttled as a whole.
4208 ssh2_add_channel_data(c, buf, len);
4209 return ssh2_try_send(c);
4213 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4218 if (ssh->state == SSH_STATE_CLOSED)
4221 if (ssh->version == 1) {
4222 buflimit = SSH1_BUFFER_LIMIT;
4224 buflimit = c->v.v2.locmaxwin;
4225 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4227 if (c->throttling_conn && bufsize <= buflimit) {
4228 c->throttling_conn = 0;
4229 ssh_throttle_conn(ssh, -1);
4233 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4235 struct queued_handler *qh = ssh->qhead;
4239 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4242 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4243 ssh->packet_dispatch[qh->msg1] = NULL;
4246 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4247 ssh->packet_dispatch[qh->msg2] = NULL;
4251 ssh->qhead = qh->next;
4253 if (ssh->qhead->msg1 > 0) {
4254 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4255 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4257 if (ssh->qhead->msg2 > 0) {
4258 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4259 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4262 ssh->qhead = ssh->qtail = NULL;
4263 ssh->packet_dispatch[pktin->type] = NULL;
4266 qh->handler(ssh, pktin, qh->ctx);
4271 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4272 chandler_fn_t handler, void *ctx)
4274 struct queued_handler *qh;
4276 qh = snew(struct queued_handler);
4279 qh->handler = handler;
4283 if (ssh->qtail == NULL) {
4287 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4288 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4291 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4292 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4295 ssh->qtail->next = qh;
4300 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4302 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4304 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4305 SSH2_MSG_REQUEST_SUCCESS)) {
4306 logeventf(ssh, "Remote port forwarding from %s enabled",
4309 logeventf(ssh, "Remote port forwarding from %s refused",
4312 rpf = del234(ssh->rportfwds, pf);
4318 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
4320 const char *portfwd_strptr = cfg->portfwd;
4321 struct ssh_portfwd *epf;
4324 if (!ssh->portfwds) {
4325 ssh->portfwds = newtree234(ssh_portcmp);
4328 * Go through the existing port forwardings and tag them
4329 * with status==DESTROY. Any that we want to keep will be
4330 * re-enabled (status==KEEP) as we go through the
4331 * configuration and find out which bits are the same as
4334 struct ssh_portfwd *epf;
4336 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4337 epf->status = DESTROY;
4340 while (*portfwd_strptr) {
4341 char address_family, type;
4342 int sport,dport,sserv,dserv;
4343 char sports[256], dports[256], saddr[256], host[256];
4346 address_family = 'A';
4348 if (*portfwd_strptr == 'A' ||
4349 *portfwd_strptr == '4' ||
4350 *portfwd_strptr == '6')
4351 address_family = *portfwd_strptr++;
4352 if (*portfwd_strptr == 'L' ||
4353 *portfwd_strptr == 'R' ||
4354 *portfwd_strptr == 'D')
4355 type = *portfwd_strptr++;
4360 while (*portfwd_strptr && *portfwd_strptr != '\t') {
4361 if (*portfwd_strptr == ':') {
4363 * We've seen a colon in the middle of the
4364 * source port number. This means that
4365 * everything we've seen until now is the
4366 * source _address_, so we'll move it into
4367 * saddr and start sports from the beginning
4372 if (ssh->version == 1 && type == 'R') {
4373 logeventf(ssh, "SSH-1 cannot handle remote source address "
4374 "spec \"%s\"; ignoring", sports);
4376 strcpy(saddr, sports);
4379 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
4383 if (*portfwd_strptr == '\t')
4386 while (*portfwd_strptr && *portfwd_strptr != ':') {
4387 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
4390 if (*portfwd_strptr == ':')
4393 while (*portfwd_strptr) {
4394 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
4398 dport = atoi(dports);
4402 dport = net_service_lookup(dports);
4404 logeventf(ssh, "Service lookup failed for destination"
4405 " port \"%s\"", dports);
4409 while (*portfwd_strptr) portfwd_strptr++;
4413 portfwd_strptr++; /* eat the NUL and move to next one */
4415 sport = atoi(sports);
4419 sport = net_service_lookup(sports);
4421 logeventf(ssh, "Service lookup failed for source"
4422 " port \"%s\"", sports);
4425 if (sport && dport) {
4426 /* Set up a description of the source port. */
4427 struct ssh_portfwd *pfrec, *epfrec;
4429 pfrec = snew(struct ssh_portfwd);
4431 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
4432 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4433 pfrec->sport = sport;
4434 pfrec->daddr = *host ? dupstr(host) : NULL;
4435 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4436 pfrec->dport = dport;
4437 pfrec->local = NULL;
4438 pfrec->remote = NULL;
4439 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4440 address_family == '6' ? ADDRTYPE_IPV6 :
4443 epfrec = add234(ssh->portfwds, pfrec);
4444 if (epfrec != pfrec) {
4445 if (epfrec->status == DESTROY) {
4447 * We already have a port forwarding up and running
4448 * with precisely these parameters. Hence, no need
4449 * to do anything; simply re-tag the existing one
4452 epfrec->status = KEEP;
4455 * Anything else indicates that there was a duplicate
4456 * in our input, which we'll silently ignore.
4458 free_portfwd(pfrec);
4460 pfrec->status = CREATE;
4466 * Now go through and destroy any port forwardings which were
4469 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4470 if (epf->status == DESTROY) {
4473 message = dupprintf("%s port forwarding from %s%s%d",
4474 epf->type == 'L' ? "local" :
4475 epf->type == 'R' ? "remote" : "dynamic",
4476 epf->saddr ? epf->saddr : "",
4477 epf->saddr ? ":" : "",
4480 if (epf->type != 'D') {
4481 char *msg2 = dupprintf("%s to %s:%d", message,
4482 epf->daddr, epf->dport);
4487 logeventf(ssh, "Cancelling %s", message);
4491 struct ssh_rportfwd *rpf = epf->remote;
4492 struct Packet *pktout;
4495 * Cancel the port forwarding at the server
4498 if (ssh->version == 1) {
4500 * We cannot cancel listening ports on the
4501 * server side in SSH-1! There's no message
4502 * to support it. Instead, we simply remove
4503 * the rportfwd record from the local end
4504 * so that any connections the server tries
4505 * to make on it are rejected.
4508 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4509 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4510 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4512 ssh2_pkt_addstring(pktout, epf->saddr);
4513 } else if (ssh->cfg.rport_acceptall) {
4514 /* XXX: ssh->cfg.rport_acceptall may not represent
4515 * what was used to open the original connection,
4516 * since it's reconfigurable. */
4517 ssh2_pkt_addstring(pktout, "0.0.0.0");
4519 ssh2_pkt_addstring(pktout, "127.0.0.1");
4521 ssh2_pkt_adduint32(pktout, epf->sport);
4522 ssh2_pkt_send(ssh, pktout);
4525 del234(ssh->rportfwds, rpf);
4527 } else if (epf->local) {
4528 pfd_terminate(epf->local);
4531 delpos234(ssh->portfwds, i);
4533 i--; /* so we don't skip one in the list */
4537 * And finally, set up any new port forwardings (status==CREATE).
4539 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4540 if (epf->status == CREATE) {
4541 char *sportdesc, *dportdesc;
4542 sportdesc = dupprintf("%s%s%s%s%d%s",
4543 epf->saddr ? epf->saddr : "",
4544 epf->saddr ? ":" : "",
4545 epf->sserv ? epf->sserv : "",
4546 epf->sserv ? "(" : "",
4548 epf->sserv ? ")" : "");
4549 if (epf->type == 'D') {
4552 dportdesc = dupprintf("%s:%s%s%d%s",
4554 epf->dserv ? epf->dserv : "",
4555 epf->dserv ? "(" : "",
4557 epf->dserv ? ")" : "");
4560 if (epf->type == 'L') {
4561 const char *err = pfd_addforward(epf->daddr, epf->dport,
4562 epf->saddr, epf->sport,
4565 epf->addressfamily);
4567 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4568 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4569 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4570 sportdesc, dportdesc,
4571 err ? " failed: " : "", err ? err : "");
4572 } else if (epf->type == 'D') {
4573 const char *err = pfd_addforward(NULL, -1,
4574 epf->saddr, epf->sport,
4577 epf->addressfamily);
4579 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4580 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4581 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4583 err ? " failed: " : "", err ? err : "");
4585 struct ssh_rportfwd *pf;
4588 * Ensure the remote port forwardings tree exists.
4590 if (!ssh->rportfwds) {
4591 if (ssh->version == 1)
4592 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4594 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4597 pf = snew(struct ssh_rportfwd);
4598 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4599 pf->dhost[lenof(pf->dhost)-1] = '\0';
4600 pf->dport = epf->dport;
4601 pf->sport = epf->sport;
4602 if (add234(ssh->rportfwds, pf) != pf) {
4603 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4604 epf->daddr, epf->dport);
4607 logeventf(ssh, "Requesting remote port %s"
4608 " forward to %s", sportdesc, dportdesc);
4610 pf->sportdesc = sportdesc;
4615 if (ssh->version == 1) {
4616 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4617 PKT_INT, epf->sport,
4618 PKT_STR, epf->daddr,
4619 PKT_INT, epf->dport,
4621 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4623 ssh_rportfwd_succfail, pf);
4625 struct Packet *pktout;
4626 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4627 ssh2_pkt_addstring(pktout, "tcpip-forward");
4628 ssh2_pkt_addbool(pktout, 1);/* want reply */
4630 ssh2_pkt_addstring(pktout, epf->saddr);
4631 } else if (cfg->rport_acceptall) {
4632 ssh2_pkt_addstring(pktout, "0.0.0.0");
4634 ssh2_pkt_addstring(pktout, "127.0.0.1");
4636 ssh2_pkt_adduint32(pktout, epf->sport);
4637 ssh2_pkt_send(ssh, pktout);
4639 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4640 SSH2_MSG_REQUEST_FAILURE,
4641 ssh_rportfwd_succfail, pf);
4650 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4653 int stringlen, bufsize;
4655 ssh_pkt_getstring(pktin, &string, &stringlen);
4656 if (string == NULL) {
4657 bombout(("Incoming terminal data packet was badly formed"));
4661 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4663 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4664 ssh->v1_stdout_throttling = 1;
4665 ssh_throttle_conn(ssh, +1);
4669 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4671 /* Remote side is trying to open a channel to talk to our
4672 * X-Server. Give them back a local channel number. */
4673 struct ssh_channel *c;
4674 int remoteid = ssh_pkt_getuint32(pktin);
4676 logevent("Received X11 connect request");
4677 /* Refuse if X11 forwarding is disabled. */
4678 if (!ssh->X11_fwd_enabled) {
4679 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4680 PKT_INT, remoteid, PKT_END);
4681 logevent("Rejected X11 connect request");
4683 c = snew(struct ssh_channel);
4686 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4687 NULL, -1, &ssh->cfg) != NULL) {
4688 logevent("Opening X11 forward connection failed");
4690 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4691 PKT_INT, remoteid, PKT_END);
4694 ("Opening X11 forward connection succeeded");
4695 c->remoteid = remoteid;
4696 c->halfopen = FALSE;
4697 c->localid = alloc_channel_id(ssh);
4699 c->throttling_conn = 0;
4700 c->type = CHAN_X11; /* identify channel type */
4701 add234(ssh->channels, c);
4702 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4703 PKT_INT, c->remoteid, PKT_INT,
4704 c->localid, PKT_END);
4705 logevent("Opened X11 forward channel");
4710 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4712 /* Remote side is trying to open a channel to talk to our
4713 * agent. Give them back a local channel number. */
4714 struct ssh_channel *c;
4715 int remoteid = ssh_pkt_getuint32(pktin);
4717 /* Refuse if agent forwarding is disabled. */
4718 if (!ssh->agentfwd_enabled) {
4719 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4720 PKT_INT, remoteid, PKT_END);
4722 c = snew(struct ssh_channel);
4724 c->remoteid = remoteid;
4725 c->halfopen = FALSE;
4726 c->localid = alloc_channel_id(ssh);
4728 c->throttling_conn = 0;
4729 c->type = CHAN_AGENT; /* identify channel type */
4730 c->u.a.lensofar = 0;
4731 add234(ssh->channels, c);
4732 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4733 PKT_INT, c->remoteid, PKT_INT, c->localid,
4738 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4740 /* Remote side is trying to open a channel to talk to a
4741 * forwarded port. Give them back a local channel number. */
4742 struct ssh_channel *c;
4743 struct ssh_rportfwd pf, *pfp;
4748 c = snew(struct ssh_channel);
4751 remoteid = ssh_pkt_getuint32(pktin);
4752 ssh_pkt_getstring(pktin, &host, &hostsize);
4753 port = ssh_pkt_getuint32(pktin);
4755 if (hostsize >= lenof(pf.dhost))
4756 hostsize = lenof(pf.dhost)-1;
4757 memcpy(pf.dhost, host, hostsize);
4758 pf.dhost[hostsize] = '\0';
4760 pfp = find234(ssh->rportfwds, &pf, NULL);
4763 logeventf(ssh, "Rejected remote port open request for %s:%d",
4765 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4766 PKT_INT, remoteid, PKT_END);
4768 logeventf(ssh, "Received remote port open request for %s:%d",
4770 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4771 c, &ssh->cfg, pfp->pfrec->addressfamily);
4773 logeventf(ssh, "Port open failed: %s", e);
4775 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4776 PKT_INT, remoteid, PKT_END);
4778 c->remoteid = remoteid;
4779 c->halfopen = FALSE;
4780 c->localid = alloc_channel_id(ssh);
4782 c->throttling_conn = 0;
4783 c->type = CHAN_SOCKDATA; /* identify channel type */
4784 add234(ssh->channels, c);
4785 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4786 PKT_INT, c->remoteid, PKT_INT,
4787 c->localid, PKT_END);
4788 logevent("Forwarded port opened successfully");
4793 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4795 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4796 unsigned int localid = ssh_pkt_getuint32(pktin);
4797 struct ssh_channel *c;
4799 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4800 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4801 c->remoteid = localid;
4802 c->halfopen = FALSE;
4803 c->type = CHAN_SOCKDATA;
4804 c->throttling_conn = 0;
4805 pfd_confirm(c->u.pfd.s);
4808 if (c && c->closes) {
4810 * We have a pending close on this channel,
4811 * which we decided on before the server acked
4812 * the channel open. So now we know the
4813 * remoteid, we can close it again.
4815 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4816 PKT_INT, c->remoteid, PKT_END);
4820 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4822 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4823 struct ssh_channel *c;
4825 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4826 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4827 logevent("Forwarded connection refused by server");
4828 pfd_close(c->u.pfd.s);
4829 del234(ssh->channels, c);
4834 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4836 /* Remote side closes a channel. */
4837 unsigned i = ssh_pkt_getuint32(pktin);
4838 struct ssh_channel *c;
4839 c = find234(ssh->channels, &i, ssh_channelfind);
4840 if (c && !c->halfopen) {
4843 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4845 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4846 logevent("Forwarded X11 connection terminated");
4847 assert(c->u.x11.s != NULL);
4848 x11_close(c->u.x11.s);
4851 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4852 logevent("Forwarded port closed");
4853 assert(c->u.pfd.s != NULL);
4854 pfd_close(c->u.pfd.s);
4858 c->closes |= (closetype << 2); /* seen this message */
4859 if (!(c->closes & closetype)) {
4860 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4862 c->closes |= closetype; /* sent it too */
4865 if (c->closes == 15) {
4866 del234(ssh->channels, c);
4870 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4871 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4872 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4877 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4879 /* Data sent down one of our channels. */
4880 int i = ssh_pkt_getuint32(pktin);
4883 struct ssh_channel *c;
4885 ssh_pkt_getstring(pktin, &p, &len);
4887 c = find234(ssh->channels, &i, ssh_channelfind);
4892 bufsize = x11_send(c->u.x11.s, p, len);
4895 bufsize = pfd_send(c->u.pfd.s, p, len);
4898 /* Data for an agent message. Buffer it. */
4900 if (c->u.a.lensofar < 4) {
4901 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4902 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4906 c->u.a.lensofar += l;
4908 if (c->u.a.lensofar == 4) {
4910 4 + GET_32BIT(c->u.a.msglen);
4911 c->u.a.message = snewn(c->u.a.totallen,
4913 memcpy(c->u.a.message, c->u.a.msglen, 4);
4915 if (c->u.a.lensofar >= 4 && len > 0) {
4917 min(c->u.a.totallen - c->u.a.lensofar,
4919 memcpy(c->u.a.message + c->u.a.lensofar, p,
4923 c->u.a.lensofar += l;
4925 if (c->u.a.lensofar == c->u.a.totallen) {
4928 if (agent_query(c->u.a.message,
4931 ssh_agentf_callback, c))
4932 ssh_agentf_callback(c, reply, replylen);
4933 sfree(c->u.a.message);
4934 c->u.a.lensofar = 0;
4937 bufsize = 0; /* agent channels never back up */
4940 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
4941 c->throttling_conn = 1;
4942 ssh_throttle_conn(ssh, +1);
4947 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4949 ssh->exitcode = ssh_pkt_getuint32(pktin);
4950 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4951 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4953 * In case `helpful' firewalls or proxies tack
4954 * extra human-readable text on the end of the
4955 * session which we might mistake for another
4956 * encrypted packet, we close the session once
4957 * we've sent EXIT_CONFIRMATION.
4959 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
4962 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4963 static void ssh1_send_ttymode(void *data, char *mode, char *val)
4965 struct Packet *pktout = (struct Packet *)data;
4967 unsigned int arg = 0;
4968 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
4969 if (i == lenof(ssh_ttymodes)) return;
4970 switch (ssh_ttymodes[i].type) {
4972 arg = ssh_tty_parse_specchar(val);
4975 arg = ssh_tty_parse_boolean(val);
4978 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
4979 ssh2_pkt_addbyte(pktout, arg);
4983 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4984 struct Packet *pktin)
4986 crBegin(ssh->do_ssh1_connection_crstate);
4988 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4989 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4990 ssh1_smsg_stdout_stderr_data;
4992 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4993 ssh1_msg_channel_open_confirmation;
4994 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4995 ssh1_msg_channel_open_failure;
4996 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4997 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4998 ssh1_msg_channel_close;
4999 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5000 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5002 if (ssh->cfg.agentfwd && agent_exists()) {
5003 logevent("Requesting agent forwarding");
5004 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5008 if (pktin->type != SSH1_SMSG_SUCCESS
5009 && pktin->type != SSH1_SMSG_FAILURE) {
5010 bombout(("Protocol confusion"));
5012 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5013 logevent("Agent forwarding refused");
5015 logevent("Agent forwarding enabled");
5016 ssh->agentfwd_enabled = TRUE;
5017 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5021 if (ssh->cfg.x11_forward &&
5022 (ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
5023 ssh->cfg.x11_auth, &ssh->cfg))) {
5024 logevent("Requesting X11 forwarding");
5026 * Note that while we blank the X authentication data here, we don't
5027 * take any special action to blank the start of an X11 channel,
5028 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5029 * without having session blanking enabled is likely to leak your
5030 * cookie into the log.
5032 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5033 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5034 PKT_STR, ssh->x11disp->remoteauthprotoname,
5036 PKT_STR, ssh->x11disp->remoteauthdatastring,
5038 PKT_INT, ssh->x11disp->screennum,
5041 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5042 PKT_STR, ssh->x11disp->remoteauthprotoname,
5044 PKT_STR, ssh->x11disp->remoteauthdatastring,
5051 if (pktin->type != SSH1_SMSG_SUCCESS
5052 && pktin->type != SSH1_SMSG_FAILURE) {
5053 bombout(("Protocol confusion"));
5055 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5056 logevent("X11 forwarding refused");
5058 logevent("X11 forwarding enabled");
5059 ssh->X11_fwd_enabled = TRUE;
5060 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5064 ssh_setup_portfwd(ssh, &ssh->cfg);
5065 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5067 if (!ssh->cfg.nopty) {
5069 /* Unpick the terminal-speed string. */
5070 /* XXX perhaps we should allow no speeds to be sent. */
5071 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5072 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
5073 /* Send the pty request. */
5074 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5075 ssh_pkt_addstring(pkt, ssh->cfg.termtype);
5076 ssh_pkt_adduint32(pkt, ssh->term_height);
5077 ssh_pkt_adduint32(pkt, ssh->term_width);
5078 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5079 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5080 parse_ttymodes(ssh, ssh->cfg.ttymodes,
5081 ssh1_send_ttymode, (void *)pkt);
5082 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5083 ssh_pkt_adduint32(pkt, ssh->ispeed);
5084 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5085 ssh_pkt_adduint32(pkt, ssh->ospeed);
5086 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5088 ssh->state = SSH_STATE_INTERMED;
5092 if (pktin->type != SSH1_SMSG_SUCCESS
5093 && pktin->type != SSH1_SMSG_FAILURE) {
5094 bombout(("Protocol confusion"));
5096 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5097 c_write_str(ssh, "Server refused to allocate pty\r\n");
5098 ssh->editing = ssh->echoing = 1;
5100 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5101 ssh->ospeed, ssh->ispeed);
5103 ssh->editing = ssh->echoing = 1;
5106 if (ssh->cfg.compression) {
5107 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5111 if (pktin->type != SSH1_SMSG_SUCCESS
5112 && pktin->type != SSH1_SMSG_FAILURE) {
5113 bombout(("Protocol confusion"));
5115 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5116 c_write_str(ssh, "Server refused to compress\r\n");
5118 logevent("Started compression");
5119 ssh->v1_compressing = TRUE;
5120 ssh->cs_comp_ctx = zlib_compress_init();
5121 logevent("Initialised zlib (RFC1950) compression");
5122 ssh->sc_comp_ctx = zlib_decompress_init();
5123 logevent("Initialised zlib (RFC1950) decompression");
5127 * Start the shell or command.
5129 * Special case: if the first-choice command is an SSH-2
5130 * subsystem (hence not usable here) and the second choice
5131 * exists, we fall straight back to that.
5134 char *cmd = ssh->cfg.remote_cmd_ptr;
5136 if (!cmd) cmd = ssh->cfg.remote_cmd;
5138 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
5139 cmd = ssh->cfg.remote_cmd_ptr2;
5140 ssh->fallback_cmd = TRUE;
5143 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5145 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5146 logevent("Started session");
5149 ssh->state = SSH_STATE_SESSION;
5150 if (ssh->size_needed)
5151 ssh_size(ssh, ssh->term_width, ssh->term_height);
5152 if (ssh->eof_needed)
5153 ssh_special(ssh, TS_EOF);
5156 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5158 ssh->channels = newtree234(ssh_channelcmp);
5162 * By this point, most incoming packets are already being
5163 * handled by the dispatch table, and we need only pay
5164 * attention to the unusual ones.
5169 if (pktin->type == SSH1_SMSG_SUCCESS) {
5170 /* may be from EXEC_SHELL on some servers */
5171 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5172 /* may be from EXEC_SHELL on some servers
5173 * if no pty is available or in other odd cases. Ignore */
5175 bombout(("Strange packet received: type %d", pktin->type));
5180 int len = min(inlen, 512);
5181 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5182 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5183 PKTT_OTHER, PKT_END);
5194 * Handle the top-level SSH-2 protocol.
5196 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5201 ssh_pkt_getstring(pktin, &msg, &msglen);
5202 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5205 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5207 /* log reason code in disconnect message */
5211 ssh_pkt_getstring(pktin, &msg, &msglen);
5212 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5215 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5217 /* Do nothing, because we're ignoring it! Duhh. */
5220 static void ssh1_protocol_setup(Ssh ssh)
5225 * Most messages are handled by the coroutines.
5227 for (i = 0; i < 256; i++)
5228 ssh->packet_dispatch[i] = NULL;
5231 * These special message types we install handlers for.
5233 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5234 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5235 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5238 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5239 struct Packet *pktin)
5241 unsigned char *in=(unsigned char*)vin;
5242 if (ssh->state == SSH_STATE_CLOSED)
5245 if (pktin && ssh->packet_dispatch[pktin->type]) {
5246 ssh->packet_dispatch[pktin->type](ssh, pktin);
5250 if (!ssh->protocol_initial_phase_done) {
5251 if (do_ssh1_login(ssh, in, inlen, pktin))
5252 ssh->protocol_initial_phase_done = TRUE;
5257 do_ssh1_connection(ssh, in, inlen, pktin);
5261 * Utility routine for decoding comma-separated strings in KEXINIT.
5263 static int in_commasep_string(char *needle, char *haystack, int haylen)
5266 if (!needle || !haystack) /* protect against null pointers */
5268 needlen = strlen(needle);
5271 * Is it at the start of the string?
5273 if (haylen >= needlen && /* haystack is long enough */
5274 !memcmp(needle, haystack, needlen) && /* initial match */
5275 (haylen == needlen || haystack[needlen] == ',')
5276 /* either , or EOS follows */
5280 * If not, search for the next comma and resume after that.
5281 * If no comma found, terminate.
5283 while (haylen > 0 && *haystack != ',')
5284 haylen--, haystack++;
5287 haylen--, haystack++; /* skip over comma itself */
5292 * Similar routine for checking whether we have the first string in a list.
5294 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5297 if (!needle || !haystack) /* protect against null pointers */
5299 needlen = strlen(needle);
5301 * Is it at the start of the string?
5303 if (haylen >= needlen && /* haystack is long enough */
5304 !memcmp(needle, haystack, needlen) && /* initial match */
5305 (haylen == needlen || haystack[needlen] == ',')
5306 /* either , or EOS follows */
5314 * SSH-2 key creation method.
5315 * (Currently assumes 2 lots of any hash are sufficient to generate
5316 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5318 #define SSH2_MKKEY_ITERS (2)
5319 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5320 unsigned char *keyspace)
5322 const struct ssh_hash *h = ssh->kex->hash;
5324 /* First hlen bytes. */
5326 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5327 hash_mpint(h, s, K);
5328 h->bytes(s, H, h->hlen);
5329 h->bytes(s, &chr, 1);
5330 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5331 h->final(s, keyspace);
5332 /* Next hlen bytes. */
5334 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5335 hash_mpint(h, s, K);
5336 h->bytes(s, H, h->hlen);
5337 h->bytes(s, keyspace, h->hlen);
5338 h->final(s, keyspace + h->hlen);
5342 * Handle the SSH-2 transport layer.
5344 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5345 struct Packet *pktin)
5347 unsigned char *in = (unsigned char *)vin;
5348 struct do_ssh2_transport_state {
5349 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5350 Bignum p, g, e, f, K;
5353 int kex_init_value, kex_reply_value;
5354 const struct ssh_mac **maclist;
5356 const struct ssh2_cipher *cscipher_tobe;
5357 const struct ssh2_cipher *sccipher_tobe;
5358 const struct ssh_mac *csmac_tobe;
5359 const struct ssh_mac *scmac_tobe;
5360 const struct ssh_compress *cscomp_tobe;
5361 const struct ssh_compress *sccomp_tobe;
5362 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5363 int hostkeylen, siglen, rsakeylen;
5364 void *hkey; /* actual host key */
5365 void *rsakey; /* for RSA kex */
5366 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5367 int n_preferred_kex;
5368 const struct ssh_kexes *preferred_kex[KEX_MAX];
5369 int n_preferred_ciphers;
5370 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5371 const struct ssh_compress *preferred_comp;
5372 int got_session_id, activated_authconn;
5373 struct Packet *pktout;
5378 crState(do_ssh2_transport_state);
5380 crBegin(ssh->do_ssh2_transport_crstate);
5382 s->cscipher_tobe = s->sccipher_tobe = NULL;
5383 s->csmac_tobe = s->scmac_tobe = NULL;
5384 s->cscomp_tobe = s->sccomp_tobe = NULL;
5386 s->got_session_id = s->activated_authconn = FALSE;
5389 * Be prepared to work around the buggy MAC problem.
5391 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5392 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5394 s->maclist = macs, s->nmacs = lenof(macs);
5397 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5399 int i, j, commalist_started;
5402 * Set up the preferred key exchange. (NULL => warn below here)
5404 s->n_preferred_kex = 0;
5405 for (i = 0; i < KEX_MAX; i++) {
5406 switch (ssh->cfg.ssh_kexlist[i]) {
5408 s->preferred_kex[s->n_preferred_kex++] =
5409 &ssh_diffiehellman_gex;
5412 s->preferred_kex[s->n_preferred_kex++] =
5413 &ssh_diffiehellman_group14;
5416 s->preferred_kex[s->n_preferred_kex++] =
5417 &ssh_diffiehellman_group1;
5420 s->preferred_kex[s->n_preferred_kex++] =
5424 /* Flag for later. Don't bother if it's the last in
5426 if (i < KEX_MAX - 1) {
5427 s->preferred_kex[s->n_preferred_kex++] = NULL;
5434 * Set up the preferred ciphers. (NULL => warn below here)
5436 s->n_preferred_ciphers = 0;
5437 for (i = 0; i < CIPHER_MAX; i++) {
5438 switch (ssh->cfg.ssh_cipherlist[i]) {
5439 case CIPHER_BLOWFISH:
5440 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5443 if (ssh->cfg.ssh2_des_cbc) {
5444 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5448 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5451 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5453 case CIPHER_ARCFOUR:
5454 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5457 /* Flag for later. Don't bother if it's the last in
5459 if (i < CIPHER_MAX - 1) {
5460 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5467 * Set up preferred compression.
5469 if (ssh->cfg.compression)
5470 s->preferred_comp = &ssh_zlib;
5472 s->preferred_comp = &ssh_comp_none;
5475 * Enable queueing of outgoing auth- or connection-layer
5476 * packets while we are in the middle of a key exchange.
5478 ssh->queueing = TRUE;
5481 * Flag that KEX is in progress.
5483 ssh->kex_in_progress = TRUE;
5486 * Construct and send our key exchange packet.
5488 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5489 for (i = 0; i < 16; i++)
5490 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5491 /* List key exchange algorithms. */
5492 ssh2_pkt_addstring_start(s->pktout);
5493 commalist_started = 0;
5494 for (i = 0; i < s->n_preferred_kex; i++) {
5495 const struct ssh_kexes *k = s->preferred_kex[i];
5496 if (!k) continue; /* warning flag */
5497 for (j = 0; j < k->nkexes; j++) {
5498 if (commalist_started)
5499 ssh2_pkt_addstring_str(s->pktout, ",");
5500 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5501 commalist_started = 1;
5504 /* List server host key algorithms. */
5505 ssh2_pkt_addstring_start(s->pktout);
5506 for (i = 0; i < lenof(hostkey_algs); i++) {
5507 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5508 if (i < lenof(hostkey_algs) - 1)
5509 ssh2_pkt_addstring_str(s->pktout, ",");
5511 /* List client->server encryption algorithms. */
5512 ssh2_pkt_addstring_start(s->pktout);
5513 commalist_started = 0;
5514 for (i = 0; i < s->n_preferred_ciphers; i++) {
5515 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5516 if (!c) continue; /* warning flag */
5517 for (j = 0; j < c->nciphers; j++) {
5518 if (commalist_started)
5519 ssh2_pkt_addstring_str(s->pktout, ",");
5520 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5521 commalist_started = 1;
5524 /* List server->client encryption algorithms. */
5525 ssh2_pkt_addstring_start(s->pktout);
5526 commalist_started = 0;
5527 for (i = 0; i < s->n_preferred_ciphers; i++) {
5528 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5529 if (!c) continue; /* warning flag */
5530 for (j = 0; j < c->nciphers; j++) {
5531 if (commalist_started)
5532 ssh2_pkt_addstring_str(s->pktout, ",");
5533 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5534 commalist_started = 1;
5537 /* List client->server MAC algorithms. */
5538 ssh2_pkt_addstring_start(s->pktout);
5539 for (i = 0; i < s->nmacs; i++) {
5540 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5541 if (i < s->nmacs - 1)
5542 ssh2_pkt_addstring_str(s->pktout, ",");
5544 /* List server->client MAC algorithms. */
5545 ssh2_pkt_addstring_start(s->pktout);
5546 for (i = 0; i < s->nmacs; i++) {
5547 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5548 if (i < s->nmacs - 1)
5549 ssh2_pkt_addstring_str(s->pktout, ",");
5551 /* List client->server compression algorithms. */
5552 ssh2_pkt_addstring_start(s->pktout);
5553 assert(lenof(compressions) > 1);
5554 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5555 for (i = 0; i < lenof(compressions); i++) {
5556 const struct ssh_compress *c = compressions[i];
5557 if (c != s->preferred_comp) {
5558 ssh2_pkt_addstring_str(s->pktout, ",");
5559 ssh2_pkt_addstring_str(s->pktout, c->name);
5562 /* List server->client compression algorithms. */
5563 ssh2_pkt_addstring_start(s->pktout);
5564 assert(lenof(compressions) > 1);
5565 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5566 for (i = 0; i < lenof(compressions); i++) {
5567 const struct ssh_compress *c = compressions[i];
5568 if (c != s->preferred_comp) {
5569 ssh2_pkt_addstring_str(s->pktout, ",");
5570 ssh2_pkt_addstring_str(s->pktout, c->name);
5573 /* List client->server languages. Empty list. */
5574 ssh2_pkt_addstring_start(s->pktout);
5575 /* List server->client languages. Empty list. */
5576 ssh2_pkt_addstring_start(s->pktout);
5577 /* First KEX packet does _not_ follow, because we're not that brave. */
5578 ssh2_pkt_addbool(s->pktout, FALSE);
5580 ssh2_pkt_adduint32(s->pktout, 0);
5583 s->our_kexinitlen = s->pktout->length - 5;
5584 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5585 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5587 ssh2_pkt_send_noqueue(ssh, s->pktout);
5593 * Now examine the other side's KEXINIT to see what we're up
5597 char *str, *preferred;
5600 if (pktin->type != SSH2_MSG_KEXINIT) {
5601 bombout(("expected key exchange packet from server"));
5605 ssh->hostkey = NULL;
5606 s->cscipher_tobe = NULL;
5607 s->sccipher_tobe = NULL;
5608 s->csmac_tobe = NULL;
5609 s->scmac_tobe = NULL;
5610 s->cscomp_tobe = NULL;
5611 s->sccomp_tobe = NULL;
5612 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5614 pktin->savedpos += 16; /* skip garbage cookie */
5615 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5618 for (i = 0; i < s->n_preferred_kex; i++) {
5619 const struct ssh_kexes *k = s->preferred_kex[i];
5623 for (j = 0; j < k->nkexes; j++) {
5624 if (!preferred) preferred = k->list[j]->name;
5625 if (in_commasep_string(k->list[j]->name, str, len)) {
5626 ssh->kex = k->list[j];
5635 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5636 str ? str : "(null)"));
5640 * Note that the server's guess is considered wrong if it doesn't match
5641 * the first algorithm in our list, even if it's still the algorithm
5644 s->guessok = first_in_commasep_string(preferred, str, len);
5645 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5646 for (i = 0; i < lenof(hostkey_algs); i++) {
5647 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5648 ssh->hostkey = hostkey_algs[i];
5652 s->guessok = s->guessok &&
5653 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5654 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5655 for (i = 0; i < s->n_preferred_ciphers; i++) {
5656 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5658 s->warn_cscipher = TRUE;
5660 for (j = 0; j < c->nciphers; j++) {
5661 if (in_commasep_string(c->list[j]->name, str, len)) {
5662 s->cscipher_tobe = c->list[j];
5667 if (s->cscipher_tobe)
5670 if (!s->cscipher_tobe) {
5671 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5672 str ? str : "(null)"));
5676 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5677 for (i = 0; i < s->n_preferred_ciphers; i++) {
5678 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5680 s->warn_sccipher = TRUE;
5682 for (j = 0; j < c->nciphers; j++) {
5683 if (in_commasep_string(c->list[j]->name, str, len)) {
5684 s->sccipher_tobe = c->list[j];
5689 if (s->sccipher_tobe)
5692 if (!s->sccipher_tobe) {
5693 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5694 str ? str : "(null)"));
5698 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5699 for (i = 0; i < s->nmacs; i++) {
5700 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5701 s->csmac_tobe = s->maclist[i];
5705 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5706 for (i = 0; i < s->nmacs; i++) {
5707 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5708 s->scmac_tobe = s->maclist[i];
5712 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5713 for (i = 0; i < lenof(compressions) + 1; i++) {
5714 const struct ssh_compress *c =
5715 i == 0 ? s->preferred_comp : compressions[i - 1];
5716 if (in_commasep_string(c->name, str, len)) {
5721 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5722 for (i = 0; i < lenof(compressions) + 1; i++) {
5723 const struct ssh_compress *c =
5724 i == 0 ? s->preferred_comp : compressions[i - 1];
5725 if (in_commasep_string(c->name, str, len)) {
5730 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5731 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5732 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5735 ssh_set_frozen(ssh, 1);
5736 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5738 ssh_dialog_callback, ssh);
5739 if (s->dlgret < 0) {
5743 bombout(("Unexpected data from server while"
5744 " waiting for user response"));
5747 } while (pktin || inlen > 0);
5748 s->dlgret = ssh->user_response;
5750 ssh_set_frozen(ssh, 0);
5751 if (s->dlgret == 0) {
5752 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5758 if (s->warn_cscipher) {
5759 ssh_set_frozen(ssh, 1);
5760 s->dlgret = askalg(ssh->frontend,
5761 "client-to-server cipher",
5762 s->cscipher_tobe->name,
5763 ssh_dialog_callback, ssh);
5764 if (s->dlgret < 0) {
5768 bombout(("Unexpected data from server while"
5769 " waiting for user response"));
5772 } while (pktin || inlen > 0);
5773 s->dlgret = ssh->user_response;
5775 ssh_set_frozen(ssh, 0);
5776 if (s->dlgret == 0) {
5777 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5783 if (s->warn_sccipher) {
5784 ssh_set_frozen(ssh, 1);
5785 s->dlgret = askalg(ssh->frontend,
5786 "server-to-client cipher",
5787 s->sccipher_tobe->name,
5788 ssh_dialog_callback, ssh);
5789 if (s->dlgret < 0) {
5793 bombout(("Unexpected data from server while"
5794 " waiting for user response"));
5797 } while (pktin || inlen > 0);
5798 s->dlgret = ssh->user_response;
5800 ssh_set_frozen(ssh, 0);
5801 if (s->dlgret == 0) {
5802 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5808 ssh->exhash = ssh->kex->hash->init();
5809 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5810 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5811 hash_string(ssh->kex->hash, ssh->exhash,
5812 s->our_kexinit, s->our_kexinitlen);
5813 sfree(s->our_kexinit);
5814 if (pktin->length > 5)
5815 hash_string(ssh->kex->hash, ssh->exhash,
5816 pktin->data + 5, pktin->length - 5);
5818 if (s->ignorepkt) /* first_kex_packet_follows */
5819 crWaitUntil(pktin); /* Ignore packet */
5822 if (ssh->kex->main_type == KEXTYPE_DH) {
5824 * Work out the number of bits of key we will need from the
5825 * key exchange. We start with the maximum key length of
5831 csbits = s->cscipher_tobe->keylen;
5832 scbits = s->sccipher_tobe->keylen;
5833 s->nbits = (csbits > scbits ? csbits : scbits);
5835 /* The keys only have hlen-bit entropy, since they're based on
5836 * a hash. So cap the key size at hlen bits. */
5837 if (s->nbits > ssh->kex->hash->hlen * 8)
5838 s->nbits = ssh->kex->hash->hlen * 8;
5841 * If we're doing Diffie-Hellman group exchange, start by
5842 * requesting a group.
5844 if (!ssh->kex->pdata) {
5845 logevent("Doing Diffie-Hellman group exchange");
5846 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5848 * Work out how big a DH group we will need to allow that
5851 s->pbits = 512 << ((s->nbits - 1) / 64);
5852 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5853 ssh2_pkt_adduint32(s->pktout, s->pbits);
5854 ssh2_pkt_send_noqueue(ssh, s->pktout);
5857 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5858 bombout(("expected key exchange group packet from server"));
5861 s->p = ssh2_pkt_getmp(pktin);
5862 s->g = ssh2_pkt_getmp(pktin);
5863 if (!s->p || !s->g) {
5864 bombout(("unable to read mp-ints from incoming group packet"));
5867 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5868 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5869 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5871 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5872 ssh->kex_ctx = dh_setup_group(ssh->kex);
5873 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5874 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5875 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5876 ssh->kex->groupname);
5879 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5880 ssh->kex->hash->text_name);
5882 * Now generate and send e for Diffie-Hellman.
5884 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5885 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5886 s->pktout = ssh2_pkt_init(s->kex_init_value);
5887 ssh2_pkt_addmp(s->pktout, s->e);
5888 ssh2_pkt_send_noqueue(ssh, s->pktout);
5890 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5892 if (pktin->type != s->kex_reply_value) {
5893 bombout(("expected key exchange reply packet from server"));
5896 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5897 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5898 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5899 s->f = ssh2_pkt_getmp(pktin);
5901 bombout(("unable to parse key exchange reply packet"));
5904 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5906 s->K = dh_find_K(ssh->kex_ctx, s->f);
5908 /* We assume everything from now on will be quick, and it might
5909 * involve user interaction. */
5910 set_busy_status(ssh->frontend, BUSY_NOT);
5912 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5913 if (!ssh->kex->pdata) {
5914 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
5915 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
5916 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
5918 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
5919 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
5921 dh_cleanup(ssh->kex_ctx);
5923 if (!ssh->kex->pdata) {
5928 logeventf(ssh, "Doing RSA key exchange with hash %s",
5929 ssh->kex->hash->text_name);
5930 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
5932 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5936 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
5937 bombout(("expected RSA public key packet from server"));
5941 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5942 hash_string(ssh->kex->hash, ssh->exhash,
5943 s->hostkeydata, s->hostkeylen);
5944 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5948 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
5949 s->rsakeydata = snewn(s->rsakeylen, char);
5950 memcpy(s->rsakeydata, keydata, s->rsakeylen);
5953 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
5955 sfree(s->rsakeydata);
5956 bombout(("unable to parse RSA public key from server"));
5960 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
5963 * Next, set up a shared secret K, of precisely KLEN -
5964 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5965 * RSA key modulus and HLEN is the bit length of the hash
5969 int klen = ssh_rsakex_klen(s->rsakey);
5970 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
5972 unsigned char *kstr1, *kstr2, *outstr;
5973 int kstr1len, kstr2len, outstrlen;
5975 s->K = bn_power_2(nbits - 1);
5977 for (i = 0; i < nbits; i++) {
5979 byte = random_byte();
5981 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
5985 * Encode this as an mpint.
5987 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
5988 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
5989 PUT_32BIT(kstr2, kstr1len);
5990 memcpy(kstr2 + 4, kstr1, kstr1len);
5993 * Encrypt it with the given RSA key.
5995 outstrlen = (klen + 7) / 8;
5996 outstr = snewn(outstrlen, unsigned char);
5997 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
5998 outstr, outstrlen, s->rsakey);
6001 * And send it off in a return packet.
6003 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6004 ssh2_pkt_addstring_start(s->pktout);
6005 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6006 ssh2_pkt_send_noqueue(ssh, s->pktout);
6008 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6015 ssh_rsakex_freekey(s->rsakey);
6018 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6019 sfree(s->rsakeydata);
6020 bombout(("expected signature packet from server"));
6024 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6026 sfree(s->rsakeydata);
6029 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6030 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6031 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6033 ssh->kex_ctx = NULL;
6036 debug(("Exchange hash is:\n"));
6037 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6041 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6042 (char *)s->exchange_hash,
6043 ssh->kex->hash->hlen)) {
6044 bombout(("Server's host key did not match the signature supplied"));
6049 * Authenticate remote host: verify host key. (We've already
6050 * checked the signature of the exchange hash.)
6052 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6053 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6054 ssh_set_frozen(ssh, 1);
6055 s->dlgret = verify_ssh_host_key(ssh->frontend,
6056 ssh->savedhost, ssh->savedport,
6057 ssh->hostkey->keytype, s->keystr,
6059 ssh_dialog_callback, ssh);
6060 if (s->dlgret < 0) {
6064 bombout(("Unexpected data from server while waiting"
6065 " for user host key response"));
6068 } while (pktin || inlen > 0);
6069 s->dlgret = ssh->user_response;
6071 ssh_set_frozen(ssh, 0);
6072 if (s->dlgret == 0) {
6073 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6077 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6078 logevent("Host key fingerprint is:");
6079 logevent(s->fingerprint);
6081 sfree(s->fingerprint);
6083 ssh->hostkey->freekey(s->hkey);
6086 * The exchange hash from the very first key exchange is also
6087 * the session id, used in session key construction and
6090 if (!s->got_session_id) {
6091 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6092 memcpy(ssh->v2_session_id, s->exchange_hash,
6093 sizeof(s->exchange_hash));
6094 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6095 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6096 s->got_session_id = TRUE;
6100 * Send SSH2_MSG_NEWKEYS.
6102 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6103 ssh2_pkt_send_noqueue(ssh, s->pktout);
6104 ssh->outgoing_data_size = 0; /* start counting from here */
6107 * We've sent client NEWKEYS, so create and initialise
6108 * client-to-server session keys.
6110 if (ssh->cs_cipher_ctx)
6111 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6112 ssh->cscipher = s->cscipher_tobe;
6113 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6115 if (ssh->cs_mac_ctx)
6116 ssh->csmac->free_context(ssh->cs_mac_ctx);
6117 ssh->csmac = s->csmac_tobe;
6118 ssh->cs_mac_ctx = ssh->csmac->make_context();
6120 if (ssh->cs_comp_ctx)
6121 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6122 ssh->cscomp = s->cscomp_tobe;
6123 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6126 * Set IVs on client-to-server keys. Here we use the exchange
6127 * hash from the _first_ key exchange.
6130 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6131 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6132 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6133 assert((ssh->cscipher->keylen+7) / 8 <=
6134 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6135 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6136 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6137 assert(ssh->cscipher->blksize <=
6138 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6139 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6140 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6141 assert(ssh->csmac->len <=
6142 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6143 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6144 memset(keyspace, 0, sizeof(keyspace));
6147 logeventf(ssh, "Initialised %.200s client->server encryption",
6148 ssh->cscipher->text_name);
6149 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6150 ssh->csmac->text_name);
6151 if (ssh->cscomp->text_name)
6152 logeventf(ssh, "Initialised %s compression",
6153 ssh->cscomp->text_name);
6156 * Now our end of the key exchange is complete, we can send all
6157 * our queued higher-layer packets.
6159 ssh->queueing = FALSE;
6160 ssh2_pkt_queuesend(ssh);
6163 * Expect SSH2_MSG_NEWKEYS from server.
6166 if (pktin->type != SSH2_MSG_NEWKEYS) {
6167 bombout(("expected new-keys packet from server"));
6170 ssh->incoming_data_size = 0; /* start counting from here */
6173 * We've seen server NEWKEYS, so create and initialise
6174 * server-to-client session keys.
6176 if (ssh->sc_cipher_ctx)
6177 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6178 ssh->sccipher = s->sccipher_tobe;
6179 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6181 if (ssh->sc_mac_ctx)
6182 ssh->scmac->free_context(ssh->sc_mac_ctx);
6183 ssh->scmac = s->scmac_tobe;
6184 ssh->sc_mac_ctx = ssh->scmac->make_context();
6186 if (ssh->sc_comp_ctx)
6187 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6188 ssh->sccomp = s->sccomp_tobe;
6189 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6192 * Set IVs on server-to-client keys. Here we use the exchange
6193 * hash from the _first_ key exchange.
6196 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6197 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6198 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6199 assert((ssh->sccipher->keylen+7) / 8 <=
6200 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6201 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6202 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6203 assert(ssh->sccipher->blksize <=
6204 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6205 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6206 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6207 assert(ssh->scmac->len <=
6208 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6209 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6210 memset(keyspace, 0, sizeof(keyspace));
6212 logeventf(ssh, "Initialised %.200s server->client encryption",
6213 ssh->sccipher->text_name);
6214 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6215 ssh->scmac->text_name);
6216 if (ssh->sccomp->text_name)
6217 logeventf(ssh, "Initialised %s decompression",
6218 ssh->sccomp->text_name);
6221 * Free shared secret.
6226 * Key exchange is over. Loop straight back round if we have a
6227 * deferred rekey reason.
6229 if (ssh->deferred_rekey_reason) {
6230 logevent(ssh->deferred_rekey_reason);
6232 ssh->deferred_rekey_reason = NULL;
6233 goto begin_key_exchange;
6237 * Otherwise, schedule a timer for our next rekey.
6239 ssh->kex_in_progress = FALSE;
6240 ssh->last_rekey = GETTICKCOUNT();
6241 if (ssh->cfg.ssh_rekey_time != 0)
6242 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6246 * If this is the first key exchange phase, we must pass the
6247 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6248 * wants to see it but because it will need time to initialise
6249 * itself before it sees an actual packet. In subsequent key
6250 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6251 * it would only confuse the layer above.
6253 if (s->activated_authconn) {
6256 s->activated_authconn = TRUE;
6259 * Now we're encrypting. Begin returning 1 to the protocol main
6260 * function so that other things can run on top of the
6261 * transport. If we ever see a KEXINIT, we must go back to the
6264 * We _also_ go back to the start if we see pktin==NULL and
6265 * inlen==-1, because this is a special signal meaning
6266 * `initiate client-driven rekey', and `in' contains a message
6267 * giving the reason for the rekey.
6269 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6270 (!pktin && inlen == -1))) {
6275 logevent("Server initiated key re-exchange");
6278 * Special case: if the server bug is set that doesn't
6279 * allow rekeying, we give a different log message and
6280 * continue waiting. (If such a server _initiates_ a rekey,
6281 * we process it anyway!)
6283 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6284 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6286 /* Reset the counters, so that at least this message doesn't
6287 * hit the event log _too_ often. */
6288 ssh->outgoing_data_size = 0;
6289 ssh->incoming_data_size = 0;
6290 if (ssh->cfg.ssh_rekey_time != 0) {
6292 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6295 goto wait_for_rekey; /* this is utterly horrid */
6297 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6300 goto begin_key_exchange;
6306 * Add data to an SSH-2 channel output buffer.
6308 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6311 bufchain_add(&c->v.v2.outbuffer, buf, len);
6315 * Attempt to send data on an SSH-2 channel.
6317 static int ssh2_try_send(struct ssh_channel *c)
6320 struct Packet *pktout;
6322 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6325 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6326 if ((unsigned)len > c->v.v2.remwindow)
6327 len = c->v.v2.remwindow;
6328 if ((unsigned)len > c->v.v2.remmaxpkt)
6329 len = c->v.v2.remmaxpkt;
6330 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6331 ssh2_pkt_adduint32(pktout, c->remoteid);
6332 ssh2_pkt_addstring_start(pktout);
6333 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6334 ssh2_pkt_addstring_data(pktout, data, len);
6335 end_log_omission(ssh, pktout);
6336 ssh2_pkt_send(ssh, pktout);
6337 bufchain_consume(&c->v.v2.outbuffer, len);
6338 c->v.v2.remwindow -= len;
6342 * After having sent as much data as we can, return the amount
6345 return bufchain_size(&c->v.v2.outbuffer);
6348 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
6352 return; /* don't send on closing channels */
6353 bufsize = ssh2_try_send(c);
6356 case CHAN_MAINSESSION:
6357 /* stdin need not receive an unthrottle
6358 * notification since it will be polled */
6361 x11_unthrottle(c->u.x11.s);
6364 /* agent sockets are request/response and need no
6365 * buffer management */
6368 pfd_unthrottle(c->u.pfd.s);
6375 * Set up most of a new ssh_channel for SSH-2.
6377 static void ssh2_channel_init(struct ssh_channel *c)
6380 c->localid = alloc_channel_id(ssh);
6382 c->throttling_conn = FALSE;
6383 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6384 ssh->cfg.ssh_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6385 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6386 c->v.v2.throttle_state = UNTHROTTLED;
6387 bufchain_init(&c->v.v2.outbuffer);
6391 * Potentially enlarge the window on an SSH-2 channel.
6393 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6398 * Never send WINDOW_ADJUST for a channel that the remote side
6399 * already thinks it's closed; there's no point, since it won't
6400 * be sending any more data anyway.
6406 * If the remote end has a habit of ignoring maxpkt, limit the
6407 * window so that it has no choice (assuming it doesn't ignore the
6410 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6411 newwin = OUR_V2_MAXPKT;
6415 * Only send a WINDOW_ADJUST if there's significantly more window
6416 * available than the other end thinks there is. This saves us
6417 * sending a WINDOW_ADJUST for every character in a shell session.
6419 * "Significant" is arbitrarily defined as half the window size.
6421 if (newwin / 2 >= c->v.v2.locwindow) {
6422 struct Packet *pktout;
6426 * In order to keep track of how much window the client
6427 * actually has available, we'd like it to acknowledge each
6428 * WINDOW_ADJUST. We can't do that directly, so we accompany
6429 * it with a CHANNEL_REQUEST that has to be acknowledged.
6431 * This is only necessary if we're opening the window wide.
6432 * If we're not, then throughput is being constrained by
6433 * something other than the maximum window size anyway.
6435 * We also only send this if the main channel has finished its
6436 * initial CHANNEL_REQUESTs and installed the default
6437 * CHANNEL_FAILURE handler, so as not to risk giving it
6438 * unexpected CHANNEL_FAILUREs.
6440 if (newwin == c->v.v2.locmaxwin &&
6441 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6442 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6443 ssh2_pkt_adduint32(pktout, c->remoteid);
6444 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6445 ssh2_pkt_addbool(pktout, TRUE);
6446 ssh2_pkt_send(ssh, pktout);
6449 * CHANNEL_FAILURE doesn't come with any indication of
6450 * what message caused it, so we have to keep track of the
6451 * outstanding CHANNEL_REQUESTs ourselves.
6453 wa = snew(struct winadj);
6454 wa->size = newwin - c->v.v2.locwindow;
6456 if (!c->v.v2.winadj_head)
6457 c->v.v2.winadj_head = wa;
6459 c->v.v2.winadj_tail->next = wa;
6460 c->v.v2.winadj_tail = wa;
6461 if (c->v.v2.throttle_state != UNTHROTTLED)
6462 c->v.v2.throttle_state = UNTHROTTLING;
6464 /* Pretend the WINDOW_ADJUST was acked immediately. */
6465 c->v.v2.remlocwin = newwin;
6466 c->v.v2.throttle_state = THROTTLED;
6468 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6469 ssh2_pkt_adduint32(pktout, c->remoteid);
6470 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6471 ssh2_pkt_send(ssh, pktout);
6472 c->v.v2.locwindow = newwin;
6477 * Find the channel associated with a message. If there's no channel,
6478 * or it's not properly open, make a noise about it and return NULL.
6480 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6482 unsigned localid = ssh_pkt_getuint32(pktin);
6483 struct ssh_channel *c;
6485 c = find234(ssh->channels, &localid, ssh_channelfind);
6487 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6488 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6489 char *buf = dupprintf("Received %s for %s channel %u",
6490 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6492 c ? "half-open" : "nonexistent", localid);
6493 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6500 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6503 * This should never get called. All channel requests are either
6504 * sent with want_reply false or are sent before this handler gets
6507 struct ssh_channel *c;
6510 c = ssh2_channel_msg(ssh, pktin);
6513 wa = c->v.v2.winadj_head;
6515 ssh_disconnect(ssh, NULL, "Received SSH_MSG_CHANNEL_SUCCESS for "
6516 "\"winadj@putty.projects.tartarus.org\"",
6517 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6519 ssh_disconnect(ssh, NULL,
6520 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6521 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6524 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6527 * The only time this should get called is for "winadj@putty"
6528 * messages sent above. All other channel requests are either
6529 * sent with want_reply false or are sent before this handler gets
6532 struct ssh_channel *c;
6535 c = ssh2_channel_msg(ssh, pktin);
6538 wa = c->v.v2.winadj_head;
6540 ssh_disconnect(ssh, NULL,
6541 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6542 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6545 c->v.v2.winadj_head = wa->next;
6546 c->v.v2.remlocwin += wa->size;
6549 * winadj messages are only sent when the window is fully open, so
6550 * if we get an ack of one, we know any pending unthrottle is
6553 if (c->v.v2.throttle_state == UNTHROTTLING)
6554 c->v.v2.throttle_state = UNTHROTTLED;
6557 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6559 struct ssh_channel *c;
6560 c = ssh2_channel_msg(ssh, pktin);
6564 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6565 ssh2_try_send_and_unthrottle(c);
6569 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6573 struct ssh_channel *c;
6574 c = ssh2_channel_msg(ssh, pktin);
6577 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6578 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6579 return; /* extended but not stderr */
6580 ssh_pkt_getstring(pktin, &data, &length);
6583 c->v.v2.locwindow -= length;
6584 c->v.v2.remlocwin -= length;
6586 case CHAN_MAINSESSION:
6588 from_backend(ssh->frontend, pktin->type ==
6589 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6593 bufsize = x11_send(c->u.x11.s, data, length);
6596 bufsize = pfd_send(c->u.pfd.s, data, length);
6599 while (length > 0) {
6600 if (c->u.a.lensofar < 4) {
6601 unsigned int l = min(4 - c->u.a.lensofar,
6603 memcpy(c->u.a.msglen + c->u.a.lensofar,
6607 c->u.a.lensofar += l;
6609 if (c->u.a.lensofar == 4) {
6611 4 + GET_32BIT(c->u.a.msglen);
6612 c->u.a.message = snewn(c->u.a.totallen,
6614 memcpy(c->u.a.message, c->u.a.msglen, 4);
6616 if (c->u.a.lensofar >= 4 && length > 0) {
6618 min(c->u.a.totallen - c->u.a.lensofar,
6620 memcpy(c->u.a.message + c->u.a.lensofar,
6624 c->u.a.lensofar += l;
6626 if (c->u.a.lensofar == c->u.a.totallen) {
6629 if (agent_query(c->u.a.message,
6632 ssh_agentf_callback, c))
6633 ssh_agentf_callback(c, reply, replylen);
6634 sfree(c->u.a.message);
6635 c->u.a.lensofar = 0;
6642 * If it looks like the remote end hit the end of its window,
6643 * and we didn't want it to do that, think about using a
6646 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6647 c->v.v2.locmaxwin < 0x40000000)
6648 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6650 * If we are not buffering too much data,
6651 * enlarge the window again at the remote side.
6652 * If we are buffering too much, we may still
6653 * need to adjust the window if the server's
6656 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6657 c->v.v2.locmaxwin - bufsize : 0);
6659 * If we're either buffering way too much data, or if we're
6660 * buffering anything at all and we're in "simple" mode,
6661 * throttle the whole channel.
6663 if ((bufsize > c->v.v2.locmaxwin ||
6664 (ssh->cfg.ssh_simple && bufsize > 0)) &&
6665 !c->throttling_conn) {
6666 c->throttling_conn = 1;
6667 ssh_throttle_conn(ssh, +1);
6672 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6674 struct ssh_channel *c;
6676 c = ssh2_channel_msg(ssh, pktin);
6680 if (c->type == CHAN_X11) {
6682 * Remote EOF on an X11 channel means we should
6683 * wrap up and close the channel ourselves.
6685 x11_close(c->u.x11.s);
6688 } else if (c->type == CHAN_AGENT) {
6690 } else if (c->type == CHAN_SOCKDATA) {
6691 pfd_close(c->u.pfd.s);
6697 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6699 struct ssh_channel *c;
6700 struct Packet *pktout;
6702 c = ssh2_channel_msg(ssh, pktin);
6705 /* Do pre-close processing on the channel. */
6707 case CHAN_MAINSESSION:
6708 ssh->mainchan = NULL;
6709 update_specials_menu(ssh->frontend);
6712 if (c->u.x11.s != NULL)
6713 x11_close(c->u.x11.s);
6720 if (c->u.pfd.s != NULL)
6721 pfd_close(c->u.pfd.s);
6725 if (c->closes == 0) {
6726 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6727 ssh2_pkt_adduint32(pktout, c->remoteid);
6728 ssh2_pkt_send(ssh, pktout);
6730 del234(ssh->channels, c);
6731 bufchain_clear(&c->v.v2.outbuffer);
6735 * See if that was the last channel left open.
6736 * (This is only our termination condition if we're
6737 * not running in -N mode.)
6739 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6741 * We used to send SSH_MSG_DISCONNECT here,
6742 * because I'd believed that _every_ conforming
6743 * SSH-2 connection had to end with a disconnect
6744 * being sent by at least one side; apparently
6745 * I was wrong and it's perfectly OK to
6746 * unceremoniously slam the connection shut
6747 * when you're done, and indeed OpenSSH feels
6748 * this is more polite than sending a
6749 * DISCONNECT. So now we don't.
6751 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6755 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6757 struct ssh_channel *c;
6758 struct Packet *pktout;
6760 c = ssh2_channel_msg(ssh, pktin);
6763 if (c->type != CHAN_SOCKDATA_DORMANT)
6764 return; /* dunno why they're confirming this */
6765 c->remoteid = ssh_pkt_getuint32(pktin);
6766 c->halfopen = FALSE;
6767 c->type = CHAN_SOCKDATA;
6768 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6769 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6771 pfd_confirm(c->u.pfd.s);
6774 * We have a pending close on this channel,
6775 * which we decided on before the server acked
6776 * the channel open. So now we know the
6777 * remoteid, we can close it again.
6779 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6780 ssh2_pkt_adduint32(pktout, c->remoteid);
6781 ssh2_pkt_send(ssh, pktout);
6785 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
6787 static const char *const reasons[] = {
6788 "<unknown reason code>",
6789 "Administratively prohibited",
6791 "Unknown channel type",
6792 "Resource shortage",
6794 unsigned reason_code;
6795 char *reason_string;
6797 struct ssh_channel *c;
6798 c = ssh2_channel_msg(ssh, pktin);
6801 if (c->type != CHAN_SOCKDATA_DORMANT)
6802 return; /* dunno why they're failing this */
6804 reason_code = ssh_pkt_getuint32(pktin);
6805 if (reason_code >= lenof(reasons))
6806 reason_code = 0; /* ensure reasons[reason_code] in range */
6807 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6808 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
6809 reasons[reason_code], reason_length, reason_string);
6811 pfd_close(c->u.pfd.s);
6813 del234(ssh->channels, c);
6817 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
6820 int typelen, want_reply;
6821 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6822 struct ssh_channel *c;
6823 struct Packet *pktout;
6825 c = ssh2_channel_msg(ssh, pktin);
6828 ssh_pkt_getstring(pktin, &type, &typelen);
6829 want_reply = ssh2_pkt_getbool(pktin);
6832 * Having got the channel number, we now look at
6833 * the request type string to see if it's something
6836 if (c == ssh->mainchan) {
6838 * We recognise "exit-status" and "exit-signal" on
6839 * the primary channel.
6841 if (typelen == 11 &&
6842 !memcmp(type, "exit-status", 11)) {
6844 ssh->exitcode = ssh_pkt_getuint32(pktin);
6845 logeventf(ssh, "Server sent command exit status %d",
6847 reply = SSH2_MSG_CHANNEL_SUCCESS;
6849 } else if (typelen == 11 &&
6850 !memcmp(type, "exit-signal", 11)) {
6852 int is_plausible = TRUE, is_int = FALSE;
6853 char *fmt_sig = "", *fmt_msg = "";
6855 int msglen = 0, core = FALSE;
6856 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6857 * provide an `int' for the signal, despite its
6858 * having been a `string' in the drafts of RFC 4254 since at
6859 * least 2001. (Fixed in session.c 1.147.) Try to
6860 * infer which we can safely parse it as. */
6862 unsigned char *p = pktin->body +
6864 long len = pktin->length - pktin->savedpos;
6865 unsigned long num = GET_32BIT(p); /* what is it? */
6866 /* If it's 0, it hardly matters; assume string */
6870 int maybe_int = FALSE, maybe_str = FALSE;
6871 #define CHECK_HYPOTHESIS(offset, result) \
6874 if (q >= 0 && q+4 <= len) { \
6875 q = q + 4 + GET_32BIT(p+q); \
6876 if (q >= 0 && q+4 <= len && \
6877 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6881 CHECK_HYPOTHESIS(4+1, maybe_int);
6882 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6883 #undef CHECK_HYPOTHESIS
6884 if (maybe_int && !maybe_str)
6886 else if (!maybe_int && maybe_str)
6889 /* Crikey. Either or neither. Panic. */
6890 is_plausible = FALSE;
6893 ssh->exitcode = 128; /* means `unknown signal' */
6896 /* Old non-standard OpenSSH. */
6897 int signum = ssh_pkt_getuint32(pktin);
6898 fmt_sig = dupprintf(" %d", signum);
6899 ssh->exitcode = 128 + signum;
6901 /* As per RFC 4254. */
6904 ssh_pkt_getstring(pktin, &sig, &siglen);
6905 /* Signal name isn't supposed to be blank, but
6906 * let's cope gracefully if it is. */
6908 fmt_sig = dupprintf(" \"%.*s\"",
6913 * Really hideous method of translating the
6914 * signal description back into a locally
6915 * meaningful number.
6920 #define TRANSLATE_SIGNAL(s) \
6921 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6922 ssh->exitcode = 128 + SIG ## s
6924 TRANSLATE_SIGNAL(ABRT);
6927 TRANSLATE_SIGNAL(ALRM);
6930 TRANSLATE_SIGNAL(FPE);
6933 TRANSLATE_SIGNAL(HUP);
6936 TRANSLATE_SIGNAL(ILL);
6939 TRANSLATE_SIGNAL(INT);
6942 TRANSLATE_SIGNAL(KILL);
6945 TRANSLATE_SIGNAL(PIPE);
6948 TRANSLATE_SIGNAL(QUIT);
6951 TRANSLATE_SIGNAL(SEGV);
6954 TRANSLATE_SIGNAL(TERM);
6957 TRANSLATE_SIGNAL(USR1);
6960 TRANSLATE_SIGNAL(USR2);
6962 #undef TRANSLATE_SIGNAL
6964 ssh->exitcode = 128;
6966 core = ssh2_pkt_getbool(pktin);
6967 ssh_pkt_getstring(pktin, &msg, &msglen);
6969 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6971 /* ignore lang tag */
6972 } /* else don't attempt to parse */
6973 logeventf(ssh, "Server exited on signal%s%s%s",
6974 fmt_sig, core ? " (core dumped)" : "",
6976 if (*fmt_sig) sfree(fmt_sig);
6977 if (*fmt_msg) sfree(fmt_msg);
6978 reply = SSH2_MSG_CHANNEL_SUCCESS;
6983 * This is a channel request we don't know
6984 * about, so we now either ignore the request
6985 * or respond with CHANNEL_FAILURE, depending
6988 reply = SSH2_MSG_CHANNEL_FAILURE;
6991 pktout = ssh2_pkt_init(reply);
6992 ssh2_pkt_adduint32(pktout, c->remoteid);
6993 ssh2_pkt_send(ssh, pktout);
6997 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7000 int typelen, want_reply;
7001 struct Packet *pktout;
7003 ssh_pkt_getstring(pktin, &type, &typelen);
7004 want_reply = ssh2_pkt_getbool(pktin);
7007 * We currently don't support any global requests
7008 * at all, so we either ignore the request or
7009 * respond with REQUEST_FAILURE, depending on
7013 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7014 ssh2_pkt_send(ssh, pktout);
7018 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7026 struct ssh_channel *c;
7027 unsigned remid, winsize, pktsize;
7028 struct Packet *pktout;
7030 ssh_pkt_getstring(pktin, &type, &typelen);
7031 c = snew(struct ssh_channel);
7034 remid = ssh_pkt_getuint32(pktin);
7035 winsize = ssh_pkt_getuint32(pktin);
7036 pktsize = ssh_pkt_getuint32(pktin);
7038 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7042 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7043 addrstr = snewn(peeraddrlen+1, char);
7044 memcpy(addrstr, peeraddr, peeraddrlen);
7045 addrstr[peeraddrlen] = '\0';
7046 peerport = ssh_pkt_getuint32(pktin);
7048 logeventf(ssh, "Received X11 connect request from %s:%d",
7051 if (!ssh->X11_fwd_enabled)
7052 error = "X11 forwarding is not enabled";
7053 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7054 addrstr, peerport, &ssh->cfg)) != NULL) {
7055 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7056 error = "Unable to open an X11 connection";
7058 logevent("Opening X11 forward connection succeeded");
7063 } else if (typelen == 15 &&
7064 !memcmp(type, "forwarded-tcpip", 15)) {
7065 struct ssh_rportfwd pf, *realpf;
7068 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7069 pf.sport = ssh_pkt_getuint32(pktin);
7070 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7071 peerport = ssh_pkt_getuint32(pktin);
7072 realpf = find234(ssh->rportfwds, &pf, NULL);
7073 logeventf(ssh, "Received remote port %d open request "
7074 "from %s:%d", pf.sport, peeraddr, peerport);
7075 if (realpf == NULL) {
7076 error = "Remote port is not recognised";
7078 const char *e = pfd_newconnect(&c->u.pfd.s,
7082 realpf->pfrec->addressfamily);
7083 logeventf(ssh, "Attempting to forward remote port to "
7084 "%s:%d", realpf->dhost, realpf->dport);
7086 logeventf(ssh, "Port open failed: %s", e);
7087 error = "Port open failed";
7089 logevent("Forwarded port opened successfully");
7090 c->type = CHAN_SOCKDATA;
7093 } else if (typelen == 22 &&
7094 !memcmp(type, "auth-agent@openssh.com", 22)) {
7095 if (!ssh->agentfwd_enabled)
7096 error = "Agent forwarding is not enabled";
7098 c->type = CHAN_AGENT; /* identify channel type */
7099 c->u.a.lensofar = 0;
7102 error = "Unsupported channel type requested";
7105 c->remoteid = remid;
7106 c->halfopen = FALSE;
7108 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7109 ssh2_pkt_adduint32(pktout, c->remoteid);
7110 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7111 ssh2_pkt_addstring(pktout, error);
7112 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7113 ssh2_pkt_send(ssh, pktout);
7114 logeventf(ssh, "Rejected channel open: %s", error);
7117 ssh2_channel_init(c);
7118 c->v.v2.remwindow = winsize;
7119 c->v.v2.remmaxpkt = pktsize;
7120 add234(ssh->channels, c);
7121 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7122 ssh2_pkt_adduint32(pktout, c->remoteid);
7123 ssh2_pkt_adduint32(pktout, c->localid);
7124 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7125 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7126 ssh2_pkt_send(ssh, pktout);
7131 * Buffer banner messages for later display at some convenient point.
7133 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7135 /* Arbitrary limit to prevent unbounded inflation of buffer */
7136 if (bufchain_size(&ssh->banner) <= 131072) {
7137 char *banner = NULL;
7139 ssh_pkt_getstring(pktin, &banner, &size);
7141 bufchain_add(&ssh->banner, banner, size);
7145 /* Helper function to deal with sending tty modes for "pty-req" */
7146 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7148 struct Packet *pktout = (struct Packet *)data;
7150 unsigned int arg = 0;
7151 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7152 if (i == lenof(ssh_ttymodes)) return;
7153 switch (ssh_ttymodes[i].type) {
7155 arg = ssh_tty_parse_specchar(val);
7158 arg = ssh_tty_parse_boolean(val);
7161 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7162 ssh2_pkt_adduint32(pktout, arg);
7166 * Handle the SSH-2 userauth and connection layers.
7168 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7169 struct Packet *pktin)
7171 struct do_ssh2_authconn_state {
7174 AUTH_TYPE_PUBLICKEY,
7175 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7176 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7179 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7180 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7182 int done_service_req;
7183 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7184 int tried_pubkey_config, done_agent;
7189 int kbd_inter_refused;
7191 prompts_t *cur_prompt;
7196 void *publickey_blob;
7197 int publickey_bloblen;
7198 int publickey_encrypted;
7199 char *publickey_algorithm;
7200 char *publickey_comment;
7201 unsigned char agent_request[5], *agent_response, *agentp;
7202 int agent_responselen;
7203 unsigned char *pkblob_in_agent;
7205 char *pkblob, *alg, *commentp;
7206 int pklen, alglen, commentlen;
7207 int siglen, retlen, len;
7208 char *q, *agentreq, *ret;
7210 int num_env, env_left, env_ok;
7211 struct Packet *pktout;
7213 struct ssh_gss_library *gsslib;
7214 Ssh_gss_ctx gss_ctx;
7215 Ssh_gss_buf gss_buf;
7216 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7217 Ssh_gss_name gss_srv_name;
7218 Ssh_gss_stat gss_stat;
7221 crState(do_ssh2_authconn_state);
7223 crBegin(ssh->do_ssh2_authconn_crstate);
7225 s->done_service_req = FALSE;
7226 s->we_are_in = FALSE;
7228 s->tried_gssapi = FALSE;
7231 if (!ssh->cfg.ssh_no_userauth) {
7233 * Request userauth protocol, and await a response to it.
7235 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7236 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7237 ssh2_pkt_send(ssh, s->pktout);
7238 crWaitUntilV(pktin);
7239 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7240 s->done_service_req = TRUE;
7242 if (!s->done_service_req) {
7244 * Request connection protocol directly, without authentication.
7246 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7247 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7248 ssh2_pkt_send(ssh, s->pktout);
7249 crWaitUntilV(pktin);
7250 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7251 s->we_are_in = TRUE; /* no auth required */
7253 bombout(("Server refused service request"));
7258 /* Arrange to be able to deal with any BANNERs that come in.
7259 * (We do this now as packets may come in during the next bit.) */
7260 bufchain_init(&ssh->banner);
7261 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7262 ssh2_msg_userauth_banner;
7265 * Misc one-time setup for authentication.
7267 s->publickey_blob = NULL;
7268 if (!s->we_are_in) {
7271 * Load the public half of any configured public key file
7274 if (!filename_is_null(ssh->cfg.keyfile)) {
7276 logeventf(ssh, "Reading private key file \"%.150s\"",
7277 filename_to_str(&ssh->cfg.keyfile));
7278 keytype = key_type(&ssh->cfg.keyfile);
7279 if (keytype == SSH_KEYTYPE_SSH2) {
7282 ssh2_userkey_loadpub(&ssh->cfg.keyfile,
7283 &s->publickey_algorithm,
7284 &s->publickey_bloblen,
7285 &s->publickey_comment, &error);
7286 if (s->publickey_blob) {
7287 s->publickey_encrypted =
7288 ssh2_userkey_encrypted(&ssh->cfg.keyfile, NULL);
7291 logeventf(ssh, "Unable to load private key (%s)",
7293 msgbuf = dupprintf("Unable to load private key file "
7294 "\"%.150s\" (%s)\r\n",
7295 filename_to_str(&ssh->cfg.keyfile),
7297 c_write_str(ssh, msgbuf);
7302 logeventf(ssh, "Unable to use this key file (%s)",
7303 key_type_to_str(keytype));
7304 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7306 filename_to_str(&ssh->cfg.keyfile),
7307 key_type_to_str(keytype));
7308 c_write_str(ssh, msgbuf);
7310 s->publickey_blob = NULL;
7315 * Find out about any keys Pageant has (but if there's a
7316 * public key configured, filter out all others).
7319 s->agent_response = NULL;
7320 s->pkblob_in_agent = NULL;
7321 if (ssh->cfg.tryagent && agent_exists()) {
7325 logevent("Pageant is running. Requesting keys.");
7327 /* Request the keys held by the agent. */
7328 PUT_32BIT(s->agent_request, 1);
7329 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7330 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7331 ssh_agent_callback, ssh)) {
7335 bombout(("Unexpected data from server while"
7336 " waiting for agent response"));
7339 } while (pktin || inlen > 0);
7340 r = ssh->agent_response;
7341 s->agent_responselen = ssh->agent_response_len;
7343 s->agent_response = (unsigned char *) r;
7344 if (s->agent_response && s->agent_responselen >= 5 &&
7345 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7348 p = s->agent_response + 5;
7349 s->nkeys = GET_32BIT(p);
7351 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7352 if (s->publickey_blob) {
7353 /* See if configured key is in agent. */
7354 for (keyi = 0; keyi < s->nkeys; keyi++) {
7355 s->pklen = GET_32BIT(p);
7356 if (s->pklen == s->publickey_bloblen &&
7357 !memcmp(p+4, s->publickey_blob,
7358 s->publickey_bloblen)) {
7359 logeventf(ssh, "Pageant key #%d matches "
7360 "configured key file", keyi);
7362 s->pkblob_in_agent = p;
7366 p += GET_32BIT(p) + 4; /* comment */
7368 if (!s->pkblob_in_agent) {
7369 logevent("Configured key file not in Pageant");
7379 * We repeat this whole loop, including the username prompt,
7380 * until we manage a successful authentication. If the user
7381 * types the wrong _password_, they can be sent back to the
7382 * beginning to try another username, if this is configured on.
7383 * (If they specify a username in the config, they are never
7384 * asked, even if they do give a wrong password.)
7386 * I think this best serves the needs of
7388 * - the people who have no configuration, no keys, and just
7389 * want to try repeated (username,password) pairs until they
7390 * type both correctly
7392 * - people who have keys and configuration but occasionally
7393 * need to fall back to passwords
7395 * - people with a key held in Pageant, who might not have
7396 * logged in to a particular machine before; so they want to
7397 * type a username, and then _either_ their key will be
7398 * accepted, _or_ they will type a password. If they mistype
7399 * the username they will want to be able to get back and
7402 s->username[0] = '\0';
7403 s->got_username = FALSE;
7404 while (!s->we_are_in) {
7408 if (s->got_username && !ssh->cfg.change_username) {
7410 * We got a username last time round this loop, and
7411 * with change_username turned off we don't try to get
7414 } else if (!get_remote_username(&ssh->cfg, s->username,
7415 sizeof(s->username))) {
7416 int ret; /* need not be kept over crReturn */
7417 s->cur_prompt = new_prompts(ssh->frontend);
7418 s->cur_prompt->to_server = TRUE;
7419 s->cur_prompt->name = dupstr("SSH login name");
7420 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
7421 lenof(s->username));
7422 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7425 crWaitUntilV(!pktin);
7426 ret = get_userpass_input(s->cur_prompt, in, inlen);
7431 * get_userpass_input() failed to get a username.
7434 free_prompts(s->cur_prompt);
7435 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7438 memcpy(s->username, s->cur_prompt->prompts[0]->result,
7439 lenof(s->username));
7440 free_prompts(s->cur_prompt);
7443 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7444 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
7445 c_write_str(ssh, stuff);
7449 s->got_username = TRUE;
7452 * Send an authentication request using method "none": (a)
7453 * just in case it succeeds, and (b) so that we know what
7454 * authentication methods we can usefully try next.
7456 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7458 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7459 ssh2_pkt_addstring(s->pktout, s->username);
7460 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7461 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7462 ssh2_pkt_send(ssh, s->pktout);
7463 s->type = AUTH_TYPE_NONE;
7465 s->we_are_in = FALSE;
7467 s->tried_pubkey_config = FALSE;
7468 s->kbd_inter_refused = FALSE;
7470 /* Reset agent request state. */
7471 s->done_agent = FALSE;
7472 if (s->agent_response) {
7473 if (s->pkblob_in_agent) {
7474 s->agentp = s->pkblob_in_agent;
7476 s->agentp = s->agent_response + 5 + 4;
7483 * Wait for the result of the last authentication request.
7486 crWaitUntilV(pktin);
7488 * Now is a convenient point to spew any banner material
7489 * that we've accumulated. (This should ensure that when
7490 * we exit the auth loop, we haven't any left to deal
7494 int size = bufchain_size(&ssh->banner);
7496 * Don't show the banner if we're operating in
7497 * non-verbose non-interactive mode. (It's probably
7498 * a script, which means nobody will read the
7499 * banner _anyway_, and moreover the printing of
7500 * the banner will screw up processing on the
7501 * output of (say) plink.)
7503 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7504 char *banner = snewn(size, char);
7505 bufchain_fetch(&ssh->banner, banner, size);
7506 c_write_untrusted(ssh, banner, size);
7509 bufchain_clear(&ssh->banner);
7511 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7512 logevent("Access granted");
7513 s->we_are_in = TRUE;
7517 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7518 bombout(("Strange packet received during authentication: "
7519 "type %d", pktin->type));
7526 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7527 * we can look at the string in it and know what we can
7528 * helpfully try next.
7530 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7533 ssh_pkt_getstring(pktin, &methods, &methlen);
7534 if (!ssh2_pkt_getbool(pktin)) {
7536 * We have received an unequivocal Access
7537 * Denied. This can translate to a variety of
7540 * - if we'd just tried "none" authentication,
7541 * it's not worth printing anything at all
7543 * - if we'd just tried a public key _offer_,
7544 * the message should be "Server refused our
7545 * key" (or no message at all if the key
7546 * came from Pageant)
7548 * - if we'd just tried anything else, the
7549 * message really should be "Access denied".
7551 * Additionally, if we'd just tried password
7552 * authentication, we should break out of this
7553 * whole loop so as to go back to the username
7554 * prompt (iff we're configured to allow
7555 * username change attempts).
7557 if (s->type == AUTH_TYPE_NONE) {
7559 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7560 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7561 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7562 c_write_str(ssh, "Server refused our key\r\n");
7563 logevent("Server refused public key");
7564 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7565 /* server declined keyboard-interactive; ignore */
7567 c_write_str(ssh, "Access denied\r\n");
7568 logevent("Access denied");
7569 if (s->type == AUTH_TYPE_PASSWORD &&
7570 ssh->cfg.change_username) {
7571 /* XXX perhaps we should allow
7572 * keyboard-interactive to do this too? */
7573 s->we_are_in = FALSE;
7578 c_write_str(ssh, "Further authentication required\r\n");
7579 logevent("Further authentication required");
7583 in_commasep_string("publickey", methods, methlen);
7585 in_commasep_string("password", methods, methlen);
7586 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
7587 in_commasep_string("keyboard-interactive", methods, methlen);
7590 s->can_gssapi = ssh->cfg.try_gssapi_auth &&
7591 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7592 n_ssh_gss_libraries > 0;
7596 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7598 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7601 * Attempt public-key authentication using a key from Pageant.
7604 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7606 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7608 /* Unpack key from agent response */
7609 s->pklen = GET_32BIT(s->agentp);
7611 s->pkblob = (char *)s->agentp;
7612 s->agentp += s->pklen;
7613 s->alglen = GET_32BIT(s->pkblob);
7614 s->alg = s->pkblob + 4;
7615 s->commentlen = GET_32BIT(s->agentp);
7617 s->commentp = (char *)s->agentp;
7618 s->agentp += s->commentlen;
7619 /* s->agentp now points at next key, if any */
7621 /* See if server will accept it */
7622 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7623 ssh2_pkt_addstring(s->pktout, s->username);
7624 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7625 /* service requested */
7626 ssh2_pkt_addstring(s->pktout, "publickey");
7628 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7629 ssh2_pkt_addstring_start(s->pktout);
7630 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7631 ssh2_pkt_addstring_start(s->pktout);
7632 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7633 ssh2_pkt_send(ssh, s->pktout);
7634 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7636 crWaitUntilV(pktin);
7637 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7639 /* Offer of key refused. */
7646 if (flags & FLAG_VERBOSE) {
7647 c_write_str(ssh, "Authenticating with "
7649 c_write(ssh, s->commentp, s->commentlen);
7650 c_write_str(ssh, "\" from agent\r\n");
7654 * Server is willing to accept the key.
7655 * Construct a SIGN_REQUEST.
7657 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7658 ssh2_pkt_addstring(s->pktout, s->username);
7659 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7660 /* service requested */
7661 ssh2_pkt_addstring(s->pktout, "publickey");
7663 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7664 ssh2_pkt_addstring_start(s->pktout);
7665 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7666 ssh2_pkt_addstring_start(s->pktout);
7667 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7669 /* Ask agent for signature. */
7670 s->siglen = s->pktout->length - 5 + 4 +
7671 ssh->v2_session_id_len;
7672 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7674 s->len = 1; /* message type */
7675 s->len += 4 + s->pklen; /* key blob */
7676 s->len += 4 + s->siglen; /* data to sign */
7677 s->len += 4; /* flags */
7678 s->agentreq = snewn(4 + s->len, char);
7679 PUT_32BIT(s->agentreq, s->len);
7680 s->q = s->agentreq + 4;
7681 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7682 PUT_32BIT(s->q, s->pklen);
7684 memcpy(s->q, s->pkblob, s->pklen);
7686 PUT_32BIT(s->q, s->siglen);
7688 /* Now the data to be signed... */
7689 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7690 PUT_32BIT(s->q, ssh->v2_session_id_len);
7693 memcpy(s->q, ssh->v2_session_id,
7694 ssh->v2_session_id_len);
7695 s->q += ssh->v2_session_id_len;
7696 memcpy(s->q, s->pktout->data + 5,
7697 s->pktout->length - 5);
7698 s->q += s->pktout->length - 5;
7699 /* And finally the (zero) flags word. */
7701 if (!agent_query(s->agentreq, s->len + 4,
7703 ssh_agent_callback, ssh)) {
7707 bombout(("Unexpected data from server"
7708 " while waiting for agent"
7712 } while (pktin || inlen > 0);
7713 vret = ssh->agent_response;
7714 s->retlen = ssh->agent_response_len;
7719 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7720 logevent("Sending Pageant's response");
7721 ssh2_add_sigblob(ssh, s->pktout,
7722 s->pkblob, s->pklen,
7724 GET_32BIT(s->ret + 5));
7725 ssh2_pkt_send(ssh, s->pktout);
7726 s->type = AUTH_TYPE_PUBLICKEY;
7728 /* FIXME: less drastic response */
7729 bombout(("Pageant failed to answer challenge"));
7735 /* Do we have any keys left to try? */
7736 if (s->pkblob_in_agent) {
7737 s->done_agent = TRUE;
7738 s->tried_pubkey_config = TRUE;
7741 if (s->keyi >= s->nkeys)
7742 s->done_agent = TRUE;
7745 } else if (s->can_pubkey && s->publickey_blob &&
7746 !s->tried_pubkey_config) {
7748 struct ssh2_userkey *key; /* not live over crReturn */
7749 char *passphrase; /* not live over crReturn */
7751 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7753 s->tried_pubkey_config = TRUE;
7756 * Try the public key supplied in the configuration.
7758 * First, offer the public blob to see if the server is
7759 * willing to accept it.
7761 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7762 ssh2_pkt_addstring(s->pktout, s->username);
7763 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7764 /* service requested */
7765 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
7766 ssh2_pkt_addbool(s->pktout, FALSE);
7767 /* no signature included */
7768 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
7769 ssh2_pkt_addstring_start(s->pktout);
7770 ssh2_pkt_addstring_data(s->pktout,
7771 (char *)s->publickey_blob,
7772 s->publickey_bloblen);
7773 ssh2_pkt_send(ssh, s->pktout);
7774 logevent("Offered public key");
7776 crWaitUntilV(pktin);
7777 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7778 /* Key refused. Give up. */
7779 s->gotit = TRUE; /* reconsider message next loop */
7780 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
7781 continue; /* process this new message */
7783 logevent("Offer of public key accepted");
7786 * Actually attempt a serious authentication using
7789 if (flags & FLAG_VERBOSE) {
7790 c_write_str(ssh, "Authenticating with public key \"");
7791 c_write_str(ssh, s->publickey_comment);
7792 c_write_str(ssh, "\"\r\n");
7796 const char *error; /* not live over crReturn */
7797 if (s->publickey_encrypted) {
7799 * Get a passphrase from the user.
7801 int ret; /* need not be kept over crReturn */
7802 s->cur_prompt = new_prompts(ssh->frontend);
7803 s->cur_prompt->to_server = FALSE;
7804 s->cur_prompt->name = dupstr("SSH key passphrase");
7805 add_prompt(s->cur_prompt,
7806 dupprintf("Passphrase for key \"%.100s\": ",
7807 s->publickey_comment),
7808 FALSE, SSH_MAX_PASSWORD_LEN);
7809 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7812 crWaitUntilV(!pktin);
7813 ret = get_userpass_input(s->cur_prompt,
7818 /* Failed to get a passphrase. Terminate. */
7819 free_prompts(s->cur_prompt);
7820 ssh_disconnect(ssh, NULL,
7821 "Unable to authenticate",
7822 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7827 dupstr(s->cur_prompt->prompts[0]->result);
7828 free_prompts(s->cur_prompt);
7830 passphrase = NULL; /* no passphrase needed */
7834 * Try decrypting the key.
7836 key = ssh2_load_userkey(&ssh->cfg.keyfile, passphrase,
7839 /* burn the evidence */
7840 memset(passphrase, 0, strlen(passphrase));
7843 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
7845 (key == SSH2_WRONG_PASSPHRASE)) {
7846 c_write_str(ssh, "Wrong passphrase\r\n");
7848 /* and loop again */
7850 c_write_str(ssh, "Unable to load private key (");
7851 c_write_str(ssh, error);
7852 c_write_str(ssh, ")\r\n");
7854 break; /* try something else */
7860 unsigned char *pkblob, *sigblob, *sigdata;
7861 int pkblob_len, sigblob_len, sigdata_len;
7865 * We have loaded the private key and the server
7866 * has announced that it's willing to accept it.
7867 * Hallelujah. Generate a signature and send it.
7869 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7870 ssh2_pkt_addstring(s->pktout, s->username);
7871 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7872 /* service requested */
7873 ssh2_pkt_addstring(s->pktout, "publickey");
7875 ssh2_pkt_addbool(s->pktout, TRUE);
7876 /* signature follows */
7877 ssh2_pkt_addstring(s->pktout, key->alg->name);
7878 pkblob = key->alg->public_blob(key->data,
7880 ssh2_pkt_addstring_start(s->pktout);
7881 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
7885 * The data to be signed is:
7889 * followed by everything so far placed in the
7892 sigdata_len = s->pktout->length - 5 + 4 +
7893 ssh->v2_session_id_len;
7894 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7896 sigdata = snewn(sigdata_len, unsigned char);
7898 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7899 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
7902 memcpy(sigdata+p, ssh->v2_session_id,
7903 ssh->v2_session_id_len);
7904 p += ssh->v2_session_id_len;
7905 memcpy(sigdata+p, s->pktout->data + 5,
7906 s->pktout->length - 5);
7907 p += s->pktout->length - 5;
7908 assert(p == sigdata_len);
7909 sigblob = key->alg->sign(key->data, (char *)sigdata,
7910 sigdata_len, &sigblob_len);
7911 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7912 sigblob, sigblob_len);
7917 ssh2_pkt_send(ssh, s->pktout);
7918 s->type = AUTH_TYPE_PUBLICKEY;
7919 key->alg->freekey(key->data);
7923 } else if (s->can_gssapi && !s->tried_gssapi) {
7925 /* GSSAPI Authentication */
7930 s->type = AUTH_TYPE_GSSAPI;
7931 s->tried_gssapi = TRUE;
7933 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
7936 * Pick the highest GSS library on the preference
7942 for (i = 0; i < ngsslibs; i++) {
7943 int want_id = ssh->cfg.ssh_gsslist[i];
7944 for (j = 0; j < n_ssh_gss_libraries; j++)
7945 if (ssh_gss_libraries[j].id == want_id) {
7946 s->gsslib = &ssh_gss_libraries[j];
7947 goto got_gsslib; /* double break */
7952 * We always expect to have found something in
7953 * the above loop: we only came here if there
7954 * was at least one viable GSS library, and the
7955 * preference list should always mention
7956 * everything and only change the order.
7961 if (s->gsslib->gsslogmsg)
7962 logevent(s->gsslib->gsslogmsg);
7964 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
7965 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7966 ssh2_pkt_addstring(s->pktout, s->username);
7967 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7968 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
7970 /* add mechanism info */
7971 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
7973 /* number of GSSAPI mechanisms */
7974 ssh2_pkt_adduint32(s->pktout,1);
7976 /* length of OID + 2 */
7977 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
7978 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
7981 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
7983 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
7985 ssh2_pkt_send(ssh, s->pktout);
7986 crWaitUntilV(pktin);
7987 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
7988 logevent("GSSAPI authentication request refused");
7992 /* check returned packet ... */
7994 ssh_pkt_getstring(pktin, &data, &len);
7995 s->gss_rcvtok.value = data;
7996 s->gss_rcvtok.length = len;
7997 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
7998 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
7999 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8000 memcmp((char *)s->gss_rcvtok.value + 2,
8001 s->gss_buf.value,s->gss_buf.length) ) {
8002 logevent("GSSAPI authentication - wrong response from server");
8006 /* now start running */
8007 s->gss_stat = s->gsslib->import_name(s->gsslib,
8010 if (s->gss_stat != SSH_GSS_OK) {
8011 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8012 logevent("GSSAPI import name failed - Bad service name");
8014 logevent("GSSAPI import name failed");
8018 /* fetch TGT into GSS engine */
8019 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8021 if (s->gss_stat != SSH_GSS_OK) {
8022 logevent("GSSAPI authentication failed to get credentials");
8023 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8027 /* initial tokens are empty */
8028 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8029 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8031 /* now enter the loop */
8033 s->gss_stat = s->gsslib->init_sec_context
8041 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8042 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8043 logevent("GSSAPI authentication initialisation failed");
8045 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8046 &s->gss_buf) == SSH_GSS_OK) {
8047 logevent(s->gss_buf.value);
8048 sfree(s->gss_buf.value);
8053 logevent("GSSAPI authentication initialised");
8055 /* Client and server now exchange tokens until GSSAPI
8056 * no longer says CONTINUE_NEEDED */
8058 if (s->gss_sndtok.length != 0) {
8059 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8060 ssh_pkt_addstring_start(s->pktout);
8061 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8062 ssh2_pkt_send(ssh, s->pktout);
8063 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8066 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8067 crWaitUntilV(pktin);
8068 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8069 logevent("GSSAPI authentication - bad server response");
8070 s->gss_stat = SSH_GSS_FAILURE;
8073 ssh_pkt_getstring(pktin, &data, &len);
8074 s->gss_rcvtok.value = data;
8075 s->gss_rcvtok.length = len;
8077 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8079 if (s->gss_stat != SSH_GSS_OK) {
8080 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8081 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8084 logevent("GSSAPI authentication loop finished OK");
8086 /* Now send the MIC */
8088 s->pktout = ssh2_pkt_init(0);
8089 micoffset = s->pktout->length;
8090 ssh_pkt_addstring_start(s->pktout);
8091 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8092 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8093 ssh_pkt_addstring(s->pktout, s->username);
8094 ssh_pkt_addstring(s->pktout, "ssh-connection");
8095 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8097 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8098 s->gss_buf.length = s->pktout->length - micoffset;
8100 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8101 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8102 ssh_pkt_addstring_start(s->pktout);
8103 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8104 ssh2_pkt_send(ssh, s->pktout);
8105 s->gsslib->free_mic(s->gsslib, &mic);
8109 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8110 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8113 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8116 * Keyboard-interactive authentication.
8119 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8121 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8123 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8124 ssh2_pkt_addstring(s->pktout, s->username);
8125 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8126 /* service requested */
8127 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8129 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8130 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8131 ssh2_pkt_send(ssh, s->pktout);
8133 crWaitUntilV(pktin);
8134 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8135 /* Server is not willing to do keyboard-interactive
8136 * at all (or, bizarrely but legally, accepts the
8137 * user without actually issuing any prompts).
8138 * Give up on it entirely. */
8140 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
8141 logevent("Keyboard-interactive authentication refused");
8142 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8143 s->kbd_inter_refused = TRUE; /* don't try it again */
8148 * Loop while the server continues to send INFO_REQUESTs.
8150 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8152 char *name, *inst, *lang;
8153 int name_len, inst_len, lang_len;
8157 * We've got a fresh USERAUTH_INFO_REQUEST.
8158 * Get the preamble and start building a prompt.
8160 ssh_pkt_getstring(pktin, &name, &name_len);
8161 ssh_pkt_getstring(pktin, &inst, &inst_len);
8162 ssh_pkt_getstring(pktin, &lang, &lang_len);
8163 s->cur_prompt = new_prompts(ssh->frontend);
8164 s->cur_prompt->to_server = TRUE;
8167 * Get any prompt(s) from the packet.
8169 s->num_prompts = ssh_pkt_getuint32(pktin);
8170 for (i = 0; i < s->num_prompts; i++) {
8174 static char noprompt[] =
8175 "<server failed to send prompt>: ";
8177 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8178 echo = ssh2_pkt_getbool(pktin);
8181 prompt_len = lenof(noprompt)-1;
8183 add_prompt(s->cur_prompt,
8184 dupprintf("%.*s", prompt_len, prompt),
8185 echo, SSH_MAX_PASSWORD_LEN);
8189 /* FIXME: better prefix to distinguish from
8191 s->cur_prompt->name =
8192 dupprintf("SSH server: %.*s", name_len, name);
8193 s->cur_prompt->name_reqd = TRUE;
8195 s->cur_prompt->name =
8196 dupstr("SSH server authentication");
8197 s->cur_prompt->name_reqd = FALSE;
8199 /* We add a prefix to try to make it clear that a prompt
8200 * has come from the server.
8201 * FIXME: ugly to print "Using..." in prompt _every_
8202 * time round. Can this be done more subtly? */
8203 /* Special case: for reasons best known to themselves,
8204 * some servers send k-i requests with no prompts and
8205 * nothing to display. Keep quiet in this case. */
8206 if (s->num_prompts || name_len || inst_len) {
8207 s->cur_prompt->instruction =
8208 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8209 inst_len ? "\n" : "", inst_len, inst);
8210 s->cur_prompt->instr_reqd = TRUE;
8212 s->cur_prompt->instr_reqd = FALSE;
8216 * Display any instructions, and get the user's
8220 int ret; /* not live over crReturn */
8221 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8224 crWaitUntilV(!pktin);
8225 ret = get_userpass_input(s->cur_prompt, in, inlen);
8230 * Failed to get responses. Terminate.
8232 free_prompts(s->cur_prompt);
8233 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8234 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8241 * Send the response(s) to the server.
8243 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8244 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8245 for (i=0; i < s->num_prompts; i++) {
8246 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8247 ssh2_pkt_addstring(s->pktout,
8248 s->cur_prompt->prompts[i]->result);
8249 end_log_omission(ssh, s->pktout);
8251 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8254 * Get the next packet in case it's another
8257 crWaitUntilV(pktin);
8262 * We should have SUCCESS or FAILURE now.
8266 } else if (s->can_passwd) {
8269 * Plain old password authentication.
8271 int ret; /* not live over crReturn */
8272 int changereq_first_time; /* not live over crReturn */
8274 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8276 s->cur_prompt = new_prompts(ssh->frontend);
8277 s->cur_prompt->to_server = TRUE;
8278 s->cur_prompt->name = dupstr("SSH password");
8279 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
8282 FALSE, SSH_MAX_PASSWORD_LEN);
8284 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8287 crWaitUntilV(!pktin);
8288 ret = get_userpass_input(s->cur_prompt, in, inlen);
8293 * Failed to get responses. Terminate.
8295 free_prompts(s->cur_prompt);
8296 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8297 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8302 * Squirrel away the password. (We may need it later if
8303 * asked to change it.)
8305 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8306 free_prompts(s->cur_prompt);
8309 * Send the password packet.
8311 * We pad out the password packet to 256 bytes to make
8312 * it harder for an attacker to find the length of the
8315 * Anyone using a password longer than 256 bytes
8316 * probably doesn't have much to worry about from
8317 * people who find out how long their password is!
8319 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8320 ssh2_pkt_addstring(s->pktout, s->username);
8321 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8322 /* service requested */
8323 ssh2_pkt_addstring(s->pktout, "password");
8324 ssh2_pkt_addbool(s->pktout, FALSE);
8325 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8326 ssh2_pkt_addstring(s->pktout, s->password);
8327 end_log_omission(ssh, s->pktout);
8328 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8329 logevent("Sent password");
8330 s->type = AUTH_TYPE_PASSWORD;
8333 * Wait for next packet, in case it's a password change
8336 crWaitUntilV(pktin);
8337 changereq_first_time = TRUE;
8339 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8342 * We're being asked for a new password
8343 * (perhaps not for the first time).
8344 * Loop until the server accepts it.
8347 int got_new = FALSE; /* not live over crReturn */
8348 char *prompt; /* not live over crReturn */
8349 int prompt_len; /* not live over crReturn */
8353 if (changereq_first_time)
8354 msg = "Server requested password change";
8356 msg = "Server rejected new password";
8358 c_write_str(ssh, msg);
8359 c_write_str(ssh, "\r\n");
8362 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8364 s->cur_prompt = new_prompts(ssh->frontend);
8365 s->cur_prompt->to_server = TRUE;
8366 s->cur_prompt->name = dupstr("New SSH password");
8367 s->cur_prompt->instruction =
8368 dupprintf("%.*s", prompt_len, prompt);
8369 s->cur_prompt->instr_reqd = TRUE;
8371 * There's no explicit requirement in the protocol
8372 * for the "old" passwords in the original and
8373 * password-change messages to be the same, and
8374 * apparently some Cisco kit supports password change
8375 * by the user entering a blank password originally
8376 * and the real password subsequently, so,
8377 * reluctantly, we prompt for the old password again.
8379 * (On the other hand, some servers don't even bother
8380 * to check this field.)
8382 add_prompt(s->cur_prompt,
8383 dupstr("Current password (blank for previously entered password): "),
8384 FALSE, SSH_MAX_PASSWORD_LEN);
8385 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8386 FALSE, SSH_MAX_PASSWORD_LEN);
8387 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8388 FALSE, SSH_MAX_PASSWORD_LEN);
8391 * Loop until the user manages to enter the same
8396 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8399 crWaitUntilV(!pktin);
8400 ret = get_userpass_input(s->cur_prompt, in, inlen);
8405 * Failed to get responses. Terminate.
8407 /* burn the evidence */
8408 free_prompts(s->cur_prompt);
8409 memset(s->password, 0, strlen(s->password));
8411 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8412 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8418 * If the user specified a new original password
8419 * (IYSWIM), overwrite any previously specified
8421 * (A side effect is that the user doesn't have to
8422 * re-enter it if they louse up the new password.)
8424 if (s->cur_prompt->prompts[0]->result[0]) {
8425 memset(s->password, 0, strlen(s->password));
8426 /* burn the evidence */
8429 dupstr(s->cur_prompt->prompts[0]->result);
8433 * Check the two new passwords match.
8435 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8436 s->cur_prompt->prompts[2]->result)
8439 /* They don't. Silly user. */
8440 c_write_str(ssh, "Passwords do not match\r\n");
8445 * Send the new password (along with the old one).
8446 * (see above for padding rationale)
8448 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8449 ssh2_pkt_addstring(s->pktout, s->username);
8450 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8451 /* service requested */
8452 ssh2_pkt_addstring(s->pktout, "password");
8453 ssh2_pkt_addbool(s->pktout, TRUE);
8454 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8455 ssh2_pkt_addstring(s->pktout, s->password);
8456 ssh2_pkt_addstring(s->pktout,
8457 s->cur_prompt->prompts[1]->result);
8458 free_prompts(s->cur_prompt);
8459 end_log_omission(ssh, s->pktout);
8460 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8461 logevent("Sent new password");
8464 * Now see what the server has to say about it.
8465 * (If it's CHANGEREQ again, it's not happy with the
8468 crWaitUntilV(pktin);
8469 changereq_first_time = FALSE;
8474 * We need to reexamine the current pktin at the top
8475 * of the loop. Either:
8476 * - we weren't asked to change password at all, in
8477 * which case it's a SUCCESS or FAILURE with the
8479 * - we sent a new password, and the server was
8480 * either OK with it (SUCCESS or FAILURE w/partial
8481 * success) or unhappy with the _old_ password
8482 * (FAILURE w/o partial success)
8483 * In any of these cases, we go back to the top of
8484 * the loop and start again.
8489 * We don't need the old password any more, in any
8490 * case. Burn the evidence.
8492 memset(s->password, 0, strlen(s->password));
8497 ssh_disconnect(ssh, NULL,
8498 "No supported authentication methods available",
8499 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8507 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8509 /* Clear up various bits and pieces from authentication. */
8510 if (s->publickey_blob) {
8511 sfree(s->publickey_blob);
8512 sfree(s->publickey_comment);
8514 if (s->agent_response)
8515 sfree(s->agent_response);
8518 * Now the connection protocol has started, one way or another.
8521 ssh->channels = newtree234(ssh_channelcmp);
8524 * Set up handlers for some connection protocol messages, so we
8525 * don't have to handle them repeatedly in this coroutine.
8527 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8528 ssh2_msg_channel_window_adjust;
8529 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8530 ssh2_msg_global_request;
8533 * Create the main session channel.
8535 if (ssh->cfg.ssh_no_shell) {
8536 ssh->mainchan = NULL;
8537 } else if (*ssh->cfg.ssh_nc_host) {
8539 * Just start a direct-tcpip channel and use it as the main
8542 ssh->mainchan = snew(struct ssh_channel);
8543 ssh->mainchan->ssh = ssh;
8544 ssh2_channel_init(ssh->mainchan);
8546 "Opening direct-tcpip channel to %s:%d in place of session",
8547 ssh->cfg.ssh_nc_host, ssh->cfg.ssh_nc_port);
8548 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8549 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8550 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8551 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8552 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8553 ssh2_pkt_addstring(s->pktout, ssh->cfg.ssh_nc_host);
8554 ssh2_pkt_adduint32(s->pktout, ssh->cfg.ssh_nc_port);
8556 * There's nothing meaningful to put in the originator
8557 * fields, but some servers insist on syntactically correct
8560 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8561 ssh2_pkt_adduint32(s->pktout, 0);
8562 ssh2_pkt_send(ssh, s->pktout);
8564 crWaitUntilV(pktin);
8565 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8566 bombout(("Server refused to open a direct-tcpip channel"));
8568 /* FIXME: error data comes back in FAILURE packet */
8570 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8571 bombout(("Server's channel confirmation cited wrong channel"));
8574 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8575 ssh->mainchan->halfopen = FALSE;
8576 ssh->mainchan->type = CHAN_MAINSESSION;
8577 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8578 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8579 add234(ssh->channels, ssh->mainchan);
8580 update_specials_menu(ssh->frontend);
8581 logevent("Opened direct-tcpip channel");
8584 ssh->mainchan = snew(struct ssh_channel);
8585 ssh->mainchan->ssh = ssh;
8586 ssh2_channel_init(ssh->mainchan);
8587 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8588 ssh2_pkt_addstring(s->pktout, "session");
8589 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8590 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8591 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8592 ssh2_pkt_send(ssh, s->pktout);
8593 crWaitUntilV(pktin);
8594 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8595 bombout(("Server refused to open a session"));
8597 /* FIXME: error data comes back in FAILURE packet */
8599 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8600 bombout(("Server's channel confirmation cited wrong channel"));
8603 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8604 ssh->mainchan->halfopen = FALSE;
8605 ssh->mainchan->type = CHAN_MAINSESSION;
8606 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8607 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8608 add234(ssh->channels, ssh->mainchan);
8609 update_specials_menu(ssh->frontend);
8610 logevent("Opened channel for session");
8611 ssh->ncmode = FALSE;
8615 * Now we have a channel, make dispatch table entries for
8616 * general channel-based messages.
8618 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8619 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8620 ssh2_msg_channel_data;
8621 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8622 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8623 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8624 ssh2_msg_channel_open_confirmation;
8625 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8626 ssh2_msg_channel_open_failure;
8627 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8628 ssh2_msg_channel_request;
8629 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8630 ssh2_msg_channel_open;
8632 if (ssh->mainchan && ssh->cfg.ssh_simple) {
8634 * This message indicates to the server that we promise
8635 * not to try to run any other channel in parallel with
8636 * this one, so it's safe for it to advertise a very large
8637 * window and leave the flow control to TCP.
8639 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8640 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8641 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8642 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8643 ssh2_pkt_send(ssh, s->pktout);
8647 * Potentially enable X11 forwarding.
8649 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.x11_forward &&
8650 (ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
8651 ssh->cfg.x11_auth, &ssh->cfg))) {
8652 logevent("Requesting X11 forwarding");
8653 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8654 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8655 ssh2_pkt_addstring(s->pktout, "x11-req");
8656 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8657 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8658 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8660 * Note that while we blank the X authentication data here, we don't
8661 * take any special action to blank the start of an X11 channel,
8662 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8663 * without having session blanking enabled is likely to leak your
8664 * cookie into the log.
8666 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8667 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8668 end_log_omission(ssh, s->pktout);
8669 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8670 ssh2_pkt_send(ssh, s->pktout);
8672 crWaitUntilV(pktin);
8674 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8675 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8676 bombout(("Unexpected response to X11 forwarding request:"
8677 " packet type %d", pktin->type));
8680 logevent("X11 forwarding refused");
8682 logevent("X11 forwarding enabled");
8683 ssh->X11_fwd_enabled = TRUE;
8688 * Enable port forwardings.
8690 ssh_setup_portfwd(ssh, &ssh->cfg);
8693 * Potentially enable agent forwarding.
8695 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.agentfwd && agent_exists()) {
8696 logevent("Requesting OpenSSH-style agent forwarding");
8697 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8698 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8699 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8700 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8701 ssh2_pkt_send(ssh, s->pktout);
8703 crWaitUntilV(pktin);
8705 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8706 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8707 bombout(("Unexpected response to agent forwarding request:"
8708 " packet type %d", pktin->type));
8711 logevent("Agent forwarding refused");
8713 logevent("Agent forwarding enabled");
8714 ssh->agentfwd_enabled = TRUE;
8719 * Now allocate a pty for the session.
8721 if (ssh->mainchan && !ssh->ncmode && !ssh->cfg.nopty) {
8722 /* Unpick the terminal-speed string. */
8723 /* XXX perhaps we should allow no speeds to be sent. */
8724 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8725 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
8726 /* Build the pty request. */
8727 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8728 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8729 ssh2_pkt_addstring(s->pktout, "pty-req");
8730 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8731 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
8732 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8733 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8734 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8735 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8736 ssh2_pkt_addstring_start(s->pktout);
8737 parse_ttymodes(ssh, ssh->cfg.ttymodes,
8738 ssh2_send_ttymode, (void *)s->pktout);
8739 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
8740 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
8741 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
8742 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
8743 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
8744 ssh2_pkt_send(ssh, s->pktout);
8745 ssh->state = SSH_STATE_INTERMED;
8747 crWaitUntilV(pktin);
8749 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8750 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8751 bombout(("Unexpected response to pty request:"
8752 " packet type %d", pktin->type));
8755 c_write_str(ssh, "Server refused to allocate pty\r\n");
8756 ssh->editing = ssh->echoing = 1;
8758 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8759 ssh->ospeed, ssh->ispeed);
8762 ssh->editing = ssh->echoing = 1;
8766 * Send environment variables.
8768 * Simplest thing here is to send all the requests at once, and
8769 * then wait for a whole bunch of successes or failures.
8771 if (ssh->mainchan && !ssh->ncmode && *ssh->cfg.environmt) {
8772 char *e = ssh->cfg.environmt;
8773 char *var, *varend, *val;
8779 while (*e && *e != '\t') e++;
8781 if (*e == '\t') e++;
8786 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8787 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8788 ssh2_pkt_addstring(s->pktout, "env");
8789 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8790 ssh2_pkt_addstring_start(s->pktout);
8791 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
8792 ssh2_pkt_addstring(s->pktout, val);
8793 ssh2_pkt_send(ssh, s->pktout);
8798 logeventf(ssh, "Sent %d environment variables", s->num_env);
8801 s->env_left = s->num_env;
8803 while (s->env_left > 0) {
8804 crWaitUntilV(pktin);
8806 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8807 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8808 bombout(("Unexpected response to environment request:"
8809 " packet type %d", pktin->type));
8819 if (s->env_ok == s->num_env) {
8820 logevent("All environment variables successfully set");
8821 } else if (s->env_ok == 0) {
8822 logevent("All environment variables refused");
8823 c_write_str(ssh, "Server refused to set environment variables\r\n");
8825 logeventf(ssh, "%d environment variables refused",
8826 s->num_env - s->env_ok);
8827 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8832 * Start a shell or a remote command. We may have to attempt
8833 * this twice if the config data has provided a second choice
8836 if (ssh->mainchan && !ssh->ncmode) while (1) {
8840 if (ssh->fallback_cmd) {
8841 subsys = ssh->cfg.ssh_subsys2;
8842 cmd = ssh->cfg.remote_cmd_ptr2;
8844 subsys = ssh->cfg.ssh_subsys;
8845 cmd = ssh->cfg.remote_cmd_ptr;
8846 if (!cmd) cmd = ssh->cfg.remote_cmd;
8849 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8850 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8852 ssh2_pkt_addstring(s->pktout, "subsystem");
8853 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8854 ssh2_pkt_addstring(s->pktout, cmd);
8856 ssh2_pkt_addstring(s->pktout, "exec");
8857 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8858 ssh2_pkt_addstring(s->pktout, cmd);
8860 ssh2_pkt_addstring(s->pktout, "shell");
8861 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8863 ssh2_pkt_send(ssh, s->pktout);
8865 crWaitUntilV(pktin);
8867 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8868 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8869 bombout(("Unexpected response to shell/command request:"
8870 " packet type %d", pktin->type));
8874 * We failed to start the command. If this is the
8875 * fallback command, we really are finished; if it's
8876 * not, and if the fallback command exists, try falling
8877 * back to it before complaining.
8879 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
8880 logevent("Primary command failed; attempting fallback");
8881 ssh->fallback_cmd = TRUE;
8884 bombout(("Server refused to start a shell/command"));
8887 logevent("Started a shell/command");
8892 ssh->state = SSH_STATE_SESSION;
8893 if (ssh->size_needed)
8894 ssh_size(ssh, ssh->term_width, ssh->term_height);
8895 if (ssh->eof_needed)
8896 ssh_special(ssh, TS_EOF);
8899 * All the initial channel requests are done, so install the default
8902 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
8903 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
8909 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
8914 s->try_send = FALSE;
8918 * _All_ the connection-layer packets we expect to
8919 * receive are now handled by the dispatch table.
8920 * Anything that reaches here must be bogus.
8923 bombout(("Strange packet received: type %d", pktin->type));
8925 } else if (ssh->mainchan) {
8927 * We have spare data. Add it to the channel buffer.
8929 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
8934 struct ssh_channel *c;
8936 * Try to send data on all channels if we can.
8938 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
8939 ssh2_try_send_and_unthrottle(c);
8947 * Handlers for SSH-2 messages that might arrive at any moment.
8949 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
8951 /* log reason code in disconnect message */
8955 reason = ssh_pkt_getuint32(pktin);
8956 ssh_pkt_getstring(pktin, &msg, &msglen);
8958 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
8959 buf = dupprintf("Received disconnect message (%s)",
8960 ssh2_disconnect_reasons[reason]);
8962 buf = dupprintf("Received disconnect message (unknown"
8963 " type %d)", reason);
8967 buf = dupprintf("Disconnection message text: %.*s",
8970 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
8972 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
8973 ssh2_disconnect_reasons[reason] : "unknown",
8978 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
8980 /* log the debug message */
8985 /* XXX maybe we should actually take notice of this */
8986 always_display = ssh2_pkt_getbool(pktin);
8987 ssh_pkt_getstring(pktin, &msg, &msglen);
8989 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
8992 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
8994 struct Packet *pktout;
8995 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
8996 ssh2_pkt_adduint32(pktout, pktin->sequence);
8998 * UNIMPLEMENTED messages MUST appear in the same order as the
8999 * messages they respond to. Hence, never queue them.
9001 ssh2_pkt_send_noqueue(ssh, pktout);
9005 * Handle the top-level SSH-2 protocol.
9007 static void ssh2_protocol_setup(Ssh ssh)
9012 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9014 for (i = 0; i < 256; i++)
9015 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9018 * Any message we actually understand, we set to NULL so that
9019 * the coroutines will get it.
9021 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9022 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9023 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9024 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9025 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9026 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9027 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9028 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9029 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9030 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9031 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9032 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9033 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9034 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9035 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9036 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9037 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9038 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9039 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9040 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9041 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9042 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9043 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9044 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9045 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9046 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9047 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9048 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9049 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9050 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9051 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9052 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9053 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9056 * These special message types we install handlers for.
9058 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9059 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9060 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9063 static void ssh2_timer(void *ctx, long now)
9067 if (ssh->state == SSH_STATE_CLOSED)
9070 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
9071 now - ssh->next_rekey >= 0) {
9072 do_ssh2_transport(ssh, "timeout", -1, NULL);
9076 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9077 struct Packet *pktin)
9079 unsigned char *in = (unsigned char *)vin;
9080 if (ssh->state == SSH_STATE_CLOSED)
9084 ssh->incoming_data_size += pktin->encrypted_len;
9085 if (!ssh->kex_in_progress &&
9086 ssh->max_data_size != 0 &&
9087 ssh->incoming_data_size > ssh->max_data_size)
9088 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9091 if (pktin && ssh->packet_dispatch[pktin->type]) {
9092 ssh->packet_dispatch[pktin->type](ssh, pktin);
9096 if (!ssh->protocol_initial_phase_done ||
9097 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9098 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9099 !ssh->protocol_initial_phase_done) {
9100 ssh->protocol_initial_phase_done = TRUE;
9102 * Allow authconn to initialise itself.
9104 do_ssh2_authconn(ssh, NULL, 0, NULL);
9107 do_ssh2_authconn(ssh, in, inlen, pktin);
9112 * Called to set up the connection.
9114 * Returns an error message, or NULL on success.
9116 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9118 char *host, int port, char **realhost, int nodelay,
9124 ssh = snew(struct ssh_tag);
9125 ssh->cfg = *cfg; /* STRUCTURE COPY */
9126 ssh->version = 0; /* when not ready yet */
9129 ssh->v1_cipher_ctx = NULL;
9130 ssh->crcda_ctx = NULL;
9131 ssh->cscipher = NULL;
9132 ssh->cs_cipher_ctx = NULL;
9133 ssh->sccipher = NULL;
9134 ssh->sc_cipher_ctx = NULL;
9136 ssh->cs_mac_ctx = NULL;
9138 ssh->sc_mac_ctx = NULL;
9140 ssh->cs_comp_ctx = NULL;
9142 ssh->sc_comp_ctx = NULL;
9144 ssh->kex_ctx = NULL;
9145 ssh->hostkey = NULL;
9147 ssh->close_expected = FALSE;
9148 ssh->clean_exit = FALSE;
9149 ssh->state = SSH_STATE_PREPACKET;
9150 ssh->size_needed = FALSE;
9151 ssh->eof_needed = FALSE;
9154 ssh->deferred_send_data = NULL;
9155 ssh->deferred_len = 0;
9156 ssh->deferred_size = 0;
9157 ssh->fallback_cmd = 0;
9158 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9159 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9160 ssh->x11disp = NULL;
9161 ssh->v1_compressing = FALSE;
9162 ssh->v2_outgoing_sequence = 0;
9163 ssh->ssh1_rdpkt_crstate = 0;
9164 ssh->ssh2_rdpkt_crstate = 0;
9165 ssh->do_ssh_init_crstate = 0;
9166 ssh->ssh_gotdata_crstate = 0;
9167 ssh->do_ssh1_connection_crstate = 0;
9168 ssh->do_ssh1_login_crstate = 0;
9169 ssh->do_ssh2_transport_crstate = 0;
9170 ssh->do_ssh2_authconn_crstate = 0;
9171 ssh->do_ssh_init_state = NULL;
9172 ssh->do_ssh1_login_state = NULL;
9173 ssh->do_ssh2_transport_state = NULL;
9174 ssh->do_ssh2_authconn_state = NULL;
9177 ssh->mainchan = NULL;
9178 ssh->throttled_all = 0;
9179 ssh->v1_stdout_throttling = 0;
9181 ssh->queuelen = ssh->queuesize = 0;
9182 ssh->queueing = FALSE;
9183 ssh->qhead = ssh->qtail = NULL;
9184 ssh->deferred_rekey_reason = NULL;
9185 bufchain_init(&ssh->queued_incoming_data);
9186 ssh->frozen = FALSE;
9188 *backend_handle = ssh;
9191 if (crypto_startup() == 0)
9192 return "Microsoft high encryption pack not installed!";
9195 ssh->frontend = frontend_handle;
9196 ssh->term_width = ssh->cfg.width;
9197 ssh->term_height = ssh->cfg.height;
9199 ssh->channels = NULL;
9200 ssh->rportfwds = NULL;
9201 ssh->portfwds = NULL;
9206 ssh->conn_throttle_count = 0;
9207 ssh->overall_bufsize = 0;
9208 ssh->fallback_cmd = 0;
9210 ssh->protocol = NULL;
9212 ssh->protocol_initial_phase_done = FALSE;
9216 ssh->incoming_data_size = ssh->outgoing_data_size =
9217 ssh->deferred_data_size = 0L;
9218 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
9219 ssh->kex_in_progress = FALSE;
9221 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9230 static void ssh_free(void *handle)
9232 Ssh ssh = (Ssh) handle;
9233 struct ssh_channel *c;
9234 struct ssh_rportfwd *pf;
9236 if (ssh->v1_cipher_ctx)
9237 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9238 if (ssh->cs_cipher_ctx)
9239 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9240 if (ssh->sc_cipher_ctx)
9241 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9242 if (ssh->cs_mac_ctx)
9243 ssh->csmac->free_context(ssh->cs_mac_ctx);
9244 if (ssh->sc_mac_ctx)
9245 ssh->scmac->free_context(ssh->sc_mac_ctx);
9246 if (ssh->cs_comp_ctx) {
9248 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9250 zlib_compress_cleanup(ssh->cs_comp_ctx);
9252 if (ssh->sc_comp_ctx) {
9254 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9256 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9259 dh_cleanup(ssh->kex_ctx);
9260 sfree(ssh->savedhost);
9262 while (ssh->queuelen-- > 0)
9263 ssh_free_packet(ssh->queue[ssh->queuelen]);
9266 while (ssh->qhead) {
9267 struct queued_handler *qh = ssh->qhead;
9268 ssh->qhead = qh->next;
9271 ssh->qhead = ssh->qtail = NULL;
9273 if (ssh->channels) {
9274 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9277 if (c->u.x11.s != NULL)
9278 x11_close(c->u.x11.s);
9281 if (c->u.pfd.s != NULL)
9282 pfd_close(c->u.pfd.s);
9287 freetree234(ssh->channels);
9288 ssh->channels = NULL;
9291 if (ssh->rportfwds) {
9292 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9294 freetree234(ssh->rportfwds);
9295 ssh->rportfwds = NULL;
9297 sfree(ssh->deferred_send_data);
9299 x11_free_display(ssh->x11disp);
9300 sfree(ssh->do_ssh_init_state);
9301 sfree(ssh->do_ssh1_login_state);
9302 sfree(ssh->do_ssh2_transport_state);
9303 sfree(ssh->do_ssh2_authconn_state);
9306 sfree(ssh->fullhostname);
9307 if (ssh->crcda_ctx) {
9308 crcda_free_context(ssh->crcda_ctx);
9309 ssh->crcda_ctx = NULL;
9312 ssh_do_close(ssh, TRUE);
9313 expire_timer_context(ssh);
9315 pinger_free(ssh->pinger);
9316 bufchain_clear(&ssh->queued_incoming_data);
9323 * Reconfigure the SSH backend.
9325 static void ssh_reconfig(void *handle, Config *cfg)
9327 Ssh ssh = (Ssh) handle;
9328 char *rekeying = NULL, rekey_mandatory = FALSE;
9329 unsigned long old_max_data_size;
9331 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
9333 ssh_setup_portfwd(ssh, cfg);
9335 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
9336 cfg->ssh_rekey_time != 0) {
9337 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
9338 long now = GETTICKCOUNT();
9340 if (new_next - now < 0) {
9341 rekeying = "timeout shortened";
9343 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9347 old_max_data_size = ssh->max_data_size;
9348 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
9349 if (old_max_data_size != ssh->max_data_size &&
9350 ssh->max_data_size != 0) {
9351 if (ssh->outgoing_data_size > ssh->max_data_size ||
9352 ssh->incoming_data_size > ssh->max_data_size)
9353 rekeying = "data limit lowered";
9356 if (ssh->cfg.compression != cfg->compression) {
9357 rekeying = "compression setting changed";
9358 rekey_mandatory = TRUE;
9361 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
9362 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
9363 sizeof(ssh->cfg.ssh_cipherlist))) {
9364 rekeying = "cipher settings changed";
9365 rekey_mandatory = TRUE;
9368 ssh->cfg = *cfg; /* STRUCTURE COPY */
9371 if (!ssh->kex_in_progress) {
9372 do_ssh2_transport(ssh, rekeying, -1, NULL);
9373 } else if (rekey_mandatory) {
9374 ssh->deferred_rekey_reason = rekeying;
9380 * Called to send data down the SSH connection.
9382 static int ssh_send(void *handle, char *buf, int len)
9384 Ssh ssh = (Ssh) handle;
9386 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9389 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9391 return ssh_sendbuffer(ssh);
9395 * Called to query the current amount of buffered stdin data.
9397 static int ssh_sendbuffer(void *handle)
9399 Ssh ssh = (Ssh) handle;
9402 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9406 * If the SSH socket itself has backed up, add the total backup
9407 * size on that to any individual buffer on the stdin channel.
9410 if (ssh->throttled_all)
9411 override_value = ssh->overall_bufsize;
9413 if (ssh->version == 1) {
9414 return override_value;
9415 } else if (ssh->version == 2) {
9416 if (!ssh->mainchan || ssh->mainchan->closes > 0)
9417 return override_value;
9419 return (override_value +
9420 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9427 * Called to set the size of the window from SSH's POV.
9429 static void ssh_size(void *handle, int width, int height)
9431 Ssh ssh = (Ssh) handle;
9432 struct Packet *pktout;
9434 ssh->term_width = width;
9435 ssh->term_height = height;
9437 switch (ssh->state) {
9438 case SSH_STATE_BEFORE_SIZE:
9439 case SSH_STATE_PREPACKET:
9440 case SSH_STATE_CLOSED:
9441 break; /* do nothing */
9442 case SSH_STATE_INTERMED:
9443 ssh->size_needed = TRUE; /* buffer for later */
9445 case SSH_STATE_SESSION:
9446 if (!ssh->cfg.nopty) {
9447 if (ssh->version == 1) {
9448 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9449 PKT_INT, ssh->term_height,
9450 PKT_INT, ssh->term_width,
9451 PKT_INT, 0, PKT_INT, 0, PKT_END);
9452 } else if (ssh->mainchan) {
9453 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9454 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9455 ssh2_pkt_addstring(pktout, "window-change");
9456 ssh2_pkt_addbool(pktout, 0);
9457 ssh2_pkt_adduint32(pktout, ssh->term_width);
9458 ssh2_pkt_adduint32(pktout, ssh->term_height);
9459 ssh2_pkt_adduint32(pktout, 0);
9460 ssh2_pkt_adduint32(pktout, 0);
9461 ssh2_pkt_send(ssh, pktout);
9469 * Return a list of the special codes that make sense in this
9472 static const struct telnet_special *ssh_get_specials(void *handle)
9474 static const struct telnet_special ssh1_ignore_special[] = {
9475 {"IGNORE message", TS_NOP}
9477 static const struct telnet_special ssh2_ignore_special[] = {
9478 {"IGNORE message", TS_NOP},
9480 static const struct telnet_special ssh2_rekey_special[] = {
9481 {"Repeat key exchange", TS_REKEY},
9483 static const struct telnet_special ssh2_session_specials[] = {
9486 /* These are the signal names defined by RFC 4254.
9487 * They include all the ISO C signals, but are a subset of the POSIX
9488 * required signals. */
9489 {"SIGINT (Interrupt)", TS_SIGINT},
9490 {"SIGTERM (Terminate)", TS_SIGTERM},
9491 {"SIGKILL (Kill)", TS_SIGKILL},
9492 {"SIGQUIT (Quit)", TS_SIGQUIT},
9493 {"SIGHUP (Hangup)", TS_SIGHUP},
9494 {"More signals", TS_SUBMENU},
9495 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9496 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9497 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9498 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9501 static const struct telnet_special specials_end[] = {
9504 /* XXX review this length for any changes: */
9505 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9506 lenof(ssh2_rekey_special) +
9507 lenof(ssh2_session_specials) +
9508 lenof(specials_end)];
9509 Ssh ssh = (Ssh) handle;
9511 #define ADD_SPECIALS(name) \
9513 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9514 memcpy(&ssh_specials[i], name, sizeof name); \
9518 if (ssh->version == 1) {
9519 /* Don't bother offering IGNORE if we've decided the remote
9520 * won't cope with it, since we wouldn't bother sending it if
9522 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9523 ADD_SPECIALS(ssh1_ignore_special);
9524 } else if (ssh->version == 2) {
9525 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9526 ADD_SPECIALS(ssh2_ignore_special);
9527 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9528 ADD_SPECIALS(ssh2_rekey_special);
9530 ADD_SPECIALS(ssh2_session_specials);
9531 } /* else we're not ready yet */
9534 ADD_SPECIALS(specials_end);
9535 return ssh_specials;
9543 * Send special codes. TS_EOF is useful for `plink', so you
9544 * can send an EOF and collect resulting output (e.g. `plink
9547 static void ssh_special(void *handle, Telnet_Special code)
9549 Ssh ssh = (Ssh) handle;
9550 struct Packet *pktout;
9552 if (code == TS_EOF) {
9553 if (ssh->state != SSH_STATE_SESSION) {
9555 * Buffer the EOF in case we are pre-SESSION, so we can
9556 * send it as soon as we reach SESSION.
9559 ssh->eof_needed = TRUE;
9562 if (ssh->version == 1) {
9563 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9564 } else if (ssh->mainchan) {
9565 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
9566 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9567 ssh2_pkt_send(ssh, pktout);
9568 ssh->send_ok = 0; /* now stop trying to read from stdin */
9570 logevent("Sent EOF message");
9571 } else if (code == TS_PING || code == TS_NOP) {
9572 if (ssh->state == SSH_STATE_CLOSED
9573 || ssh->state == SSH_STATE_PREPACKET) return;
9574 if (ssh->version == 1) {
9575 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9576 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9578 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9579 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9580 ssh2_pkt_addstring_start(pktout);
9581 ssh2_pkt_send_noqueue(ssh, pktout);
9584 } else if (code == TS_REKEY) {
9585 if (!ssh->kex_in_progress && ssh->version == 2) {
9586 do_ssh2_transport(ssh, "at user request", -1, NULL);
9588 } else if (code == TS_BRK) {
9589 if (ssh->state == SSH_STATE_CLOSED
9590 || ssh->state == SSH_STATE_PREPACKET) return;
9591 if (ssh->version == 1) {
9592 logevent("Unable to send BREAK signal in SSH-1");
9593 } else if (ssh->mainchan) {
9594 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9595 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9596 ssh2_pkt_addstring(pktout, "break");
9597 ssh2_pkt_addbool(pktout, 0);
9598 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9599 ssh2_pkt_send(ssh, pktout);
9602 /* Is is a POSIX signal? */
9603 char *signame = NULL;
9604 if (code == TS_SIGABRT) signame = "ABRT";
9605 if (code == TS_SIGALRM) signame = "ALRM";
9606 if (code == TS_SIGFPE) signame = "FPE";
9607 if (code == TS_SIGHUP) signame = "HUP";
9608 if (code == TS_SIGILL) signame = "ILL";
9609 if (code == TS_SIGINT) signame = "INT";
9610 if (code == TS_SIGKILL) signame = "KILL";
9611 if (code == TS_SIGPIPE) signame = "PIPE";
9612 if (code == TS_SIGQUIT) signame = "QUIT";
9613 if (code == TS_SIGSEGV) signame = "SEGV";
9614 if (code == TS_SIGTERM) signame = "TERM";
9615 if (code == TS_SIGUSR1) signame = "USR1";
9616 if (code == TS_SIGUSR2) signame = "USR2";
9617 /* The SSH-2 protocol does in principle support arbitrary named
9618 * signals, including signame@domain, but we don't support those. */
9620 /* It's a signal. */
9621 if (ssh->version == 2 && ssh->mainchan) {
9622 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9623 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9624 ssh2_pkt_addstring(pktout, "signal");
9625 ssh2_pkt_addbool(pktout, 0);
9626 ssh2_pkt_addstring(pktout, signame);
9627 ssh2_pkt_send(ssh, pktout);
9628 logeventf(ssh, "Sent signal SIG%s", signame);
9631 /* Never heard of it. Do nothing */
9636 void *new_sock_channel(void *handle, Socket s)
9638 Ssh ssh = (Ssh) handle;
9639 struct ssh_channel *c;
9640 c = snew(struct ssh_channel);
9643 ssh2_channel_init(c);
9645 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9647 add234(ssh->channels, c);
9652 * This is called when stdout/stderr (the entity to which
9653 * from_backend sends data) manages to clear some backlog.
9655 static void ssh_unthrottle(void *handle, int bufsize)
9657 Ssh ssh = (Ssh) handle;
9660 if (ssh->version == 1) {
9661 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9662 ssh->v1_stdout_throttling = 0;
9663 ssh_throttle_conn(ssh, -1);
9666 if (ssh->mainchan) {
9667 ssh2_set_window(ssh->mainchan,
9668 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9669 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9670 if (ssh->cfg.ssh_simple)
9673 buflimit = ssh->mainchan->v.v2.locmaxwin;
9674 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9675 ssh->mainchan->throttling_conn = 0;
9676 ssh_throttle_conn(ssh, -1);
9682 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9684 struct ssh_channel *c = (struct ssh_channel *)channel;
9686 struct Packet *pktout;
9688 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9690 if (ssh->version == 1) {
9691 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9692 PKT_INT, c->localid,
9695 /* PKT_STR, <org:orgport>, */
9698 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9699 ssh2_pkt_addstring(pktout, "direct-tcpip");
9700 ssh2_pkt_adduint32(pktout, c->localid);
9701 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9702 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9703 ssh2_pkt_addstring(pktout, hostname);
9704 ssh2_pkt_adduint32(pktout, port);
9706 * We make up values for the originator data; partly it's
9707 * too much hassle to keep track, and partly I'm not
9708 * convinced the server should be told details like that
9709 * about my local network configuration.
9710 * The "originator IP address" is syntactically a numeric
9711 * IP address, and some servers (e.g., Tectia) get upset
9712 * if it doesn't match this syntax.
9714 ssh2_pkt_addstring(pktout, "0.0.0.0");
9715 ssh2_pkt_adduint32(pktout, 0);
9716 ssh2_pkt_send(ssh, pktout);
9720 static int ssh_connected(void *handle)
9722 Ssh ssh = (Ssh) handle;
9723 return ssh->s != NULL;
9726 static int ssh_sendok(void *handle)
9728 Ssh ssh = (Ssh) handle;
9729 return ssh->send_ok;
9732 static int ssh_ldisc(void *handle, int option)
9734 Ssh ssh = (Ssh) handle;
9735 if (option == LD_ECHO)
9736 return ssh->echoing;
9737 if (option == LD_EDIT)
9738 return ssh->editing;
9742 static void ssh_provide_ldisc(void *handle, void *ldisc)
9744 Ssh ssh = (Ssh) handle;
9748 static void ssh_provide_logctx(void *handle, void *logctx)
9750 Ssh ssh = (Ssh) handle;
9751 ssh->logctx = logctx;
9754 static int ssh_return_exitcode(void *handle)
9756 Ssh ssh = (Ssh) handle;
9760 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
9764 * cfg_info for SSH is the currently running version of the
9765 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9767 static int ssh_cfg_info(void *handle)
9769 Ssh ssh = (Ssh) handle;
9770 return ssh->version;
9774 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9775 * that fails. This variable is the means by which scp.c can reach
9776 * into the SSH code and find out which one it got.
9778 extern int ssh_fallback_cmd(void *handle)
9780 Ssh ssh = (Ssh) handle;
9781 return ssh->fallback_cmd;
9784 Backend ssh_backend = {
9794 ssh_return_exitcode,