27 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
28 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
29 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
30 #define SSH1_CMSG_USER 4 /* 0x4 */
31 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
32 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
33 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
34 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
35 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
36 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
37 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
38 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
39 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
40 #define SSH1_SMSG_FAILURE 15 /* 0xf */
41 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
42 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
43 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
44 #define SSH1_CMSG_EOF 19 /* 0x13 */
45 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
46 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
47 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
48 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
49 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
50 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
51 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
52 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
53 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
54 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
55 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
56 #define SSH1_MSG_IGNORE 32 /* 0x20 */
57 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
58 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
59 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
60 #define SSH1_MSG_DEBUG 36 /* 0x24 */
61 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
62 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
63 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
64 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
65 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
66 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
67 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
69 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
70 #define SSH1_AUTH_RSA 2 /* 0x2 */
71 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
72 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
73 #define SSH1_AUTH_TIS 5 /* 0x5 */
74 #define SSH1_AUTH_CCARD 16 /* 0x10 */
76 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
77 /* Mask for protoflags we will echo back to server if seen */
78 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
91 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
92 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
93 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
94 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
95 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
96 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
97 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
98 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
99 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
100 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
101 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
102 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
103 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
104 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
105 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
106 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
107 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
108 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
109 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
110 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
111 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
112 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
113 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
114 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
115 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
116 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
117 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
118 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
119 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
120 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
121 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
122 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
123 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
124 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
138 SSH2_PKTCTX_PUBLICKEY,
139 SSH2_PKTCTX_PASSWORD,
144 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
145 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
146 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
147 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
148 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
149 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
150 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
151 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
152 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
153 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
154 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
155 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
156 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
157 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
158 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
160 static const char *const ssh2_disconnect_reasons[] = {
162 "host not allowed to connect",
164 "key exchange failed",
165 "host authentication failed",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
179 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
180 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
181 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
182 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
184 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
187 * Various remote-bug flags.
189 #define BUG_CHOKES_ON_SSH1_IGNORE 1
190 #define BUG_SSH2_HMAC 2
191 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
192 #define BUG_CHOKES_ON_RSA 8
193 #define BUG_SSH2_RSA_PADDING 16
194 #define BUG_SSH2_DERIVEKEY 32
195 #define BUG_SSH2_REKEY 64
196 #define BUG_SSH2_PK_SESSIONID 128
197 #define BUG_SSH2_MAXPKT 256
198 #define BUG_CHOKES_ON_SSH2_IGNORE 512
201 * Codes for terminal modes.
202 * Most of these are the same in SSH-1 and SSH-2.
203 * This list is derived from RFC 4254 and
206 static const struct {
207 const char* const mode;
209 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
211 /* "V" prefix discarded for special characters relative to SSH specs */
212 { "INTR", 1, TTY_OP_CHAR },
213 { "QUIT", 2, TTY_OP_CHAR },
214 { "ERASE", 3, TTY_OP_CHAR },
215 { "KILL", 4, TTY_OP_CHAR },
216 { "EOF", 5, TTY_OP_CHAR },
217 { "EOL", 6, TTY_OP_CHAR },
218 { "EOL2", 7, TTY_OP_CHAR },
219 { "START", 8, TTY_OP_CHAR },
220 { "STOP", 9, TTY_OP_CHAR },
221 { "SUSP", 10, TTY_OP_CHAR },
222 { "DSUSP", 11, TTY_OP_CHAR },
223 { "REPRINT", 12, TTY_OP_CHAR },
224 { "WERASE", 13, TTY_OP_CHAR },
225 { "LNEXT", 14, TTY_OP_CHAR },
226 { "FLUSH", 15, TTY_OP_CHAR },
227 { "SWTCH", 16, TTY_OP_CHAR },
228 { "STATUS", 17, TTY_OP_CHAR },
229 { "DISCARD", 18, TTY_OP_CHAR },
230 { "IGNPAR", 30, TTY_OP_BOOL },
231 { "PARMRK", 31, TTY_OP_BOOL },
232 { "INPCK", 32, TTY_OP_BOOL },
233 { "ISTRIP", 33, TTY_OP_BOOL },
234 { "INLCR", 34, TTY_OP_BOOL },
235 { "IGNCR", 35, TTY_OP_BOOL },
236 { "ICRNL", 36, TTY_OP_BOOL },
237 { "IUCLC", 37, TTY_OP_BOOL },
238 { "IXON", 38, TTY_OP_BOOL },
239 { "IXANY", 39, TTY_OP_BOOL },
240 { "IXOFF", 40, TTY_OP_BOOL },
241 { "IMAXBEL", 41, TTY_OP_BOOL },
242 { "ISIG", 50, TTY_OP_BOOL },
243 { "ICANON", 51, TTY_OP_BOOL },
244 { "XCASE", 52, TTY_OP_BOOL },
245 { "ECHO", 53, TTY_OP_BOOL },
246 { "ECHOE", 54, TTY_OP_BOOL },
247 { "ECHOK", 55, TTY_OP_BOOL },
248 { "ECHONL", 56, TTY_OP_BOOL },
249 { "NOFLSH", 57, TTY_OP_BOOL },
250 { "TOSTOP", 58, TTY_OP_BOOL },
251 { "IEXTEN", 59, TTY_OP_BOOL },
252 { "ECHOCTL", 60, TTY_OP_BOOL },
253 { "ECHOKE", 61, TTY_OP_BOOL },
254 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
255 { "OPOST", 70, TTY_OP_BOOL },
256 { "OLCUC", 71, TTY_OP_BOOL },
257 { "ONLCR", 72, TTY_OP_BOOL },
258 { "OCRNL", 73, TTY_OP_BOOL },
259 { "ONOCR", 74, TTY_OP_BOOL },
260 { "ONLRET", 75, TTY_OP_BOOL },
261 { "CS7", 90, TTY_OP_BOOL },
262 { "CS8", 91, TTY_OP_BOOL },
263 { "PARENB", 92, TTY_OP_BOOL },
264 { "PARODD", 93, TTY_OP_BOOL }
267 /* Miscellaneous other tty-related constants. */
268 #define SSH_TTY_OP_END 0
269 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
270 #define SSH1_TTY_OP_ISPEED 192
271 #define SSH1_TTY_OP_OSPEED 193
272 #define SSH2_TTY_OP_ISPEED 128
273 #define SSH2_TTY_OP_OSPEED 129
275 /* Helper functions for parsing tty-related config. */
276 static unsigned int ssh_tty_parse_specchar(char *s)
281 ret = ctrlparse(s, &next);
282 if (!next) ret = s[0];
284 ret = 255; /* special value meaning "don't set" */
288 static unsigned int ssh_tty_parse_boolean(char *s)
290 if (stricmp(s, "yes") == 0 ||
291 stricmp(s, "on") == 0 ||
292 stricmp(s, "true") == 0 ||
293 stricmp(s, "+") == 0)
295 else if (stricmp(s, "no") == 0 ||
296 stricmp(s, "off") == 0 ||
297 stricmp(s, "false") == 0 ||
298 stricmp(s, "-") == 0)
299 return 0; /* false */
301 return (atoi(s) != 0);
304 #define translate(x) if (type == x) return #x
305 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
306 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
307 static char *ssh1_pkt_type(int type)
309 translate(SSH1_MSG_DISCONNECT);
310 translate(SSH1_SMSG_PUBLIC_KEY);
311 translate(SSH1_CMSG_SESSION_KEY);
312 translate(SSH1_CMSG_USER);
313 translate(SSH1_CMSG_AUTH_RSA);
314 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
315 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
316 translate(SSH1_CMSG_AUTH_PASSWORD);
317 translate(SSH1_CMSG_REQUEST_PTY);
318 translate(SSH1_CMSG_WINDOW_SIZE);
319 translate(SSH1_CMSG_EXEC_SHELL);
320 translate(SSH1_CMSG_EXEC_CMD);
321 translate(SSH1_SMSG_SUCCESS);
322 translate(SSH1_SMSG_FAILURE);
323 translate(SSH1_CMSG_STDIN_DATA);
324 translate(SSH1_SMSG_STDOUT_DATA);
325 translate(SSH1_SMSG_STDERR_DATA);
326 translate(SSH1_CMSG_EOF);
327 translate(SSH1_SMSG_EXIT_STATUS);
328 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
329 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
330 translate(SSH1_MSG_CHANNEL_DATA);
331 translate(SSH1_MSG_CHANNEL_CLOSE);
332 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
333 translate(SSH1_SMSG_X11_OPEN);
334 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
335 translate(SSH1_MSG_PORT_OPEN);
336 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
337 translate(SSH1_SMSG_AGENT_OPEN);
338 translate(SSH1_MSG_IGNORE);
339 translate(SSH1_CMSG_EXIT_CONFIRMATION);
340 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
341 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
342 translate(SSH1_MSG_DEBUG);
343 translate(SSH1_CMSG_REQUEST_COMPRESSION);
344 translate(SSH1_CMSG_AUTH_TIS);
345 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
346 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
347 translate(SSH1_CMSG_AUTH_CCARD);
348 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
349 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
352 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
360 translate(SSH2_MSG_DISCONNECT);
361 translate(SSH2_MSG_IGNORE);
362 translate(SSH2_MSG_UNIMPLEMENTED);
363 translate(SSH2_MSG_DEBUG);
364 translate(SSH2_MSG_SERVICE_REQUEST);
365 translate(SSH2_MSG_SERVICE_ACCEPT);
366 translate(SSH2_MSG_KEXINIT);
367 translate(SSH2_MSG_NEWKEYS);
368 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
369 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
371 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
375 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
377 translate(SSH2_MSG_USERAUTH_REQUEST);
378 translate(SSH2_MSG_USERAUTH_FAILURE);
379 translate(SSH2_MSG_USERAUTH_SUCCESS);
380 translate(SSH2_MSG_USERAUTH_BANNER);
381 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
382 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
383 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
384 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
385 translate(SSH2_MSG_GLOBAL_REQUEST);
386 translate(SSH2_MSG_REQUEST_SUCCESS);
387 translate(SSH2_MSG_REQUEST_FAILURE);
388 translate(SSH2_MSG_CHANNEL_OPEN);
389 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
390 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
391 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
392 translate(SSH2_MSG_CHANNEL_DATA);
393 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
394 translate(SSH2_MSG_CHANNEL_EOF);
395 translate(SSH2_MSG_CHANNEL_CLOSE);
396 translate(SSH2_MSG_CHANNEL_REQUEST);
397 translate(SSH2_MSG_CHANNEL_SUCCESS);
398 translate(SSH2_MSG_CHANNEL_FAILURE);
404 /* Enumeration values for fields in SSH-1 packets */
406 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
407 /* These values are for communicating relevant semantics of
408 * fields to the packet logging code. */
409 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
413 * Coroutine mechanics for the sillier bits of the code. If these
414 * macros look impenetrable to you, you might find it helpful to
417 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
419 * which explains the theory behind these macros.
421 * In particular, if you are getting `case expression not constant'
422 * errors when building with MS Visual Studio, this is because MS's
423 * Edit and Continue debugging feature causes their compiler to
424 * violate ANSI C. To disable Edit and Continue debugging:
426 * - right-click ssh.c in the FileView
428 * - select the C/C++ tab and the General category
429 * - under `Debug info:', select anything _other_ than `Program
430 * Database for Edit and Continue'.
432 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
435 if (!ssh->t) ssh->t = snew(struct t); \
437 #define crFinish(z) } *crLine = 0; return (z); }
438 #define crFinishV } *crLine = 0; return; }
439 #define crReturn(z) \
441 *crLine =__LINE__; return (z); case __LINE__:;\
445 *crLine=__LINE__; return; case __LINE__:;\
447 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
448 #define crStopV do{ *crLine = 0; return; }while(0)
449 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
450 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
452 typedef struct ssh_tag *Ssh;
455 static struct Packet *ssh1_pkt_init(int pkt_type);
456 static struct Packet *ssh2_pkt_init(int pkt_type);
457 static void ssh_pkt_ensure(struct Packet *, int length);
458 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
459 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
460 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
461 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
462 static void ssh_pkt_addstring_start(struct Packet *);
463 static void ssh_pkt_addstring_str(struct Packet *, char *data);
464 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
465 static void ssh_pkt_addstring(struct Packet *, char *data);
466 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
467 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
468 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
469 static int ssh2_pkt_construct(Ssh, struct Packet *);
470 static void ssh2_pkt_send(Ssh, struct Packet *);
471 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
472 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
473 struct Packet *pktin);
474 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
475 struct Packet *pktin);
478 * Buffer management constants. There are several of these for
479 * various different purposes:
481 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
482 * on a local data stream before we throttle the whole SSH
483 * connection (in SSH-1 only). Throttling the whole connection is
484 * pretty drastic so we set this high in the hope it won't
487 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
488 * on the SSH connection itself before we defensively throttle
489 * _all_ local data streams. This is pretty drastic too (though
490 * thankfully unlikely in SSH-2 since the window mechanism should
491 * ensure that the server never has any need to throttle its end
492 * of the connection), so we set this high as well.
494 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
497 * - OUR_V2_BIGWIN is the window size we advertise for the only
498 * channel in a simple connection. It must be <= INT_MAX.
500 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
501 * to the remote side. This actually has nothing to do with the
502 * size of the _packet_, but is instead a limit on the amount
503 * of data we're willing to receive in a single SSH2 channel
506 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
507 * _packet_ we're prepared to cope with. It must be a multiple
508 * of the cipher block size, and must be at least 35000.
511 #define SSH1_BUFFER_LIMIT 32768
512 #define SSH_MAX_BACKLOG 32768
513 #define OUR_V2_WINSIZE 16384
514 #define OUR_V2_BIGWIN 0x7fffffff
515 #define OUR_V2_MAXPKT 0x4000UL
516 #define OUR_V2_PACKETLIMIT 0x9000UL
518 /* Maximum length of passwords/passphrases (arbitrary) */
519 #define SSH_MAX_PASSWORD_LEN 100
521 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
523 const static struct ssh_mac *macs[] = {
524 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
526 const static struct ssh_mac *buggymacs[] = {
527 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
530 static void *ssh_comp_none_init(void)
534 static void ssh_comp_none_cleanup(void *handle)
537 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
538 unsigned char **outblock, int *outlen)
542 static int ssh_comp_none_disable(void *handle)
546 const static struct ssh_compress ssh_comp_none = {
548 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
549 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
550 ssh_comp_none_disable, NULL
552 extern const struct ssh_compress ssh_zlib;
553 const static struct ssh_compress *compressions[] = {
554 &ssh_zlib, &ssh_comp_none
557 enum { /* channel types */
562 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
566 * little structure to keep track of outstanding WINDOW_ADJUSTs
574 * 2-3-4 tree storing channels.
577 Ssh ssh; /* pointer back to main context */
578 unsigned remoteid, localid;
580 /* True if we opened this channel but server hasn't confirmed. */
583 * In SSH-1, this value contains four bits:
585 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
586 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
587 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
588 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
590 * A channel is completely finished with when all four bits are set.
595 * This flag indicates that a close is pending on the outgoing
596 * side of the channel: that is, wherever we're getting the data
597 * for this channel has sent us some data followed by EOF. We
598 * can't actually close the channel until we've finished sending
599 * the data, so we set this flag instead to remind us to
600 * initiate the closing process once our buffer is clear.
605 * True if this channel is causing the underlying connection to be
610 struct ssh2_data_channel {
612 unsigned remwindow, remmaxpkt;
613 /* locwindow is signed so we can cope with excess data. */
614 int locwindow, locmaxwin;
616 * remlocwin is the amount of local window that we think
617 * the remote end had available to it after it sent the
618 * last data packet or window adjust ack.
622 * These store the list of window adjusts that haven't
625 struct winadj *winadj_head, *winadj_tail;
626 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
630 struct ssh_agent_channel {
631 unsigned char *message;
632 unsigned char msglen[4];
633 unsigned lensofar, totallen;
635 struct ssh_x11_channel {
638 struct ssh_pfd_channel {
645 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
646 * use this structure in different ways, reflecting SSH-2's
647 * altogether saner approach to port forwarding.
649 * In SSH-1, you arrange a remote forwarding by sending the server
650 * the remote port number, and the local destination host:port.
651 * When a connection comes in, the server sends you back that
652 * host:port pair, and you connect to it. This is a ready-made
653 * security hole if you're not on the ball: a malicious server
654 * could send you back _any_ host:port pair, so if you trustingly
655 * connect to the address it gives you then you've just opened the
656 * entire inside of your corporate network just by connecting
657 * through it to a dodgy SSH server. Hence, we must store a list of
658 * host:port pairs we _are_ trying to forward to, and reject a
659 * connection request from the server if it's not in the list.
661 * In SSH-2, each side of the connection minds its own business and
662 * doesn't send unnecessary information to the other. You arrange a
663 * remote forwarding by sending the server just the remote port
664 * number. When a connection comes in, the server tells you which
665 * of its ports was connected to; and _you_ have to remember what
666 * local host:port pair went with that port number.
668 * Hence, in SSH-1 this structure is indexed by destination
669 * host:port pair, whereas in SSH-2 it is indexed by source port.
671 struct ssh_portfwd; /* forward declaration */
673 struct ssh_rportfwd {
674 unsigned sport, dport;
677 struct ssh_portfwd *pfrec;
679 #define free_rportfwd(pf) ( \
680 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
683 * Separately to the rportfwd tree (which is for looking up port
684 * open requests from the server), a tree of _these_ structures is
685 * used to keep track of all the currently open port forwardings,
686 * so that we can reconfigure in mid-session if the user requests
690 enum { DESTROY, KEEP, CREATE } status;
692 unsigned sport, dport;
695 struct ssh_rportfwd *remote;
699 #define free_portfwd(pf) ( \
700 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
701 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
704 long length; /* length of `data' actually used */
705 long forcepad; /* SSH-2: force padding to at least this length */
706 int type; /* only used for incoming packets */
707 unsigned long sequence; /* SSH-2 incoming sequence number */
708 unsigned char *data; /* allocated storage */
709 unsigned char *body; /* offset of payload within `data' */
710 long savedpos; /* temporary index into `data' (for strings) */
711 long maxlen; /* amount of storage allocated for `data' */
712 long encrypted_len; /* for SSH-2 total-size counting */
715 * State associated with packet logging
719 struct logblank_t *blanks;
722 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
723 struct Packet *pktin);
724 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
725 struct Packet *pktin);
726 static void ssh1_protocol_setup(Ssh ssh);
727 static void ssh2_protocol_setup(Ssh ssh);
728 static void ssh_size(void *handle, int width, int height);
729 static void ssh_special(void *handle, Telnet_Special);
730 static int ssh2_try_send(struct ssh_channel *c);
731 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
732 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
733 static void ssh2_set_window(struct ssh_channel *c, int newwin);
734 static int ssh_sendbuffer(void *handle);
735 static int ssh_do_close(Ssh ssh, int notify_exit);
736 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
737 static int ssh2_pkt_getbool(struct Packet *pkt);
738 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
739 static void ssh2_timer(void *ctx, long now);
740 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
741 struct Packet *pktin);
743 struct rdpkt1_state_tag {
744 long len, pad, biglen, to_read;
745 unsigned long realcrc, gotcrc;
749 struct Packet *pktin;
752 struct rdpkt2_state_tag {
753 long len, pad, payload, packetlen, maclen;
756 unsigned long incoming_sequence;
757 struct Packet *pktin;
760 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
761 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
763 struct queued_handler;
764 struct queued_handler {
766 chandler_fn_t handler;
768 struct queued_handler *next;
772 const struct plug_function_table *fn;
773 /* the above field _must_ be first in the structure */
783 unsigned char session_key[32];
785 int v1_remote_protoflags;
786 int v1_local_protoflags;
787 int agentfwd_enabled;
790 const struct ssh_cipher *cipher;
793 const struct ssh2_cipher *cscipher, *sccipher;
794 void *cs_cipher_ctx, *sc_cipher_ctx;
795 const struct ssh_mac *csmac, *scmac;
796 void *cs_mac_ctx, *sc_mac_ctx;
797 const struct ssh_compress *cscomp, *sccomp;
798 void *cs_comp_ctx, *sc_comp_ctx;
799 const struct ssh_kex *kex;
800 const struct ssh_signkey *hostkey;
801 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
802 int v2_session_id_len;
808 int echoing, editing;
812 int ospeed, ispeed; /* temporaries */
813 int term_width, term_height;
815 tree234 *channels; /* indexed by local id */
816 struct ssh_channel *mainchan; /* primary session channel */
817 int ncmode; /* is primary channel direct-tcpip? */
822 tree234 *rportfwds, *portfwds;
826 SSH_STATE_BEFORE_SIZE,
832 int size_needed, eof_needed;
834 struct Packet **queue;
835 int queuelen, queuesize;
837 unsigned char *deferred_send_data;
838 int deferred_len, deferred_size;
841 * Gross hack: pscp will try to start SFTP but fall back to
842 * scp1 if that fails. This variable is the means by which
843 * scp.c can reach into the SSH code and find out which one it
848 bufchain banner; /* accumulates banners during do_ssh2_authconn */
853 struct X11Display *x11disp;
856 int conn_throttle_count;
859 int v1_stdout_throttling;
860 unsigned long v2_outgoing_sequence;
862 int ssh1_rdpkt_crstate;
863 int ssh2_rdpkt_crstate;
864 int do_ssh_init_crstate;
865 int ssh_gotdata_crstate;
866 int do_ssh1_login_crstate;
867 int do_ssh1_connection_crstate;
868 int do_ssh2_transport_crstate;
869 int do_ssh2_authconn_crstate;
871 void *do_ssh_init_state;
872 void *do_ssh1_login_state;
873 void *do_ssh2_transport_state;
874 void *do_ssh2_authconn_state;
876 struct rdpkt1_state_tag rdpkt1_state;
877 struct rdpkt2_state_tag rdpkt2_state;
879 /* SSH-1 and SSH-2 use this for different things, but both use it */
880 int protocol_initial_phase_done;
882 void (*protocol) (Ssh ssh, void *vin, int inlen,
884 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
887 * We maintain a full _copy_ of a Config structure here, not
888 * merely a pointer to it. That way, when we're passed a new
889 * one for reconfiguration, we can check the differences and
890 * potentially reconfigure port forwardings etc in mid-session.
895 * Used to transfer data back from async callbacks.
897 void *agent_response;
898 int agent_response_len;
902 * The SSH connection can be set as `frozen', meaning we are
903 * not currently accepting incoming data from the network. This
904 * is slightly more serious than setting the _socket_ as
905 * frozen, because we may already have had data passed to us
906 * from the network which we need to delay processing until
907 * after the freeze is lifted, so we also need a bufchain to
911 bufchain queued_incoming_data;
914 * Dispatch table for packet types that we may have to deal
917 handler_fn_t packet_dispatch[256];
920 * Queues of one-off handler functions for success/failure
921 * indications from a request.
923 struct queued_handler *qhead, *qtail;
926 * This module deals with sending keepalives.
931 * Track incoming and outgoing data sizes and time, for
934 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
935 unsigned long max_data_size;
937 long next_rekey, last_rekey;
938 char *deferred_rekey_reason; /* points to STATIC string; don't free */
941 * Fully qualified host name, which we need if doing GSSAPI.
946 #define logevent(s) logevent(ssh->frontend, s)
948 /* logevent, only printf-formatted. */
949 static void logeventf(Ssh ssh, const char *fmt, ...)
955 buf = dupvprintf(fmt, ap);
961 #define bombout(msg) \
963 char *text = dupprintf msg; \
964 ssh_do_close(ssh, FALSE); \
966 connection_fatal(ssh->frontend, "%s", text); \
970 /* Functions to leave bits out of the SSH packet log file. */
972 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
974 if (ssh->cfg.logomitpass)
975 pkt->logmode = blanktype;
978 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
980 if (ssh->cfg.logomitdata)
981 pkt->logmode = blanktype;
984 static void end_log_omission(Ssh ssh, struct Packet *pkt)
986 pkt->logmode = PKTLOG_EMIT;
989 /* Helper function for common bits of parsing cfg.ttymodes. */
990 static void parse_ttymodes(Ssh ssh, char *modes,
991 void (*do_mode)(void *data, char *mode, char *val),
995 char *t = strchr(modes, '\t');
996 char *m = snewn(t-modes+1, char);
998 strncpy(m, modes, t-modes);
1001 val = get_ttymode(ssh->frontend, m);
1005 do_mode(data, m, val);
1008 modes += strlen(modes) + 1;
1012 static int ssh_channelcmp(void *av, void *bv)
1014 struct ssh_channel *a = (struct ssh_channel *) av;
1015 struct ssh_channel *b = (struct ssh_channel *) bv;
1016 if (a->localid < b->localid)
1018 if (a->localid > b->localid)
1022 static int ssh_channelfind(void *av, void *bv)
1024 unsigned *a = (unsigned *) av;
1025 struct ssh_channel *b = (struct ssh_channel *) bv;
1026 if (*a < b->localid)
1028 if (*a > b->localid)
1033 static int ssh_rportcmp_ssh1(void *av, void *bv)
1035 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1036 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1038 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1039 return i < 0 ? -1 : +1;
1040 if (a->dport > b->dport)
1042 if (a->dport < b->dport)
1047 static int ssh_rportcmp_ssh2(void *av, void *bv)
1049 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1050 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1052 if (a->sport > b->sport)
1054 if (a->sport < b->sport)
1060 * Special form of strcmp which can cope with NULL inputs. NULL is
1061 * defined to sort before even the empty string.
1063 static int nullstrcmp(const char *a, const char *b)
1065 if (a == NULL && b == NULL)
1071 return strcmp(a, b);
1074 static int ssh_portcmp(void *av, void *bv)
1076 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1077 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1079 if (a->type > b->type)
1081 if (a->type < b->type)
1083 if (a->addressfamily > b->addressfamily)
1085 if (a->addressfamily < b->addressfamily)
1087 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1088 return i < 0 ? -1 : +1;
1089 if (a->sport > b->sport)
1091 if (a->sport < b->sport)
1093 if (a->type != 'D') {
1094 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1095 return i < 0 ? -1 : +1;
1096 if (a->dport > b->dport)
1098 if (a->dport < b->dport)
1104 static int alloc_channel_id(Ssh ssh)
1106 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1107 unsigned low, high, mid;
1109 struct ssh_channel *c;
1112 * First-fit allocation of channel numbers: always pick the
1113 * lowest unused one. To do this, binary-search using the
1114 * counted B-tree to find the largest channel ID which is in a
1115 * contiguous sequence from the beginning. (Precisely
1116 * everything in that sequence must have ID equal to its tree
1117 * index plus CHANNEL_NUMBER_OFFSET.)
1119 tsize = count234(ssh->channels);
1123 while (high - low > 1) {
1124 mid = (high + low) / 2;
1125 c = index234(ssh->channels, mid);
1126 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1127 low = mid; /* this one is fine */
1129 high = mid; /* this one is past it */
1132 * Now low points to either -1, or the tree index of the
1133 * largest ID in the initial sequence.
1136 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1137 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1139 return low + 1 + CHANNEL_NUMBER_OFFSET;
1142 static void c_write_stderr(int trusted, const char *buf, int len)
1145 for (i = 0; i < len; i++)
1146 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1147 fputc(buf[i], stderr);
1150 static void c_write(Ssh ssh, const char *buf, int len)
1152 if (flags & FLAG_STDERR)
1153 c_write_stderr(1, buf, len);
1155 from_backend(ssh->frontend, 1, buf, len);
1158 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1160 if (flags & FLAG_STDERR)
1161 c_write_stderr(0, buf, len);
1163 from_backend_untrusted(ssh->frontend, buf, len);
1166 static void c_write_str(Ssh ssh, const char *buf)
1168 c_write(ssh, buf, strlen(buf));
1171 static void ssh_free_packet(struct Packet *pkt)
1176 static struct Packet *ssh_new_packet(void)
1178 struct Packet *pkt = snew(struct Packet);
1180 pkt->body = pkt->data = NULL;
1182 pkt->logmode = PKTLOG_EMIT;
1190 * Collect incoming data in the incoming packet buffer.
1191 * Decipher and verify the packet when it is completely read.
1192 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1193 * Update the *data and *datalen variables.
1194 * Return a Packet structure when a packet is completed.
1196 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1198 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1200 crBegin(ssh->ssh1_rdpkt_crstate);
1202 st->pktin = ssh_new_packet();
1204 st->pktin->type = 0;
1205 st->pktin->length = 0;
1207 for (st->i = st->len = 0; st->i < 4; st->i++) {
1208 while ((*datalen) == 0)
1210 st->len = (st->len << 8) + **data;
1211 (*data)++, (*datalen)--;
1214 st->pad = 8 - (st->len % 8);
1215 st->biglen = st->len + st->pad;
1216 st->pktin->length = st->len - 5;
1218 if (st->biglen < 0) {
1219 bombout(("Extremely large packet length from server suggests"
1220 " data stream corruption"));
1221 ssh_free_packet(st->pktin);
1225 st->pktin->maxlen = st->biglen;
1226 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1228 st->to_read = st->biglen;
1229 st->p = st->pktin->data;
1230 while (st->to_read > 0) {
1231 st->chunk = st->to_read;
1232 while ((*datalen) == 0)
1234 if (st->chunk > (*datalen))
1235 st->chunk = (*datalen);
1236 memcpy(st->p, *data, st->chunk);
1238 *datalen -= st->chunk;
1240 st->to_read -= st->chunk;
1243 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1244 st->biglen, NULL)) {
1245 bombout(("Network attack (CRC compensation) detected!"));
1246 ssh_free_packet(st->pktin);
1251 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1253 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1254 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1255 if (st->gotcrc != st->realcrc) {
1256 bombout(("Incorrect CRC received on packet"));
1257 ssh_free_packet(st->pktin);
1261 st->pktin->body = st->pktin->data + st->pad + 1;
1262 st->pktin->savedpos = 0;
1264 if (ssh->v1_compressing) {
1265 unsigned char *decompblk;
1267 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1268 st->pktin->body - 1, st->pktin->length + 1,
1269 &decompblk, &decomplen)) {
1270 bombout(("Zlib decompression encountered invalid data"));
1271 ssh_free_packet(st->pktin);
1275 if (st->pktin->maxlen < st->pad + decomplen) {
1276 st->pktin->maxlen = st->pad + decomplen;
1277 st->pktin->data = sresize(st->pktin->data,
1278 st->pktin->maxlen + APIEXTRA,
1280 st->pktin->body = st->pktin->data + st->pad + 1;
1283 memcpy(st->pktin->body - 1, decompblk, decomplen);
1285 st->pktin->length = decomplen - 1;
1288 st->pktin->type = st->pktin->body[-1];
1291 * Log incoming packet, possibly omitting sensitive fields.
1295 struct logblank_t blank;
1296 if (ssh->cfg.logomitdata) {
1297 int do_blank = FALSE, blank_prefix = 0;
1298 /* "Session data" packets - omit the data field */
1299 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1300 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1301 do_blank = TRUE; blank_prefix = 4;
1302 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1303 do_blank = TRUE; blank_prefix = 8;
1306 blank.offset = blank_prefix;
1307 blank.len = st->pktin->length;
1308 blank.type = PKTLOG_OMIT;
1312 log_packet(ssh->logctx,
1313 PKT_INCOMING, st->pktin->type,
1314 ssh1_pkt_type(st->pktin->type),
1315 st->pktin->body, st->pktin->length,
1316 nblanks, &blank, NULL);
1319 crFinish(st->pktin);
1322 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1324 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1326 crBegin(ssh->ssh2_rdpkt_crstate);
1328 st->pktin = ssh_new_packet();
1330 st->pktin->type = 0;
1331 st->pktin->length = 0;
1333 st->cipherblk = ssh->sccipher->blksize;
1336 if (st->cipherblk < 8)
1338 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1340 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1343 * When dealing with a CBC-mode cipher, we want to avoid the
1344 * possibility of an attacker's tweaking the ciphertext stream
1345 * so as to cause us to feed the same block to the block
1346 * cipher more than once and thus leak information
1347 * (VU#958563). The way we do this is not to take any
1348 * decisions on the basis of anything we've decrypted until
1349 * we've verified it with a MAC. That includes the packet
1350 * length, so we just read data and check the MAC repeatedly,
1351 * and when the MAC passes, see if the length we've got is
1355 /* May as well allocate the whole lot now. */
1356 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1359 /* Read an amount corresponding to the MAC. */
1360 for (st->i = 0; st->i < st->maclen; st->i++) {
1361 while ((*datalen) == 0)
1363 st->pktin->data[st->i] = *(*data)++;
1369 unsigned char seq[4];
1370 ssh->scmac->start(ssh->sc_mac_ctx);
1371 PUT_32BIT(seq, st->incoming_sequence);
1372 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1375 for (;;) { /* Once around this loop per cipher block. */
1376 /* Read another cipher-block's worth, and tack it onto the end. */
1377 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1378 while ((*datalen) == 0)
1380 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1383 /* Decrypt one more block (a little further back in the stream). */
1384 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1385 st->pktin->data + st->packetlen,
1387 /* Feed that block to the MAC. */
1388 ssh->scmac->bytes(ssh->sc_mac_ctx,
1389 st->pktin->data + st->packetlen, st->cipherblk);
1390 st->packetlen += st->cipherblk;
1391 /* See if that gives us a valid packet. */
1392 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1393 st->pktin->data + st->packetlen) &&
1394 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1396 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1397 bombout(("No valid incoming packet found"));
1398 ssh_free_packet(st->pktin);
1402 st->pktin->maxlen = st->packetlen + st->maclen;
1403 st->pktin->data = sresize(st->pktin->data,
1404 st->pktin->maxlen + APIEXTRA,
1407 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1410 * Acquire and decrypt the first block of the packet. This will
1411 * contain the length and padding details.
1413 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1414 while ((*datalen) == 0)
1416 st->pktin->data[st->i] = *(*data)++;
1421 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1422 st->pktin->data, st->cipherblk);
1425 * Now get the length figure.
1427 st->len = GET_32BIT(st->pktin->data);
1430 * _Completely_ silly lengths should be stomped on before they
1431 * do us any more damage.
1433 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1434 (st->len + 4) % st->cipherblk != 0) {
1435 bombout(("Incoming packet was garbled on decryption"));
1436 ssh_free_packet(st->pktin);
1441 * So now we can work out the total packet length.
1443 st->packetlen = st->len + 4;
1446 * Allocate memory for the rest of the packet.
1448 st->pktin->maxlen = st->packetlen + st->maclen;
1449 st->pktin->data = sresize(st->pktin->data,
1450 st->pktin->maxlen + APIEXTRA,
1454 * Read and decrypt the remainder of the packet.
1456 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1458 while ((*datalen) == 0)
1460 st->pktin->data[st->i] = *(*data)++;
1463 /* Decrypt everything _except_ the MAC. */
1465 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1466 st->pktin->data + st->cipherblk,
1467 st->packetlen - st->cipherblk);
1473 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1474 st->len + 4, st->incoming_sequence)) {
1475 bombout(("Incorrect MAC received on packet"));
1476 ssh_free_packet(st->pktin);
1480 /* Get and sanity-check the amount of random padding. */
1481 st->pad = st->pktin->data[4];
1482 if (st->pad < 4 || st->len - st->pad < 1) {
1483 bombout(("Invalid padding length on received packet"));
1484 ssh_free_packet(st->pktin);
1488 * This enables us to deduce the payload length.
1490 st->payload = st->len - st->pad - 1;
1492 st->pktin->length = st->payload + 5;
1493 st->pktin->encrypted_len = st->packetlen;
1495 st->pktin->sequence = st->incoming_sequence++;
1498 * Decompress packet payload.
1501 unsigned char *newpayload;
1504 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1505 st->pktin->data + 5, st->pktin->length - 5,
1506 &newpayload, &newlen)) {
1507 if (st->pktin->maxlen < newlen + 5) {
1508 st->pktin->maxlen = newlen + 5;
1509 st->pktin->data = sresize(st->pktin->data,
1510 st->pktin->maxlen + APIEXTRA,
1513 st->pktin->length = 5 + newlen;
1514 memcpy(st->pktin->data + 5, newpayload, newlen);
1519 st->pktin->savedpos = 6;
1520 st->pktin->body = st->pktin->data;
1521 st->pktin->type = st->pktin->data[5];
1524 * Log incoming packet, possibly omitting sensitive fields.
1528 struct logblank_t blank;
1529 if (ssh->cfg.logomitdata) {
1530 int do_blank = FALSE, blank_prefix = 0;
1531 /* "Session data" packets - omit the data field */
1532 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1533 do_blank = TRUE; blank_prefix = 8;
1534 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1535 do_blank = TRUE; blank_prefix = 12;
1538 blank.offset = blank_prefix;
1539 blank.len = (st->pktin->length-6) - blank_prefix;
1540 blank.type = PKTLOG_OMIT;
1544 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1545 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1547 st->pktin->data+6, st->pktin->length-6,
1548 nblanks, &blank, &st->pktin->sequence);
1551 crFinish(st->pktin);
1554 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1556 int pad, biglen, i, pktoffs;
1560 * XXX various versions of SC (including 8.8.4) screw up the
1561 * register allocation in this function and use the same register
1562 * (D6) for len and as a temporary, with predictable results. The
1563 * following sledgehammer prevents this.
1570 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1571 ssh1_pkt_type(pkt->data[12]),
1572 pkt->body, pkt->length - (pkt->body - pkt->data),
1573 pkt->nblanks, pkt->blanks, NULL);
1574 sfree(pkt->blanks); pkt->blanks = NULL;
1577 if (ssh->v1_compressing) {
1578 unsigned char *compblk;
1580 zlib_compress_block(ssh->cs_comp_ctx,
1581 pkt->data + 12, pkt->length - 12,
1582 &compblk, &complen);
1583 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1584 memcpy(pkt->data + 12, compblk, complen);
1586 pkt->length = complen + 12;
1589 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1591 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1592 pad = 8 - (len % 8);
1594 biglen = len + pad; /* len(padding+type+data+CRC) */
1596 for (i = pktoffs; i < 4+8; i++)
1597 pkt->data[i] = random_byte();
1598 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1599 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1600 PUT_32BIT(pkt->data + pktoffs, len);
1603 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1604 pkt->data + pktoffs + 4, biglen);
1606 if (offset_p) *offset_p = pktoffs;
1607 return biglen + 4; /* len(length+padding+type+data+CRC) */
1610 static int s_write(Ssh ssh, void *data, int len)
1613 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1615 return sk_write(ssh->s, (char *)data, len);
1618 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1620 int len, backlog, offset;
1621 len = s_wrpkt_prepare(ssh, pkt, &offset);
1622 backlog = s_write(ssh, pkt->data + offset, len);
1623 if (backlog > SSH_MAX_BACKLOG)
1624 ssh_throttle_all(ssh, 1, backlog);
1625 ssh_free_packet(pkt);
1628 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1631 len = s_wrpkt_prepare(ssh, pkt, &offset);
1632 if (ssh->deferred_len + len > ssh->deferred_size) {
1633 ssh->deferred_size = ssh->deferred_len + len + 128;
1634 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1638 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1639 pkt->data + offset, len);
1640 ssh->deferred_len += len;
1641 ssh_free_packet(pkt);
1645 * Construct a SSH-1 packet with the specified contents.
1646 * (This all-at-once interface used to be the only one, but now SSH-1
1647 * packets can also be constructed incrementally.)
1649 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1655 pkt = ssh1_pkt_init(pkttype);
1657 while ((argtype = va_arg(ap, int)) != PKT_END) {
1658 unsigned char *argp, argchar;
1660 unsigned long argint;
1663 /* Actual fields in the packet */
1665 argint = va_arg(ap, int);
1666 ssh_pkt_adduint32(pkt, argint);
1669 argchar = (unsigned char) va_arg(ap, int);
1670 ssh_pkt_addbyte(pkt, argchar);
1673 argp = va_arg(ap, unsigned char *);
1674 arglen = va_arg(ap, int);
1675 ssh_pkt_adddata(pkt, argp, arglen);
1678 sargp = va_arg(ap, char *);
1679 ssh_pkt_addstring(pkt, sargp);
1682 bn = va_arg(ap, Bignum);
1683 ssh1_pkt_addmp(pkt, bn);
1685 /* Tokens for modifications to packet logging */
1687 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1690 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1693 end_log_omission(ssh, pkt);
1701 static void send_packet(Ssh ssh, int pkttype, ...)
1705 va_start(ap, pkttype);
1706 pkt = construct_packet(ssh, pkttype, ap);
1711 static void defer_packet(Ssh ssh, int pkttype, ...)
1715 va_start(ap, pkttype);
1716 pkt = construct_packet(ssh, pkttype, ap);
1718 s_wrpkt_defer(ssh, pkt);
1721 static int ssh_versioncmp(char *a, char *b)
1724 unsigned long av, bv;
1726 av = strtoul(a, &ae, 10);
1727 bv = strtoul(b, &be, 10);
1729 return (av < bv ? -1 : +1);
1734 av = strtoul(ae, &ae, 10);
1735 bv = strtoul(be, &be, 10);
1737 return (av < bv ? -1 : +1);
1742 * Utility routines for putting an SSH-protocol `string' and
1743 * `uint32' into a hash state.
1745 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1747 unsigned char lenblk[4];
1748 PUT_32BIT(lenblk, len);
1749 h->bytes(s, lenblk, 4);
1750 h->bytes(s, str, len);
1753 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1755 unsigned char intblk[4];
1756 PUT_32BIT(intblk, i);
1757 h->bytes(s, intblk, 4);
1761 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1763 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1765 if (pkt->maxlen < length) {
1766 unsigned char *body = pkt->body;
1767 int offset = body ? body - pkt->data : 0;
1768 pkt->maxlen = length + 256;
1769 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1770 if (body) pkt->body = pkt->data + offset;
1773 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1775 if (pkt->logmode != PKTLOG_EMIT) {
1777 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1779 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1780 (pkt->body - pkt->data);
1781 pkt->blanks[pkt->nblanks-1].len = len;
1782 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1785 ssh_pkt_ensure(pkt, pkt->length);
1786 memcpy(pkt->data + pkt->length - len, data, len);
1788 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1790 ssh_pkt_adddata(pkt, &byte, 1);
1792 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1794 ssh_pkt_adddata(pkt, &value, 1);
1796 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1799 PUT_32BIT(x, value);
1800 ssh_pkt_adddata(pkt, x, 4);
1802 static void ssh_pkt_addstring_start(struct Packet *pkt)
1804 ssh_pkt_adduint32(pkt, 0);
1805 pkt->savedpos = pkt->length;
1807 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1809 ssh_pkt_adddata(pkt, data, strlen(data));
1810 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1812 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1814 ssh_pkt_adddata(pkt, data, len);
1815 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1817 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1819 ssh_pkt_addstring_start(pkt);
1820 ssh_pkt_addstring_str(pkt, data);
1822 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1824 int len = ssh1_bignum_length(b);
1825 unsigned char *data = snewn(len, unsigned char);
1826 (void) ssh1_write_bignum(data, b);
1827 ssh_pkt_adddata(pkt, data, len);
1830 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1833 int i, n = (bignum_bitcount(b) + 7) / 8;
1834 p = snewn(n + 1, unsigned char);
1836 for (i = 1; i <= n; i++)
1837 p[i] = bignum_byte(b, n - i);
1839 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1841 memmove(p, p + i, n + 1 - i);
1845 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1849 p = ssh2_mpint_fmt(b, &len);
1850 ssh_pkt_addstring_start(pkt);
1851 ssh_pkt_addstring_data(pkt, (char *)p, len);
1855 static struct Packet *ssh1_pkt_init(int pkt_type)
1857 struct Packet *pkt = ssh_new_packet();
1858 pkt->length = 4 + 8; /* space for length + max padding */
1859 ssh_pkt_addbyte(pkt, pkt_type);
1860 pkt->body = pkt->data + pkt->length;
1864 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1865 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1866 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1867 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1868 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1869 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1870 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1871 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1872 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1874 static struct Packet *ssh2_pkt_init(int pkt_type)
1876 struct Packet *pkt = ssh_new_packet();
1877 pkt->length = 5; /* space for packet length + padding length */
1879 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1880 pkt->body = pkt->data + pkt->length; /* after packet type */
1885 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1886 * put the MAC on it. Final packet, ready to be sent, is stored in
1887 * pkt->data. Total length is returned.
1889 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1891 int cipherblk, maclen, padding, i;
1894 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1895 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1896 pkt->body, pkt->length - (pkt->body - pkt->data),
1897 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1898 sfree(pkt->blanks); pkt->blanks = NULL;
1902 * Compress packet payload.
1905 unsigned char *newpayload;
1908 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1910 &newpayload, &newlen)) {
1912 ssh2_pkt_adddata(pkt, newpayload, newlen);
1918 * Add padding. At least four bytes, and must also bring total
1919 * length (minus MAC) up to a multiple of the block size.
1920 * If pkt->forcepad is set, make sure the packet is at least that size
1923 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1924 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1926 if (pkt->length + padding < pkt->forcepad)
1927 padding = pkt->forcepad - pkt->length;
1929 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1930 assert(padding <= 255);
1931 maclen = ssh->csmac ? ssh->csmac->len : 0;
1932 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1933 pkt->data[4] = padding;
1934 for (i = 0; i < padding; i++)
1935 pkt->data[pkt->length + i] = random_byte();
1936 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1938 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1939 pkt->length + padding,
1940 ssh->v2_outgoing_sequence);
1941 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1944 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1945 pkt->data, pkt->length + padding);
1947 pkt->encrypted_len = pkt->length + padding;
1949 /* Ready-to-send packet starts at pkt->data. We return length. */
1950 return pkt->length + padding + maclen;
1954 * Routines called from the main SSH code to send packets. There
1955 * are quite a few of these, because we have two separate
1956 * mechanisms for delaying the sending of packets:
1958 * - In order to send an IGNORE message and a password message in
1959 * a single fixed-length blob, we require the ability to
1960 * concatenate the encrypted forms of those two packets _into_ a
1961 * single blob and then pass it to our <network.h> transport
1962 * layer in one go. Hence, there's a deferment mechanism which
1963 * works after packet encryption.
1965 * - In order to avoid sending any connection-layer messages
1966 * during repeat key exchange, we have to queue up any such
1967 * outgoing messages _before_ they are encrypted (and in
1968 * particular before they're allocated sequence numbers), and
1969 * then send them once we've finished.
1971 * I call these mechanisms `defer' and `queue' respectively, so as
1972 * to distinguish them reasonably easily.
1974 * The functions send_noqueue() and defer_noqueue() free the packet
1975 * structure they are passed. Every outgoing packet goes through
1976 * precisely one of these functions in its life; packets passed to
1977 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1978 * these or get queued, and then when the queue is later emptied
1979 * the packets are all passed to defer_noqueue().
1981 * When using a CBC-mode cipher, it's necessary to ensure that an
1982 * attacker can't provide data to be encrypted using an IV that they
1983 * know. We ensure this by prefixing each packet that might contain
1984 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1985 * mechanism, so in this case send_noqueue() ends up redirecting to
1986 * defer_noqueue(). If you don't like this inefficiency, don't use
1990 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1991 static void ssh_pkt_defersend(Ssh);
1994 * Send an SSH-2 packet immediately, without queuing or deferring.
1996 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2000 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2001 /* We need to send two packets, so use the deferral mechanism. */
2002 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2003 ssh_pkt_defersend(ssh);
2006 len = ssh2_pkt_construct(ssh, pkt);
2007 backlog = s_write(ssh, pkt->data, len);
2008 if (backlog > SSH_MAX_BACKLOG)
2009 ssh_throttle_all(ssh, 1, backlog);
2011 ssh->outgoing_data_size += pkt->encrypted_len;
2012 if (!ssh->kex_in_progress &&
2013 ssh->max_data_size != 0 &&
2014 ssh->outgoing_data_size > ssh->max_data_size)
2015 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2017 ssh_free_packet(pkt);
2021 * Defer an SSH-2 packet.
2023 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2026 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2027 ssh->deferred_len == 0 && !noignore &&
2028 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2030 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2031 * get encrypted with a known IV.
2033 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2034 ssh2_pkt_addstring_start(ipkt);
2035 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2037 len = ssh2_pkt_construct(ssh, pkt);
2038 if (ssh->deferred_len + len > ssh->deferred_size) {
2039 ssh->deferred_size = ssh->deferred_len + len + 128;
2040 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2044 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2045 ssh->deferred_len += len;
2046 ssh->deferred_data_size += pkt->encrypted_len;
2047 ssh_free_packet(pkt);
2051 * Queue an SSH-2 packet.
2053 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2055 assert(ssh->queueing);
2057 if (ssh->queuelen >= ssh->queuesize) {
2058 ssh->queuesize = ssh->queuelen + 32;
2059 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2062 ssh->queue[ssh->queuelen++] = pkt;
2066 * Either queue or send a packet, depending on whether queueing is
2069 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2072 ssh2_pkt_queue(ssh, pkt);
2074 ssh2_pkt_send_noqueue(ssh, pkt);
2078 * Either queue or defer a packet, depending on whether queueing is
2081 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2084 ssh2_pkt_queue(ssh, pkt);
2086 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2090 * Send the whole deferred data block constructed by
2091 * ssh2_pkt_defer() or SSH-1's defer_packet().
2093 * The expected use of the defer mechanism is that you call
2094 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2095 * not currently queueing, this simply sets up deferred_send_data
2096 * and then sends it. If we _are_ currently queueing, the calls to
2097 * ssh2_pkt_defer() put the deferred packets on to the queue
2098 * instead, and therefore ssh_pkt_defersend() has no deferred data
2099 * to send. Hence, there's no need to make it conditional on
2102 static void ssh_pkt_defersend(Ssh ssh)
2105 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2106 ssh->deferred_len = ssh->deferred_size = 0;
2107 sfree(ssh->deferred_send_data);
2108 ssh->deferred_send_data = NULL;
2109 if (backlog > SSH_MAX_BACKLOG)
2110 ssh_throttle_all(ssh, 1, backlog);
2112 ssh->outgoing_data_size += ssh->deferred_data_size;
2113 if (!ssh->kex_in_progress &&
2114 ssh->max_data_size != 0 &&
2115 ssh->outgoing_data_size > ssh->max_data_size)
2116 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2117 ssh->deferred_data_size = 0;
2121 * Send a packet whose length needs to be disguised (typically
2122 * passwords or keyboard-interactive responses).
2124 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2130 * The simplest way to do this is to adjust the
2131 * variable-length padding field in the outgoing packet.
2133 * Currently compiled out, because some Cisco SSH servers
2134 * don't like excessively padded packets (bah, why's it
2137 pkt->forcepad = padsize;
2138 ssh2_pkt_send(ssh, pkt);
2143 * If we can't do that, however, an alternative approach is
2144 * to use the pkt_defer mechanism to bundle the packet
2145 * tightly together with an SSH_MSG_IGNORE such that their
2146 * combined length is a constant. So first we construct the
2147 * final form of this packet and defer its sending.
2149 ssh2_pkt_defer(ssh, pkt);
2152 * Now construct an SSH_MSG_IGNORE which includes a string
2153 * that's an exact multiple of the cipher block size. (If
2154 * the cipher is NULL so that the block size is
2155 * unavailable, we don't do this trick at all, because we
2156 * gain nothing by it.)
2158 if (ssh->cscipher &&
2159 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2162 stringlen = (256 - ssh->deferred_len);
2163 stringlen += ssh->cscipher->blksize - 1;
2164 stringlen -= (stringlen % ssh->cscipher->blksize);
2167 * Temporarily disable actual compression, so we
2168 * can guarantee to get this string exactly the
2169 * length we want it. The compression-disabling
2170 * routine should return an integer indicating how
2171 * many bytes we should adjust our string length
2175 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2177 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2178 ssh2_pkt_addstring_start(pkt);
2179 for (i = 0; i < stringlen; i++) {
2180 char c = (char) random_byte();
2181 ssh2_pkt_addstring_data(pkt, &c, 1);
2183 ssh2_pkt_defer(ssh, pkt);
2185 ssh_pkt_defersend(ssh);
2190 * Send all queued SSH-2 packets. We send them by means of
2191 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2192 * packets that needed to be lumped together.
2194 static void ssh2_pkt_queuesend(Ssh ssh)
2198 assert(!ssh->queueing);
2200 for (i = 0; i < ssh->queuelen; i++)
2201 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2204 ssh_pkt_defersend(ssh);
2208 void bndebug(char *string, Bignum b)
2212 p = ssh2_mpint_fmt(b, &len);
2213 debug(("%s", string));
2214 for (i = 0; i < len; i++)
2215 debug((" %02x", p[i]));
2221 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2225 p = ssh2_mpint_fmt(b, &len);
2226 hash_string(h, s, p, len);
2231 * Packet decode functions for both SSH-1 and SSH-2.
2233 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2235 unsigned long value;
2236 if (pkt->length - pkt->savedpos < 4)
2237 return 0; /* arrgh, no way to decline (FIXME?) */
2238 value = GET_32BIT(pkt->body + pkt->savedpos);
2242 static int ssh2_pkt_getbool(struct Packet *pkt)
2244 unsigned long value;
2245 if (pkt->length - pkt->savedpos < 1)
2246 return 0; /* arrgh, no way to decline (FIXME?) */
2247 value = pkt->body[pkt->savedpos] != 0;
2251 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2256 if (pkt->length - pkt->savedpos < 4)
2258 len = GET_32BIT(pkt->body + pkt->savedpos);
2263 if (pkt->length - pkt->savedpos < *length)
2265 *p = (char *)(pkt->body + pkt->savedpos);
2266 pkt->savedpos += *length;
2268 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2270 if (pkt->length - pkt->savedpos < length)
2272 pkt->savedpos += length;
2273 return pkt->body + (pkt->savedpos - length);
2275 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2276 unsigned char **keystr)
2280 j = makekey(pkt->body + pkt->savedpos,
2281 pkt->length - pkt->savedpos,
2288 assert(pkt->savedpos < pkt->length);
2292 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2297 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2298 pkt->length - pkt->savedpos, &b);
2306 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2312 ssh_pkt_getstring(pkt, &p, &length);
2317 b = bignum_from_bytes((unsigned char *)p, length);
2322 * Helper function to add an SSH-2 signature blob to a packet.
2323 * Expects to be shown the public key blob as well as the signature
2324 * blob. Normally works just like ssh2_pkt_addstring, but will
2325 * fiddle with the signature packet if necessary for
2326 * BUG_SSH2_RSA_PADDING.
2328 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2329 void *pkblob_v, int pkblob_len,
2330 void *sigblob_v, int sigblob_len)
2332 unsigned char *pkblob = (unsigned char *)pkblob_v;
2333 unsigned char *sigblob = (unsigned char *)sigblob_v;
2335 /* dmemdump(pkblob, pkblob_len); */
2336 /* dmemdump(sigblob, sigblob_len); */
2339 * See if this is in fact an ssh-rsa signature and a buggy
2340 * server; otherwise we can just do this the easy way.
2342 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2343 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2344 int pos, len, siglen;
2347 * Find the byte length of the modulus.
2350 pos = 4+7; /* skip over "ssh-rsa" */
2351 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2352 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2353 pos += 4; /* find modulus itself */
2354 while (len > 0 && pkblob[pos] == 0)
2356 /* debug(("modulus length is %d\n", len)); */
2359 * Now find the signature integer.
2361 pos = 4+7; /* skip over "ssh-rsa" */
2362 siglen = GET_32BIT(sigblob+pos);
2363 /* debug(("signature length is %d\n", siglen)); */
2365 if (len != siglen) {
2366 unsigned char newlen[4];
2367 ssh2_pkt_addstring_start(pkt);
2368 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2369 /* dmemdump(sigblob, pos); */
2370 pos += 4; /* point to start of actual sig */
2371 PUT_32BIT(newlen, len);
2372 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2373 /* dmemdump(newlen, 4); */
2375 while (len-- > siglen) {
2376 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2377 /* dmemdump(newlen, 1); */
2379 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2380 /* dmemdump(sigblob+pos, siglen); */
2384 /* Otherwise fall through and do it the easy way. */
2387 ssh2_pkt_addstring_start(pkt);
2388 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2392 * Examine the remote side's version string and compare it against
2393 * a list of known buggy implementations.
2395 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2397 char *imp; /* pointer to implementation part */
2399 imp += strcspn(imp, "-");
2401 imp += strcspn(imp, "-");
2404 ssh->remote_bugs = 0;
2407 * General notes on server version strings:
2408 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2409 * here -- in particular, we've heard of one that's perfectly happy
2410 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2411 * so we can't distinguish them.
2413 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2414 (ssh->cfg.sshbug_ignore1 == AUTO &&
2415 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2416 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2417 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2418 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2420 * These versions don't support SSH1_MSG_IGNORE, so we have
2421 * to use a different defence against password length
2424 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2425 logevent("We believe remote version has SSH-1 ignore bug");
2428 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2429 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2430 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2432 * These versions need a plain password sent; they can't
2433 * handle having a null and a random length of data after
2436 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2437 logevent("We believe remote version needs a plain SSH-1 password");
2440 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2441 (ssh->cfg.sshbug_rsa1 == AUTO &&
2442 (!strcmp(imp, "Cisco-1.25")))) {
2444 * These versions apparently have no clue whatever about
2445 * RSA authentication and will panic and die if they see
2446 * an AUTH_RSA message.
2448 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2449 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2452 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2453 (ssh->cfg.sshbug_hmac2 == AUTO &&
2454 !wc_match("* VShell", imp) &&
2455 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2456 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2457 wc_match("2.1 *", imp)))) {
2459 * These versions have the HMAC bug.
2461 ssh->remote_bugs |= BUG_SSH2_HMAC;
2462 logevent("We believe remote version has SSH-2 HMAC bug");
2465 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2466 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2467 !wc_match("* VShell", imp) &&
2468 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2470 * These versions have the key-derivation bug (failing to
2471 * include the literal shared secret in the hashes that
2472 * generate the keys).
2474 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2475 logevent("We believe remote version has SSH-2 key-derivation bug");
2478 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2479 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2480 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2481 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2483 * These versions have the SSH-2 RSA padding bug.
2485 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2486 logevent("We believe remote version has SSH-2 RSA padding bug");
2489 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2490 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2491 wc_match("OpenSSH_2.[0-2]*", imp))) {
2493 * These versions have the SSH-2 session-ID bug in
2494 * public-key authentication.
2496 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2497 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2500 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2501 (ssh->cfg.sshbug_rekey2 == AUTO &&
2502 (wc_match("DigiSSH_2.0", imp) ||
2503 wc_match("OpenSSH_2.[0-4]*", imp) ||
2504 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2505 wc_match("Sun_SSH_1.0", imp) ||
2506 wc_match("Sun_SSH_1.0.1", imp) ||
2507 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2508 wc_match("WeOnlyDo-*", imp)))) {
2510 * These versions have the SSH-2 rekey bug.
2512 ssh->remote_bugs |= BUG_SSH2_REKEY;
2513 logevent("We believe remote version has SSH-2 rekey bug");
2516 if (ssh->cfg.sshbug_maxpkt2 == FORCE_ON ||
2517 (ssh->cfg.sshbug_maxpkt2 == AUTO &&
2518 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2519 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2521 * This version ignores our makpkt and needs to be throttled.
2523 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2524 logevent("We believe remote version ignores SSH-2 maximum packet size");
2527 if (ssh->cfg.sshbug_ignore2 == FORCE_ON) {
2529 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2530 * none detected automatically.
2532 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2533 logevent("We believe remote version has SSH-2 ignore bug");
2538 * The `software version' part of an SSH version string is required
2539 * to contain no spaces or minus signs.
2541 static void ssh_fix_verstring(char *str)
2543 /* Eat "SSH-<protoversion>-". */
2544 assert(*str == 'S'); str++;
2545 assert(*str == 'S'); str++;
2546 assert(*str == 'H'); str++;
2547 assert(*str == '-'); str++;
2548 while (*str && *str != '-') str++;
2549 assert(*str == '-'); str++;
2551 /* Convert minus signs and spaces in the remaining string into
2554 if (*str == '-' || *str == ' ')
2561 * Send an appropriate SSH version string.
2563 static void ssh_send_verstring(Ssh ssh, char *svers)
2567 if (ssh->version == 2) {
2569 * Construct a v2 version string.
2571 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2574 * Construct a v1 version string.
2576 verstring = dupprintf("SSH-%s-%s\012",
2577 (ssh_versioncmp(svers, "1.5") <= 0 ?
2582 ssh_fix_verstring(verstring);
2584 if (ssh->version == 2) {
2587 * Record our version string.
2589 len = strcspn(verstring, "\015\012");
2590 ssh->v_c = snewn(len + 1, char);
2591 memcpy(ssh->v_c, verstring, len);
2595 logeventf(ssh, "We claim version: %.*s",
2596 strcspn(verstring, "\015\012"), verstring);
2597 s_write(ssh, verstring, strlen(verstring));
2601 static int do_ssh_init(Ssh ssh, unsigned char c)
2603 struct do_ssh_init_state {
2611 crState(do_ssh_init_state);
2613 crBegin(ssh->do_ssh_init_crstate);
2615 /* Search for a line beginning with the string "SSH-" in the input. */
2617 if (c != 'S') goto no;
2619 if (c != 'S') goto no;
2621 if (c != 'H') goto no;
2623 if (c != '-') goto no;
2632 s->vstring = snewn(s->vstrsize, char);
2633 strcpy(s->vstring, "SSH-");
2637 crReturn(1); /* get another char */
2638 if (s->vslen >= s->vstrsize - 1) {
2640 s->vstring = sresize(s->vstring, s->vstrsize, char);
2642 s->vstring[s->vslen++] = c;
2645 s->version[s->i] = '\0';
2647 } else if (s->i < sizeof(s->version) - 1)
2648 s->version[s->i++] = c;
2649 } else if (c == '\012')
2653 ssh->agentfwd_enabled = FALSE;
2654 ssh->rdpkt2_state.incoming_sequence = 0;
2656 s->vstring[s->vslen] = 0;
2657 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2658 logeventf(ssh, "Server version: %s", s->vstring);
2659 ssh_detect_bugs(ssh, s->vstring);
2662 * Decide which SSH protocol version to support.
2665 /* Anything strictly below "2.0" means protocol 1 is supported. */
2666 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2667 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2668 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2670 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2671 bombout(("SSH protocol version 1 required by user but not provided by server"));
2674 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2675 bombout(("SSH protocol version 2 required by user but not provided by server"));
2679 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1))
2684 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2686 /* Send the version string, if we haven't already */
2687 if (ssh->cfg.sshprot != 3)
2688 ssh_send_verstring(ssh, s->version);
2690 if (ssh->version == 2) {
2693 * Record their version string.
2695 len = strcspn(s->vstring, "\015\012");
2696 ssh->v_s = snewn(len + 1, char);
2697 memcpy(ssh->v_s, s->vstring, len);
2701 * Initialise SSH-2 protocol.
2703 ssh->protocol = ssh2_protocol;
2704 ssh2_protocol_setup(ssh);
2705 ssh->s_rdpkt = ssh2_rdpkt;
2708 * Initialise SSH-1 protocol.
2710 ssh->protocol = ssh1_protocol;
2711 ssh1_protocol_setup(ssh);
2712 ssh->s_rdpkt = ssh1_rdpkt;
2714 if (ssh->version == 2)
2715 do_ssh2_transport(ssh, NULL, -1, NULL);
2717 update_specials_menu(ssh->frontend);
2718 ssh->state = SSH_STATE_BEFORE_SIZE;
2719 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2726 static void ssh_process_incoming_data(Ssh ssh,
2727 unsigned char **data, int *datalen)
2729 struct Packet *pktin;
2731 pktin = ssh->s_rdpkt(ssh, data, datalen);
2733 ssh->protocol(ssh, NULL, 0, pktin);
2734 ssh_free_packet(pktin);
2738 static void ssh_queue_incoming_data(Ssh ssh,
2739 unsigned char **data, int *datalen)
2741 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2746 static void ssh_process_queued_incoming_data(Ssh ssh)
2749 unsigned char *data;
2752 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2753 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2757 while (!ssh->frozen && len > 0)
2758 ssh_process_incoming_data(ssh, &data, &len);
2761 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2765 static void ssh_set_frozen(Ssh ssh, int frozen)
2768 sk_set_frozen(ssh->s, frozen);
2769 ssh->frozen = frozen;
2772 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2774 /* Log raw data, if we're in that mode. */
2776 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2779 crBegin(ssh->ssh_gotdata_crstate);
2782 * To begin with, feed the characters one by one to the
2783 * protocol initialisation / selection function do_ssh_init().
2784 * When that returns 0, we're done with the initial greeting
2785 * exchange and can move on to packet discipline.
2788 int ret; /* need not be kept across crReturn */
2790 crReturnV; /* more data please */
2791 ret = do_ssh_init(ssh, *data);
2799 * We emerge from that loop when the initial negotiation is
2800 * over and we have selected an s_rdpkt function. Now pass
2801 * everything to s_rdpkt, and then pass the resulting packets
2802 * to the proper protocol handler.
2806 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2808 ssh_queue_incoming_data(ssh, &data, &datalen);
2809 /* This uses up all data and cannot cause anything interesting
2810 * to happen; indeed, for anything to happen at all, we must
2811 * return, so break out. */
2813 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2814 /* This uses up some or all data, and may freeze the
2816 ssh_process_queued_incoming_data(ssh);
2818 /* This uses up some or all data, and may freeze the
2820 ssh_process_incoming_data(ssh, &data, &datalen);
2822 /* FIXME this is probably EBW. */
2823 if (ssh->state == SSH_STATE_CLOSED)
2826 /* We're out of data. Go and get some more. */
2832 static int ssh_do_close(Ssh ssh, int notify_exit)
2835 struct ssh_channel *c;
2837 ssh->state = SSH_STATE_CLOSED;
2838 expire_timer_context(ssh);
2843 notify_remote_exit(ssh->frontend);
2848 * Now we must shut down any port- and X-forwarded channels going
2849 * through this connection.
2851 if (ssh->channels) {
2852 while (NULL != (c = index234(ssh->channels, 0))) {
2855 x11_close(c->u.x11.s);
2858 pfd_close(c->u.pfd.s);
2861 del234(ssh->channels, c); /* moving next one to index 0 */
2862 if (ssh->version == 2)
2863 bufchain_clear(&c->v.v2.outbuffer);
2868 * Go through port-forwardings, and close any associated
2869 * listening sockets.
2871 if (ssh->portfwds) {
2872 struct ssh_portfwd *pf;
2873 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2874 /* Dispose of any listening socket. */
2876 pfd_terminate(pf->local);
2877 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2880 freetree234(ssh->portfwds);
2881 ssh->portfwds = NULL;
2887 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2888 const char *error_msg, int error_code)
2890 Ssh ssh = (Ssh) plug;
2891 char addrbuf[256], *msg;
2893 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2896 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2898 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2904 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2907 Ssh ssh = (Ssh) plug;
2908 int need_notify = ssh_do_close(ssh, FALSE);
2911 if (!ssh->close_expected)
2912 error_msg = "Server unexpectedly closed network connection";
2914 error_msg = "Server closed network connection";
2917 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2921 notify_remote_exit(ssh->frontend);
2924 logevent(error_msg);
2925 if (!ssh->close_expected || !ssh->clean_exit)
2926 connection_fatal(ssh->frontend, "%s", error_msg);
2930 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2932 Ssh ssh = (Ssh) plug;
2933 ssh_gotdata(ssh, (unsigned char *)data, len);
2934 if (ssh->state == SSH_STATE_CLOSED) {
2935 ssh_do_close(ssh, TRUE);
2941 static void ssh_sent(Plug plug, int bufsize)
2943 Ssh ssh = (Ssh) plug;
2945 * If the send backlog on the SSH socket itself clears, we
2946 * should unthrottle the whole world if it was throttled.
2948 if (bufsize < SSH_MAX_BACKLOG)
2949 ssh_throttle_all(ssh, 0, bufsize);
2953 * Connect to specified host and port.
2954 * Returns an error message, or NULL on success.
2955 * Also places the canonical host name into `realhost'. It must be
2956 * freed by the caller.
2958 static const char *connect_to_host(Ssh ssh, char *host, int port,
2959 char **realhost, int nodelay, int keepalive)
2961 static const struct plug_function_table fn_table = {
2972 if (*ssh->cfg.loghost) {
2975 ssh->savedhost = dupstr(ssh->cfg.loghost);
2976 ssh->savedport = 22; /* default ssh port */
2979 * A colon suffix on savedhost also lets us affect
2982 * (FIXME: do something about IPv6 address literals here.)
2984 colon = strrchr(ssh->savedhost, ':');
2988 ssh->savedport = atoi(colon);
2991 ssh->savedhost = dupstr(host);
2993 port = 22; /* default ssh port */
2994 ssh->savedport = port;
3000 logeventf(ssh, "Looking up host \"%s\"%s", host,
3001 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3002 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3003 addr = name_lookup(host, port, realhost, &ssh->cfg,
3004 ssh->cfg.addressfamily);
3005 if ((err = sk_addr_error(addr)) != NULL) {
3009 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3014 ssh->fn = &fn_table;
3015 ssh->s = new_connection(addr, *realhost, port,
3016 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
3017 if ((err = sk_socket_error(ssh->s)) != NULL) {
3019 notify_remote_exit(ssh->frontend);
3024 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3025 * send the version string too.
3027 if (ssh->cfg.sshprot == 0)
3029 if (ssh->cfg.sshprot == 3) {
3031 ssh_send_verstring(ssh, NULL);
3035 * loghost, if configured, overrides realhost.
3037 if (*ssh->cfg.loghost) {
3039 *realhost = dupstr(ssh->cfg.loghost);
3046 * Throttle or unthrottle the SSH connection.
3048 static void ssh_throttle_conn(Ssh ssh, int adjust)
3050 int old_count = ssh->conn_throttle_count;
3051 ssh->conn_throttle_count += adjust;
3052 assert(ssh->conn_throttle_count >= 0);
3053 if (ssh->conn_throttle_count && !old_count) {
3054 ssh_set_frozen(ssh, 1);
3055 } else if (!ssh->conn_throttle_count && old_count) {
3056 ssh_set_frozen(ssh, 0);
3061 * Throttle or unthrottle _all_ local data streams (for when sends
3062 * on the SSH connection itself back up).
3064 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3067 struct ssh_channel *c;
3069 if (enable == ssh->throttled_all)
3071 ssh->throttled_all = enable;
3072 ssh->overall_bufsize = bufsize;
3075 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3077 case CHAN_MAINSESSION:
3079 * This is treated separately, outside the switch.
3083 x11_override_throttle(c->u.x11.s, enable);
3086 /* Agent channels require no buffer management. */
3089 pfd_override_throttle(c->u.pfd.s, enable);
3095 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3097 Ssh ssh = (Ssh) sshv;
3099 ssh->agent_response = reply;
3100 ssh->agent_response_len = replylen;
3102 if (ssh->version == 1)
3103 do_ssh1_login(ssh, NULL, -1, NULL);
3105 do_ssh2_authconn(ssh, NULL, -1, NULL);
3108 static void ssh_dialog_callback(void *sshv, int ret)
3110 Ssh ssh = (Ssh) sshv;
3112 ssh->user_response = ret;
3114 if (ssh->version == 1)
3115 do_ssh1_login(ssh, NULL, -1, NULL);
3117 do_ssh2_transport(ssh, NULL, -1, NULL);
3120 * This may have unfrozen the SSH connection, so do a
3123 ssh_process_queued_incoming_data(ssh);
3126 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3128 struct ssh_channel *c = (struct ssh_channel *)cv;
3130 void *sentreply = reply;
3133 /* Fake SSH_AGENT_FAILURE. */
3134 sentreply = "\0\0\0\1\5";
3137 if (ssh->version == 2) {
3138 ssh2_add_channel_data(c, sentreply, replylen);
3141 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3142 PKT_INT, c->remoteid,
3145 PKT_DATA, sentreply, replylen,
3154 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3155 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3156 * => log `wire_reason'.
3158 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3159 int code, int clean_exit)
3163 client_reason = wire_reason;
3165 error = dupprintf("Disconnected: %s", client_reason);
3167 error = dupstr("Disconnected");
3169 if (ssh->version == 1) {
3170 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3172 } else if (ssh->version == 2) {
3173 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3174 ssh2_pkt_adduint32(pktout, code);
3175 ssh2_pkt_addstring(pktout, wire_reason);
3176 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3177 ssh2_pkt_send_noqueue(ssh, pktout);
3180 ssh->close_expected = TRUE;
3181 ssh->clean_exit = clean_exit;
3182 ssh_closing((Plug)ssh, error, 0, 0);
3187 * Handle the key exchange and user authentication phases.
3189 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3190 struct Packet *pktin)
3193 unsigned char cookie[8], *ptr;
3194 struct RSAKey servkey, hostkey;
3195 struct MD5Context md5c;
3196 struct do_ssh1_login_state {
3198 unsigned char *rsabuf, *keystr1, *keystr2;
3199 unsigned long supported_ciphers_mask, supported_auths_mask;
3200 int tried_publickey, tried_agent;
3201 int tis_auth_refused, ccard_auth_refused;
3202 unsigned char session_id[16];
3205 void *publickey_blob;
3206 int publickey_bloblen;
3207 char *publickey_comment;
3208 int publickey_encrypted;
3209 prompts_t *cur_prompt;
3212 unsigned char request[5], *response, *p;
3222 crState(do_ssh1_login_state);
3224 crBegin(ssh->do_ssh1_login_crstate);
3229 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3230 bombout(("Public key packet not received"));
3234 logevent("Received public keys");
3236 ptr = ssh_pkt_getdata(pktin, 8);
3238 bombout(("SSH-1 public key packet stopped before random cookie"));
3241 memcpy(cookie, ptr, 8);
3243 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3244 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3245 bombout(("Failed to read SSH-1 public keys from public key packet"));
3250 * Log the host key fingerprint.
3254 logevent("Host key fingerprint is:");
3255 strcpy(logmsg, " ");
3256 hostkey.comment = NULL;
3257 rsa_fingerprint(logmsg + strlen(logmsg),
3258 sizeof(logmsg) - strlen(logmsg), &hostkey);
3262 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3263 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3264 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3265 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3266 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3268 ssh->v1_local_protoflags =
3269 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3270 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3273 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3274 MD5Update(&md5c, s->keystr1, servkey.bytes);
3275 MD5Update(&md5c, cookie, 8);
3276 MD5Final(s->session_id, &md5c);
3278 for (i = 0; i < 32; i++)
3279 ssh->session_key[i] = random_byte();
3282 * Verify that the `bits' and `bytes' parameters match.
3284 if (hostkey.bits > hostkey.bytes * 8 ||
3285 servkey.bits > servkey.bytes * 8) {
3286 bombout(("SSH-1 public keys were badly formatted"));
3290 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3292 s->rsabuf = snewn(s->len, unsigned char);
3295 * Verify the host key.
3299 * First format the key into a string.
3301 int len = rsastr_len(&hostkey);
3302 char fingerprint[100];
3303 char *keystr = snewn(len, char);
3304 rsastr_fmt(keystr, &hostkey);
3305 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3307 ssh_set_frozen(ssh, 1);
3308 s->dlgret = verify_ssh_host_key(ssh->frontend,
3309 ssh->savedhost, ssh->savedport,
3310 "rsa", keystr, fingerprint,
3311 ssh_dialog_callback, ssh);
3313 if (s->dlgret < 0) {
3317 bombout(("Unexpected data from server while waiting"
3318 " for user host key response"));
3321 } while (pktin || inlen > 0);
3322 s->dlgret = ssh->user_response;
3324 ssh_set_frozen(ssh, 0);
3326 if (s->dlgret == 0) {
3327 ssh_disconnect(ssh, "User aborted at host key verification",
3333 for (i = 0; i < 32; i++) {
3334 s->rsabuf[i] = ssh->session_key[i];
3336 s->rsabuf[i] ^= s->session_id[i];
3339 if (hostkey.bytes > servkey.bytes) {
3340 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3342 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3344 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3346 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3349 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3353 logevent("Encrypted session key");
3356 int cipher_chosen = 0, warn = 0;
3357 char *cipher_string = NULL;
3359 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3360 int next_cipher = ssh->cfg.ssh_cipherlist[i];
3361 if (next_cipher == CIPHER_WARN) {
3362 /* If/when we choose a cipher, warn about it */
3364 } else if (next_cipher == CIPHER_AES) {
3365 /* XXX Probably don't need to mention this. */
3366 logevent("AES not supported in SSH-1, skipping");
3368 switch (next_cipher) {
3369 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3370 cipher_string = "3DES"; break;
3371 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3372 cipher_string = "Blowfish"; break;
3373 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3374 cipher_string = "single-DES"; break;
3376 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3380 if (!cipher_chosen) {
3381 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3382 bombout(("Server violates SSH-1 protocol by not "
3383 "supporting 3DES encryption"));
3385 /* shouldn't happen */
3386 bombout(("No supported ciphers found"));
3390 /* Warn about chosen cipher if necessary. */
3392 ssh_set_frozen(ssh, 1);
3393 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3394 ssh_dialog_callback, ssh);
3395 if (s->dlgret < 0) {
3399 bombout(("Unexpected data from server while waiting"
3400 " for user response"));
3403 } while (pktin || inlen > 0);
3404 s->dlgret = ssh->user_response;
3406 ssh_set_frozen(ssh, 0);
3407 if (s->dlgret == 0) {
3408 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3415 switch (s->cipher_type) {
3416 case SSH_CIPHER_3DES:
3417 logevent("Using 3DES encryption");
3419 case SSH_CIPHER_DES:
3420 logevent("Using single-DES encryption");
3422 case SSH_CIPHER_BLOWFISH:
3423 logevent("Using Blowfish encryption");
3427 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3428 PKT_CHAR, s->cipher_type,
3429 PKT_DATA, cookie, 8,
3430 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3431 PKT_DATA, s->rsabuf, s->len,
3432 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3434 logevent("Trying to enable encryption...");
3438 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3439 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3441 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3442 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3443 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3445 ssh->crcda_ctx = crcda_make_context();
3446 logevent("Installing CRC compensation attack detector");
3448 if (servkey.modulus) {
3449 sfree(servkey.modulus);
3450 servkey.modulus = NULL;
3452 if (servkey.exponent) {
3453 sfree(servkey.exponent);
3454 servkey.exponent = NULL;
3456 if (hostkey.modulus) {
3457 sfree(hostkey.modulus);
3458 hostkey.modulus = NULL;
3460 if (hostkey.exponent) {
3461 sfree(hostkey.exponent);
3462 hostkey.exponent = NULL;
3466 if (pktin->type != SSH1_SMSG_SUCCESS) {
3467 bombout(("Encryption not successfully enabled"));
3471 logevent("Successfully started encryption");
3473 fflush(stdout); /* FIXME eh? */
3475 if (!get_remote_username(&ssh->cfg, s->username,
3476 sizeof(s->username))) {
3477 int ret; /* need not be kept over crReturn */
3478 s->cur_prompt = new_prompts(ssh->frontend);
3479 s->cur_prompt->to_server = TRUE;
3480 s->cur_prompt->name = dupstr("SSH login name");
3481 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
3482 lenof(s->username));
3483 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3486 crWaitUntil(!pktin);
3487 ret = get_userpass_input(s->cur_prompt, in, inlen);
3492 * Failed to get a username. Terminate.
3494 free_prompts(s->cur_prompt);
3495 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3498 memcpy(s->username, s->cur_prompt->prompts[0]->result,
3499 lenof(s->username));
3500 free_prompts(s->cur_prompt);
3503 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3505 char *userlog = dupprintf("Sent username \"%s\"", s->username);
3507 if (flags & FLAG_INTERACTIVE &&
3508 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3509 c_write_str(ssh, userlog);
3510 c_write_str(ssh, "\r\n");
3518 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3519 /* We must not attempt PK auth. Pretend we've already tried it. */
3520 s->tried_publickey = s->tried_agent = 1;
3522 s->tried_publickey = s->tried_agent = 0;
3524 s->tis_auth_refused = s->ccard_auth_refused = 0;
3526 * Load the public half of any configured keyfile for later use.
3528 if (!filename_is_null(ssh->cfg.keyfile)) {
3530 logeventf(ssh, "Reading private key file \"%.150s\"",
3531 filename_to_str(&ssh->cfg.keyfile));
3532 keytype = key_type(&ssh->cfg.keyfile);
3533 if (keytype == SSH_KEYTYPE_SSH1) {
3535 if (rsakey_pubblob(&ssh->cfg.keyfile,
3536 &s->publickey_blob, &s->publickey_bloblen,
3537 &s->publickey_comment, &error)) {
3538 s->publickey_encrypted = rsakey_encrypted(&ssh->cfg.keyfile,
3542 logeventf(ssh, "Unable to load private key (%s)", error);
3543 msgbuf = dupprintf("Unable to load private key file "
3544 "\"%.150s\" (%s)\r\n",
3545 filename_to_str(&ssh->cfg.keyfile),
3547 c_write_str(ssh, msgbuf);
3549 s->publickey_blob = NULL;
3553 logeventf(ssh, "Unable to use this key file (%s)",
3554 key_type_to_str(keytype));
3555 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3557 filename_to_str(&ssh->cfg.keyfile),
3558 key_type_to_str(keytype));
3559 c_write_str(ssh, msgbuf);
3561 s->publickey_blob = NULL;
3564 s->publickey_blob = NULL;
3566 while (pktin->type == SSH1_SMSG_FAILURE) {
3567 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3569 if (ssh->cfg.tryagent && agent_exists() && !s->tried_agent) {
3571 * Attempt RSA authentication using Pageant.
3577 logevent("Pageant is running. Requesting keys.");
3579 /* Request the keys held by the agent. */
3580 PUT_32BIT(s->request, 1);
3581 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3582 if (!agent_query(s->request, 5, &r, &s->responselen,
3583 ssh_agent_callback, ssh)) {
3587 bombout(("Unexpected data from server while waiting"
3588 " for agent response"));
3591 } while (pktin || inlen > 0);
3592 r = ssh->agent_response;
3593 s->responselen = ssh->agent_response_len;
3595 s->response = (unsigned char *) r;
3596 if (s->response && s->responselen >= 5 &&
3597 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3598 s->p = s->response + 5;
3599 s->nkeys = GET_32BIT(s->p);
3601 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3602 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3603 unsigned char *pkblob = s->p;
3607 do { /* do while (0) to make breaking easy */
3608 n = ssh1_read_bignum
3609 (s->p, s->responselen-(s->p-s->response),
3614 n = ssh1_read_bignum
3615 (s->p, s->responselen-(s->p-s->response),
3620 if (s->responselen - (s->p-s->response) < 4)
3622 s->commentlen = GET_32BIT(s->p);
3624 if (s->responselen - (s->p-s->response) <
3627 s->commentp = (char *)s->p;
3628 s->p += s->commentlen;
3632 logevent("Pageant key list packet was truncated");
3636 if (s->publickey_blob) {
3637 if (!memcmp(pkblob, s->publickey_blob,
3638 s->publickey_bloblen)) {
3639 logeventf(ssh, "Pageant key #%d matches "
3640 "configured key file", s->keyi);
3641 s->tried_publickey = 1;
3643 /* Skip non-configured key */
3646 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3647 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3648 PKT_BIGNUM, s->key.modulus, PKT_END);
3650 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3651 logevent("Key refused");
3654 logevent("Received RSA challenge");
3655 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3656 bombout(("Server's RSA challenge was badly formatted"));
3661 char *agentreq, *q, *ret;
3664 len = 1 + 4; /* message type, bit count */
3665 len += ssh1_bignum_length(s->key.exponent);
3666 len += ssh1_bignum_length(s->key.modulus);
3667 len += ssh1_bignum_length(s->challenge);
3668 len += 16; /* session id */
3669 len += 4; /* response format */
3670 agentreq = snewn(4 + len, char);
3671 PUT_32BIT(agentreq, len);
3673 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3674 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3676 q += ssh1_write_bignum(q, s->key.exponent);
3677 q += ssh1_write_bignum(q, s->key.modulus);
3678 q += ssh1_write_bignum(q, s->challenge);
3679 memcpy(q, s->session_id, 16);
3681 PUT_32BIT(q, 1); /* response format */
3682 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3683 ssh_agent_callback, ssh)) {
3688 bombout(("Unexpected data from server"
3689 " while waiting for agent"
3693 } while (pktin || inlen > 0);
3694 vret = ssh->agent_response;
3695 retlen = ssh->agent_response_len;
3700 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3701 logevent("Sending Pageant's response");
3702 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3703 PKT_DATA, ret + 5, 16,
3707 if (pktin->type == SSH1_SMSG_SUCCESS) {
3709 ("Pageant's response accepted");
3710 if (flags & FLAG_VERBOSE) {
3711 c_write_str(ssh, "Authenticated using"
3713 c_write(ssh, s->commentp,
3715 c_write_str(ssh, "\" from agent\r\n");
3720 ("Pageant's response not accepted");
3723 ("Pageant failed to answer challenge");
3727 logevent("No reply received from Pageant");
3730 freebn(s->key.exponent);
3731 freebn(s->key.modulus);
3732 freebn(s->challenge);
3737 if (s->publickey_blob && !s->tried_publickey)
3738 logevent("Configured key file not in Pageant");
3743 if (s->publickey_blob && !s->tried_publickey) {
3745 * Try public key authentication with the specified
3748 int got_passphrase; /* need not be kept over crReturn */
3749 if (flags & FLAG_VERBOSE)
3750 c_write_str(ssh, "Trying public key authentication.\r\n");
3751 logeventf(ssh, "Trying public key \"%s\"",
3752 filename_to_str(&ssh->cfg.keyfile));
3753 s->tried_publickey = 1;
3754 got_passphrase = FALSE;
3755 while (!got_passphrase) {
3757 * Get a passphrase, if necessary.
3759 char *passphrase = NULL; /* only written after crReturn */
3761 if (!s->publickey_encrypted) {
3762 if (flags & FLAG_VERBOSE)
3763 c_write_str(ssh, "No passphrase required.\r\n");
3766 int ret; /* need not be kept over crReturn */
3767 s->cur_prompt = new_prompts(ssh->frontend);
3768 s->cur_prompt->to_server = FALSE;
3769 s->cur_prompt->name = dupstr("SSH key passphrase");
3770 add_prompt(s->cur_prompt,
3771 dupprintf("Passphrase for key \"%.100s\": ",
3772 s->publickey_comment),
3773 FALSE, SSH_MAX_PASSWORD_LEN);
3774 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3777 crWaitUntil(!pktin);
3778 ret = get_userpass_input(s->cur_prompt, in, inlen);
3782 /* Failed to get a passphrase. Terminate. */
3783 free_prompts(s->cur_prompt);
3784 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3788 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3789 free_prompts(s->cur_prompt);
3792 * Try decrypting key with passphrase.
3794 ret = loadrsakey(&ssh->cfg.keyfile, &s->key, passphrase,
3797 memset(passphrase, 0, strlen(passphrase));
3801 /* Correct passphrase. */
3802 got_passphrase = TRUE;
3803 } else if (ret == 0) {
3804 c_write_str(ssh, "Couldn't load private key from ");
3805 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3806 c_write_str(ssh, " (");
3807 c_write_str(ssh, error);
3808 c_write_str(ssh, ").\r\n");
3809 got_passphrase = FALSE;
3810 break; /* go and try something else */
3811 } else if (ret == -1) {
3812 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3813 got_passphrase = FALSE;
3816 assert(0 && "unexpected return from loadrsakey()");
3817 got_passphrase = FALSE; /* placate optimisers */
3821 if (got_passphrase) {
3824 * Send a public key attempt.
3826 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3827 PKT_BIGNUM, s->key.modulus, PKT_END);
3830 if (pktin->type == SSH1_SMSG_FAILURE) {
3831 c_write_str(ssh, "Server refused our public key.\r\n");
3832 continue; /* go and try something else */
3834 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3835 bombout(("Bizarre response to offer of public key"));
3841 unsigned char buffer[32];
3842 Bignum challenge, response;
3844 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3845 bombout(("Server's RSA challenge was badly formatted"));
3848 response = rsadecrypt(challenge, &s->key);
3849 freebn(s->key.private_exponent);/* burn the evidence */
3851 for (i = 0; i < 32; i++) {
3852 buffer[i] = bignum_byte(response, 31 - i);
3856 MD5Update(&md5c, buffer, 32);
3857 MD5Update(&md5c, s->session_id, 16);
3858 MD5Final(buffer, &md5c);
3860 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3861 PKT_DATA, buffer, 16, PKT_END);
3868 if (pktin->type == SSH1_SMSG_FAILURE) {
3869 if (flags & FLAG_VERBOSE)
3870 c_write_str(ssh, "Failed to authenticate with"
3871 " our public key.\r\n");
3872 continue; /* go and try something else */
3873 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3874 bombout(("Bizarre response to RSA authentication response"));
3878 break; /* we're through! */
3884 * Otherwise, try various forms of password-like authentication.
3886 s->cur_prompt = new_prompts(ssh->frontend);
3888 if (ssh->cfg.try_tis_auth &&
3889 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3890 !s->tis_auth_refused) {
3891 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3892 logevent("Requested TIS authentication");
3893 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3895 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3896 logevent("TIS authentication declined");
3897 if (flags & FLAG_INTERACTIVE)
3898 c_write_str(ssh, "TIS authentication refused.\r\n");
3899 s->tis_auth_refused = 1;
3904 char *instr_suf, *prompt;
3906 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3908 bombout(("TIS challenge packet was badly formed"));
3911 logevent("Received TIS challenge");
3912 s->cur_prompt->to_server = TRUE;
3913 s->cur_prompt->name = dupstr("SSH TIS authentication");
3914 /* Prompt heuristic comes from OpenSSH */
3915 if (memchr(challenge, '\n', challengelen)) {
3916 instr_suf = dupstr("");
3917 prompt = dupprintf("%.*s", challengelen, challenge);
3919 instr_suf = dupprintf("%.*s", challengelen, challenge);
3920 prompt = dupstr("Response: ");
3922 s->cur_prompt->instruction =
3923 dupprintf("Using TIS authentication.%s%s",
3924 (*instr_suf) ? "\n" : "",
3926 s->cur_prompt->instr_reqd = TRUE;
3927 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3931 if (ssh->cfg.try_tis_auth &&
3932 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3933 !s->ccard_auth_refused) {
3934 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3935 logevent("Requested CryptoCard authentication");
3936 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3938 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3939 logevent("CryptoCard authentication declined");
3940 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3941 s->ccard_auth_refused = 1;
3946 char *instr_suf, *prompt;
3948 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3950 bombout(("CryptoCard challenge packet was badly formed"));
3953 logevent("Received CryptoCard challenge");
3954 s->cur_prompt->to_server = TRUE;
3955 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3956 s->cur_prompt->name_reqd = FALSE;
3957 /* Prompt heuristic comes from OpenSSH */
3958 if (memchr(challenge, '\n', challengelen)) {
3959 instr_suf = dupstr("");
3960 prompt = dupprintf("%.*s", challengelen, challenge);
3962 instr_suf = dupprintf("%.*s", challengelen, challenge);
3963 prompt = dupstr("Response: ");
3965 s->cur_prompt->instruction =
3966 dupprintf("Using CryptoCard authentication.%s%s",
3967 (*instr_suf) ? "\n" : "",
3969 s->cur_prompt->instr_reqd = TRUE;
3970 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3974 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3975 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
3976 bombout(("No supported authentication methods available"));
3979 s->cur_prompt->to_server = TRUE;
3980 s->cur_prompt->name = dupstr("SSH password");
3981 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
3982 s->username, ssh->savedhost),
3983 FALSE, SSH_MAX_PASSWORD_LEN);
3987 * Show password prompt, having first obtained it via a TIS
3988 * or CryptoCard exchange if we're doing TIS or CryptoCard
3992 int ret; /* need not be kept over crReturn */
3993 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3996 crWaitUntil(!pktin);
3997 ret = get_userpass_input(s->cur_prompt, in, inlen);
4002 * Failed to get a password (for example
4003 * because one was supplied on the command line
4004 * which has already failed to work). Terminate.
4006 free_prompts(s->cur_prompt);
4007 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4012 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4014 * Defence against traffic analysis: we send a
4015 * whole bunch of packets containing strings of
4016 * different lengths. One of these strings is the
4017 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4018 * The others are all random data in
4019 * SSH1_MSG_IGNORE packets. This way a passive
4020 * listener can't tell which is the password, and
4021 * hence can't deduce the password length.
4023 * Anybody with a password length greater than 16
4024 * bytes is going to have enough entropy in their
4025 * password that a listener won't find it _that_
4026 * much help to know how long it is. So what we'll
4029 * - if password length < 16, we send 15 packets
4030 * containing string lengths 1 through 15
4032 * - otherwise, we let N be the nearest multiple
4033 * of 8 below the password length, and send 8
4034 * packets containing string lengths N through
4035 * N+7. This won't obscure the order of
4036 * magnitude of the password length, but it will
4037 * introduce a bit of extra uncertainty.
4039 * A few servers can't deal with SSH1_MSG_IGNORE, at
4040 * least in this context. For these servers, we need
4041 * an alternative defence. We make use of the fact
4042 * that the password is interpreted as a C string:
4043 * so we can append a NUL, then some random data.
4045 * A few servers can deal with neither SSH1_MSG_IGNORE
4046 * here _nor_ a padded password string.
4047 * For these servers we are left with no defences
4048 * against password length sniffing.
4050 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4051 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4053 * The server can deal with SSH1_MSG_IGNORE, so
4054 * we can use the primary defence.
4056 int bottom, top, pwlen, i;
4059 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4061 bottom = 0; /* zero length passwords are OK! :-) */
4064 bottom = pwlen & ~7;
4068 assert(pwlen >= bottom && pwlen <= top);
4070 randomstr = snewn(top + 1, char);
4072 for (i = bottom; i <= top; i++) {
4074 defer_packet(ssh, s->pwpkt_type,
4075 PKTT_PASSWORD, PKT_STR,
4076 s->cur_prompt->prompts[0]->result,
4077 PKTT_OTHER, PKT_END);
4079 for (j = 0; j < i; j++) {
4081 randomstr[j] = random_byte();
4082 } while (randomstr[j] == '\0');
4084 randomstr[i] = '\0';
4085 defer_packet(ssh, SSH1_MSG_IGNORE,
4086 PKT_STR, randomstr, PKT_END);
4089 logevent("Sending password with camouflage packets");
4090 ssh_pkt_defersend(ssh);
4093 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4095 * The server can't deal with SSH1_MSG_IGNORE
4096 * but can deal with padded passwords, so we
4097 * can use the secondary defence.
4103 len = strlen(s->cur_prompt->prompts[0]->result);
4104 if (len < sizeof(string)) {
4106 strcpy(string, s->cur_prompt->prompts[0]->result);
4107 len++; /* cover the zero byte */
4108 while (len < sizeof(string)) {
4109 string[len++] = (char) random_byte();
4112 ss = s->cur_prompt->prompts[0]->result;
4114 logevent("Sending length-padded password");
4115 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4116 PKT_INT, len, PKT_DATA, ss, len,
4117 PKTT_OTHER, PKT_END);
4120 * The server is believed unable to cope with
4121 * any of our password camouflage methods.
4124 len = strlen(s->cur_prompt->prompts[0]->result);
4125 logevent("Sending unpadded password");
4126 send_packet(ssh, s->pwpkt_type,
4127 PKTT_PASSWORD, PKT_INT, len,
4128 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4129 PKTT_OTHER, PKT_END);
4132 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4133 PKT_STR, s->cur_prompt->prompts[0]->result,
4134 PKTT_OTHER, PKT_END);
4136 logevent("Sent password");
4137 free_prompts(s->cur_prompt);
4139 if (pktin->type == SSH1_SMSG_FAILURE) {
4140 if (flags & FLAG_VERBOSE)
4141 c_write_str(ssh, "Access denied\r\n");
4142 logevent("Authentication refused");
4143 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4144 bombout(("Strange packet received, type %d", pktin->type));
4150 if (s->publickey_blob) {
4151 sfree(s->publickey_blob);
4152 sfree(s->publickey_comment);
4155 logevent("Authentication successful");
4160 void sshfwd_close(struct ssh_channel *c)
4164 if (ssh->state == SSH_STATE_CLOSED)
4169 * If halfopen is true, we have sent
4170 * CHANNEL_OPEN for this channel, but it hasn't even been
4171 * acknowledged by the server. So we must set a close flag
4172 * on it now, and then when the server acks the channel
4173 * open, we can close it then.
4176 if (ssh->version == 1) {
4177 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4179 c->closes = 1; /* sent MSG_CLOSE */
4181 int bytes_to_send = bufchain_size(&c->v.v2.outbuffer);
4182 if (bytes_to_send > 0) {
4184 * If we still have unsent data in our outgoing
4185 * buffer for this channel, we can't actually
4186 * initiate a close operation yet or that data
4187 * will be lost. Instead, set the pending_close
4188 * flag so that when we do clear the buffer
4189 * we'll start closing the channel.
4191 char logmsg[160] = {'\0'};
4194 "Forwarded port pending to be closed : "
4195 "%d bytes remaining",
4199 c->pending_close = TRUE;
4202 * No locally buffered data, so we can send the
4203 * close message immediately.
4205 struct Packet *pktout;
4206 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4207 ssh2_pkt_adduint32(pktout, c->remoteid);
4208 ssh2_pkt_send(ssh, pktout);
4209 c->closes = 1; /* sent MSG_CLOSE */
4210 logevent("Nothing left to send, closing channel");
4215 if (c->type == CHAN_X11) {
4217 logevent("Forwarded X11 connection terminated");
4218 } else if (c->type == CHAN_SOCKDATA ||
4219 c->type == CHAN_SOCKDATA_DORMANT) {
4221 logevent("Forwarded port closed");
4226 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4230 if (ssh->state == SSH_STATE_CLOSED)
4233 if (ssh->version == 1) {
4234 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4235 PKT_INT, c->remoteid,
4236 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4237 PKTT_OTHER, PKT_END);
4239 * In SSH-1 we can return 0 here - implying that forwarded
4240 * connections are never individually throttled - because
4241 * the only circumstance that can cause throttling will be
4242 * the whole SSH connection backing up, in which case
4243 * _everything_ will be throttled as a whole.
4247 ssh2_add_channel_data(c, buf, len);
4248 return ssh2_try_send(c);
4252 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4257 if (ssh->state == SSH_STATE_CLOSED)
4260 if (ssh->version == 1) {
4261 buflimit = SSH1_BUFFER_LIMIT;
4263 buflimit = c->v.v2.locmaxwin;
4264 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4266 if (c->throttling_conn && bufsize <= buflimit) {
4267 c->throttling_conn = 0;
4268 ssh_throttle_conn(ssh, -1);
4272 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4274 struct queued_handler *qh = ssh->qhead;
4278 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4281 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4282 ssh->packet_dispatch[qh->msg1] = NULL;
4285 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4286 ssh->packet_dispatch[qh->msg2] = NULL;
4290 ssh->qhead = qh->next;
4292 if (ssh->qhead->msg1 > 0) {
4293 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4294 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4296 if (ssh->qhead->msg2 > 0) {
4297 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4298 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4301 ssh->qhead = ssh->qtail = NULL;
4302 ssh->packet_dispatch[pktin->type] = NULL;
4305 qh->handler(ssh, pktin, qh->ctx);
4310 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4311 chandler_fn_t handler, void *ctx)
4313 struct queued_handler *qh;
4315 qh = snew(struct queued_handler);
4318 qh->handler = handler;
4322 if (ssh->qtail == NULL) {
4326 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4327 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4330 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4331 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4334 ssh->qtail->next = qh;
4339 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4341 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4343 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4344 SSH2_MSG_REQUEST_SUCCESS)) {
4345 logeventf(ssh, "Remote port forwarding from %s enabled",
4348 logeventf(ssh, "Remote port forwarding from %s refused",
4351 rpf = del234(ssh->rportfwds, pf);
4353 pf->pfrec->remote = NULL;
4358 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
4360 const char *portfwd_strptr = cfg->portfwd;
4361 struct ssh_portfwd *epf;
4364 if (!ssh->portfwds) {
4365 ssh->portfwds = newtree234(ssh_portcmp);
4368 * Go through the existing port forwardings and tag them
4369 * with status==DESTROY. Any that we want to keep will be
4370 * re-enabled (status==KEEP) as we go through the
4371 * configuration and find out which bits are the same as
4374 struct ssh_portfwd *epf;
4376 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4377 epf->status = DESTROY;
4380 while (*portfwd_strptr) {
4381 char address_family, type;
4382 int sport,dport,sserv,dserv;
4383 char sports[256], dports[256], saddr[256], host[256];
4386 address_family = 'A';
4388 if (*portfwd_strptr == 'A' ||
4389 *portfwd_strptr == '4' ||
4390 *portfwd_strptr == '6')
4391 address_family = *portfwd_strptr++;
4392 if (*portfwd_strptr == 'L' ||
4393 *portfwd_strptr == 'R' ||
4394 *portfwd_strptr == 'D')
4395 type = *portfwd_strptr++;
4400 while (*portfwd_strptr && *portfwd_strptr != '\t') {
4401 if (*portfwd_strptr == ':') {
4403 * We've seen a colon in the middle of the
4404 * source port number. This means that
4405 * everything we've seen until now is the
4406 * source _address_, so we'll move it into
4407 * saddr and start sports from the beginning
4412 if (ssh->version == 1 && type == 'R') {
4413 logeventf(ssh, "SSH-1 cannot handle remote source address "
4414 "spec \"%s\"; ignoring", sports);
4416 strcpy(saddr, sports);
4419 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
4423 if (*portfwd_strptr == '\t')
4426 while (*portfwd_strptr && *portfwd_strptr != ':') {
4427 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
4430 if (*portfwd_strptr == ':')
4433 while (*portfwd_strptr) {
4434 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
4438 dport = atoi(dports);
4442 dport = net_service_lookup(dports);
4444 logeventf(ssh, "Service lookup failed for destination"
4445 " port \"%s\"", dports);
4449 while (*portfwd_strptr) portfwd_strptr++;
4453 portfwd_strptr++; /* eat the NUL and move to next one */
4455 sport = atoi(sports);
4459 sport = net_service_lookup(sports);
4461 logeventf(ssh, "Service lookup failed for source"
4462 " port \"%s\"", sports);
4465 if (sport && dport) {
4466 /* Set up a description of the source port. */
4467 struct ssh_portfwd *pfrec, *epfrec;
4469 pfrec = snew(struct ssh_portfwd);
4471 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
4472 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4473 pfrec->sport = sport;
4474 pfrec->daddr = *host ? dupstr(host) : NULL;
4475 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4476 pfrec->dport = dport;
4477 pfrec->local = NULL;
4478 pfrec->remote = NULL;
4479 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4480 address_family == '6' ? ADDRTYPE_IPV6 :
4483 epfrec = add234(ssh->portfwds, pfrec);
4484 if (epfrec != pfrec) {
4485 if (epfrec->status == DESTROY) {
4487 * We already have a port forwarding up and running
4488 * with precisely these parameters. Hence, no need
4489 * to do anything; simply re-tag the existing one
4492 epfrec->status = KEEP;
4495 * Anything else indicates that there was a duplicate
4496 * in our input, which we'll silently ignore.
4498 free_portfwd(pfrec);
4500 pfrec->status = CREATE;
4506 * Now go through and destroy any port forwardings which were
4509 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4510 if (epf->status == DESTROY) {
4513 message = dupprintf("%s port forwarding from %s%s%d",
4514 epf->type == 'L' ? "local" :
4515 epf->type == 'R' ? "remote" : "dynamic",
4516 epf->saddr ? epf->saddr : "",
4517 epf->saddr ? ":" : "",
4520 if (epf->type != 'D') {
4521 char *msg2 = dupprintf("%s to %s:%d", message,
4522 epf->daddr, epf->dport);
4527 logeventf(ssh, "Cancelling %s", message);
4530 /* epf->remote or epf->local may be NULL if setting up a
4531 * forwarding failed. */
4533 struct ssh_rportfwd *rpf = epf->remote;
4534 struct Packet *pktout;
4537 * Cancel the port forwarding at the server
4540 if (ssh->version == 1) {
4542 * We cannot cancel listening ports on the
4543 * server side in SSH-1! There's no message
4544 * to support it. Instead, we simply remove
4545 * the rportfwd record from the local end
4546 * so that any connections the server tries
4547 * to make on it are rejected.
4550 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4551 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4552 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4554 ssh2_pkt_addstring(pktout, epf->saddr);
4555 } else if (ssh->cfg.rport_acceptall) {
4556 /* XXX: ssh->cfg.rport_acceptall may not represent
4557 * what was used to open the original connection,
4558 * since it's reconfigurable. */
4559 ssh2_pkt_addstring(pktout, "0.0.0.0");
4561 ssh2_pkt_addstring(pktout, "127.0.0.1");
4563 ssh2_pkt_adduint32(pktout, epf->sport);
4564 ssh2_pkt_send(ssh, pktout);
4567 del234(ssh->rportfwds, rpf);
4569 } else if (epf->local) {
4570 pfd_terminate(epf->local);
4573 delpos234(ssh->portfwds, i);
4575 i--; /* so we don't skip one in the list */
4579 * And finally, set up any new port forwardings (status==CREATE).
4581 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4582 if (epf->status == CREATE) {
4583 char *sportdesc, *dportdesc;
4584 sportdesc = dupprintf("%s%s%s%s%d%s",
4585 epf->saddr ? epf->saddr : "",
4586 epf->saddr ? ":" : "",
4587 epf->sserv ? epf->sserv : "",
4588 epf->sserv ? "(" : "",
4590 epf->sserv ? ")" : "");
4591 if (epf->type == 'D') {
4594 dportdesc = dupprintf("%s:%s%s%d%s",
4596 epf->dserv ? epf->dserv : "",
4597 epf->dserv ? "(" : "",
4599 epf->dserv ? ")" : "");
4602 if (epf->type == 'L') {
4603 const char *err = pfd_addforward(epf->daddr, epf->dport,
4604 epf->saddr, epf->sport,
4607 epf->addressfamily);
4609 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4610 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4611 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4612 sportdesc, dportdesc,
4613 err ? " failed: " : "", err ? err : "");
4614 } else if (epf->type == 'D') {
4615 const char *err = pfd_addforward(NULL, -1,
4616 epf->saddr, epf->sport,
4619 epf->addressfamily);
4621 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4622 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4623 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4625 err ? " failed: " : "", err ? err : "");
4627 struct ssh_rportfwd *pf;
4630 * Ensure the remote port forwardings tree exists.
4632 if (!ssh->rportfwds) {
4633 if (ssh->version == 1)
4634 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4636 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4639 pf = snew(struct ssh_rportfwd);
4640 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4641 pf->dhost[lenof(pf->dhost)-1] = '\0';
4642 pf->dport = epf->dport;
4643 pf->sport = epf->sport;
4644 if (add234(ssh->rportfwds, pf) != pf) {
4645 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4646 epf->daddr, epf->dport);
4649 logeventf(ssh, "Requesting remote port %s"
4650 " forward to %s", sportdesc, dportdesc);
4652 pf->sportdesc = sportdesc;
4657 if (ssh->version == 1) {
4658 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4659 PKT_INT, epf->sport,
4660 PKT_STR, epf->daddr,
4661 PKT_INT, epf->dport,
4663 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4665 ssh_rportfwd_succfail, pf);
4667 struct Packet *pktout;
4668 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4669 ssh2_pkt_addstring(pktout, "tcpip-forward");
4670 ssh2_pkt_addbool(pktout, 1);/* want reply */
4672 ssh2_pkt_addstring(pktout, epf->saddr);
4673 } else if (cfg->rport_acceptall) {
4674 ssh2_pkt_addstring(pktout, "0.0.0.0");
4676 ssh2_pkt_addstring(pktout, "127.0.0.1");
4678 ssh2_pkt_adduint32(pktout, epf->sport);
4679 ssh2_pkt_send(ssh, pktout);
4681 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4682 SSH2_MSG_REQUEST_FAILURE,
4683 ssh_rportfwd_succfail, pf);
4692 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4695 int stringlen, bufsize;
4697 ssh_pkt_getstring(pktin, &string, &stringlen);
4698 if (string == NULL) {
4699 bombout(("Incoming terminal data packet was badly formed"));
4703 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4705 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4706 ssh->v1_stdout_throttling = 1;
4707 ssh_throttle_conn(ssh, +1);
4711 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4713 /* Remote side is trying to open a channel to talk to our
4714 * X-Server. Give them back a local channel number. */
4715 struct ssh_channel *c;
4716 int remoteid = ssh_pkt_getuint32(pktin);
4718 logevent("Received X11 connect request");
4719 /* Refuse if X11 forwarding is disabled. */
4720 if (!ssh->X11_fwd_enabled) {
4721 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4722 PKT_INT, remoteid, PKT_END);
4723 logevent("Rejected X11 connect request");
4725 c = snew(struct ssh_channel);
4728 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4729 NULL, -1, &ssh->cfg) != NULL) {
4730 logevent("Opening X11 forward connection failed");
4732 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4733 PKT_INT, remoteid, PKT_END);
4736 ("Opening X11 forward connection succeeded");
4737 c->remoteid = remoteid;
4738 c->halfopen = FALSE;
4739 c->localid = alloc_channel_id(ssh);
4741 c->pending_close = FALSE;
4742 c->throttling_conn = 0;
4743 c->type = CHAN_X11; /* identify channel type */
4744 add234(ssh->channels, c);
4745 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4746 PKT_INT, c->remoteid, PKT_INT,
4747 c->localid, PKT_END);
4748 logevent("Opened X11 forward channel");
4753 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4755 /* Remote side is trying to open a channel to talk to our
4756 * agent. Give them back a local channel number. */
4757 struct ssh_channel *c;
4758 int remoteid = ssh_pkt_getuint32(pktin);
4760 /* Refuse if agent forwarding is disabled. */
4761 if (!ssh->agentfwd_enabled) {
4762 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4763 PKT_INT, remoteid, PKT_END);
4765 c = snew(struct ssh_channel);
4767 c->remoteid = remoteid;
4768 c->halfopen = FALSE;
4769 c->localid = alloc_channel_id(ssh);
4771 c->pending_close = FALSE;
4772 c->throttling_conn = 0;
4773 c->type = CHAN_AGENT; /* identify channel type */
4774 c->u.a.lensofar = 0;
4775 add234(ssh->channels, c);
4776 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4777 PKT_INT, c->remoteid, PKT_INT, c->localid,
4782 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4784 /* Remote side is trying to open a channel to talk to a
4785 * forwarded port. Give them back a local channel number. */
4786 struct ssh_channel *c;
4787 struct ssh_rportfwd pf, *pfp;
4792 c = snew(struct ssh_channel);
4795 remoteid = ssh_pkt_getuint32(pktin);
4796 ssh_pkt_getstring(pktin, &host, &hostsize);
4797 port = ssh_pkt_getuint32(pktin);
4799 if (hostsize >= lenof(pf.dhost))
4800 hostsize = lenof(pf.dhost)-1;
4801 memcpy(pf.dhost, host, hostsize);
4802 pf.dhost[hostsize] = '\0';
4804 pfp = find234(ssh->rportfwds, &pf, NULL);
4807 logeventf(ssh, "Rejected remote port open request for %s:%d",
4809 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4810 PKT_INT, remoteid, PKT_END);
4812 logeventf(ssh, "Received remote port open request for %s:%d",
4814 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4815 c, &ssh->cfg, pfp->pfrec->addressfamily);
4817 logeventf(ssh, "Port open failed: %s", e);
4819 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4820 PKT_INT, remoteid, PKT_END);
4822 c->remoteid = remoteid;
4823 c->halfopen = FALSE;
4824 c->localid = alloc_channel_id(ssh);
4826 c->pending_close = FALSE;
4827 c->throttling_conn = 0;
4828 c->type = CHAN_SOCKDATA; /* identify channel type */
4829 add234(ssh->channels, c);
4830 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4831 PKT_INT, c->remoteid, PKT_INT,
4832 c->localid, PKT_END);
4833 logevent("Forwarded port opened successfully");
4838 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4840 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4841 unsigned int localid = ssh_pkt_getuint32(pktin);
4842 struct ssh_channel *c;
4844 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4845 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4846 c->remoteid = localid;
4847 c->halfopen = FALSE;
4848 c->type = CHAN_SOCKDATA;
4849 c->throttling_conn = 0;
4850 pfd_confirm(c->u.pfd.s);
4853 if (c && c->closes) {
4855 * We have a pending close on this channel,
4856 * which we decided on before the server acked
4857 * the channel open. So now we know the
4858 * remoteid, we can close it again.
4860 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4861 PKT_INT, c->remoteid, PKT_END);
4865 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4867 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4868 struct ssh_channel *c;
4870 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4871 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4872 logevent("Forwarded connection refused by server");
4873 pfd_close(c->u.pfd.s);
4874 del234(ssh->channels, c);
4879 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4881 /* Remote side closes a channel. */
4882 unsigned i = ssh_pkt_getuint32(pktin);
4883 struct ssh_channel *c;
4884 c = find234(ssh->channels, &i, ssh_channelfind);
4885 if (c && !c->halfopen) {
4888 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4890 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4891 logevent("Forwarded X11 connection terminated");
4892 assert(c->u.x11.s != NULL);
4893 x11_close(c->u.x11.s);
4896 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4897 logevent("Forwarded port closed");
4898 assert(c->u.pfd.s != NULL);
4899 pfd_close(c->u.pfd.s);
4903 c->closes |= (closetype << 2); /* seen this message */
4904 if (!(c->closes & closetype)) {
4905 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4907 c->closes |= closetype; /* sent it too */
4910 if (c->closes == 15) {
4911 del234(ssh->channels, c);
4915 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4916 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4917 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4922 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4924 /* Data sent down one of our channels. */
4925 int i = ssh_pkt_getuint32(pktin);
4928 struct ssh_channel *c;
4930 ssh_pkt_getstring(pktin, &p, &len);
4932 c = find234(ssh->channels, &i, ssh_channelfind);
4937 bufsize = x11_send(c->u.x11.s, p, len);
4940 bufsize = pfd_send(c->u.pfd.s, p, len);
4943 /* Data for an agent message. Buffer it. */
4945 if (c->u.a.lensofar < 4) {
4946 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4947 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4951 c->u.a.lensofar += l;
4953 if (c->u.a.lensofar == 4) {
4955 4 + GET_32BIT(c->u.a.msglen);
4956 c->u.a.message = snewn(c->u.a.totallen,
4958 memcpy(c->u.a.message, c->u.a.msglen, 4);
4960 if (c->u.a.lensofar >= 4 && len > 0) {
4962 min(c->u.a.totallen - c->u.a.lensofar,
4964 memcpy(c->u.a.message + c->u.a.lensofar, p,
4968 c->u.a.lensofar += l;
4970 if (c->u.a.lensofar == c->u.a.totallen) {
4973 if (agent_query(c->u.a.message,
4976 ssh_agentf_callback, c))
4977 ssh_agentf_callback(c, reply, replylen);
4978 sfree(c->u.a.message);
4979 c->u.a.lensofar = 0;
4982 bufsize = 0; /* agent channels never back up */
4985 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
4986 c->throttling_conn = 1;
4987 ssh_throttle_conn(ssh, +1);
4992 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4994 ssh->exitcode = ssh_pkt_getuint32(pktin);
4995 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4996 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4998 * In case `helpful' firewalls or proxies tack
4999 * extra human-readable text on the end of the
5000 * session which we might mistake for another
5001 * encrypted packet, we close the session once
5002 * we've sent EXIT_CONFIRMATION.
5004 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5007 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5008 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5010 struct Packet *pktout = (struct Packet *)data;
5012 unsigned int arg = 0;
5013 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5014 if (i == lenof(ssh_ttymodes)) return;
5015 switch (ssh_ttymodes[i].type) {
5017 arg = ssh_tty_parse_specchar(val);
5020 arg = ssh_tty_parse_boolean(val);
5023 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5024 ssh2_pkt_addbyte(pktout, arg);
5028 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5029 struct Packet *pktin)
5031 crBegin(ssh->do_ssh1_connection_crstate);
5033 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5034 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5035 ssh1_smsg_stdout_stderr_data;
5037 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5038 ssh1_msg_channel_open_confirmation;
5039 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5040 ssh1_msg_channel_open_failure;
5041 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5042 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5043 ssh1_msg_channel_close;
5044 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5045 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5047 if (ssh->cfg.agentfwd && agent_exists()) {
5048 logevent("Requesting agent forwarding");
5049 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5053 if (pktin->type != SSH1_SMSG_SUCCESS
5054 && pktin->type != SSH1_SMSG_FAILURE) {
5055 bombout(("Protocol confusion"));
5057 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5058 logevent("Agent forwarding refused");
5060 logevent("Agent forwarding enabled");
5061 ssh->agentfwd_enabled = TRUE;
5062 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5066 if (ssh->cfg.x11_forward &&
5067 (ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
5068 ssh->cfg.x11_auth, &ssh->cfg))) {
5069 logevent("Requesting X11 forwarding");
5071 * Note that while we blank the X authentication data here, we don't
5072 * take any special action to blank the start of an X11 channel,
5073 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5074 * without having session blanking enabled is likely to leak your
5075 * cookie into the log.
5077 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5078 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5079 PKT_STR, ssh->x11disp->remoteauthprotoname,
5081 PKT_STR, ssh->x11disp->remoteauthdatastring,
5083 PKT_INT, ssh->x11disp->screennum,
5086 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5087 PKT_STR, ssh->x11disp->remoteauthprotoname,
5089 PKT_STR, ssh->x11disp->remoteauthdatastring,
5096 if (pktin->type != SSH1_SMSG_SUCCESS
5097 && pktin->type != SSH1_SMSG_FAILURE) {
5098 bombout(("Protocol confusion"));
5100 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5101 logevent("X11 forwarding refused");
5103 logevent("X11 forwarding enabled");
5104 ssh->X11_fwd_enabled = TRUE;
5105 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5109 ssh_setup_portfwd(ssh, &ssh->cfg);
5110 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5112 if (!ssh->cfg.nopty) {
5114 /* Unpick the terminal-speed string. */
5115 /* XXX perhaps we should allow no speeds to be sent. */
5116 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5117 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
5118 /* Send the pty request. */
5119 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5120 ssh_pkt_addstring(pkt, ssh->cfg.termtype);
5121 ssh_pkt_adduint32(pkt, ssh->term_height);
5122 ssh_pkt_adduint32(pkt, ssh->term_width);
5123 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5124 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5125 parse_ttymodes(ssh, ssh->cfg.ttymodes,
5126 ssh1_send_ttymode, (void *)pkt);
5127 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5128 ssh_pkt_adduint32(pkt, ssh->ispeed);
5129 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5130 ssh_pkt_adduint32(pkt, ssh->ospeed);
5131 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5133 ssh->state = SSH_STATE_INTERMED;
5137 if (pktin->type != SSH1_SMSG_SUCCESS
5138 && pktin->type != SSH1_SMSG_FAILURE) {
5139 bombout(("Protocol confusion"));
5141 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5142 c_write_str(ssh, "Server refused to allocate pty\r\n");
5143 ssh->editing = ssh->echoing = 1;
5145 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5146 ssh->ospeed, ssh->ispeed);
5148 ssh->editing = ssh->echoing = 1;
5151 if (ssh->cfg.compression) {
5152 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5156 if (pktin->type != SSH1_SMSG_SUCCESS
5157 && pktin->type != SSH1_SMSG_FAILURE) {
5158 bombout(("Protocol confusion"));
5160 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5161 c_write_str(ssh, "Server refused to compress\r\n");
5163 logevent("Started compression");
5164 ssh->v1_compressing = TRUE;
5165 ssh->cs_comp_ctx = zlib_compress_init();
5166 logevent("Initialised zlib (RFC1950) compression");
5167 ssh->sc_comp_ctx = zlib_decompress_init();
5168 logevent("Initialised zlib (RFC1950) decompression");
5172 * Start the shell or command.
5174 * Special case: if the first-choice command is an SSH-2
5175 * subsystem (hence not usable here) and the second choice
5176 * exists, we fall straight back to that.
5179 char *cmd = ssh->cfg.remote_cmd_ptr;
5181 if (!cmd) cmd = ssh->cfg.remote_cmd;
5183 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
5184 cmd = ssh->cfg.remote_cmd_ptr2;
5185 ssh->fallback_cmd = TRUE;
5188 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5190 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5191 logevent("Started session");
5194 ssh->state = SSH_STATE_SESSION;
5195 if (ssh->size_needed)
5196 ssh_size(ssh, ssh->term_width, ssh->term_height);
5197 if (ssh->eof_needed)
5198 ssh_special(ssh, TS_EOF);
5201 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5203 ssh->channels = newtree234(ssh_channelcmp);
5207 * By this point, most incoming packets are already being
5208 * handled by the dispatch table, and we need only pay
5209 * attention to the unusual ones.
5214 if (pktin->type == SSH1_SMSG_SUCCESS) {
5215 /* may be from EXEC_SHELL on some servers */
5216 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5217 /* may be from EXEC_SHELL on some servers
5218 * if no pty is available or in other odd cases. Ignore */
5220 bombout(("Strange packet received: type %d", pktin->type));
5225 int len = min(inlen, 512);
5226 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5227 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5228 PKTT_OTHER, PKT_END);
5239 * Handle the top-level SSH-2 protocol.
5241 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5246 ssh_pkt_getstring(pktin, &msg, &msglen);
5247 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5250 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5252 /* log reason code in disconnect message */
5256 ssh_pkt_getstring(pktin, &msg, &msglen);
5257 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5260 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5262 /* Do nothing, because we're ignoring it! Duhh. */
5265 static void ssh1_protocol_setup(Ssh ssh)
5270 * Most messages are handled by the coroutines.
5272 for (i = 0; i < 256; i++)
5273 ssh->packet_dispatch[i] = NULL;
5276 * These special message types we install handlers for.
5278 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5279 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5280 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5283 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5284 struct Packet *pktin)
5286 unsigned char *in=(unsigned char*)vin;
5287 if (ssh->state == SSH_STATE_CLOSED)
5290 if (pktin && ssh->packet_dispatch[pktin->type]) {
5291 ssh->packet_dispatch[pktin->type](ssh, pktin);
5295 if (!ssh->protocol_initial_phase_done) {
5296 if (do_ssh1_login(ssh, in, inlen, pktin))
5297 ssh->protocol_initial_phase_done = TRUE;
5302 do_ssh1_connection(ssh, in, inlen, pktin);
5306 * Utility routine for decoding comma-separated strings in KEXINIT.
5308 static int in_commasep_string(char *needle, char *haystack, int haylen)
5311 if (!needle || !haystack) /* protect against null pointers */
5313 needlen = strlen(needle);
5316 * Is it at the start of the string?
5318 if (haylen >= needlen && /* haystack is long enough */
5319 !memcmp(needle, haystack, needlen) && /* initial match */
5320 (haylen == needlen || haystack[needlen] == ',')
5321 /* either , or EOS follows */
5325 * If not, search for the next comma and resume after that.
5326 * If no comma found, terminate.
5328 while (haylen > 0 && *haystack != ',')
5329 haylen--, haystack++;
5332 haylen--, haystack++; /* skip over comma itself */
5337 * Similar routine for checking whether we have the first string in a list.
5339 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5342 if (!needle || !haystack) /* protect against null pointers */
5344 needlen = strlen(needle);
5346 * Is it at the start of the string?
5348 if (haylen >= needlen && /* haystack is long enough */
5349 !memcmp(needle, haystack, needlen) && /* initial match */
5350 (haylen == needlen || haystack[needlen] == ',')
5351 /* either , or EOS follows */
5359 * SSH-2 key creation method.
5360 * (Currently assumes 2 lots of any hash are sufficient to generate
5361 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5363 #define SSH2_MKKEY_ITERS (2)
5364 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5365 unsigned char *keyspace)
5367 const struct ssh_hash *h = ssh->kex->hash;
5369 /* First hlen bytes. */
5371 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5372 hash_mpint(h, s, K);
5373 h->bytes(s, H, h->hlen);
5374 h->bytes(s, &chr, 1);
5375 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5376 h->final(s, keyspace);
5377 /* Next hlen bytes. */
5379 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5380 hash_mpint(h, s, K);
5381 h->bytes(s, H, h->hlen);
5382 h->bytes(s, keyspace, h->hlen);
5383 h->final(s, keyspace + h->hlen);
5387 * Handle the SSH-2 transport layer.
5389 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5390 struct Packet *pktin)
5392 unsigned char *in = (unsigned char *)vin;
5393 struct do_ssh2_transport_state {
5394 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5395 Bignum p, g, e, f, K;
5398 int kex_init_value, kex_reply_value;
5399 const struct ssh_mac **maclist;
5401 const struct ssh2_cipher *cscipher_tobe;
5402 const struct ssh2_cipher *sccipher_tobe;
5403 const struct ssh_mac *csmac_tobe;
5404 const struct ssh_mac *scmac_tobe;
5405 const struct ssh_compress *cscomp_tobe;
5406 const struct ssh_compress *sccomp_tobe;
5407 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5408 int hostkeylen, siglen, rsakeylen;
5409 void *hkey; /* actual host key */
5410 void *rsakey; /* for RSA kex */
5411 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5412 int n_preferred_kex;
5413 const struct ssh_kexes *preferred_kex[KEX_MAX];
5414 int n_preferred_ciphers;
5415 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5416 const struct ssh_compress *preferred_comp;
5417 int got_session_id, activated_authconn;
5418 struct Packet *pktout;
5423 crState(do_ssh2_transport_state);
5425 crBegin(ssh->do_ssh2_transport_crstate);
5427 s->cscipher_tobe = s->sccipher_tobe = NULL;
5428 s->csmac_tobe = s->scmac_tobe = NULL;
5429 s->cscomp_tobe = s->sccomp_tobe = NULL;
5431 s->got_session_id = s->activated_authconn = FALSE;
5434 * Be prepared to work around the buggy MAC problem.
5436 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5437 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5439 s->maclist = macs, s->nmacs = lenof(macs);
5442 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5444 int i, j, commalist_started;
5447 * Set up the preferred key exchange. (NULL => warn below here)
5449 s->n_preferred_kex = 0;
5450 for (i = 0; i < KEX_MAX; i++) {
5451 switch (ssh->cfg.ssh_kexlist[i]) {
5453 s->preferred_kex[s->n_preferred_kex++] =
5454 &ssh_diffiehellman_gex;
5457 s->preferred_kex[s->n_preferred_kex++] =
5458 &ssh_diffiehellman_group14;
5461 s->preferred_kex[s->n_preferred_kex++] =
5462 &ssh_diffiehellman_group1;
5465 s->preferred_kex[s->n_preferred_kex++] =
5469 /* Flag for later. Don't bother if it's the last in
5471 if (i < KEX_MAX - 1) {
5472 s->preferred_kex[s->n_preferred_kex++] = NULL;
5479 * Set up the preferred ciphers. (NULL => warn below here)
5481 s->n_preferred_ciphers = 0;
5482 for (i = 0; i < CIPHER_MAX; i++) {
5483 switch (ssh->cfg.ssh_cipherlist[i]) {
5484 case CIPHER_BLOWFISH:
5485 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5488 if (ssh->cfg.ssh2_des_cbc) {
5489 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5493 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5496 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5498 case CIPHER_ARCFOUR:
5499 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5502 /* Flag for later. Don't bother if it's the last in
5504 if (i < CIPHER_MAX - 1) {
5505 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5512 * Set up preferred compression.
5514 if (ssh->cfg.compression)
5515 s->preferred_comp = &ssh_zlib;
5517 s->preferred_comp = &ssh_comp_none;
5520 * Enable queueing of outgoing auth- or connection-layer
5521 * packets while we are in the middle of a key exchange.
5523 ssh->queueing = TRUE;
5526 * Flag that KEX is in progress.
5528 ssh->kex_in_progress = TRUE;
5531 * Construct and send our key exchange packet.
5533 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5534 for (i = 0; i < 16; i++)
5535 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5536 /* List key exchange algorithms. */
5537 ssh2_pkt_addstring_start(s->pktout);
5538 commalist_started = 0;
5539 for (i = 0; i < s->n_preferred_kex; i++) {
5540 const struct ssh_kexes *k = s->preferred_kex[i];
5541 if (!k) continue; /* warning flag */
5542 for (j = 0; j < k->nkexes; j++) {
5543 if (commalist_started)
5544 ssh2_pkt_addstring_str(s->pktout, ",");
5545 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5546 commalist_started = 1;
5549 /* List server host key algorithms. */
5550 ssh2_pkt_addstring_start(s->pktout);
5551 for (i = 0; i < lenof(hostkey_algs); i++) {
5552 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5553 if (i < lenof(hostkey_algs) - 1)
5554 ssh2_pkt_addstring_str(s->pktout, ",");
5556 /* List client->server encryption algorithms. */
5557 ssh2_pkt_addstring_start(s->pktout);
5558 commalist_started = 0;
5559 for (i = 0; i < s->n_preferred_ciphers; i++) {
5560 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5561 if (!c) continue; /* warning flag */
5562 for (j = 0; j < c->nciphers; j++) {
5563 if (commalist_started)
5564 ssh2_pkt_addstring_str(s->pktout, ",");
5565 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5566 commalist_started = 1;
5569 /* List server->client encryption algorithms. */
5570 ssh2_pkt_addstring_start(s->pktout);
5571 commalist_started = 0;
5572 for (i = 0; i < s->n_preferred_ciphers; i++) {
5573 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5574 if (!c) continue; /* warning flag */
5575 for (j = 0; j < c->nciphers; j++) {
5576 if (commalist_started)
5577 ssh2_pkt_addstring_str(s->pktout, ",");
5578 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5579 commalist_started = 1;
5582 /* List client->server MAC algorithms. */
5583 ssh2_pkt_addstring_start(s->pktout);
5584 for (i = 0; i < s->nmacs; i++) {
5585 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5586 if (i < s->nmacs - 1)
5587 ssh2_pkt_addstring_str(s->pktout, ",");
5589 /* List server->client MAC algorithms. */
5590 ssh2_pkt_addstring_start(s->pktout);
5591 for (i = 0; i < s->nmacs; i++) {
5592 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5593 if (i < s->nmacs - 1)
5594 ssh2_pkt_addstring_str(s->pktout, ",");
5596 /* List client->server compression algorithms. */
5597 ssh2_pkt_addstring_start(s->pktout);
5598 assert(lenof(compressions) > 1);
5599 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5600 for (i = 0; i < lenof(compressions); i++) {
5601 const struct ssh_compress *c = compressions[i];
5602 if (c != s->preferred_comp) {
5603 ssh2_pkt_addstring_str(s->pktout, ",");
5604 ssh2_pkt_addstring_str(s->pktout, c->name);
5607 /* List server->client compression algorithms. */
5608 ssh2_pkt_addstring_start(s->pktout);
5609 assert(lenof(compressions) > 1);
5610 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5611 for (i = 0; i < lenof(compressions); i++) {
5612 const struct ssh_compress *c = compressions[i];
5613 if (c != s->preferred_comp) {
5614 ssh2_pkt_addstring_str(s->pktout, ",");
5615 ssh2_pkt_addstring_str(s->pktout, c->name);
5618 /* List client->server languages. Empty list. */
5619 ssh2_pkt_addstring_start(s->pktout);
5620 /* List server->client languages. Empty list. */
5621 ssh2_pkt_addstring_start(s->pktout);
5622 /* First KEX packet does _not_ follow, because we're not that brave. */
5623 ssh2_pkt_addbool(s->pktout, FALSE);
5625 ssh2_pkt_adduint32(s->pktout, 0);
5628 s->our_kexinitlen = s->pktout->length - 5;
5629 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5630 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5632 ssh2_pkt_send_noqueue(ssh, s->pktout);
5638 * Now examine the other side's KEXINIT to see what we're up
5642 char *str, *preferred;
5645 if (pktin->type != SSH2_MSG_KEXINIT) {
5646 bombout(("expected key exchange packet from server"));
5650 ssh->hostkey = NULL;
5651 s->cscipher_tobe = NULL;
5652 s->sccipher_tobe = NULL;
5653 s->csmac_tobe = NULL;
5654 s->scmac_tobe = NULL;
5655 s->cscomp_tobe = NULL;
5656 s->sccomp_tobe = NULL;
5657 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5659 pktin->savedpos += 16; /* skip garbage cookie */
5660 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5663 for (i = 0; i < s->n_preferred_kex; i++) {
5664 const struct ssh_kexes *k = s->preferred_kex[i];
5668 for (j = 0; j < k->nkexes; j++) {
5669 if (!preferred) preferred = k->list[j]->name;
5670 if (in_commasep_string(k->list[j]->name, str, len)) {
5671 ssh->kex = k->list[j];
5680 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5681 str ? str : "(null)"));
5685 * Note that the server's guess is considered wrong if it doesn't match
5686 * the first algorithm in our list, even if it's still the algorithm
5689 s->guessok = first_in_commasep_string(preferred, str, len);
5690 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5691 for (i = 0; i < lenof(hostkey_algs); i++) {
5692 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5693 ssh->hostkey = hostkey_algs[i];
5697 s->guessok = s->guessok &&
5698 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5699 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5700 for (i = 0; i < s->n_preferred_ciphers; i++) {
5701 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5703 s->warn_cscipher = TRUE;
5705 for (j = 0; j < c->nciphers; j++) {
5706 if (in_commasep_string(c->list[j]->name, str, len)) {
5707 s->cscipher_tobe = c->list[j];
5712 if (s->cscipher_tobe)
5715 if (!s->cscipher_tobe) {
5716 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5717 str ? str : "(null)"));
5721 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5722 for (i = 0; i < s->n_preferred_ciphers; i++) {
5723 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5725 s->warn_sccipher = TRUE;
5727 for (j = 0; j < c->nciphers; j++) {
5728 if (in_commasep_string(c->list[j]->name, str, len)) {
5729 s->sccipher_tobe = c->list[j];
5734 if (s->sccipher_tobe)
5737 if (!s->sccipher_tobe) {
5738 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5739 str ? str : "(null)"));
5743 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5744 for (i = 0; i < s->nmacs; i++) {
5745 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5746 s->csmac_tobe = s->maclist[i];
5750 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5751 for (i = 0; i < s->nmacs; i++) {
5752 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5753 s->scmac_tobe = s->maclist[i];
5757 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5758 for (i = 0; i < lenof(compressions) + 1; i++) {
5759 const struct ssh_compress *c =
5760 i == 0 ? s->preferred_comp : compressions[i - 1];
5761 if (in_commasep_string(c->name, str, len)) {
5766 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5767 for (i = 0; i < lenof(compressions) + 1; i++) {
5768 const struct ssh_compress *c =
5769 i == 0 ? s->preferred_comp : compressions[i - 1];
5770 if (in_commasep_string(c->name, str, len)) {
5775 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5776 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5777 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5780 ssh_set_frozen(ssh, 1);
5781 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5783 ssh_dialog_callback, ssh);
5784 if (s->dlgret < 0) {
5788 bombout(("Unexpected data from server while"
5789 " waiting for user response"));
5792 } while (pktin || inlen > 0);
5793 s->dlgret = ssh->user_response;
5795 ssh_set_frozen(ssh, 0);
5796 if (s->dlgret == 0) {
5797 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5803 if (s->warn_cscipher) {
5804 ssh_set_frozen(ssh, 1);
5805 s->dlgret = askalg(ssh->frontend,
5806 "client-to-server cipher",
5807 s->cscipher_tobe->name,
5808 ssh_dialog_callback, ssh);
5809 if (s->dlgret < 0) {
5813 bombout(("Unexpected data from server while"
5814 " waiting for user response"));
5817 } while (pktin || inlen > 0);
5818 s->dlgret = ssh->user_response;
5820 ssh_set_frozen(ssh, 0);
5821 if (s->dlgret == 0) {
5822 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5828 if (s->warn_sccipher) {
5829 ssh_set_frozen(ssh, 1);
5830 s->dlgret = askalg(ssh->frontend,
5831 "server-to-client cipher",
5832 s->sccipher_tobe->name,
5833 ssh_dialog_callback, ssh);
5834 if (s->dlgret < 0) {
5838 bombout(("Unexpected data from server while"
5839 " waiting for user response"));
5842 } while (pktin || inlen > 0);
5843 s->dlgret = ssh->user_response;
5845 ssh_set_frozen(ssh, 0);
5846 if (s->dlgret == 0) {
5847 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5853 ssh->exhash = ssh->kex->hash->init();
5854 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5855 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5856 hash_string(ssh->kex->hash, ssh->exhash,
5857 s->our_kexinit, s->our_kexinitlen);
5858 sfree(s->our_kexinit);
5859 if (pktin->length > 5)
5860 hash_string(ssh->kex->hash, ssh->exhash,
5861 pktin->data + 5, pktin->length - 5);
5863 if (s->ignorepkt) /* first_kex_packet_follows */
5864 crWaitUntil(pktin); /* Ignore packet */
5867 if (ssh->kex->main_type == KEXTYPE_DH) {
5869 * Work out the number of bits of key we will need from the
5870 * key exchange. We start with the maximum key length of
5876 csbits = s->cscipher_tobe->keylen;
5877 scbits = s->sccipher_tobe->keylen;
5878 s->nbits = (csbits > scbits ? csbits : scbits);
5880 /* The keys only have hlen-bit entropy, since they're based on
5881 * a hash. So cap the key size at hlen bits. */
5882 if (s->nbits > ssh->kex->hash->hlen * 8)
5883 s->nbits = ssh->kex->hash->hlen * 8;
5886 * If we're doing Diffie-Hellman group exchange, start by
5887 * requesting a group.
5889 if (!ssh->kex->pdata) {
5890 logevent("Doing Diffie-Hellman group exchange");
5891 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5893 * Work out how big a DH group we will need to allow that
5896 s->pbits = 512 << ((s->nbits - 1) / 64);
5897 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5898 ssh2_pkt_adduint32(s->pktout, s->pbits);
5899 ssh2_pkt_send_noqueue(ssh, s->pktout);
5902 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5903 bombout(("expected key exchange group packet from server"));
5906 s->p = ssh2_pkt_getmp(pktin);
5907 s->g = ssh2_pkt_getmp(pktin);
5908 if (!s->p || !s->g) {
5909 bombout(("unable to read mp-ints from incoming group packet"));
5912 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5913 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5914 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5916 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5917 ssh->kex_ctx = dh_setup_group(ssh->kex);
5918 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5919 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5920 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5921 ssh->kex->groupname);
5924 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5925 ssh->kex->hash->text_name);
5927 * Now generate and send e for Diffie-Hellman.
5929 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5930 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5931 s->pktout = ssh2_pkt_init(s->kex_init_value);
5932 ssh2_pkt_addmp(s->pktout, s->e);
5933 ssh2_pkt_send_noqueue(ssh, s->pktout);
5935 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5937 if (pktin->type != s->kex_reply_value) {
5938 bombout(("expected key exchange reply packet from server"));
5941 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5942 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5943 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5944 s->f = ssh2_pkt_getmp(pktin);
5946 bombout(("unable to parse key exchange reply packet"));
5949 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5951 s->K = dh_find_K(ssh->kex_ctx, s->f);
5953 /* We assume everything from now on will be quick, and it might
5954 * involve user interaction. */
5955 set_busy_status(ssh->frontend, BUSY_NOT);
5957 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5958 if (!ssh->kex->pdata) {
5959 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
5960 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
5961 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
5963 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
5964 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
5966 dh_cleanup(ssh->kex_ctx);
5968 if (!ssh->kex->pdata) {
5973 logeventf(ssh, "Doing RSA key exchange with hash %s",
5974 ssh->kex->hash->text_name);
5975 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
5977 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5981 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
5982 bombout(("expected RSA public key packet from server"));
5986 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5987 hash_string(ssh->kex->hash, ssh->exhash,
5988 s->hostkeydata, s->hostkeylen);
5989 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5993 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
5994 s->rsakeydata = snewn(s->rsakeylen, char);
5995 memcpy(s->rsakeydata, keydata, s->rsakeylen);
5998 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6000 sfree(s->rsakeydata);
6001 bombout(("unable to parse RSA public key from server"));
6005 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6008 * Next, set up a shared secret K, of precisely KLEN -
6009 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6010 * RSA key modulus and HLEN is the bit length of the hash
6014 int klen = ssh_rsakex_klen(s->rsakey);
6015 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6017 unsigned char *kstr1, *kstr2, *outstr;
6018 int kstr1len, kstr2len, outstrlen;
6020 s->K = bn_power_2(nbits - 1);
6022 for (i = 0; i < nbits; i++) {
6024 byte = random_byte();
6026 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6030 * Encode this as an mpint.
6032 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6033 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6034 PUT_32BIT(kstr2, kstr1len);
6035 memcpy(kstr2 + 4, kstr1, kstr1len);
6038 * Encrypt it with the given RSA key.
6040 outstrlen = (klen + 7) / 8;
6041 outstr = snewn(outstrlen, unsigned char);
6042 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6043 outstr, outstrlen, s->rsakey);
6046 * And send it off in a return packet.
6048 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6049 ssh2_pkt_addstring_start(s->pktout);
6050 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6051 ssh2_pkt_send_noqueue(ssh, s->pktout);
6053 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6060 ssh_rsakex_freekey(s->rsakey);
6063 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6064 sfree(s->rsakeydata);
6065 bombout(("expected signature packet from server"));
6069 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6071 sfree(s->rsakeydata);
6074 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6075 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6076 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6078 ssh->kex_ctx = NULL;
6081 debug(("Exchange hash is:\n"));
6082 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6086 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6087 (char *)s->exchange_hash,
6088 ssh->kex->hash->hlen)) {
6089 bombout(("Server's host key did not match the signature supplied"));
6094 * Authenticate remote host: verify host key. (We've already
6095 * checked the signature of the exchange hash.)
6097 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6098 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6099 ssh_set_frozen(ssh, 1);
6100 s->dlgret = verify_ssh_host_key(ssh->frontend,
6101 ssh->savedhost, ssh->savedport,
6102 ssh->hostkey->keytype, s->keystr,
6104 ssh_dialog_callback, ssh);
6105 if (s->dlgret < 0) {
6109 bombout(("Unexpected data from server while waiting"
6110 " for user host key response"));
6113 } while (pktin || inlen > 0);
6114 s->dlgret = ssh->user_response;
6116 ssh_set_frozen(ssh, 0);
6117 if (s->dlgret == 0) {
6118 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6122 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6123 logevent("Host key fingerprint is:");
6124 logevent(s->fingerprint);
6126 sfree(s->fingerprint);
6128 ssh->hostkey->freekey(s->hkey);
6131 * The exchange hash from the very first key exchange is also
6132 * the session id, used in session key construction and
6135 if (!s->got_session_id) {
6136 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6137 memcpy(ssh->v2_session_id, s->exchange_hash,
6138 sizeof(s->exchange_hash));
6139 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6140 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6141 s->got_session_id = TRUE;
6145 * Send SSH2_MSG_NEWKEYS.
6147 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6148 ssh2_pkt_send_noqueue(ssh, s->pktout);
6149 ssh->outgoing_data_size = 0; /* start counting from here */
6152 * We've sent client NEWKEYS, so create and initialise
6153 * client-to-server session keys.
6155 if (ssh->cs_cipher_ctx)
6156 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6157 ssh->cscipher = s->cscipher_tobe;
6158 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6160 if (ssh->cs_mac_ctx)
6161 ssh->csmac->free_context(ssh->cs_mac_ctx);
6162 ssh->csmac = s->csmac_tobe;
6163 ssh->cs_mac_ctx = ssh->csmac->make_context();
6165 if (ssh->cs_comp_ctx)
6166 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6167 ssh->cscomp = s->cscomp_tobe;
6168 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6171 * Set IVs on client-to-server keys. Here we use the exchange
6172 * hash from the _first_ key exchange.
6175 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6176 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6177 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6178 assert((ssh->cscipher->keylen+7) / 8 <=
6179 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6180 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6181 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6182 assert(ssh->cscipher->blksize <=
6183 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6184 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6185 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6186 assert(ssh->csmac->len <=
6187 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6188 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6189 memset(keyspace, 0, sizeof(keyspace));
6192 logeventf(ssh, "Initialised %.200s client->server encryption",
6193 ssh->cscipher->text_name);
6194 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6195 ssh->csmac->text_name);
6196 if (ssh->cscomp->text_name)
6197 logeventf(ssh, "Initialised %s compression",
6198 ssh->cscomp->text_name);
6201 * Now our end of the key exchange is complete, we can send all
6202 * our queued higher-layer packets.
6204 ssh->queueing = FALSE;
6205 ssh2_pkt_queuesend(ssh);
6208 * Expect SSH2_MSG_NEWKEYS from server.
6211 if (pktin->type != SSH2_MSG_NEWKEYS) {
6212 bombout(("expected new-keys packet from server"));
6215 ssh->incoming_data_size = 0; /* start counting from here */
6218 * We've seen server NEWKEYS, so create and initialise
6219 * server-to-client session keys.
6221 if (ssh->sc_cipher_ctx)
6222 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6223 ssh->sccipher = s->sccipher_tobe;
6224 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6226 if (ssh->sc_mac_ctx)
6227 ssh->scmac->free_context(ssh->sc_mac_ctx);
6228 ssh->scmac = s->scmac_tobe;
6229 ssh->sc_mac_ctx = ssh->scmac->make_context();
6231 if (ssh->sc_comp_ctx)
6232 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6233 ssh->sccomp = s->sccomp_tobe;
6234 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6237 * Set IVs on server-to-client keys. Here we use the exchange
6238 * hash from the _first_ key exchange.
6241 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6242 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6243 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6244 assert((ssh->sccipher->keylen+7) / 8 <=
6245 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6246 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6247 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6248 assert(ssh->sccipher->blksize <=
6249 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6250 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6251 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6252 assert(ssh->scmac->len <=
6253 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6254 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6255 memset(keyspace, 0, sizeof(keyspace));
6257 logeventf(ssh, "Initialised %.200s server->client encryption",
6258 ssh->sccipher->text_name);
6259 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6260 ssh->scmac->text_name);
6261 if (ssh->sccomp->text_name)
6262 logeventf(ssh, "Initialised %s decompression",
6263 ssh->sccomp->text_name);
6266 * Free shared secret.
6271 * Key exchange is over. Loop straight back round if we have a
6272 * deferred rekey reason.
6274 if (ssh->deferred_rekey_reason) {
6275 logevent(ssh->deferred_rekey_reason);
6277 ssh->deferred_rekey_reason = NULL;
6278 goto begin_key_exchange;
6282 * Otherwise, schedule a timer for our next rekey.
6284 ssh->kex_in_progress = FALSE;
6285 ssh->last_rekey = GETTICKCOUNT();
6286 if (ssh->cfg.ssh_rekey_time != 0)
6287 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6291 * If this is the first key exchange phase, we must pass the
6292 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6293 * wants to see it but because it will need time to initialise
6294 * itself before it sees an actual packet. In subsequent key
6295 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6296 * it would only confuse the layer above.
6298 if (s->activated_authconn) {
6301 s->activated_authconn = TRUE;
6304 * Now we're encrypting. Begin returning 1 to the protocol main
6305 * function so that other things can run on top of the
6306 * transport. If we ever see a KEXINIT, we must go back to the
6309 * We _also_ go back to the start if we see pktin==NULL and
6310 * inlen==-1, because this is a special signal meaning
6311 * `initiate client-driven rekey', and `in' contains a message
6312 * giving the reason for the rekey.
6314 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6315 (!pktin && inlen == -1))) {
6320 logevent("Server initiated key re-exchange");
6323 * Special case: if the server bug is set that doesn't
6324 * allow rekeying, we give a different log message and
6325 * continue waiting. (If such a server _initiates_ a rekey,
6326 * we process it anyway!)
6328 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6329 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6331 /* Reset the counters, so that at least this message doesn't
6332 * hit the event log _too_ often. */
6333 ssh->outgoing_data_size = 0;
6334 ssh->incoming_data_size = 0;
6335 if (ssh->cfg.ssh_rekey_time != 0) {
6337 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6340 goto wait_for_rekey; /* this is utterly horrid */
6342 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6345 goto begin_key_exchange;
6351 * Add data to an SSH-2 channel output buffer.
6353 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6356 bufchain_add(&c->v.v2.outbuffer, buf, len);
6360 * Attempt to send data on an SSH-2 channel.
6362 static int ssh2_try_send(struct ssh_channel *c)
6365 struct Packet *pktout;
6367 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6370 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6371 if ((unsigned)len > c->v.v2.remwindow)
6372 len = c->v.v2.remwindow;
6373 if ((unsigned)len > c->v.v2.remmaxpkt)
6374 len = c->v.v2.remmaxpkt;
6375 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6376 ssh2_pkt_adduint32(pktout, c->remoteid);
6377 ssh2_pkt_addstring_start(pktout);
6378 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6379 ssh2_pkt_addstring_data(pktout, data, len);
6380 end_log_omission(ssh, pktout);
6381 ssh2_pkt_send(ssh, pktout);
6382 bufchain_consume(&c->v.v2.outbuffer, len);
6383 c->v.v2.remwindow -= len;
6387 * After having sent as much data as we can, return the amount
6390 return bufchain_size(&c->v.v2.outbuffer);
6393 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6397 return; /* don't send on closing channels */
6398 bufsize = ssh2_try_send(c);
6401 case CHAN_MAINSESSION:
6402 /* stdin need not receive an unthrottle
6403 * notification since it will be polled */
6406 x11_unthrottle(c->u.x11.s);
6409 /* agent sockets are request/response and need no
6410 * buffer management */
6413 pfd_unthrottle(c->u.pfd.s);
6419 * If we've emptied the channel's output buffer and there's a
6420 * pending close event, start the channel-closing procedure.
6422 if (c->pending_close && bufchain_size(&c->v.v2.outbuffer) == 0) {
6423 struct Packet *pktout;
6424 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6425 ssh2_pkt_adduint32(pktout, c->remoteid);
6426 ssh2_pkt_send(ssh, pktout);
6428 c->pending_close = FALSE;
6433 * Set up most of a new ssh_channel for SSH-2.
6435 static void ssh2_channel_init(struct ssh_channel *c)
6438 c->localid = alloc_channel_id(ssh);
6440 c->pending_close = FALSE;
6441 c->throttling_conn = FALSE;
6442 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6443 ssh->cfg.ssh_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6444 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6445 c->v.v2.throttle_state = UNTHROTTLED;
6446 bufchain_init(&c->v.v2.outbuffer);
6450 * Potentially enlarge the window on an SSH-2 channel.
6452 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6457 * Never send WINDOW_ADJUST for a channel that the remote side
6458 * already thinks it's closed; there's no point, since it won't
6459 * be sending any more data anyway.
6465 * If the remote end has a habit of ignoring maxpkt, limit the
6466 * window so that it has no choice (assuming it doesn't ignore the
6469 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6470 newwin = OUR_V2_MAXPKT;
6474 * Only send a WINDOW_ADJUST if there's significantly more window
6475 * available than the other end thinks there is. This saves us
6476 * sending a WINDOW_ADJUST for every character in a shell session.
6478 * "Significant" is arbitrarily defined as half the window size.
6480 if (newwin / 2 >= c->v.v2.locwindow) {
6481 struct Packet *pktout;
6485 * In order to keep track of how much window the client
6486 * actually has available, we'd like it to acknowledge each
6487 * WINDOW_ADJUST. We can't do that directly, so we accompany
6488 * it with a CHANNEL_REQUEST that has to be acknowledged.
6490 * This is only necessary if we're opening the window wide.
6491 * If we're not, then throughput is being constrained by
6492 * something other than the maximum window size anyway.
6494 * We also only send this if the main channel has finished its
6495 * initial CHANNEL_REQUESTs and installed the default
6496 * CHANNEL_FAILURE handler, so as not to risk giving it
6497 * unexpected CHANNEL_FAILUREs.
6499 if (newwin == c->v.v2.locmaxwin &&
6500 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6501 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6502 ssh2_pkt_adduint32(pktout, c->remoteid);
6503 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6504 ssh2_pkt_addbool(pktout, TRUE);
6505 ssh2_pkt_send(ssh, pktout);
6508 * CHANNEL_FAILURE doesn't come with any indication of
6509 * what message caused it, so we have to keep track of the
6510 * outstanding CHANNEL_REQUESTs ourselves.
6512 wa = snew(struct winadj);
6513 wa->size = newwin - c->v.v2.locwindow;
6515 if (!c->v.v2.winadj_head)
6516 c->v.v2.winadj_head = wa;
6518 c->v.v2.winadj_tail->next = wa;
6519 c->v.v2.winadj_tail = wa;
6520 if (c->v.v2.throttle_state != UNTHROTTLED)
6521 c->v.v2.throttle_state = UNTHROTTLING;
6523 /* Pretend the WINDOW_ADJUST was acked immediately. */
6524 c->v.v2.remlocwin = newwin;
6525 c->v.v2.throttle_state = THROTTLED;
6527 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6528 ssh2_pkt_adduint32(pktout, c->remoteid);
6529 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6530 ssh2_pkt_send(ssh, pktout);
6531 c->v.v2.locwindow = newwin;
6536 * Find the channel associated with a message. If there's no channel,
6537 * or it's not properly open, make a noise about it and return NULL.
6539 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6541 unsigned localid = ssh_pkt_getuint32(pktin);
6542 struct ssh_channel *c;
6544 c = find234(ssh->channels, &localid, ssh_channelfind);
6546 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6547 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6548 char *buf = dupprintf("Received %s for %s channel %u",
6549 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6551 c ? "half-open" : "nonexistent", localid);
6552 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6559 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6562 * This should never get called. All channel requests are either
6563 * sent with want_reply false or are sent before this handler gets
6566 struct ssh_channel *c;
6569 c = ssh2_channel_msg(ssh, pktin);
6572 wa = c->v.v2.winadj_head;
6574 ssh_disconnect(ssh, NULL, "Received SSH_MSG_CHANNEL_SUCCESS for "
6575 "\"winadj@putty.projects.tartarus.org\"",
6576 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6578 ssh_disconnect(ssh, NULL,
6579 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6580 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6583 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6586 * The only time this should get called is for "winadj@putty"
6587 * messages sent above. All other channel requests are either
6588 * sent with want_reply false or are sent before this handler gets
6591 struct ssh_channel *c;
6594 c = ssh2_channel_msg(ssh, pktin);
6597 wa = c->v.v2.winadj_head;
6599 ssh_disconnect(ssh, NULL,
6600 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6601 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6604 c->v.v2.winadj_head = wa->next;
6605 c->v.v2.remlocwin += wa->size;
6608 * winadj messages are only sent when the window is fully open, so
6609 * if we get an ack of one, we know any pending unthrottle is
6612 if (c->v.v2.throttle_state == UNTHROTTLING)
6613 c->v.v2.throttle_state = UNTHROTTLED;
6616 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6618 struct ssh_channel *c;
6619 c = ssh2_channel_msg(ssh, pktin);
6623 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6624 ssh2_try_send_and_unthrottle(ssh, c);
6628 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6632 struct ssh_channel *c;
6633 c = ssh2_channel_msg(ssh, pktin);
6636 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6637 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6638 return; /* extended but not stderr */
6639 ssh_pkt_getstring(pktin, &data, &length);
6642 c->v.v2.locwindow -= length;
6643 c->v.v2.remlocwin -= length;
6645 case CHAN_MAINSESSION:
6647 from_backend(ssh->frontend, pktin->type ==
6648 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6652 bufsize = x11_send(c->u.x11.s, data, length);
6655 bufsize = pfd_send(c->u.pfd.s, data, length);
6658 while (length > 0) {
6659 if (c->u.a.lensofar < 4) {
6660 unsigned int l = min(4 - c->u.a.lensofar,
6662 memcpy(c->u.a.msglen + c->u.a.lensofar,
6666 c->u.a.lensofar += l;
6668 if (c->u.a.lensofar == 4) {
6670 4 + GET_32BIT(c->u.a.msglen);
6671 c->u.a.message = snewn(c->u.a.totallen,
6673 memcpy(c->u.a.message, c->u.a.msglen, 4);
6675 if (c->u.a.lensofar >= 4 && length > 0) {
6677 min(c->u.a.totallen - c->u.a.lensofar,
6679 memcpy(c->u.a.message + c->u.a.lensofar,
6683 c->u.a.lensofar += l;
6685 if (c->u.a.lensofar == c->u.a.totallen) {
6688 if (agent_query(c->u.a.message,
6691 ssh_agentf_callback, c))
6692 ssh_agentf_callback(c, reply, replylen);
6693 sfree(c->u.a.message);
6694 c->u.a.lensofar = 0;
6701 * If it looks like the remote end hit the end of its window,
6702 * and we didn't want it to do that, think about using a
6705 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6706 c->v.v2.locmaxwin < 0x40000000)
6707 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6709 * If we are not buffering too much data,
6710 * enlarge the window again at the remote side.
6711 * If we are buffering too much, we may still
6712 * need to adjust the window if the server's
6715 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6716 c->v.v2.locmaxwin - bufsize : 0);
6718 * If we're either buffering way too much data, or if we're
6719 * buffering anything at all and we're in "simple" mode,
6720 * throttle the whole channel.
6722 if ((bufsize > c->v.v2.locmaxwin ||
6723 (ssh->cfg.ssh_simple && bufsize > 0)) &&
6724 !c->throttling_conn) {
6725 c->throttling_conn = 1;
6726 ssh_throttle_conn(ssh, +1);
6731 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6733 struct ssh_channel *c;
6735 c = ssh2_channel_msg(ssh, pktin);
6739 if (c->type == CHAN_X11) {
6741 * Remote EOF on an X11 channel means we should
6742 * wrap up and close the channel ourselves.
6744 x11_close(c->u.x11.s);
6747 } else if (c->type == CHAN_AGENT) {
6749 } else if (c->type == CHAN_SOCKDATA) {
6750 pfd_close(c->u.pfd.s);
6756 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6758 struct ssh_channel *c;
6759 struct Packet *pktout;
6761 c = ssh2_channel_msg(ssh, pktin);
6764 /* Do pre-close processing on the channel. */
6766 case CHAN_MAINSESSION:
6767 ssh->mainchan = NULL;
6768 update_specials_menu(ssh->frontend);
6771 if (c->u.x11.s != NULL)
6772 x11_close(c->u.x11.s);
6779 if (c->u.pfd.s != NULL)
6780 pfd_close(c->u.pfd.s);
6784 if (c->closes == 0) {
6785 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6786 ssh2_pkt_adduint32(pktout, c->remoteid);
6787 ssh2_pkt_send(ssh, pktout);
6789 del234(ssh->channels, c);
6790 bufchain_clear(&c->v.v2.outbuffer);
6794 * See if that was the last channel left open.
6795 * (This is only our termination condition if we're
6796 * not running in -N mode.)
6798 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6800 * We used to send SSH_MSG_DISCONNECT here,
6801 * because I'd believed that _every_ conforming
6802 * SSH-2 connection had to end with a disconnect
6803 * being sent by at least one side; apparently
6804 * I was wrong and it's perfectly OK to
6805 * unceremoniously slam the connection shut
6806 * when you're done, and indeed OpenSSH feels
6807 * this is more polite than sending a
6808 * DISCONNECT. So now we don't.
6810 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6814 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6816 struct ssh_channel *c;
6817 struct Packet *pktout;
6819 c = ssh2_channel_msg(ssh, pktin);
6822 if (c->type != CHAN_SOCKDATA_DORMANT)
6823 return; /* dunno why they're confirming this */
6824 c->remoteid = ssh_pkt_getuint32(pktin);
6825 c->halfopen = FALSE;
6826 c->type = CHAN_SOCKDATA;
6827 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6828 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6830 pfd_confirm(c->u.pfd.s);
6833 * We have a pending close on this channel,
6834 * which we decided on before the server acked
6835 * the channel open. So now we know the
6836 * remoteid, we can close it again.
6838 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6839 ssh2_pkt_adduint32(pktout, c->remoteid);
6840 ssh2_pkt_send(ssh, pktout);
6844 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
6846 static const char *const reasons[] = {
6847 "<unknown reason code>",
6848 "Administratively prohibited",
6850 "Unknown channel type",
6851 "Resource shortage",
6853 unsigned reason_code;
6854 char *reason_string;
6856 struct ssh_channel *c;
6857 c = ssh2_channel_msg(ssh, pktin);
6860 if (c->type != CHAN_SOCKDATA_DORMANT)
6861 return; /* dunno why they're failing this */
6863 reason_code = ssh_pkt_getuint32(pktin);
6864 if (reason_code >= lenof(reasons))
6865 reason_code = 0; /* ensure reasons[reason_code] in range */
6866 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6867 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
6868 reasons[reason_code], reason_length, reason_string);
6870 pfd_close(c->u.pfd.s);
6872 del234(ssh->channels, c);
6876 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
6879 int typelen, want_reply;
6880 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6881 struct ssh_channel *c;
6882 struct Packet *pktout;
6884 c = ssh2_channel_msg(ssh, pktin);
6887 ssh_pkt_getstring(pktin, &type, &typelen);
6888 want_reply = ssh2_pkt_getbool(pktin);
6891 * Having got the channel number, we now look at
6892 * the request type string to see if it's something
6895 if (c == ssh->mainchan) {
6897 * We recognise "exit-status" and "exit-signal" on
6898 * the primary channel.
6900 if (typelen == 11 &&
6901 !memcmp(type, "exit-status", 11)) {
6903 ssh->exitcode = ssh_pkt_getuint32(pktin);
6904 logeventf(ssh, "Server sent command exit status %d",
6906 reply = SSH2_MSG_CHANNEL_SUCCESS;
6908 } else if (typelen == 11 &&
6909 !memcmp(type, "exit-signal", 11)) {
6911 int is_plausible = TRUE, is_int = FALSE;
6912 char *fmt_sig = "", *fmt_msg = "";
6914 int msglen = 0, core = FALSE;
6915 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6916 * provide an `int' for the signal, despite its
6917 * having been a `string' in the drafts of RFC 4254 since at
6918 * least 2001. (Fixed in session.c 1.147.) Try to
6919 * infer which we can safely parse it as. */
6921 unsigned char *p = pktin->body +
6923 long len = pktin->length - pktin->savedpos;
6924 unsigned long num = GET_32BIT(p); /* what is it? */
6925 /* If it's 0, it hardly matters; assume string */
6929 int maybe_int = FALSE, maybe_str = FALSE;
6930 #define CHECK_HYPOTHESIS(offset, result) \
6933 if (q >= 0 && q+4 <= len) { \
6934 q = q + 4 + GET_32BIT(p+q); \
6935 if (q >= 0 && q+4 <= len && \
6936 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6940 CHECK_HYPOTHESIS(4+1, maybe_int);
6941 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6942 #undef CHECK_HYPOTHESIS
6943 if (maybe_int && !maybe_str)
6945 else if (!maybe_int && maybe_str)
6948 /* Crikey. Either or neither. Panic. */
6949 is_plausible = FALSE;
6952 ssh->exitcode = 128; /* means `unknown signal' */
6955 /* Old non-standard OpenSSH. */
6956 int signum = ssh_pkt_getuint32(pktin);
6957 fmt_sig = dupprintf(" %d", signum);
6958 ssh->exitcode = 128 + signum;
6960 /* As per RFC 4254. */
6963 ssh_pkt_getstring(pktin, &sig, &siglen);
6964 /* Signal name isn't supposed to be blank, but
6965 * let's cope gracefully if it is. */
6967 fmt_sig = dupprintf(" \"%.*s\"",
6972 * Really hideous method of translating the
6973 * signal description back into a locally
6974 * meaningful number.
6979 #define TRANSLATE_SIGNAL(s) \
6980 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6981 ssh->exitcode = 128 + SIG ## s
6983 TRANSLATE_SIGNAL(ABRT);
6986 TRANSLATE_SIGNAL(ALRM);
6989 TRANSLATE_SIGNAL(FPE);
6992 TRANSLATE_SIGNAL(HUP);
6995 TRANSLATE_SIGNAL(ILL);
6998 TRANSLATE_SIGNAL(INT);
7001 TRANSLATE_SIGNAL(KILL);
7004 TRANSLATE_SIGNAL(PIPE);
7007 TRANSLATE_SIGNAL(QUIT);
7010 TRANSLATE_SIGNAL(SEGV);
7013 TRANSLATE_SIGNAL(TERM);
7016 TRANSLATE_SIGNAL(USR1);
7019 TRANSLATE_SIGNAL(USR2);
7021 #undef TRANSLATE_SIGNAL
7023 ssh->exitcode = 128;
7025 core = ssh2_pkt_getbool(pktin);
7026 ssh_pkt_getstring(pktin, &msg, &msglen);
7028 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7030 /* ignore lang tag */
7031 } /* else don't attempt to parse */
7032 logeventf(ssh, "Server exited on signal%s%s%s",
7033 fmt_sig, core ? " (core dumped)" : "",
7035 if (*fmt_sig) sfree(fmt_sig);
7036 if (*fmt_msg) sfree(fmt_msg);
7037 reply = SSH2_MSG_CHANNEL_SUCCESS;
7042 * This is a channel request we don't know
7043 * about, so we now either ignore the request
7044 * or respond with CHANNEL_FAILURE, depending
7047 reply = SSH2_MSG_CHANNEL_FAILURE;
7050 pktout = ssh2_pkt_init(reply);
7051 ssh2_pkt_adduint32(pktout, c->remoteid);
7052 ssh2_pkt_send(ssh, pktout);
7056 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7059 int typelen, want_reply;
7060 struct Packet *pktout;
7062 ssh_pkt_getstring(pktin, &type, &typelen);
7063 want_reply = ssh2_pkt_getbool(pktin);
7066 * We currently don't support any global requests
7067 * at all, so we either ignore the request or
7068 * respond with REQUEST_FAILURE, depending on
7072 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7073 ssh2_pkt_send(ssh, pktout);
7077 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7085 struct ssh_channel *c;
7086 unsigned remid, winsize, pktsize;
7087 struct Packet *pktout;
7089 ssh_pkt_getstring(pktin, &type, &typelen);
7090 c = snew(struct ssh_channel);
7093 remid = ssh_pkt_getuint32(pktin);
7094 winsize = ssh_pkt_getuint32(pktin);
7095 pktsize = ssh_pkt_getuint32(pktin);
7097 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7101 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7102 addrstr = snewn(peeraddrlen+1, char);
7103 memcpy(addrstr, peeraddr, peeraddrlen);
7104 addrstr[peeraddrlen] = '\0';
7105 peerport = ssh_pkt_getuint32(pktin);
7107 logeventf(ssh, "Received X11 connect request from %s:%d",
7110 if (!ssh->X11_fwd_enabled)
7111 error = "X11 forwarding is not enabled";
7112 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7113 addrstr, peerport, &ssh->cfg)) != NULL) {
7114 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7115 error = "Unable to open an X11 connection";
7117 logevent("Opening X11 forward connection succeeded");
7122 } else if (typelen == 15 &&
7123 !memcmp(type, "forwarded-tcpip", 15)) {
7124 struct ssh_rportfwd pf, *realpf;
7127 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7128 pf.sport = ssh_pkt_getuint32(pktin);
7129 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7130 peerport = ssh_pkt_getuint32(pktin);
7131 realpf = find234(ssh->rportfwds, &pf, NULL);
7132 logeventf(ssh, "Received remote port %d open request "
7133 "from %s:%d", pf.sport, peeraddr, peerport);
7134 if (realpf == NULL) {
7135 error = "Remote port is not recognised";
7137 const char *e = pfd_newconnect(&c->u.pfd.s,
7141 realpf->pfrec->addressfamily);
7142 logeventf(ssh, "Attempting to forward remote port to "
7143 "%s:%d", realpf->dhost, realpf->dport);
7145 logeventf(ssh, "Port open failed: %s", e);
7146 error = "Port open failed";
7148 logevent("Forwarded port opened successfully");
7149 c->type = CHAN_SOCKDATA;
7152 } else if (typelen == 22 &&
7153 !memcmp(type, "auth-agent@openssh.com", 22)) {
7154 if (!ssh->agentfwd_enabled)
7155 error = "Agent forwarding is not enabled";
7157 c->type = CHAN_AGENT; /* identify channel type */
7158 c->u.a.lensofar = 0;
7161 error = "Unsupported channel type requested";
7164 c->remoteid = remid;
7165 c->halfopen = FALSE;
7167 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7168 ssh2_pkt_adduint32(pktout, c->remoteid);
7169 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7170 ssh2_pkt_addstring(pktout, error);
7171 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7172 ssh2_pkt_send(ssh, pktout);
7173 logeventf(ssh, "Rejected channel open: %s", error);
7176 ssh2_channel_init(c);
7177 c->v.v2.remwindow = winsize;
7178 c->v.v2.remmaxpkt = pktsize;
7179 add234(ssh->channels, c);
7180 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7181 ssh2_pkt_adduint32(pktout, c->remoteid);
7182 ssh2_pkt_adduint32(pktout, c->localid);
7183 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7184 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7185 ssh2_pkt_send(ssh, pktout);
7190 * Buffer banner messages for later display at some convenient point.
7192 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7194 /* Arbitrary limit to prevent unbounded inflation of buffer */
7195 if (bufchain_size(&ssh->banner) <= 131072) {
7196 char *banner = NULL;
7198 ssh_pkt_getstring(pktin, &banner, &size);
7200 bufchain_add(&ssh->banner, banner, size);
7204 /* Helper function to deal with sending tty modes for "pty-req" */
7205 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7207 struct Packet *pktout = (struct Packet *)data;
7209 unsigned int arg = 0;
7210 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7211 if (i == lenof(ssh_ttymodes)) return;
7212 switch (ssh_ttymodes[i].type) {
7214 arg = ssh_tty_parse_specchar(val);
7217 arg = ssh_tty_parse_boolean(val);
7220 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7221 ssh2_pkt_adduint32(pktout, arg);
7225 * Handle the SSH-2 userauth and connection layers.
7227 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7228 struct Packet *pktin)
7230 struct do_ssh2_authconn_state {
7233 AUTH_TYPE_PUBLICKEY,
7234 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7235 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7238 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7239 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7241 int done_service_req;
7242 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7243 int tried_pubkey_config, done_agent;
7248 int kbd_inter_refused;
7250 prompts_t *cur_prompt;
7255 void *publickey_blob;
7256 int publickey_bloblen;
7257 int publickey_encrypted;
7258 char *publickey_algorithm;
7259 char *publickey_comment;
7260 unsigned char agent_request[5], *agent_response, *agentp;
7261 int agent_responselen;
7262 unsigned char *pkblob_in_agent;
7264 char *pkblob, *alg, *commentp;
7265 int pklen, alglen, commentlen;
7266 int siglen, retlen, len;
7267 char *q, *agentreq, *ret;
7269 int num_env, env_left, env_ok;
7270 struct Packet *pktout;
7272 struct ssh_gss_library *gsslib;
7273 Ssh_gss_ctx gss_ctx;
7274 Ssh_gss_buf gss_buf;
7275 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7276 Ssh_gss_name gss_srv_name;
7277 Ssh_gss_stat gss_stat;
7280 crState(do_ssh2_authconn_state);
7282 crBegin(ssh->do_ssh2_authconn_crstate);
7284 s->done_service_req = FALSE;
7285 s->we_are_in = FALSE;
7287 s->tried_gssapi = FALSE;
7290 if (!ssh->cfg.ssh_no_userauth) {
7292 * Request userauth protocol, and await a response to it.
7294 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7295 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7296 ssh2_pkt_send(ssh, s->pktout);
7297 crWaitUntilV(pktin);
7298 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7299 s->done_service_req = TRUE;
7301 if (!s->done_service_req) {
7303 * Request connection protocol directly, without authentication.
7305 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7306 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7307 ssh2_pkt_send(ssh, s->pktout);
7308 crWaitUntilV(pktin);
7309 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7310 s->we_are_in = TRUE; /* no auth required */
7312 bombout(("Server refused service request"));
7317 /* Arrange to be able to deal with any BANNERs that come in.
7318 * (We do this now as packets may come in during the next bit.) */
7319 bufchain_init(&ssh->banner);
7320 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7321 ssh2_msg_userauth_banner;
7324 * Misc one-time setup for authentication.
7326 s->publickey_blob = NULL;
7327 if (!s->we_are_in) {
7330 * Load the public half of any configured public key file
7333 if (!filename_is_null(ssh->cfg.keyfile)) {
7335 logeventf(ssh, "Reading private key file \"%.150s\"",
7336 filename_to_str(&ssh->cfg.keyfile));
7337 keytype = key_type(&ssh->cfg.keyfile);
7338 if (keytype == SSH_KEYTYPE_SSH2) {
7341 ssh2_userkey_loadpub(&ssh->cfg.keyfile,
7342 &s->publickey_algorithm,
7343 &s->publickey_bloblen,
7344 &s->publickey_comment, &error);
7345 if (s->publickey_blob) {
7346 s->publickey_encrypted =
7347 ssh2_userkey_encrypted(&ssh->cfg.keyfile, NULL);
7350 logeventf(ssh, "Unable to load private key (%s)",
7352 msgbuf = dupprintf("Unable to load private key file "
7353 "\"%.150s\" (%s)\r\n",
7354 filename_to_str(&ssh->cfg.keyfile),
7356 c_write_str(ssh, msgbuf);
7361 logeventf(ssh, "Unable to use this key file (%s)",
7362 key_type_to_str(keytype));
7363 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7365 filename_to_str(&ssh->cfg.keyfile),
7366 key_type_to_str(keytype));
7367 c_write_str(ssh, msgbuf);
7369 s->publickey_blob = NULL;
7374 * Find out about any keys Pageant has (but if there's a
7375 * public key configured, filter out all others).
7378 s->agent_response = NULL;
7379 s->pkblob_in_agent = NULL;
7380 if (ssh->cfg.tryagent && agent_exists()) {
7384 logevent("Pageant is running. Requesting keys.");
7386 /* Request the keys held by the agent. */
7387 PUT_32BIT(s->agent_request, 1);
7388 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7389 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7390 ssh_agent_callback, ssh)) {
7394 bombout(("Unexpected data from server while"
7395 " waiting for agent response"));
7398 } while (pktin || inlen > 0);
7399 r = ssh->agent_response;
7400 s->agent_responselen = ssh->agent_response_len;
7402 s->agent_response = (unsigned char *) r;
7403 if (s->agent_response && s->agent_responselen >= 5 &&
7404 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7407 p = s->agent_response + 5;
7408 s->nkeys = GET_32BIT(p);
7410 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7411 if (s->publickey_blob) {
7412 /* See if configured key is in agent. */
7413 for (keyi = 0; keyi < s->nkeys; keyi++) {
7414 s->pklen = GET_32BIT(p);
7415 if (s->pklen == s->publickey_bloblen &&
7416 !memcmp(p+4, s->publickey_blob,
7417 s->publickey_bloblen)) {
7418 logeventf(ssh, "Pageant key #%d matches "
7419 "configured key file", keyi);
7421 s->pkblob_in_agent = p;
7425 p += GET_32BIT(p) + 4; /* comment */
7427 if (!s->pkblob_in_agent) {
7428 logevent("Configured key file not in Pageant");
7438 * We repeat this whole loop, including the username prompt,
7439 * until we manage a successful authentication. If the user
7440 * types the wrong _password_, they can be sent back to the
7441 * beginning to try another username, if this is configured on.
7442 * (If they specify a username in the config, they are never
7443 * asked, even if they do give a wrong password.)
7445 * I think this best serves the needs of
7447 * - the people who have no configuration, no keys, and just
7448 * want to try repeated (username,password) pairs until they
7449 * type both correctly
7451 * - people who have keys and configuration but occasionally
7452 * need to fall back to passwords
7454 * - people with a key held in Pageant, who might not have
7455 * logged in to a particular machine before; so they want to
7456 * type a username, and then _either_ their key will be
7457 * accepted, _or_ they will type a password. If they mistype
7458 * the username they will want to be able to get back and
7461 s->username[0] = '\0';
7462 s->got_username = FALSE;
7463 while (!s->we_are_in) {
7467 if (s->got_username && !ssh->cfg.change_username) {
7469 * We got a username last time round this loop, and
7470 * with change_username turned off we don't try to get
7473 } else if (!get_remote_username(&ssh->cfg, s->username,
7474 sizeof(s->username))) {
7475 int ret; /* need not be kept over crReturn */
7476 s->cur_prompt = new_prompts(ssh->frontend);
7477 s->cur_prompt->to_server = TRUE;
7478 s->cur_prompt->name = dupstr("SSH login name");
7479 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
7480 lenof(s->username));
7481 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7484 crWaitUntilV(!pktin);
7485 ret = get_userpass_input(s->cur_prompt, in, inlen);
7490 * get_userpass_input() failed to get a username.
7493 free_prompts(s->cur_prompt);
7494 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7497 memcpy(s->username, s->cur_prompt->prompts[0]->result,
7498 lenof(s->username));
7499 free_prompts(s->cur_prompt);
7502 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7503 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
7504 c_write_str(ssh, stuff);
7508 s->got_username = TRUE;
7511 * Send an authentication request using method "none": (a)
7512 * just in case it succeeds, and (b) so that we know what
7513 * authentication methods we can usefully try next.
7515 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7517 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7518 ssh2_pkt_addstring(s->pktout, s->username);
7519 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7520 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7521 ssh2_pkt_send(ssh, s->pktout);
7522 s->type = AUTH_TYPE_NONE;
7524 s->we_are_in = FALSE;
7526 s->tried_pubkey_config = FALSE;
7527 s->kbd_inter_refused = FALSE;
7529 /* Reset agent request state. */
7530 s->done_agent = FALSE;
7531 if (s->agent_response) {
7532 if (s->pkblob_in_agent) {
7533 s->agentp = s->pkblob_in_agent;
7535 s->agentp = s->agent_response + 5 + 4;
7541 char *methods = NULL;
7545 * Wait for the result of the last authentication request.
7548 crWaitUntilV(pktin);
7550 * Now is a convenient point to spew any banner material
7551 * that we've accumulated. (This should ensure that when
7552 * we exit the auth loop, we haven't any left to deal
7556 int size = bufchain_size(&ssh->banner);
7558 * Don't show the banner if we're operating in
7559 * non-verbose non-interactive mode. (It's probably
7560 * a script, which means nobody will read the
7561 * banner _anyway_, and moreover the printing of
7562 * the banner will screw up processing on the
7563 * output of (say) plink.)
7565 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7566 char *banner = snewn(size, char);
7567 bufchain_fetch(&ssh->banner, banner, size);
7568 c_write_untrusted(ssh, banner, size);
7571 bufchain_clear(&ssh->banner);
7573 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7574 logevent("Access granted");
7575 s->we_are_in = TRUE;
7579 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7580 bombout(("Strange packet received during authentication: "
7581 "type %d", pktin->type));
7588 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7589 * we can look at the string in it and know what we can
7590 * helpfully try next.
7592 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7593 ssh_pkt_getstring(pktin, &methods, &methlen);
7594 if (!ssh2_pkt_getbool(pktin)) {
7596 * We have received an unequivocal Access
7597 * Denied. This can translate to a variety of
7600 * - if we'd just tried "none" authentication,
7601 * it's not worth printing anything at all
7603 * - if we'd just tried a public key _offer_,
7604 * the message should be "Server refused our
7605 * key" (or no message at all if the key
7606 * came from Pageant)
7608 * - if we'd just tried anything else, the
7609 * message really should be "Access denied".
7611 * Additionally, if we'd just tried password
7612 * authentication, we should break out of this
7613 * whole loop so as to go back to the username
7614 * prompt (iff we're configured to allow
7615 * username change attempts).
7617 if (s->type == AUTH_TYPE_NONE) {
7619 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7620 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7621 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7622 c_write_str(ssh, "Server refused our key\r\n");
7623 logevent("Server refused public key");
7624 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7625 /* server declined keyboard-interactive; ignore */
7627 c_write_str(ssh, "Access denied\r\n");
7628 logevent("Access denied");
7629 if (s->type == AUTH_TYPE_PASSWORD &&
7630 ssh->cfg.change_username) {
7631 /* XXX perhaps we should allow
7632 * keyboard-interactive to do this too? */
7633 s->we_are_in = FALSE;
7638 c_write_str(ssh, "Further authentication required\r\n");
7639 logevent("Further authentication required");
7643 in_commasep_string("publickey", methods, methlen);
7645 in_commasep_string("password", methods, methlen);
7646 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
7647 in_commasep_string("keyboard-interactive", methods, methlen);
7650 s->can_gssapi = ssh->cfg.try_gssapi_auth &&
7651 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7652 n_ssh_gss_libraries > 0;
7656 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7658 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7661 * Attempt public-key authentication using a key from Pageant.
7664 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7666 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7668 /* Unpack key from agent response */
7669 s->pklen = GET_32BIT(s->agentp);
7671 s->pkblob = (char *)s->agentp;
7672 s->agentp += s->pklen;
7673 s->alglen = GET_32BIT(s->pkblob);
7674 s->alg = s->pkblob + 4;
7675 s->commentlen = GET_32BIT(s->agentp);
7677 s->commentp = (char *)s->agentp;
7678 s->agentp += s->commentlen;
7679 /* s->agentp now points at next key, if any */
7681 /* See if server will accept it */
7682 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7683 ssh2_pkt_addstring(s->pktout, s->username);
7684 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7685 /* service requested */
7686 ssh2_pkt_addstring(s->pktout, "publickey");
7688 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7689 ssh2_pkt_addstring_start(s->pktout);
7690 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7691 ssh2_pkt_addstring_start(s->pktout);
7692 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7693 ssh2_pkt_send(ssh, s->pktout);
7694 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7696 crWaitUntilV(pktin);
7697 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7699 /* Offer of key refused. */
7706 if (flags & FLAG_VERBOSE) {
7707 c_write_str(ssh, "Authenticating with "
7709 c_write(ssh, s->commentp, s->commentlen);
7710 c_write_str(ssh, "\" from agent\r\n");
7714 * Server is willing to accept the key.
7715 * Construct a SIGN_REQUEST.
7717 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7718 ssh2_pkt_addstring(s->pktout, s->username);
7719 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7720 /* service requested */
7721 ssh2_pkt_addstring(s->pktout, "publickey");
7723 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7724 ssh2_pkt_addstring_start(s->pktout);
7725 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7726 ssh2_pkt_addstring_start(s->pktout);
7727 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7729 /* Ask agent for signature. */
7730 s->siglen = s->pktout->length - 5 + 4 +
7731 ssh->v2_session_id_len;
7732 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7734 s->len = 1; /* message type */
7735 s->len += 4 + s->pklen; /* key blob */
7736 s->len += 4 + s->siglen; /* data to sign */
7737 s->len += 4; /* flags */
7738 s->agentreq = snewn(4 + s->len, char);
7739 PUT_32BIT(s->agentreq, s->len);
7740 s->q = s->agentreq + 4;
7741 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7742 PUT_32BIT(s->q, s->pklen);
7744 memcpy(s->q, s->pkblob, s->pklen);
7746 PUT_32BIT(s->q, s->siglen);
7748 /* Now the data to be signed... */
7749 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7750 PUT_32BIT(s->q, ssh->v2_session_id_len);
7753 memcpy(s->q, ssh->v2_session_id,
7754 ssh->v2_session_id_len);
7755 s->q += ssh->v2_session_id_len;
7756 memcpy(s->q, s->pktout->data + 5,
7757 s->pktout->length - 5);
7758 s->q += s->pktout->length - 5;
7759 /* And finally the (zero) flags word. */
7761 if (!agent_query(s->agentreq, s->len + 4,
7763 ssh_agent_callback, ssh)) {
7767 bombout(("Unexpected data from server"
7768 " while waiting for agent"
7772 } while (pktin || inlen > 0);
7773 vret = ssh->agent_response;
7774 s->retlen = ssh->agent_response_len;
7779 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7780 logevent("Sending Pageant's response");
7781 ssh2_add_sigblob(ssh, s->pktout,
7782 s->pkblob, s->pklen,
7784 GET_32BIT(s->ret + 5));
7785 ssh2_pkt_send(ssh, s->pktout);
7786 s->type = AUTH_TYPE_PUBLICKEY;
7788 /* FIXME: less drastic response */
7789 bombout(("Pageant failed to answer challenge"));
7795 /* Do we have any keys left to try? */
7796 if (s->pkblob_in_agent) {
7797 s->done_agent = TRUE;
7798 s->tried_pubkey_config = TRUE;
7801 if (s->keyi >= s->nkeys)
7802 s->done_agent = TRUE;
7805 } else if (s->can_pubkey && s->publickey_blob &&
7806 !s->tried_pubkey_config) {
7808 struct ssh2_userkey *key; /* not live over crReturn */
7809 char *passphrase; /* not live over crReturn */
7811 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7813 s->tried_pubkey_config = TRUE;
7816 * Try the public key supplied in the configuration.
7818 * First, offer the public blob to see if the server is
7819 * willing to accept it.
7821 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7822 ssh2_pkt_addstring(s->pktout, s->username);
7823 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7824 /* service requested */
7825 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
7826 ssh2_pkt_addbool(s->pktout, FALSE);
7827 /* no signature included */
7828 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
7829 ssh2_pkt_addstring_start(s->pktout);
7830 ssh2_pkt_addstring_data(s->pktout,
7831 (char *)s->publickey_blob,
7832 s->publickey_bloblen);
7833 ssh2_pkt_send(ssh, s->pktout);
7834 logevent("Offered public key");
7836 crWaitUntilV(pktin);
7837 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7838 /* Key refused. Give up. */
7839 s->gotit = TRUE; /* reconsider message next loop */
7840 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
7841 continue; /* process this new message */
7843 logevent("Offer of public key accepted");
7846 * Actually attempt a serious authentication using
7849 if (flags & FLAG_VERBOSE) {
7850 c_write_str(ssh, "Authenticating with public key \"");
7851 c_write_str(ssh, s->publickey_comment);
7852 c_write_str(ssh, "\"\r\n");
7856 const char *error; /* not live over crReturn */
7857 if (s->publickey_encrypted) {
7859 * Get a passphrase from the user.
7861 int ret; /* need not be kept over crReturn */
7862 s->cur_prompt = new_prompts(ssh->frontend);
7863 s->cur_prompt->to_server = FALSE;
7864 s->cur_prompt->name = dupstr("SSH key passphrase");
7865 add_prompt(s->cur_prompt,
7866 dupprintf("Passphrase for key \"%.100s\": ",
7867 s->publickey_comment),
7868 FALSE, SSH_MAX_PASSWORD_LEN);
7869 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7872 crWaitUntilV(!pktin);
7873 ret = get_userpass_input(s->cur_prompt,
7878 /* Failed to get a passphrase. Terminate. */
7879 free_prompts(s->cur_prompt);
7880 ssh_disconnect(ssh, NULL,
7881 "Unable to authenticate",
7882 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7887 dupstr(s->cur_prompt->prompts[0]->result);
7888 free_prompts(s->cur_prompt);
7890 passphrase = NULL; /* no passphrase needed */
7894 * Try decrypting the key.
7896 key = ssh2_load_userkey(&ssh->cfg.keyfile, passphrase,
7899 /* burn the evidence */
7900 memset(passphrase, 0, strlen(passphrase));
7903 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
7905 (key == SSH2_WRONG_PASSPHRASE)) {
7906 c_write_str(ssh, "Wrong passphrase\r\n");
7908 /* and loop again */
7910 c_write_str(ssh, "Unable to load private key (");
7911 c_write_str(ssh, error);
7912 c_write_str(ssh, ")\r\n");
7914 break; /* try something else */
7920 unsigned char *pkblob, *sigblob, *sigdata;
7921 int pkblob_len, sigblob_len, sigdata_len;
7925 * We have loaded the private key and the server
7926 * has announced that it's willing to accept it.
7927 * Hallelujah. Generate a signature and send it.
7929 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7930 ssh2_pkt_addstring(s->pktout, s->username);
7931 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7932 /* service requested */
7933 ssh2_pkt_addstring(s->pktout, "publickey");
7935 ssh2_pkt_addbool(s->pktout, TRUE);
7936 /* signature follows */
7937 ssh2_pkt_addstring(s->pktout, key->alg->name);
7938 pkblob = key->alg->public_blob(key->data,
7940 ssh2_pkt_addstring_start(s->pktout);
7941 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
7945 * The data to be signed is:
7949 * followed by everything so far placed in the
7952 sigdata_len = s->pktout->length - 5 + 4 +
7953 ssh->v2_session_id_len;
7954 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7956 sigdata = snewn(sigdata_len, unsigned char);
7958 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7959 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
7962 memcpy(sigdata+p, ssh->v2_session_id,
7963 ssh->v2_session_id_len);
7964 p += ssh->v2_session_id_len;
7965 memcpy(sigdata+p, s->pktout->data + 5,
7966 s->pktout->length - 5);
7967 p += s->pktout->length - 5;
7968 assert(p == sigdata_len);
7969 sigblob = key->alg->sign(key->data, (char *)sigdata,
7970 sigdata_len, &sigblob_len);
7971 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7972 sigblob, sigblob_len);
7977 ssh2_pkt_send(ssh, s->pktout);
7978 s->type = AUTH_TYPE_PUBLICKEY;
7979 key->alg->freekey(key->data);
7983 } else if (s->can_gssapi && !s->tried_gssapi) {
7985 /* GSSAPI Authentication */
7990 s->type = AUTH_TYPE_GSSAPI;
7991 s->tried_gssapi = TRUE;
7993 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
7996 * Pick the highest GSS library on the preference
8002 for (i = 0; i < ngsslibs; i++) {
8003 int want_id = ssh->cfg.ssh_gsslist[i];
8004 for (j = 0; j < n_ssh_gss_libraries; j++)
8005 if (ssh_gss_libraries[j].id == want_id) {
8006 s->gsslib = &ssh_gss_libraries[j];
8007 goto got_gsslib; /* double break */
8012 * We always expect to have found something in
8013 * the above loop: we only came here if there
8014 * was at least one viable GSS library, and the
8015 * preference list should always mention
8016 * everything and only change the order.
8021 if (s->gsslib->gsslogmsg)
8022 logevent(s->gsslib->gsslogmsg);
8024 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8025 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8026 ssh2_pkt_addstring(s->pktout, s->username);
8027 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8028 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8030 /* add mechanism info */
8031 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8033 /* number of GSSAPI mechanisms */
8034 ssh2_pkt_adduint32(s->pktout,1);
8036 /* length of OID + 2 */
8037 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8038 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8041 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8043 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8045 ssh2_pkt_send(ssh, s->pktout);
8046 crWaitUntilV(pktin);
8047 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8048 logevent("GSSAPI authentication request refused");
8052 /* check returned packet ... */
8054 ssh_pkt_getstring(pktin, &data, &len);
8055 s->gss_rcvtok.value = data;
8056 s->gss_rcvtok.length = len;
8057 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8058 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8059 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8060 memcmp((char *)s->gss_rcvtok.value + 2,
8061 s->gss_buf.value,s->gss_buf.length) ) {
8062 logevent("GSSAPI authentication - wrong response from server");
8066 /* now start running */
8067 s->gss_stat = s->gsslib->import_name(s->gsslib,
8070 if (s->gss_stat != SSH_GSS_OK) {
8071 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8072 logevent("GSSAPI import name failed - Bad service name");
8074 logevent("GSSAPI import name failed");
8078 /* fetch TGT into GSS engine */
8079 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8081 if (s->gss_stat != SSH_GSS_OK) {
8082 logevent("GSSAPI authentication failed to get credentials");
8083 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8087 /* initial tokens are empty */
8088 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8089 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8091 /* now enter the loop */
8093 s->gss_stat = s->gsslib->init_sec_context
8101 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8102 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8103 logevent("GSSAPI authentication initialisation failed");
8105 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8106 &s->gss_buf) == SSH_GSS_OK) {
8107 logevent(s->gss_buf.value);
8108 sfree(s->gss_buf.value);
8113 logevent("GSSAPI authentication initialised");
8115 /* Client and server now exchange tokens until GSSAPI
8116 * no longer says CONTINUE_NEEDED */
8118 if (s->gss_sndtok.length != 0) {
8119 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8120 ssh_pkt_addstring_start(s->pktout);
8121 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8122 ssh2_pkt_send(ssh, s->pktout);
8123 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8126 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8127 crWaitUntilV(pktin);
8128 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8129 logevent("GSSAPI authentication - bad server response");
8130 s->gss_stat = SSH_GSS_FAILURE;
8133 ssh_pkt_getstring(pktin, &data, &len);
8134 s->gss_rcvtok.value = data;
8135 s->gss_rcvtok.length = len;
8137 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8139 if (s->gss_stat != SSH_GSS_OK) {
8140 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8141 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8144 logevent("GSSAPI authentication loop finished OK");
8146 /* Now send the MIC */
8148 s->pktout = ssh2_pkt_init(0);
8149 micoffset = s->pktout->length;
8150 ssh_pkt_addstring_start(s->pktout);
8151 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8152 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8153 ssh_pkt_addstring(s->pktout, s->username);
8154 ssh_pkt_addstring(s->pktout, "ssh-connection");
8155 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8157 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8158 s->gss_buf.length = s->pktout->length - micoffset;
8160 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8161 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8162 ssh_pkt_addstring_start(s->pktout);
8163 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8164 ssh2_pkt_send(ssh, s->pktout);
8165 s->gsslib->free_mic(s->gsslib, &mic);
8169 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8170 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8173 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8176 * Keyboard-interactive authentication.
8179 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8181 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8183 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8184 ssh2_pkt_addstring(s->pktout, s->username);
8185 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8186 /* service requested */
8187 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8189 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8190 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8191 ssh2_pkt_send(ssh, s->pktout);
8193 crWaitUntilV(pktin);
8194 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8195 /* Server is not willing to do keyboard-interactive
8196 * at all (or, bizarrely but legally, accepts the
8197 * user without actually issuing any prompts).
8198 * Give up on it entirely. */
8200 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
8201 logevent("Keyboard-interactive authentication refused");
8202 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8203 s->kbd_inter_refused = TRUE; /* don't try it again */
8208 * Loop while the server continues to send INFO_REQUESTs.
8210 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8212 char *name, *inst, *lang;
8213 int name_len, inst_len, lang_len;
8217 * We've got a fresh USERAUTH_INFO_REQUEST.
8218 * Get the preamble and start building a prompt.
8220 ssh_pkt_getstring(pktin, &name, &name_len);
8221 ssh_pkt_getstring(pktin, &inst, &inst_len);
8222 ssh_pkt_getstring(pktin, &lang, &lang_len);
8223 s->cur_prompt = new_prompts(ssh->frontend);
8224 s->cur_prompt->to_server = TRUE;
8227 * Get any prompt(s) from the packet.
8229 s->num_prompts = ssh_pkt_getuint32(pktin);
8230 for (i = 0; i < s->num_prompts; i++) {
8234 static char noprompt[] =
8235 "<server failed to send prompt>: ";
8237 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8238 echo = ssh2_pkt_getbool(pktin);
8241 prompt_len = lenof(noprompt)-1;
8243 add_prompt(s->cur_prompt,
8244 dupprintf("%.*s", prompt_len, prompt),
8245 echo, SSH_MAX_PASSWORD_LEN);
8249 /* FIXME: better prefix to distinguish from
8251 s->cur_prompt->name =
8252 dupprintf("SSH server: %.*s", name_len, name);
8253 s->cur_prompt->name_reqd = TRUE;
8255 s->cur_prompt->name =
8256 dupstr("SSH server authentication");
8257 s->cur_prompt->name_reqd = FALSE;
8259 /* We add a prefix to try to make it clear that a prompt
8260 * has come from the server.
8261 * FIXME: ugly to print "Using..." in prompt _every_
8262 * time round. Can this be done more subtly? */
8263 /* Special case: for reasons best known to themselves,
8264 * some servers send k-i requests with no prompts and
8265 * nothing to display. Keep quiet in this case. */
8266 if (s->num_prompts || name_len || inst_len) {
8267 s->cur_prompt->instruction =
8268 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8269 inst_len ? "\n" : "", inst_len, inst);
8270 s->cur_prompt->instr_reqd = TRUE;
8272 s->cur_prompt->instr_reqd = FALSE;
8276 * Display any instructions, and get the user's
8280 int ret; /* not live over crReturn */
8281 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8284 crWaitUntilV(!pktin);
8285 ret = get_userpass_input(s->cur_prompt, in, inlen);
8290 * Failed to get responses. Terminate.
8292 free_prompts(s->cur_prompt);
8293 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8294 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8301 * Send the response(s) to the server.
8303 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8304 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8305 for (i=0; i < s->num_prompts; i++) {
8306 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8307 ssh2_pkt_addstring(s->pktout,
8308 s->cur_prompt->prompts[i]->result);
8309 end_log_omission(ssh, s->pktout);
8311 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8314 * Get the next packet in case it's another
8317 crWaitUntilV(pktin);
8322 * We should have SUCCESS or FAILURE now.
8326 } else if (s->can_passwd) {
8329 * Plain old password authentication.
8331 int ret; /* not live over crReturn */
8332 int changereq_first_time; /* not live over crReturn */
8334 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8336 s->cur_prompt = new_prompts(ssh->frontend);
8337 s->cur_prompt->to_server = TRUE;
8338 s->cur_prompt->name = dupstr("SSH password");
8339 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
8342 FALSE, SSH_MAX_PASSWORD_LEN);
8344 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8347 crWaitUntilV(!pktin);
8348 ret = get_userpass_input(s->cur_prompt, in, inlen);
8353 * Failed to get responses. Terminate.
8355 free_prompts(s->cur_prompt);
8356 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8357 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8362 * Squirrel away the password. (We may need it later if
8363 * asked to change it.)
8365 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8366 free_prompts(s->cur_prompt);
8369 * Send the password packet.
8371 * We pad out the password packet to 256 bytes to make
8372 * it harder for an attacker to find the length of the
8375 * Anyone using a password longer than 256 bytes
8376 * probably doesn't have much to worry about from
8377 * people who find out how long their password is!
8379 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8380 ssh2_pkt_addstring(s->pktout, s->username);
8381 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8382 /* service requested */
8383 ssh2_pkt_addstring(s->pktout, "password");
8384 ssh2_pkt_addbool(s->pktout, FALSE);
8385 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8386 ssh2_pkt_addstring(s->pktout, s->password);
8387 end_log_omission(ssh, s->pktout);
8388 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8389 logevent("Sent password");
8390 s->type = AUTH_TYPE_PASSWORD;
8393 * Wait for next packet, in case it's a password change
8396 crWaitUntilV(pktin);
8397 changereq_first_time = TRUE;
8399 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8402 * We're being asked for a new password
8403 * (perhaps not for the first time).
8404 * Loop until the server accepts it.
8407 int got_new = FALSE; /* not live over crReturn */
8408 char *prompt; /* not live over crReturn */
8409 int prompt_len; /* not live over crReturn */
8413 if (changereq_first_time)
8414 msg = "Server requested password change";
8416 msg = "Server rejected new password";
8418 c_write_str(ssh, msg);
8419 c_write_str(ssh, "\r\n");
8422 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8424 s->cur_prompt = new_prompts(ssh->frontend);
8425 s->cur_prompt->to_server = TRUE;
8426 s->cur_prompt->name = dupstr("New SSH password");
8427 s->cur_prompt->instruction =
8428 dupprintf("%.*s", prompt_len, prompt);
8429 s->cur_prompt->instr_reqd = TRUE;
8431 * There's no explicit requirement in the protocol
8432 * for the "old" passwords in the original and
8433 * password-change messages to be the same, and
8434 * apparently some Cisco kit supports password change
8435 * by the user entering a blank password originally
8436 * and the real password subsequently, so,
8437 * reluctantly, we prompt for the old password again.
8439 * (On the other hand, some servers don't even bother
8440 * to check this field.)
8442 add_prompt(s->cur_prompt,
8443 dupstr("Current password (blank for previously entered password): "),
8444 FALSE, SSH_MAX_PASSWORD_LEN);
8445 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8446 FALSE, SSH_MAX_PASSWORD_LEN);
8447 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8448 FALSE, SSH_MAX_PASSWORD_LEN);
8451 * Loop until the user manages to enter the same
8456 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8459 crWaitUntilV(!pktin);
8460 ret = get_userpass_input(s->cur_prompt, in, inlen);
8465 * Failed to get responses. Terminate.
8467 /* burn the evidence */
8468 free_prompts(s->cur_prompt);
8469 memset(s->password, 0, strlen(s->password));
8471 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8472 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8478 * If the user specified a new original password
8479 * (IYSWIM), overwrite any previously specified
8481 * (A side effect is that the user doesn't have to
8482 * re-enter it if they louse up the new password.)
8484 if (s->cur_prompt->prompts[0]->result[0]) {
8485 memset(s->password, 0, strlen(s->password));
8486 /* burn the evidence */
8489 dupstr(s->cur_prompt->prompts[0]->result);
8493 * Check the two new passwords match.
8495 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8496 s->cur_prompt->prompts[2]->result)
8499 /* They don't. Silly user. */
8500 c_write_str(ssh, "Passwords do not match\r\n");
8505 * Send the new password (along with the old one).
8506 * (see above for padding rationale)
8508 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8509 ssh2_pkt_addstring(s->pktout, s->username);
8510 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8511 /* service requested */
8512 ssh2_pkt_addstring(s->pktout, "password");
8513 ssh2_pkt_addbool(s->pktout, TRUE);
8514 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8515 ssh2_pkt_addstring(s->pktout, s->password);
8516 ssh2_pkt_addstring(s->pktout,
8517 s->cur_prompt->prompts[1]->result);
8518 free_prompts(s->cur_prompt);
8519 end_log_omission(ssh, s->pktout);
8520 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8521 logevent("Sent new password");
8524 * Now see what the server has to say about it.
8525 * (If it's CHANGEREQ again, it's not happy with the
8528 crWaitUntilV(pktin);
8529 changereq_first_time = FALSE;
8534 * We need to reexamine the current pktin at the top
8535 * of the loop. Either:
8536 * - we weren't asked to change password at all, in
8537 * which case it's a SUCCESS or FAILURE with the
8539 * - we sent a new password, and the server was
8540 * either OK with it (SUCCESS or FAILURE w/partial
8541 * success) or unhappy with the _old_ password
8542 * (FAILURE w/o partial success)
8543 * In any of these cases, we go back to the top of
8544 * the loop and start again.
8549 * We don't need the old password any more, in any
8550 * case. Burn the evidence.
8552 memset(s->password, 0, strlen(s->password));
8556 char *str = dupprintf("No supported authentication methods available"
8557 " (server sent: %.*s)",
8560 ssh_disconnect(ssh, str,
8561 "No supported authentication methods available",
8562 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8572 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8574 /* Clear up various bits and pieces from authentication. */
8575 if (s->publickey_blob) {
8576 sfree(s->publickey_blob);
8577 sfree(s->publickey_comment);
8579 if (s->agent_response)
8580 sfree(s->agent_response);
8583 * Now the connection protocol has started, one way or another.
8586 ssh->channels = newtree234(ssh_channelcmp);
8589 * Set up handlers for some connection protocol messages, so we
8590 * don't have to handle them repeatedly in this coroutine.
8592 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8593 ssh2_msg_channel_window_adjust;
8594 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8595 ssh2_msg_global_request;
8598 * Create the main session channel.
8600 if (ssh->cfg.ssh_no_shell) {
8601 ssh->mainchan = NULL;
8602 } else if (*ssh->cfg.ssh_nc_host) {
8604 * Just start a direct-tcpip channel and use it as the main
8607 ssh->mainchan = snew(struct ssh_channel);
8608 ssh->mainchan->ssh = ssh;
8609 ssh2_channel_init(ssh->mainchan);
8611 "Opening direct-tcpip channel to %s:%d in place of session",
8612 ssh->cfg.ssh_nc_host, ssh->cfg.ssh_nc_port);
8613 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8614 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8615 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8616 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8617 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8618 ssh2_pkt_addstring(s->pktout, ssh->cfg.ssh_nc_host);
8619 ssh2_pkt_adduint32(s->pktout, ssh->cfg.ssh_nc_port);
8621 * There's nothing meaningful to put in the originator
8622 * fields, but some servers insist on syntactically correct
8625 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8626 ssh2_pkt_adduint32(s->pktout, 0);
8627 ssh2_pkt_send(ssh, s->pktout);
8629 crWaitUntilV(pktin);
8630 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8631 bombout(("Server refused to open a direct-tcpip channel"));
8633 /* FIXME: error data comes back in FAILURE packet */
8635 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8636 bombout(("Server's channel confirmation cited wrong channel"));
8639 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8640 ssh->mainchan->halfopen = FALSE;
8641 ssh->mainchan->type = CHAN_MAINSESSION;
8642 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8643 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8644 add234(ssh->channels, ssh->mainchan);
8645 update_specials_menu(ssh->frontend);
8646 logevent("Opened direct-tcpip channel");
8649 ssh->mainchan = snew(struct ssh_channel);
8650 ssh->mainchan->ssh = ssh;
8651 ssh2_channel_init(ssh->mainchan);
8652 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8653 ssh2_pkt_addstring(s->pktout, "session");
8654 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8655 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8656 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8657 ssh2_pkt_send(ssh, s->pktout);
8658 crWaitUntilV(pktin);
8659 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8660 bombout(("Server refused to open a session"));
8662 /* FIXME: error data comes back in FAILURE packet */
8664 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8665 bombout(("Server's channel confirmation cited wrong channel"));
8668 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8669 ssh->mainchan->halfopen = FALSE;
8670 ssh->mainchan->type = CHAN_MAINSESSION;
8671 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8672 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8673 add234(ssh->channels, ssh->mainchan);
8674 update_specials_menu(ssh->frontend);
8675 logevent("Opened channel for session");
8676 ssh->ncmode = FALSE;
8680 * Now we have a channel, make dispatch table entries for
8681 * general channel-based messages.
8683 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8684 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8685 ssh2_msg_channel_data;
8686 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8687 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8688 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8689 ssh2_msg_channel_open_confirmation;
8690 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8691 ssh2_msg_channel_open_failure;
8692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8693 ssh2_msg_channel_request;
8694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8695 ssh2_msg_channel_open;
8697 if (ssh->mainchan && ssh->cfg.ssh_simple) {
8699 * This message indicates to the server that we promise
8700 * not to try to run any other channel in parallel with
8701 * this one, so it's safe for it to advertise a very large
8702 * window and leave the flow control to TCP.
8704 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8705 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8706 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8707 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8708 ssh2_pkt_send(ssh, s->pktout);
8712 * Potentially enable X11 forwarding.
8714 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.x11_forward &&
8715 (ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
8716 ssh->cfg.x11_auth, &ssh->cfg))) {
8717 logevent("Requesting X11 forwarding");
8718 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8719 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8720 ssh2_pkt_addstring(s->pktout, "x11-req");
8721 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8722 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8723 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8725 * Note that while we blank the X authentication data here, we don't
8726 * take any special action to blank the start of an X11 channel,
8727 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8728 * without having session blanking enabled is likely to leak your
8729 * cookie into the log.
8731 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8732 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8733 end_log_omission(ssh, s->pktout);
8734 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8735 ssh2_pkt_send(ssh, s->pktout);
8737 crWaitUntilV(pktin);
8739 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8740 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8741 bombout(("Unexpected response to X11 forwarding request:"
8742 " packet type %d", pktin->type));
8745 logevent("X11 forwarding refused");
8747 logevent("X11 forwarding enabled");
8748 ssh->X11_fwd_enabled = TRUE;
8753 * Enable port forwardings.
8755 ssh_setup_portfwd(ssh, &ssh->cfg);
8758 * Potentially enable agent forwarding.
8760 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.agentfwd && agent_exists()) {
8761 logevent("Requesting OpenSSH-style agent forwarding");
8762 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8763 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8764 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8765 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8766 ssh2_pkt_send(ssh, s->pktout);
8768 crWaitUntilV(pktin);
8770 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8771 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8772 bombout(("Unexpected response to agent forwarding request:"
8773 " packet type %d", pktin->type));
8776 logevent("Agent forwarding refused");
8778 logevent("Agent forwarding enabled");
8779 ssh->agentfwd_enabled = TRUE;
8784 * Now allocate a pty for the session.
8786 if (ssh->mainchan && !ssh->ncmode && !ssh->cfg.nopty) {
8787 /* Unpick the terminal-speed string. */
8788 /* XXX perhaps we should allow no speeds to be sent. */
8789 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8790 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
8791 /* Build the pty request. */
8792 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8793 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8794 ssh2_pkt_addstring(s->pktout, "pty-req");
8795 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8796 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
8797 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8798 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8799 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8800 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8801 ssh2_pkt_addstring_start(s->pktout);
8802 parse_ttymodes(ssh, ssh->cfg.ttymodes,
8803 ssh2_send_ttymode, (void *)s->pktout);
8804 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
8805 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
8806 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
8807 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
8808 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
8809 ssh2_pkt_send(ssh, s->pktout);
8810 ssh->state = SSH_STATE_INTERMED;
8812 crWaitUntilV(pktin);
8814 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8815 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8816 bombout(("Unexpected response to pty request:"
8817 " packet type %d", pktin->type));
8820 c_write_str(ssh, "Server refused to allocate pty\r\n");
8821 ssh->editing = ssh->echoing = 1;
8823 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8824 ssh->ospeed, ssh->ispeed);
8827 ssh->editing = ssh->echoing = 1;
8831 * Send environment variables.
8833 * Simplest thing here is to send all the requests at once, and
8834 * then wait for a whole bunch of successes or failures.
8836 if (ssh->mainchan && !ssh->ncmode && *ssh->cfg.environmt) {
8837 char *e = ssh->cfg.environmt;
8838 char *var, *varend, *val;
8844 while (*e && *e != '\t') e++;
8846 if (*e == '\t') e++;
8851 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8852 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8853 ssh2_pkt_addstring(s->pktout, "env");
8854 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8855 ssh2_pkt_addstring_start(s->pktout);
8856 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
8857 ssh2_pkt_addstring(s->pktout, val);
8858 ssh2_pkt_send(ssh, s->pktout);
8863 logeventf(ssh, "Sent %d environment variables", s->num_env);
8866 s->env_left = s->num_env;
8868 while (s->env_left > 0) {
8869 crWaitUntilV(pktin);
8871 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8872 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8873 bombout(("Unexpected response to environment request:"
8874 " packet type %d", pktin->type));
8884 if (s->env_ok == s->num_env) {
8885 logevent("All environment variables successfully set");
8886 } else if (s->env_ok == 0) {
8887 logevent("All environment variables refused");
8888 c_write_str(ssh, "Server refused to set environment variables\r\n");
8890 logeventf(ssh, "%d environment variables refused",
8891 s->num_env - s->env_ok);
8892 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8897 * Start a shell or a remote command. We may have to attempt
8898 * this twice if the config data has provided a second choice
8901 if (ssh->mainchan && !ssh->ncmode) while (1) {
8905 if (ssh->fallback_cmd) {
8906 subsys = ssh->cfg.ssh_subsys2;
8907 cmd = ssh->cfg.remote_cmd_ptr2;
8909 subsys = ssh->cfg.ssh_subsys;
8910 cmd = ssh->cfg.remote_cmd_ptr;
8911 if (!cmd) cmd = ssh->cfg.remote_cmd;
8914 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8915 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8917 ssh2_pkt_addstring(s->pktout, "subsystem");
8918 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8919 ssh2_pkt_addstring(s->pktout, cmd);
8921 ssh2_pkt_addstring(s->pktout, "exec");
8922 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8923 ssh2_pkt_addstring(s->pktout, cmd);
8925 ssh2_pkt_addstring(s->pktout, "shell");
8926 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8928 ssh2_pkt_send(ssh, s->pktout);
8930 crWaitUntilV(pktin);
8932 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8933 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8934 bombout(("Unexpected response to shell/command request:"
8935 " packet type %d", pktin->type));
8939 * We failed to start the command. If this is the
8940 * fallback command, we really are finished; if it's
8941 * not, and if the fallback command exists, try falling
8942 * back to it before complaining.
8944 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
8945 logevent("Primary command failed; attempting fallback");
8946 ssh->fallback_cmd = TRUE;
8949 bombout(("Server refused to start a shell/command"));
8952 logevent("Started a shell/command");
8957 ssh->state = SSH_STATE_SESSION;
8958 if (ssh->size_needed)
8959 ssh_size(ssh, ssh->term_width, ssh->term_height);
8960 if (ssh->eof_needed)
8961 ssh_special(ssh, TS_EOF);
8964 * All the initial channel requests are done, so install the default
8967 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
8968 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
8974 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
8979 s->try_send = FALSE;
8983 * _All_ the connection-layer packets we expect to
8984 * receive are now handled by the dispatch table.
8985 * Anything that reaches here must be bogus.
8988 bombout(("Strange packet received: type %d", pktin->type));
8990 } else if (ssh->mainchan) {
8992 * We have spare data. Add it to the channel buffer.
8994 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
8999 struct ssh_channel *c;
9001 * Try to send data on all channels if we can.
9003 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9004 ssh2_try_send_and_unthrottle(ssh, c);
9012 * Handlers for SSH-2 messages that might arrive at any moment.
9014 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9016 /* log reason code in disconnect message */
9020 reason = ssh_pkt_getuint32(pktin);
9021 ssh_pkt_getstring(pktin, &msg, &msglen);
9023 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9024 buf = dupprintf("Received disconnect message (%s)",
9025 ssh2_disconnect_reasons[reason]);
9027 buf = dupprintf("Received disconnect message (unknown"
9028 " type %d)", reason);
9032 buf = dupprintf("Disconnection message text: %.*s",
9035 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9037 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9038 ssh2_disconnect_reasons[reason] : "unknown",
9043 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9045 /* log the debug message */
9050 /* XXX maybe we should actually take notice of this */
9051 always_display = ssh2_pkt_getbool(pktin);
9052 ssh_pkt_getstring(pktin, &msg, &msglen);
9054 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9057 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9059 struct Packet *pktout;
9060 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9061 ssh2_pkt_adduint32(pktout, pktin->sequence);
9063 * UNIMPLEMENTED messages MUST appear in the same order as the
9064 * messages they respond to. Hence, never queue them.
9066 ssh2_pkt_send_noqueue(ssh, pktout);
9070 * Handle the top-level SSH-2 protocol.
9072 static void ssh2_protocol_setup(Ssh ssh)
9077 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9079 for (i = 0; i < 256; i++)
9080 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9083 * Any message we actually understand, we set to NULL so that
9084 * the coroutines will get it.
9086 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9087 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9088 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9089 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9090 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9091 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9092 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9093 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9094 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9095 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9096 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9097 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9098 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9099 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9100 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9101 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9102 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9103 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9104 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9105 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9106 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9107 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9108 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9109 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9110 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9111 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9112 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9113 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9114 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9115 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9116 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9117 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9118 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9121 * These special message types we install handlers for.
9123 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9124 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9125 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9128 static void ssh2_timer(void *ctx, long now)
9132 if (ssh->state == SSH_STATE_CLOSED)
9135 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
9136 now - ssh->next_rekey >= 0) {
9137 do_ssh2_transport(ssh, "timeout", -1, NULL);
9141 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9142 struct Packet *pktin)
9144 unsigned char *in = (unsigned char *)vin;
9145 if (ssh->state == SSH_STATE_CLOSED)
9149 ssh->incoming_data_size += pktin->encrypted_len;
9150 if (!ssh->kex_in_progress &&
9151 ssh->max_data_size != 0 &&
9152 ssh->incoming_data_size > ssh->max_data_size)
9153 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9156 if (pktin && ssh->packet_dispatch[pktin->type]) {
9157 ssh->packet_dispatch[pktin->type](ssh, pktin);
9161 if (!ssh->protocol_initial_phase_done ||
9162 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9163 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9164 !ssh->protocol_initial_phase_done) {
9165 ssh->protocol_initial_phase_done = TRUE;
9167 * Allow authconn to initialise itself.
9169 do_ssh2_authconn(ssh, NULL, 0, NULL);
9172 do_ssh2_authconn(ssh, in, inlen, pktin);
9177 * Called to set up the connection.
9179 * Returns an error message, or NULL on success.
9181 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9183 char *host, int port, char **realhost, int nodelay,
9189 ssh = snew(struct ssh_tag);
9190 ssh->cfg = *cfg; /* STRUCTURE COPY */
9191 ssh->version = 0; /* when not ready yet */
9194 ssh->v1_cipher_ctx = NULL;
9195 ssh->crcda_ctx = NULL;
9196 ssh->cscipher = NULL;
9197 ssh->cs_cipher_ctx = NULL;
9198 ssh->sccipher = NULL;
9199 ssh->sc_cipher_ctx = NULL;
9201 ssh->cs_mac_ctx = NULL;
9203 ssh->sc_mac_ctx = NULL;
9205 ssh->cs_comp_ctx = NULL;
9207 ssh->sc_comp_ctx = NULL;
9209 ssh->kex_ctx = NULL;
9210 ssh->hostkey = NULL;
9212 ssh->close_expected = FALSE;
9213 ssh->clean_exit = FALSE;
9214 ssh->state = SSH_STATE_PREPACKET;
9215 ssh->size_needed = FALSE;
9216 ssh->eof_needed = FALSE;
9219 ssh->deferred_send_data = NULL;
9220 ssh->deferred_len = 0;
9221 ssh->deferred_size = 0;
9222 ssh->fallback_cmd = 0;
9223 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9224 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9225 ssh->x11disp = NULL;
9226 ssh->v1_compressing = FALSE;
9227 ssh->v2_outgoing_sequence = 0;
9228 ssh->ssh1_rdpkt_crstate = 0;
9229 ssh->ssh2_rdpkt_crstate = 0;
9230 ssh->do_ssh_init_crstate = 0;
9231 ssh->ssh_gotdata_crstate = 0;
9232 ssh->do_ssh1_connection_crstate = 0;
9233 ssh->do_ssh1_login_crstate = 0;
9234 ssh->do_ssh2_transport_crstate = 0;
9235 ssh->do_ssh2_authconn_crstate = 0;
9236 ssh->do_ssh_init_state = NULL;
9237 ssh->do_ssh1_login_state = NULL;
9238 ssh->do_ssh2_transport_state = NULL;
9239 ssh->do_ssh2_authconn_state = NULL;
9242 ssh->mainchan = NULL;
9243 ssh->throttled_all = 0;
9244 ssh->v1_stdout_throttling = 0;
9246 ssh->queuelen = ssh->queuesize = 0;
9247 ssh->queueing = FALSE;
9248 ssh->qhead = ssh->qtail = NULL;
9249 ssh->deferred_rekey_reason = NULL;
9250 bufchain_init(&ssh->queued_incoming_data);
9251 ssh->frozen = FALSE;
9253 *backend_handle = ssh;
9256 if (crypto_startup() == 0)
9257 return "Microsoft high encryption pack not installed!";
9260 ssh->frontend = frontend_handle;
9261 ssh->term_width = ssh->cfg.width;
9262 ssh->term_height = ssh->cfg.height;
9264 ssh->channels = NULL;
9265 ssh->rportfwds = NULL;
9266 ssh->portfwds = NULL;
9271 ssh->conn_throttle_count = 0;
9272 ssh->overall_bufsize = 0;
9273 ssh->fallback_cmd = 0;
9275 ssh->protocol = NULL;
9277 ssh->protocol_initial_phase_done = FALSE;
9281 ssh->incoming_data_size = ssh->outgoing_data_size =
9282 ssh->deferred_data_size = 0L;
9283 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
9284 ssh->kex_in_progress = FALSE;
9286 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9295 static void ssh_free(void *handle)
9297 Ssh ssh = (Ssh) handle;
9298 struct ssh_channel *c;
9299 struct ssh_rportfwd *pf;
9301 if (ssh->v1_cipher_ctx)
9302 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9303 if (ssh->cs_cipher_ctx)
9304 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9305 if (ssh->sc_cipher_ctx)
9306 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9307 if (ssh->cs_mac_ctx)
9308 ssh->csmac->free_context(ssh->cs_mac_ctx);
9309 if (ssh->sc_mac_ctx)
9310 ssh->scmac->free_context(ssh->sc_mac_ctx);
9311 if (ssh->cs_comp_ctx) {
9313 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9315 zlib_compress_cleanup(ssh->cs_comp_ctx);
9317 if (ssh->sc_comp_ctx) {
9319 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9321 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9324 dh_cleanup(ssh->kex_ctx);
9325 sfree(ssh->savedhost);
9327 while (ssh->queuelen-- > 0)
9328 ssh_free_packet(ssh->queue[ssh->queuelen]);
9331 while (ssh->qhead) {
9332 struct queued_handler *qh = ssh->qhead;
9333 ssh->qhead = qh->next;
9336 ssh->qhead = ssh->qtail = NULL;
9338 if (ssh->channels) {
9339 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9342 if (c->u.x11.s != NULL)
9343 x11_close(c->u.x11.s);
9346 if (c->u.pfd.s != NULL)
9347 pfd_close(c->u.pfd.s);
9352 freetree234(ssh->channels);
9353 ssh->channels = NULL;
9356 if (ssh->rportfwds) {
9357 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9359 freetree234(ssh->rportfwds);
9360 ssh->rportfwds = NULL;
9362 sfree(ssh->deferred_send_data);
9364 x11_free_display(ssh->x11disp);
9365 sfree(ssh->do_ssh_init_state);
9366 sfree(ssh->do_ssh1_login_state);
9367 sfree(ssh->do_ssh2_transport_state);
9368 sfree(ssh->do_ssh2_authconn_state);
9371 sfree(ssh->fullhostname);
9372 if (ssh->crcda_ctx) {
9373 crcda_free_context(ssh->crcda_ctx);
9374 ssh->crcda_ctx = NULL;
9377 ssh_do_close(ssh, TRUE);
9378 expire_timer_context(ssh);
9380 pinger_free(ssh->pinger);
9381 bufchain_clear(&ssh->queued_incoming_data);
9388 * Reconfigure the SSH backend.
9390 static void ssh_reconfig(void *handle, Config *cfg)
9392 Ssh ssh = (Ssh) handle;
9393 char *rekeying = NULL, rekey_mandatory = FALSE;
9394 unsigned long old_max_data_size;
9396 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
9398 ssh_setup_portfwd(ssh, cfg);
9400 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
9401 cfg->ssh_rekey_time != 0) {
9402 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
9403 long now = GETTICKCOUNT();
9405 if (new_next - now < 0) {
9406 rekeying = "timeout shortened";
9408 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9412 old_max_data_size = ssh->max_data_size;
9413 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
9414 if (old_max_data_size != ssh->max_data_size &&
9415 ssh->max_data_size != 0) {
9416 if (ssh->outgoing_data_size > ssh->max_data_size ||
9417 ssh->incoming_data_size > ssh->max_data_size)
9418 rekeying = "data limit lowered";
9421 if (ssh->cfg.compression != cfg->compression) {
9422 rekeying = "compression setting changed";
9423 rekey_mandatory = TRUE;
9426 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
9427 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
9428 sizeof(ssh->cfg.ssh_cipherlist))) {
9429 rekeying = "cipher settings changed";
9430 rekey_mandatory = TRUE;
9433 ssh->cfg = *cfg; /* STRUCTURE COPY */
9436 if (!ssh->kex_in_progress) {
9437 do_ssh2_transport(ssh, rekeying, -1, NULL);
9438 } else if (rekey_mandatory) {
9439 ssh->deferred_rekey_reason = rekeying;
9445 * Called to send data down the SSH connection.
9447 static int ssh_send(void *handle, char *buf, int len)
9449 Ssh ssh = (Ssh) handle;
9451 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9454 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9456 return ssh_sendbuffer(ssh);
9460 * Called to query the current amount of buffered stdin data.
9462 static int ssh_sendbuffer(void *handle)
9464 Ssh ssh = (Ssh) handle;
9467 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9471 * If the SSH socket itself has backed up, add the total backup
9472 * size on that to any individual buffer on the stdin channel.
9475 if (ssh->throttled_all)
9476 override_value = ssh->overall_bufsize;
9478 if (ssh->version == 1) {
9479 return override_value;
9480 } else if (ssh->version == 2) {
9481 if (!ssh->mainchan || ssh->mainchan->closes > 0)
9482 return override_value;
9484 return (override_value +
9485 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9492 * Called to set the size of the window from SSH's POV.
9494 static void ssh_size(void *handle, int width, int height)
9496 Ssh ssh = (Ssh) handle;
9497 struct Packet *pktout;
9499 ssh->term_width = width;
9500 ssh->term_height = height;
9502 switch (ssh->state) {
9503 case SSH_STATE_BEFORE_SIZE:
9504 case SSH_STATE_PREPACKET:
9505 case SSH_STATE_CLOSED:
9506 break; /* do nothing */
9507 case SSH_STATE_INTERMED:
9508 ssh->size_needed = TRUE; /* buffer for later */
9510 case SSH_STATE_SESSION:
9511 if (!ssh->cfg.nopty) {
9512 if (ssh->version == 1) {
9513 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9514 PKT_INT, ssh->term_height,
9515 PKT_INT, ssh->term_width,
9516 PKT_INT, 0, PKT_INT, 0, PKT_END);
9517 } else if (ssh->mainchan) {
9518 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9519 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9520 ssh2_pkt_addstring(pktout, "window-change");
9521 ssh2_pkt_addbool(pktout, 0);
9522 ssh2_pkt_adduint32(pktout, ssh->term_width);
9523 ssh2_pkt_adduint32(pktout, ssh->term_height);
9524 ssh2_pkt_adduint32(pktout, 0);
9525 ssh2_pkt_adduint32(pktout, 0);
9526 ssh2_pkt_send(ssh, pktout);
9534 * Return a list of the special codes that make sense in this
9537 static const struct telnet_special *ssh_get_specials(void *handle)
9539 static const struct telnet_special ssh1_ignore_special[] = {
9540 {"IGNORE message", TS_NOP}
9542 static const struct telnet_special ssh2_ignore_special[] = {
9543 {"IGNORE message", TS_NOP},
9545 static const struct telnet_special ssh2_rekey_special[] = {
9546 {"Repeat key exchange", TS_REKEY},
9548 static const struct telnet_special ssh2_session_specials[] = {
9551 /* These are the signal names defined by RFC 4254.
9552 * They include all the ISO C signals, but are a subset of the POSIX
9553 * required signals. */
9554 {"SIGINT (Interrupt)", TS_SIGINT},
9555 {"SIGTERM (Terminate)", TS_SIGTERM},
9556 {"SIGKILL (Kill)", TS_SIGKILL},
9557 {"SIGQUIT (Quit)", TS_SIGQUIT},
9558 {"SIGHUP (Hangup)", TS_SIGHUP},
9559 {"More signals", TS_SUBMENU},
9560 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9561 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9562 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9563 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9566 static const struct telnet_special specials_end[] = {
9569 /* XXX review this length for any changes: */
9570 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9571 lenof(ssh2_rekey_special) +
9572 lenof(ssh2_session_specials) +
9573 lenof(specials_end)];
9574 Ssh ssh = (Ssh) handle;
9576 #define ADD_SPECIALS(name) \
9578 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9579 memcpy(&ssh_specials[i], name, sizeof name); \
9583 if (ssh->version == 1) {
9584 /* Don't bother offering IGNORE if we've decided the remote
9585 * won't cope with it, since we wouldn't bother sending it if
9587 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9588 ADD_SPECIALS(ssh1_ignore_special);
9589 } else if (ssh->version == 2) {
9590 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9591 ADD_SPECIALS(ssh2_ignore_special);
9592 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9593 ADD_SPECIALS(ssh2_rekey_special);
9595 ADD_SPECIALS(ssh2_session_specials);
9596 } /* else we're not ready yet */
9599 ADD_SPECIALS(specials_end);
9600 return ssh_specials;
9608 * Send special codes. TS_EOF is useful for `plink', so you
9609 * can send an EOF and collect resulting output (e.g. `plink
9612 static void ssh_special(void *handle, Telnet_Special code)
9614 Ssh ssh = (Ssh) handle;
9615 struct Packet *pktout;
9617 if (code == TS_EOF) {
9618 if (ssh->state != SSH_STATE_SESSION) {
9620 * Buffer the EOF in case we are pre-SESSION, so we can
9621 * send it as soon as we reach SESSION.
9624 ssh->eof_needed = TRUE;
9627 if (ssh->version == 1) {
9628 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9629 } else if (ssh->mainchan) {
9630 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
9631 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9632 ssh2_pkt_send(ssh, pktout);
9633 ssh->send_ok = 0; /* now stop trying to read from stdin */
9635 logevent("Sent EOF message");
9636 } else if (code == TS_PING || code == TS_NOP) {
9637 if (ssh->state == SSH_STATE_CLOSED
9638 || ssh->state == SSH_STATE_PREPACKET) return;
9639 if (ssh->version == 1) {
9640 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9641 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9643 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9644 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9645 ssh2_pkt_addstring_start(pktout);
9646 ssh2_pkt_send_noqueue(ssh, pktout);
9649 } else if (code == TS_REKEY) {
9650 if (!ssh->kex_in_progress && ssh->version == 2) {
9651 do_ssh2_transport(ssh, "at user request", -1, NULL);
9653 } else if (code == TS_BRK) {
9654 if (ssh->state == SSH_STATE_CLOSED
9655 || ssh->state == SSH_STATE_PREPACKET) return;
9656 if (ssh->version == 1) {
9657 logevent("Unable to send BREAK signal in SSH-1");
9658 } else if (ssh->mainchan) {
9659 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9660 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9661 ssh2_pkt_addstring(pktout, "break");
9662 ssh2_pkt_addbool(pktout, 0);
9663 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9664 ssh2_pkt_send(ssh, pktout);
9667 /* Is is a POSIX signal? */
9668 char *signame = NULL;
9669 if (code == TS_SIGABRT) signame = "ABRT";
9670 if (code == TS_SIGALRM) signame = "ALRM";
9671 if (code == TS_SIGFPE) signame = "FPE";
9672 if (code == TS_SIGHUP) signame = "HUP";
9673 if (code == TS_SIGILL) signame = "ILL";
9674 if (code == TS_SIGINT) signame = "INT";
9675 if (code == TS_SIGKILL) signame = "KILL";
9676 if (code == TS_SIGPIPE) signame = "PIPE";
9677 if (code == TS_SIGQUIT) signame = "QUIT";
9678 if (code == TS_SIGSEGV) signame = "SEGV";
9679 if (code == TS_SIGTERM) signame = "TERM";
9680 if (code == TS_SIGUSR1) signame = "USR1";
9681 if (code == TS_SIGUSR2) signame = "USR2";
9682 /* The SSH-2 protocol does in principle support arbitrary named
9683 * signals, including signame@domain, but we don't support those. */
9685 /* It's a signal. */
9686 if (ssh->version == 2 && ssh->mainchan) {
9687 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9688 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9689 ssh2_pkt_addstring(pktout, "signal");
9690 ssh2_pkt_addbool(pktout, 0);
9691 ssh2_pkt_addstring(pktout, signame);
9692 ssh2_pkt_send(ssh, pktout);
9693 logeventf(ssh, "Sent signal SIG%s", signame);
9696 /* Never heard of it. Do nothing */
9701 void *new_sock_channel(void *handle, Socket s)
9703 Ssh ssh = (Ssh) handle;
9704 struct ssh_channel *c;
9705 c = snew(struct ssh_channel);
9708 ssh2_channel_init(c);
9710 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9712 add234(ssh->channels, c);
9717 * This is called when stdout/stderr (the entity to which
9718 * from_backend sends data) manages to clear some backlog.
9720 static void ssh_unthrottle(void *handle, int bufsize)
9722 Ssh ssh = (Ssh) handle;
9725 if (ssh->version == 1) {
9726 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9727 ssh->v1_stdout_throttling = 0;
9728 ssh_throttle_conn(ssh, -1);
9731 if (ssh->mainchan) {
9732 ssh2_set_window(ssh->mainchan,
9733 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9734 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9735 if (ssh->cfg.ssh_simple)
9738 buflimit = ssh->mainchan->v.v2.locmaxwin;
9739 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9740 ssh->mainchan->throttling_conn = 0;
9741 ssh_throttle_conn(ssh, -1);
9747 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9749 struct ssh_channel *c = (struct ssh_channel *)channel;
9751 struct Packet *pktout;
9753 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9755 if (ssh->version == 1) {
9756 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9757 PKT_INT, c->localid,
9760 /* PKT_STR, <org:orgport>, */
9763 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9764 ssh2_pkt_addstring(pktout, "direct-tcpip");
9765 ssh2_pkt_adduint32(pktout, c->localid);
9766 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9767 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9768 ssh2_pkt_addstring(pktout, hostname);
9769 ssh2_pkt_adduint32(pktout, port);
9771 * We make up values for the originator data; partly it's
9772 * too much hassle to keep track, and partly I'm not
9773 * convinced the server should be told details like that
9774 * about my local network configuration.
9775 * The "originator IP address" is syntactically a numeric
9776 * IP address, and some servers (e.g., Tectia) get upset
9777 * if it doesn't match this syntax.
9779 ssh2_pkt_addstring(pktout, "0.0.0.0");
9780 ssh2_pkt_adduint32(pktout, 0);
9781 ssh2_pkt_send(ssh, pktout);
9785 static int ssh_connected(void *handle)
9787 Ssh ssh = (Ssh) handle;
9788 return ssh->s != NULL;
9791 static int ssh_sendok(void *handle)
9793 Ssh ssh = (Ssh) handle;
9794 return ssh->send_ok;
9797 static int ssh_ldisc(void *handle, int option)
9799 Ssh ssh = (Ssh) handle;
9800 if (option == LD_ECHO)
9801 return ssh->echoing;
9802 if (option == LD_EDIT)
9803 return ssh->editing;
9807 static void ssh_provide_ldisc(void *handle, void *ldisc)
9809 Ssh ssh = (Ssh) handle;
9813 static void ssh_provide_logctx(void *handle, void *logctx)
9815 Ssh ssh = (Ssh) handle;
9816 ssh->logctx = logctx;
9819 static int ssh_return_exitcode(void *handle)
9821 Ssh ssh = (Ssh) handle;
9825 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
9829 * cfg_info for SSH is the currently running version of the
9830 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9832 static int ssh_cfg_info(void *handle)
9834 Ssh ssh = (Ssh) handle;
9835 return ssh->version;
9839 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9840 * that fails. This variable is the means by which scp.c can reach
9841 * into the SSH code and find out which one it got.
9843 extern int ssh_fallback_cmd(void *handle)
9845 Ssh ssh = (Ssh) handle;
9846 return ssh->fallback_cmd;
9849 Backend ssh_backend = {
9859 ssh_return_exitcode,