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);
476 static void ssh2_channel_check_close(struct ssh_channel *c);
477 static void ssh_channel_destroy(struct ssh_channel *c);
480 * Buffer management constants. There are several of these for
481 * various different purposes:
483 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
484 * on a local data stream before we throttle the whole SSH
485 * connection (in SSH-1 only). Throttling the whole connection is
486 * pretty drastic so we set this high in the hope it won't
489 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
490 * on the SSH connection itself before we defensively throttle
491 * _all_ local data streams. This is pretty drastic too (though
492 * thankfully unlikely in SSH-2 since the window mechanism should
493 * ensure that the server never has any need to throttle its end
494 * of the connection), so we set this high as well.
496 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
499 * - OUR_V2_BIGWIN is the window size we advertise for the only
500 * channel in a simple connection. It must be <= INT_MAX.
502 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
503 * to the remote side. This actually has nothing to do with the
504 * size of the _packet_, but is instead a limit on the amount
505 * of data we're willing to receive in a single SSH2 channel
508 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
509 * _packet_ we're prepared to cope with. It must be a multiple
510 * of the cipher block size, and must be at least 35000.
513 #define SSH1_BUFFER_LIMIT 32768
514 #define SSH_MAX_BACKLOG 32768
515 #define OUR_V2_WINSIZE 16384
516 #define OUR_V2_BIGWIN 0x7fffffff
517 #define OUR_V2_MAXPKT 0x4000UL
518 #define OUR_V2_PACKETLIMIT 0x9000UL
520 /* Maximum length of passwords/passphrases (arbitrary) */
521 #define SSH_MAX_PASSWORD_LEN 100
523 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
525 const static struct ssh_mac *macs[] = {
526 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
528 const static struct ssh_mac *buggymacs[] = {
529 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
532 static void *ssh_comp_none_init(void)
536 static void ssh_comp_none_cleanup(void *handle)
539 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
540 unsigned char **outblock, int *outlen)
544 static int ssh_comp_none_disable(void *handle)
548 const static struct ssh_compress ssh_comp_none = {
550 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
551 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
552 ssh_comp_none_disable, NULL
554 extern const struct ssh_compress ssh_zlib;
555 const static struct ssh_compress *compressions[] = {
556 &ssh_zlib, &ssh_comp_none
559 enum { /* channel types */
564 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
568 * little structure to keep track of outstanding WINDOW_ADJUSTs
576 * 2-3-4 tree storing channels.
579 Ssh ssh; /* pointer back to main context */
580 unsigned remoteid, localid;
582 /* True if we opened this channel but server hasn't confirmed. */
585 * In SSH-1, this value contains four bits:
587 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
588 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
589 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
590 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
592 * A channel is completely finished with when all four bits are set.
594 * In SSH-2, the four bits mean:
596 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
597 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
598 * 4 We have received SSH2_MSG_CHANNEL_EOF.
599 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
601 * A channel is completely finished with when we have both sent
602 * and received CLOSE.
604 * The symbolic constants below use the SSH-2 terminology, which
605 * is a bit confusing in SSH-1, but we have to use _something_.
607 #define CLOSES_SENT_EOF 1
608 #define CLOSES_SENT_CLOSE 2
609 #define CLOSES_RCVD_EOF 4
610 #define CLOSES_RCVD_CLOSE 8
614 * This flag indicates that an EOF is pending on the outgoing side
615 * of the channel: that is, wherever we're getting the data for
616 * this channel has sent us some data followed by EOF. We can't
617 * actually send the EOF until we've finished sending the data, so
618 * we set this flag instead to remind us to do so once our buffer
624 * True if this channel is causing the underlying connection to be
629 struct ssh2_data_channel {
631 unsigned remwindow, remmaxpkt;
632 /* locwindow is signed so we can cope with excess data. */
633 int locwindow, locmaxwin;
635 * remlocwin is the amount of local window that we think
636 * the remote end had available to it after it sent the
637 * last data packet or window adjust ack.
641 * These store the list of window adjusts that haven't
644 struct winadj *winadj_head, *winadj_tail;
645 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
649 struct ssh_agent_channel {
650 unsigned char *message;
651 unsigned char msglen[4];
652 unsigned lensofar, totallen;
654 struct ssh_x11_channel {
657 struct ssh_pfd_channel {
664 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
665 * use this structure in different ways, reflecting SSH-2's
666 * altogether saner approach to port forwarding.
668 * In SSH-1, you arrange a remote forwarding by sending the server
669 * the remote port number, and the local destination host:port.
670 * When a connection comes in, the server sends you back that
671 * host:port pair, and you connect to it. This is a ready-made
672 * security hole if you're not on the ball: a malicious server
673 * could send you back _any_ host:port pair, so if you trustingly
674 * connect to the address it gives you then you've just opened the
675 * entire inside of your corporate network just by connecting
676 * through it to a dodgy SSH server. Hence, we must store a list of
677 * host:port pairs we _are_ trying to forward to, and reject a
678 * connection request from the server if it's not in the list.
680 * In SSH-2, each side of the connection minds its own business and
681 * doesn't send unnecessary information to the other. You arrange a
682 * remote forwarding by sending the server just the remote port
683 * number. When a connection comes in, the server tells you which
684 * of its ports was connected to; and _you_ have to remember what
685 * local host:port pair went with that port number.
687 * Hence, in SSH-1 this structure is indexed by destination
688 * host:port pair, whereas in SSH-2 it is indexed by source port.
690 struct ssh_portfwd; /* forward declaration */
692 struct ssh_rportfwd {
693 unsigned sport, dport;
696 struct ssh_portfwd *pfrec;
698 #define free_rportfwd(pf) ( \
699 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
702 * Separately to the rportfwd tree (which is for looking up port
703 * open requests from the server), a tree of _these_ structures is
704 * used to keep track of all the currently open port forwardings,
705 * so that we can reconfigure in mid-session if the user requests
709 enum { DESTROY, KEEP, CREATE } status;
711 unsigned sport, dport;
714 struct ssh_rportfwd *remote;
718 #define free_portfwd(pf) ( \
719 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
720 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
723 long length; /* length of `data' actually used */
724 long forcepad; /* SSH-2: force padding to at least this length */
725 int type; /* only used for incoming packets */
726 unsigned long sequence; /* SSH-2 incoming sequence number */
727 unsigned char *data; /* allocated storage */
728 unsigned char *body; /* offset of payload within `data' */
729 long savedpos; /* temporary index into `data' (for strings) */
730 long maxlen; /* amount of storage allocated for `data' */
731 long encrypted_len; /* for SSH-2 total-size counting */
734 * State associated with packet logging
738 struct logblank_t *blanks;
741 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
742 struct Packet *pktin);
743 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
744 struct Packet *pktin);
745 static void ssh1_protocol_setup(Ssh ssh);
746 static void ssh2_protocol_setup(Ssh ssh);
747 static void ssh_size(void *handle, int width, int height);
748 static void ssh_special(void *handle, Telnet_Special);
749 static int ssh2_try_send(struct ssh_channel *c);
750 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
751 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
752 static void ssh2_set_window(struct ssh_channel *c, int newwin);
753 static int ssh_sendbuffer(void *handle);
754 static int ssh_do_close(Ssh ssh, int notify_exit);
755 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
756 static int ssh2_pkt_getbool(struct Packet *pkt);
757 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
758 static void ssh2_timer(void *ctx, long now);
759 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
760 struct Packet *pktin);
762 struct rdpkt1_state_tag {
763 long len, pad, biglen, to_read;
764 unsigned long realcrc, gotcrc;
768 struct Packet *pktin;
771 struct rdpkt2_state_tag {
772 long len, pad, payload, packetlen, maclen;
775 unsigned long incoming_sequence;
776 struct Packet *pktin;
779 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
780 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
782 struct queued_handler;
783 struct queued_handler {
785 chandler_fn_t handler;
787 struct queued_handler *next;
791 const struct plug_function_table *fn;
792 /* the above field _must_ be first in the structure */
802 unsigned char session_key[32];
804 int v1_remote_protoflags;
805 int v1_local_protoflags;
806 int agentfwd_enabled;
809 const struct ssh_cipher *cipher;
812 const struct ssh2_cipher *cscipher, *sccipher;
813 void *cs_cipher_ctx, *sc_cipher_ctx;
814 const struct ssh_mac *csmac, *scmac;
815 void *cs_mac_ctx, *sc_mac_ctx;
816 const struct ssh_compress *cscomp, *sccomp;
817 void *cs_comp_ctx, *sc_comp_ctx;
818 const struct ssh_kex *kex;
819 const struct ssh_signkey *hostkey;
820 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
821 int v2_session_id_len;
827 int echoing, editing;
831 int ospeed, ispeed; /* temporaries */
832 int term_width, term_height;
834 tree234 *channels; /* indexed by local id */
835 struct ssh_channel *mainchan; /* primary session channel */
836 int ncmode; /* is primary channel direct-tcpip? */
841 tree234 *rportfwds, *portfwds;
845 SSH_STATE_BEFORE_SIZE,
851 int size_needed, eof_needed;
852 int sent_console_eof;
853 int got_pty; /* affects EOF behaviour on main channel */
855 struct Packet **queue;
856 int queuelen, queuesize;
858 unsigned char *deferred_send_data;
859 int deferred_len, deferred_size;
862 * Gross hack: pscp will try to start SFTP but fall back to
863 * scp1 if that fails. This variable is the means by which
864 * scp.c can reach into the SSH code and find out which one it
869 bufchain banner; /* accumulates banners during do_ssh2_authconn */
874 struct X11Display *x11disp;
877 int conn_throttle_count;
880 int v1_stdout_throttling;
881 unsigned long v2_outgoing_sequence;
883 int ssh1_rdpkt_crstate;
884 int ssh2_rdpkt_crstate;
885 int do_ssh_init_crstate;
886 int ssh_gotdata_crstate;
887 int do_ssh1_login_crstate;
888 int do_ssh1_connection_crstate;
889 int do_ssh2_transport_crstate;
890 int do_ssh2_authconn_crstate;
892 void *do_ssh_init_state;
893 void *do_ssh1_login_state;
894 void *do_ssh2_transport_state;
895 void *do_ssh2_authconn_state;
897 struct rdpkt1_state_tag rdpkt1_state;
898 struct rdpkt2_state_tag rdpkt2_state;
900 /* SSH-1 and SSH-2 use this for different things, but both use it */
901 int protocol_initial_phase_done;
903 void (*protocol) (Ssh ssh, void *vin, int inlen,
905 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
908 * We maintain our own copy of a Conf structure here. That way,
909 * when we're passed a new one for reconfiguration, we can check
910 * the differences and potentially reconfigure port forwardings
911 * etc in mid-session.
916 * Values cached out of conf so as to avoid the tree234 lookup
917 * cost every time they're used.
922 * Dynamically allocated username string created during SSH
923 * login. Stored in here rather than in the coroutine state so
924 * that it'll be reliably freed if we shut down the SSH session
925 * at some unexpected moment.
930 * Used to transfer data back from async callbacks.
932 void *agent_response;
933 int agent_response_len;
937 * The SSH connection can be set as `frozen', meaning we are
938 * not currently accepting incoming data from the network. This
939 * is slightly more serious than setting the _socket_ as
940 * frozen, because we may already have had data passed to us
941 * from the network which we need to delay processing until
942 * after the freeze is lifted, so we also need a bufchain to
946 bufchain queued_incoming_data;
949 * Dispatch table for packet types that we may have to deal
952 handler_fn_t packet_dispatch[256];
955 * Queues of one-off handler functions for success/failure
956 * indications from a request.
958 struct queued_handler *qhead, *qtail;
961 * This module deals with sending keepalives.
966 * Track incoming and outgoing data sizes and time, for
969 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
970 unsigned long max_data_size;
972 long next_rekey, last_rekey;
973 char *deferred_rekey_reason; /* points to STATIC string; don't free */
976 * Fully qualified host name, which we need if doing GSSAPI.
982 * GSSAPI libraries for this session.
984 struct ssh_gss_liblist *gsslibs;
988 #define logevent(s) logevent(ssh->frontend, s)
990 /* logevent, only printf-formatted. */
991 static void logeventf(Ssh ssh, const char *fmt, ...)
997 buf = dupvprintf(fmt, ap);
1003 #define bombout(msg) \
1005 char *text = dupprintf msg; \
1006 ssh_do_close(ssh, FALSE); \
1008 connection_fatal(ssh->frontend, "%s", text); \
1012 /* Functions to leave bits out of the SSH packet log file. */
1014 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1016 if (conf_get_int(ssh->conf, CONF_logomitpass))
1017 pkt->logmode = blanktype;
1020 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1022 if (ssh->logomitdata)
1023 pkt->logmode = blanktype;
1026 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1028 pkt->logmode = PKTLOG_EMIT;
1031 /* Helper function for common bits of parsing ttymodes. */
1032 static void parse_ttymodes(Ssh ssh,
1033 void (*do_mode)(void *data, char *mode, char *val),
1038 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1040 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1042 * val[0] is either 'V', indicating that an explicit value
1043 * follows it, or 'A' indicating that we should pass the
1044 * value through from the local environment via get_ttymode.
1047 val = get_ttymode(ssh->frontend, key);
1049 val++; /* skip the 'V' */
1051 do_mode(data, key, val);
1055 static int ssh_channelcmp(void *av, void *bv)
1057 struct ssh_channel *a = (struct ssh_channel *) av;
1058 struct ssh_channel *b = (struct ssh_channel *) bv;
1059 if (a->localid < b->localid)
1061 if (a->localid > b->localid)
1065 static int ssh_channelfind(void *av, void *bv)
1067 unsigned *a = (unsigned *) av;
1068 struct ssh_channel *b = (struct ssh_channel *) bv;
1069 if (*a < b->localid)
1071 if (*a > b->localid)
1076 static int ssh_rportcmp_ssh1(void *av, void *bv)
1078 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1079 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1081 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1082 return i < 0 ? -1 : +1;
1083 if (a->dport > b->dport)
1085 if (a->dport < b->dport)
1090 static int ssh_rportcmp_ssh2(void *av, void *bv)
1092 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1093 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1095 if (a->sport > b->sport)
1097 if (a->sport < b->sport)
1103 * Special form of strcmp which can cope with NULL inputs. NULL is
1104 * defined to sort before even the empty string.
1106 static int nullstrcmp(const char *a, const char *b)
1108 if (a == NULL && b == NULL)
1114 return strcmp(a, b);
1117 static int ssh_portcmp(void *av, void *bv)
1119 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1120 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1122 if (a->type > b->type)
1124 if (a->type < b->type)
1126 if (a->addressfamily > b->addressfamily)
1128 if (a->addressfamily < b->addressfamily)
1130 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1131 return i < 0 ? -1 : +1;
1132 if (a->sport > b->sport)
1134 if (a->sport < b->sport)
1136 if (a->type != 'D') {
1137 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1138 return i < 0 ? -1 : +1;
1139 if (a->dport > b->dport)
1141 if (a->dport < b->dport)
1147 static int alloc_channel_id(Ssh ssh)
1149 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1150 unsigned low, high, mid;
1152 struct ssh_channel *c;
1155 * First-fit allocation of channel numbers: always pick the
1156 * lowest unused one. To do this, binary-search using the
1157 * counted B-tree to find the largest channel ID which is in a
1158 * contiguous sequence from the beginning. (Precisely
1159 * everything in that sequence must have ID equal to its tree
1160 * index plus CHANNEL_NUMBER_OFFSET.)
1162 tsize = count234(ssh->channels);
1166 while (high - low > 1) {
1167 mid = (high + low) / 2;
1168 c = index234(ssh->channels, mid);
1169 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1170 low = mid; /* this one is fine */
1172 high = mid; /* this one is past it */
1175 * Now low points to either -1, or the tree index of the
1176 * largest ID in the initial sequence.
1179 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1180 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1182 return low + 1 + CHANNEL_NUMBER_OFFSET;
1185 static void c_write_stderr(int trusted, const char *buf, int len)
1188 for (i = 0; i < len; i++)
1189 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1190 fputc(buf[i], stderr);
1193 static void c_write(Ssh ssh, const char *buf, int len)
1195 if (flags & FLAG_STDERR)
1196 c_write_stderr(1, buf, len);
1198 from_backend(ssh->frontend, 1, buf, len);
1201 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1203 if (flags & FLAG_STDERR)
1204 c_write_stderr(0, buf, len);
1206 from_backend_untrusted(ssh->frontend, buf, len);
1209 static void c_write_str(Ssh ssh, const char *buf)
1211 c_write(ssh, buf, strlen(buf));
1214 static void ssh_free_packet(struct Packet *pkt)
1219 static struct Packet *ssh_new_packet(void)
1221 struct Packet *pkt = snew(struct Packet);
1223 pkt->body = pkt->data = NULL;
1225 pkt->logmode = PKTLOG_EMIT;
1233 * Collect incoming data in the incoming packet buffer.
1234 * Decipher and verify the packet when it is completely read.
1235 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1236 * Update the *data and *datalen variables.
1237 * Return a Packet structure when a packet is completed.
1239 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1241 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1243 crBegin(ssh->ssh1_rdpkt_crstate);
1245 st->pktin = ssh_new_packet();
1247 st->pktin->type = 0;
1248 st->pktin->length = 0;
1250 for (st->i = st->len = 0; st->i < 4; st->i++) {
1251 while ((*datalen) == 0)
1253 st->len = (st->len << 8) + **data;
1254 (*data)++, (*datalen)--;
1257 st->pad = 8 - (st->len % 8);
1258 st->biglen = st->len + st->pad;
1259 st->pktin->length = st->len - 5;
1261 if (st->biglen < 0) {
1262 bombout(("Extremely large packet length from server suggests"
1263 " data stream corruption"));
1264 ssh_free_packet(st->pktin);
1268 st->pktin->maxlen = st->biglen;
1269 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1271 st->to_read = st->biglen;
1272 st->p = st->pktin->data;
1273 while (st->to_read > 0) {
1274 st->chunk = st->to_read;
1275 while ((*datalen) == 0)
1277 if (st->chunk > (*datalen))
1278 st->chunk = (*datalen);
1279 memcpy(st->p, *data, st->chunk);
1281 *datalen -= st->chunk;
1283 st->to_read -= st->chunk;
1286 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1287 st->biglen, NULL)) {
1288 bombout(("Network attack (CRC compensation) detected!"));
1289 ssh_free_packet(st->pktin);
1294 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1296 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1297 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1298 if (st->gotcrc != st->realcrc) {
1299 bombout(("Incorrect CRC received on packet"));
1300 ssh_free_packet(st->pktin);
1304 st->pktin->body = st->pktin->data + st->pad + 1;
1305 st->pktin->savedpos = 0;
1307 if (ssh->v1_compressing) {
1308 unsigned char *decompblk;
1310 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1311 st->pktin->body - 1, st->pktin->length + 1,
1312 &decompblk, &decomplen)) {
1313 bombout(("Zlib decompression encountered invalid data"));
1314 ssh_free_packet(st->pktin);
1318 if (st->pktin->maxlen < st->pad + decomplen) {
1319 st->pktin->maxlen = st->pad + decomplen;
1320 st->pktin->data = sresize(st->pktin->data,
1321 st->pktin->maxlen + APIEXTRA,
1323 st->pktin->body = st->pktin->data + st->pad + 1;
1326 memcpy(st->pktin->body - 1, decompblk, decomplen);
1328 st->pktin->length = decomplen - 1;
1331 st->pktin->type = st->pktin->body[-1];
1334 * Log incoming packet, possibly omitting sensitive fields.
1338 struct logblank_t blank;
1339 if (ssh->logomitdata) {
1340 int do_blank = FALSE, blank_prefix = 0;
1341 /* "Session data" packets - omit the data field */
1342 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1343 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1344 do_blank = TRUE; blank_prefix = 4;
1345 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1346 do_blank = TRUE; blank_prefix = 8;
1349 blank.offset = blank_prefix;
1350 blank.len = st->pktin->length;
1351 blank.type = PKTLOG_OMIT;
1355 log_packet(ssh->logctx,
1356 PKT_INCOMING, st->pktin->type,
1357 ssh1_pkt_type(st->pktin->type),
1358 st->pktin->body, st->pktin->length,
1359 nblanks, &blank, NULL);
1362 crFinish(st->pktin);
1365 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1367 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1369 crBegin(ssh->ssh2_rdpkt_crstate);
1371 st->pktin = ssh_new_packet();
1373 st->pktin->type = 0;
1374 st->pktin->length = 0;
1376 st->cipherblk = ssh->sccipher->blksize;
1379 if (st->cipherblk < 8)
1381 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1383 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1386 * When dealing with a CBC-mode cipher, we want to avoid the
1387 * possibility of an attacker's tweaking the ciphertext stream
1388 * so as to cause us to feed the same block to the block
1389 * cipher more than once and thus leak information
1390 * (VU#958563). The way we do this is not to take any
1391 * decisions on the basis of anything we've decrypted until
1392 * we've verified it with a MAC. That includes the packet
1393 * length, so we just read data and check the MAC repeatedly,
1394 * and when the MAC passes, see if the length we've got is
1398 /* May as well allocate the whole lot now. */
1399 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1402 /* Read an amount corresponding to the MAC. */
1403 for (st->i = 0; st->i < st->maclen; st->i++) {
1404 while ((*datalen) == 0)
1406 st->pktin->data[st->i] = *(*data)++;
1412 unsigned char seq[4];
1413 ssh->scmac->start(ssh->sc_mac_ctx);
1414 PUT_32BIT(seq, st->incoming_sequence);
1415 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1418 for (;;) { /* Once around this loop per cipher block. */
1419 /* Read another cipher-block's worth, and tack it onto the end. */
1420 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1421 while ((*datalen) == 0)
1423 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1426 /* Decrypt one more block (a little further back in the stream). */
1427 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1428 st->pktin->data + st->packetlen,
1430 /* Feed that block to the MAC. */
1431 ssh->scmac->bytes(ssh->sc_mac_ctx,
1432 st->pktin->data + st->packetlen, st->cipherblk);
1433 st->packetlen += st->cipherblk;
1434 /* See if that gives us a valid packet. */
1435 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1436 st->pktin->data + st->packetlen) &&
1437 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1439 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1440 bombout(("No valid incoming packet found"));
1441 ssh_free_packet(st->pktin);
1445 st->pktin->maxlen = st->packetlen + st->maclen;
1446 st->pktin->data = sresize(st->pktin->data,
1447 st->pktin->maxlen + APIEXTRA,
1450 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1453 * Acquire and decrypt the first block of the packet. This will
1454 * contain the length and padding details.
1456 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1457 while ((*datalen) == 0)
1459 st->pktin->data[st->i] = *(*data)++;
1464 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1465 st->pktin->data, st->cipherblk);
1468 * Now get the length figure.
1470 st->len = GET_32BIT(st->pktin->data);
1473 * _Completely_ silly lengths should be stomped on before they
1474 * do us any more damage.
1476 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1477 (st->len + 4) % st->cipherblk != 0) {
1478 bombout(("Incoming packet was garbled on decryption"));
1479 ssh_free_packet(st->pktin);
1484 * So now we can work out the total packet length.
1486 st->packetlen = st->len + 4;
1489 * Allocate memory for the rest of the packet.
1491 st->pktin->maxlen = st->packetlen + st->maclen;
1492 st->pktin->data = sresize(st->pktin->data,
1493 st->pktin->maxlen + APIEXTRA,
1497 * Read and decrypt the remainder of the packet.
1499 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1501 while ((*datalen) == 0)
1503 st->pktin->data[st->i] = *(*data)++;
1506 /* Decrypt everything _except_ the MAC. */
1508 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1509 st->pktin->data + st->cipherblk,
1510 st->packetlen - st->cipherblk);
1516 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1517 st->len + 4, st->incoming_sequence)) {
1518 bombout(("Incorrect MAC received on packet"));
1519 ssh_free_packet(st->pktin);
1523 /* Get and sanity-check the amount of random padding. */
1524 st->pad = st->pktin->data[4];
1525 if (st->pad < 4 || st->len - st->pad < 1) {
1526 bombout(("Invalid padding length on received packet"));
1527 ssh_free_packet(st->pktin);
1531 * This enables us to deduce the payload length.
1533 st->payload = st->len - st->pad - 1;
1535 st->pktin->length = st->payload + 5;
1536 st->pktin->encrypted_len = st->packetlen;
1538 st->pktin->sequence = st->incoming_sequence++;
1541 * Decompress packet payload.
1544 unsigned char *newpayload;
1547 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1548 st->pktin->data + 5, st->pktin->length - 5,
1549 &newpayload, &newlen)) {
1550 if (st->pktin->maxlen < newlen + 5) {
1551 st->pktin->maxlen = newlen + 5;
1552 st->pktin->data = sresize(st->pktin->data,
1553 st->pktin->maxlen + APIEXTRA,
1556 st->pktin->length = 5 + newlen;
1557 memcpy(st->pktin->data + 5, newpayload, newlen);
1562 st->pktin->savedpos = 6;
1563 st->pktin->body = st->pktin->data;
1564 st->pktin->type = st->pktin->data[5];
1567 * Log incoming packet, possibly omitting sensitive fields.
1571 struct logblank_t blank;
1572 if (ssh->logomitdata) {
1573 int do_blank = FALSE, blank_prefix = 0;
1574 /* "Session data" packets - omit the data field */
1575 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1576 do_blank = TRUE; blank_prefix = 8;
1577 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1578 do_blank = TRUE; blank_prefix = 12;
1581 blank.offset = blank_prefix;
1582 blank.len = (st->pktin->length-6) - blank_prefix;
1583 blank.type = PKTLOG_OMIT;
1587 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1588 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1590 st->pktin->data+6, st->pktin->length-6,
1591 nblanks, &blank, &st->pktin->sequence);
1594 crFinish(st->pktin);
1597 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1599 int pad, biglen, i, pktoffs;
1603 * XXX various versions of SC (including 8.8.4) screw up the
1604 * register allocation in this function and use the same register
1605 * (D6) for len and as a temporary, with predictable results. The
1606 * following sledgehammer prevents this.
1613 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1614 ssh1_pkt_type(pkt->data[12]),
1615 pkt->body, pkt->length - (pkt->body - pkt->data),
1616 pkt->nblanks, pkt->blanks, NULL);
1617 sfree(pkt->blanks); pkt->blanks = NULL;
1620 if (ssh->v1_compressing) {
1621 unsigned char *compblk;
1623 zlib_compress_block(ssh->cs_comp_ctx,
1624 pkt->data + 12, pkt->length - 12,
1625 &compblk, &complen);
1626 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1627 memcpy(pkt->data + 12, compblk, complen);
1629 pkt->length = complen + 12;
1632 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1634 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1635 pad = 8 - (len % 8);
1637 biglen = len + pad; /* len(padding+type+data+CRC) */
1639 for (i = pktoffs; i < 4+8; i++)
1640 pkt->data[i] = random_byte();
1641 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1642 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1643 PUT_32BIT(pkt->data + pktoffs, len);
1646 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1647 pkt->data + pktoffs + 4, biglen);
1649 if (offset_p) *offset_p = pktoffs;
1650 return biglen + 4; /* len(length+padding+type+data+CRC) */
1653 static int s_write(Ssh ssh, void *data, int len)
1656 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1658 return sk_write(ssh->s, (char *)data, len);
1661 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1663 int len, backlog, offset;
1664 len = s_wrpkt_prepare(ssh, pkt, &offset);
1665 backlog = s_write(ssh, pkt->data + offset, len);
1666 if (backlog > SSH_MAX_BACKLOG)
1667 ssh_throttle_all(ssh, 1, backlog);
1668 ssh_free_packet(pkt);
1671 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1674 len = s_wrpkt_prepare(ssh, pkt, &offset);
1675 if (ssh->deferred_len + len > ssh->deferred_size) {
1676 ssh->deferred_size = ssh->deferred_len + len + 128;
1677 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1681 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1682 pkt->data + offset, len);
1683 ssh->deferred_len += len;
1684 ssh_free_packet(pkt);
1688 * Construct a SSH-1 packet with the specified contents.
1689 * (This all-at-once interface used to be the only one, but now SSH-1
1690 * packets can also be constructed incrementally.)
1692 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1698 pkt = ssh1_pkt_init(pkttype);
1700 while ((argtype = va_arg(ap, int)) != PKT_END) {
1701 unsigned char *argp, argchar;
1703 unsigned long argint;
1706 /* Actual fields in the packet */
1708 argint = va_arg(ap, int);
1709 ssh_pkt_adduint32(pkt, argint);
1712 argchar = (unsigned char) va_arg(ap, int);
1713 ssh_pkt_addbyte(pkt, argchar);
1716 argp = va_arg(ap, unsigned char *);
1717 arglen = va_arg(ap, int);
1718 ssh_pkt_adddata(pkt, argp, arglen);
1721 sargp = va_arg(ap, char *);
1722 ssh_pkt_addstring(pkt, sargp);
1725 bn = va_arg(ap, Bignum);
1726 ssh1_pkt_addmp(pkt, bn);
1728 /* Tokens for modifications to packet logging */
1730 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1733 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1736 end_log_omission(ssh, pkt);
1744 static void send_packet(Ssh ssh, int pkttype, ...)
1748 va_start(ap, pkttype);
1749 pkt = construct_packet(ssh, pkttype, ap);
1754 static void defer_packet(Ssh ssh, int pkttype, ...)
1758 va_start(ap, pkttype);
1759 pkt = construct_packet(ssh, pkttype, ap);
1761 s_wrpkt_defer(ssh, pkt);
1764 static int ssh_versioncmp(char *a, char *b)
1767 unsigned long av, bv;
1769 av = strtoul(a, &ae, 10);
1770 bv = strtoul(b, &be, 10);
1772 return (av < bv ? -1 : +1);
1777 av = strtoul(ae, &ae, 10);
1778 bv = strtoul(be, &be, 10);
1780 return (av < bv ? -1 : +1);
1785 * Utility routines for putting an SSH-protocol `string' and
1786 * `uint32' into a hash state.
1788 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1790 unsigned char lenblk[4];
1791 PUT_32BIT(lenblk, len);
1792 h->bytes(s, lenblk, 4);
1793 h->bytes(s, str, len);
1796 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1798 unsigned char intblk[4];
1799 PUT_32BIT(intblk, i);
1800 h->bytes(s, intblk, 4);
1804 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1806 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1808 if (pkt->maxlen < length) {
1809 unsigned char *body = pkt->body;
1810 int offset = body ? body - pkt->data : 0;
1811 pkt->maxlen = length + 256;
1812 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1813 if (body) pkt->body = pkt->data + offset;
1816 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1818 if (pkt->logmode != PKTLOG_EMIT) {
1820 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1822 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1823 (pkt->body - pkt->data);
1824 pkt->blanks[pkt->nblanks-1].len = len;
1825 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1828 ssh_pkt_ensure(pkt, pkt->length);
1829 memcpy(pkt->data + pkt->length - len, data, len);
1831 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1833 ssh_pkt_adddata(pkt, &byte, 1);
1835 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1837 ssh_pkt_adddata(pkt, &value, 1);
1839 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1842 PUT_32BIT(x, value);
1843 ssh_pkt_adddata(pkt, x, 4);
1845 static void ssh_pkt_addstring_start(struct Packet *pkt)
1847 ssh_pkt_adduint32(pkt, 0);
1848 pkt->savedpos = pkt->length;
1850 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1852 ssh_pkt_adddata(pkt, data, strlen(data));
1853 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1855 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1857 ssh_pkt_adddata(pkt, data, len);
1858 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1860 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1862 ssh_pkt_addstring_start(pkt);
1863 ssh_pkt_addstring_str(pkt, data);
1865 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1867 int len = ssh1_bignum_length(b);
1868 unsigned char *data = snewn(len, unsigned char);
1869 (void) ssh1_write_bignum(data, b);
1870 ssh_pkt_adddata(pkt, data, len);
1873 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1876 int i, n = (bignum_bitcount(b) + 7) / 8;
1877 p = snewn(n + 1, unsigned char);
1879 for (i = 1; i <= n; i++)
1880 p[i] = bignum_byte(b, n - i);
1882 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1884 memmove(p, p + i, n + 1 - i);
1888 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1892 p = ssh2_mpint_fmt(b, &len);
1893 ssh_pkt_addstring_start(pkt);
1894 ssh_pkt_addstring_data(pkt, (char *)p, len);
1898 static struct Packet *ssh1_pkt_init(int pkt_type)
1900 struct Packet *pkt = ssh_new_packet();
1901 pkt->length = 4 + 8; /* space for length + max padding */
1902 ssh_pkt_addbyte(pkt, pkt_type);
1903 pkt->body = pkt->data + pkt->length;
1907 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1908 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1909 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1910 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1911 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1912 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1913 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1914 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1915 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1917 static struct Packet *ssh2_pkt_init(int pkt_type)
1919 struct Packet *pkt = ssh_new_packet();
1920 pkt->length = 5; /* space for packet length + padding length */
1922 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1923 pkt->body = pkt->data + pkt->length; /* after packet type */
1928 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1929 * put the MAC on it. Final packet, ready to be sent, is stored in
1930 * pkt->data. Total length is returned.
1932 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1934 int cipherblk, maclen, padding, i;
1937 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1938 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1939 pkt->body, pkt->length - (pkt->body - pkt->data),
1940 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1941 sfree(pkt->blanks); pkt->blanks = NULL;
1945 * Compress packet payload.
1948 unsigned char *newpayload;
1951 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1953 &newpayload, &newlen)) {
1955 ssh2_pkt_adddata(pkt, newpayload, newlen);
1961 * Add padding. At least four bytes, and must also bring total
1962 * length (minus MAC) up to a multiple of the block size.
1963 * If pkt->forcepad is set, make sure the packet is at least that size
1966 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1967 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1969 if (pkt->length + padding < pkt->forcepad)
1970 padding = pkt->forcepad - pkt->length;
1972 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1973 assert(padding <= 255);
1974 maclen = ssh->csmac ? ssh->csmac->len : 0;
1975 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1976 pkt->data[4] = padding;
1977 for (i = 0; i < padding; i++)
1978 pkt->data[pkt->length + i] = random_byte();
1979 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1981 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1982 pkt->length + padding,
1983 ssh->v2_outgoing_sequence);
1984 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1987 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1988 pkt->data, pkt->length + padding);
1990 pkt->encrypted_len = pkt->length + padding;
1992 /* Ready-to-send packet starts at pkt->data. We return length. */
1993 return pkt->length + padding + maclen;
1997 * Routines called from the main SSH code to send packets. There
1998 * are quite a few of these, because we have two separate
1999 * mechanisms for delaying the sending of packets:
2001 * - In order to send an IGNORE message and a password message in
2002 * a single fixed-length blob, we require the ability to
2003 * concatenate the encrypted forms of those two packets _into_ a
2004 * single blob and then pass it to our <network.h> transport
2005 * layer in one go. Hence, there's a deferment mechanism which
2006 * works after packet encryption.
2008 * - In order to avoid sending any connection-layer messages
2009 * during repeat key exchange, we have to queue up any such
2010 * outgoing messages _before_ they are encrypted (and in
2011 * particular before they're allocated sequence numbers), and
2012 * then send them once we've finished.
2014 * I call these mechanisms `defer' and `queue' respectively, so as
2015 * to distinguish them reasonably easily.
2017 * The functions send_noqueue() and defer_noqueue() free the packet
2018 * structure they are passed. Every outgoing packet goes through
2019 * precisely one of these functions in its life; packets passed to
2020 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2021 * these or get queued, and then when the queue is later emptied
2022 * the packets are all passed to defer_noqueue().
2024 * When using a CBC-mode cipher, it's necessary to ensure that an
2025 * attacker can't provide data to be encrypted using an IV that they
2026 * know. We ensure this by prefixing each packet that might contain
2027 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2028 * mechanism, so in this case send_noqueue() ends up redirecting to
2029 * defer_noqueue(). If you don't like this inefficiency, don't use
2033 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2034 static void ssh_pkt_defersend(Ssh);
2037 * Send an SSH-2 packet immediately, without queuing or deferring.
2039 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2043 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2044 /* We need to send two packets, so use the deferral mechanism. */
2045 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2046 ssh_pkt_defersend(ssh);
2049 len = ssh2_pkt_construct(ssh, pkt);
2050 backlog = s_write(ssh, pkt->data, len);
2051 if (backlog > SSH_MAX_BACKLOG)
2052 ssh_throttle_all(ssh, 1, backlog);
2054 ssh->outgoing_data_size += pkt->encrypted_len;
2055 if (!ssh->kex_in_progress &&
2056 ssh->max_data_size != 0 &&
2057 ssh->outgoing_data_size > ssh->max_data_size)
2058 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2060 ssh_free_packet(pkt);
2064 * Defer an SSH-2 packet.
2066 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2069 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2070 ssh->deferred_len == 0 && !noignore &&
2071 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2073 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2074 * get encrypted with a known IV.
2076 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2077 ssh2_pkt_addstring_start(ipkt);
2078 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2080 len = ssh2_pkt_construct(ssh, pkt);
2081 if (ssh->deferred_len + len > ssh->deferred_size) {
2082 ssh->deferred_size = ssh->deferred_len + len + 128;
2083 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2087 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2088 ssh->deferred_len += len;
2089 ssh->deferred_data_size += pkt->encrypted_len;
2090 ssh_free_packet(pkt);
2094 * Queue an SSH-2 packet.
2096 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2098 assert(ssh->queueing);
2100 if (ssh->queuelen >= ssh->queuesize) {
2101 ssh->queuesize = ssh->queuelen + 32;
2102 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2105 ssh->queue[ssh->queuelen++] = pkt;
2109 * Either queue or send a packet, depending on whether queueing is
2112 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2115 ssh2_pkt_queue(ssh, pkt);
2117 ssh2_pkt_send_noqueue(ssh, pkt);
2121 * Either queue or defer a packet, depending on whether queueing is
2124 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2127 ssh2_pkt_queue(ssh, pkt);
2129 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2133 * Send the whole deferred data block constructed by
2134 * ssh2_pkt_defer() or SSH-1's defer_packet().
2136 * The expected use of the defer mechanism is that you call
2137 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2138 * not currently queueing, this simply sets up deferred_send_data
2139 * and then sends it. If we _are_ currently queueing, the calls to
2140 * ssh2_pkt_defer() put the deferred packets on to the queue
2141 * instead, and therefore ssh_pkt_defersend() has no deferred data
2142 * to send. Hence, there's no need to make it conditional on
2145 static void ssh_pkt_defersend(Ssh ssh)
2148 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2149 ssh->deferred_len = ssh->deferred_size = 0;
2150 sfree(ssh->deferred_send_data);
2151 ssh->deferred_send_data = NULL;
2152 if (backlog > SSH_MAX_BACKLOG)
2153 ssh_throttle_all(ssh, 1, backlog);
2155 ssh->outgoing_data_size += ssh->deferred_data_size;
2156 if (!ssh->kex_in_progress &&
2157 ssh->max_data_size != 0 &&
2158 ssh->outgoing_data_size > ssh->max_data_size)
2159 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2160 ssh->deferred_data_size = 0;
2164 * Send a packet whose length needs to be disguised (typically
2165 * passwords or keyboard-interactive responses).
2167 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2173 * The simplest way to do this is to adjust the
2174 * variable-length padding field in the outgoing packet.
2176 * Currently compiled out, because some Cisco SSH servers
2177 * don't like excessively padded packets (bah, why's it
2180 pkt->forcepad = padsize;
2181 ssh2_pkt_send(ssh, pkt);
2186 * If we can't do that, however, an alternative approach is
2187 * to use the pkt_defer mechanism to bundle the packet
2188 * tightly together with an SSH_MSG_IGNORE such that their
2189 * combined length is a constant. So first we construct the
2190 * final form of this packet and defer its sending.
2192 ssh2_pkt_defer(ssh, pkt);
2195 * Now construct an SSH_MSG_IGNORE which includes a string
2196 * that's an exact multiple of the cipher block size. (If
2197 * the cipher is NULL so that the block size is
2198 * unavailable, we don't do this trick at all, because we
2199 * gain nothing by it.)
2201 if (ssh->cscipher &&
2202 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2205 stringlen = (256 - ssh->deferred_len);
2206 stringlen += ssh->cscipher->blksize - 1;
2207 stringlen -= (stringlen % ssh->cscipher->blksize);
2210 * Temporarily disable actual compression, so we
2211 * can guarantee to get this string exactly the
2212 * length we want it. The compression-disabling
2213 * routine should return an integer indicating how
2214 * many bytes we should adjust our string length
2218 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2220 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2221 ssh2_pkt_addstring_start(pkt);
2222 for (i = 0; i < stringlen; i++) {
2223 char c = (char) random_byte();
2224 ssh2_pkt_addstring_data(pkt, &c, 1);
2226 ssh2_pkt_defer(ssh, pkt);
2228 ssh_pkt_defersend(ssh);
2233 * Send all queued SSH-2 packets. We send them by means of
2234 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2235 * packets that needed to be lumped together.
2237 static void ssh2_pkt_queuesend(Ssh ssh)
2241 assert(!ssh->queueing);
2243 for (i = 0; i < ssh->queuelen; i++)
2244 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2247 ssh_pkt_defersend(ssh);
2251 void bndebug(char *string, Bignum b)
2255 p = ssh2_mpint_fmt(b, &len);
2256 debug(("%s", string));
2257 for (i = 0; i < len; i++)
2258 debug((" %02x", p[i]));
2264 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2268 p = ssh2_mpint_fmt(b, &len);
2269 hash_string(h, s, p, len);
2274 * Packet decode functions for both SSH-1 and SSH-2.
2276 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2278 unsigned long value;
2279 if (pkt->length - pkt->savedpos < 4)
2280 return 0; /* arrgh, no way to decline (FIXME?) */
2281 value = GET_32BIT(pkt->body + pkt->savedpos);
2285 static int ssh2_pkt_getbool(struct Packet *pkt)
2287 unsigned long value;
2288 if (pkt->length - pkt->savedpos < 1)
2289 return 0; /* arrgh, no way to decline (FIXME?) */
2290 value = pkt->body[pkt->savedpos] != 0;
2294 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2299 if (pkt->length - pkt->savedpos < 4)
2301 len = GET_32BIT(pkt->body + pkt->savedpos);
2306 if (pkt->length - pkt->savedpos < *length)
2308 *p = (char *)(pkt->body + pkt->savedpos);
2309 pkt->savedpos += *length;
2311 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2313 if (pkt->length - pkt->savedpos < length)
2315 pkt->savedpos += length;
2316 return pkt->body + (pkt->savedpos - length);
2318 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2319 unsigned char **keystr)
2323 j = makekey(pkt->body + pkt->savedpos,
2324 pkt->length - pkt->savedpos,
2331 assert(pkt->savedpos < pkt->length);
2335 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2340 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2341 pkt->length - pkt->savedpos, &b);
2349 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2355 ssh_pkt_getstring(pkt, &p, &length);
2360 b = bignum_from_bytes((unsigned char *)p, length);
2365 * Helper function to add an SSH-2 signature blob to a packet.
2366 * Expects to be shown the public key blob as well as the signature
2367 * blob. Normally works just like ssh2_pkt_addstring, but will
2368 * fiddle with the signature packet if necessary for
2369 * BUG_SSH2_RSA_PADDING.
2371 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2372 void *pkblob_v, int pkblob_len,
2373 void *sigblob_v, int sigblob_len)
2375 unsigned char *pkblob = (unsigned char *)pkblob_v;
2376 unsigned char *sigblob = (unsigned char *)sigblob_v;
2378 /* dmemdump(pkblob, pkblob_len); */
2379 /* dmemdump(sigblob, sigblob_len); */
2382 * See if this is in fact an ssh-rsa signature and a buggy
2383 * server; otherwise we can just do this the easy way.
2385 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2386 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2387 int pos, len, siglen;
2390 * Find the byte length of the modulus.
2393 pos = 4+7; /* skip over "ssh-rsa" */
2394 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2395 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2396 pos += 4; /* find modulus itself */
2397 while (len > 0 && pkblob[pos] == 0)
2399 /* debug(("modulus length is %d\n", len)); */
2402 * Now find the signature integer.
2404 pos = 4+7; /* skip over "ssh-rsa" */
2405 siglen = GET_32BIT(sigblob+pos);
2406 /* debug(("signature length is %d\n", siglen)); */
2408 if (len != siglen) {
2409 unsigned char newlen[4];
2410 ssh2_pkt_addstring_start(pkt);
2411 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2412 /* dmemdump(sigblob, pos); */
2413 pos += 4; /* point to start of actual sig */
2414 PUT_32BIT(newlen, len);
2415 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2416 /* dmemdump(newlen, 4); */
2418 while (len-- > siglen) {
2419 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2420 /* dmemdump(newlen, 1); */
2422 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2423 /* dmemdump(sigblob+pos, siglen); */
2427 /* Otherwise fall through and do it the easy way. */
2430 ssh2_pkt_addstring_start(pkt);
2431 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2435 * Examine the remote side's version string and compare it against
2436 * a list of known buggy implementations.
2438 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2440 char *imp; /* pointer to implementation part */
2442 imp += strcspn(imp, "-");
2444 imp += strcspn(imp, "-");
2447 ssh->remote_bugs = 0;
2450 * General notes on server version strings:
2451 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2452 * here -- in particular, we've heard of one that's perfectly happy
2453 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2454 * so we can't distinguish them.
2456 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2457 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2458 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2459 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2460 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2461 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2463 * These versions don't support SSH1_MSG_IGNORE, so we have
2464 * to use a different defence against password length
2467 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2468 logevent("We believe remote version has SSH-1 ignore bug");
2471 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2472 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2473 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2475 * These versions need a plain password sent; they can't
2476 * handle having a null and a random length of data after
2479 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2480 logevent("We believe remote version needs a plain SSH-1 password");
2483 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2484 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2485 (!strcmp(imp, "Cisco-1.25")))) {
2487 * These versions apparently have no clue whatever about
2488 * RSA authentication and will panic and die if they see
2489 * an AUTH_RSA message.
2491 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2492 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2495 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2496 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2497 !wc_match("* VShell", imp) &&
2498 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2499 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2500 wc_match("2.1 *", imp)))) {
2502 * These versions have the HMAC bug.
2504 ssh->remote_bugs |= BUG_SSH2_HMAC;
2505 logevent("We believe remote version has SSH-2 HMAC bug");
2508 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2509 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2510 !wc_match("* VShell", imp) &&
2511 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2513 * These versions have the key-derivation bug (failing to
2514 * include the literal shared secret in the hashes that
2515 * generate the keys).
2517 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2518 logevent("We believe remote version has SSH-2 key-derivation bug");
2521 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2522 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2523 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2524 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2526 * These versions have the SSH-2 RSA padding bug.
2528 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2529 logevent("We believe remote version has SSH-2 RSA padding bug");
2532 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2533 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2534 wc_match("OpenSSH_2.[0-2]*", imp))) {
2536 * These versions have the SSH-2 session-ID bug in
2537 * public-key authentication.
2539 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2540 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2543 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2544 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2545 (wc_match("DigiSSH_2.0", imp) ||
2546 wc_match("OpenSSH_2.[0-4]*", imp) ||
2547 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2548 wc_match("Sun_SSH_1.0", imp) ||
2549 wc_match("Sun_SSH_1.0.1", imp) ||
2550 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2551 wc_match("WeOnlyDo-*", imp)))) {
2553 * These versions have the SSH-2 rekey bug.
2555 ssh->remote_bugs |= BUG_SSH2_REKEY;
2556 logevent("We believe remote version has SSH-2 rekey bug");
2559 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2560 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2561 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2562 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2564 * This version ignores our makpkt and needs to be throttled.
2566 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2567 logevent("We believe remote version ignores SSH-2 maximum packet size");
2570 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2572 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2573 * none detected automatically.
2575 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2576 logevent("We believe remote version has SSH-2 ignore bug");
2581 * The `software version' part of an SSH version string is required
2582 * to contain no spaces or minus signs.
2584 static void ssh_fix_verstring(char *str)
2586 /* Eat "SSH-<protoversion>-". */
2587 assert(*str == 'S'); str++;
2588 assert(*str == 'S'); str++;
2589 assert(*str == 'H'); str++;
2590 assert(*str == '-'); str++;
2591 while (*str && *str != '-') str++;
2592 assert(*str == '-'); str++;
2594 /* Convert minus signs and spaces in the remaining string into
2597 if (*str == '-' || *str == ' ')
2604 * Send an appropriate SSH version string.
2606 static void ssh_send_verstring(Ssh ssh, char *svers)
2610 if (ssh->version == 2) {
2612 * Construct a v2 version string.
2614 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2617 * Construct a v1 version string.
2619 verstring = dupprintf("SSH-%s-%s\012",
2620 (ssh_versioncmp(svers, "1.5") <= 0 ?
2625 ssh_fix_verstring(verstring);
2627 if (ssh->version == 2) {
2630 * Record our version string.
2632 len = strcspn(verstring, "\015\012");
2633 ssh->v_c = snewn(len + 1, char);
2634 memcpy(ssh->v_c, verstring, len);
2638 logeventf(ssh, "We claim version: %.*s",
2639 strcspn(verstring, "\015\012"), verstring);
2640 s_write(ssh, verstring, strlen(verstring));
2644 static int do_ssh_init(Ssh ssh, unsigned char c)
2646 struct do_ssh_init_state {
2654 crState(do_ssh_init_state);
2656 crBegin(ssh->do_ssh_init_crstate);
2658 /* Search for a line beginning with the string "SSH-" in the input. */
2660 if (c != 'S') goto no;
2662 if (c != 'S') goto no;
2664 if (c != 'H') goto no;
2666 if (c != '-') goto no;
2675 s->vstring = snewn(s->vstrsize, char);
2676 strcpy(s->vstring, "SSH-");
2680 crReturn(1); /* get another char */
2681 if (s->vslen >= s->vstrsize - 1) {
2683 s->vstring = sresize(s->vstring, s->vstrsize, char);
2685 s->vstring[s->vslen++] = c;
2688 s->version[s->i] = '\0';
2690 } else if (s->i < sizeof(s->version) - 1)
2691 s->version[s->i++] = c;
2692 } else if (c == '\012')
2696 ssh->agentfwd_enabled = FALSE;
2697 ssh->rdpkt2_state.incoming_sequence = 0;
2699 s->vstring[s->vslen] = 0;
2700 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2701 logeventf(ssh, "Server version: %s", s->vstring);
2702 ssh_detect_bugs(ssh, s->vstring);
2705 * Decide which SSH protocol version to support.
2708 /* Anything strictly below "2.0" means protocol 1 is supported. */
2709 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2710 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2711 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2713 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2714 bombout(("SSH protocol version 1 required by user but not provided by server"));
2717 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2718 bombout(("SSH protocol version 2 required by user but not provided by server"));
2722 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2727 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2729 /* Send the version string, if we haven't already */
2730 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2731 ssh_send_verstring(ssh, s->version);
2733 if (ssh->version == 2) {
2736 * Record their version string.
2738 len = strcspn(s->vstring, "\015\012");
2739 ssh->v_s = snewn(len + 1, char);
2740 memcpy(ssh->v_s, s->vstring, len);
2744 * Initialise SSH-2 protocol.
2746 ssh->protocol = ssh2_protocol;
2747 ssh2_protocol_setup(ssh);
2748 ssh->s_rdpkt = ssh2_rdpkt;
2751 * Initialise SSH-1 protocol.
2753 ssh->protocol = ssh1_protocol;
2754 ssh1_protocol_setup(ssh);
2755 ssh->s_rdpkt = ssh1_rdpkt;
2757 if (ssh->version == 2)
2758 do_ssh2_transport(ssh, NULL, -1, NULL);
2760 update_specials_menu(ssh->frontend);
2761 ssh->state = SSH_STATE_BEFORE_SIZE;
2762 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2769 static void ssh_process_incoming_data(Ssh ssh,
2770 unsigned char **data, int *datalen)
2772 struct Packet *pktin;
2774 pktin = ssh->s_rdpkt(ssh, data, datalen);
2776 ssh->protocol(ssh, NULL, 0, pktin);
2777 ssh_free_packet(pktin);
2781 static void ssh_queue_incoming_data(Ssh ssh,
2782 unsigned char **data, int *datalen)
2784 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2789 static void ssh_process_queued_incoming_data(Ssh ssh)
2792 unsigned char *data;
2795 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2796 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2800 while (!ssh->frozen && len > 0)
2801 ssh_process_incoming_data(ssh, &data, &len);
2804 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2808 static void ssh_set_frozen(Ssh ssh, int frozen)
2811 sk_set_frozen(ssh->s, frozen);
2812 ssh->frozen = frozen;
2815 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2817 /* Log raw data, if we're in that mode. */
2819 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2822 crBegin(ssh->ssh_gotdata_crstate);
2825 * To begin with, feed the characters one by one to the
2826 * protocol initialisation / selection function do_ssh_init().
2827 * When that returns 0, we're done with the initial greeting
2828 * exchange and can move on to packet discipline.
2831 int ret; /* need not be kept across crReturn */
2833 crReturnV; /* more data please */
2834 ret = do_ssh_init(ssh, *data);
2842 * We emerge from that loop when the initial negotiation is
2843 * over and we have selected an s_rdpkt function. Now pass
2844 * everything to s_rdpkt, and then pass the resulting packets
2845 * to the proper protocol handler.
2849 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2851 ssh_queue_incoming_data(ssh, &data, &datalen);
2852 /* This uses up all data and cannot cause anything interesting
2853 * to happen; indeed, for anything to happen at all, we must
2854 * return, so break out. */
2856 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2857 /* This uses up some or all data, and may freeze the
2859 ssh_process_queued_incoming_data(ssh);
2861 /* This uses up some or all data, and may freeze the
2863 ssh_process_incoming_data(ssh, &data, &datalen);
2865 /* FIXME this is probably EBW. */
2866 if (ssh->state == SSH_STATE_CLOSED)
2869 /* We're out of data. Go and get some more. */
2875 static int ssh_do_close(Ssh ssh, int notify_exit)
2878 struct ssh_channel *c;
2880 ssh->state = SSH_STATE_CLOSED;
2881 expire_timer_context(ssh);
2886 notify_remote_exit(ssh->frontend);
2891 * Now we must shut down any port- and X-forwarded channels going
2892 * through this connection.
2894 if (ssh->channels) {
2895 while (NULL != (c = index234(ssh->channels, 0))) {
2898 x11_close(c->u.x11.s);
2901 case CHAN_SOCKDATA_DORMANT:
2902 pfd_close(c->u.pfd.s);
2905 del234(ssh->channels, c); /* moving next one to index 0 */
2906 if (ssh->version == 2)
2907 bufchain_clear(&c->v.v2.outbuffer);
2912 * Go through port-forwardings, and close any associated
2913 * listening sockets.
2915 if (ssh->portfwds) {
2916 struct ssh_portfwd *pf;
2917 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2918 /* Dispose of any listening socket. */
2920 pfd_terminate(pf->local);
2921 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2924 freetree234(ssh->portfwds);
2925 ssh->portfwds = NULL;
2931 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2932 const char *error_msg, int error_code)
2934 Ssh ssh = (Ssh) plug;
2935 char addrbuf[256], *msg;
2937 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2940 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2942 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2948 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2951 Ssh ssh = (Ssh) plug;
2952 int need_notify = ssh_do_close(ssh, FALSE);
2955 if (!ssh->close_expected)
2956 error_msg = "Server unexpectedly closed network connection";
2958 error_msg = "Server closed network connection";
2961 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2965 notify_remote_exit(ssh->frontend);
2968 logevent(error_msg);
2969 if (!ssh->close_expected || !ssh->clean_exit)
2970 connection_fatal(ssh->frontend, "%s", error_msg);
2974 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2976 Ssh ssh = (Ssh) plug;
2977 ssh_gotdata(ssh, (unsigned char *)data, len);
2978 if (ssh->state == SSH_STATE_CLOSED) {
2979 ssh_do_close(ssh, TRUE);
2985 static void ssh_sent(Plug plug, int bufsize)
2987 Ssh ssh = (Ssh) plug;
2989 * If the send backlog on the SSH socket itself clears, we
2990 * should unthrottle the whole world if it was throttled.
2992 if (bufsize < SSH_MAX_BACKLOG)
2993 ssh_throttle_all(ssh, 0, bufsize);
2997 * Connect to specified host and port.
2998 * Returns an error message, or NULL on success.
2999 * Also places the canonical host name into `realhost'. It must be
3000 * freed by the caller.
3002 static const char *connect_to_host(Ssh ssh, char *host, int port,
3003 char **realhost, int nodelay, int keepalive)
3005 static const struct plug_function_table fn_table = {
3016 int addressfamily, sshprot;
3018 loghost = conf_get_str(ssh->conf, CONF_loghost);
3022 ssh->savedhost = dupstr(loghost);
3023 ssh->savedport = 22; /* default ssh port */
3026 * A colon suffix on savedhost also lets us affect
3029 * (FIXME: do something about IPv6 address literals here.)
3031 colon = strrchr(ssh->savedhost, ':');
3035 ssh->savedport = atoi(colon);
3038 ssh->savedhost = dupstr(host);
3040 port = 22; /* default ssh port */
3041 ssh->savedport = port;
3047 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3048 logeventf(ssh, "Looking up host \"%s\"%s", host,
3049 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3050 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3051 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3052 if ((err = sk_addr_error(addr)) != NULL) {
3056 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3061 ssh->fn = &fn_table;
3062 ssh->s = new_connection(addr, *realhost, port,
3063 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3064 if ((err = sk_socket_error(ssh->s)) != NULL) {
3066 notify_remote_exit(ssh->frontend);
3071 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3072 * send the version string too.
3074 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3079 ssh_send_verstring(ssh, NULL);
3083 * loghost, if configured, overrides realhost.
3087 *realhost = dupstr(loghost);
3094 * Throttle or unthrottle the SSH connection.
3096 static void ssh_throttle_conn(Ssh ssh, int adjust)
3098 int old_count = ssh->conn_throttle_count;
3099 ssh->conn_throttle_count += adjust;
3100 assert(ssh->conn_throttle_count >= 0);
3101 if (ssh->conn_throttle_count && !old_count) {
3102 ssh_set_frozen(ssh, 1);
3103 } else if (!ssh->conn_throttle_count && old_count) {
3104 ssh_set_frozen(ssh, 0);
3109 * Throttle or unthrottle _all_ local data streams (for when sends
3110 * on the SSH connection itself back up).
3112 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3115 struct ssh_channel *c;
3117 if (enable == ssh->throttled_all)
3119 ssh->throttled_all = enable;
3120 ssh->overall_bufsize = bufsize;
3123 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3125 case CHAN_MAINSESSION:
3127 * This is treated separately, outside the switch.
3131 x11_override_throttle(c->u.x11.s, enable);
3134 /* Agent channels require no buffer management. */
3137 pfd_override_throttle(c->u.pfd.s, enable);
3143 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3145 Ssh ssh = (Ssh) sshv;
3147 ssh->agent_response = reply;
3148 ssh->agent_response_len = replylen;
3150 if (ssh->version == 1)
3151 do_ssh1_login(ssh, NULL, -1, NULL);
3153 do_ssh2_authconn(ssh, NULL, -1, NULL);
3156 static void ssh_dialog_callback(void *sshv, int ret)
3158 Ssh ssh = (Ssh) sshv;
3160 ssh->user_response = ret;
3162 if (ssh->version == 1)
3163 do_ssh1_login(ssh, NULL, -1, NULL);
3165 do_ssh2_transport(ssh, NULL, -1, NULL);
3168 * This may have unfrozen the SSH connection, so do a
3171 ssh_process_queued_incoming_data(ssh);
3174 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3176 struct ssh_channel *c = (struct ssh_channel *)cv;
3178 void *sentreply = reply;
3181 /* Fake SSH_AGENT_FAILURE. */
3182 sentreply = "\0\0\0\1\5";
3185 if (ssh->version == 2) {
3186 ssh2_add_channel_data(c, sentreply, replylen);
3189 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3190 PKT_INT, c->remoteid,
3193 PKT_DATA, sentreply, replylen,
3202 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3203 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3204 * => log `wire_reason'.
3206 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3207 int code, int clean_exit)
3211 client_reason = wire_reason;
3213 error = dupprintf("Disconnected: %s", client_reason);
3215 error = dupstr("Disconnected");
3217 if (ssh->version == 1) {
3218 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3220 } else if (ssh->version == 2) {
3221 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3222 ssh2_pkt_adduint32(pktout, code);
3223 ssh2_pkt_addstring(pktout, wire_reason);
3224 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3225 ssh2_pkt_send_noqueue(ssh, pktout);
3228 ssh->close_expected = TRUE;
3229 ssh->clean_exit = clean_exit;
3230 ssh_closing((Plug)ssh, error, 0, 0);
3235 * Handle the key exchange and user authentication phases.
3237 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3238 struct Packet *pktin)
3241 unsigned char cookie[8], *ptr;
3242 struct RSAKey servkey, hostkey;
3243 struct MD5Context md5c;
3244 struct do_ssh1_login_state {
3246 unsigned char *rsabuf, *keystr1, *keystr2;
3247 unsigned long supported_ciphers_mask, supported_auths_mask;
3248 int tried_publickey, tried_agent;
3249 int tis_auth_refused, ccard_auth_refused;
3250 unsigned char session_id[16];
3252 void *publickey_blob;
3253 int publickey_bloblen;
3254 char *publickey_comment;
3255 int publickey_encrypted;
3256 prompts_t *cur_prompt;
3259 unsigned char request[5], *response, *p;
3270 crState(do_ssh1_login_state);
3272 crBegin(ssh->do_ssh1_login_crstate);
3277 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3278 bombout(("Public key packet not received"));
3282 logevent("Received public keys");
3284 ptr = ssh_pkt_getdata(pktin, 8);
3286 bombout(("SSH-1 public key packet stopped before random cookie"));
3289 memcpy(cookie, ptr, 8);
3291 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3292 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3293 bombout(("Failed to read SSH-1 public keys from public key packet"));
3298 * Log the host key fingerprint.
3302 logevent("Host key fingerprint is:");
3303 strcpy(logmsg, " ");
3304 hostkey.comment = NULL;
3305 rsa_fingerprint(logmsg + strlen(logmsg),
3306 sizeof(logmsg) - strlen(logmsg), &hostkey);
3310 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3311 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3312 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3313 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3314 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3316 ssh->v1_local_protoflags =
3317 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3318 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3321 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3322 MD5Update(&md5c, s->keystr1, servkey.bytes);
3323 MD5Update(&md5c, cookie, 8);
3324 MD5Final(s->session_id, &md5c);
3326 for (i = 0; i < 32; i++)
3327 ssh->session_key[i] = random_byte();
3330 * Verify that the `bits' and `bytes' parameters match.
3332 if (hostkey.bits > hostkey.bytes * 8 ||
3333 servkey.bits > servkey.bytes * 8) {
3334 bombout(("SSH-1 public keys were badly formatted"));
3338 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3340 s->rsabuf = snewn(s->len, unsigned char);
3343 * Verify the host key.
3347 * First format the key into a string.
3349 int len = rsastr_len(&hostkey);
3350 char fingerprint[100];
3351 char *keystr = snewn(len, char);
3352 rsastr_fmt(keystr, &hostkey);
3353 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3355 ssh_set_frozen(ssh, 1);
3356 s->dlgret = verify_ssh_host_key(ssh->frontend,
3357 ssh->savedhost, ssh->savedport,
3358 "rsa", keystr, fingerprint,
3359 ssh_dialog_callback, ssh);
3361 if (s->dlgret < 0) {
3365 bombout(("Unexpected data from server while waiting"
3366 " for user host key response"));
3369 } while (pktin || inlen > 0);
3370 s->dlgret = ssh->user_response;
3372 ssh_set_frozen(ssh, 0);
3374 if (s->dlgret == 0) {
3375 ssh_disconnect(ssh, "User aborted at host key verification",
3381 for (i = 0; i < 32; i++) {
3382 s->rsabuf[i] = ssh->session_key[i];
3384 s->rsabuf[i] ^= s->session_id[i];
3387 if (hostkey.bytes > servkey.bytes) {
3388 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3390 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3392 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3394 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3397 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3401 logevent("Encrypted session key");
3404 int cipher_chosen = 0, warn = 0;
3405 char *cipher_string = NULL;
3407 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3408 int next_cipher = conf_get_int_int(ssh->conf,
3409 CONF_ssh_cipherlist, i);
3410 if (next_cipher == CIPHER_WARN) {
3411 /* If/when we choose a cipher, warn about it */
3413 } else if (next_cipher == CIPHER_AES) {
3414 /* XXX Probably don't need to mention this. */
3415 logevent("AES not supported in SSH-1, skipping");
3417 switch (next_cipher) {
3418 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3419 cipher_string = "3DES"; break;
3420 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3421 cipher_string = "Blowfish"; break;
3422 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3423 cipher_string = "single-DES"; break;
3425 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3429 if (!cipher_chosen) {
3430 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3431 bombout(("Server violates SSH-1 protocol by not "
3432 "supporting 3DES encryption"));
3434 /* shouldn't happen */
3435 bombout(("No supported ciphers found"));
3439 /* Warn about chosen cipher if necessary. */
3441 ssh_set_frozen(ssh, 1);
3442 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3443 ssh_dialog_callback, ssh);
3444 if (s->dlgret < 0) {
3448 bombout(("Unexpected data from server while waiting"
3449 " for user response"));
3452 } while (pktin || inlen > 0);
3453 s->dlgret = ssh->user_response;
3455 ssh_set_frozen(ssh, 0);
3456 if (s->dlgret == 0) {
3457 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3464 switch (s->cipher_type) {
3465 case SSH_CIPHER_3DES:
3466 logevent("Using 3DES encryption");
3468 case SSH_CIPHER_DES:
3469 logevent("Using single-DES encryption");
3471 case SSH_CIPHER_BLOWFISH:
3472 logevent("Using Blowfish encryption");
3476 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3477 PKT_CHAR, s->cipher_type,
3478 PKT_DATA, cookie, 8,
3479 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3480 PKT_DATA, s->rsabuf, s->len,
3481 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3483 logevent("Trying to enable encryption...");
3487 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3488 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3490 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3491 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3492 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3494 ssh->crcda_ctx = crcda_make_context();
3495 logevent("Installing CRC compensation attack detector");
3497 if (servkey.modulus) {
3498 sfree(servkey.modulus);
3499 servkey.modulus = NULL;
3501 if (servkey.exponent) {
3502 sfree(servkey.exponent);
3503 servkey.exponent = NULL;
3505 if (hostkey.modulus) {
3506 sfree(hostkey.modulus);
3507 hostkey.modulus = NULL;
3509 if (hostkey.exponent) {
3510 sfree(hostkey.exponent);
3511 hostkey.exponent = NULL;
3515 if (pktin->type != SSH1_SMSG_SUCCESS) {
3516 bombout(("Encryption not successfully enabled"));
3520 logevent("Successfully started encryption");
3522 fflush(stdout); /* FIXME eh? */
3524 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3525 int ret; /* need not be kept over crReturn */
3526 s->cur_prompt = new_prompts(ssh->frontend);
3527 s->cur_prompt->to_server = TRUE;
3528 s->cur_prompt->name = dupstr("SSH login name");
3529 /* 512 is an arbitrary upper limit on username size */
3530 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
3531 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3534 crWaitUntil(!pktin);
3535 ret = get_userpass_input(s->cur_prompt, in, inlen);
3540 * Failed to get a username. Terminate.
3542 free_prompts(s->cur_prompt);
3543 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3546 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3547 free_prompts(s->cur_prompt);
3550 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3552 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3554 if (flags & FLAG_INTERACTIVE &&
3555 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3556 c_write_str(ssh, userlog);
3557 c_write_str(ssh, "\r\n");
3565 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3566 /* We must not attempt PK auth. Pretend we've already tried it. */
3567 s->tried_publickey = s->tried_agent = 1;
3569 s->tried_publickey = s->tried_agent = 0;
3571 s->tis_auth_refused = s->ccard_auth_refused = 0;
3573 * Load the public half of any configured keyfile for later use.
3575 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3576 if (!filename_is_null(*s->keyfile)) {
3578 logeventf(ssh, "Reading private key file \"%.150s\"",
3579 filename_to_str(s->keyfile));
3580 keytype = key_type(s->keyfile);
3581 if (keytype == SSH_KEYTYPE_SSH1) {
3583 if (rsakey_pubblob(s->keyfile,
3584 &s->publickey_blob, &s->publickey_bloblen,
3585 &s->publickey_comment, &error)) {
3586 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3590 logeventf(ssh, "Unable to load private key (%s)", error);
3591 msgbuf = dupprintf("Unable to load private key file "
3592 "\"%.150s\" (%s)\r\n",
3593 filename_to_str(s->keyfile),
3595 c_write_str(ssh, msgbuf);
3597 s->publickey_blob = NULL;
3601 logeventf(ssh, "Unable to use this key file (%s)",
3602 key_type_to_str(keytype));
3603 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3605 filename_to_str(s->keyfile),
3606 key_type_to_str(keytype));
3607 c_write_str(ssh, msgbuf);
3609 s->publickey_blob = NULL;
3612 s->publickey_blob = NULL;
3614 while (pktin->type == SSH1_SMSG_FAILURE) {
3615 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3617 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3619 * Attempt RSA authentication using Pageant.
3625 logevent("Pageant is running. Requesting keys.");
3627 /* Request the keys held by the agent. */
3628 PUT_32BIT(s->request, 1);
3629 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3630 if (!agent_query(s->request, 5, &r, &s->responselen,
3631 ssh_agent_callback, ssh)) {
3635 bombout(("Unexpected data from server while waiting"
3636 " for agent response"));
3639 } while (pktin || inlen > 0);
3640 r = ssh->agent_response;
3641 s->responselen = ssh->agent_response_len;
3643 s->response = (unsigned char *) r;
3644 if (s->response && s->responselen >= 5 &&
3645 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3646 s->p = s->response + 5;
3647 s->nkeys = GET_32BIT(s->p);
3649 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3650 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3651 unsigned char *pkblob = s->p;
3655 do { /* do while (0) to make breaking easy */
3656 n = ssh1_read_bignum
3657 (s->p, s->responselen-(s->p-s->response),
3662 n = ssh1_read_bignum
3663 (s->p, s->responselen-(s->p-s->response),
3668 if (s->responselen - (s->p-s->response) < 4)
3670 s->commentlen = GET_32BIT(s->p);
3672 if (s->responselen - (s->p-s->response) <
3675 s->commentp = (char *)s->p;
3676 s->p += s->commentlen;
3680 logevent("Pageant key list packet was truncated");
3684 if (s->publickey_blob) {
3685 if (!memcmp(pkblob, s->publickey_blob,
3686 s->publickey_bloblen)) {
3687 logeventf(ssh, "Pageant key #%d matches "
3688 "configured key file", s->keyi);
3689 s->tried_publickey = 1;
3691 /* Skip non-configured key */
3694 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3695 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3696 PKT_BIGNUM, s->key.modulus, PKT_END);
3698 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3699 logevent("Key refused");
3702 logevent("Received RSA challenge");
3703 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3704 bombout(("Server's RSA challenge was badly formatted"));
3709 char *agentreq, *q, *ret;
3712 len = 1 + 4; /* message type, bit count */
3713 len += ssh1_bignum_length(s->key.exponent);
3714 len += ssh1_bignum_length(s->key.modulus);
3715 len += ssh1_bignum_length(s->challenge);
3716 len += 16; /* session id */
3717 len += 4; /* response format */
3718 agentreq = snewn(4 + len, char);
3719 PUT_32BIT(agentreq, len);
3721 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3722 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3724 q += ssh1_write_bignum(q, s->key.exponent);
3725 q += ssh1_write_bignum(q, s->key.modulus);
3726 q += ssh1_write_bignum(q, s->challenge);
3727 memcpy(q, s->session_id, 16);
3729 PUT_32BIT(q, 1); /* response format */
3730 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3731 ssh_agent_callback, ssh)) {
3736 bombout(("Unexpected data from server"
3737 " while waiting for agent"
3741 } while (pktin || inlen > 0);
3742 vret = ssh->agent_response;
3743 retlen = ssh->agent_response_len;
3748 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3749 logevent("Sending Pageant's response");
3750 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3751 PKT_DATA, ret + 5, 16,
3755 if (pktin->type == SSH1_SMSG_SUCCESS) {
3757 ("Pageant's response accepted");
3758 if (flags & FLAG_VERBOSE) {
3759 c_write_str(ssh, "Authenticated using"
3761 c_write(ssh, s->commentp,
3763 c_write_str(ssh, "\" from agent\r\n");
3768 ("Pageant's response not accepted");
3771 ("Pageant failed to answer challenge");
3775 logevent("No reply received from Pageant");
3778 freebn(s->key.exponent);
3779 freebn(s->key.modulus);
3780 freebn(s->challenge);
3785 if (s->publickey_blob && !s->tried_publickey)
3786 logevent("Configured key file not in Pageant");
3788 logevent("Failed to get reply from Pageant");
3793 if (s->publickey_blob && !s->tried_publickey) {
3795 * Try public key authentication with the specified
3798 int got_passphrase; /* need not be kept over crReturn */
3799 if (flags & FLAG_VERBOSE)
3800 c_write_str(ssh, "Trying public key authentication.\r\n");
3801 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3802 logeventf(ssh, "Trying public key \"%s\"",
3803 filename_to_str(s->keyfile));
3804 s->tried_publickey = 1;
3805 got_passphrase = FALSE;
3806 while (!got_passphrase) {
3808 * Get a passphrase, if necessary.
3810 char *passphrase = NULL; /* only written after crReturn */
3812 if (!s->publickey_encrypted) {
3813 if (flags & FLAG_VERBOSE)
3814 c_write_str(ssh, "No passphrase required.\r\n");
3817 int ret; /* need not be kept over crReturn */
3818 s->cur_prompt = new_prompts(ssh->frontend);
3819 s->cur_prompt->to_server = FALSE;
3820 s->cur_prompt->name = dupstr("SSH key passphrase");
3821 add_prompt(s->cur_prompt,
3822 dupprintf("Passphrase for key \"%.100s\": ",
3823 s->publickey_comment),
3824 FALSE, SSH_MAX_PASSWORD_LEN);
3825 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3828 crWaitUntil(!pktin);
3829 ret = get_userpass_input(s->cur_prompt, in, inlen);
3833 /* Failed to get a passphrase. Terminate. */
3834 free_prompts(s->cur_prompt);
3835 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3839 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3840 free_prompts(s->cur_prompt);
3843 * Try decrypting key with passphrase.
3845 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3846 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3849 memset(passphrase, 0, strlen(passphrase));
3853 /* Correct passphrase. */
3854 got_passphrase = TRUE;
3855 } else if (ret == 0) {
3856 c_write_str(ssh, "Couldn't load private key from ");
3857 c_write_str(ssh, filename_to_str(s->keyfile));
3858 c_write_str(ssh, " (");
3859 c_write_str(ssh, error);
3860 c_write_str(ssh, ").\r\n");
3861 got_passphrase = FALSE;
3862 break; /* go and try something else */
3863 } else if (ret == -1) {
3864 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3865 got_passphrase = FALSE;
3868 assert(0 && "unexpected return from loadrsakey()");
3869 got_passphrase = FALSE; /* placate optimisers */
3873 if (got_passphrase) {
3876 * Send a public key attempt.
3878 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3879 PKT_BIGNUM, s->key.modulus, PKT_END);
3882 if (pktin->type == SSH1_SMSG_FAILURE) {
3883 c_write_str(ssh, "Server refused our public key.\r\n");
3884 continue; /* go and try something else */
3886 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3887 bombout(("Bizarre response to offer of public key"));
3893 unsigned char buffer[32];
3894 Bignum challenge, response;
3896 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3897 bombout(("Server's RSA challenge was badly formatted"));
3900 response = rsadecrypt(challenge, &s->key);
3901 freebn(s->key.private_exponent);/* burn the evidence */
3903 for (i = 0; i < 32; i++) {
3904 buffer[i] = bignum_byte(response, 31 - i);
3908 MD5Update(&md5c, buffer, 32);
3909 MD5Update(&md5c, s->session_id, 16);
3910 MD5Final(buffer, &md5c);
3912 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3913 PKT_DATA, buffer, 16, PKT_END);
3920 if (pktin->type == SSH1_SMSG_FAILURE) {
3921 if (flags & FLAG_VERBOSE)
3922 c_write_str(ssh, "Failed to authenticate with"
3923 " our public key.\r\n");
3924 continue; /* go and try something else */
3925 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3926 bombout(("Bizarre response to RSA authentication response"));
3930 break; /* we're through! */
3936 * Otherwise, try various forms of password-like authentication.
3938 s->cur_prompt = new_prompts(ssh->frontend);
3940 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3941 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3942 !s->tis_auth_refused) {
3943 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3944 logevent("Requested TIS authentication");
3945 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3947 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3948 logevent("TIS authentication declined");
3949 if (flags & FLAG_INTERACTIVE)
3950 c_write_str(ssh, "TIS authentication refused.\r\n");
3951 s->tis_auth_refused = 1;
3956 char *instr_suf, *prompt;
3958 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3960 bombout(("TIS challenge packet was badly formed"));
3963 logevent("Received TIS challenge");
3964 s->cur_prompt->to_server = TRUE;
3965 s->cur_prompt->name = dupstr("SSH TIS authentication");
3966 /* Prompt heuristic comes from OpenSSH */
3967 if (memchr(challenge, '\n', challengelen)) {
3968 instr_suf = dupstr("");
3969 prompt = dupprintf("%.*s", challengelen, challenge);
3971 instr_suf = dupprintf("%.*s", challengelen, challenge);
3972 prompt = dupstr("Response: ");
3974 s->cur_prompt->instruction =
3975 dupprintf("Using TIS authentication.%s%s",
3976 (*instr_suf) ? "\n" : "",
3978 s->cur_prompt->instr_reqd = TRUE;
3979 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3983 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3984 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3985 !s->ccard_auth_refused) {
3986 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3987 logevent("Requested CryptoCard authentication");
3988 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3990 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3991 logevent("CryptoCard authentication declined");
3992 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3993 s->ccard_auth_refused = 1;
3998 char *instr_suf, *prompt;
4000 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4002 bombout(("CryptoCard challenge packet was badly formed"));
4005 logevent("Received CryptoCard challenge");
4006 s->cur_prompt->to_server = TRUE;
4007 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4008 s->cur_prompt->name_reqd = FALSE;
4009 /* Prompt heuristic comes from OpenSSH */
4010 if (memchr(challenge, '\n', challengelen)) {
4011 instr_suf = dupstr("");
4012 prompt = dupprintf("%.*s", challengelen, challenge);
4014 instr_suf = dupprintf("%.*s", challengelen, challenge);
4015 prompt = dupstr("Response: ");
4017 s->cur_prompt->instruction =
4018 dupprintf("Using CryptoCard authentication.%s%s",
4019 (*instr_suf) ? "\n" : "",
4021 s->cur_prompt->instr_reqd = TRUE;
4022 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
4026 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4027 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4028 bombout(("No supported authentication methods available"));
4031 s->cur_prompt->to_server = TRUE;
4032 s->cur_prompt->name = dupstr("SSH password");
4033 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4034 ssh->username, ssh->savedhost),
4035 FALSE, SSH_MAX_PASSWORD_LEN);
4039 * Show password prompt, having first obtained it via a TIS
4040 * or CryptoCard exchange if we're doing TIS or CryptoCard
4044 int ret; /* need not be kept over crReturn */
4045 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4048 crWaitUntil(!pktin);
4049 ret = get_userpass_input(s->cur_prompt, in, inlen);
4054 * Failed to get a password (for example
4055 * because one was supplied on the command line
4056 * which has already failed to work). Terminate.
4058 free_prompts(s->cur_prompt);
4059 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4064 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4066 * Defence against traffic analysis: we send a
4067 * whole bunch of packets containing strings of
4068 * different lengths. One of these strings is the
4069 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4070 * The others are all random data in
4071 * SSH1_MSG_IGNORE packets. This way a passive
4072 * listener can't tell which is the password, and
4073 * hence can't deduce the password length.
4075 * Anybody with a password length greater than 16
4076 * bytes is going to have enough entropy in their
4077 * password that a listener won't find it _that_
4078 * much help to know how long it is. So what we'll
4081 * - if password length < 16, we send 15 packets
4082 * containing string lengths 1 through 15
4084 * - otherwise, we let N be the nearest multiple
4085 * of 8 below the password length, and send 8
4086 * packets containing string lengths N through
4087 * N+7. This won't obscure the order of
4088 * magnitude of the password length, but it will
4089 * introduce a bit of extra uncertainty.
4091 * A few servers can't deal with SSH1_MSG_IGNORE, at
4092 * least in this context. For these servers, we need
4093 * an alternative defence. We make use of the fact
4094 * that the password is interpreted as a C string:
4095 * so we can append a NUL, then some random data.
4097 * A few servers can deal with neither SSH1_MSG_IGNORE
4098 * here _nor_ a padded password string.
4099 * For these servers we are left with no defences
4100 * against password length sniffing.
4102 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4103 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4105 * The server can deal with SSH1_MSG_IGNORE, so
4106 * we can use the primary defence.
4108 int bottom, top, pwlen, i;
4111 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4113 bottom = 0; /* zero length passwords are OK! :-) */
4116 bottom = pwlen & ~7;
4120 assert(pwlen >= bottom && pwlen <= top);
4122 randomstr = snewn(top + 1, char);
4124 for (i = bottom; i <= top; i++) {
4126 defer_packet(ssh, s->pwpkt_type,
4127 PKTT_PASSWORD, PKT_STR,
4128 s->cur_prompt->prompts[0]->result,
4129 PKTT_OTHER, PKT_END);
4131 for (j = 0; j < i; j++) {
4133 randomstr[j] = random_byte();
4134 } while (randomstr[j] == '\0');
4136 randomstr[i] = '\0';
4137 defer_packet(ssh, SSH1_MSG_IGNORE,
4138 PKT_STR, randomstr, PKT_END);
4141 logevent("Sending password with camouflage packets");
4142 ssh_pkt_defersend(ssh);
4145 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4147 * The server can't deal with SSH1_MSG_IGNORE
4148 * but can deal with padded passwords, so we
4149 * can use the secondary defence.
4155 len = strlen(s->cur_prompt->prompts[0]->result);
4156 if (len < sizeof(string)) {
4158 strcpy(string, s->cur_prompt->prompts[0]->result);
4159 len++; /* cover the zero byte */
4160 while (len < sizeof(string)) {
4161 string[len++] = (char) random_byte();
4164 ss = s->cur_prompt->prompts[0]->result;
4166 logevent("Sending length-padded password");
4167 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4168 PKT_INT, len, PKT_DATA, ss, len,
4169 PKTT_OTHER, PKT_END);
4172 * The server is believed unable to cope with
4173 * any of our password camouflage methods.
4176 len = strlen(s->cur_prompt->prompts[0]->result);
4177 logevent("Sending unpadded password");
4178 send_packet(ssh, s->pwpkt_type,
4179 PKTT_PASSWORD, PKT_INT, len,
4180 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4181 PKTT_OTHER, PKT_END);
4184 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4185 PKT_STR, s->cur_prompt->prompts[0]->result,
4186 PKTT_OTHER, PKT_END);
4188 logevent("Sent password");
4189 free_prompts(s->cur_prompt);
4191 if (pktin->type == SSH1_SMSG_FAILURE) {
4192 if (flags & FLAG_VERBOSE)
4193 c_write_str(ssh, "Access denied\r\n");
4194 logevent("Authentication refused");
4195 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4196 bombout(("Strange packet received, type %d", pktin->type));
4202 if (s->publickey_blob) {
4203 sfree(s->publickey_blob);
4204 sfree(s->publickey_comment);
4207 logevent("Authentication successful");
4212 static void ssh_channel_try_eof(struct ssh_channel *c)
4215 assert(c->pending_eof); /* precondition for calling us */
4217 return; /* can't close: not even opened yet */
4218 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4219 return; /* can't send EOF: pending outgoing data */
4221 if (ssh->version == 1) {
4222 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4224 c->closes |= CLOSES_SENT_EOF;
4226 struct Packet *pktout;
4227 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4228 ssh2_pkt_adduint32(pktout, c->remoteid);
4229 ssh2_pkt_send(ssh, pktout);
4230 c->closes |= CLOSES_SENT_EOF;
4231 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4233 * Also send MSG_CLOSE.
4235 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4236 ssh2_pkt_adduint32(pktout, c->remoteid);
4237 ssh2_pkt_send(ssh, pktout);
4238 c->closes |= CLOSES_SENT_CLOSE;
4241 c->pending_eof = FALSE; /* we've sent it now */
4244 void sshfwd_write_eof(struct ssh_channel *c)
4248 if (ssh->state == SSH_STATE_CLOSED)
4251 if (c->closes & CLOSES_SENT_EOF)
4254 c->pending_eof = TRUE;
4255 ssh_channel_try_eof(c);
4258 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4262 if (ssh->state == SSH_STATE_CLOSED)
4265 if (ssh->version == 1) {
4266 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4267 PKT_INT, c->remoteid,
4268 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4269 PKTT_OTHER, PKT_END);
4271 * In SSH-1 we can return 0 here - implying that forwarded
4272 * connections are never individually throttled - because
4273 * the only circumstance that can cause throttling will be
4274 * the whole SSH connection backing up, in which case
4275 * _everything_ will be throttled as a whole.
4279 ssh2_add_channel_data(c, buf, len);
4280 return ssh2_try_send(c);
4284 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4289 if (ssh->state == SSH_STATE_CLOSED)
4292 if (ssh->version == 1) {
4293 buflimit = SSH1_BUFFER_LIMIT;
4295 buflimit = c->v.v2.locmaxwin;
4296 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4298 if (c->throttling_conn && bufsize <= buflimit) {
4299 c->throttling_conn = 0;
4300 ssh_throttle_conn(ssh, -1);
4304 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4306 struct queued_handler *qh = ssh->qhead;
4310 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4313 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4314 ssh->packet_dispatch[qh->msg1] = NULL;
4317 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4318 ssh->packet_dispatch[qh->msg2] = NULL;
4322 ssh->qhead = qh->next;
4324 if (ssh->qhead->msg1 > 0) {
4325 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4326 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4328 if (ssh->qhead->msg2 > 0) {
4329 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4330 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4333 ssh->qhead = ssh->qtail = NULL;
4334 ssh->packet_dispatch[pktin->type] = NULL;
4337 qh->handler(ssh, pktin, qh->ctx);
4342 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4343 chandler_fn_t handler, void *ctx)
4345 struct queued_handler *qh;
4347 qh = snew(struct queued_handler);
4350 qh->handler = handler;
4354 if (ssh->qtail == NULL) {
4358 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4359 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4362 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4363 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4366 ssh->qtail->next = qh;
4371 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4373 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4375 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4376 SSH2_MSG_REQUEST_SUCCESS)) {
4377 logeventf(ssh, "Remote port forwarding from %s enabled",
4380 logeventf(ssh, "Remote port forwarding from %s refused",
4383 rpf = del234(ssh->rportfwds, pf);
4385 pf->pfrec->remote = NULL;
4390 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4392 struct ssh_portfwd *epf;
4396 if (!ssh->portfwds) {
4397 ssh->portfwds = newtree234(ssh_portcmp);
4400 * Go through the existing port forwardings and tag them
4401 * with status==DESTROY. Any that we want to keep will be
4402 * re-enabled (status==KEEP) as we go through the
4403 * configuration and find out which bits are the same as
4406 struct ssh_portfwd *epf;
4408 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4409 epf->status = DESTROY;
4412 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4414 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4415 char *kp, *kp2, *vp, *vp2;
4416 char address_family, type;
4417 int sport,dport,sserv,dserv;
4418 char *sports, *dports, *saddr, *host;
4422 address_family = 'A';
4424 if (*kp == 'A' || *kp == '4' || *kp == '6')
4425 address_family = *kp++;
4426 if (*kp == 'L' || *kp == 'R')
4429 if ((kp2 = strchr(kp, ':')) != NULL) {
4431 * There's a colon in the middle of the source port
4432 * string, which means that the part before it is
4433 * actually a source address.
4435 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4441 sport = atoi(sports);
4445 sport = net_service_lookup(sports);
4447 logeventf(ssh, "Service lookup failed for source"
4448 " port \"%s\"", sports);
4452 if (type == 'L' && !strcmp(val, "D")) {
4453 /* dynamic forwarding */
4460 /* ordinary forwarding */
4462 vp2 = vp + strcspn(vp, ":");
4463 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4467 dport = atoi(dports);
4471 dport = net_service_lookup(dports);
4473 logeventf(ssh, "Service lookup failed for destination"
4474 " port \"%s\"", dports);
4479 if (sport && dport) {
4480 /* Set up a description of the source port. */
4481 struct ssh_portfwd *pfrec, *epfrec;
4483 pfrec = snew(struct ssh_portfwd);
4485 pfrec->saddr = saddr;
4486 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4487 pfrec->sport = sport;
4488 pfrec->daddr = host;
4489 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4490 pfrec->dport = dport;
4491 pfrec->local = NULL;
4492 pfrec->remote = NULL;
4493 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4494 address_family == '6' ? ADDRTYPE_IPV6 :
4497 epfrec = add234(ssh->portfwds, pfrec);
4498 if (epfrec != pfrec) {
4499 if (epfrec->status == DESTROY) {
4501 * We already have a port forwarding up and running
4502 * with precisely these parameters. Hence, no need
4503 * to do anything; simply re-tag the existing one
4506 epfrec->status = KEEP;
4509 * Anything else indicates that there was a duplicate
4510 * in our input, which we'll silently ignore.
4512 free_portfwd(pfrec);
4514 pfrec->status = CREATE;
4523 * Now go through and destroy any port forwardings which were
4526 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4527 if (epf->status == DESTROY) {
4530 message = dupprintf("%s port forwarding from %s%s%d",
4531 epf->type == 'L' ? "local" :
4532 epf->type == 'R' ? "remote" : "dynamic",
4533 epf->saddr ? epf->saddr : "",
4534 epf->saddr ? ":" : "",
4537 if (epf->type != 'D') {
4538 char *msg2 = dupprintf("%s to %s:%d", message,
4539 epf->daddr, epf->dport);
4544 logeventf(ssh, "Cancelling %s", message);
4547 /* epf->remote or epf->local may be NULL if setting up a
4548 * forwarding failed. */
4550 struct ssh_rportfwd *rpf = epf->remote;
4551 struct Packet *pktout;
4554 * Cancel the port forwarding at the server
4557 if (ssh->version == 1) {
4559 * We cannot cancel listening ports on the
4560 * server side in SSH-1! There's no message
4561 * to support it. Instead, we simply remove
4562 * the rportfwd record from the local end
4563 * so that any connections the server tries
4564 * to make on it are rejected.
4567 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4568 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4569 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4571 ssh2_pkt_addstring(pktout, epf->saddr);
4572 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4573 /* XXX: rport_acceptall may not represent
4574 * what was used to open the original connection,
4575 * since it's reconfigurable. */
4576 ssh2_pkt_addstring(pktout, "0.0.0.0");
4578 ssh2_pkt_addstring(pktout, "127.0.0.1");
4580 ssh2_pkt_adduint32(pktout, epf->sport);
4581 ssh2_pkt_send(ssh, pktout);
4584 del234(ssh->rportfwds, rpf);
4586 } else if (epf->local) {
4587 pfd_terminate(epf->local);
4590 delpos234(ssh->portfwds, i);
4592 i--; /* so we don't skip one in the list */
4596 * And finally, set up any new port forwardings (status==CREATE).
4598 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4599 if (epf->status == CREATE) {
4600 char *sportdesc, *dportdesc;
4601 sportdesc = dupprintf("%s%s%s%s%d%s",
4602 epf->saddr ? epf->saddr : "",
4603 epf->saddr ? ":" : "",
4604 epf->sserv ? epf->sserv : "",
4605 epf->sserv ? "(" : "",
4607 epf->sserv ? ")" : "");
4608 if (epf->type == 'D') {
4611 dportdesc = dupprintf("%s:%s%s%d%s",
4613 epf->dserv ? epf->dserv : "",
4614 epf->dserv ? "(" : "",
4616 epf->dserv ? ")" : "");
4619 if (epf->type == 'L') {
4620 const char *err = pfd_addforward(epf->daddr, epf->dport,
4621 epf->saddr, epf->sport,
4624 epf->addressfamily);
4626 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4627 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4628 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4629 sportdesc, dportdesc,
4630 err ? " failed: " : "", err ? err : "");
4631 } else if (epf->type == 'D') {
4632 const char *err = pfd_addforward(NULL, -1,
4633 epf->saddr, epf->sport,
4636 epf->addressfamily);
4638 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4639 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4640 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4642 err ? " failed: " : "", err ? err : "");
4644 struct ssh_rportfwd *pf;
4647 * Ensure the remote port forwardings tree exists.
4649 if (!ssh->rportfwds) {
4650 if (ssh->version == 1)
4651 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4653 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4656 pf = snew(struct ssh_rportfwd);
4657 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4658 pf->dhost[lenof(pf->dhost)-1] = '\0';
4659 pf->dport = epf->dport;
4660 pf->sport = epf->sport;
4661 if (add234(ssh->rportfwds, pf) != pf) {
4662 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4663 epf->daddr, epf->dport);
4666 logeventf(ssh, "Requesting remote port %s"
4667 " forward to %s", sportdesc, dportdesc);
4669 pf->sportdesc = sportdesc;
4674 if (ssh->version == 1) {
4675 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4676 PKT_INT, epf->sport,
4677 PKT_STR, epf->daddr,
4678 PKT_INT, epf->dport,
4680 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4682 ssh_rportfwd_succfail, pf);
4684 struct Packet *pktout;
4685 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4686 ssh2_pkt_addstring(pktout, "tcpip-forward");
4687 ssh2_pkt_addbool(pktout, 1);/* want reply */
4689 ssh2_pkt_addstring(pktout, epf->saddr);
4690 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4691 ssh2_pkt_addstring(pktout, "0.0.0.0");
4693 ssh2_pkt_addstring(pktout, "127.0.0.1");
4695 ssh2_pkt_adduint32(pktout, epf->sport);
4696 ssh2_pkt_send(ssh, pktout);
4698 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4699 SSH2_MSG_REQUEST_FAILURE,
4700 ssh_rportfwd_succfail, pf);
4709 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4712 int stringlen, bufsize;
4714 ssh_pkt_getstring(pktin, &string, &stringlen);
4715 if (string == NULL) {
4716 bombout(("Incoming terminal data packet was badly formed"));
4720 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4722 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4723 ssh->v1_stdout_throttling = 1;
4724 ssh_throttle_conn(ssh, +1);
4728 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4730 /* Remote side is trying to open a channel to talk to our
4731 * X-Server. Give them back a local channel number. */
4732 struct ssh_channel *c;
4733 int remoteid = ssh_pkt_getuint32(pktin);
4735 logevent("Received X11 connect request");
4736 /* Refuse if X11 forwarding is disabled. */
4737 if (!ssh->X11_fwd_enabled) {
4738 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4739 PKT_INT, remoteid, PKT_END);
4740 logevent("Rejected X11 connect request");
4742 c = snew(struct ssh_channel);
4745 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4746 NULL, -1, ssh->conf) != NULL) {
4747 logevent("Opening X11 forward connection failed");
4749 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4750 PKT_INT, remoteid, PKT_END);
4753 ("Opening X11 forward connection succeeded");
4754 c->remoteid = remoteid;
4755 c->halfopen = FALSE;
4756 c->localid = alloc_channel_id(ssh);
4758 c->pending_eof = FALSE;
4759 c->throttling_conn = 0;
4760 c->type = CHAN_X11; /* identify channel type */
4761 add234(ssh->channels, c);
4762 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4763 PKT_INT, c->remoteid, PKT_INT,
4764 c->localid, PKT_END);
4765 logevent("Opened X11 forward channel");
4770 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4772 /* Remote side is trying to open a channel to talk to our
4773 * agent. Give them back a local channel number. */
4774 struct ssh_channel *c;
4775 int remoteid = ssh_pkt_getuint32(pktin);
4777 /* Refuse if agent forwarding is disabled. */
4778 if (!ssh->agentfwd_enabled) {
4779 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4780 PKT_INT, remoteid, PKT_END);
4782 c = snew(struct ssh_channel);
4784 c->remoteid = remoteid;
4785 c->halfopen = FALSE;
4786 c->localid = alloc_channel_id(ssh);
4788 c->pending_eof = FALSE;
4789 c->throttling_conn = 0;
4790 c->type = CHAN_AGENT; /* identify channel type */
4791 c->u.a.lensofar = 0;
4792 c->u.a.message = NULL;
4793 add234(ssh->channels, c);
4794 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4795 PKT_INT, c->remoteid, PKT_INT, c->localid,
4800 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4802 /* Remote side is trying to open a channel to talk to a
4803 * forwarded port. Give them back a local channel number. */
4804 struct ssh_channel *c;
4805 struct ssh_rportfwd pf, *pfp;
4810 c = snew(struct ssh_channel);
4813 remoteid = ssh_pkt_getuint32(pktin);
4814 ssh_pkt_getstring(pktin, &host, &hostsize);
4815 port = ssh_pkt_getuint32(pktin);
4817 if (hostsize >= lenof(pf.dhost))
4818 hostsize = lenof(pf.dhost)-1;
4819 memcpy(pf.dhost, host, hostsize);
4820 pf.dhost[hostsize] = '\0';
4822 pfp = find234(ssh->rportfwds, &pf, NULL);
4825 logeventf(ssh, "Rejected remote port open request for %s:%d",
4827 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4828 PKT_INT, remoteid, PKT_END);
4830 logeventf(ssh, "Received remote port open request for %s:%d",
4832 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4833 c, ssh->conf, pfp->pfrec->addressfamily);
4835 logeventf(ssh, "Port open failed: %s", e);
4837 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4838 PKT_INT, remoteid, PKT_END);
4840 c->remoteid = remoteid;
4841 c->halfopen = FALSE;
4842 c->localid = alloc_channel_id(ssh);
4844 c->pending_eof = FALSE;
4845 c->throttling_conn = 0;
4846 c->type = CHAN_SOCKDATA; /* identify channel type */
4847 add234(ssh->channels, c);
4848 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4849 PKT_INT, c->remoteid, PKT_INT,
4850 c->localid, PKT_END);
4851 logevent("Forwarded port opened successfully");
4856 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4858 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4859 unsigned int localid = ssh_pkt_getuint32(pktin);
4860 struct ssh_channel *c;
4862 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4863 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4864 c->remoteid = localid;
4865 c->halfopen = FALSE;
4866 c->type = CHAN_SOCKDATA;
4867 c->throttling_conn = 0;
4868 pfd_confirm(c->u.pfd.s);
4871 if (c && c->pending_eof) {
4873 * We have a pending close on this channel,
4874 * which we decided on before the server acked
4875 * the channel open. So now we know the
4876 * remoteid, we can close it again.
4878 ssh_channel_try_eof(c);
4882 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4884 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4885 struct ssh_channel *c;
4887 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4888 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4889 logevent("Forwarded connection refused by server");
4890 pfd_close(c->u.pfd.s);
4891 del234(ssh->channels, c);
4896 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4898 /* Remote side closes a channel. */
4899 unsigned i = ssh_pkt_getuint32(pktin);
4900 struct ssh_channel *c;
4901 c = find234(ssh->channels, &i, ssh_channelfind);
4902 if (c && !c->halfopen) {
4904 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4905 !(c->closes & CLOSES_RCVD_EOF)) {
4907 * Received CHANNEL_CLOSE, which we translate into
4910 int send_close = FALSE;
4912 c->closes |= CLOSES_RCVD_EOF;
4917 x11_send_eof(c->u.x11.s);
4922 x11_send_eof(c->u.pfd.s);
4929 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4930 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4932 c->closes |= CLOSES_SENT_EOF;
4936 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4937 !(c->closes & CLOSES_RCVD_CLOSE)) {
4939 if (!(c->closes & CLOSES_SENT_EOF)) {
4940 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4941 " for which we never sent CHANNEL_CLOSE\n", i));
4944 c->closes |= CLOSES_RCVD_CLOSE;
4947 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4948 !(c->closes & CLOSES_SENT_CLOSE)) {
4949 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4950 PKT_INT, c->remoteid, PKT_END);
4951 c->closes |= CLOSES_SENT_CLOSE;
4954 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4955 ssh_channel_destroy(c);
4957 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4958 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4959 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4964 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4966 /* Data sent down one of our channels. */
4967 int i = ssh_pkt_getuint32(pktin);
4970 struct ssh_channel *c;
4972 ssh_pkt_getstring(pktin, &p, &len);
4974 c = find234(ssh->channels, &i, ssh_channelfind);
4979 bufsize = x11_send(c->u.x11.s, p, len);
4982 bufsize = pfd_send(c->u.pfd.s, p, len);
4985 /* Data for an agent message. Buffer it. */
4987 if (c->u.a.lensofar < 4) {
4988 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4989 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4993 c->u.a.lensofar += l;
4995 if (c->u.a.lensofar == 4) {
4997 4 + GET_32BIT(c->u.a.msglen);
4998 c->u.a.message = snewn(c->u.a.totallen,
5000 memcpy(c->u.a.message, c->u.a.msglen, 4);
5002 if (c->u.a.lensofar >= 4 && len > 0) {
5004 min(c->u.a.totallen - c->u.a.lensofar,
5006 memcpy(c->u.a.message + c->u.a.lensofar, p,
5010 c->u.a.lensofar += l;
5012 if (c->u.a.lensofar == c->u.a.totallen) {
5015 if (agent_query(c->u.a.message,
5018 ssh_agentf_callback, c))
5019 ssh_agentf_callback(c, reply, replylen);
5020 sfree(c->u.a.message);
5021 c->u.a.lensofar = 0;
5024 bufsize = 0; /* agent channels never back up */
5027 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5028 c->throttling_conn = 1;
5029 ssh_throttle_conn(ssh, +1);
5034 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5036 ssh->exitcode = ssh_pkt_getuint32(pktin);
5037 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5038 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5040 * In case `helpful' firewalls or proxies tack
5041 * extra human-readable text on the end of the
5042 * session which we might mistake for another
5043 * encrypted packet, we close the session once
5044 * we've sent EXIT_CONFIRMATION.
5046 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5049 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5050 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5052 struct Packet *pktout = (struct Packet *)data;
5054 unsigned int arg = 0;
5055 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5056 if (i == lenof(ssh_ttymodes)) return;
5057 switch (ssh_ttymodes[i].type) {
5059 arg = ssh_tty_parse_specchar(val);
5062 arg = ssh_tty_parse_boolean(val);
5065 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5066 ssh2_pkt_addbyte(pktout, arg);
5070 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5071 struct Packet *pktin)
5073 crBegin(ssh->do_ssh1_connection_crstate);
5075 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5076 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5077 ssh1_smsg_stdout_stderr_data;
5079 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5080 ssh1_msg_channel_open_confirmation;
5081 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5082 ssh1_msg_channel_open_failure;
5083 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5084 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5085 ssh1_msg_channel_close;
5086 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5087 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5089 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5090 logevent("Requesting agent forwarding");
5091 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5095 if (pktin->type != SSH1_SMSG_SUCCESS
5096 && pktin->type != SSH1_SMSG_FAILURE) {
5097 bombout(("Protocol confusion"));
5099 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5100 logevent("Agent forwarding refused");
5102 logevent("Agent forwarding enabled");
5103 ssh->agentfwd_enabled = TRUE;
5104 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5108 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5109 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5110 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5111 logevent("Requesting X11 forwarding");
5113 * Note that while we blank the X authentication data here, we don't
5114 * take any special action to blank the start of an X11 channel,
5115 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5116 * without having session blanking enabled is likely to leak your
5117 * cookie into the log.
5119 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5120 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5121 PKT_STR, ssh->x11disp->remoteauthprotoname,
5123 PKT_STR, ssh->x11disp->remoteauthdatastring,
5125 PKT_INT, ssh->x11disp->screennum,
5128 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5129 PKT_STR, ssh->x11disp->remoteauthprotoname,
5131 PKT_STR, ssh->x11disp->remoteauthdatastring,
5138 if (pktin->type != SSH1_SMSG_SUCCESS
5139 && pktin->type != SSH1_SMSG_FAILURE) {
5140 bombout(("Protocol confusion"));
5142 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5143 logevent("X11 forwarding refused");
5145 logevent("X11 forwarding enabled");
5146 ssh->X11_fwd_enabled = TRUE;
5147 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5151 ssh_setup_portfwd(ssh, ssh->conf);
5152 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5154 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5156 /* Unpick the terminal-speed string. */
5157 /* XXX perhaps we should allow no speeds to be sent. */
5158 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5159 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5160 /* Send the pty request. */
5161 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5162 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5163 ssh_pkt_adduint32(pkt, ssh->term_height);
5164 ssh_pkt_adduint32(pkt, ssh->term_width);
5165 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5166 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5167 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5168 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5169 ssh_pkt_adduint32(pkt, ssh->ispeed);
5170 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5171 ssh_pkt_adduint32(pkt, ssh->ospeed);
5172 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5174 ssh->state = SSH_STATE_INTERMED;
5178 if (pktin->type != SSH1_SMSG_SUCCESS
5179 && pktin->type != SSH1_SMSG_FAILURE) {
5180 bombout(("Protocol confusion"));
5182 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5183 c_write_str(ssh, "Server refused to allocate pty\r\n");
5184 ssh->editing = ssh->echoing = 1;
5186 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5187 ssh->ospeed, ssh->ispeed);
5188 ssh->got_pty = TRUE;
5191 ssh->editing = ssh->echoing = 1;
5194 if (conf_get_int(ssh->conf, CONF_compression)) {
5195 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5199 if (pktin->type != SSH1_SMSG_SUCCESS
5200 && pktin->type != SSH1_SMSG_FAILURE) {
5201 bombout(("Protocol confusion"));
5203 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5204 c_write_str(ssh, "Server refused to compress\r\n");
5206 logevent("Started compression");
5207 ssh->v1_compressing = TRUE;
5208 ssh->cs_comp_ctx = zlib_compress_init();
5209 logevent("Initialised zlib (RFC1950) compression");
5210 ssh->sc_comp_ctx = zlib_decompress_init();
5211 logevent("Initialised zlib (RFC1950) decompression");
5215 * Start the shell or command.
5217 * Special case: if the first-choice command is an SSH-2
5218 * subsystem (hence not usable here) and the second choice
5219 * exists, we fall straight back to that.
5222 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5224 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5225 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5226 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5227 ssh->fallback_cmd = TRUE;
5230 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5232 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5233 logevent("Started session");
5236 ssh->state = SSH_STATE_SESSION;
5237 if (ssh->size_needed)
5238 ssh_size(ssh, ssh->term_width, ssh->term_height);
5239 if (ssh->eof_needed)
5240 ssh_special(ssh, TS_EOF);
5243 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5245 ssh->channels = newtree234(ssh_channelcmp);
5249 * By this point, most incoming packets are already being
5250 * handled by the dispatch table, and we need only pay
5251 * attention to the unusual ones.
5256 if (pktin->type == SSH1_SMSG_SUCCESS) {
5257 /* may be from EXEC_SHELL on some servers */
5258 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5259 /* may be from EXEC_SHELL on some servers
5260 * if no pty is available or in other odd cases. Ignore */
5262 bombout(("Strange packet received: type %d", pktin->type));
5267 int len = min(inlen, 512);
5268 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5269 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5270 PKTT_OTHER, PKT_END);
5281 * Handle the top-level SSH-2 protocol.
5283 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5288 ssh_pkt_getstring(pktin, &msg, &msglen);
5289 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5292 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5294 /* log reason code in disconnect message */
5298 ssh_pkt_getstring(pktin, &msg, &msglen);
5299 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5302 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5304 /* Do nothing, because we're ignoring it! Duhh. */
5307 static void ssh1_protocol_setup(Ssh ssh)
5312 * Most messages are handled by the coroutines.
5314 for (i = 0; i < 256; i++)
5315 ssh->packet_dispatch[i] = NULL;
5318 * These special message types we install handlers for.
5320 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5321 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5322 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5325 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5326 struct Packet *pktin)
5328 unsigned char *in=(unsigned char*)vin;
5329 if (ssh->state == SSH_STATE_CLOSED)
5332 if (pktin && ssh->packet_dispatch[pktin->type]) {
5333 ssh->packet_dispatch[pktin->type](ssh, pktin);
5337 if (!ssh->protocol_initial_phase_done) {
5338 if (do_ssh1_login(ssh, in, inlen, pktin))
5339 ssh->protocol_initial_phase_done = TRUE;
5344 do_ssh1_connection(ssh, in, inlen, pktin);
5348 * Utility routine for decoding comma-separated strings in KEXINIT.
5350 static int in_commasep_string(char *needle, char *haystack, int haylen)
5353 if (!needle || !haystack) /* protect against null pointers */
5355 needlen = strlen(needle);
5358 * Is it at the start of the string?
5360 if (haylen >= needlen && /* haystack is long enough */
5361 !memcmp(needle, haystack, needlen) && /* initial match */
5362 (haylen == needlen || haystack[needlen] == ',')
5363 /* either , or EOS follows */
5367 * If not, search for the next comma and resume after that.
5368 * If no comma found, terminate.
5370 while (haylen > 0 && *haystack != ',')
5371 haylen--, haystack++;
5374 haylen--, haystack++; /* skip over comma itself */
5379 * Similar routine for checking whether we have the first string in a list.
5381 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5384 if (!needle || !haystack) /* protect against null pointers */
5386 needlen = strlen(needle);
5388 * Is it at the start of the string?
5390 if (haylen >= needlen && /* haystack is long enough */
5391 !memcmp(needle, haystack, needlen) && /* initial match */
5392 (haylen == needlen || haystack[needlen] == ',')
5393 /* either , or EOS follows */
5401 * SSH-2 key creation method.
5402 * (Currently assumes 2 lots of any hash are sufficient to generate
5403 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5405 #define SSH2_MKKEY_ITERS (2)
5406 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5407 unsigned char *keyspace)
5409 const struct ssh_hash *h = ssh->kex->hash;
5411 /* First hlen bytes. */
5413 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5414 hash_mpint(h, s, K);
5415 h->bytes(s, H, h->hlen);
5416 h->bytes(s, &chr, 1);
5417 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5418 h->final(s, keyspace);
5419 /* Next hlen bytes. */
5421 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5422 hash_mpint(h, s, K);
5423 h->bytes(s, H, h->hlen);
5424 h->bytes(s, keyspace, h->hlen);
5425 h->final(s, keyspace + h->hlen);
5429 * Handle the SSH-2 transport layer.
5431 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5432 struct Packet *pktin)
5434 unsigned char *in = (unsigned char *)vin;
5435 struct do_ssh2_transport_state {
5436 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5437 Bignum p, g, e, f, K;
5440 int kex_init_value, kex_reply_value;
5441 const struct ssh_mac **maclist;
5443 const struct ssh2_cipher *cscipher_tobe;
5444 const struct ssh2_cipher *sccipher_tobe;
5445 const struct ssh_mac *csmac_tobe;
5446 const struct ssh_mac *scmac_tobe;
5447 const struct ssh_compress *cscomp_tobe;
5448 const struct ssh_compress *sccomp_tobe;
5449 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5450 int hostkeylen, siglen, rsakeylen;
5451 void *hkey; /* actual host key */
5452 void *rsakey; /* for RSA kex */
5453 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5454 int n_preferred_kex;
5455 const struct ssh_kexes *preferred_kex[KEX_MAX];
5456 int n_preferred_ciphers;
5457 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5458 const struct ssh_compress *preferred_comp;
5459 int userauth_succeeded; /* for delayed compression */
5460 int pending_compression;
5461 int got_session_id, activated_authconn;
5462 struct Packet *pktout;
5467 crState(do_ssh2_transport_state);
5469 crBegin(ssh->do_ssh2_transport_crstate);
5471 s->cscipher_tobe = s->sccipher_tobe = NULL;
5472 s->csmac_tobe = s->scmac_tobe = NULL;
5473 s->cscomp_tobe = s->sccomp_tobe = NULL;
5475 s->got_session_id = s->activated_authconn = FALSE;
5476 s->userauth_succeeded = FALSE;
5477 s->pending_compression = FALSE;
5480 * Be prepared to work around the buggy MAC problem.
5482 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5483 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5485 s->maclist = macs, s->nmacs = lenof(macs);
5488 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5490 int i, j, commalist_started;
5493 * Set up the preferred key exchange. (NULL => warn below here)
5495 s->n_preferred_kex = 0;
5496 for (i = 0; i < KEX_MAX; i++) {
5497 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5499 s->preferred_kex[s->n_preferred_kex++] =
5500 &ssh_diffiehellman_gex;
5503 s->preferred_kex[s->n_preferred_kex++] =
5504 &ssh_diffiehellman_group14;
5507 s->preferred_kex[s->n_preferred_kex++] =
5508 &ssh_diffiehellman_group1;
5511 s->preferred_kex[s->n_preferred_kex++] =
5515 /* Flag for later. Don't bother if it's the last in
5517 if (i < KEX_MAX - 1) {
5518 s->preferred_kex[s->n_preferred_kex++] = NULL;
5525 * Set up the preferred ciphers. (NULL => warn below here)
5527 s->n_preferred_ciphers = 0;
5528 for (i = 0; i < CIPHER_MAX; i++) {
5529 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5530 case CIPHER_BLOWFISH:
5531 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5534 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5535 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5539 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5542 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5544 case CIPHER_ARCFOUR:
5545 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5548 /* Flag for later. Don't bother if it's the last in
5550 if (i < CIPHER_MAX - 1) {
5551 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5558 * Set up preferred compression.
5560 if (conf_get_int(ssh->conf, CONF_compression))
5561 s->preferred_comp = &ssh_zlib;
5563 s->preferred_comp = &ssh_comp_none;
5566 * Enable queueing of outgoing auth- or connection-layer
5567 * packets while we are in the middle of a key exchange.
5569 ssh->queueing = TRUE;
5572 * Flag that KEX is in progress.
5574 ssh->kex_in_progress = TRUE;
5577 * Construct and send our key exchange packet.
5579 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5580 for (i = 0; i < 16; i++)
5581 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5582 /* List key exchange algorithms. */
5583 ssh2_pkt_addstring_start(s->pktout);
5584 commalist_started = 0;
5585 for (i = 0; i < s->n_preferred_kex; i++) {
5586 const struct ssh_kexes *k = s->preferred_kex[i];
5587 if (!k) continue; /* warning flag */
5588 for (j = 0; j < k->nkexes; j++) {
5589 if (commalist_started)
5590 ssh2_pkt_addstring_str(s->pktout, ",");
5591 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5592 commalist_started = 1;
5595 /* List server host key algorithms. */
5596 ssh2_pkt_addstring_start(s->pktout);
5597 for (i = 0; i < lenof(hostkey_algs); i++) {
5598 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5599 if (i < lenof(hostkey_algs) - 1)
5600 ssh2_pkt_addstring_str(s->pktout, ",");
5602 /* List client->server encryption algorithms. */
5603 ssh2_pkt_addstring_start(s->pktout);
5604 commalist_started = 0;
5605 for (i = 0; i < s->n_preferred_ciphers; i++) {
5606 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5607 if (!c) continue; /* warning flag */
5608 for (j = 0; j < c->nciphers; j++) {
5609 if (commalist_started)
5610 ssh2_pkt_addstring_str(s->pktout, ",");
5611 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5612 commalist_started = 1;
5615 /* List server->client encryption algorithms. */
5616 ssh2_pkt_addstring_start(s->pktout);
5617 commalist_started = 0;
5618 for (i = 0; i < s->n_preferred_ciphers; i++) {
5619 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5620 if (!c) continue; /* warning flag */
5621 for (j = 0; j < c->nciphers; j++) {
5622 if (commalist_started)
5623 ssh2_pkt_addstring_str(s->pktout, ",");
5624 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5625 commalist_started = 1;
5628 /* List client->server MAC algorithms. */
5629 ssh2_pkt_addstring_start(s->pktout);
5630 for (i = 0; i < s->nmacs; i++) {
5631 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5632 if (i < s->nmacs - 1)
5633 ssh2_pkt_addstring_str(s->pktout, ",");
5635 /* List server->client MAC algorithms. */
5636 ssh2_pkt_addstring_start(s->pktout);
5637 for (i = 0; i < s->nmacs; i++) {
5638 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5639 if (i < s->nmacs - 1)
5640 ssh2_pkt_addstring_str(s->pktout, ",");
5642 /* List client->server compression algorithms,
5643 * then server->client compression algorithms. (We use the
5644 * same set twice.) */
5645 for (j = 0; j < 2; j++) {
5646 ssh2_pkt_addstring_start(s->pktout);
5647 assert(lenof(compressions) > 1);
5648 /* Prefer non-delayed versions */
5649 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5650 /* We don't even list delayed versions of algorithms until
5651 * they're allowed to be used, to avoid a race. See the end of
5653 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5654 ssh2_pkt_addstring_str(s->pktout, ",");
5655 ssh2_pkt_addstring_str(s->pktout,
5656 s->preferred_comp->delayed_name);
5658 for (i = 0; i < lenof(compressions); i++) {
5659 const struct ssh_compress *c = compressions[i];
5660 if (c != s->preferred_comp) {
5661 ssh2_pkt_addstring_str(s->pktout, ",");
5662 ssh2_pkt_addstring_str(s->pktout, c->name);
5663 if (s->userauth_succeeded && c->delayed_name) {
5664 ssh2_pkt_addstring_str(s->pktout, ",");
5665 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5670 /* List client->server languages. Empty list. */
5671 ssh2_pkt_addstring_start(s->pktout);
5672 /* List server->client languages. Empty list. */
5673 ssh2_pkt_addstring_start(s->pktout);
5674 /* First KEX packet does _not_ follow, because we're not that brave. */
5675 ssh2_pkt_addbool(s->pktout, FALSE);
5677 ssh2_pkt_adduint32(s->pktout, 0);
5680 s->our_kexinitlen = s->pktout->length - 5;
5681 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5682 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5684 ssh2_pkt_send_noqueue(ssh, s->pktout);
5690 * Now examine the other side's KEXINIT to see what we're up
5694 char *str, *preferred;
5697 if (pktin->type != SSH2_MSG_KEXINIT) {
5698 bombout(("expected key exchange packet from server"));
5702 ssh->hostkey = NULL;
5703 s->cscipher_tobe = NULL;
5704 s->sccipher_tobe = NULL;
5705 s->csmac_tobe = NULL;
5706 s->scmac_tobe = NULL;
5707 s->cscomp_tobe = NULL;
5708 s->sccomp_tobe = NULL;
5709 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5711 pktin->savedpos += 16; /* skip garbage cookie */
5712 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5715 for (i = 0; i < s->n_preferred_kex; i++) {
5716 const struct ssh_kexes *k = s->preferred_kex[i];
5720 for (j = 0; j < k->nkexes; j++) {
5721 if (!preferred) preferred = k->list[j]->name;
5722 if (in_commasep_string(k->list[j]->name, str, len)) {
5723 ssh->kex = k->list[j];
5732 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5733 str ? str : "(null)"));
5737 * Note that the server's guess is considered wrong if it doesn't match
5738 * the first algorithm in our list, even if it's still the algorithm
5741 s->guessok = first_in_commasep_string(preferred, str, len);
5742 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5743 for (i = 0; i < lenof(hostkey_algs); i++) {
5744 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5745 ssh->hostkey = hostkey_algs[i];
5749 s->guessok = s->guessok &&
5750 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5751 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5752 for (i = 0; i < s->n_preferred_ciphers; i++) {
5753 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5755 s->warn_cscipher = TRUE;
5757 for (j = 0; j < c->nciphers; j++) {
5758 if (in_commasep_string(c->list[j]->name, str, len)) {
5759 s->cscipher_tobe = c->list[j];
5764 if (s->cscipher_tobe)
5767 if (!s->cscipher_tobe) {
5768 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5769 str ? str : "(null)"));
5773 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5774 for (i = 0; i < s->n_preferred_ciphers; i++) {
5775 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5777 s->warn_sccipher = TRUE;
5779 for (j = 0; j < c->nciphers; j++) {
5780 if (in_commasep_string(c->list[j]->name, str, len)) {
5781 s->sccipher_tobe = c->list[j];
5786 if (s->sccipher_tobe)
5789 if (!s->sccipher_tobe) {
5790 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5791 str ? str : "(null)"));
5795 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5796 for (i = 0; i < s->nmacs; i++) {
5797 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5798 s->csmac_tobe = s->maclist[i];
5802 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5803 for (i = 0; i < s->nmacs; i++) {
5804 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5805 s->scmac_tobe = s->maclist[i];
5809 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5810 for (i = 0; i < lenof(compressions) + 1; i++) {
5811 const struct ssh_compress *c =
5812 i == 0 ? s->preferred_comp : compressions[i - 1];
5813 if (in_commasep_string(c->name, str, len)) {
5816 } else if (in_commasep_string(c->delayed_name, str, len)) {
5817 if (s->userauth_succeeded) {
5821 s->pending_compression = TRUE; /* try this later */
5825 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5826 for (i = 0; i < lenof(compressions) + 1; i++) {
5827 const struct ssh_compress *c =
5828 i == 0 ? s->preferred_comp : compressions[i - 1];
5829 if (in_commasep_string(c->name, str, len)) {
5832 } else if (in_commasep_string(c->delayed_name, str, len)) {
5833 if (s->userauth_succeeded) {
5837 s->pending_compression = TRUE; /* try this later */
5841 if (s->pending_compression) {
5842 logevent("Server supports delayed compression; "
5843 "will try this later");
5845 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5846 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5847 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5850 ssh_set_frozen(ssh, 1);
5851 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5853 ssh_dialog_callback, ssh);
5854 if (s->dlgret < 0) {
5858 bombout(("Unexpected data from server while"
5859 " waiting for user response"));
5862 } while (pktin || inlen > 0);
5863 s->dlgret = ssh->user_response;
5865 ssh_set_frozen(ssh, 0);
5866 if (s->dlgret == 0) {
5867 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5873 if (s->warn_cscipher) {
5874 ssh_set_frozen(ssh, 1);
5875 s->dlgret = askalg(ssh->frontend,
5876 "client-to-server cipher",
5877 s->cscipher_tobe->name,
5878 ssh_dialog_callback, ssh);
5879 if (s->dlgret < 0) {
5883 bombout(("Unexpected data from server while"
5884 " waiting for user response"));
5887 } while (pktin || inlen > 0);
5888 s->dlgret = ssh->user_response;
5890 ssh_set_frozen(ssh, 0);
5891 if (s->dlgret == 0) {
5892 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5898 if (s->warn_sccipher) {
5899 ssh_set_frozen(ssh, 1);
5900 s->dlgret = askalg(ssh->frontend,
5901 "server-to-client cipher",
5902 s->sccipher_tobe->name,
5903 ssh_dialog_callback, ssh);
5904 if (s->dlgret < 0) {
5908 bombout(("Unexpected data from server while"
5909 " waiting for user response"));
5912 } while (pktin || inlen > 0);
5913 s->dlgret = ssh->user_response;
5915 ssh_set_frozen(ssh, 0);
5916 if (s->dlgret == 0) {
5917 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5923 ssh->exhash = ssh->kex->hash->init();
5924 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5925 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5926 hash_string(ssh->kex->hash, ssh->exhash,
5927 s->our_kexinit, s->our_kexinitlen);
5928 sfree(s->our_kexinit);
5929 if (pktin->length > 5)
5930 hash_string(ssh->kex->hash, ssh->exhash,
5931 pktin->data + 5, pktin->length - 5);
5933 if (s->ignorepkt) /* first_kex_packet_follows */
5934 crWaitUntil(pktin); /* Ignore packet */
5937 if (ssh->kex->main_type == KEXTYPE_DH) {
5939 * Work out the number of bits of key we will need from the
5940 * key exchange. We start with the maximum key length of
5946 csbits = s->cscipher_tobe->keylen;
5947 scbits = s->sccipher_tobe->keylen;
5948 s->nbits = (csbits > scbits ? csbits : scbits);
5950 /* The keys only have hlen-bit entropy, since they're based on
5951 * a hash. So cap the key size at hlen bits. */
5952 if (s->nbits > ssh->kex->hash->hlen * 8)
5953 s->nbits = ssh->kex->hash->hlen * 8;
5956 * If we're doing Diffie-Hellman group exchange, start by
5957 * requesting a group.
5959 if (!ssh->kex->pdata) {
5960 logevent("Doing Diffie-Hellman group exchange");
5961 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5963 * Work out how big a DH group we will need to allow that
5966 s->pbits = 512 << ((s->nbits - 1) / 64);
5967 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5968 ssh2_pkt_adduint32(s->pktout, s->pbits);
5969 ssh2_pkt_send_noqueue(ssh, s->pktout);
5972 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5973 bombout(("expected key exchange group packet from server"));
5976 s->p = ssh2_pkt_getmp(pktin);
5977 s->g = ssh2_pkt_getmp(pktin);
5978 if (!s->p || !s->g) {
5979 bombout(("unable to read mp-ints from incoming group packet"));
5982 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5983 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5984 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5986 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5987 ssh->kex_ctx = dh_setup_group(ssh->kex);
5988 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5989 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5990 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5991 ssh->kex->groupname);
5994 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5995 ssh->kex->hash->text_name);
5997 * Now generate and send e for Diffie-Hellman.
5999 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6000 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6001 s->pktout = ssh2_pkt_init(s->kex_init_value);
6002 ssh2_pkt_addmp(s->pktout, s->e);
6003 ssh2_pkt_send_noqueue(ssh, s->pktout);
6005 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6007 if (pktin->type != s->kex_reply_value) {
6008 bombout(("expected key exchange reply packet from server"));
6011 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6012 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6013 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6014 s->f = ssh2_pkt_getmp(pktin);
6016 bombout(("unable to parse key exchange reply packet"));
6019 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6021 s->K = dh_find_K(ssh->kex_ctx, s->f);
6023 /* We assume everything from now on will be quick, and it might
6024 * involve user interaction. */
6025 set_busy_status(ssh->frontend, BUSY_NOT);
6027 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6028 if (!ssh->kex->pdata) {
6029 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6030 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6031 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6033 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6034 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6036 dh_cleanup(ssh->kex_ctx);
6038 if (!ssh->kex->pdata) {
6043 logeventf(ssh, "Doing RSA key exchange with hash %s",
6044 ssh->kex->hash->text_name);
6045 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6047 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6051 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6052 bombout(("expected RSA public key packet from server"));
6056 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6057 hash_string(ssh->kex->hash, ssh->exhash,
6058 s->hostkeydata, s->hostkeylen);
6059 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6063 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6064 s->rsakeydata = snewn(s->rsakeylen, char);
6065 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6068 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6070 sfree(s->rsakeydata);
6071 bombout(("unable to parse RSA public key from server"));
6075 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6078 * Next, set up a shared secret K, of precisely KLEN -
6079 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6080 * RSA key modulus and HLEN is the bit length of the hash
6084 int klen = ssh_rsakex_klen(s->rsakey);
6085 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6087 unsigned char *kstr1, *kstr2, *outstr;
6088 int kstr1len, kstr2len, outstrlen;
6090 s->K = bn_power_2(nbits - 1);
6092 for (i = 0; i < nbits; i++) {
6094 byte = random_byte();
6096 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6100 * Encode this as an mpint.
6102 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6103 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6104 PUT_32BIT(kstr2, kstr1len);
6105 memcpy(kstr2 + 4, kstr1, kstr1len);
6108 * Encrypt it with the given RSA key.
6110 outstrlen = (klen + 7) / 8;
6111 outstr = snewn(outstrlen, unsigned char);
6112 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6113 outstr, outstrlen, s->rsakey);
6116 * And send it off in a return packet.
6118 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6119 ssh2_pkt_addstring_start(s->pktout);
6120 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6121 ssh2_pkt_send_noqueue(ssh, s->pktout);
6123 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6130 ssh_rsakex_freekey(s->rsakey);
6133 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6134 sfree(s->rsakeydata);
6135 bombout(("expected signature packet from server"));
6139 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6141 sfree(s->rsakeydata);
6144 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6145 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6146 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6148 ssh->kex_ctx = NULL;
6151 debug(("Exchange hash is:\n"));
6152 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6156 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6157 (char *)s->exchange_hash,
6158 ssh->kex->hash->hlen)) {
6159 bombout(("Server's host key did not match the signature supplied"));
6164 * Authenticate remote host: verify host key. (We've already
6165 * checked the signature of the exchange hash.)
6167 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6168 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6169 ssh_set_frozen(ssh, 1);
6170 s->dlgret = verify_ssh_host_key(ssh->frontend,
6171 ssh->savedhost, ssh->savedport,
6172 ssh->hostkey->keytype, s->keystr,
6174 ssh_dialog_callback, ssh);
6175 if (s->dlgret < 0) {
6179 bombout(("Unexpected data from server while waiting"
6180 " for user host key response"));
6183 } while (pktin || inlen > 0);
6184 s->dlgret = ssh->user_response;
6186 ssh_set_frozen(ssh, 0);
6187 if (s->dlgret == 0) {
6188 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6192 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6193 logevent("Host key fingerprint is:");
6194 logevent(s->fingerprint);
6196 sfree(s->fingerprint);
6198 ssh->hostkey->freekey(s->hkey);
6201 * The exchange hash from the very first key exchange is also
6202 * the session id, used in session key construction and
6205 if (!s->got_session_id) {
6206 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6207 memcpy(ssh->v2_session_id, s->exchange_hash,
6208 sizeof(s->exchange_hash));
6209 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6210 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6211 s->got_session_id = TRUE;
6215 * Send SSH2_MSG_NEWKEYS.
6217 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6218 ssh2_pkt_send_noqueue(ssh, s->pktout);
6219 ssh->outgoing_data_size = 0; /* start counting from here */
6222 * We've sent client NEWKEYS, so create and initialise
6223 * client-to-server session keys.
6225 if (ssh->cs_cipher_ctx)
6226 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6227 ssh->cscipher = s->cscipher_tobe;
6228 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6230 if (ssh->cs_mac_ctx)
6231 ssh->csmac->free_context(ssh->cs_mac_ctx);
6232 ssh->csmac = s->csmac_tobe;
6233 ssh->cs_mac_ctx = ssh->csmac->make_context();
6235 if (ssh->cs_comp_ctx)
6236 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6237 ssh->cscomp = s->cscomp_tobe;
6238 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6241 * Set IVs on client-to-server keys. Here we use the exchange
6242 * hash from the _first_ key exchange.
6245 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6246 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6247 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6248 assert((ssh->cscipher->keylen+7) / 8 <=
6249 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6250 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6251 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6252 assert(ssh->cscipher->blksize <=
6253 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6254 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6255 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6256 assert(ssh->csmac->len <=
6257 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6258 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6259 memset(keyspace, 0, sizeof(keyspace));
6262 logeventf(ssh, "Initialised %.200s client->server encryption",
6263 ssh->cscipher->text_name);
6264 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6265 ssh->csmac->text_name);
6266 if (ssh->cscomp->text_name)
6267 logeventf(ssh, "Initialised %s compression",
6268 ssh->cscomp->text_name);
6271 * Now our end of the key exchange is complete, we can send all
6272 * our queued higher-layer packets.
6274 ssh->queueing = FALSE;
6275 ssh2_pkt_queuesend(ssh);
6278 * Expect SSH2_MSG_NEWKEYS from server.
6281 if (pktin->type != SSH2_MSG_NEWKEYS) {
6282 bombout(("expected new-keys packet from server"));
6285 ssh->incoming_data_size = 0; /* start counting from here */
6288 * We've seen server NEWKEYS, so create and initialise
6289 * server-to-client session keys.
6291 if (ssh->sc_cipher_ctx)
6292 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6293 ssh->sccipher = s->sccipher_tobe;
6294 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6296 if (ssh->sc_mac_ctx)
6297 ssh->scmac->free_context(ssh->sc_mac_ctx);
6298 ssh->scmac = s->scmac_tobe;
6299 ssh->sc_mac_ctx = ssh->scmac->make_context();
6301 if (ssh->sc_comp_ctx)
6302 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6303 ssh->sccomp = s->sccomp_tobe;
6304 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6307 * Set IVs on server-to-client keys. Here we use the exchange
6308 * hash from the _first_ key exchange.
6311 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6312 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6313 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6314 assert((ssh->sccipher->keylen+7) / 8 <=
6315 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6316 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6317 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6318 assert(ssh->sccipher->blksize <=
6319 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6320 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6321 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6322 assert(ssh->scmac->len <=
6323 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6324 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6325 memset(keyspace, 0, sizeof(keyspace));
6327 logeventf(ssh, "Initialised %.200s server->client encryption",
6328 ssh->sccipher->text_name);
6329 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6330 ssh->scmac->text_name);
6331 if (ssh->sccomp->text_name)
6332 logeventf(ssh, "Initialised %s decompression",
6333 ssh->sccomp->text_name);
6336 * Free shared secret.
6341 * Key exchange is over. Loop straight back round if we have a
6342 * deferred rekey reason.
6344 if (ssh->deferred_rekey_reason) {
6345 logevent(ssh->deferred_rekey_reason);
6347 ssh->deferred_rekey_reason = NULL;
6348 goto begin_key_exchange;
6352 * Otherwise, schedule a timer for our next rekey.
6354 ssh->kex_in_progress = FALSE;
6355 ssh->last_rekey = GETTICKCOUNT();
6356 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6357 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6361 * If this is the first key exchange phase, we must pass the
6362 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6363 * wants to see it but because it will need time to initialise
6364 * itself before it sees an actual packet. In subsequent key
6365 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6366 * it would only confuse the layer above.
6368 if (s->activated_authconn) {
6371 s->activated_authconn = TRUE;
6374 * Now we're encrypting. Begin returning 1 to the protocol main
6375 * function so that other things can run on top of the
6376 * transport. If we ever see a KEXINIT, we must go back to the
6379 * We _also_ go back to the start if we see pktin==NULL and
6380 * inlen negative, because this is a special signal meaning
6381 * `initiate client-driven rekey', and `in' contains a message
6382 * giving the reason for the rekey.
6384 * inlen==-1 means always initiate a rekey;
6385 * inlen==-2 means that userauth has completed successfully and
6386 * we should consider rekeying (for delayed compression).
6388 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6389 (!pktin && inlen < 0))) {
6394 logevent("Server initiated key re-exchange");
6398 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6399 * delayed compression, if it's available.
6401 * draft-miller-secsh-compression-delayed-00 says that you
6402 * negotiate delayed compression in the first key exchange, and
6403 * both sides start compressing when the server has sent
6404 * USERAUTH_SUCCESS. This has a race condition -- the server
6405 * can't know when the client has seen it, and thus which incoming
6406 * packets it should treat as compressed.
6408 * Instead, we do the initial key exchange without offering the
6409 * delayed methods, but note if the server offers them; when we
6410 * get here, if a delayed method was available that was higher
6411 * on our list than what we got, we initiate a rekey in which we
6412 * _do_ list the delayed methods (and hopefully get it as a
6413 * result). Subsequent rekeys will do the same.
6415 assert(!s->userauth_succeeded); /* should only happen once */
6416 s->userauth_succeeded = TRUE;
6417 if (!s->pending_compression)
6418 /* Can't see any point rekeying. */
6419 goto wait_for_rekey; /* this is utterly horrid */
6420 /* else fall through to rekey... */
6421 s->pending_compression = FALSE;
6424 * Now we've decided to rekey.
6426 * Special case: if the server bug is set that doesn't
6427 * allow rekeying, we give a different log message and
6428 * continue waiting. (If such a server _initiates_ a rekey,
6429 * we process it anyway!)
6431 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6432 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6434 /* Reset the counters, so that at least this message doesn't
6435 * hit the event log _too_ often. */
6436 ssh->outgoing_data_size = 0;
6437 ssh->incoming_data_size = 0;
6438 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6440 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6443 goto wait_for_rekey; /* this is still utterly horrid */
6445 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6448 goto begin_key_exchange;
6454 * Add data to an SSH-2 channel output buffer.
6456 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6459 bufchain_add(&c->v.v2.outbuffer, buf, len);
6463 * Attempt to send data on an SSH-2 channel.
6465 static int ssh2_try_send(struct ssh_channel *c)
6468 struct Packet *pktout;
6471 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6474 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6475 if ((unsigned)len > c->v.v2.remwindow)
6476 len = c->v.v2.remwindow;
6477 if ((unsigned)len > c->v.v2.remmaxpkt)
6478 len = c->v.v2.remmaxpkt;
6479 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6480 ssh2_pkt_adduint32(pktout, c->remoteid);
6481 ssh2_pkt_addstring_start(pktout);
6482 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6483 ssh2_pkt_addstring_data(pktout, data, len);
6484 end_log_omission(ssh, pktout);
6485 ssh2_pkt_send(ssh, pktout);
6486 bufchain_consume(&c->v.v2.outbuffer, len);
6487 c->v.v2.remwindow -= len;
6491 * After having sent as much data as we can, return the amount
6494 ret = bufchain_size(&c->v.v2.outbuffer);
6497 * And if there's no data pending but we need to send an EOF, send
6500 if (!ret && c->pending_eof)
6501 ssh_channel_try_eof(c);
6506 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6509 if (c->closes & CLOSES_SENT_EOF)
6510 return; /* don't send on channels we've EOFed */
6511 bufsize = ssh2_try_send(c);
6514 case CHAN_MAINSESSION:
6515 /* stdin need not receive an unthrottle
6516 * notification since it will be polled */
6519 x11_unthrottle(c->u.x11.s);
6522 /* agent sockets are request/response and need no
6523 * buffer management */
6526 pfd_unthrottle(c->u.pfd.s);
6533 * Set up most of a new ssh_channel for SSH-2.
6535 static void ssh2_channel_init(struct ssh_channel *c)
6538 c->localid = alloc_channel_id(ssh);
6540 c->pending_eof = FALSE;
6541 c->throttling_conn = FALSE;
6542 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6543 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6544 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6545 c->v.v2.throttle_state = UNTHROTTLED;
6546 bufchain_init(&c->v.v2.outbuffer);
6550 * Potentially enlarge the window on an SSH-2 channel.
6552 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6557 * Never send WINDOW_ADJUST for a channel that the remote side has
6558 * already sent EOF on; there's no point, since it won't be
6559 * sending any more data anyway.
6561 if (c->closes & CLOSES_RCVD_EOF)
6565 * If the remote end has a habit of ignoring maxpkt, limit the
6566 * window so that it has no choice (assuming it doesn't ignore the
6569 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6570 newwin = OUR_V2_MAXPKT;
6574 * Only send a WINDOW_ADJUST if there's significantly more window
6575 * available than the other end thinks there is. This saves us
6576 * sending a WINDOW_ADJUST for every character in a shell session.
6578 * "Significant" is arbitrarily defined as half the window size.
6580 if (newwin / 2 >= c->v.v2.locwindow) {
6581 struct Packet *pktout;
6585 * In order to keep track of how much window the client
6586 * actually has available, we'd like it to acknowledge each
6587 * WINDOW_ADJUST. We can't do that directly, so we accompany
6588 * it with a CHANNEL_REQUEST that has to be acknowledged.
6590 * This is only necessary if we're opening the window wide.
6591 * If we're not, then throughput is being constrained by
6592 * something other than the maximum window size anyway.
6594 * We also only send this if the main channel has finished its
6595 * initial CHANNEL_REQUESTs and installed the default
6596 * CHANNEL_FAILURE handler, so as not to risk giving it
6597 * unexpected CHANNEL_FAILUREs.
6599 if (newwin == c->v.v2.locmaxwin &&
6600 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6601 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6602 ssh2_pkt_adduint32(pktout, c->remoteid);
6603 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6604 ssh2_pkt_addbool(pktout, TRUE);
6605 ssh2_pkt_send(ssh, pktout);
6608 * CHANNEL_FAILURE doesn't come with any indication of
6609 * what message caused it, so we have to keep track of the
6610 * outstanding CHANNEL_REQUESTs ourselves.
6612 wa = snew(struct winadj);
6613 wa->size = newwin - c->v.v2.locwindow;
6615 if (!c->v.v2.winadj_head)
6616 c->v.v2.winadj_head = wa;
6618 c->v.v2.winadj_tail->next = wa;
6619 c->v.v2.winadj_tail = wa;
6620 if (c->v.v2.throttle_state != UNTHROTTLED)
6621 c->v.v2.throttle_state = UNTHROTTLING;
6623 /* Pretend the WINDOW_ADJUST was acked immediately. */
6624 c->v.v2.remlocwin = newwin;
6625 c->v.v2.throttle_state = THROTTLED;
6627 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6628 ssh2_pkt_adduint32(pktout, c->remoteid);
6629 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6630 ssh2_pkt_send(ssh, pktout);
6631 c->v.v2.locwindow = newwin;
6636 * Find the channel associated with a message. If there's no channel,
6637 * or it's not properly open, make a noise about it and return NULL.
6639 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6641 unsigned localid = ssh_pkt_getuint32(pktin);
6642 struct ssh_channel *c;
6644 c = find234(ssh->channels, &localid, ssh_channelfind);
6646 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6647 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6648 char *buf = dupprintf("Received %s for %s channel %u",
6649 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6651 c ? "half-open" : "nonexistent", localid);
6652 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6659 static int ssh2_handle_winadj_response(struct ssh_channel *c)
6661 struct winadj *wa = c->v.v2.winadj_head;
6664 c->v.v2.winadj_head = wa->next;
6665 c->v.v2.remlocwin += wa->size;
6668 * winadj messages are only sent when the window is fully open, so
6669 * if we get an ack of one, we know any pending unthrottle is
6672 if (c->v.v2.throttle_state == UNTHROTTLING)
6673 c->v.v2.throttle_state = UNTHROTTLED;
6675 * We may now initiate channel-closing procedures, if that winadj
6676 * was the last thing outstanding before we send CHANNEL_CLOSE.
6678 ssh2_channel_check_close(c);
6682 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6685 * This should never get called. All channel requests are either
6686 * sent with want_reply false, are sent before this handler gets
6687 * installed, or are "winadj@putty" requests, which servers should
6688 * never respond to with success.
6690 * However, at least one server ("boks_sshd") is known to return
6691 * SUCCESS for channel requests it's never heard of, such as
6692 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6693 * for the sake of a quiet life, we handle it just the same as the
6696 struct ssh_channel *c;
6698 c = ssh2_channel_msg(ssh, pktin);
6701 if (!ssh2_handle_winadj_response(c))
6702 ssh_disconnect(ssh, NULL,
6703 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6704 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6707 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6710 * The only time this should get called is for "winadj@putty"
6711 * messages sent above. All other channel requests are either
6712 * sent with want_reply false or are sent before this handler gets
6715 struct ssh_channel *c;
6717 c = ssh2_channel_msg(ssh, pktin);
6720 if (!ssh2_handle_winadj_response(c))
6721 ssh_disconnect(ssh, NULL,
6722 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6723 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6726 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6728 struct ssh_channel *c;
6729 c = ssh2_channel_msg(ssh, pktin);
6732 if (!(c->closes & CLOSES_SENT_EOF)) {
6733 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6734 ssh2_try_send_and_unthrottle(ssh, c);
6738 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6742 struct ssh_channel *c;
6743 c = ssh2_channel_msg(ssh, pktin);
6746 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6747 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6748 return; /* extended but not stderr */
6749 ssh_pkt_getstring(pktin, &data, &length);
6752 c->v.v2.locwindow -= length;
6753 c->v.v2.remlocwin -= length;
6755 case CHAN_MAINSESSION:
6757 from_backend(ssh->frontend, pktin->type ==
6758 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6762 bufsize = x11_send(c->u.x11.s, data, length);
6765 bufsize = pfd_send(c->u.pfd.s, data, length);
6768 while (length > 0) {
6769 if (c->u.a.lensofar < 4) {
6770 unsigned int l = min(4 - c->u.a.lensofar,
6772 memcpy(c->u.a.msglen + c->u.a.lensofar,
6776 c->u.a.lensofar += l;
6778 if (c->u.a.lensofar == 4) {
6780 4 + GET_32BIT(c->u.a.msglen);
6781 c->u.a.message = snewn(c->u.a.totallen,
6783 memcpy(c->u.a.message, c->u.a.msglen, 4);
6785 if (c->u.a.lensofar >= 4 && length > 0) {
6787 min(c->u.a.totallen - c->u.a.lensofar,
6789 memcpy(c->u.a.message + c->u.a.lensofar,
6793 c->u.a.lensofar += l;
6795 if (c->u.a.lensofar == c->u.a.totallen) {
6798 if (agent_query(c->u.a.message,
6801 ssh_agentf_callback, c))
6802 ssh_agentf_callback(c, reply, replylen);
6803 sfree(c->u.a.message);
6804 c->u.a.message = NULL;
6805 c->u.a.lensofar = 0;
6812 * If it looks like the remote end hit the end of its window,
6813 * and we didn't want it to do that, think about using a
6816 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6817 c->v.v2.locmaxwin < 0x40000000)
6818 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6820 * If we are not buffering too much data,
6821 * enlarge the window again at the remote side.
6822 * If we are buffering too much, we may still
6823 * need to adjust the window if the server's
6826 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6827 c->v.v2.locmaxwin - bufsize : 0);
6829 * If we're either buffering way too much data, or if we're
6830 * buffering anything at all and we're in "simple" mode,
6831 * throttle the whole channel.
6833 if ((bufsize > c->v.v2.locmaxwin ||
6834 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6835 !c->throttling_conn) {
6836 c->throttling_conn = 1;
6837 ssh_throttle_conn(ssh, +1);
6842 static void ssh_channel_destroy(struct ssh_channel *c)
6847 case CHAN_MAINSESSION:
6848 ssh->mainchan = NULL;
6849 update_specials_menu(ssh->frontend);
6852 if (c->u.x11.s != NULL)
6853 x11_close(c->u.x11.s);
6854 logevent("Forwarded X11 connection terminated");
6857 sfree(c->u.a.message);
6860 if (c->u.pfd.s != NULL)
6861 pfd_close(c->u.pfd.s);
6862 logevent("Forwarded port closed");
6866 del234(ssh->channels, c);
6867 if (ssh->version == 2)
6868 bufchain_clear(&c->v.v2.outbuffer);
6872 * See if that was the last channel left open.
6873 * (This is only our termination condition if we're
6874 * not running in -N mode.)
6876 if (ssh->version == 2 &&
6877 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6878 count234(ssh->channels) == 0) {
6880 * We used to send SSH_MSG_DISCONNECT here,
6881 * because I'd believed that _every_ conforming
6882 * SSH-2 connection had to end with a disconnect
6883 * being sent by at least one side; apparently
6884 * I was wrong and it's perfectly OK to
6885 * unceremoniously slam the connection shut
6886 * when you're done, and indeed OpenSSH feels
6887 * this is more polite than sending a
6888 * DISCONNECT. So now we don't.
6890 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6894 static void ssh2_channel_check_close(struct ssh_channel *c)
6897 struct Packet *pktout;
6899 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6900 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
6902 * We have both sent and received EOF, and we have no
6903 * outstanding winadj channel requests, which means the
6904 * channel is in final wind-up. But we haven't sent CLOSE, so
6907 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6908 ssh2_pkt_adduint32(pktout, c->remoteid);
6909 ssh2_pkt_send(ssh, pktout);
6910 c->closes |= CLOSES_SENT_CLOSE;
6913 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6915 * We have both sent and received CLOSE, which means we're
6916 * completely done with the channel.
6918 ssh_channel_destroy(c);
6922 static void ssh2_channel_got_eof(struct ssh_channel *c)
6924 if (c->closes & CLOSES_RCVD_EOF)
6925 return; /* already seen EOF */
6926 c->closes |= CLOSES_RCVD_EOF;
6928 if (c->type == CHAN_X11) {
6929 x11_send_eof(c->u.x11.s);
6930 } else if (c->type == CHAN_AGENT) {
6931 /* Manufacture an outgoing EOF in response to the incoming one. */
6932 sshfwd_write_eof(c);
6933 } else if (c->type == CHAN_SOCKDATA) {
6934 pfd_send_eof(c->u.pfd.s);
6935 } else if (c->type == CHAN_MAINSESSION) {
6938 if (!ssh->sent_console_eof &&
6939 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6941 * Either from_backend_eof told us that the front end
6942 * wants us to close the outgoing side of the connection
6943 * as soon as we see EOF from the far end, or else we've
6944 * unilaterally decided to do that because we've allocated
6945 * a remote pty and hence EOF isn't a particularly
6946 * meaningful concept.
6948 sshfwd_write_eof(c);
6950 ssh->sent_console_eof = TRUE;
6953 ssh2_channel_check_close(c);
6956 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6958 struct ssh_channel *c;
6960 c = ssh2_channel_msg(ssh, pktin);
6963 ssh2_channel_got_eof(c);
6966 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6968 struct ssh_channel *c;
6970 c = ssh2_channel_msg(ssh, pktin);
6975 * When we receive CLOSE on a channel, we assume it comes with an
6976 * implied EOF if we haven't seen EOF yet.
6978 ssh2_channel_got_eof(c);
6981 * And we also send an outgoing EOF, if we haven't already, on the
6982 * assumption that CLOSE is a pretty forceful announcement that
6983 * the remote side is doing away with the entire channel. (If it
6984 * had wanted to send us EOF and continue receiving data from us,
6985 * it would have just sent CHANNEL_EOF.)
6987 if (!(c->closes & CLOSES_SENT_EOF)) {
6989 * Make sure we don't read any more from whatever our local
6990 * data source is for this channel.
6993 case CHAN_MAINSESSION:
6994 ssh->send_ok = 0; /* stop trying to read from stdin */
6997 x11_override_throttle(c->u.x11.s, 1);
7000 pfd_override_throttle(c->u.pfd.s, 1);
7005 * Send outgoing EOF.
7007 sshfwd_write_eof(ssh->mainchan);
7011 * Now process the actual close.
7013 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7014 c->closes |= CLOSES_RCVD_CLOSE;
7015 ssh2_channel_check_close(c);
7019 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7021 struct ssh_channel *c;
7023 c = ssh2_channel_msg(ssh, pktin);
7026 if (c->type != CHAN_SOCKDATA_DORMANT)
7027 return; /* dunno why they're confirming this */
7028 c->remoteid = ssh_pkt_getuint32(pktin);
7029 c->halfopen = FALSE;
7030 c->type = CHAN_SOCKDATA;
7031 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7032 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7034 pfd_confirm(c->u.pfd.s);
7036 ssh_channel_try_eof(c);
7039 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7041 static const char *const reasons[] = {
7042 "<unknown reason code>",
7043 "Administratively prohibited",
7045 "Unknown channel type",
7046 "Resource shortage",
7048 unsigned reason_code;
7049 char *reason_string;
7051 struct ssh_channel *c;
7052 c = ssh2_channel_msg(ssh, pktin);
7055 if (c->type != CHAN_SOCKDATA_DORMANT)
7056 return; /* dunno why they're failing this */
7058 reason_code = ssh_pkt_getuint32(pktin);
7059 if (reason_code >= lenof(reasons))
7060 reason_code = 0; /* ensure reasons[reason_code] in range */
7061 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7062 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7063 reasons[reason_code], reason_length, reason_string);
7065 pfd_close(c->u.pfd.s);
7067 del234(ssh->channels, c);
7071 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7074 int typelen, want_reply;
7075 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7076 struct ssh_channel *c;
7077 struct Packet *pktout;
7079 c = ssh2_channel_msg(ssh, pktin);
7082 ssh_pkt_getstring(pktin, &type, &typelen);
7083 want_reply = ssh2_pkt_getbool(pktin);
7086 * Having got the channel number, we now look at
7087 * the request type string to see if it's something
7090 if (c == ssh->mainchan) {
7092 * We recognise "exit-status" and "exit-signal" on
7093 * the primary channel.
7095 if (typelen == 11 &&
7096 !memcmp(type, "exit-status", 11)) {
7098 ssh->exitcode = ssh_pkt_getuint32(pktin);
7099 logeventf(ssh, "Server sent command exit status %d",
7101 reply = SSH2_MSG_CHANNEL_SUCCESS;
7103 } else if (typelen == 11 &&
7104 !memcmp(type, "exit-signal", 11)) {
7106 int is_plausible = TRUE, is_int = FALSE;
7107 char *fmt_sig = "", *fmt_msg = "";
7109 int msglen = 0, core = FALSE;
7110 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7111 * provide an `int' for the signal, despite its
7112 * having been a `string' in the drafts of RFC 4254 since at
7113 * least 2001. (Fixed in session.c 1.147.) Try to
7114 * infer which we can safely parse it as. */
7116 unsigned char *p = pktin->body +
7118 long len = pktin->length - pktin->savedpos;
7119 unsigned long num = GET_32BIT(p); /* what is it? */
7120 /* If it's 0, it hardly matters; assume string */
7124 int maybe_int = FALSE, maybe_str = FALSE;
7125 #define CHECK_HYPOTHESIS(offset, result) \
7128 if (q >= 0 && q+4 <= len) { \
7129 q = q + 4 + GET_32BIT(p+q); \
7130 if (q >= 0 && q+4 <= len && \
7131 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7135 CHECK_HYPOTHESIS(4+1, maybe_int);
7136 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7137 #undef CHECK_HYPOTHESIS
7138 if (maybe_int && !maybe_str)
7140 else if (!maybe_int && maybe_str)
7143 /* Crikey. Either or neither. Panic. */
7144 is_plausible = FALSE;
7147 ssh->exitcode = 128; /* means `unknown signal' */
7150 /* Old non-standard OpenSSH. */
7151 int signum = ssh_pkt_getuint32(pktin);
7152 fmt_sig = dupprintf(" %d", signum);
7153 ssh->exitcode = 128 + signum;
7155 /* As per RFC 4254. */
7158 ssh_pkt_getstring(pktin, &sig, &siglen);
7159 /* Signal name isn't supposed to be blank, but
7160 * let's cope gracefully if it is. */
7162 fmt_sig = dupprintf(" \"%.*s\"",
7167 * Really hideous method of translating the
7168 * signal description back into a locally
7169 * meaningful number.
7174 #define TRANSLATE_SIGNAL(s) \
7175 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7176 ssh->exitcode = 128 + SIG ## s
7178 TRANSLATE_SIGNAL(ABRT);
7181 TRANSLATE_SIGNAL(ALRM);
7184 TRANSLATE_SIGNAL(FPE);
7187 TRANSLATE_SIGNAL(HUP);
7190 TRANSLATE_SIGNAL(ILL);
7193 TRANSLATE_SIGNAL(INT);
7196 TRANSLATE_SIGNAL(KILL);
7199 TRANSLATE_SIGNAL(PIPE);
7202 TRANSLATE_SIGNAL(QUIT);
7205 TRANSLATE_SIGNAL(SEGV);
7208 TRANSLATE_SIGNAL(TERM);
7211 TRANSLATE_SIGNAL(USR1);
7214 TRANSLATE_SIGNAL(USR2);
7216 #undef TRANSLATE_SIGNAL
7218 ssh->exitcode = 128;
7220 core = ssh2_pkt_getbool(pktin);
7221 ssh_pkt_getstring(pktin, &msg, &msglen);
7223 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7225 /* ignore lang tag */
7226 } /* else don't attempt to parse */
7227 logeventf(ssh, "Server exited on signal%s%s%s",
7228 fmt_sig, core ? " (core dumped)" : "",
7230 if (*fmt_sig) sfree(fmt_sig);
7231 if (*fmt_msg) sfree(fmt_msg);
7232 reply = SSH2_MSG_CHANNEL_SUCCESS;
7237 * This is a channel request we don't know
7238 * about, so we now either ignore the request
7239 * or respond with CHANNEL_FAILURE, depending
7242 reply = SSH2_MSG_CHANNEL_FAILURE;
7245 pktout = ssh2_pkt_init(reply);
7246 ssh2_pkt_adduint32(pktout, c->remoteid);
7247 ssh2_pkt_send(ssh, pktout);
7251 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7254 int typelen, want_reply;
7255 struct Packet *pktout;
7257 ssh_pkt_getstring(pktin, &type, &typelen);
7258 want_reply = ssh2_pkt_getbool(pktin);
7261 * We currently don't support any global requests
7262 * at all, so we either ignore the request or
7263 * respond with REQUEST_FAILURE, depending on
7267 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7268 ssh2_pkt_send(ssh, pktout);
7272 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7280 struct ssh_channel *c;
7281 unsigned remid, winsize, pktsize;
7282 struct Packet *pktout;
7284 ssh_pkt_getstring(pktin, &type, &typelen);
7285 c = snew(struct ssh_channel);
7288 remid = ssh_pkt_getuint32(pktin);
7289 winsize = ssh_pkt_getuint32(pktin);
7290 pktsize = ssh_pkt_getuint32(pktin);
7292 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7296 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7297 addrstr = snewn(peeraddrlen+1, char);
7298 memcpy(addrstr, peeraddr, peeraddrlen);
7299 addrstr[peeraddrlen] = '\0';
7300 peerport = ssh_pkt_getuint32(pktin);
7302 logeventf(ssh, "Received X11 connect request from %s:%d",
7305 if (!ssh->X11_fwd_enabled)
7306 error = "X11 forwarding is not enabled";
7307 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7308 addrstr, peerport, ssh->conf)) != NULL) {
7309 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7310 error = "Unable to open an X11 connection";
7312 logevent("Opening X11 forward connection succeeded");
7317 } else if (typelen == 15 &&
7318 !memcmp(type, "forwarded-tcpip", 15)) {
7319 struct ssh_rportfwd pf, *realpf;
7322 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7323 pf.sport = ssh_pkt_getuint32(pktin);
7324 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7325 peerport = ssh_pkt_getuint32(pktin);
7326 realpf = find234(ssh->rportfwds, &pf, NULL);
7327 logeventf(ssh, "Received remote port %d open request "
7328 "from %s:%d", pf.sport, peeraddr, peerport);
7329 if (realpf == NULL) {
7330 error = "Remote port is not recognised";
7332 const char *e = pfd_newconnect(&c->u.pfd.s,
7336 realpf->pfrec->addressfamily);
7337 logeventf(ssh, "Attempting to forward remote port to "
7338 "%s:%d", realpf->dhost, realpf->dport);
7340 logeventf(ssh, "Port open failed: %s", e);
7341 error = "Port open failed";
7343 logevent("Forwarded port opened successfully");
7344 c->type = CHAN_SOCKDATA;
7347 } else if (typelen == 22 &&
7348 !memcmp(type, "auth-agent@openssh.com", 22)) {
7349 if (!ssh->agentfwd_enabled)
7350 error = "Agent forwarding is not enabled";
7352 c->type = CHAN_AGENT; /* identify channel type */
7353 c->u.a.lensofar = 0;
7356 error = "Unsupported channel type requested";
7359 c->remoteid = remid;
7360 c->halfopen = FALSE;
7362 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7363 ssh2_pkt_adduint32(pktout, c->remoteid);
7364 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7365 ssh2_pkt_addstring(pktout, error);
7366 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7367 ssh2_pkt_send(ssh, pktout);
7368 logeventf(ssh, "Rejected channel open: %s", error);
7371 ssh2_channel_init(c);
7372 c->v.v2.remwindow = winsize;
7373 c->v.v2.remmaxpkt = pktsize;
7374 add234(ssh->channels, c);
7375 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7376 ssh2_pkt_adduint32(pktout, c->remoteid);
7377 ssh2_pkt_adduint32(pktout, c->localid);
7378 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7379 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7380 ssh2_pkt_send(ssh, pktout);
7385 * Buffer banner messages for later display at some convenient point,
7386 * if we're going to display them.
7388 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7390 /* Arbitrary limit to prevent unbounded inflation of buffer */
7391 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7392 bufchain_size(&ssh->banner) <= 131072) {
7393 char *banner = NULL;
7395 ssh_pkt_getstring(pktin, &banner, &size);
7397 bufchain_add(&ssh->banner, banner, size);
7401 /* Helper function to deal with sending tty modes for "pty-req" */
7402 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7404 struct Packet *pktout = (struct Packet *)data;
7406 unsigned int arg = 0;
7407 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7408 if (i == lenof(ssh_ttymodes)) return;
7409 switch (ssh_ttymodes[i].type) {
7411 arg = ssh_tty_parse_specchar(val);
7414 arg = ssh_tty_parse_boolean(val);
7417 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7418 ssh2_pkt_adduint32(pktout, arg);
7422 * Handle the SSH-2 userauth and connection layers.
7424 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7425 struct Packet *pktin)
7427 struct do_ssh2_authconn_state {
7430 AUTH_TYPE_PUBLICKEY,
7431 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7432 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7434 AUTH_TYPE_GSSAPI, /* always QUIET */
7435 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7436 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7438 int done_service_req;
7439 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7440 int tried_pubkey_config, done_agent;
7445 int kbd_inter_refused;
7446 int we_are_in, userauth_success;
7447 prompts_t *cur_prompt;
7452 void *publickey_blob;
7453 int publickey_bloblen;
7454 int publickey_encrypted;
7455 char *publickey_algorithm;
7456 char *publickey_comment;
7457 unsigned char agent_request[5], *agent_response, *agentp;
7458 int agent_responselen;
7459 unsigned char *pkblob_in_agent;
7461 char *pkblob, *alg, *commentp;
7462 int pklen, alglen, commentlen;
7463 int siglen, retlen, len;
7464 char *q, *agentreq, *ret;
7466 int num_env, env_left, env_ok;
7467 struct Packet *pktout;
7470 struct ssh_gss_library *gsslib;
7471 Ssh_gss_ctx gss_ctx;
7472 Ssh_gss_buf gss_buf;
7473 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7474 Ssh_gss_name gss_srv_name;
7475 Ssh_gss_stat gss_stat;
7478 crState(do_ssh2_authconn_state);
7480 crBegin(ssh->do_ssh2_authconn_crstate);
7482 s->done_service_req = FALSE;
7483 s->we_are_in = s->userauth_success = FALSE;
7485 s->tried_gssapi = FALSE;
7488 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7490 * Request userauth protocol, and await a response to it.
7492 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7493 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7494 ssh2_pkt_send(ssh, s->pktout);
7495 crWaitUntilV(pktin);
7496 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7497 s->done_service_req = TRUE;
7499 if (!s->done_service_req) {
7501 * Request connection protocol directly, without authentication.
7503 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7504 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7505 ssh2_pkt_send(ssh, s->pktout);
7506 crWaitUntilV(pktin);
7507 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7508 s->we_are_in = TRUE; /* no auth required */
7510 bombout(("Server refused service request"));
7515 /* Arrange to be able to deal with any BANNERs that come in.
7516 * (We do this now as packets may come in during the next bit.) */
7517 bufchain_init(&ssh->banner);
7518 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7519 ssh2_msg_userauth_banner;
7522 * Misc one-time setup for authentication.
7524 s->publickey_blob = NULL;
7525 if (!s->we_are_in) {
7528 * Load the public half of any configured public key file
7531 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7532 if (!filename_is_null(*s->keyfile)) {
7534 logeventf(ssh, "Reading private key file \"%.150s\"",
7535 filename_to_str(s->keyfile));
7536 keytype = key_type(s->keyfile);
7537 if (keytype == SSH_KEYTYPE_SSH2) {
7540 ssh2_userkey_loadpub(s->keyfile,
7541 &s->publickey_algorithm,
7542 &s->publickey_bloblen,
7543 &s->publickey_comment, &error);
7544 if (s->publickey_blob) {
7545 s->publickey_encrypted =
7546 ssh2_userkey_encrypted(s->keyfile, NULL);
7549 logeventf(ssh, "Unable to load private key (%s)",
7551 msgbuf = dupprintf("Unable to load private key file "
7552 "\"%.150s\" (%s)\r\n",
7553 filename_to_str(s->keyfile),
7555 c_write_str(ssh, msgbuf);
7560 logeventf(ssh, "Unable to use this key file (%s)",
7561 key_type_to_str(keytype));
7562 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7564 filename_to_str(s->keyfile),
7565 key_type_to_str(keytype));
7566 c_write_str(ssh, msgbuf);
7568 s->publickey_blob = NULL;
7573 * Find out about any keys Pageant has (but if there's a
7574 * public key configured, filter out all others).
7577 s->agent_response = NULL;
7578 s->pkblob_in_agent = NULL;
7579 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7583 logevent("Pageant is running. Requesting keys.");
7585 /* Request the keys held by the agent. */
7586 PUT_32BIT(s->agent_request, 1);
7587 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7588 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7589 ssh_agent_callback, ssh)) {
7593 bombout(("Unexpected data from server while"
7594 " waiting for agent response"));
7597 } while (pktin || inlen > 0);
7598 r = ssh->agent_response;
7599 s->agent_responselen = ssh->agent_response_len;
7601 s->agent_response = (unsigned char *) r;
7602 if (s->agent_response && s->agent_responselen >= 5 &&
7603 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7606 p = s->agent_response + 5;
7607 s->nkeys = GET_32BIT(p);
7609 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7610 if (s->publickey_blob) {
7611 /* See if configured key is in agent. */
7612 for (keyi = 0; keyi < s->nkeys; keyi++) {
7613 s->pklen = GET_32BIT(p);
7614 if (s->pklen == s->publickey_bloblen &&
7615 !memcmp(p+4, s->publickey_blob,
7616 s->publickey_bloblen)) {
7617 logeventf(ssh, "Pageant key #%d matches "
7618 "configured key file", keyi);
7620 s->pkblob_in_agent = p;
7624 p += GET_32BIT(p) + 4; /* comment */
7626 if (!s->pkblob_in_agent) {
7627 logevent("Configured key file not in Pageant");
7632 logevent("Failed to get reply from Pageant");
7639 * We repeat this whole loop, including the username prompt,
7640 * until we manage a successful authentication. If the user
7641 * types the wrong _password_, they can be sent back to the
7642 * beginning to try another username, if this is configured on.
7643 * (If they specify a username in the config, they are never
7644 * asked, even if they do give a wrong password.)
7646 * I think this best serves the needs of
7648 * - the people who have no configuration, no keys, and just
7649 * want to try repeated (username,password) pairs until they
7650 * type both correctly
7652 * - people who have keys and configuration but occasionally
7653 * need to fall back to passwords
7655 * - people with a key held in Pageant, who might not have
7656 * logged in to a particular machine before; so they want to
7657 * type a username, and then _either_ their key will be
7658 * accepted, _or_ they will type a password. If they mistype
7659 * the username they will want to be able to get back and
7662 s->got_username = FALSE;
7663 while (!s->we_are_in) {
7667 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
7669 * We got a username last time round this loop, and
7670 * with change_username turned off we don't try to get
7673 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
7674 int ret; /* need not be kept over crReturn */
7675 s->cur_prompt = new_prompts(ssh->frontend);
7676 s->cur_prompt->to_server = TRUE;
7677 s->cur_prompt->name = dupstr("SSH login name");
7678 /* 512 is an arbitrary limit :-( */
7679 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
7680 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7683 crWaitUntilV(!pktin);
7684 ret = get_userpass_input(s->cur_prompt, in, inlen);
7689 * get_userpass_input() failed to get a username.
7692 free_prompts(s->cur_prompt);
7693 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7696 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
7697 free_prompts(s->cur_prompt);
7700 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7701 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
7702 c_write_str(ssh, stuff);
7706 s->got_username = TRUE;
7709 * Send an authentication request using method "none": (a)
7710 * just in case it succeeds, and (b) so that we know what
7711 * authentication methods we can usefully try next.
7713 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7715 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7716 ssh2_pkt_addstring(s->pktout, ssh->username);
7717 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7718 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7719 ssh2_pkt_send(ssh, s->pktout);
7720 s->type = AUTH_TYPE_NONE;
7722 s->we_are_in = FALSE;
7724 s->tried_pubkey_config = FALSE;
7725 s->kbd_inter_refused = FALSE;
7727 /* Reset agent request state. */
7728 s->done_agent = FALSE;
7729 if (s->agent_response) {
7730 if (s->pkblob_in_agent) {
7731 s->agentp = s->pkblob_in_agent;
7733 s->agentp = s->agent_response + 5 + 4;
7739 char *methods = NULL;
7743 * Wait for the result of the last authentication request.
7746 crWaitUntilV(pktin);
7748 * Now is a convenient point to spew any banner material
7749 * that we've accumulated. (This should ensure that when
7750 * we exit the auth loop, we haven't any left to deal
7754 int size = bufchain_size(&ssh->banner);
7756 * Don't show the banner if we're operating in
7757 * non-verbose non-interactive mode. (It's probably
7758 * a script, which means nobody will read the
7759 * banner _anyway_, and moreover the printing of
7760 * the banner will screw up processing on the
7761 * output of (say) plink.)
7763 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7764 char *banner = snewn(size, char);
7765 bufchain_fetch(&ssh->banner, banner, size);
7766 c_write_untrusted(ssh, banner, size);
7769 bufchain_clear(&ssh->banner);
7771 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7772 logevent("Access granted");
7773 s->we_are_in = s->userauth_success = TRUE;
7777 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7778 bombout(("Strange packet received during authentication: "
7779 "type %d", pktin->type));
7786 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7787 * we can look at the string in it and know what we can
7788 * helpfully try next.
7790 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7791 ssh_pkt_getstring(pktin, &methods, &methlen);
7792 if (!ssh2_pkt_getbool(pktin)) {
7794 * We have received an unequivocal Access
7795 * Denied. This can translate to a variety of
7796 * messages, or no message at all.
7798 * For forms of authentication which are attempted
7799 * implicitly, by which I mean without printing
7800 * anything in the window indicating that we're
7801 * trying them, we should never print 'Access
7804 * If we do print a message saying that we're
7805 * attempting some kind of authentication, it's OK
7806 * to print a followup message saying it failed -
7807 * but the message may sometimes be more specific
7808 * than simply 'Access denied'.
7810 * Additionally, if we'd just tried password
7811 * authentication, we should break out of this
7812 * whole loop so as to go back to the username
7813 * prompt (iff we're configured to allow
7814 * username change attempts).
7816 if (s->type == AUTH_TYPE_NONE) {
7818 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7819 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7820 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7821 c_write_str(ssh, "Server refused our key\r\n");
7822 logevent("Server refused our key");
7823 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7824 /* This _shouldn't_ happen except by a
7825 * protocol bug causing client and server to
7826 * disagree on what is a correct signature. */
7827 c_write_str(ssh, "Server refused public-key signature"
7828 " despite accepting key!\r\n");
7829 logevent("Server refused public-key signature"
7830 " despite accepting key!");
7831 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7832 /* quiet, so no c_write */
7833 logevent("Server refused keyboard-interactive authentication");
7834 } else if (s->type==AUTH_TYPE_GSSAPI) {
7835 /* always quiet, so no c_write */
7836 /* also, the code down in the GSSAPI block has
7837 * already logged this in the Event Log */
7838 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7839 logevent("Keyboard-interactive authentication failed");
7840 c_write_str(ssh, "Access denied\r\n");
7842 assert(s->type == AUTH_TYPE_PASSWORD);
7843 logevent("Password authentication failed");
7844 c_write_str(ssh, "Access denied\r\n");
7846 if (conf_get_int(ssh->conf, CONF_change_username)) {
7847 /* XXX perhaps we should allow
7848 * keyboard-interactive to do this too? */
7849 s->we_are_in = FALSE;
7854 c_write_str(ssh, "Further authentication required\r\n");
7855 logevent("Further authentication required");
7859 in_commasep_string("publickey", methods, methlen);
7861 in_commasep_string("password", methods, methlen);
7862 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
7863 in_commasep_string("keyboard-interactive", methods, methlen);
7866 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7867 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
7868 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7869 ssh->gsslibs->nlibraries > 0;
7873 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7875 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7878 * Attempt public-key authentication using a key from Pageant.
7881 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7883 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7885 /* Unpack key from agent response */
7886 s->pklen = GET_32BIT(s->agentp);
7888 s->pkblob = (char *)s->agentp;
7889 s->agentp += s->pklen;
7890 s->alglen = GET_32BIT(s->pkblob);
7891 s->alg = s->pkblob + 4;
7892 s->commentlen = GET_32BIT(s->agentp);
7894 s->commentp = (char *)s->agentp;
7895 s->agentp += s->commentlen;
7896 /* s->agentp now points at next key, if any */
7898 /* See if server will accept it */
7899 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7900 ssh2_pkt_addstring(s->pktout, ssh->username);
7901 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7902 /* service requested */
7903 ssh2_pkt_addstring(s->pktout, "publickey");
7905 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7906 ssh2_pkt_addstring_start(s->pktout);
7907 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7908 ssh2_pkt_addstring_start(s->pktout);
7909 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7910 ssh2_pkt_send(ssh, s->pktout);
7911 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7913 crWaitUntilV(pktin);
7914 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7916 /* Offer of key refused. */
7923 if (flags & FLAG_VERBOSE) {
7924 c_write_str(ssh, "Authenticating with "
7926 c_write(ssh, s->commentp, s->commentlen);
7927 c_write_str(ssh, "\" from agent\r\n");
7931 * Server is willing to accept the key.
7932 * Construct a SIGN_REQUEST.
7934 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7935 ssh2_pkt_addstring(s->pktout, ssh->username);
7936 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7937 /* service requested */
7938 ssh2_pkt_addstring(s->pktout, "publickey");
7940 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7941 ssh2_pkt_addstring_start(s->pktout);
7942 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7943 ssh2_pkt_addstring_start(s->pktout);
7944 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7946 /* Ask agent for signature. */
7947 s->siglen = s->pktout->length - 5 + 4 +
7948 ssh->v2_session_id_len;
7949 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7951 s->len = 1; /* message type */
7952 s->len += 4 + s->pklen; /* key blob */
7953 s->len += 4 + s->siglen; /* data to sign */
7954 s->len += 4; /* flags */
7955 s->agentreq = snewn(4 + s->len, char);
7956 PUT_32BIT(s->agentreq, s->len);
7957 s->q = s->agentreq + 4;
7958 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7959 PUT_32BIT(s->q, s->pklen);
7961 memcpy(s->q, s->pkblob, s->pklen);
7963 PUT_32BIT(s->q, s->siglen);
7965 /* Now the data to be signed... */
7966 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7967 PUT_32BIT(s->q, ssh->v2_session_id_len);
7970 memcpy(s->q, ssh->v2_session_id,
7971 ssh->v2_session_id_len);
7972 s->q += ssh->v2_session_id_len;
7973 memcpy(s->q, s->pktout->data + 5,
7974 s->pktout->length - 5);
7975 s->q += s->pktout->length - 5;
7976 /* And finally the (zero) flags word. */
7978 if (!agent_query(s->agentreq, s->len + 4,
7980 ssh_agent_callback, ssh)) {
7984 bombout(("Unexpected data from server"
7985 " while waiting for agent"
7989 } while (pktin || inlen > 0);
7990 vret = ssh->agent_response;
7991 s->retlen = ssh->agent_response_len;
7996 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7997 logevent("Sending Pageant's response");
7998 ssh2_add_sigblob(ssh, s->pktout,
7999 s->pkblob, s->pklen,
8001 GET_32BIT(s->ret + 5));
8002 ssh2_pkt_send(ssh, s->pktout);
8003 s->type = AUTH_TYPE_PUBLICKEY;
8005 /* FIXME: less drastic response */
8006 bombout(("Pageant failed to answer challenge"));
8012 /* Do we have any keys left to try? */
8013 if (s->pkblob_in_agent) {
8014 s->done_agent = TRUE;
8015 s->tried_pubkey_config = TRUE;
8018 if (s->keyi >= s->nkeys)
8019 s->done_agent = TRUE;
8022 } else if (s->can_pubkey && s->publickey_blob &&
8023 !s->tried_pubkey_config) {
8025 struct ssh2_userkey *key; /* not live over crReturn */
8026 char *passphrase; /* not live over crReturn */
8028 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8030 s->tried_pubkey_config = TRUE;
8033 * Try the public key supplied in the configuration.
8035 * First, offer the public blob to see if the server is
8036 * willing to accept it.
8038 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8039 ssh2_pkt_addstring(s->pktout, ssh->username);
8040 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8041 /* service requested */
8042 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8043 ssh2_pkt_addbool(s->pktout, FALSE);
8044 /* no signature included */
8045 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8046 ssh2_pkt_addstring_start(s->pktout);
8047 ssh2_pkt_addstring_data(s->pktout,
8048 (char *)s->publickey_blob,
8049 s->publickey_bloblen);
8050 ssh2_pkt_send(ssh, s->pktout);
8051 logevent("Offered public key");
8053 crWaitUntilV(pktin);
8054 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8055 /* Key refused. Give up. */
8056 s->gotit = TRUE; /* reconsider message next loop */
8057 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8058 continue; /* process this new message */
8060 logevent("Offer of public key accepted");
8063 * Actually attempt a serious authentication using
8066 if (flags & FLAG_VERBOSE) {
8067 c_write_str(ssh, "Authenticating with public key \"");
8068 c_write_str(ssh, s->publickey_comment);
8069 c_write_str(ssh, "\"\r\n");
8073 const char *error; /* not live over crReturn */
8074 if (s->publickey_encrypted) {
8076 * Get a passphrase from the user.
8078 int ret; /* need not be kept over crReturn */
8079 s->cur_prompt = new_prompts(ssh->frontend);
8080 s->cur_prompt->to_server = FALSE;
8081 s->cur_prompt->name = dupstr("SSH key passphrase");
8082 add_prompt(s->cur_prompt,
8083 dupprintf("Passphrase for key \"%.100s\": ",
8084 s->publickey_comment),
8085 FALSE, SSH_MAX_PASSWORD_LEN);
8086 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8089 crWaitUntilV(!pktin);
8090 ret = get_userpass_input(s->cur_prompt,
8095 /* Failed to get a passphrase. Terminate. */
8096 free_prompts(s->cur_prompt);
8097 ssh_disconnect(ssh, NULL,
8098 "Unable to authenticate",
8099 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8104 dupstr(s->cur_prompt->prompts[0]->result);
8105 free_prompts(s->cur_prompt);
8107 passphrase = NULL; /* no passphrase needed */
8111 * Try decrypting the key.
8113 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8114 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8116 /* burn the evidence */
8117 memset(passphrase, 0, strlen(passphrase));
8120 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8122 (key == SSH2_WRONG_PASSPHRASE)) {
8123 c_write_str(ssh, "Wrong passphrase\r\n");
8125 /* and loop again */
8127 c_write_str(ssh, "Unable to load private key (");
8128 c_write_str(ssh, error);
8129 c_write_str(ssh, ")\r\n");
8131 break; /* try something else */
8137 unsigned char *pkblob, *sigblob, *sigdata;
8138 int pkblob_len, sigblob_len, sigdata_len;
8142 * We have loaded the private key and the server
8143 * has announced that it's willing to accept it.
8144 * Hallelujah. Generate a signature and send it.
8146 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8147 ssh2_pkt_addstring(s->pktout, ssh->username);
8148 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8149 /* service requested */
8150 ssh2_pkt_addstring(s->pktout, "publickey");
8152 ssh2_pkt_addbool(s->pktout, TRUE);
8153 /* signature follows */
8154 ssh2_pkt_addstring(s->pktout, key->alg->name);
8155 pkblob = key->alg->public_blob(key->data,
8157 ssh2_pkt_addstring_start(s->pktout);
8158 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8162 * The data to be signed is:
8166 * followed by everything so far placed in the
8169 sigdata_len = s->pktout->length - 5 + 4 +
8170 ssh->v2_session_id_len;
8171 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8173 sigdata = snewn(sigdata_len, unsigned char);
8175 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8176 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8179 memcpy(sigdata+p, ssh->v2_session_id,
8180 ssh->v2_session_id_len);
8181 p += ssh->v2_session_id_len;
8182 memcpy(sigdata+p, s->pktout->data + 5,
8183 s->pktout->length - 5);
8184 p += s->pktout->length - 5;
8185 assert(p == sigdata_len);
8186 sigblob = key->alg->sign(key->data, (char *)sigdata,
8187 sigdata_len, &sigblob_len);
8188 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8189 sigblob, sigblob_len);
8194 ssh2_pkt_send(ssh, s->pktout);
8195 logevent("Sent public key signature");
8196 s->type = AUTH_TYPE_PUBLICKEY;
8197 key->alg->freekey(key->data);
8201 } else if (s->can_gssapi && !s->tried_gssapi) {
8203 /* GSSAPI Authentication */
8208 s->type = AUTH_TYPE_GSSAPI;
8209 s->tried_gssapi = TRUE;
8211 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8214 * Pick the highest GSS library on the preference
8220 for (i = 0; i < ngsslibs; i++) {
8221 int want_id = conf_get_int_int(ssh->conf,
8222 CONF_ssh_gsslist, i);
8223 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8224 if (ssh->gsslibs->libraries[j].id == want_id) {
8225 s->gsslib = &ssh->gsslibs->libraries[j];
8226 goto got_gsslib; /* double break */
8231 * We always expect to have found something in
8232 * the above loop: we only came here if there
8233 * was at least one viable GSS library, and the
8234 * preference list should always mention
8235 * everything and only change the order.
8240 if (s->gsslib->gsslogmsg)
8241 logevent(s->gsslib->gsslogmsg);
8243 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8244 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8245 ssh2_pkt_addstring(s->pktout, ssh->username);
8246 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8247 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8248 logevent("Attempting GSSAPI authentication");
8250 /* add mechanism info */
8251 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8253 /* number of GSSAPI mechanisms */
8254 ssh2_pkt_adduint32(s->pktout,1);
8256 /* length of OID + 2 */
8257 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8258 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8261 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8263 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8265 ssh2_pkt_send(ssh, s->pktout);
8266 crWaitUntilV(pktin);
8267 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8268 logevent("GSSAPI authentication request refused");
8272 /* check returned packet ... */
8274 ssh_pkt_getstring(pktin, &data, &len);
8275 s->gss_rcvtok.value = data;
8276 s->gss_rcvtok.length = len;
8277 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8278 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8279 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8280 memcmp((char *)s->gss_rcvtok.value + 2,
8281 s->gss_buf.value,s->gss_buf.length) ) {
8282 logevent("GSSAPI authentication - wrong response from server");
8286 /* now start running */
8287 s->gss_stat = s->gsslib->import_name(s->gsslib,
8290 if (s->gss_stat != SSH_GSS_OK) {
8291 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8292 logevent("GSSAPI import name failed - Bad service name");
8294 logevent("GSSAPI import name failed");
8298 /* fetch TGT into GSS engine */
8299 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8301 if (s->gss_stat != SSH_GSS_OK) {
8302 logevent("GSSAPI authentication failed to get credentials");
8303 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8307 /* initial tokens are empty */
8308 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8309 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8311 /* now enter the loop */
8313 s->gss_stat = s->gsslib->init_sec_context
8317 conf_get_int(ssh->conf, CONF_gssapifwd),
8321 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8322 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8323 logevent("GSSAPI authentication initialisation failed");
8325 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8326 &s->gss_buf) == SSH_GSS_OK) {
8327 logevent(s->gss_buf.value);
8328 sfree(s->gss_buf.value);
8333 logevent("GSSAPI authentication initialised");
8335 /* Client and server now exchange tokens until GSSAPI
8336 * no longer says CONTINUE_NEEDED */
8338 if (s->gss_sndtok.length != 0) {
8339 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8340 ssh_pkt_addstring_start(s->pktout);
8341 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8342 ssh2_pkt_send(ssh, s->pktout);
8343 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8346 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8347 crWaitUntilV(pktin);
8348 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8349 logevent("GSSAPI authentication - bad server response");
8350 s->gss_stat = SSH_GSS_FAILURE;
8353 ssh_pkt_getstring(pktin, &data, &len);
8354 s->gss_rcvtok.value = data;
8355 s->gss_rcvtok.length = len;
8357 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8359 if (s->gss_stat != SSH_GSS_OK) {
8360 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8361 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8364 logevent("GSSAPI authentication loop finished OK");
8366 /* Now send the MIC */
8368 s->pktout = ssh2_pkt_init(0);
8369 micoffset = s->pktout->length;
8370 ssh_pkt_addstring_start(s->pktout);
8371 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8372 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8373 ssh_pkt_addstring(s->pktout, ssh->username);
8374 ssh_pkt_addstring(s->pktout, "ssh-connection");
8375 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8377 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8378 s->gss_buf.length = s->pktout->length - micoffset;
8380 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8381 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8382 ssh_pkt_addstring_start(s->pktout);
8383 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8384 ssh2_pkt_send(ssh, s->pktout);
8385 s->gsslib->free_mic(s->gsslib, &mic);
8389 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8390 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8393 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8396 * Keyboard-interactive authentication.
8399 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8401 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8403 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8404 ssh2_pkt_addstring(s->pktout, ssh->username);
8405 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8406 /* service requested */
8407 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8409 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8410 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8411 ssh2_pkt_send(ssh, s->pktout);
8413 logevent("Attempting keyboard-interactive authentication");
8415 crWaitUntilV(pktin);
8416 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8417 /* Server is not willing to do keyboard-interactive
8418 * at all (or, bizarrely but legally, accepts the
8419 * user without actually issuing any prompts).
8420 * Give up on it entirely. */
8422 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8423 s->kbd_inter_refused = TRUE; /* don't try it again */
8428 * Loop while the server continues to send INFO_REQUESTs.
8430 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8432 char *name, *inst, *lang;
8433 int name_len, inst_len, lang_len;
8437 * We've got a fresh USERAUTH_INFO_REQUEST.
8438 * Get the preamble and start building a prompt.
8440 ssh_pkt_getstring(pktin, &name, &name_len);
8441 ssh_pkt_getstring(pktin, &inst, &inst_len);
8442 ssh_pkt_getstring(pktin, &lang, &lang_len);
8443 s->cur_prompt = new_prompts(ssh->frontend);
8444 s->cur_prompt->to_server = TRUE;
8447 * Get any prompt(s) from the packet.
8449 s->num_prompts = ssh_pkt_getuint32(pktin);
8450 for (i = 0; i < s->num_prompts; i++) {
8454 static char noprompt[] =
8455 "<server failed to send prompt>: ";
8457 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8458 echo = ssh2_pkt_getbool(pktin);
8461 prompt_len = lenof(noprompt)-1;
8463 add_prompt(s->cur_prompt,
8464 dupprintf("%.*s", prompt_len, prompt),
8465 echo, SSH_MAX_PASSWORD_LEN);
8469 /* FIXME: better prefix to distinguish from
8471 s->cur_prompt->name =
8472 dupprintf("SSH server: %.*s", name_len, name);
8473 s->cur_prompt->name_reqd = TRUE;
8475 s->cur_prompt->name =
8476 dupstr("SSH server authentication");
8477 s->cur_prompt->name_reqd = FALSE;
8479 /* We add a prefix to try to make it clear that a prompt
8480 * has come from the server.
8481 * FIXME: ugly to print "Using..." in prompt _every_
8482 * time round. Can this be done more subtly? */
8483 /* Special case: for reasons best known to themselves,
8484 * some servers send k-i requests with no prompts and
8485 * nothing to display. Keep quiet in this case. */
8486 if (s->num_prompts || name_len || inst_len) {
8487 s->cur_prompt->instruction =
8488 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8489 inst_len ? "\n" : "", inst_len, inst);
8490 s->cur_prompt->instr_reqd = TRUE;
8492 s->cur_prompt->instr_reqd = FALSE;
8496 * Display any instructions, and get the user's
8500 int ret; /* not live over crReturn */
8501 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8504 crWaitUntilV(!pktin);
8505 ret = get_userpass_input(s->cur_prompt, in, inlen);
8510 * Failed to get responses. Terminate.
8512 free_prompts(s->cur_prompt);
8513 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8514 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8521 * Send the response(s) to the server.
8523 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8524 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8525 for (i=0; i < s->num_prompts; i++) {
8526 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8527 ssh2_pkt_addstring(s->pktout,
8528 s->cur_prompt->prompts[i]->result);
8529 end_log_omission(ssh, s->pktout);
8531 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8534 * Get the next packet in case it's another
8537 crWaitUntilV(pktin);
8542 * We should have SUCCESS or FAILURE now.
8546 } else if (s->can_passwd) {
8549 * Plain old password authentication.
8551 int ret; /* not live over crReturn */
8552 int changereq_first_time; /* not live over crReturn */
8554 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8556 s->cur_prompt = new_prompts(ssh->frontend);
8557 s->cur_prompt->to_server = TRUE;
8558 s->cur_prompt->name = dupstr("SSH password");
8559 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8562 FALSE, SSH_MAX_PASSWORD_LEN);
8564 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8567 crWaitUntilV(!pktin);
8568 ret = get_userpass_input(s->cur_prompt, in, inlen);
8573 * Failed to get responses. Terminate.
8575 free_prompts(s->cur_prompt);
8576 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8577 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8582 * Squirrel away the password. (We may need it later if
8583 * asked to change it.)
8585 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8586 free_prompts(s->cur_prompt);
8589 * Send the password packet.
8591 * We pad out the password packet to 256 bytes to make
8592 * it harder for an attacker to find the length of the
8595 * Anyone using a password longer than 256 bytes
8596 * probably doesn't have much to worry about from
8597 * people who find out how long their password is!
8599 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8600 ssh2_pkt_addstring(s->pktout, ssh->username);
8601 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8602 /* service requested */
8603 ssh2_pkt_addstring(s->pktout, "password");
8604 ssh2_pkt_addbool(s->pktout, FALSE);
8605 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8606 ssh2_pkt_addstring(s->pktout, s->password);
8607 end_log_omission(ssh, s->pktout);
8608 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8609 logevent("Sent password");
8610 s->type = AUTH_TYPE_PASSWORD;
8613 * Wait for next packet, in case it's a password change
8616 crWaitUntilV(pktin);
8617 changereq_first_time = TRUE;
8619 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8622 * We're being asked for a new password
8623 * (perhaps not for the first time).
8624 * Loop until the server accepts it.
8627 int got_new = FALSE; /* not live over crReturn */
8628 char *prompt; /* not live over crReturn */
8629 int prompt_len; /* not live over crReturn */
8633 if (changereq_first_time)
8634 msg = "Server requested password change";
8636 msg = "Server rejected new password";
8638 c_write_str(ssh, msg);
8639 c_write_str(ssh, "\r\n");
8642 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8644 s->cur_prompt = new_prompts(ssh->frontend);
8645 s->cur_prompt->to_server = TRUE;
8646 s->cur_prompt->name = dupstr("New SSH password");
8647 s->cur_prompt->instruction =
8648 dupprintf("%.*s", prompt_len, prompt);
8649 s->cur_prompt->instr_reqd = TRUE;
8651 * There's no explicit requirement in the protocol
8652 * for the "old" passwords in the original and
8653 * password-change messages to be the same, and
8654 * apparently some Cisco kit supports password change
8655 * by the user entering a blank password originally
8656 * and the real password subsequently, so,
8657 * reluctantly, we prompt for the old password again.
8659 * (On the other hand, some servers don't even bother
8660 * to check this field.)
8662 add_prompt(s->cur_prompt,
8663 dupstr("Current password (blank for previously entered password): "),
8664 FALSE, SSH_MAX_PASSWORD_LEN);
8665 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8666 FALSE, SSH_MAX_PASSWORD_LEN);
8667 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8668 FALSE, SSH_MAX_PASSWORD_LEN);
8671 * Loop until the user manages to enter the same
8676 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8679 crWaitUntilV(!pktin);
8680 ret = get_userpass_input(s->cur_prompt, in, inlen);
8685 * Failed to get responses. Terminate.
8687 /* burn the evidence */
8688 free_prompts(s->cur_prompt);
8689 memset(s->password, 0, strlen(s->password));
8691 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8692 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8698 * If the user specified a new original password
8699 * (IYSWIM), overwrite any previously specified
8701 * (A side effect is that the user doesn't have to
8702 * re-enter it if they louse up the new password.)
8704 if (s->cur_prompt->prompts[0]->result[0]) {
8705 memset(s->password, 0, strlen(s->password));
8706 /* burn the evidence */
8709 dupstr(s->cur_prompt->prompts[0]->result);
8713 * Check the two new passwords match.
8715 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8716 s->cur_prompt->prompts[2]->result)
8719 /* They don't. Silly user. */
8720 c_write_str(ssh, "Passwords do not match\r\n");
8725 * Send the new password (along with the old one).
8726 * (see above for padding rationale)
8728 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8729 ssh2_pkt_addstring(s->pktout, ssh->username);
8730 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8731 /* service requested */
8732 ssh2_pkt_addstring(s->pktout, "password");
8733 ssh2_pkt_addbool(s->pktout, TRUE);
8734 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8735 ssh2_pkt_addstring(s->pktout, s->password);
8736 ssh2_pkt_addstring(s->pktout,
8737 s->cur_prompt->prompts[1]->result);
8738 free_prompts(s->cur_prompt);
8739 end_log_omission(ssh, s->pktout);
8740 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8741 logevent("Sent new password");
8744 * Now see what the server has to say about it.
8745 * (If it's CHANGEREQ again, it's not happy with the
8748 crWaitUntilV(pktin);
8749 changereq_first_time = FALSE;
8754 * We need to reexamine the current pktin at the top
8755 * of the loop. Either:
8756 * - we weren't asked to change password at all, in
8757 * which case it's a SUCCESS or FAILURE with the
8759 * - we sent a new password, and the server was
8760 * either OK with it (SUCCESS or FAILURE w/partial
8761 * success) or unhappy with the _old_ password
8762 * (FAILURE w/o partial success)
8763 * In any of these cases, we go back to the top of
8764 * the loop and start again.
8769 * We don't need the old password any more, in any
8770 * case. Burn the evidence.
8772 memset(s->password, 0, strlen(s->password));
8776 char *str = dupprintf("No supported authentication methods available"
8777 " (server sent: %.*s)",
8780 ssh_disconnect(ssh, str,
8781 "No supported authentication methods available",
8782 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8792 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8794 /* Clear up various bits and pieces from authentication. */
8795 if (s->publickey_blob) {
8796 sfree(s->publickey_blob);
8797 sfree(s->publickey_comment);
8799 if (s->agent_response)
8800 sfree(s->agent_response);
8802 if (s->userauth_success) {
8804 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8805 * packets since. Signal the transport layer to consider enacting
8806 * delayed compression.
8808 * (Relying on we_are_in is not sufficient, as
8809 * draft-miller-secsh-compression-delayed is quite clear that it
8810 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8811 * become set for other reasons.)
8813 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8817 * Now the connection protocol has started, one way or another.
8820 ssh->channels = newtree234(ssh_channelcmp);
8823 * Set up handlers for some connection protocol messages, so we
8824 * don't have to handle them repeatedly in this coroutine.
8826 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8827 ssh2_msg_channel_window_adjust;
8828 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8829 ssh2_msg_global_request;
8832 * Create the main session channel.
8834 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
8835 ssh->mainchan = NULL;
8836 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
8838 * Just start a direct-tcpip channel and use it as the main
8841 ssh->mainchan = snew(struct ssh_channel);
8842 ssh->mainchan->ssh = ssh;
8843 ssh2_channel_init(ssh->mainchan);
8845 "Opening direct-tcpip channel to %s:%d in place of session",
8846 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8847 conf_get_int(ssh->conf, CONF_ssh_nc_port));
8848 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8849 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8850 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8851 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8852 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8853 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8854 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
8856 * There's nothing meaningful to put in the originator
8857 * fields, but some servers insist on syntactically correct
8860 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8861 ssh2_pkt_adduint32(s->pktout, 0);
8862 ssh2_pkt_send(ssh, s->pktout);
8864 crWaitUntilV(pktin);
8865 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8866 bombout(("Server refused to open a direct-tcpip channel"));
8868 /* FIXME: error data comes back in FAILURE packet */
8870 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8871 bombout(("Server's channel confirmation cited wrong channel"));
8874 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8875 ssh->mainchan->halfopen = FALSE;
8876 ssh->mainchan->type = CHAN_MAINSESSION;
8877 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8878 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8879 add234(ssh->channels, ssh->mainchan);
8880 update_specials_menu(ssh->frontend);
8881 logevent("Opened direct-tcpip channel");
8884 ssh->mainchan = snew(struct ssh_channel);
8885 ssh->mainchan->ssh = ssh;
8886 ssh2_channel_init(ssh->mainchan);
8887 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8888 ssh2_pkt_addstring(s->pktout, "session");
8889 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8890 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8891 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8892 ssh2_pkt_send(ssh, s->pktout);
8893 crWaitUntilV(pktin);
8894 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8895 bombout(("Server refused to open a session"));
8897 /* FIXME: error data comes back in FAILURE packet */
8899 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8900 bombout(("Server's channel confirmation cited wrong channel"));
8903 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8904 ssh->mainchan->halfopen = FALSE;
8905 ssh->mainchan->type = CHAN_MAINSESSION;
8906 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8907 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8908 add234(ssh->channels, ssh->mainchan);
8909 update_specials_menu(ssh->frontend);
8910 logevent("Opened channel for session");
8911 ssh->ncmode = FALSE;
8915 * Now we have a channel, make dispatch table entries for
8916 * general channel-based messages.
8918 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8919 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8920 ssh2_msg_channel_data;
8921 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8922 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8923 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8924 ssh2_msg_channel_open_confirmation;
8925 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8926 ssh2_msg_channel_open_failure;
8927 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8928 ssh2_msg_channel_request;
8929 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8930 ssh2_msg_channel_open;
8932 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
8934 * This message indicates to the server that we promise
8935 * not to try to run any other channel in parallel with
8936 * this one, so it's safe for it to advertise a very large
8937 * window and leave the flow control to TCP.
8939 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8940 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8941 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8942 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8943 ssh2_pkt_send(ssh, s->pktout);
8947 * Potentially enable X11 forwarding.
8949 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
8950 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
8951 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
8952 logevent("Requesting X11 forwarding");
8953 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8954 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8955 ssh2_pkt_addstring(s->pktout, "x11-req");
8956 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8957 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8958 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8960 * Note that while we blank the X authentication data here, we don't
8961 * take any special action to blank the start of an X11 channel,
8962 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8963 * without having session blanking enabled is likely to leak your
8964 * cookie into the log.
8966 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8967 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8968 end_log_omission(ssh, s->pktout);
8969 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8970 ssh2_pkt_send(ssh, s->pktout);
8972 crWaitUntilV(pktin);
8974 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8975 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8976 bombout(("Unexpected response to X11 forwarding request:"
8977 " packet type %d", pktin->type));
8980 logevent("X11 forwarding refused");
8982 logevent("X11 forwarding enabled");
8983 ssh->X11_fwd_enabled = TRUE;
8988 * Enable port forwardings.
8990 ssh_setup_portfwd(ssh, ssh->conf);
8993 * Potentially enable agent forwarding.
8995 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
8996 logevent("Requesting OpenSSH-style agent forwarding");
8997 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8998 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8999 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
9000 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9001 ssh2_pkt_send(ssh, s->pktout);
9003 crWaitUntilV(pktin);
9005 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9006 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9007 bombout(("Unexpected response to agent forwarding request:"
9008 " packet type %d", pktin->type));
9011 logevent("Agent forwarding refused");
9013 logevent("Agent forwarding enabled");
9014 ssh->agentfwd_enabled = TRUE;
9019 * Now allocate a pty for the session.
9021 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
9022 /* Unpick the terminal-speed string. */
9023 /* XXX perhaps we should allow no speeds to be sent. */
9024 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9025 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9026 /* Build the pty request. */
9027 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9028 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9029 ssh2_pkt_addstring(s->pktout, "pty-req");
9030 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9031 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
9032 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
9033 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
9034 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
9035 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
9036 ssh2_pkt_addstring_start(s->pktout);
9037 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
9038 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
9039 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
9040 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
9041 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9042 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9043 ssh2_pkt_send(ssh, s->pktout);
9044 ssh->state = SSH_STATE_INTERMED;
9046 crWaitUntilV(pktin);
9048 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9049 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9050 bombout(("Unexpected response to pty request:"
9051 " packet type %d", pktin->type));
9054 c_write_str(ssh, "Server refused to allocate pty\r\n");
9055 ssh->editing = ssh->echoing = 1;
9057 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9058 ssh->ospeed, ssh->ispeed);
9059 ssh->got_pty = TRUE;
9062 ssh->editing = ssh->echoing = 1;
9066 * Send environment variables.
9068 * Simplest thing here is to send all the requests at once, and
9069 * then wait for a whole bunch of successes or failures.
9071 if (ssh->mainchan && !ssh->ncmode) {
9076 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9078 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9079 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9080 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9081 ssh2_pkt_addstring(s->pktout, "env");
9082 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9083 ssh2_pkt_addstring(s->pktout, key);
9084 ssh2_pkt_addstring(s->pktout, val);
9085 ssh2_pkt_send(ssh, s->pktout);
9091 logeventf(ssh, "Sent %d environment variables", s->num_env);
9094 s->env_left = s->num_env;
9096 while (s->env_left > 0) {
9097 crWaitUntilV(pktin);
9099 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9100 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9101 bombout(("Unexpected response to environment request:"
9102 " packet type %d", pktin->type));
9112 if (s->env_ok == s->num_env) {
9113 logevent("All environment variables successfully set");
9114 } else if (s->env_ok == 0) {
9115 logevent("All environment variables refused");
9116 c_write_str(ssh, "Server refused to set environment variables\r\n");
9118 logeventf(ssh, "%d environment variables refused",
9119 s->num_env - s->env_ok);
9120 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9126 * Start a shell or a remote command. We may have to attempt
9127 * this twice if the config data has provided a second choice
9130 if (ssh->mainchan && !ssh->ncmode) while (1) {
9134 if (ssh->fallback_cmd) {
9135 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9136 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9138 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9139 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9142 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9143 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9145 ssh2_pkt_addstring(s->pktout, "subsystem");
9146 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9147 ssh2_pkt_addstring(s->pktout, cmd);
9149 ssh2_pkt_addstring(s->pktout, "exec");
9150 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9151 ssh2_pkt_addstring(s->pktout, cmd);
9153 ssh2_pkt_addstring(s->pktout, "shell");
9154 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9156 ssh2_pkt_send(ssh, s->pktout);
9158 crWaitUntilV(pktin);
9160 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9161 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9162 bombout(("Unexpected response to shell/command request:"
9163 " packet type %d", pktin->type));
9167 * We failed to start the command. If this is the
9168 * fallback command, we really are finished; if it's
9169 * not, and if the fallback command exists, try falling
9170 * back to it before complaining.
9172 if (!ssh->fallback_cmd &&
9173 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9174 logevent("Primary command failed; attempting fallback");
9175 ssh->fallback_cmd = TRUE;
9178 bombout(("Server refused to start a shell/command"));
9181 logevent("Started a shell/command");
9186 ssh->state = SSH_STATE_SESSION;
9187 if (ssh->size_needed)
9188 ssh_size(ssh, ssh->term_width, ssh->term_height);
9189 if (ssh->eof_needed)
9190 ssh_special(ssh, TS_EOF);
9193 * All the initial channel requests are done, so install the default
9196 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
9197 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9203 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9208 s->try_send = FALSE;
9212 * _All_ the connection-layer packets we expect to
9213 * receive are now handled by the dispatch table.
9214 * Anything that reaches here must be bogus.
9217 bombout(("Strange packet received: type %d", pktin->type));
9219 } else if (ssh->mainchan) {
9221 * We have spare data. Add it to the channel buffer.
9223 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9228 struct ssh_channel *c;
9230 * Try to send data on all channels if we can.
9232 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9233 ssh2_try_send_and_unthrottle(ssh, c);
9241 * Handlers for SSH-2 messages that might arrive at any moment.
9243 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9245 /* log reason code in disconnect message */
9249 reason = ssh_pkt_getuint32(pktin);
9250 ssh_pkt_getstring(pktin, &msg, &msglen);
9252 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9253 buf = dupprintf("Received disconnect message (%s)",
9254 ssh2_disconnect_reasons[reason]);
9256 buf = dupprintf("Received disconnect message (unknown"
9257 " type %d)", reason);
9261 buf = dupprintf("Disconnection message text: %.*s",
9264 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9266 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9267 ssh2_disconnect_reasons[reason] : "unknown",
9272 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9274 /* log the debug message */
9278 /* XXX maybe we should actually take notice of the return value */
9279 ssh2_pkt_getbool(pktin);
9280 ssh_pkt_getstring(pktin, &msg, &msglen);
9282 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9285 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9287 struct Packet *pktout;
9288 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9289 ssh2_pkt_adduint32(pktout, pktin->sequence);
9291 * UNIMPLEMENTED messages MUST appear in the same order as the
9292 * messages they respond to. Hence, never queue them.
9294 ssh2_pkt_send_noqueue(ssh, pktout);
9298 * Handle the top-level SSH-2 protocol.
9300 static void ssh2_protocol_setup(Ssh ssh)
9305 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9307 for (i = 0; i < 256; i++)
9308 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9311 * Any message we actually understand, we set to NULL so that
9312 * the coroutines will get it.
9314 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9315 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9316 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9317 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9318 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9319 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9320 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9321 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9322 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9323 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9324 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9325 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9326 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9327 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9328 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9329 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9330 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9331 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9332 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9333 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9334 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9335 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9336 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9337 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9338 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9339 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9340 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9341 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9342 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9343 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9344 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9345 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9346 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9349 * These special message types we install handlers for.
9351 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9352 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9353 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9356 static void ssh2_timer(void *ctx, long now)
9360 if (ssh->state == SSH_STATE_CLOSED)
9363 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9364 now - ssh->next_rekey >= 0) {
9365 do_ssh2_transport(ssh, "timeout", -1, NULL);
9369 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9370 struct Packet *pktin)
9372 unsigned char *in = (unsigned char *)vin;
9373 if (ssh->state == SSH_STATE_CLOSED)
9377 ssh->incoming_data_size += pktin->encrypted_len;
9378 if (!ssh->kex_in_progress &&
9379 ssh->max_data_size != 0 &&
9380 ssh->incoming_data_size > ssh->max_data_size)
9381 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9384 if (pktin && ssh->packet_dispatch[pktin->type]) {
9385 ssh->packet_dispatch[pktin->type](ssh, pktin);
9389 if (!ssh->protocol_initial_phase_done ||
9390 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9391 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9392 !ssh->protocol_initial_phase_done) {
9393 ssh->protocol_initial_phase_done = TRUE;
9395 * Allow authconn to initialise itself.
9397 do_ssh2_authconn(ssh, NULL, 0, NULL);
9400 do_ssh2_authconn(ssh, in, inlen, pktin);
9404 static void ssh_cache_conf_values(Ssh ssh)
9406 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9410 * Called to set up the connection.
9412 * Returns an error message, or NULL on success.
9414 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9415 Conf *conf, char *host, int port, char **realhost,
9416 int nodelay, int keepalive)
9421 ssh = snew(struct ssh_tag);
9422 ssh->conf = conf_copy(conf);
9423 ssh_cache_conf_values(ssh);
9424 ssh->version = 0; /* when not ready yet */
9427 ssh->v1_cipher_ctx = NULL;
9428 ssh->crcda_ctx = NULL;
9429 ssh->cscipher = NULL;
9430 ssh->cs_cipher_ctx = NULL;
9431 ssh->sccipher = NULL;
9432 ssh->sc_cipher_ctx = NULL;
9434 ssh->cs_mac_ctx = NULL;
9436 ssh->sc_mac_ctx = NULL;
9438 ssh->cs_comp_ctx = NULL;
9440 ssh->sc_comp_ctx = NULL;
9442 ssh->kex_ctx = NULL;
9443 ssh->hostkey = NULL;
9445 ssh->close_expected = FALSE;
9446 ssh->clean_exit = FALSE;
9447 ssh->state = SSH_STATE_PREPACKET;
9448 ssh->size_needed = FALSE;
9449 ssh->eof_needed = FALSE;
9452 ssh->deferred_send_data = NULL;
9453 ssh->deferred_len = 0;
9454 ssh->deferred_size = 0;
9455 ssh->fallback_cmd = 0;
9456 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9457 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9458 ssh->x11disp = NULL;
9459 ssh->v1_compressing = FALSE;
9460 ssh->v2_outgoing_sequence = 0;
9461 ssh->ssh1_rdpkt_crstate = 0;
9462 ssh->ssh2_rdpkt_crstate = 0;
9463 ssh->do_ssh_init_crstate = 0;
9464 ssh->ssh_gotdata_crstate = 0;
9465 ssh->do_ssh1_connection_crstate = 0;
9466 ssh->do_ssh1_login_crstate = 0;
9467 ssh->do_ssh2_transport_crstate = 0;
9468 ssh->do_ssh2_authconn_crstate = 0;
9469 ssh->do_ssh_init_state = NULL;
9470 ssh->do_ssh1_login_state = NULL;
9471 ssh->do_ssh2_transport_state = NULL;
9472 ssh->do_ssh2_authconn_state = NULL;
9475 ssh->mainchan = NULL;
9476 ssh->throttled_all = 0;
9477 ssh->v1_stdout_throttling = 0;
9479 ssh->queuelen = ssh->queuesize = 0;
9480 ssh->queueing = FALSE;
9481 ssh->qhead = ssh->qtail = NULL;
9482 ssh->deferred_rekey_reason = NULL;
9483 bufchain_init(&ssh->queued_incoming_data);
9484 ssh->frozen = FALSE;
9485 ssh->username = NULL;
9486 ssh->sent_console_eof = FALSE;
9487 ssh->got_pty = FALSE;
9489 *backend_handle = ssh;
9492 if (crypto_startup() == 0)
9493 return "Microsoft high encryption pack not installed!";
9496 ssh->frontend = frontend_handle;
9497 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9498 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9500 ssh->channels = NULL;
9501 ssh->rportfwds = NULL;
9502 ssh->portfwds = NULL;
9507 ssh->conn_throttle_count = 0;
9508 ssh->overall_bufsize = 0;
9509 ssh->fallback_cmd = 0;
9511 ssh->protocol = NULL;
9513 ssh->protocol_initial_phase_done = FALSE;
9517 ssh->incoming_data_size = ssh->outgoing_data_size =
9518 ssh->deferred_data_size = 0L;
9519 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9520 CONF_ssh_rekey_data));
9521 ssh->kex_in_progress = FALSE;
9524 ssh->gsslibs = NULL;
9527 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9536 static void ssh_free(void *handle)
9538 Ssh ssh = (Ssh) handle;
9539 struct ssh_channel *c;
9540 struct ssh_rportfwd *pf;
9542 if (ssh->v1_cipher_ctx)
9543 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9544 if (ssh->cs_cipher_ctx)
9545 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9546 if (ssh->sc_cipher_ctx)
9547 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9548 if (ssh->cs_mac_ctx)
9549 ssh->csmac->free_context(ssh->cs_mac_ctx);
9550 if (ssh->sc_mac_ctx)
9551 ssh->scmac->free_context(ssh->sc_mac_ctx);
9552 if (ssh->cs_comp_ctx) {
9554 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9556 zlib_compress_cleanup(ssh->cs_comp_ctx);
9558 if (ssh->sc_comp_ctx) {
9560 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9562 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9565 dh_cleanup(ssh->kex_ctx);
9566 sfree(ssh->savedhost);
9568 while (ssh->queuelen-- > 0)
9569 ssh_free_packet(ssh->queue[ssh->queuelen]);
9572 while (ssh->qhead) {
9573 struct queued_handler *qh = ssh->qhead;
9574 ssh->qhead = qh->next;
9577 ssh->qhead = ssh->qtail = NULL;
9579 if (ssh->channels) {
9580 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9583 if (c->u.x11.s != NULL)
9584 x11_close(c->u.x11.s);
9587 case CHAN_SOCKDATA_DORMANT:
9588 if (c->u.pfd.s != NULL)
9589 pfd_close(c->u.pfd.s);
9594 freetree234(ssh->channels);
9595 ssh->channels = NULL;
9598 if (ssh->rportfwds) {
9599 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9601 freetree234(ssh->rportfwds);
9602 ssh->rportfwds = NULL;
9604 sfree(ssh->deferred_send_data);
9606 x11_free_display(ssh->x11disp);
9607 sfree(ssh->do_ssh_init_state);
9608 sfree(ssh->do_ssh1_login_state);
9609 sfree(ssh->do_ssh2_transport_state);
9610 sfree(ssh->do_ssh2_authconn_state);
9613 sfree(ssh->fullhostname);
9614 if (ssh->crcda_ctx) {
9615 crcda_free_context(ssh->crcda_ctx);
9616 ssh->crcda_ctx = NULL;
9619 ssh_do_close(ssh, TRUE);
9620 expire_timer_context(ssh);
9622 pinger_free(ssh->pinger);
9623 bufchain_clear(&ssh->queued_incoming_data);
9624 sfree(ssh->username);
9625 conf_free(ssh->conf);
9628 ssh_gss_cleanup(ssh->gsslibs);
9636 * Reconfigure the SSH backend.
9638 static void ssh_reconfig(void *handle, Conf *conf)
9640 Ssh ssh = (Ssh) handle;
9641 char *rekeying = NULL, rekey_mandatory = FALSE;
9642 unsigned long old_max_data_size;
9645 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9647 ssh_setup_portfwd(ssh, conf);
9649 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9650 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9652 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9653 long now = GETTICKCOUNT();
9655 if (new_next - now < 0) {
9656 rekeying = "timeout shortened";
9658 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9662 old_max_data_size = ssh->max_data_size;
9663 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9664 CONF_ssh_rekey_data));
9665 if (old_max_data_size != ssh->max_data_size &&
9666 ssh->max_data_size != 0) {
9667 if (ssh->outgoing_data_size > ssh->max_data_size ||
9668 ssh->incoming_data_size > ssh->max_data_size)
9669 rekeying = "data limit lowered";
9672 if (conf_get_int(ssh->conf, CONF_compression) !=
9673 conf_get_int(conf, CONF_compression)) {
9674 rekeying = "compression setting changed";
9675 rekey_mandatory = TRUE;
9678 for (i = 0; i < CIPHER_MAX; i++)
9679 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9680 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9681 rekeying = "cipher settings changed";
9682 rekey_mandatory = TRUE;
9684 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9685 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9686 rekeying = "cipher settings changed";
9687 rekey_mandatory = TRUE;
9690 conf_free(ssh->conf);
9691 ssh->conf = conf_copy(conf);
9692 ssh_cache_conf_values(ssh);
9695 if (!ssh->kex_in_progress) {
9696 do_ssh2_transport(ssh, rekeying, -1, NULL);
9697 } else if (rekey_mandatory) {
9698 ssh->deferred_rekey_reason = rekeying;
9704 * Called to send data down the SSH connection.
9706 static int ssh_send(void *handle, char *buf, int len)
9708 Ssh ssh = (Ssh) handle;
9710 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9713 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9715 return ssh_sendbuffer(ssh);
9719 * Called to query the current amount of buffered stdin data.
9721 static int ssh_sendbuffer(void *handle)
9723 Ssh ssh = (Ssh) handle;
9726 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9730 * If the SSH socket itself has backed up, add the total backup
9731 * size on that to any individual buffer on the stdin channel.
9734 if (ssh->throttled_all)
9735 override_value = ssh->overall_bufsize;
9737 if (ssh->version == 1) {
9738 return override_value;
9739 } else if (ssh->version == 2) {
9741 return override_value;
9743 return (override_value +
9744 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9751 * Called to set the size of the window from SSH's POV.
9753 static void ssh_size(void *handle, int width, int height)
9755 Ssh ssh = (Ssh) handle;
9756 struct Packet *pktout;
9758 ssh->term_width = width;
9759 ssh->term_height = height;
9761 switch (ssh->state) {
9762 case SSH_STATE_BEFORE_SIZE:
9763 case SSH_STATE_PREPACKET:
9764 case SSH_STATE_CLOSED:
9765 break; /* do nothing */
9766 case SSH_STATE_INTERMED:
9767 ssh->size_needed = TRUE; /* buffer for later */
9769 case SSH_STATE_SESSION:
9770 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9771 if (ssh->version == 1) {
9772 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9773 PKT_INT, ssh->term_height,
9774 PKT_INT, ssh->term_width,
9775 PKT_INT, 0, PKT_INT, 0, PKT_END);
9776 } else if (ssh->mainchan) {
9777 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9778 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9779 ssh2_pkt_addstring(pktout, "window-change");
9780 ssh2_pkt_addbool(pktout, 0);
9781 ssh2_pkt_adduint32(pktout, ssh->term_width);
9782 ssh2_pkt_adduint32(pktout, ssh->term_height);
9783 ssh2_pkt_adduint32(pktout, 0);
9784 ssh2_pkt_adduint32(pktout, 0);
9785 ssh2_pkt_send(ssh, pktout);
9793 * Return a list of the special codes that make sense in this
9796 static const struct telnet_special *ssh_get_specials(void *handle)
9798 static const struct telnet_special ssh1_ignore_special[] = {
9799 {"IGNORE message", TS_NOP}
9801 static const struct telnet_special ssh2_ignore_special[] = {
9802 {"IGNORE message", TS_NOP},
9804 static const struct telnet_special ssh2_rekey_special[] = {
9805 {"Repeat key exchange", TS_REKEY},
9807 static const struct telnet_special ssh2_session_specials[] = {
9810 /* These are the signal names defined by RFC 4254.
9811 * They include all the ISO C signals, but are a subset of the POSIX
9812 * required signals. */
9813 {"SIGINT (Interrupt)", TS_SIGINT},
9814 {"SIGTERM (Terminate)", TS_SIGTERM},
9815 {"SIGKILL (Kill)", TS_SIGKILL},
9816 {"SIGQUIT (Quit)", TS_SIGQUIT},
9817 {"SIGHUP (Hangup)", TS_SIGHUP},
9818 {"More signals", TS_SUBMENU},
9819 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9820 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9821 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9822 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9825 static const struct telnet_special specials_end[] = {
9828 /* XXX review this length for any changes: */
9829 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9830 lenof(ssh2_rekey_special) +
9831 lenof(ssh2_session_specials) +
9832 lenof(specials_end)];
9833 Ssh ssh = (Ssh) handle;
9835 #define ADD_SPECIALS(name) \
9837 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9838 memcpy(&ssh_specials[i], name, sizeof name); \
9842 if (ssh->version == 1) {
9843 /* Don't bother offering IGNORE if we've decided the remote
9844 * won't cope with it, since we wouldn't bother sending it if
9846 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9847 ADD_SPECIALS(ssh1_ignore_special);
9848 } else if (ssh->version == 2) {
9849 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9850 ADD_SPECIALS(ssh2_ignore_special);
9851 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9852 ADD_SPECIALS(ssh2_rekey_special);
9854 ADD_SPECIALS(ssh2_session_specials);
9855 } /* else we're not ready yet */
9858 ADD_SPECIALS(specials_end);
9859 return ssh_specials;
9867 * Send special codes. TS_EOF is useful for `plink', so you
9868 * can send an EOF and collect resulting output (e.g. `plink
9871 static void ssh_special(void *handle, Telnet_Special code)
9873 Ssh ssh = (Ssh) handle;
9874 struct Packet *pktout;
9876 if (code == TS_EOF) {
9877 if (ssh->state != SSH_STATE_SESSION) {
9879 * Buffer the EOF in case we are pre-SESSION, so we can
9880 * send it as soon as we reach SESSION.
9883 ssh->eof_needed = TRUE;
9886 if (ssh->version == 1) {
9887 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9888 } else if (ssh->mainchan) {
9889 sshfwd_write_eof(ssh->mainchan);
9890 ssh->send_ok = 0; /* now stop trying to read from stdin */
9892 logevent("Sent EOF message");
9893 } else if (code == TS_PING || code == TS_NOP) {
9894 if (ssh->state == SSH_STATE_CLOSED
9895 || ssh->state == SSH_STATE_PREPACKET) return;
9896 if (ssh->version == 1) {
9897 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9898 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9900 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9901 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9902 ssh2_pkt_addstring_start(pktout);
9903 ssh2_pkt_send_noqueue(ssh, pktout);
9906 } else if (code == TS_REKEY) {
9907 if (!ssh->kex_in_progress && ssh->version == 2) {
9908 do_ssh2_transport(ssh, "at user request", -1, NULL);
9910 } else if (code == TS_BRK) {
9911 if (ssh->state == SSH_STATE_CLOSED
9912 || ssh->state == SSH_STATE_PREPACKET) return;
9913 if (ssh->version == 1) {
9914 logevent("Unable to send BREAK signal in SSH-1");
9915 } else if (ssh->mainchan) {
9916 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9917 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9918 ssh2_pkt_addstring(pktout, "break");
9919 ssh2_pkt_addbool(pktout, 0);
9920 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9921 ssh2_pkt_send(ssh, pktout);
9924 /* Is is a POSIX signal? */
9925 char *signame = NULL;
9926 if (code == TS_SIGABRT) signame = "ABRT";
9927 if (code == TS_SIGALRM) signame = "ALRM";
9928 if (code == TS_SIGFPE) signame = "FPE";
9929 if (code == TS_SIGHUP) signame = "HUP";
9930 if (code == TS_SIGILL) signame = "ILL";
9931 if (code == TS_SIGINT) signame = "INT";
9932 if (code == TS_SIGKILL) signame = "KILL";
9933 if (code == TS_SIGPIPE) signame = "PIPE";
9934 if (code == TS_SIGQUIT) signame = "QUIT";
9935 if (code == TS_SIGSEGV) signame = "SEGV";
9936 if (code == TS_SIGTERM) signame = "TERM";
9937 if (code == TS_SIGUSR1) signame = "USR1";
9938 if (code == TS_SIGUSR2) signame = "USR2";
9939 /* The SSH-2 protocol does in principle support arbitrary named
9940 * signals, including signame@domain, but we don't support those. */
9942 /* It's a signal. */
9943 if (ssh->version == 2 && ssh->mainchan) {
9944 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9945 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9946 ssh2_pkt_addstring(pktout, "signal");
9947 ssh2_pkt_addbool(pktout, 0);
9948 ssh2_pkt_addstring(pktout, signame);
9949 ssh2_pkt_send(ssh, pktout);
9950 logeventf(ssh, "Sent signal SIG%s", signame);
9953 /* Never heard of it. Do nothing */
9958 void *new_sock_channel(void *handle, Socket s)
9960 Ssh ssh = (Ssh) handle;
9961 struct ssh_channel *c;
9962 c = snew(struct ssh_channel);
9965 ssh2_channel_init(c);
9967 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9969 add234(ssh->channels, c);
9974 * This is called when stdout/stderr (the entity to which
9975 * from_backend sends data) manages to clear some backlog.
9977 static void ssh_unthrottle(void *handle, int bufsize)
9979 Ssh ssh = (Ssh) handle;
9982 if (ssh->version == 1) {
9983 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9984 ssh->v1_stdout_throttling = 0;
9985 ssh_throttle_conn(ssh, -1);
9988 if (ssh->mainchan) {
9989 ssh2_set_window(ssh->mainchan,
9990 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9991 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9992 if (conf_get_int(ssh->conf, CONF_ssh_simple))
9995 buflimit = ssh->mainchan->v.v2.locmaxwin;
9996 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9997 ssh->mainchan->throttling_conn = 0;
9998 ssh_throttle_conn(ssh, -1);
10004 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10006 struct ssh_channel *c = (struct ssh_channel *)channel;
10008 struct Packet *pktout;
10010 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
10012 if (ssh->version == 1) {
10013 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10014 PKT_INT, c->localid,
10017 /* PKT_STR, <org:orgport>, */
10020 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
10021 ssh2_pkt_addstring(pktout, "direct-tcpip");
10022 ssh2_pkt_adduint32(pktout, c->localid);
10023 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
10024 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
10025 ssh2_pkt_addstring(pktout, hostname);
10026 ssh2_pkt_adduint32(pktout, port);
10028 * We make up values for the originator data; partly it's
10029 * too much hassle to keep track, and partly I'm not
10030 * convinced the server should be told details like that
10031 * about my local network configuration.
10032 * The "originator IP address" is syntactically a numeric
10033 * IP address, and some servers (e.g., Tectia) get upset
10034 * if it doesn't match this syntax.
10036 ssh2_pkt_addstring(pktout, "0.0.0.0");
10037 ssh2_pkt_adduint32(pktout, 0);
10038 ssh2_pkt_send(ssh, pktout);
10042 static int ssh_connected(void *handle)
10044 Ssh ssh = (Ssh) handle;
10045 return ssh->s != NULL;
10048 static int ssh_sendok(void *handle)
10050 Ssh ssh = (Ssh) handle;
10051 return ssh->send_ok;
10054 static int ssh_ldisc(void *handle, int option)
10056 Ssh ssh = (Ssh) handle;
10057 if (option == LD_ECHO)
10058 return ssh->echoing;
10059 if (option == LD_EDIT)
10060 return ssh->editing;
10064 static void ssh_provide_ldisc(void *handle, void *ldisc)
10066 Ssh ssh = (Ssh) handle;
10067 ssh->ldisc = ldisc;
10070 static void ssh_provide_logctx(void *handle, void *logctx)
10072 Ssh ssh = (Ssh) handle;
10073 ssh->logctx = logctx;
10076 static int ssh_return_exitcode(void *handle)
10078 Ssh ssh = (Ssh) handle;
10079 if (ssh->s != NULL)
10082 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10086 * cfg_info for SSH is the currently running version of the
10087 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10089 static int ssh_cfg_info(void *handle)
10091 Ssh ssh = (Ssh) handle;
10092 return ssh->version;
10096 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10097 * that fails. This variable is the means by which scp.c can reach
10098 * into the SSH code and find out which one it got.
10100 extern int ssh_fallback_cmd(void *handle)
10102 Ssh ssh = (Ssh) handle;
10103 return ssh->fallback_cmd;
10106 Backend ssh_backend = {
10116 ssh_return_exitcode,
10120 ssh_provide_logctx,