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
199 #define BUG_CHOKES_ON_WINADJ 1024
202 * Codes for terminal modes.
203 * Most of these are the same in SSH-1 and SSH-2.
204 * This list is derived from RFC 4254 and
207 static const struct {
208 const char* const mode;
210 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
212 /* "V" prefix discarded for special characters relative to SSH specs */
213 { "INTR", 1, TTY_OP_CHAR },
214 { "QUIT", 2, TTY_OP_CHAR },
215 { "ERASE", 3, TTY_OP_CHAR },
216 { "KILL", 4, TTY_OP_CHAR },
217 { "EOF", 5, TTY_OP_CHAR },
218 { "EOL", 6, TTY_OP_CHAR },
219 { "EOL2", 7, TTY_OP_CHAR },
220 { "START", 8, TTY_OP_CHAR },
221 { "STOP", 9, TTY_OP_CHAR },
222 { "SUSP", 10, TTY_OP_CHAR },
223 { "DSUSP", 11, TTY_OP_CHAR },
224 { "REPRINT", 12, TTY_OP_CHAR },
225 { "WERASE", 13, TTY_OP_CHAR },
226 { "LNEXT", 14, TTY_OP_CHAR },
227 { "FLUSH", 15, TTY_OP_CHAR },
228 { "SWTCH", 16, TTY_OP_CHAR },
229 { "STATUS", 17, TTY_OP_CHAR },
230 { "DISCARD", 18, TTY_OP_CHAR },
231 { "IGNPAR", 30, TTY_OP_BOOL },
232 { "PARMRK", 31, TTY_OP_BOOL },
233 { "INPCK", 32, TTY_OP_BOOL },
234 { "ISTRIP", 33, TTY_OP_BOOL },
235 { "INLCR", 34, TTY_OP_BOOL },
236 { "IGNCR", 35, TTY_OP_BOOL },
237 { "ICRNL", 36, TTY_OP_BOOL },
238 { "IUCLC", 37, TTY_OP_BOOL },
239 { "IXON", 38, TTY_OP_BOOL },
240 { "IXANY", 39, TTY_OP_BOOL },
241 { "IXOFF", 40, TTY_OP_BOOL },
242 { "IMAXBEL", 41, TTY_OP_BOOL },
243 { "ISIG", 50, TTY_OP_BOOL },
244 { "ICANON", 51, TTY_OP_BOOL },
245 { "XCASE", 52, TTY_OP_BOOL },
246 { "ECHO", 53, TTY_OP_BOOL },
247 { "ECHOE", 54, TTY_OP_BOOL },
248 { "ECHOK", 55, TTY_OP_BOOL },
249 { "ECHONL", 56, TTY_OP_BOOL },
250 { "NOFLSH", 57, TTY_OP_BOOL },
251 { "TOSTOP", 58, TTY_OP_BOOL },
252 { "IEXTEN", 59, TTY_OP_BOOL },
253 { "ECHOCTL", 60, TTY_OP_BOOL },
254 { "ECHOKE", 61, TTY_OP_BOOL },
255 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
256 { "OPOST", 70, TTY_OP_BOOL },
257 { "OLCUC", 71, TTY_OP_BOOL },
258 { "ONLCR", 72, TTY_OP_BOOL },
259 { "OCRNL", 73, TTY_OP_BOOL },
260 { "ONOCR", 74, TTY_OP_BOOL },
261 { "ONLRET", 75, TTY_OP_BOOL },
262 { "CS7", 90, TTY_OP_BOOL },
263 { "CS8", 91, TTY_OP_BOOL },
264 { "PARENB", 92, TTY_OP_BOOL },
265 { "PARODD", 93, TTY_OP_BOOL }
268 /* Miscellaneous other tty-related constants. */
269 #define SSH_TTY_OP_END 0
270 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
271 #define SSH1_TTY_OP_ISPEED 192
272 #define SSH1_TTY_OP_OSPEED 193
273 #define SSH2_TTY_OP_ISPEED 128
274 #define SSH2_TTY_OP_OSPEED 129
276 /* Helper functions for parsing tty-related config. */
277 static unsigned int ssh_tty_parse_specchar(char *s)
282 ret = ctrlparse(s, &next);
283 if (!next) ret = s[0];
285 ret = 255; /* special value meaning "don't set" */
289 static unsigned int ssh_tty_parse_boolean(char *s)
291 if (stricmp(s, "yes") == 0 ||
292 stricmp(s, "on") == 0 ||
293 stricmp(s, "true") == 0 ||
294 stricmp(s, "+") == 0)
296 else if (stricmp(s, "no") == 0 ||
297 stricmp(s, "off") == 0 ||
298 stricmp(s, "false") == 0 ||
299 stricmp(s, "-") == 0)
300 return 0; /* false */
302 return (atoi(s) != 0);
305 #define translate(x) if (type == x) return #x
306 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
307 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
308 static char *ssh1_pkt_type(int type)
310 translate(SSH1_MSG_DISCONNECT);
311 translate(SSH1_SMSG_PUBLIC_KEY);
312 translate(SSH1_CMSG_SESSION_KEY);
313 translate(SSH1_CMSG_USER);
314 translate(SSH1_CMSG_AUTH_RSA);
315 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
316 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
317 translate(SSH1_CMSG_AUTH_PASSWORD);
318 translate(SSH1_CMSG_REQUEST_PTY);
319 translate(SSH1_CMSG_WINDOW_SIZE);
320 translate(SSH1_CMSG_EXEC_SHELL);
321 translate(SSH1_CMSG_EXEC_CMD);
322 translate(SSH1_SMSG_SUCCESS);
323 translate(SSH1_SMSG_FAILURE);
324 translate(SSH1_CMSG_STDIN_DATA);
325 translate(SSH1_SMSG_STDOUT_DATA);
326 translate(SSH1_SMSG_STDERR_DATA);
327 translate(SSH1_CMSG_EOF);
328 translate(SSH1_SMSG_EXIT_STATUS);
329 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
330 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
331 translate(SSH1_MSG_CHANNEL_DATA);
332 translate(SSH1_MSG_CHANNEL_CLOSE);
333 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
334 translate(SSH1_SMSG_X11_OPEN);
335 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
336 translate(SSH1_MSG_PORT_OPEN);
337 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
338 translate(SSH1_SMSG_AGENT_OPEN);
339 translate(SSH1_MSG_IGNORE);
340 translate(SSH1_CMSG_EXIT_CONFIRMATION);
341 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
342 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
343 translate(SSH1_MSG_DEBUG);
344 translate(SSH1_CMSG_REQUEST_COMPRESSION);
345 translate(SSH1_CMSG_AUTH_TIS);
346 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
347 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
348 translate(SSH1_CMSG_AUTH_CCARD);
349 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
350 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
353 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
360 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
361 translate(SSH2_MSG_DISCONNECT);
362 translate(SSH2_MSG_IGNORE);
363 translate(SSH2_MSG_UNIMPLEMENTED);
364 translate(SSH2_MSG_DEBUG);
365 translate(SSH2_MSG_SERVICE_REQUEST);
366 translate(SSH2_MSG_SERVICE_ACCEPT);
367 translate(SSH2_MSG_KEXINIT);
368 translate(SSH2_MSG_NEWKEYS);
369 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
371 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
375 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
377 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
378 translate(SSH2_MSG_USERAUTH_REQUEST);
379 translate(SSH2_MSG_USERAUTH_FAILURE);
380 translate(SSH2_MSG_USERAUTH_SUCCESS);
381 translate(SSH2_MSG_USERAUTH_BANNER);
382 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
383 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
384 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
385 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
386 translate(SSH2_MSG_GLOBAL_REQUEST);
387 translate(SSH2_MSG_REQUEST_SUCCESS);
388 translate(SSH2_MSG_REQUEST_FAILURE);
389 translate(SSH2_MSG_CHANNEL_OPEN);
390 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
391 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
392 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
393 translate(SSH2_MSG_CHANNEL_DATA);
394 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
395 translate(SSH2_MSG_CHANNEL_EOF);
396 translate(SSH2_MSG_CHANNEL_CLOSE);
397 translate(SSH2_MSG_CHANNEL_REQUEST);
398 translate(SSH2_MSG_CHANNEL_SUCCESS);
399 translate(SSH2_MSG_CHANNEL_FAILURE);
405 /* Enumeration values for fields in SSH-1 packets */
407 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
408 /* These values are for communicating relevant semantics of
409 * fields to the packet logging code. */
410 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
414 * Coroutine mechanics for the sillier bits of the code. If these
415 * macros look impenetrable to you, you might find it helpful to
418 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
420 * which explains the theory behind these macros.
422 * In particular, if you are getting `case expression not constant'
423 * errors when building with MS Visual Studio, this is because MS's
424 * Edit and Continue debugging feature causes their compiler to
425 * violate ANSI C. To disable Edit and Continue debugging:
427 * - right-click ssh.c in the FileView
429 * - select the C/C++ tab and the General category
430 * - under `Debug info:', select anything _other_ than `Program
431 * Database for Edit and Continue'.
433 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
434 #define crBeginState crBegin(s->crLine)
435 #define crStateP(t, v) \
437 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
439 #define crState(t) crStateP(t, ssh->t)
440 #define crFinish(z) } *crLine = 0; return (z); }
441 #define crFinishV } *crLine = 0; return; }
442 #define crFinishFree(z) } sfree(s); return (z); }
443 #define crFinishFreeV } sfree(s); return; }
444 #define crReturn(z) \
446 *crLine =__LINE__; return (z); case __LINE__:;\
450 *crLine=__LINE__; return; case __LINE__:;\
452 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
453 #define crStopV do{ *crLine = 0; return; }while(0)
454 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
455 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
457 typedef struct ssh_tag *Ssh;
460 static struct Packet *ssh1_pkt_init(int pkt_type);
461 static struct Packet *ssh2_pkt_init(int pkt_type);
462 static void ssh_pkt_ensure(struct Packet *, int length);
463 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
464 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
465 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
466 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
467 static void ssh_pkt_addstring_start(struct Packet *);
468 static void ssh_pkt_addstring_str(struct Packet *, char *data);
469 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
470 static void ssh_pkt_addstring(struct Packet *, char *data);
471 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
472 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
473 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
474 static int ssh2_pkt_construct(Ssh, struct Packet *);
475 static void ssh2_pkt_send(Ssh, struct Packet *);
476 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
477 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
478 struct Packet *pktin);
479 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
480 struct Packet *pktin);
481 static void ssh2_channel_check_close(struct ssh_channel *c);
482 static void ssh_channel_destroy(struct ssh_channel *c);
485 * Buffer management constants. There are several of these for
486 * various different purposes:
488 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
489 * on a local data stream before we throttle the whole SSH
490 * connection (in SSH-1 only). Throttling the whole connection is
491 * pretty drastic so we set this high in the hope it won't
494 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
495 * on the SSH connection itself before we defensively throttle
496 * _all_ local data streams. This is pretty drastic too (though
497 * thankfully unlikely in SSH-2 since the window mechanism should
498 * ensure that the server never has any need to throttle its end
499 * of the connection), so we set this high as well.
501 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
504 * - OUR_V2_BIGWIN is the window size we advertise for the only
505 * channel in a simple connection. It must be <= INT_MAX.
507 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
508 * to the remote side. This actually has nothing to do with the
509 * size of the _packet_, but is instead a limit on the amount
510 * of data we're willing to receive in a single SSH2 channel
513 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
514 * _packet_ we're prepared to cope with. It must be a multiple
515 * of the cipher block size, and must be at least 35000.
518 #define SSH1_BUFFER_LIMIT 32768
519 #define SSH_MAX_BACKLOG 32768
520 #define OUR_V2_WINSIZE 16384
521 #define OUR_V2_BIGWIN 0x7fffffff
522 #define OUR_V2_MAXPKT 0x4000UL
523 #define OUR_V2_PACKETLIMIT 0x9000UL
525 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
527 const static struct ssh_mac *macs[] = {
528 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
530 const static struct ssh_mac *buggymacs[] = {
531 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
534 static void *ssh_comp_none_init(void)
538 static void ssh_comp_none_cleanup(void *handle)
541 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
542 unsigned char **outblock, int *outlen)
546 static int ssh_comp_none_disable(void *handle)
550 const static struct ssh_compress ssh_comp_none = {
552 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
553 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
554 ssh_comp_none_disable, NULL
556 extern const struct ssh_compress ssh_zlib;
557 const static struct ssh_compress *compressions[] = {
558 &ssh_zlib, &ssh_comp_none
561 enum { /* channel types */
566 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
568 * CHAN_ZOMBIE is used to indicate a channel for which we've
569 * already destroyed the local data source: for instance, if a
570 * forwarded port experiences a socket error on the local side, we
571 * immediately destroy its local socket and turn the SSH channel
577 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
578 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
579 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
582 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
585 struct outstanding_channel_request {
586 cchandler_fn_t handler;
588 struct outstanding_channel_request *next;
592 * 2-3-4 tree storing channels.
595 Ssh ssh; /* pointer back to main context */
596 unsigned remoteid, localid;
598 /* True if we opened this channel but server hasn't confirmed. */
601 * In SSH-1, this value contains four bits:
603 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
604 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
605 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
606 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
608 * A channel is completely finished with when all four bits are set.
610 * In SSH-2, the four bits mean:
612 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
613 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
614 * 4 We have received SSH2_MSG_CHANNEL_EOF.
615 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
617 * A channel is completely finished with when we have both sent
618 * and received CLOSE.
620 * The symbolic constants below use the SSH-2 terminology, which
621 * is a bit confusing in SSH-1, but we have to use _something_.
623 #define CLOSES_SENT_EOF 1
624 #define CLOSES_SENT_CLOSE 2
625 #define CLOSES_RCVD_EOF 4
626 #define CLOSES_RCVD_CLOSE 8
630 * This flag indicates that an EOF is pending on the outgoing side
631 * of the channel: that is, wherever we're getting the data for
632 * this channel has sent us some data followed by EOF. We can't
633 * actually send the EOF until we've finished sending the data, so
634 * we set this flag instead to remind us to do so once our buffer
640 * True if this channel is causing the underlying connection to be
645 struct ssh2_data_channel {
647 unsigned remwindow, remmaxpkt;
648 /* locwindow is signed so we can cope with excess data. */
649 int locwindow, locmaxwin;
651 * remlocwin is the amount of local window that we think
652 * the remote end had available to it after it sent the
653 * last data packet or window adjust ack.
657 * These store the list of channel requests that haven't
660 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
661 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
665 struct ssh_agent_channel {
666 unsigned char *message;
667 unsigned char msglen[4];
668 unsigned lensofar, totallen;
669 int outstanding_requests;
671 struct ssh_x11_channel {
674 struct ssh_pfd_channel {
681 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
682 * use this structure in different ways, reflecting SSH-2's
683 * altogether saner approach to port forwarding.
685 * In SSH-1, you arrange a remote forwarding by sending the server
686 * the remote port number, and the local destination host:port.
687 * When a connection comes in, the server sends you back that
688 * host:port pair, and you connect to it. This is a ready-made
689 * security hole if you're not on the ball: a malicious server
690 * could send you back _any_ host:port pair, so if you trustingly
691 * connect to the address it gives you then you've just opened the
692 * entire inside of your corporate network just by connecting
693 * through it to a dodgy SSH server. Hence, we must store a list of
694 * host:port pairs we _are_ trying to forward to, and reject a
695 * connection request from the server if it's not in the list.
697 * In SSH-2, each side of the connection minds its own business and
698 * doesn't send unnecessary information to the other. You arrange a
699 * remote forwarding by sending the server just the remote port
700 * number. When a connection comes in, the server tells you which
701 * of its ports was connected to; and _you_ have to remember what
702 * local host:port pair went with that port number.
704 * Hence, in SSH-1 this structure is indexed by destination
705 * host:port pair, whereas in SSH-2 it is indexed by source port.
707 struct ssh_portfwd; /* forward declaration */
709 struct ssh_rportfwd {
710 unsigned sport, dport;
713 struct ssh_portfwd *pfrec;
715 #define free_rportfwd(pf) ( \
716 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
719 * Separately to the rportfwd tree (which is for looking up port
720 * open requests from the server), a tree of _these_ structures is
721 * used to keep track of all the currently open port forwardings,
722 * so that we can reconfigure in mid-session if the user requests
726 enum { DESTROY, KEEP, CREATE } status;
728 unsigned sport, dport;
731 struct ssh_rportfwd *remote;
735 #define free_portfwd(pf) ( \
736 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
737 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
740 long length; /* length of `data' actually used */
741 long forcepad; /* SSH-2: force padding to at least this length */
742 int type; /* only used for incoming packets */
743 unsigned long sequence; /* SSH-2 incoming sequence number */
744 unsigned char *data; /* allocated storage */
745 unsigned char *body; /* offset of payload within `data' */
746 long savedpos; /* temporary index into `data' (for strings) */
747 long maxlen; /* amount of storage allocated for `data' */
748 long encrypted_len; /* for SSH-2 total-size counting */
751 * State associated with packet logging
755 struct logblank_t *blanks;
758 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
759 struct Packet *pktin);
760 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
761 struct Packet *pktin);
762 static void ssh1_protocol_setup(Ssh ssh);
763 static void ssh2_protocol_setup(Ssh ssh);
764 static void ssh_size(void *handle, int width, int height);
765 static void ssh_special(void *handle, Telnet_Special);
766 static int ssh2_try_send(struct ssh_channel *c);
767 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
768 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
769 static void ssh2_set_window(struct ssh_channel *c, int newwin);
770 static int ssh_sendbuffer(void *handle);
771 static int ssh_do_close(Ssh ssh, int notify_exit);
772 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
773 static int ssh2_pkt_getbool(struct Packet *pkt);
774 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
775 static void ssh2_timer(void *ctx, unsigned long now);
776 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
777 struct Packet *pktin);
778 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
780 struct rdpkt1_state_tag {
781 long len, pad, biglen, to_read;
782 unsigned long realcrc, gotcrc;
786 struct Packet *pktin;
789 struct rdpkt2_state_tag {
790 long len, pad, payload, packetlen, maclen;
793 unsigned long incoming_sequence;
794 struct Packet *pktin;
797 struct queued_handler;
798 struct queued_handler {
800 chandler_fn_t handler;
802 struct queued_handler *next;
806 const struct plug_function_table *fn;
807 /* the above field _must_ be first in the structure */
817 unsigned char session_key[32];
819 int v1_remote_protoflags;
820 int v1_local_protoflags;
821 int agentfwd_enabled;
824 const struct ssh_cipher *cipher;
827 const struct ssh2_cipher *cscipher, *sccipher;
828 void *cs_cipher_ctx, *sc_cipher_ctx;
829 const struct ssh_mac *csmac, *scmac;
830 void *cs_mac_ctx, *sc_mac_ctx;
831 const struct ssh_compress *cscomp, *sccomp;
832 void *cs_comp_ctx, *sc_comp_ctx;
833 const struct ssh_kex *kex;
834 const struct ssh_signkey *hostkey;
835 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
836 int v2_session_id_len;
842 int echoing, editing;
846 int ospeed, ispeed; /* temporaries */
847 int term_width, term_height;
849 tree234 *channels; /* indexed by local id */
850 struct ssh_channel *mainchan; /* primary session channel */
851 int ncmode; /* is primary channel direct-tcpip? */
856 tree234 *rportfwds, *portfwds;
860 SSH_STATE_BEFORE_SIZE,
866 int size_needed, eof_needed;
867 int sent_console_eof;
868 int got_pty; /* affects EOF behaviour on main channel */
870 struct Packet **queue;
871 int queuelen, queuesize;
873 unsigned char *deferred_send_data;
874 int deferred_len, deferred_size;
877 * Gross hack: pscp will try to start SFTP but fall back to
878 * scp1 if that fails. This variable is the means by which
879 * scp.c can reach into the SSH code and find out which one it
884 bufchain banner; /* accumulates banners during do_ssh2_authconn */
889 struct X11Display *x11disp;
892 int conn_throttle_count;
895 int v1_stdout_throttling;
896 unsigned long v2_outgoing_sequence;
898 int ssh1_rdpkt_crstate;
899 int ssh2_rdpkt_crstate;
900 int ssh_gotdata_crstate;
901 int do_ssh1_connection_crstate;
903 void *do_ssh_init_state;
904 void *do_ssh1_login_state;
905 void *do_ssh2_transport_state;
906 void *do_ssh2_authconn_state;
908 struct rdpkt1_state_tag rdpkt1_state;
909 struct rdpkt2_state_tag rdpkt2_state;
911 /* SSH-1 and SSH-2 use this for different things, but both use it */
912 int protocol_initial_phase_done;
914 void (*protocol) (Ssh ssh, void *vin, int inlen,
916 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
919 * We maintain our own copy of a Conf structure here. That way,
920 * when we're passed a new one for reconfiguration, we can check
921 * the differences and potentially reconfigure port forwardings
922 * etc in mid-session.
927 * Values cached out of conf so as to avoid the tree234 lookup
928 * cost every time they're used.
933 * Dynamically allocated username string created during SSH
934 * login. Stored in here rather than in the coroutine state so
935 * that it'll be reliably freed if we shut down the SSH session
936 * at some unexpected moment.
941 * Used to transfer data back from async callbacks.
943 void *agent_response;
944 int agent_response_len;
948 * The SSH connection can be set as `frozen', meaning we are
949 * not currently accepting incoming data from the network. This
950 * is slightly more serious than setting the _socket_ as
951 * frozen, because we may already have had data passed to us
952 * from the network which we need to delay processing until
953 * after the freeze is lifted, so we also need a bufchain to
957 bufchain queued_incoming_data;
960 * Dispatch table for packet types that we may have to deal
963 handler_fn_t packet_dispatch[256];
966 * Queues of one-off handler functions for success/failure
967 * indications from a request.
969 struct queued_handler *qhead, *qtail;
970 handler_fn_t q_saved_handler1, q_saved_handler2;
973 * This module deals with sending keepalives.
978 * Track incoming and outgoing data sizes and time, for
981 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
982 unsigned long max_data_size;
984 unsigned long next_rekey, last_rekey;
985 char *deferred_rekey_reason; /* points to STATIC string; don't free */
988 * Fully qualified host name, which we need if doing GSSAPI.
994 * GSSAPI libraries for this session.
996 struct ssh_gss_liblist *gsslibs;
1000 #define logevent(s) logevent(ssh->frontend, s)
1002 /* logevent, only printf-formatted. */
1003 static void logeventf(Ssh ssh, const char *fmt, ...)
1009 buf = dupvprintf(fmt, ap);
1015 static void bomb_out(Ssh ssh, char *text)
1017 ssh_do_close(ssh, FALSE);
1019 connection_fatal(ssh->frontend, "%s", text);
1023 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1025 /* Functions to leave bits out of the SSH packet log file. */
1027 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1029 if (conf_get_int(ssh->conf, CONF_logomitpass))
1030 pkt->logmode = blanktype;
1033 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1035 if (ssh->logomitdata)
1036 pkt->logmode = blanktype;
1039 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1041 pkt->logmode = PKTLOG_EMIT;
1044 /* Helper function for common bits of parsing ttymodes. */
1045 static void parse_ttymodes(Ssh ssh,
1046 void (*do_mode)(void *data, char *mode, char *val),
1051 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1053 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1055 * val[0] is either 'V', indicating that an explicit value
1056 * follows it, or 'A' indicating that we should pass the
1057 * value through from the local environment via get_ttymode.
1059 if (val[0] == 'A') {
1060 val = get_ttymode(ssh->frontend, key);
1062 do_mode(data, key, val);
1066 do_mode(data, key, val + 1); /* skip the 'V' */
1070 static int ssh_channelcmp(void *av, void *bv)
1072 struct ssh_channel *a = (struct ssh_channel *) av;
1073 struct ssh_channel *b = (struct ssh_channel *) bv;
1074 if (a->localid < b->localid)
1076 if (a->localid > b->localid)
1080 static int ssh_channelfind(void *av, void *bv)
1082 unsigned *a = (unsigned *) av;
1083 struct ssh_channel *b = (struct ssh_channel *) bv;
1084 if (*a < b->localid)
1086 if (*a > b->localid)
1091 static int ssh_rportcmp_ssh1(void *av, void *bv)
1093 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1094 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1096 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1097 return i < 0 ? -1 : +1;
1098 if (a->dport > b->dport)
1100 if (a->dport < b->dport)
1105 static int ssh_rportcmp_ssh2(void *av, void *bv)
1107 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1108 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1110 if (a->sport > b->sport)
1112 if (a->sport < b->sport)
1118 * Special form of strcmp which can cope with NULL inputs. NULL is
1119 * defined to sort before even the empty string.
1121 static int nullstrcmp(const char *a, const char *b)
1123 if (a == NULL && b == NULL)
1129 return strcmp(a, b);
1132 static int ssh_portcmp(void *av, void *bv)
1134 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1135 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1137 if (a->type > b->type)
1139 if (a->type < b->type)
1141 if (a->addressfamily > b->addressfamily)
1143 if (a->addressfamily < b->addressfamily)
1145 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1146 return i < 0 ? -1 : +1;
1147 if (a->sport > b->sport)
1149 if (a->sport < b->sport)
1151 if (a->type != 'D') {
1152 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1153 return i < 0 ? -1 : +1;
1154 if (a->dport > b->dport)
1156 if (a->dport < b->dport)
1162 static int alloc_channel_id(Ssh ssh)
1164 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1165 unsigned low, high, mid;
1167 struct ssh_channel *c;
1170 * First-fit allocation of channel numbers: always pick the
1171 * lowest unused one. To do this, binary-search using the
1172 * counted B-tree to find the largest channel ID which is in a
1173 * contiguous sequence from the beginning. (Precisely
1174 * everything in that sequence must have ID equal to its tree
1175 * index plus CHANNEL_NUMBER_OFFSET.)
1177 tsize = count234(ssh->channels);
1181 while (high - low > 1) {
1182 mid = (high + low) / 2;
1183 c = index234(ssh->channels, mid);
1184 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1185 low = mid; /* this one is fine */
1187 high = mid; /* this one is past it */
1190 * Now low points to either -1, or the tree index of the
1191 * largest ID in the initial sequence.
1194 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1195 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1197 return low + 1 + CHANNEL_NUMBER_OFFSET;
1200 static void c_write_stderr(int trusted, const char *buf, int len)
1203 for (i = 0; i < len; i++)
1204 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1205 fputc(buf[i], stderr);
1208 static void c_write(Ssh ssh, const char *buf, int len)
1210 if (flags & FLAG_STDERR)
1211 c_write_stderr(1, buf, len);
1213 from_backend(ssh->frontend, 1, buf, len);
1216 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1218 if (flags & FLAG_STDERR)
1219 c_write_stderr(0, buf, len);
1221 from_backend_untrusted(ssh->frontend, buf, len);
1224 static void c_write_str(Ssh ssh, const char *buf)
1226 c_write(ssh, buf, strlen(buf));
1229 static void ssh_free_packet(struct Packet *pkt)
1234 static struct Packet *ssh_new_packet(void)
1236 struct Packet *pkt = snew(struct Packet);
1238 pkt->body = pkt->data = NULL;
1240 pkt->logmode = PKTLOG_EMIT;
1248 * Collect incoming data in the incoming packet buffer.
1249 * Decipher and verify the packet when it is completely read.
1250 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1251 * Update the *data and *datalen variables.
1252 * Return a Packet structure when a packet is completed.
1254 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1256 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1258 crBegin(ssh->ssh1_rdpkt_crstate);
1260 st->pktin = ssh_new_packet();
1262 st->pktin->type = 0;
1263 st->pktin->length = 0;
1265 for (st->i = st->len = 0; st->i < 4; st->i++) {
1266 while ((*datalen) == 0)
1268 st->len = (st->len << 8) + **data;
1269 (*data)++, (*datalen)--;
1272 st->pad = 8 - (st->len % 8);
1273 st->biglen = st->len + st->pad;
1274 st->pktin->length = st->len - 5;
1276 if (st->biglen < 0) {
1277 bombout(("Extremely large packet length from server suggests"
1278 " data stream corruption"));
1279 ssh_free_packet(st->pktin);
1283 st->pktin->maxlen = st->biglen;
1284 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1286 st->to_read = st->biglen;
1287 st->p = st->pktin->data;
1288 while (st->to_read > 0) {
1289 st->chunk = st->to_read;
1290 while ((*datalen) == 0)
1292 if (st->chunk > (*datalen))
1293 st->chunk = (*datalen);
1294 memcpy(st->p, *data, st->chunk);
1296 *datalen -= st->chunk;
1298 st->to_read -= st->chunk;
1301 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1302 st->biglen, NULL)) {
1303 bombout(("Network attack (CRC compensation) detected!"));
1304 ssh_free_packet(st->pktin);
1309 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1311 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1312 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1313 if (st->gotcrc != st->realcrc) {
1314 bombout(("Incorrect CRC received on packet"));
1315 ssh_free_packet(st->pktin);
1319 st->pktin->body = st->pktin->data + st->pad + 1;
1320 st->pktin->savedpos = 0;
1322 if (ssh->v1_compressing) {
1323 unsigned char *decompblk;
1325 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1326 st->pktin->body - 1, st->pktin->length + 1,
1327 &decompblk, &decomplen)) {
1328 bombout(("Zlib decompression encountered invalid data"));
1329 ssh_free_packet(st->pktin);
1333 if (st->pktin->maxlen < st->pad + decomplen) {
1334 st->pktin->maxlen = st->pad + decomplen;
1335 st->pktin->data = sresize(st->pktin->data,
1336 st->pktin->maxlen + APIEXTRA,
1338 st->pktin->body = st->pktin->data + st->pad + 1;
1341 memcpy(st->pktin->body - 1, decompblk, decomplen);
1343 st->pktin->length = decomplen - 1;
1346 st->pktin->type = st->pktin->body[-1];
1349 * Log incoming packet, possibly omitting sensitive fields.
1353 struct logblank_t blank;
1354 if (ssh->logomitdata) {
1355 int do_blank = FALSE, blank_prefix = 0;
1356 /* "Session data" packets - omit the data field */
1357 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1358 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1359 do_blank = TRUE; blank_prefix = 4;
1360 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1361 do_blank = TRUE; blank_prefix = 8;
1364 blank.offset = blank_prefix;
1365 blank.len = st->pktin->length;
1366 blank.type = PKTLOG_OMIT;
1370 log_packet(ssh->logctx,
1371 PKT_INCOMING, st->pktin->type,
1372 ssh1_pkt_type(st->pktin->type),
1373 st->pktin->body, st->pktin->length,
1374 nblanks, &blank, NULL);
1377 crFinish(st->pktin);
1380 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1382 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1384 crBegin(ssh->ssh2_rdpkt_crstate);
1386 st->pktin = ssh_new_packet();
1388 st->pktin->type = 0;
1389 st->pktin->length = 0;
1391 st->cipherblk = ssh->sccipher->blksize;
1394 if (st->cipherblk < 8)
1396 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1398 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1401 * When dealing with a CBC-mode cipher, we want to avoid the
1402 * possibility of an attacker's tweaking the ciphertext stream
1403 * so as to cause us to feed the same block to the block
1404 * cipher more than once and thus leak information
1405 * (VU#958563). The way we do this is not to take any
1406 * decisions on the basis of anything we've decrypted until
1407 * we've verified it with a MAC. That includes the packet
1408 * length, so we just read data and check the MAC repeatedly,
1409 * and when the MAC passes, see if the length we've got is
1413 /* May as well allocate the whole lot now. */
1414 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1417 /* Read an amount corresponding to the MAC. */
1418 for (st->i = 0; st->i < st->maclen; st->i++) {
1419 while ((*datalen) == 0)
1421 st->pktin->data[st->i] = *(*data)++;
1427 unsigned char seq[4];
1428 ssh->scmac->start(ssh->sc_mac_ctx);
1429 PUT_32BIT(seq, st->incoming_sequence);
1430 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1433 for (;;) { /* Once around this loop per cipher block. */
1434 /* Read another cipher-block's worth, and tack it onto the end. */
1435 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1436 while ((*datalen) == 0)
1438 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1441 /* Decrypt one more block (a little further back in the stream). */
1442 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1443 st->pktin->data + st->packetlen,
1445 /* Feed that block to the MAC. */
1446 ssh->scmac->bytes(ssh->sc_mac_ctx,
1447 st->pktin->data + st->packetlen, st->cipherblk);
1448 st->packetlen += st->cipherblk;
1449 /* See if that gives us a valid packet. */
1450 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1451 st->pktin->data + st->packetlen) &&
1452 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1455 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1456 bombout(("No valid incoming packet found"));
1457 ssh_free_packet(st->pktin);
1461 st->pktin->maxlen = st->packetlen + st->maclen;
1462 st->pktin->data = sresize(st->pktin->data,
1463 st->pktin->maxlen + APIEXTRA,
1466 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1469 * Acquire and decrypt the first block of the packet. This will
1470 * contain the length and padding details.
1472 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1473 while ((*datalen) == 0)
1475 st->pktin->data[st->i] = *(*data)++;
1480 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1481 st->pktin->data, st->cipherblk);
1484 * Now get the length figure.
1486 st->len = toint(GET_32BIT(st->pktin->data));
1489 * _Completely_ silly lengths should be stomped on before they
1490 * do us any more damage.
1492 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1493 (st->len + 4) % st->cipherblk != 0) {
1494 bombout(("Incoming packet was garbled on decryption"));
1495 ssh_free_packet(st->pktin);
1500 * So now we can work out the total packet length.
1502 st->packetlen = st->len + 4;
1505 * Allocate memory for the rest of the packet.
1507 st->pktin->maxlen = st->packetlen + st->maclen;
1508 st->pktin->data = sresize(st->pktin->data,
1509 st->pktin->maxlen + APIEXTRA,
1513 * Read and decrypt the remainder of the packet.
1515 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1517 while ((*datalen) == 0)
1519 st->pktin->data[st->i] = *(*data)++;
1522 /* Decrypt everything _except_ the MAC. */
1524 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1525 st->pktin->data + st->cipherblk,
1526 st->packetlen - st->cipherblk);
1532 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1533 st->len + 4, st->incoming_sequence)) {
1534 bombout(("Incorrect MAC received on packet"));
1535 ssh_free_packet(st->pktin);
1539 /* Get and sanity-check the amount of random padding. */
1540 st->pad = st->pktin->data[4];
1541 if (st->pad < 4 || st->len - st->pad < 1) {
1542 bombout(("Invalid padding length on received packet"));
1543 ssh_free_packet(st->pktin);
1547 * This enables us to deduce the payload length.
1549 st->payload = st->len - st->pad - 1;
1551 st->pktin->length = st->payload + 5;
1552 st->pktin->encrypted_len = st->packetlen;
1554 st->pktin->sequence = st->incoming_sequence++;
1557 * Decompress packet payload.
1560 unsigned char *newpayload;
1563 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1564 st->pktin->data + 5, st->pktin->length - 5,
1565 &newpayload, &newlen)) {
1566 if (st->pktin->maxlen < newlen + 5) {
1567 st->pktin->maxlen = newlen + 5;
1568 st->pktin->data = sresize(st->pktin->data,
1569 st->pktin->maxlen + APIEXTRA,
1572 st->pktin->length = 5 + newlen;
1573 memcpy(st->pktin->data + 5, newpayload, newlen);
1578 st->pktin->savedpos = 6;
1579 st->pktin->body = st->pktin->data;
1580 st->pktin->type = st->pktin->data[5];
1583 * Log incoming packet, possibly omitting sensitive fields.
1587 struct logblank_t blank;
1588 if (ssh->logomitdata) {
1589 int do_blank = FALSE, blank_prefix = 0;
1590 /* "Session data" packets - omit the data field */
1591 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1592 do_blank = TRUE; blank_prefix = 8;
1593 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1594 do_blank = TRUE; blank_prefix = 12;
1597 blank.offset = blank_prefix;
1598 blank.len = (st->pktin->length-6) - blank_prefix;
1599 blank.type = PKTLOG_OMIT;
1603 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1604 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1606 st->pktin->data+6, st->pktin->length-6,
1607 nblanks, &blank, &st->pktin->sequence);
1610 crFinish(st->pktin);
1613 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1615 int pad, biglen, i, pktoffs;
1619 * XXX various versions of SC (including 8.8.4) screw up the
1620 * register allocation in this function and use the same register
1621 * (D6) for len and as a temporary, with predictable results. The
1622 * following sledgehammer prevents this.
1629 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1630 ssh1_pkt_type(pkt->data[12]),
1631 pkt->body, pkt->length - (pkt->body - pkt->data),
1632 pkt->nblanks, pkt->blanks, NULL);
1633 sfree(pkt->blanks); pkt->blanks = NULL;
1636 if (ssh->v1_compressing) {
1637 unsigned char *compblk;
1639 zlib_compress_block(ssh->cs_comp_ctx,
1640 pkt->data + 12, pkt->length - 12,
1641 &compblk, &complen);
1642 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1643 memcpy(pkt->data + 12, compblk, complen);
1645 pkt->length = complen + 12;
1648 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1650 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1651 pad = 8 - (len % 8);
1653 biglen = len + pad; /* len(padding+type+data+CRC) */
1655 for (i = pktoffs; i < 4+8; i++)
1656 pkt->data[i] = random_byte();
1657 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1658 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1659 PUT_32BIT(pkt->data + pktoffs, len);
1662 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1663 pkt->data + pktoffs + 4, biglen);
1665 if (offset_p) *offset_p = pktoffs;
1666 return biglen + 4; /* len(length+padding+type+data+CRC) */
1669 static int s_write(Ssh ssh, void *data, int len)
1672 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1674 return sk_write(ssh->s, (char *)data, len);
1677 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1679 int len, backlog, offset;
1680 len = s_wrpkt_prepare(ssh, pkt, &offset);
1681 backlog = s_write(ssh, pkt->data + offset, len);
1682 if (backlog > SSH_MAX_BACKLOG)
1683 ssh_throttle_all(ssh, 1, backlog);
1684 ssh_free_packet(pkt);
1687 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1690 len = s_wrpkt_prepare(ssh, pkt, &offset);
1691 if (ssh->deferred_len + len > ssh->deferred_size) {
1692 ssh->deferred_size = ssh->deferred_len + len + 128;
1693 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1697 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1698 pkt->data + offset, len);
1699 ssh->deferred_len += len;
1700 ssh_free_packet(pkt);
1704 * Construct a SSH-1 packet with the specified contents.
1705 * (This all-at-once interface used to be the only one, but now SSH-1
1706 * packets can also be constructed incrementally.)
1708 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1714 pkt = ssh1_pkt_init(pkttype);
1716 while ((argtype = va_arg(ap, int)) != PKT_END) {
1717 unsigned char *argp, argchar;
1719 unsigned long argint;
1722 /* Actual fields in the packet */
1724 argint = va_arg(ap, int);
1725 ssh_pkt_adduint32(pkt, argint);
1728 argchar = (unsigned char) va_arg(ap, int);
1729 ssh_pkt_addbyte(pkt, argchar);
1732 argp = va_arg(ap, unsigned char *);
1733 arglen = va_arg(ap, int);
1734 ssh_pkt_adddata(pkt, argp, arglen);
1737 sargp = va_arg(ap, char *);
1738 ssh_pkt_addstring(pkt, sargp);
1741 bn = va_arg(ap, Bignum);
1742 ssh1_pkt_addmp(pkt, bn);
1744 /* Tokens for modifications to packet logging */
1746 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1749 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1752 end_log_omission(ssh, pkt);
1760 static void send_packet(Ssh ssh, int pkttype, ...)
1764 va_start(ap, pkttype);
1765 pkt = construct_packet(ssh, pkttype, ap);
1770 static void defer_packet(Ssh ssh, int pkttype, ...)
1774 va_start(ap, pkttype);
1775 pkt = construct_packet(ssh, pkttype, ap);
1777 s_wrpkt_defer(ssh, pkt);
1780 static int ssh_versioncmp(char *a, char *b)
1783 unsigned long av, bv;
1785 av = strtoul(a, &ae, 10);
1786 bv = strtoul(b, &be, 10);
1788 return (av < bv ? -1 : +1);
1793 av = strtoul(ae, &ae, 10);
1794 bv = strtoul(be, &be, 10);
1796 return (av < bv ? -1 : +1);
1801 * Utility routines for putting an SSH-protocol `string' and
1802 * `uint32' into a hash state.
1804 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1806 unsigned char lenblk[4];
1807 PUT_32BIT(lenblk, len);
1808 h->bytes(s, lenblk, 4);
1809 h->bytes(s, str, len);
1812 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1814 unsigned char intblk[4];
1815 PUT_32BIT(intblk, i);
1816 h->bytes(s, intblk, 4);
1820 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1822 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1824 if (pkt->maxlen < length) {
1825 unsigned char *body = pkt->body;
1826 int offset = body ? body - pkt->data : 0;
1827 pkt->maxlen = length + 256;
1828 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1829 if (body) pkt->body = pkt->data + offset;
1832 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1834 if (pkt->logmode != PKTLOG_EMIT) {
1836 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1838 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1839 (pkt->body - pkt->data);
1840 pkt->blanks[pkt->nblanks-1].len = len;
1841 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1844 ssh_pkt_ensure(pkt, pkt->length);
1845 memcpy(pkt->data + pkt->length - len, data, len);
1847 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1849 ssh_pkt_adddata(pkt, &byte, 1);
1851 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1853 ssh_pkt_adddata(pkt, &value, 1);
1855 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1858 PUT_32BIT(x, value);
1859 ssh_pkt_adddata(pkt, x, 4);
1861 static void ssh_pkt_addstring_start(struct Packet *pkt)
1863 ssh_pkt_adduint32(pkt, 0);
1864 pkt->savedpos = pkt->length;
1866 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1868 ssh_pkt_adddata(pkt, data, strlen(data));
1869 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1871 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1873 ssh_pkt_adddata(pkt, data, len);
1874 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1876 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1878 ssh_pkt_addstring_start(pkt);
1879 ssh_pkt_addstring_str(pkt, data);
1881 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1883 int len = ssh1_bignum_length(b);
1884 unsigned char *data = snewn(len, unsigned char);
1885 (void) ssh1_write_bignum(data, b);
1886 ssh_pkt_adddata(pkt, data, len);
1889 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1892 int i, n = (bignum_bitcount(b) + 7) / 8;
1893 p = snewn(n + 1, unsigned char);
1895 for (i = 1; i <= n; i++)
1896 p[i] = bignum_byte(b, n - i);
1898 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1900 memmove(p, p + i, n + 1 - i);
1904 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1908 p = ssh2_mpint_fmt(b, &len);
1909 ssh_pkt_addstring_start(pkt);
1910 ssh_pkt_addstring_data(pkt, (char *)p, len);
1914 static struct Packet *ssh1_pkt_init(int pkt_type)
1916 struct Packet *pkt = ssh_new_packet();
1917 pkt->length = 4 + 8; /* space for length + max padding */
1918 ssh_pkt_addbyte(pkt, pkt_type);
1919 pkt->body = pkt->data + pkt->length;
1923 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1924 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1925 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1926 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1927 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1928 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1929 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1930 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1931 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1933 static struct Packet *ssh2_pkt_init(int pkt_type)
1935 struct Packet *pkt = ssh_new_packet();
1936 pkt->length = 5; /* space for packet length + padding length */
1938 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1939 pkt->body = pkt->data + pkt->length; /* after packet type */
1944 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1945 * put the MAC on it. Final packet, ready to be sent, is stored in
1946 * pkt->data. Total length is returned.
1948 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1950 int cipherblk, maclen, padding, i;
1953 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1954 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1955 pkt->body, pkt->length - (pkt->body - pkt->data),
1956 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1957 sfree(pkt->blanks); pkt->blanks = NULL;
1961 * Compress packet payload.
1964 unsigned char *newpayload;
1967 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1969 &newpayload, &newlen)) {
1971 ssh2_pkt_adddata(pkt, newpayload, newlen);
1977 * Add padding. At least four bytes, and must also bring total
1978 * length (minus MAC) up to a multiple of the block size.
1979 * If pkt->forcepad is set, make sure the packet is at least that size
1982 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1983 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1985 if (pkt->length + padding < pkt->forcepad)
1986 padding = pkt->forcepad - pkt->length;
1988 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1989 assert(padding <= 255);
1990 maclen = ssh->csmac ? ssh->csmac->len : 0;
1991 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1992 pkt->data[4] = padding;
1993 for (i = 0; i < padding; i++)
1994 pkt->data[pkt->length + i] = random_byte();
1995 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1997 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1998 pkt->length + padding,
1999 ssh->v2_outgoing_sequence);
2000 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2003 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2004 pkt->data, pkt->length + padding);
2006 pkt->encrypted_len = pkt->length + padding;
2008 /* Ready-to-send packet starts at pkt->data. We return length. */
2009 return pkt->length + padding + maclen;
2013 * Routines called from the main SSH code to send packets. There
2014 * are quite a few of these, because we have two separate
2015 * mechanisms for delaying the sending of packets:
2017 * - In order to send an IGNORE message and a password message in
2018 * a single fixed-length blob, we require the ability to
2019 * concatenate the encrypted forms of those two packets _into_ a
2020 * single blob and then pass it to our <network.h> transport
2021 * layer in one go. Hence, there's a deferment mechanism which
2022 * works after packet encryption.
2024 * - In order to avoid sending any connection-layer messages
2025 * during repeat key exchange, we have to queue up any such
2026 * outgoing messages _before_ they are encrypted (and in
2027 * particular before they're allocated sequence numbers), and
2028 * then send them once we've finished.
2030 * I call these mechanisms `defer' and `queue' respectively, so as
2031 * to distinguish them reasonably easily.
2033 * The functions send_noqueue() and defer_noqueue() free the packet
2034 * structure they are passed. Every outgoing packet goes through
2035 * precisely one of these functions in its life; packets passed to
2036 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2037 * these or get queued, and then when the queue is later emptied
2038 * the packets are all passed to defer_noqueue().
2040 * When using a CBC-mode cipher, it's necessary to ensure that an
2041 * attacker can't provide data to be encrypted using an IV that they
2042 * know. We ensure this by prefixing each packet that might contain
2043 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2044 * mechanism, so in this case send_noqueue() ends up redirecting to
2045 * defer_noqueue(). If you don't like this inefficiency, don't use
2049 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2050 static void ssh_pkt_defersend(Ssh);
2053 * Send an SSH-2 packet immediately, without queuing or deferring.
2055 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2059 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2060 /* We need to send two packets, so use the deferral mechanism. */
2061 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2062 ssh_pkt_defersend(ssh);
2065 len = ssh2_pkt_construct(ssh, pkt);
2066 backlog = s_write(ssh, pkt->data, len);
2067 if (backlog > SSH_MAX_BACKLOG)
2068 ssh_throttle_all(ssh, 1, backlog);
2070 ssh->outgoing_data_size += pkt->encrypted_len;
2071 if (!ssh->kex_in_progress &&
2072 ssh->max_data_size != 0 &&
2073 ssh->outgoing_data_size > ssh->max_data_size)
2074 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2076 ssh_free_packet(pkt);
2080 * Defer an SSH-2 packet.
2082 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2085 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2086 ssh->deferred_len == 0 && !noignore &&
2087 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2089 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2090 * get encrypted with a known IV.
2092 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2093 ssh2_pkt_addstring_start(ipkt);
2094 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2096 len = ssh2_pkt_construct(ssh, pkt);
2097 if (ssh->deferred_len + len > ssh->deferred_size) {
2098 ssh->deferred_size = ssh->deferred_len + len + 128;
2099 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2103 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2104 ssh->deferred_len += len;
2105 ssh->deferred_data_size += pkt->encrypted_len;
2106 ssh_free_packet(pkt);
2110 * Queue an SSH-2 packet.
2112 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2114 assert(ssh->queueing);
2116 if (ssh->queuelen >= ssh->queuesize) {
2117 ssh->queuesize = ssh->queuelen + 32;
2118 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2121 ssh->queue[ssh->queuelen++] = pkt;
2125 * Either queue or send a packet, depending on whether queueing is
2128 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2131 ssh2_pkt_queue(ssh, pkt);
2133 ssh2_pkt_send_noqueue(ssh, pkt);
2137 * Either queue or defer a packet, depending on whether queueing is
2140 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2143 ssh2_pkt_queue(ssh, pkt);
2145 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2149 * Send the whole deferred data block constructed by
2150 * ssh2_pkt_defer() or SSH-1's defer_packet().
2152 * The expected use of the defer mechanism is that you call
2153 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2154 * not currently queueing, this simply sets up deferred_send_data
2155 * and then sends it. If we _are_ currently queueing, the calls to
2156 * ssh2_pkt_defer() put the deferred packets on to the queue
2157 * instead, and therefore ssh_pkt_defersend() has no deferred data
2158 * to send. Hence, there's no need to make it conditional on
2161 static void ssh_pkt_defersend(Ssh ssh)
2164 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2165 ssh->deferred_len = ssh->deferred_size = 0;
2166 sfree(ssh->deferred_send_data);
2167 ssh->deferred_send_data = NULL;
2168 if (backlog > SSH_MAX_BACKLOG)
2169 ssh_throttle_all(ssh, 1, backlog);
2171 ssh->outgoing_data_size += ssh->deferred_data_size;
2172 if (!ssh->kex_in_progress &&
2173 ssh->max_data_size != 0 &&
2174 ssh->outgoing_data_size > ssh->max_data_size)
2175 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2176 ssh->deferred_data_size = 0;
2180 * Send a packet whose length needs to be disguised (typically
2181 * passwords or keyboard-interactive responses).
2183 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2189 * The simplest way to do this is to adjust the
2190 * variable-length padding field in the outgoing packet.
2192 * Currently compiled out, because some Cisco SSH servers
2193 * don't like excessively padded packets (bah, why's it
2196 pkt->forcepad = padsize;
2197 ssh2_pkt_send(ssh, pkt);
2202 * If we can't do that, however, an alternative approach is
2203 * to use the pkt_defer mechanism to bundle the packet
2204 * tightly together with an SSH_MSG_IGNORE such that their
2205 * combined length is a constant. So first we construct the
2206 * final form of this packet and defer its sending.
2208 ssh2_pkt_defer(ssh, pkt);
2211 * Now construct an SSH_MSG_IGNORE which includes a string
2212 * that's an exact multiple of the cipher block size. (If
2213 * the cipher is NULL so that the block size is
2214 * unavailable, we don't do this trick at all, because we
2215 * gain nothing by it.)
2217 if (ssh->cscipher &&
2218 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2221 stringlen = (256 - ssh->deferred_len);
2222 stringlen += ssh->cscipher->blksize - 1;
2223 stringlen -= (stringlen % ssh->cscipher->blksize);
2226 * Temporarily disable actual compression, so we
2227 * can guarantee to get this string exactly the
2228 * length we want it. The compression-disabling
2229 * routine should return an integer indicating how
2230 * many bytes we should adjust our string length
2234 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2236 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2237 ssh2_pkt_addstring_start(pkt);
2238 for (i = 0; i < stringlen; i++) {
2239 char c = (char) random_byte();
2240 ssh2_pkt_addstring_data(pkt, &c, 1);
2242 ssh2_pkt_defer(ssh, pkt);
2244 ssh_pkt_defersend(ssh);
2249 * Send all queued SSH-2 packets. We send them by means of
2250 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2251 * packets that needed to be lumped together.
2253 static void ssh2_pkt_queuesend(Ssh ssh)
2257 assert(!ssh->queueing);
2259 for (i = 0; i < ssh->queuelen; i++)
2260 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2263 ssh_pkt_defersend(ssh);
2267 void bndebug(char *string, Bignum b)
2271 p = ssh2_mpint_fmt(b, &len);
2272 debug(("%s", string));
2273 for (i = 0; i < len; i++)
2274 debug((" %02x", p[i]));
2280 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2284 p = ssh2_mpint_fmt(b, &len);
2285 hash_string(h, s, p, len);
2290 * Packet decode functions for both SSH-1 and SSH-2.
2292 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2294 unsigned long value;
2295 if (pkt->length - pkt->savedpos < 4)
2296 return 0; /* arrgh, no way to decline (FIXME?) */
2297 value = GET_32BIT(pkt->body + pkt->savedpos);
2301 static int ssh2_pkt_getbool(struct Packet *pkt)
2303 unsigned long value;
2304 if (pkt->length - pkt->savedpos < 1)
2305 return 0; /* arrgh, no way to decline (FIXME?) */
2306 value = pkt->body[pkt->savedpos] != 0;
2310 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2315 if (pkt->length - pkt->savedpos < 4)
2317 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2322 if (pkt->length - pkt->savedpos < *length)
2324 *p = (char *)(pkt->body + pkt->savedpos);
2325 pkt->savedpos += *length;
2327 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2329 if (pkt->length - pkt->savedpos < length)
2331 pkt->savedpos += length;
2332 return pkt->body + (pkt->savedpos - length);
2334 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2335 unsigned char **keystr)
2339 j = makekey(pkt->body + pkt->savedpos,
2340 pkt->length - pkt->savedpos,
2347 assert(pkt->savedpos < pkt->length);
2351 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2356 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2357 pkt->length - pkt->savedpos, &b);
2365 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2371 ssh_pkt_getstring(pkt, &p, &length);
2376 b = bignum_from_bytes((unsigned char *)p, length);
2381 * Helper function to add an SSH-2 signature blob to a packet.
2382 * Expects to be shown the public key blob as well as the signature
2383 * blob. Normally works just like ssh2_pkt_addstring, but will
2384 * fiddle with the signature packet if necessary for
2385 * BUG_SSH2_RSA_PADDING.
2387 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2388 void *pkblob_v, int pkblob_len,
2389 void *sigblob_v, int sigblob_len)
2391 unsigned char *pkblob = (unsigned char *)pkblob_v;
2392 unsigned char *sigblob = (unsigned char *)sigblob_v;
2394 /* dmemdump(pkblob, pkblob_len); */
2395 /* dmemdump(sigblob, sigblob_len); */
2398 * See if this is in fact an ssh-rsa signature and a buggy
2399 * server; otherwise we can just do this the easy way.
2401 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2402 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2403 int pos, len, siglen;
2406 * Find the byte length of the modulus.
2409 pos = 4+7; /* skip over "ssh-rsa" */
2410 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2411 if (len < 0 || len > pkblob_len - pos - 4)
2413 pos += 4 + len; /* skip over exponent */
2414 if (pkblob_len - pos < 4)
2416 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2417 if (len < 0 || len > pkblob_len - pos - 4)
2419 pos += 4; /* find modulus itself */
2420 while (len > 0 && pkblob[pos] == 0)
2422 /* debug(("modulus length is %d\n", len)); */
2425 * Now find the signature integer.
2427 pos = 4+7; /* skip over "ssh-rsa" */
2428 if (sigblob_len < pos+4)
2430 siglen = toint(GET_32BIT(sigblob+pos));
2431 if (siglen != sigblob_len - pos - 4)
2433 /* debug(("signature length is %d\n", siglen)); */
2435 if (len != siglen) {
2436 unsigned char newlen[4];
2437 ssh2_pkt_addstring_start(pkt);
2438 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2439 /* dmemdump(sigblob, pos); */
2440 pos += 4; /* point to start of actual sig */
2441 PUT_32BIT(newlen, len);
2442 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2443 /* dmemdump(newlen, 4); */
2445 while (len-- > siglen) {
2446 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2447 /* dmemdump(newlen, 1); */
2449 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2450 /* dmemdump(sigblob+pos, siglen); */
2454 /* Otherwise fall through and do it the easy way. We also come
2455 * here as a fallback if we discover above that the key blob
2456 * is misformatted in some way. */
2460 ssh2_pkt_addstring_start(pkt);
2461 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2465 * Examine the remote side's version string and compare it against
2466 * a list of known buggy implementations.
2468 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2470 char *imp; /* pointer to implementation part */
2472 imp += strcspn(imp, "-");
2474 imp += strcspn(imp, "-");
2477 ssh->remote_bugs = 0;
2480 * General notes on server version strings:
2481 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2482 * here -- in particular, we've heard of one that's perfectly happy
2483 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2484 * so we can't distinguish them.
2486 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2487 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2488 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2489 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2490 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2491 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2493 * These versions don't support SSH1_MSG_IGNORE, so we have
2494 * to use a different defence against password length
2497 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2498 logevent("We believe remote version has SSH-1 ignore bug");
2501 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2502 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2503 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2505 * These versions need a plain password sent; they can't
2506 * handle having a null and a random length of data after
2509 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2510 logevent("We believe remote version needs a plain SSH-1 password");
2513 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2514 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2515 (!strcmp(imp, "Cisco-1.25")))) {
2517 * These versions apparently have no clue whatever about
2518 * RSA authentication and will panic and die if they see
2519 * an AUTH_RSA message.
2521 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2522 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2525 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2526 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2527 !wc_match("* VShell", imp) &&
2528 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2529 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2530 wc_match("2.1 *", imp)))) {
2532 * These versions have the HMAC bug.
2534 ssh->remote_bugs |= BUG_SSH2_HMAC;
2535 logevent("We believe remote version has SSH-2 HMAC bug");
2538 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2539 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2540 !wc_match("* VShell", imp) &&
2541 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2543 * These versions have the key-derivation bug (failing to
2544 * include the literal shared secret in the hashes that
2545 * generate the keys).
2547 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2548 logevent("We believe remote version has SSH-2 key-derivation bug");
2551 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2552 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2553 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2554 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2556 * These versions have the SSH-2 RSA padding bug.
2558 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2559 logevent("We believe remote version has SSH-2 RSA padding bug");
2562 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2563 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2564 wc_match("OpenSSH_2.[0-2]*", imp))) {
2566 * These versions have the SSH-2 session-ID bug in
2567 * public-key authentication.
2569 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2570 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2573 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2574 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2575 (wc_match("DigiSSH_2.0", imp) ||
2576 wc_match("OpenSSH_2.[0-4]*", imp) ||
2577 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2578 wc_match("Sun_SSH_1.0", imp) ||
2579 wc_match("Sun_SSH_1.0.1", imp) ||
2580 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2581 wc_match("WeOnlyDo-*", imp)))) {
2583 * These versions have the SSH-2 rekey bug.
2585 ssh->remote_bugs |= BUG_SSH2_REKEY;
2586 logevent("We believe remote version has SSH-2 rekey bug");
2589 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2590 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2591 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2592 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2594 * This version ignores our makpkt and needs to be throttled.
2596 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2597 logevent("We believe remote version ignores SSH-2 maximum packet size");
2600 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2602 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2603 * none detected automatically.
2605 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2606 logevent("We believe remote version has SSH-2 ignore bug");
2609 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2611 * Servers that don't support our winadj request for one
2612 * reason or another. Currently, none detected automatically.
2614 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2615 logevent("We believe remote version has winadj bug");
2620 * The `software version' part of an SSH version string is required
2621 * to contain no spaces or minus signs.
2623 static void ssh_fix_verstring(char *str)
2625 /* Eat "SSH-<protoversion>-". */
2626 assert(*str == 'S'); str++;
2627 assert(*str == 'S'); str++;
2628 assert(*str == 'H'); str++;
2629 assert(*str == '-'); str++;
2630 while (*str && *str != '-') str++;
2631 assert(*str == '-'); str++;
2633 /* Convert minus signs and spaces in the remaining string into
2636 if (*str == '-' || *str == ' ')
2643 * Send an appropriate SSH version string.
2645 static void ssh_send_verstring(Ssh ssh, char *svers)
2649 if (ssh->version == 2) {
2651 * Construct a v2 version string.
2653 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2656 * Construct a v1 version string.
2658 verstring = dupprintf("SSH-%s-%s\012",
2659 (ssh_versioncmp(svers, "1.5") <= 0 ?
2664 ssh_fix_verstring(verstring);
2666 if (ssh->version == 2) {
2669 * Record our version string.
2671 len = strcspn(verstring, "\015\012");
2672 ssh->v_c = snewn(len + 1, char);
2673 memcpy(ssh->v_c, verstring, len);
2677 logeventf(ssh, "We claim version: %.*s",
2678 strcspn(verstring, "\015\012"), verstring);
2679 s_write(ssh, verstring, strlen(verstring));
2683 static int do_ssh_init(Ssh ssh, unsigned char c)
2685 struct do_ssh_init_state {
2694 crState(do_ssh_init_state);
2698 /* Search for a line beginning with the string "SSH-" in the input. */
2700 if (c != 'S') goto no;
2702 if (c != 'S') goto no;
2704 if (c != 'H') goto no;
2706 if (c != '-') goto no;
2715 s->vstring = snewn(s->vstrsize, char);
2716 strcpy(s->vstring, "SSH-");
2720 crReturn(1); /* get another char */
2721 if (s->vslen >= s->vstrsize - 1) {
2723 s->vstring = sresize(s->vstring, s->vstrsize, char);
2725 s->vstring[s->vslen++] = c;
2728 s->version[s->i] = '\0';
2730 } else if (s->i < sizeof(s->version) - 1)
2731 s->version[s->i++] = c;
2732 } else if (c == '\012')
2736 ssh->agentfwd_enabled = FALSE;
2737 ssh->rdpkt2_state.incoming_sequence = 0;
2739 s->vstring[s->vslen] = 0;
2740 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2741 logeventf(ssh, "Server version: %s", s->vstring);
2742 ssh_detect_bugs(ssh, s->vstring);
2745 * Decide which SSH protocol version to support.
2748 /* Anything strictly below "2.0" means protocol 1 is supported. */
2749 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2750 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2751 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2753 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2754 bombout(("SSH protocol version 1 required by user but not provided by server"));
2757 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2758 bombout(("SSH protocol version 2 required by user but not provided by server"));
2762 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2767 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2769 /* Send the version string, if we haven't already */
2770 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2771 ssh_send_verstring(ssh, s->version);
2773 if (ssh->version == 2) {
2776 * Record their version string.
2778 len = strcspn(s->vstring, "\015\012");
2779 ssh->v_s = snewn(len + 1, char);
2780 memcpy(ssh->v_s, s->vstring, len);
2784 * Initialise SSH-2 protocol.
2786 ssh->protocol = ssh2_protocol;
2787 ssh2_protocol_setup(ssh);
2788 ssh->s_rdpkt = ssh2_rdpkt;
2791 * Initialise SSH-1 protocol.
2793 ssh->protocol = ssh1_protocol;
2794 ssh1_protocol_setup(ssh);
2795 ssh->s_rdpkt = ssh1_rdpkt;
2797 if (ssh->version == 2)
2798 do_ssh2_transport(ssh, NULL, -1, NULL);
2800 update_specials_menu(ssh->frontend);
2801 ssh->state = SSH_STATE_BEFORE_SIZE;
2802 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2809 static void ssh_process_incoming_data(Ssh ssh,
2810 unsigned char **data, int *datalen)
2812 struct Packet *pktin;
2814 pktin = ssh->s_rdpkt(ssh, data, datalen);
2816 ssh->protocol(ssh, NULL, 0, pktin);
2817 ssh_free_packet(pktin);
2821 static void ssh_queue_incoming_data(Ssh ssh,
2822 unsigned char **data, int *datalen)
2824 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2829 static void ssh_process_queued_incoming_data(Ssh ssh)
2832 unsigned char *data;
2835 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2836 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2840 while (!ssh->frozen && len > 0)
2841 ssh_process_incoming_data(ssh, &data, &len);
2844 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2848 static void ssh_set_frozen(Ssh ssh, int frozen)
2851 sk_set_frozen(ssh->s, frozen);
2852 ssh->frozen = frozen;
2855 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2857 /* Log raw data, if we're in that mode. */
2859 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2862 crBegin(ssh->ssh_gotdata_crstate);
2865 * To begin with, feed the characters one by one to the
2866 * protocol initialisation / selection function do_ssh_init().
2867 * When that returns 0, we're done with the initial greeting
2868 * exchange and can move on to packet discipline.
2871 int ret; /* need not be kept across crReturn */
2873 crReturnV; /* more data please */
2874 ret = do_ssh_init(ssh, *data);
2882 * We emerge from that loop when the initial negotiation is
2883 * over and we have selected an s_rdpkt function. Now pass
2884 * everything to s_rdpkt, and then pass the resulting packets
2885 * to the proper protocol handler.
2889 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2891 ssh_queue_incoming_data(ssh, &data, &datalen);
2892 /* This uses up all data and cannot cause anything interesting
2893 * to happen; indeed, for anything to happen at all, we must
2894 * return, so break out. */
2896 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2897 /* This uses up some or all data, and may freeze the
2899 ssh_process_queued_incoming_data(ssh);
2901 /* This uses up some or all data, and may freeze the
2903 ssh_process_incoming_data(ssh, &data, &datalen);
2905 /* FIXME this is probably EBW. */
2906 if (ssh->state == SSH_STATE_CLOSED)
2909 /* We're out of data. Go and get some more. */
2915 static int ssh_do_close(Ssh ssh, int notify_exit)
2918 struct ssh_channel *c;
2920 ssh->state = SSH_STATE_CLOSED;
2921 expire_timer_context(ssh);
2926 notify_remote_exit(ssh->frontend);
2931 * Now we must shut down any port- and X-forwarded channels going
2932 * through this connection.
2934 if (ssh->channels) {
2935 while (NULL != (c = index234(ssh->channels, 0))) {
2938 x11_close(c->u.x11.s);
2941 case CHAN_SOCKDATA_DORMANT:
2942 pfd_close(c->u.pfd.s);
2945 del234(ssh->channels, c); /* moving next one to index 0 */
2946 if (ssh->version == 2)
2947 bufchain_clear(&c->v.v2.outbuffer);
2952 * Go through port-forwardings, and close any associated
2953 * listening sockets.
2955 if (ssh->portfwds) {
2956 struct ssh_portfwd *pf;
2957 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2958 /* Dispose of any listening socket. */
2960 pfd_terminate(pf->local);
2961 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2964 freetree234(ssh->portfwds);
2965 ssh->portfwds = NULL;
2971 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2972 const char *error_msg, int error_code)
2974 Ssh ssh = (Ssh) plug;
2975 char addrbuf[256], *msg;
2977 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2980 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2982 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2988 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2991 Ssh ssh = (Ssh) plug;
2992 int need_notify = ssh_do_close(ssh, FALSE);
2995 if (!ssh->close_expected)
2996 error_msg = "Server unexpectedly closed network connection";
2998 error_msg = "Server closed network connection";
3001 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3005 notify_remote_exit(ssh->frontend);
3008 logevent(error_msg);
3009 if (!ssh->close_expected || !ssh->clean_exit)
3010 connection_fatal(ssh->frontend, "%s", error_msg);
3014 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3016 Ssh ssh = (Ssh) plug;
3017 ssh_gotdata(ssh, (unsigned char *)data, len);
3018 if (ssh->state == SSH_STATE_CLOSED) {
3019 ssh_do_close(ssh, TRUE);
3025 static void ssh_sent(Plug plug, int bufsize)
3027 Ssh ssh = (Ssh) plug;
3029 * If the send backlog on the SSH socket itself clears, we
3030 * should unthrottle the whole world if it was throttled.
3032 if (bufsize < SSH_MAX_BACKLOG)
3033 ssh_throttle_all(ssh, 0, bufsize);
3037 * Connect to specified host and port.
3038 * Returns an error message, or NULL on success.
3039 * Also places the canonical host name into `realhost'. It must be
3040 * freed by the caller.
3042 static const char *connect_to_host(Ssh ssh, char *host, int port,
3043 char **realhost, int nodelay, int keepalive)
3045 static const struct plug_function_table fn_table = {
3056 int addressfamily, sshprot;
3058 loghost = conf_get_str(ssh->conf, CONF_loghost);
3062 ssh->savedhost = dupstr(loghost);
3063 ssh->savedport = 22; /* default ssh port */
3066 * A colon suffix on savedhost also lets us affect
3069 * (FIXME: do something about IPv6 address literals here.)
3071 colon = strrchr(ssh->savedhost, ':');
3075 ssh->savedport = atoi(colon);
3078 ssh->savedhost = dupstr(host);
3080 port = 22; /* default ssh port */
3081 ssh->savedport = port;
3087 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3088 logeventf(ssh, "Looking up host \"%s\"%s", host,
3089 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3090 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3091 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3092 if ((err = sk_addr_error(addr)) != NULL) {
3096 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3101 ssh->fn = &fn_table;
3102 ssh->s = new_connection(addr, *realhost, port,
3103 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3104 if ((err = sk_socket_error(ssh->s)) != NULL) {
3106 notify_remote_exit(ssh->frontend);
3111 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3112 * send the version string too.
3114 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3119 ssh_send_verstring(ssh, NULL);
3123 * loghost, if configured, overrides realhost.
3127 *realhost = dupstr(loghost);
3134 * Throttle or unthrottle the SSH connection.
3136 static void ssh_throttle_conn(Ssh ssh, int adjust)
3138 int old_count = ssh->conn_throttle_count;
3139 ssh->conn_throttle_count += adjust;
3140 assert(ssh->conn_throttle_count >= 0);
3141 if (ssh->conn_throttle_count && !old_count) {
3142 ssh_set_frozen(ssh, 1);
3143 } else if (!ssh->conn_throttle_count && old_count) {
3144 ssh_set_frozen(ssh, 0);
3149 * Throttle or unthrottle _all_ local data streams (for when sends
3150 * on the SSH connection itself back up).
3152 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3155 struct ssh_channel *c;
3157 if (enable == ssh->throttled_all)
3159 ssh->throttled_all = enable;
3160 ssh->overall_bufsize = bufsize;
3163 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3165 case CHAN_MAINSESSION:
3167 * This is treated separately, outside the switch.
3171 x11_override_throttle(c->u.x11.s, enable);
3174 /* Agent channels require no buffer management. */
3177 pfd_override_throttle(c->u.pfd.s, enable);
3183 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3185 Ssh ssh = (Ssh) sshv;
3187 ssh->agent_response = reply;
3188 ssh->agent_response_len = replylen;
3190 if (ssh->version == 1)
3191 do_ssh1_login(ssh, NULL, -1, NULL);
3193 do_ssh2_authconn(ssh, NULL, -1, NULL);
3196 static void ssh_dialog_callback(void *sshv, int ret)
3198 Ssh ssh = (Ssh) sshv;
3200 ssh->user_response = ret;
3202 if (ssh->version == 1)
3203 do_ssh1_login(ssh, NULL, -1, NULL);
3205 do_ssh2_transport(ssh, NULL, -1, NULL);
3208 * This may have unfrozen the SSH connection, so do a
3211 ssh_process_queued_incoming_data(ssh);
3214 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3216 struct ssh_channel *c = (struct ssh_channel *)cv;
3218 void *sentreply = reply;
3220 c->u.a.outstanding_requests--;
3222 /* Fake SSH_AGENT_FAILURE. */
3223 sentreply = "\0\0\0\1\5";
3226 if (ssh->version == 2) {
3227 ssh2_add_channel_data(c, sentreply, replylen);
3230 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3231 PKT_INT, c->remoteid,
3234 PKT_DATA, sentreply, replylen,
3241 * If we've already seen an incoming EOF but haven't sent an
3242 * outgoing one, this may be the moment to send it.
3244 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3245 sshfwd_write_eof(c);
3249 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3250 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3251 * => log `wire_reason'.
3253 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3254 int code, int clean_exit)
3258 client_reason = wire_reason;
3260 error = dupprintf("Disconnected: %s", client_reason);
3262 error = dupstr("Disconnected");
3264 if (ssh->version == 1) {
3265 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3267 } else if (ssh->version == 2) {
3268 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3269 ssh2_pkt_adduint32(pktout, code);
3270 ssh2_pkt_addstring(pktout, wire_reason);
3271 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3272 ssh2_pkt_send_noqueue(ssh, pktout);
3275 ssh->close_expected = TRUE;
3276 ssh->clean_exit = clean_exit;
3277 ssh_closing((Plug)ssh, error, 0, 0);
3282 * Handle the key exchange and user authentication phases.
3284 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3285 struct Packet *pktin)
3288 unsigned char cookie[8], *ptr;
3289 struct MD5Context md5c;
3290 struct do_ssh1_login_state {
3293 unsigned char *rsabuf, *keystr1, *keystr2;
3294 unsigned long supported_ciphers_mask, supported_auths_mask;
3295 int tried_publickey, tried_agent;
3296 int tis_auth_refused, ccard_auth_refused;
3297 unsigned char session_id[16];
3299 void *publickey_blob;
3300 int publickey_bloblen;
3301 char *publickey_comment;
3302 int publickey_encrypted;
3303 prompts_t *cur_prompt;
3306 unsigned char request[5], *response, *p;
3316 struct RSAKey servkey, hostkey;
3318 crState(do_ssh1_login_state);
3325 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3326 bombout(("Public key packet not received"));
3330 logevent("Received public keys");
3332 ptr = ssh_pkt_getdata(pktin, 8);
3334 bombout(("SSH-1 public key packet stopped before random cookie"));
3337 memcpy(cookie, ptr, 8);
3339 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3340 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3341 bombout(("Failed to read SSH-1 public keys from public key packet"));
3346 * Log the host key fingerprint.
3350 logevent("Host key fingerprint is:");
3351 strcpy(logmsg, " ");
3352 s->hostkey.comment = NULL;
3353 rsa_fingerprint(logmsg + strlen(logmsg),
3354 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3358 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3359 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3360 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3361 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3362 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3364 ssh->v1_local_protoflags =
3365 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3366 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3369 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3370 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3371 MD5Update(&md5c, cookie, 8);
3372 MD5Final(s->session_id, &md5c);
3374 for (i = 0; i < 32; i++)
3375 ssh->session_key[i] = random_byte();
3378 * Verify that the `bits' and `bytes' parameters match.
3380 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3381 s->servkey.bits > s->servkey.bytes * 8) {
3382 bombout(("SSH-1 public keys were badly formatted"));
3386 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3387 s->hostkey.bytes : s->servkey.bytes);
3389 s->rsabuf = snewn(s->len, unsigned char);
3392 * Verify the host key.
3396 * First format the key into a string.
3398 int len = rsastr_len(&s->hostkey);
3399 char fingerprint[100];
3400 char *keystr = snewn(len, char);
3401 rsastr_fmt(keystr, &s->hostkey);
3402 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3404 ssh_set_frozen(ssh, 1);
3405 s->dlgret = verify_ssh_host_key(ssh->frontend,
3406 ssh->savedhost, ssh->savedport,
3407 "rsa", keystr, fingerprint,
3408 ssh_dialog_callback, ssh);
3410 if (s->dlgret < 0) {
3414 bombout(("Unexpected data from server while waiting"
3415 " for user host key response"));
3418 } while (pktin || inlen > 0);
3419 s->dlgret = ssh->user_response;
3421 ssh_set_frozen(ssh, 0);
3423 if (s->dlgret == 0) {
3424 ssh_disconnect(ssh, "User aborted at host key verification",
3430 for (i = 0; i < 32; i++) {
3431 s->rsabuf[i] = ssh->session_key[i];
3433 s->rsabuf[i] ^= s->session_id[i];
3436 if (s->hostkey.bytes > s->servkey.bytes) {
3437 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3439 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3441 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3443 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3446 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3450 logevent("Encrypted session key");
3453 int cipher_chosen = 0, warn = 0;
3454 char *cipher_string = NULL;
3456 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3457 int next_cipher = conf_get_int_int(ssh->conf,
3458 CONF_ssh_cipherlist, i);
3459 if (next_cipher == CIPHER_WARN) {
3460 /* If/when we choose a cipher, warn about it */
3462 } else if (next_cipher == CIPHER_AES) {
3463 /* XXX Probably don't need to mention this. */
3464 logevent("AES not supported in SSH-1, skipping");
3466 switch (next_cipher) {
3467 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3468 cipher_string = "3DES"; break;
3469 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3470 cipher_string = "Blowfish"; break;
3471 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3472 cipher_string = "single-DES"; break;
3474 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3478 if (!cipher_chosen) {
3479 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3480 bombout(("Server violates SSH-1 protocol by not "
3481 "supporting 3DES encryption"));
3483 /* shouldn't happen */
3484 bombout(("No supported ciphers found"));
3488 /* Warn about chosen cipher if necessary. */
3490 ssh_set_frozen(ssh, 1);
3491 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3492 ssh_dialog_callback, ssh);
3493 if (s->dlgret < 0) {
3497 bombout(("Unexpected data from server while waiting"
3498 " for user response"));
3501 } while (pktin || inlen > 0);
3502 s->dlgret = ssh->user_response;
3504 ssh_set_frozen(ssh, 0);
3505 if (s->dlgret == 0) {
3506 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3513 switch (s->cipher_type) {
3514 case SSH_CIPHER_3DES:
3515 logevent("Using 3DES encryption");
3517 case SSH_CIPHER_DES:
3518 logevent("Using single-DES encryption");
3520 case SSH_CIPHER_BLOWFISH:
3521 logevent("Using Blowfish encryption");
3525 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3526 PKT_CHAR, s->cipher_type,
3527 PKT_DATA, cookie, 8,
3528 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3529 PKT_DATA, s->rsabuf, s->len,
3530 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3532 logevent("Trying to enable encryption...");
3536 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3537 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3539 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3540 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3541 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3543 ssh->crcda_ctx = crcda_make_context();
3544 logevent("Installing CRC compensation attack detector");
3546 if (s->servkey.modulus) {
3547 sfree(s->servkey.modulus);
3548 s->servkey.modulus = NULL;
3550 if (s->servkey.exponent) {
3551 sfree(s->servkey.exponent);
3552 s->servkey.exponent = NULL;
3554 if (s->hostkey.modulus) {
3555 sfree(s->hostkey.modulus);
3556 s->hostkey.modulus = NULL;
3558 if (s->hostkey.exponent) {
3559 sfree(s->hostkey.exponent);
3560 s->hostkey.exponent = NULL;
3564 if (pktin->type != SSH1_SMSG_SUCCESS) {
3565 bombout(("Encryption not successfully enabled"));
3569 logevent("Successfully started encryption");
3571 fflush(stdout); /* FIXME eh? */
3573 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3574 int ret; /* need not be kept over crReturn */
3575 s->cur_prompt = new_prompts(ssh->frontend);
3576 s->cur_prompt->to_server = TRUE;
3577 s->cur_prompt->name = dupstr("SSH login name");
3578 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3579 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3582 crWaitUntil(!pktin);
3583 ret = get_userpass_input(s->cur_prompt, in, inlen);
3588 * Failed to get a username. Terminate.
3590 free_prompts(s->cur_prompt);
3591 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3594 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3595 free_prompts(s->cur_prompt);
3598 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3600 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3602 if (flags & FLAG_INTERACTIVE &&
3603 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3604 c_write_str(ssh, userlog);
3605 c_write_str(ssh, "\r\n");
3613 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3614 /* We must not attempt PK auth. Pretend we've already tried it. */
3615 s->tried_publickey = s->tried_agent = 1;
3617 s->tried_publickey = s->tried_agent = 0;
3619 s->tis_auth_refused = s->ccard_auth_refused = 0;
3621 * Load the public half of any configured keyfile for later use.
3623 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3624 if (!filename_is_null(s->keyfile)) {
3626 logeventf(ssh, "Reading private key file \"%.150s\"",
3627 filename_to_str(s->keyfile));
3628 keytype = key_type(s->keyfile);
3629 if (keytype == SSH_KEYTYPE_SSH1) {
3631 if (rsakey_pubblob(s->keyfile,
3632 &s->publickey_blob, &s->publickey_bloblen,
3633 &s->publickey_comment, &error)) {
3634 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3638 logeventf(ssh, "Unable to load private key (%s)", error);
3639 msgbuf = dupprintf("Unable to load private key file "
3640 "\"%.150s\" (%s)\r\n",
3641 filename_to_str(s->keyfile),
3643 c_write_str(ssh, msgbuf);
3645 s->publickey_blob = NULL;
3649 logeventf(ssh, "Unable to use this key file (%s)",
3650 key_type_to_str(keytype));
3651 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3653 filename_to_str(s->keyfile),
3654 key_type_to_str(keytype));
3655 c_write_str(ssh, msgbuf);
3657 s->publickey_blob = NULL;
3660 s->publickey_blob = NULL;
3662 while (pktin->type == SSH1_SMSG_FAILURE) {
3663 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3665 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3667 * Attempt RSA authentication using Pageant.
3673 logevent("Pageant is running. Requesting keys.");
3675 /* Request the keys held by the agent. */
3676 PUT_32BIT(s->request, 1);
3677 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3678 if (!agent_query(s->request, 5, &r, &s->responselen,
3679 ssh_agent_callback, ssh)) {
3683 bombout(("Unexpected data from server while waiting"
3684 " for agent response"));
3687 } while (pktin || inlen > 0);
3688 r = ssh->agent_response;
3689 s->responselen = ssh->agent_response_len;
3691 s->response = (unsigned char *) r;
3692 if (s->response && s->responselen >= 5 &&
3693 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3694 s->p = s->response + 5;
3695 s->nkeys = toint(GET_32BIT(s->p));
3697 logeventf(ssh, "Pageant reported negative key count %d",
3702 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3703 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3704 unsigned char *pkblob = s->p;
3708 do { /* do while (0) to make breaking easy */
3709 n = ssh1_read_bignum
3710 (s->p, toint(s->responselen-(s->p-s->response)),
3715 n = ssh1_read_bignum
3716 (s->p, toint(s->responselen-(s->p-s->response)),
3721 if (s->responselen - (s->p-s->response) < 4)
3723 s->commentlen = toint(GET_32BIT(s->p));
3725 if (s->commentlen < 0 ||
3726 toint(s->responselen - (s->p-s->response)) <
3729 s->commentp = (char *)s->p;
3730 s->p += s->commentlen;
3734 logevent("Pageant key list packet was truncated");
3738 if (s->publickey_blob) {
3739 if (!memcmp(pkblob, s->publickey_blob,
3740 s->publickey_bloblen)) {
3741 logeventf(ssh, "Pageant key #%d matches "
3742 "configured key file", s->keyi);
3743 s->tried_publickey = 1;
3745 /* Skip non-configured key */
3748 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3749 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3750 PKT_BIGNUM, s->key.modulus, PKT_END);
3752 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3753 logevent("Key refused");
3756 logevent("Received RSA challenge");
3757 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3758 bombout(("Server's RSA challenge was badly formatted"));
3763 char *agentreq, *q, *ret;
3766 len = 1 + 4; /* message type, bit count */
3767 len += ssh1_bignum_length(s->key.exponent);
3768 len += ssh1_bignum_length(s->key.modulus);
3769 len += ssh1_bignum_length(s->challenge);
3770 len += 16; /* session id */
3771 len += 4; /* response format */
3772 agentreq = snewn(4 + len, char);
3773 PUT_32BIT(agentreq, len);
3775 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3776 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3778 q += ssh1_write_bignum(q, s->key.exponent);
3779 q += ssh1_write_bignum(q, s->key.modulus);
3780 q += ssh1_write_bignum(q, s->challenge);
3781 memcpy(q, s->session_id, 16);
3783 PUT_32BIT(q, 1); /* response format */
3784 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3785 ssh_agent_callback, ssh)) {
3790 bombout(("Unexpected data from server"
3791 " while waiting for agent"
3795 } while (pktin || inlen > 0);
3796 vret = ssh->agent_response;
3797 retlen = ssh->agent_response_len;
3802 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3803 logevent("Sending Pageant's response");
3804 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3805 PKT_DATA, ret + 5, 16,
3809 if (pktin->type == SSH1_SMSG_SUCCESS) {
3811 ("Pageant's response accepted");
3812 if (flags & FLAG_VERBOSE) {
3813 c_write_str(ssh, "Authenticated using"
3815 c_write(ssh, s->commentp,
3817 c_write_str(ssh, "\" from agent\r\n");
3822 ("Pageant's response not accepted");
3825 ("Pageant failed to answer challenge");
3829 logevent("No reply received from Pageant");
3832 freebn(s->key.exponent);
3833 freebn(s->key.modulus);
3834 freebn(s->challenge);
3839 if (s->publickey_blob && !s->tried_publickey)
3840 logevent("Configured key file not in Pageant");
3842 logevent("Failed to get reply from Pageant");
3847 if (s->publickey_blob && !s->tried_publickey) {
3849 * Try public key authentication with the specified
3852 int got_passphrase; /* need not be kept over crReturn */
3853 if (flags & FLAG_VERBOSE)
3854 c_write_str(ssh, "Trying public key authentication.\r\n");
3855 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3856 logeventf(ssh, "Trying public key \"%s\"",
3857 filename_to_str(s->keyfile));
3858 s->tried_publickey = 1;
3859 got_passphrase = FALSE;
3860 while (!got_passphrase) {
3862 * Get a passphrase, if necessary.
3864 char *passphrase = NULL; /* only written after crReturn */
3866 if (!s->publickey_encrypted) {
3867 if (flags & FLAG_VERBOSE)
3868 c_write_str(ssh, "No passphrase required.\r\n");
3871 int ret; /* need not be kept over crReturn */
3872 s->cur_prompt = new_prompts(ssh->frontend);
3873 s->cur_prompt->to_server = FALSE;
3874 s->cur_prompt->name = dupstr("SSH key passphrase");
3875 add_prompt(s->cur_prompt,
3876 dupprintf("Passphrase for key \"%.100s\": ",
3877 s->publickey_comment), FALSE);
3878 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3881 crWaitUntil(!pktin);
3882 ret = get_userpass_input(s->cur_prompt, in, inlen);
3886 /* Failed to get a passphrase. Terminate. */
3887 free_prompts(s->cur_prompt);
3888 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3892 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3893 free_prompts(s->cur_prompt);
3896 * Try decrypting key with passphrase.
3898 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3899 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3902 smemclr(passphrase, strlen(passphrase));
3906 /* Correct passphrase. */
3907 got_passphrase = TRUE;
3908 } else if (ret == 0) {
3909 c_write_str(ssh, "Couldn't load private key from ");
3910 c_write_str(ssh, filename_to_str(s->keyfile));
3911 c_write_str(ssh, " (");
3912 c_write_str(ssh, error);
3913 c_write_str(ssh, ").\r\n");
3914 got_passphrase = FALSE;
3915 break; /* go and try something else */
3916 } else if (ret == -1) {
3917 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3918 got_passphrase = FALSE;
3921 assert(0 && "unexpected return from loadrsakey()");
3922 got_passphrase = FALSE; /* placate optimisers */
3926 if (got_passphrase) {
3929 * Send a public key attempt.
3931 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3932 PKT_BIGNUM, s->key.modulus, PKT_END);
3935 if (pktin->type == SSH1_SMSG_FAILURE) {
3936 c_write_str(ssh, "Server refused our public key.\r\n");
3937 continue; /* go and try something else */
3939 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3940 bombout(("Bizarre response to offer of public key"));
3946 unsigned char buffer[32];
3947 Bignum challenge, response;
3949 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3950 bombout(("Server's RSA challenge was badly formatted"));
3953 response = rsadecrypt(challenge, &s->key);
3954 freebn(s->key.private_exponent);/* burn the evidence */
3956 for (i = 0; i < 32; i++) {
3957 buffer[i] = bignum_byte(response, 31 - i);
3961 MD5Update(&md5c, buffer, 32);
3962 MD5Update(&md5c, s->session_id, 16);
3963 MD5Final(buffer, &md5c);
3965 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3966 PKT_DATA, buffer, 16, PKT_END);
3973 if (pktin->type == SSH1_SMSG_FAILURE) {
3974 if (flags & FLAG_VERBOSE)
3975 c_write_str(ssh, "Failed to authenticate with"
3976 " our public key.\r\n");
3977 continue; /* go and try something else */
3978 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3979 bombout(("Bizarre response to RSA authentication response"));
3983 break; /* we're through! */
3989 * Otherwise, try various forms of password-like authentication.
3991 s->cur_prompt = new_prompts(ssh->frontend);
3993 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3994 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3995 !s->tis_auth_refused) {
3996 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3997 logevent("Requested TIS authentication");
3998 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4000 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4001 logevent("TIS authentication declined");
4002 if (flags & FLAG_INTERACTIVE)
4003 c_write_str(ssh, "TIS authentication refused.\r\n");
4004 s->tis_auth_refused = 1;
4009 char *instr_suf, *prompt;
4011 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4013 bombout(("TIS challenge packet was badly formed"));
4016 logevent("Received TIS challenge");
4017 s->cur_prompt->to_server = TRUE;
4018 s->cur_prompt->name = dupstr("SSH TIS authentication");
4019 /* Prompt heuristic comes from OpenSSH */
4020 if (memchr(challenge, '\n', challengelen)) {
4021 instr_suf = dupstr("");
4022 prompt = dupprintf("%.*s", challengelen, challenge);
4024 instr_suf = dupprintf("%.*s", challengelen, challenge);
4025 prompt = dupstr("Response: ");
4027 s->cur_prompt->instruction =
4028 dupprintf("Using TIS authentication.%s%s",
4029 (*instr_suf) ? "\n" : "",
4031 s->cur_prompt->instr_reqd = TRUE;
4032 add_prompt(s->cur_prompt, prompt, FALSE);
4036 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4037 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4038 !s->ccard_auth_refused) {
4039 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4040 logevent("Requested CryptoCard authentication");
4041 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4043 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4044 logevent("CryptoCard authentication declined");
4045 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4046 s->ccard_auth_refused = 1;
4051 char *instr_suf, *prompt;
4053 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4055 bombout(("CryptoCard challenge packet was badly formed"));
4058 logevent("Received CryptoCard challenge");
4059 s->cur_prompt->to_server = TRUE;
4060 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4061 s->cur_prompt->name_reqd = FALSE;
4062 /* Prompt heuristic comes from OpenSSH */
4063 if (memchr(challenge, '\n', challengelen)) {
4064 instr_suf = dupstr("");
4065 prompt = dupprintf("%.*s", challengelen, challenge);
4067 instr_suf = dupprintf("%.*s", challengelen, challenge);
4068 prompt = dupstr("Response: ");
4070 s->cur_prompt->instruction =
4071 dupprintf("Using CryptoCard authentication.%s%s",
4072 (*instr_suf) ? "\n" : "",
4074 s->cur_prompt->instr_reqd = TRUE;
4075 add_prompt(s->cur_prompt, prompt, FALSE);
4079 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4080 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4081 bombout(("No supported authentication methods available"));
4084 s->cur_prompt->to_server = TRUE;
4085 s->cur_prompt->name = dupstr("SSH password");
4086 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4087 ssh->username, ssh->savedhost),
4092 * Show password prompt, having first obtained it via a TIS
4093 * or CryptoCard exchange if we're doing TIS or CryptoCard
4097 int ret; /* need not be kept over crReturn */
4098 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4101 crWaitUntil(!pktin);
4102 ret = get_userpass_input(s->cur_prompt, in, inlen);
4107 * Failed to get a password (for example
4108 * because one was supplied on the command line
4109 * which has already failed to work). Terminate.
4111 free_prompts(s->cur_prompt);
4112 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4117 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4119 * Defence against traffic analysis: we send a
4120 * whole bunch of packets containing strings of
4121 * different lengths. One of these strings is the
4122 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4123 * The others are all random data in
4124 * SSH1_MSG_IGNORE packets. This way a passive
4125 * listener can't tell which is the password, and
4126 * hence can't deduce the password length.
4128 * Anybody with a password length greater than 16
4129 * bytes is going to have enough entropy in their
4130 * password that a listener won't find it _that_
4131 * much help to know how long it is. So what we'll
4134 * - if password length < 16, we send 15 packets
4135 * containing string lengths 1 through 15
4137 * - otherwise, we let N be the nearest multiple
4138 * of 8 below the password length, and send 8
4139 * packets containing string lengths N through
4140 * N+7. This won't obscure the order of
4141 * magnitude of the password length, but it will
4142 * introduce a bit of extra uncertainty.
4144 * A few servers can't deal with SSH1_MSG_IGNORE, at
4145 * least in this context. For these servers, we need
4146 * an alternative defence. We make use of the fact
4147 * that the password is interpreted as a C string:
4148 * so we can append a NUL, then some random data.
4150 * A few servers can deal with neither SSH1_MSG_IGNORE
4151 * here _nor_ a padded password string.
4152 * For these servers we are left with no defences
4153 * against password length sniffing.
4155 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4156 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4158 * The server can deal with SSH1_MSG_IGNORE, so
4159 * we can use the primary defence.
4161 int bottom, top, pwlen, i;
4164 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4166 bottom = 0; /* zero length passwords are OK! :-) */
4169 bottom = pwlen & ~7;
4173 assert(pwlen >= bottom && pwlen <= top);
4175 randomstr = snewn(top + 1, char);
4177 for (i = bottom; i <= top; i++) {
4179 defer_packet(ssh, s->pwpkt_type,
4180 PKTT_PASSWORD, PKT_STR,
4181 s->cur_prompt->prompts[0]->result,
4182 PKTT_OTHER, PKT_END);
4184 for (j = 0; j < i; j++) {
4186 randomstr[j] = random_byte();
4187 } while (randomstr[j] == '\0');
4189 randomstr[i] = '\0';
4190 defer_packet(ssh, SSH1_MSG_IGNORE,
4191 PKT_STR, randomstr, PKT_END);
4194 logevent("Sending password with camouflage packets");
4195 ssh_pkt_defersend(ssh);
4198 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4200 * The server can't deal with SSH1_MSG_IGNORE
4201 * but can deal with padded passwords, so we
4202 * can use the secondary defence.
4208 len = strlen(s->cur_prompt->prompts[0]->result);
4209 if (len < sizeof(string)) {
4211 strcpy(string, s->cur_prompt->prompts[0]->result);
4212 len++; /* cover the zero byte */
4213 while (len < sizeof(string)) {
4214 string[len++] = (char) random_byte();
4217 ss = s->cur_prompt->prompts[0]->result;
4219 logevent("Sending length-padded password");
4220 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4221 PKT_INT, len, PKT_DATA, ss, len,
4222 PKTT_OTHER, PKT_END);
4225 * The server is believed unable to cope with
4226 * any of our password camouflage methods.
4229 len = strlen(s->cur_prompt->prompts[0]->result);
4230 logevent("Sending unpadded password");
4231 send_packet(ssh, s->pwpkt_type,
4232 PKTT_PASSWORD, PKT_INT, len,
4233 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4234 PKTT_OTHER, PKT_END);
4237 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4238 PKT_STR, s->cur_prompt->prompts[0]->result,
4239 PKTT_OTHER, PKT_END);
4241 logevent("Sent password");
4242 free_prompts(s->cur_prompt);
4244 if (pktin->type == SSH1_SMSG_FAILURE) {
4245 if (flags & FLAG_VERBOSE)
4246 c_write_str(ssh, "Access denied\r\n");
4247 logevent("Authentication refused");
4248 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4249 bombout(("Strange packet received, type %d", pktin->type));
4255 if (s->publickey_blob) {
4256 sfree(s->publickey_blob);
4257 sfree(s->publickey_comment);
4260 logevent("Authentication successful");
4265 static void ssh_channel_try_eof(struct ssh_channel *c)
4268 assert(c->pending_eof); /* precondition for calling us */
4270 return; /* can't close: not even opened yet */
4271 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4272 return; /* can't send EOF: pending outgoing data */
4274 c->pending_eof = FALSE; /* we're about to send it */
4275 if (ssh->version == 1) {
4276 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4278 c->closes |= CLOSES_SENT_EOF;
4280 struct Packet *pktout;
4281 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4282 ssh2_pkt_adduint32(pktout, c->remoteid);
4283 ssh2_pkt_send(ssh, pktout);
4284 c->closes |= CLOSES_SENT_EOF;
4285 ssh2_channel_check_close(c);
4289 void sshfwd_write_eof(struct ssh_channel *c)
4293 if (ssh->state == SSH_STATE_CLOSED)
4296 if (c->closes & CLOSES_SENT_EOF)
4299 c->pending_eof = TRUE;
4300 ssh_channel_try_eof(c);
4303 void sshfwd_unclean_close(struct ssh_channel *c)
4307 if (ssh->state == SSH_STATE_CLOSED)
4312 x11_close(c->u.x11.s);
4313 logevent("Forwarded X11 connection terminated due to local error");
4316 case CHAN_SOCKDATA_DORMANT:
4317 pfd_close(c->u.pfd.s);
4318 logevent("Forwarded port closed due to local error");
4321 c->type = CHAN_ZOMBIE;
4323 ssh2_channel_check_close(c);
4326 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4330 if (ssh->state == SSH_STATE_CLOSED)
4333 if (ssh->version == 1) {
4334 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4335 PKT_INT, c->remoteid,
4336 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4337 PKTT_OTHER, PKT_END);
4339 * In SSH-1 we can return 0 here - implying that forwarded
4340 * connections are never individually throttled - because
4341 * the only circumstance that can cause throttling will be
4342 * the whole SSH connection backing up, in which case
4343 * _everything_ will be throttled as a whole.
4347 ssh2_add_channel_data(c, buf, len);
4348 return ssh2_try_send(c);
4352 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4357 if (ssh->state == SSH_STATE_CLOSED)
4360 if (ssh->version == 1) {
4361 buflimit = SSH1_BUFFER_LIMIT;
4363 buflimit = c->v.v2.locmaxwin;
4364 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4366 if (c->throttling_conn && bufsize <= buflimit) {
4367 c->throttling_conn = 0;
4368 ssh_throttle_conn(ssh, -1);
4372 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4374 struct queued_handler *qh = ssh->qhead;
4378 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4381 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4382 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4385 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4386 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4390 ssh->qhead = qh->next;
4392 if (ssh->qhead->msg1 > 0) {
4393 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4394 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4396 if (ssh->qhead->msg2 > 0) {
4397 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4398 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4401 ssh->qhead = ssh->qtail = NULL;
4404 qh->handler(ssh, pktin, qh->ctx);
4409 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4410 chandler_fn_t handler, void *ctx)
4412 struct queued_handler *qh;
4414 qh = snew(struct queued_handler);
4417 qh->handler = handler;
4421 if (ssh->qtail == NULL) {
4425 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4426 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4429 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4430 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4433 ssh->qtail->next = qh;
4438 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4440 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4442 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4443 SSH2_MSG_REQUEST_SUCCESS)) {
4444 logeventf(ssh, "Remote port forwarding from %s enabled",
4447 logeventf(ssh, "Remote port forwarding from %s refused",
4450 rpf = del234(ssh->rportfwds, pf);
4452 pf->pfrec->remote = NULL;
4457 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4459 struct ssh_portfwd *epf;
4463 if (!ssh->portfwds) {
4464 ssh->portfwds = newtree234(ssh_portcmp);
4467 * Go through the existing port forwardings and tag them
4468 * with status==DESTROY. Any that we want to keep will be
4469 * re-enabled (status==KEEP) as we go through the
4470 * configuration and find out which bits are the same as
4473 struct ssh_portfwd *epf;
4475 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4476 epf->status = DESTROY;
4479 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4481 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4482 char *kp, *kp2, *vp, *vp2;
4483 char address_family, type;
4484 int sport,dport,sserv,dserv;
4485 char *sports, *dports, *saddr, *host;
4489 address_family = 'A';
4491 if (*kp == 'A' || *kp == '4' || *kp == '6')
4492 address_family = *kp++;
4493 if (*kp == 'L' || *kp == 'R')
4496 if ((kp2 = strchr(kp, ':')) != NULL) {
4498 * There's a colon in the middle of the source port
4499 * string, which means that the part before it is
4500 * actually a source address.
4502 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4508 sport = atoi(sports);
4512 sport = net_service_lookup(sports);
4514 logeventf(ssh, "Service lookup failed for source"
4515 " port \"%s\"", sports);
4519 if (type == 'L' && !strcmp(val, "D")) {
4520 /* dynamic forwarding */
4527 /* ordinary forwarding */
4529 vp2 = vp + strcspn(vp, ":");
4530 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4534 dport = atoi(dports);
4538 dport = net_service_lookup(dports);
4540 logeventf(ssh, "Service lookup failed for destination"
4541 " port \"%s\"", dports);
4546 if (sport && dport) {
4547 /* Set up a description of the source port. */
4548 struct ssh_portfwd *pfrec, *epfrec;
4550 pfrec = snew(struct ssh_portfwd);
4552 pfrec->saddr = saddr;
4553 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4554 pfrec->sport = sport;
4555 pfrec->daddr = host;
4556 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4557 pfrec->dport = dport;
4558 pfrec->local = NULL;
4559 pfrec->remote = NULL;
4560 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4561 address_family == '6' ? ADDRTYPE_IPV6 :
4564 epfrec = add234(ssh->portfwds, pfrec);
4565 if (epfrec != pfrec) {
4566 if (epfrec->status == DESTROY) {
4568 * We already have a port forwarding up and running
4569 * with precisely these parameters. Hence, no need
4570 * to do anything; simply re-tag the existing one
4573 epfrec->status = KEEP;
4576 * Anything else indicates that there was a duplicate
4577 * in our input, which we'll silently ignore.
4579 free_portfwd(pfrec);
4581 pfrec->status = CREATE;
4590 * Now go through and destroy any port forwardings which were
4593 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4594 if (epf->status == DESTROY) {
4597 message = dupprintf("%s port forwarding from %s%s%d",
4598 epf->type == 'L' ? "local" :
4599 epf->type == 'R' ? "remote" : "dynamic",
4600 epf->saddr ? epf->saddr : "",
4601 epf->saddr ? ":" : "",
4604 if (epf->type != 'D') {
4605 char *msg2 = dupprintf("%s to %s:%d", message,
4606 epf->daddr, epf->dport);
4611 logeventf(ssh, "Cancelling %s", message);
4614 /* epf->remote or epf->local may be NULL if setting up a
4615 * forwarding failed. */
4617 struct ssh_rportfwd *rpf = epf->remote;
4618 struct Packet *pktout;
4621 * Cancel the port forwarding at the server
4624 if (ssh->version == 1) {
4626 * We cannot cancel listening ports on the
4627 * server side in SSH-1! There's no message
4628 * to support it. Instead, we simply remove
4629 * the rportfwd record from the local end
4630 * so that any connections the server tries
4631 * to make on it are rejected.
4634 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4635 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4636 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4638 ssh2_pkt_addstring(pktout, epf->saddr);
4639 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4640 /* XXX: rport_acceptall may not represent
4641 * what was used to open the original connection,
4642 * since it's reconfigurable. */
4643 ssh2_pkt_addstring(pktout, "");
4645 ssh2_pkt_addstring(pktout, "localhost");
4647 ssh2_pkt_adduint32(pktout, epf->sport);
4648 ssh2_pkt_send(ssh, pktout);
4651 del234(ssh->rportfwds, rpf);
4653 } else if (epf->local) {
4654 pfd_terminate(epf->local);
4657 delpos234(ssh->portfwds, i);
4659 i--; /* so we don't skip one in the list */
4663 * And finally, set up any new port forwardings (status==CREATE).
4665 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4666 if (epf->status == CREATE) {
4667 char *sportdesc, *dportdesc;
4668 sportdesc = dupprintf("%s%s%s%s%d%s",
4669 epf->saddr ? epf->saddr : "",
4670 epf->saddr ? ":" : "",
4671 epf->sserv ? epf->sserv : "",
4672 epf->sserv ? "(" : "",
4674 epf->sserv ? ")" : "");
4675 if (epf->type == 'D') {
4678 dportdesc = dupprintf("%s:%s%s%d%s",
4680 epf->dserv ? epf->dserv : "",
4681 epf->dserv ? "(" : "",
4683 epf->dserv ? ")" : "");
4686 if (epf->type == 'L') {
4687 const char *err = pfd_addforward(epf->daddr, epf->dport,
4688 epf->saddr, epf->sport,
4691 epf->addressfamily);
4693 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4694 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4695 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4696 sportdesc, dportdesc,
4697 err ? " failed: " : "", err ? err : "");
4698 } else if (epf->type == 'D') {
4699 const char *err = pfd_addforward(NULL, -1,
4700 epf->saddr, epf->sport,
4703 epf->addressfamily);
4705 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4706 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4707 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4709 err ? " failed: " : "", err ? err : "");
4711 struct ssh_rportfwd *pf;
4714 * Ensure the remote port forwardings tree exists.
4716 if (!ssh->rportfwds) {
4717 if (ssh->version == 1)
4718 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4720 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4723 pf = snew(struct ssh_rportfwd);
4724 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4725 pf->dhost[lenof(pf->dhost)-1] = '\0';
4726 pf->dport = epf->dport;
4727 pf->sport = epf->sport;
4728 if (add234(ssh->rportfwds, pf) != pf) {
4729 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4730 epf->daddr, epf->dport);
4733 logeventf(ssh, "Requesting remote port %s"
4734 " forward to %s", sportdesc, dportdesc);
4736 pf->sportdesc = sportdesc;
4741 if (ssh->version == 1) {
4742 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4743 PKT_INT, epf->sport,
4744 PKT_STR, epf->daddr,
4745 PKT_INT, epf->dport,
4747 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4749 ssh_rportfwd_succfail, pf);
4751 struct Packet *pktout;
4752 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4753 ssh2_pkt_addstring(pktout, "tcpip-forward");
4754 ssh2_pkt_addbool(pktout, 1);/* want reply */
4756 ssh2_pkt_addstring(pktout, epf->saddr);
4757 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4758 ssh2_pkt_addstring(pktout, "");
4760 ssh2_pkt_addstring(pktout, "localhost");
4762 ssh2_pkt_adduint32(pktout, epf->sport);
4763 ssh2_pkt_send(ssh, pktout);
4765 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4766 SSH2_MSG_REQUEST_FAILURE,
4767 ssh_rportfwd_succfail, pf);
4776 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4779 int stringlen, bufsize;
4781 ssh_pkt_getstring(pktin, &string, &stringlen);
4782 if (string == NULL) {
4783 bombout(("Incoming terminal data packet was badly formed"));
4787 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4789 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4790 ssh->v1_stdout_throttling = 1;
4791 ssh_throttle_conn(ssh, +1);
4795 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4797 /* Remote side is trying to open a channel to talk to our
4798 * X-Server. Give them back a local channel number. */
4799 struct ssh_channel *c;
4800 int remoteid = ssh_pkt_getuint32(pktin);
4802 logevent("Received X11 connect request");
4803 /* Refuse if X11 forwarding is disabled. */
4804 if (!ssh->X11_fwd_enabled) {
4805 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4806 PKT_INT, remoteid, PKT_END);
4807 logevent("Rejected X11 connect request");
4809 c = snew(struct ssh_channel);
4812 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4813 NULL, -1, ssh->conf) != NULL) {
4814 logevent("Opening X11 forward connection failed");
4816 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4817 PKT_INT, remoteid, PKT_END);
4820 ("Opening X11 forward connection succeeded");
4821 c->remoteid = remoteid;
4822 c->halfopen = FALSE;
4823 c->localid = alloc_channel_id(ssh);
4825 c->pending_eof = FALSE;
4826 c->throttling_conn = 0;
4827 c->type = CHAN_X11; /* identify channel type */
4828 add234(ssh->channels, c);
4829 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4830 PKT_INT, c->remoteid, PKT_INT,
4831 c->localid, PKT_END);
4832 logevent("Opened X11 forward channel");
4837 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4839 /* Remote side is trying to open a channel to talk to our
4840 * agent. Give them back a local channel number. */
4841 struct ssh_channel *c;
4842 int remoteid = ssh_pkt_getuint32(pktin);
4844 /* Refuse if agent forwarding is disabled. */
4845 if (!ssh->agentfwd_enabled) {
4846 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4847 PKT_INT, remoteid, PKT_END);
4849 c = snew(struct ssh_channel);
4851 c->remoteid = remoteid;
4852 c->halfopen = FALSE;
4853 c->localid = alloc_channel_id(ssh);
4855 c->pending_eof = FALSE;
4856 c->throttling_conn = 0;
4857 c->type = CHAN_AGENT; /* identify channel type */
4858 c->u.a.lensofar = 0;
4859 c->u.a.message = NULL;
4860 c->u.a.outstanding_requests = 0;
4861 add234(ssh->channels, c);
4862 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4863 PKT_INT, c->remoteid, PKT_INT, c->localid,
4868 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4870 /* Remote side is trying to open a channel to talk to a
4871 * forwarded port. Give them back a local channel number. */
4872 struct ssh_rportfwd pf, *pfp;
4878 remoteid = ssh_pkt_getuint32(pktin);
4879 ssh_pkt_getstring(pktin, &host, &hostsize);
4880 port = ssh_pkt_getuint32(pktin);
4882 if (hostsize >= lenof(pf.dhost))
4883 hostsize = lenof(pf.dhost)-1;
4884 memcpy(pf.dhost, host, hostsize);
4885 pf.dhost[hostsize] = '\0';
4887 pfp = find234(ssh->rportfwds, &pf, NULL);
4890 logeventf(ssh, "Rejected remote port open request for %s:%d",
4892 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4893 PKT_INT, remoteid, PKT_END);
4895 struct ssh_channel *c = snew(struct ssh_channel);
4898 logeventf(ssh, "Received remote port open request for %s:%d",
4900 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4901 c, ssh->conf, pfp->pfrec->addressfamily);
4903 logeventf(ssh, "Port open failed: %s", e);
4905 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4906 PKT_INT, remoteid, PKT_END);
4908 c->remoteid = remoteid;
4909 c->halfopen = FALSE;
4910 c->localid = alloc_channel_id(ssh);
4912 c->pending_eof = FALSE;
4913 c->throttling_conn = 0;
4914 c->type = CHAN_SOCKDATA; /* identify channel type */
4915 add234(ssh->channels, c);
4916 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4917 PKT_INT, c->remoteid, PKT_INT,
4918 c->localid, PKT_END);
4919 logevent("Forwarded port opened successfully");
4924 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4926 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4927 unsigned int localid = ssh_pkt_getuint32(pktin);
4928 struct ssh_channel *c;
4930 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4931 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4932 c->remoteid = localid;
4933 c->halfopen = FALSE;
4934 c->type = CHAN_SOCKDATA;
4935 c->throttling_conn = 0;
4936 pfd_confirm(c->u.pfd.s);
4939 if (c && c->pending_eof) {
4941 * We have a pending close on this channel,
4942 * which we decided on before the server acked
4943 * the channel open. So now we know the
4944 * remoteid, we can close it again.
4946 ssh_channel_try_eof(c);
4950 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4952 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4953 struct ssh_channel *c;
4955 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4956 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4957 logevent("Forwarded connection refused by server");
4958 pfd_close(c->u.pfd.s);
4959 del234(ssh->channels, c);
4964 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4966 /* Remote side closes a channel. */
4967 unsigned i = ssh_pkt_getuint32(pktin);
4968 struct ssh_channel *c;
4969 c = find234(ssh->channels, &i, ssh_channelfind);
4970 if (c && !c->halfopen) {
4972 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4973 !(c->closes & CLOSES_RCVD_EOF)) {
4975 * Received CHANNEL_CLOSE, which we translate into
4978 int send_close = FALSE;
4980 c->closes |= CLOSES_RCVD_EOF;
4985 x11_send_eof(c->u.x11.s);
4991 pfd_send_eof(c->u.pfd.s);
5000 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5001 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5003 c->closes |= CLOSES_SENT_EOF;
5007 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5008 !(c->closes & CLOSES_RCVD_CLOSE)) {
5010 if (!(c->closes & CLOSES_SENT_EOF)) {
5011 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5012 " for which we never sent CHANNEL_CLOSE\n", i));
5015 c->closes |= CLOSES_RCVD_CLOSE;
5018 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5019 !(c->closes & CLOSES_SENT_CLOSE)) {
5020 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5021 PKT_INT, c->remoteid, PKT_END);
5022 c->closes |= CLOSES_SENT_CLOSE;
5025 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5026 ssh_channel_destroy(c);
5028 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5029 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5030 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5035 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5037 /* Data sent down one of our channels. */
5038 int i = ssh_pkt_getuint32(pktin);
5041 struct ssh_channel *c;
5043 ssh_pkt_getstring(pktin, &p, &len);
5045 c = find234(ssh->channels, &i, ssh_channelfind);
5050 bufsize = x11_send(c->u.x11.s, p, len);
5053 bufsize = pfd_send(c->u.pfd.s, p, len);
5056 /* Data for an agent message. Buffer it. */
5058 if (c->u.a.lensofar < 4) {
5059 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5060 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5064 c->u.a.lensofar += l;
5066 if (c->u.a.lensofar == 4) {
5068 4 + GET_32BIT(c->u.a.msglen);
5069 c->u.a.message = snewn(c->u.a.totallen,
5071 memcpy(c->u.a.message, c->u.a.msglen, 4);
5073 if (c->u.a.lensofar >= 4 && len > 0) {
5075 min(c->u.a.totallen - c->u.a.lensofar,
5077 memcpy(c->u.a.message + c->u.a.lensofar, p,
5081 c->u.a.lensofar += l;
5083 if (c->u.a.lensofar == c->u.a.totallen) {
5086 c->u.a.outstanding_requests++;
5087 if (agent_query(c->u.a.message,
5090 ssh_agentf_callback, c))
5091 ssh_agentf_callback(c, reply, replylen);
5092 sfree(c->u.a.message);
5093 c->u.a.lensofar = 0;
5096 bufsize = 0; /* agent channels never back up */
5099 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5100 c->throttling_conn = 1;
5101 ssh_throttle_conn(ssh, +1);
5106 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5108 ssh->exitcode = ssh_pkt_getuint32(pktin);
5109 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5110 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5112 * In case `helpful' firewalls or proxies tack
5113 * extra human-readable text on the end of the
5114 * session which we might mistake for another
5115 * encrypted packet, we close the session once
5116 * we've sent EXIT_CONFIRMATION.
5118 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5121 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5122 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5124 struct Packet *pktout = (struct Packet *)data;
5126 unsigned int arg = 0;
5127 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5128 if (i == lenof(ssh_ttymodes)) return;
5129 switch (ssh_ttymodes[i].type) {
5131 arg = ssh_tty_parse_specchar(val);
5134 arg = ssh_tty_parse_boolean(val);
5137 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5138 ssh2_pkt_addbyte(pktout, arg);
5142 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5143 struct Packet *pktin)
5145 crBegin(ssh->do_ssh1_connection_crstate);
5147 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5148 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5149 ssh1_smsg_stdout_stderr_data;
5151 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5152 ssh1_msg_channel_open_confirmation;
5153 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5154 ssh1_msg_channel_open_failure;
5155 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5156 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5157 ssh1_msg_channel_close;
5158 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5159 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5161 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5162 logevent("Requesting agent forwarding");
5163 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5167 if (pktin->type != SSH1_SMSG_SUCCESS
5168 && pktin->type != SSH1_SMSG_FAILURE) {
5169 bombout(("Protocol confusion"));
5171 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5172 logevent("Agent forwarding refused");
5174 logevent("Agent forwarding enabled");
5175 ssh->agentfwd_enabled = TRUE;
5176 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5180 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5181 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5182 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5183 logevent("Requesting X11 forwarding");
5185 * Note that while we blank the X authentication data here, we don't
5186 * take any special action to blank the start of an X11 channel,
5187 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5188 * without having session blanking enabled is likely to leak your
5189 * cookie into the log.
5191 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5192 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5193 PKT_STR, ssh->x11disp->remoteauthprotoname,
5195 PKT_STR, ssh->x11disp->remoteauthdatastring,
5197 PKT_INT, ssh->x11disp->screennum,
5200 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5201 PKT_STR, ssh->x11disp->remoteauthprotoname,
5203 PKT_STR, ssh->x11disp->remoteauthdatastring,
5210 if (pktin->type != SSH1_SMSG_SUCCESS
5211 && pktin->type != SSH1_SMSG_FAILURE) {
5212 bombout(("Protocol confusion"));
5214 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5215 logevent("X11 forwarding refused");
5217 logevent("X11 forwarding enabled");
5218 ssh->X11_fwd_enabled = TRUE;
5219 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5223 ssh_setup_portfwd(ssh, ssh->conf);
5224 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5226 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5228 /* Unpick the terminal-speed string. */
5229 /* XXX perhaps we should allow no speeds to be sent. */
5230 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5231 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5232 /* Send the pty request. */
5233 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5234 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5235 ssh_pkt_adduint32(pkt, ssh->term_height);
5236 ssh_pkt_adduint32(pkt, ssh->term_width);
5237 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5238 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5239 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5240 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5241 ssh_pkt_adduint32(pkt, ssh->ispeed);
5242 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5243 ssh_pkt_adduint32(pkt, ssh->ospeed);
5244 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5246 ssh->state = SSH_STATE_INTERMED;
5250 if (pktin->type != SSH1_SMSG_SUCCESS
5251 && pktin->type != SSH1_SMSG_FAILURE) {
5252 bombout(("Protocol confusion"));
5254 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5255 c_write_str(ssh, "Server refused to allocate pty\r\n");
5256 ssh->editing = ssh->echoing = 1;
5258 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5259 ssh->ospeed, ssh->ispeed);
5260 ssh->got_pty = TRUE;
5263 ssh->editing = ssh->echoing = 1;
5266 if (conf_get_int(ssh->conf, CONF_compression)) {
5267 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5271 if (pktin->type != SSH1_SMSG_SUCCESS
5272 && pktin->type != SSH1_SMSG_FAILURE) {
5273 bombout(("Protocol confusion"));
5275 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5276 c_write_str(ssh, "Server refused to compress\r\n");
5278 logevent("Started compression");
5279 ssh->v1_compressing = TRUE;
5280 ssh->cs_comp_ctx = zlib_compress_init();
5281 logevent("Initialised zlib (RFC1950) compression");
5282 ssh->sc_comp_ctx = zlib_decompress_init();
5283 logevent("Initialised zlib (RFC1950) decompression");
5287 * Start the shell or command.
5289 * Special case: if the first-choice command is an SSH-2
5290 * subsystem (hence not usable here) and the second choice
5291 * exists, we fall straight back to that.
5294 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5296 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5297 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5298 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5299 ssh->fallback_cmd = TRUE;
5302 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5304 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5305 logevent("Started session");
5308 ssh->state = SSH_STATE_SESSION;
5309 if (ssh->size_needed)
5310 ssh_size(ssh, ssh->term_width, ssh->term_height);
5311 if (ssh->eof_needed)
5312 ssh_special(ssh, TS_EOF);
5315 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5317 ssh->channels = newtree234(ssh_channelcmp);
5321 * By this point, most incoming packets are already being
5322 * handled by the dispatch table, and we need only pay
5323 * attention to the unusual ones.
5328 if (pktin->type == SSH1_SMSG_SUCCESS) {
5329 /* may be from EXEC_SHELL on some servers */
5330 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5331 /* may be from EXEC_SHELL on some servers
5332 * if no pty is available or in other odd cases. Ignore */
5334 bombout(("Strange packet received: type %d", pktin->type));
5339 int len = min(inlen, 512);
5340 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5341 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5342 PKTT_OTHER, PKT_END);
5353 * Handle the top-level SSH-2 protocol.
5355 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5360 ssh_pkt_getstring(pktin, &msg, &msglen);
5361 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5364 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5366 /* log reason code in disconnect message */
5370 ssh_pkt_getstring(pktin, &msg, &msglen);
5371 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5374 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5376 /* Do nothing, because we're ignoring it! Duhh. */
5379 static void ssh1_protocol_setup(Ssh ssh)
5384 * Most messages are handled by the coroutines.
5386 for (i = 0; i < 256; i++)
5387 ssh->packet_dispatch[i] = NULL;
5390 * These special message types we install handlers for.
5392 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5393 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5394 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5397 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5398 struct Packet *pktin)
5400 unsigned char *in=(unsigned char*)vin;
5401 if (ssh->state == SSH_STATE_CLOSED)
5404 if (pktin && ssh->packet_dispatch[pktin->type]) {
5405 ssh->packet_dispatch[pktin->type](ssh, pktin);
5409 if (!ssh->protocol_initial_phase_done) {
5410 if (do_ssh1_login(ssh, in, inlen, pktin))
5411 ssh->protocol_initial_phase_done = TRUE;
5416 do_ssh1_connection(ssh, in, inlen, pktin);
5420 * Utility routine for decoding comma-separated strings in KEXINIT.
5422 static int in_commasep_string(char *needle, char *haystack, int haylen)
5425 if (!needle || !haystack) /* protect against null pointers */
5427 needlen = strlen(needle);
5430 * Is it at the start of the string?
5432 if (haylen >= needlen && /* haystack is long enough */
5433 !memcmp(needle, haystack, needlen) && /* initial match */
5434 (haylen == needlen || haystack[needlen] == ',')
5435 /* either , or EOS follows */
5439 * If not, search for the next comma and resume after that.
5440 * If no comma found, terminate.
5442 while (haylen > 0 && *haystack != ',')
5443 haylen--, haystack++;
5446 haylen--, haystack++; /* skip over comma itself */
5451 * Similar routine for checking whether we have the first string in a list.
5453 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5456 if (!needle || !haystack) /* protect against null pointers */
5458 needlen = strlen(needle);
5460 * Is it at the start of the string?
5462 if (haylen >= needlen && /* haystack is long enough */
5463 !memcmp(needle, haystack, needlen) && /* initial match */
5464 (haylen == needlen || haystack[needlen] == ',')
5465 /* either , or EOS follows */
5473 * SSH-2 key creation method.
5474 * (Currently assumes 2 lots of any hash are sufficient to generate
5475 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5477 #define SSH2_MKKEY_ITERS (2)
5478 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5479 unsigned char *keyspace)
5481 const struct ssh_hash *h = ssh->kex->hash;
5483 /* First hlen bytes. */
5485 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5486 hash_mpint(h, s, K);
5487 h->bytes(s, H, h->hlen);
5488 h->bytes(s, &chr, 1);
5489 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5490 h->final(s, keyspace);
5491 /* Next hlen bytes. */
5493 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5494 hash_mpint(h, s, K);
5495 h->bytes(s, H, h->hlen);
5496 h->bytes(s, keyspace, h->hlen);
5497 h->final(s, keyspace + h->hlen);
5501 * Handle the SSH-2 transport layer.
5503 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5504 struct Packet *pktin)
5506 unsigned char *in = (unsigned char *)vin;
5507 struct do_ssh2_transport_state {
5509 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5510 Bignum p, g, e, f, K;
5513 int kex_init_value, kex_reply_value;
5514 const struct ssh_mac **maclist;
5516 const struct ssh2_cipher *cscipher_tobe;
5517 const struct ssh2_cipher *sccipher_tobe;
5518 const struct ssh_mac *csmac_tobe;
5519 const struct ssh_mac *scmac_tobe;
5520 const struct ssh_compress *cscomp_tobe;
5521 const struct ssh_compress *sccomp_tobe;
5522 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5523 int hostkeylen, siglen, rsakeylen;
5524 void *hkey; /* actual host key */
5525 void *rsakey; /* for RSA kex */
5526 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5527 int n_preferred_kex;
5528 const struct ssh_kexes *preferred_kex[KEX_MAX];
5529 int n_preferred_ciphers;
5530 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5531 const struct ssh_compress *preferred_comp;
5532 int userauth_succeeded; /* for delayed compression */
5533 int pending_compression;
5534 int got_session_id, activated_authconn;
5535 struct Packet *pktout;
5540 crState(do_ssh2_transport_state);
5544 s->cscipher_tobe = s->sccipher_tobe = NULL;
5545 s->csmac_tobe = s->scmac_tobe = NULL;
5546 s->cscomp_tobe = s->sccomp_tobe = NULL;
5548 s->got_session_id = s->activated_authconn = FALSE;
5549 s->userauth_succeeded = FALSE;
5550 s->pending_compression = FALSE;
5553 * Be prepared to work around the buggy MAC problem.
5555 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5556 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5558 s->maclist = macs, s->nmacs = lenof(macs);
5561 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5563 int i, j, k, commalist_started;
5566 * Set up the preferred key exchange. (NULL => warn below here)
5568 s->n_preferred_kex = 0;
5569 for (i = 0; i < KEX_MAX; i++) {
5570 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5572 s->preferred_kex[s->n_preferred_kex++] =
5573 &ssh_diffiehellman_gex;
5576 s->preferred_kex[s->n_preferred_kex++] =
5577 &ssh_diffiehellman_group14;
5580 s->preferred_kex[s->n_preferred_kex++] =
5581 &ssh_diffiehellman_group1;
5584 s->preferred_kex[s->n_preferred_kex++] =
5588 /* Flag for later. Don't bother if it's the last in
5590 if (i < KEX_MAX - 1) {
5591 s->preferred_kex[s->n_preferred_kex++] = NULL;
5598 * Set up the preferred ciphers. (NULL => warn below here)
5600 s->n_preferred_ciphers = 0;
5601 for (i = 0; i < CIPHER_MAX; i++) {
5602 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5603 case CIPHER_BLOWFISH:
5604 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5607 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5608 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5612 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5615 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5617 case CIPHER_ARCFOUR:
5618 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5621 /* Flag for later. Don't bother if it's the last in
5623 if (i < CIPHER_MAX - 1) {
5624 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5631 * Set up preferred compression.
5633 if (conf_get_int(ssh->conf, CONF_compression))
5634 s->preferred_comp = &ssh_zlib;
5636 s->preferred_comp = &ssh_comp_none;
5639 * Enable queueing of outgoing auth- or connection-layer
5640 * packets while we are in the middle of a key exchange.
5642 ssh->queueing = TRUE;
5645 * Flag that KEX is in progress.
5647 ssh->kex_in_progress = TRUE;
5650 * Construct and send our key exchange packet.
5652 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5653 for (i = 0; i < 16; i++)
5654 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5655 /* List key exchange algorithms. */
5656 ssh2_pkt_addstring_start(s->pktout);
5657 commalist_started = 0;
5658 for (i = 0; i < s->n_preferred_kex; i++) {
5659 const struct ssh_kexes *k = s->preferred_kex[i];
5660 if (!k) continue; /* warning flag */
5661 for (j = 0; j < k->nkexes; j++) {
5662 if (commalist_started)
5663 ssh2_pkt_addstring_str(s->pktout, ",");
5664 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5665 commalist_started = 1;
5668 /* List server host key algorithms. */
5669 ssh2_pkt_addstring_start(s->pktout);
5670 for (i = 0; i < lenof(hostkey_algs); i++) {
5671 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5672 if (i < lenof(hostkey_algs) - 1)
5673 ssh2_pkt_addstring_str(s->pktout, ",");
5675 /* List encryption algorithms (client->server then server->client). */
5676 for (k = 0; k < 2; k++) {
5677 ssh2_pkt_addstring_start(s->pktout);
5678 commalist_started = 0;
5679 for (i = 0; i < s->n_preferred_ciphers; i++) {
5680 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5681 if (!c) continue; /* warning flag */
5682 for (j = 0; j < c->nciphers; j++) {
5683 if (commalist_started)
5684 ssh2_pkt_addstring_str(s->pktout, ",");
5685 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5686 commalist_started = 1;
5690 /* List MAC algorithms (client->server then server->client). */
5691 for (j = 0; j < 2; j++) {
5692 ssh2_pkt_addstring_start(s->pktout);
5693 for (i = 0; i < s->nmacs; i++) {
5694 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5695 if (i < s->nmacs - 1)
5696 ssh2_pkt_addstring_str(s->pktout, ",");
5699 /* List client->server compression algorithms,
5700 * then server->client compression algorithms. (We use the
5701 * same set twice.) */
5702 for (j = 0; j < 2; j++) {
5703 ssh2_pkt_addstring_start(s->pktout);
5704 assert(lenof(compressions) > 1);
5705 /* Prefer non-delayed versions */
5706 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5707 /* We don't even list delayed versions of algorithms until
5708 * they're allowed to be used, to avoid a race. See the end of
5710 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5711 ssh2_pkt_addstring_str(s->pktout, ",");
5712 ssh2_pkt_addstring_str(s->pktout,
5713 s->preferred_comp->delayed_name);
5715 for (i = 0; i < lenof(compressions); i++) {
5716 const struct ssh_compress *c = compressions[i];
5717 if (c != s->preferred_comp) {
5718 ssh2_pkt_addstring_str(s->pktout, ",");
5719 ssh2_pkt_addstring_str(s->pktout, c->name);
5720 if (s->userauth_succeeded && c->delayed_name) {
5721 ssh2_pkt_addstring_str(s->pktout, ",");
5722 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5727 /* List client->server languages. Empty list. */
5728 ssh2_pkt_addstring_start(s->pktout);
5729 /* List server->client languages. Empty list. */
5730 ssh2_pkt_addstring_start(s->pktout);
5731 /* First KEX packet does _not_ follow, because we're not that brave. */
5732 ssh2_pkt_addbool(s->pktout, FALSE);
5734 ssh2_pkt_adduint32(s->pktout, 0);
5737 s->our_kexinitlen = s->pktout->length - 5;
5738 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5739 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5741 ssh2_pkt_send_noqueue(ssh, s->pktout);
5744 crWaitUntilV(pktin);
5747 * Now examine the other side's KEXINIT to see what we're up
5751 char *str, *preferred;
5754 if (pktin->type != SSH2_MSG_KEXINIT) {
5755 bombout(("expected key exchange packet from server"));
5759 ssh->hostkey = NULL;
5760 s->cscipher_tobe = NULL;
5761 s->sccipher_tobe = NULL;
5762 s->csmac_tobe = NULL;
5763 s->scmac_tobe = NULL;
5764 s->cscomp_tobe = NULL;
5765 s->sccomp_tobe = NULL;
5766 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5768 pktin->savedpos += 16; /* skip garbage cookie */
5769 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5772 for (i = 0; i < s->n_preferred_kex; i++) {
5773 const struct ssh_kexes *k = s->preferred_kex[i];
5777 for (j = 0; j < k->nkexes; j++) {
5778 if (!preferred) preferred = k->list[j]->name;
5779 if (in_commasep_string(k->list[j]->name, str, len)) {
5780 ssh->kex = k->list[j];
5789 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5790 str ? str : "(null)"));
5794 * Note that the server's guess is considered wrong if it doesn't match
5795 * the first algorithm in our list, even if it's still the algorithm
5798 s->guessok = first_in_commasep_string(preferred, str, len);
5799 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5800 for (i = 0; i < lenof(hostkey_algs); i++) {
5801 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5802 ssh->hostkey = hostkey_algs[i];
5806 if (!ssh->hostkey) {
5807 bombout(("Couldn't agree a host key algorithm (available: %s)",
5808 str ? str : "(null)"));
5812 s->guessok = s->guessok &&
5813 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5814 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5815 for (i = 0; i < s->n_preferred_ciphers; i++) {
5816 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5818 s->warn_cscipher = TRUE;
5820 for (j = 0; j < c->nciphers; j++) {
5821 if (in_commasep_string(c->list[j]->name, str, len)) {
5822 s->cscipher_tobe = c->list[j];
5827 if (s->cscipher_tobe)
5830 if (!s->cscipher_tobe) {
5831 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5832 str ? str : "(null)"));
5836 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5837 for (i = 0; i < s->n_preferred_ciphers; i++) {
5838 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5840 s->warn_sccipher = TRUE;
5842 for (j = 0; j < c->nciphers; j++) {
5843 if (in_commasep_string(c->list[j]->name, str, len)) {
5844 s->sccipher_tobe = c->list[j];
5849 if (s->sccipher_tobe)
5852 if (!s->sccipher_tobe) {
5853 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5854 str ? str : "(null)"));
5858 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5859 for (i = 0; i < s->nmacs; i++) {
5860 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5861 s->csmac_tobe = s->maclist[i];
5865 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5866 for (i = 0; i < s->nmacs; i++) {
5867 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5868 s->scmac_tobe = s->maclist[i];
5872 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5873 for (i = 0; i < lenof(compressions) + 1; i++) {
5874 const struct ssh_compress *c =
5875 i == 0 ? s->preferred_comp : compressions[i - 1];
5876 if (in_commasep_string(c->name, str, len)) {
5879 } else if (in_commasep_string(c->delayed_name, str, len)) {
5880 if (s->userauth_succeeded) {
5884 s->pending_compression = TRUE; /* try this later */
5888 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5889 for (i = 0; i < lenof(compressions) + 1; i++) {
5890 const struct ssh_compress *c =
5891 i == 0 ? s->preferred_comp : compressions[i - 1];
5892 if (in_commasep_string(c->name, str, len)) {
5895 } else if (in_commasep_string(c->delayed_name, str, len)) {
5896 if (s->userauth_succeeded) {
5900 s->pending_compression = TRUE; /* try this later */
5904 if (s->pending_compression) {
5905 logevent("Server supports delayed compression; "
5906 "will try this later");
5908 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5909 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5910 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5912 ssh->exhash = ssh->kex->hash->init();
5913 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5914 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5915 hash_string(ssh->kex->hash, ssh->exhash,
5916 s->our_kexinit, s->our_kexinitlen);
5917 sfree(s->our_kexinit);
5918 if (pktin->length > 5)
5919 hash_string(ssh->kex->hash, ssh->exhash,
5920 pktin->data + 5, pktin->length - 5);
5923 ssh_set_frozen(ssh, 1);
5924 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5926 ssh_dialog_callback, ssh);
5927 if (s->dlgret < 0) {
5931 bombout(("Unexpected data from server while"
5932 " waiting for user response"));
5935 } while (pktin || inlen > 0);
5936 s->dlgret = ssh->user_response;
5938 ssh_set_frozen(ssh, 0);
5939 if (s->dlgret == 0) {
5940 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5946 if (s->warn_cscipher) {
5947 ssh_set_frozen(ssh, 1);
5948 s->dlgret = askalg(ssh->frontend,
5949 "client-to-server cipher",
5950 s->cscipher_tobe->name,
5951 ssh_dialog_callback, ssh);
5952 if (s->dlgret < 0) {
5956 bombout(("Unexpected data from server while"
5957 " waiting for user response"));
5960 } while (pktin || inlen > 0);
5961 s->dlgret = ssh->user_response;
5963 ssh_set_frozen(ssh, 0);
5964 if (s->dlgret == 0) {
5965 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5971 if (s->warn_sccipher) {
5972 ssh_set_frozen(ssh, 1);
5973 s->dlgret = askalg(ssh->frontend,
5974 "server-to-client cipher",
5975 s->sccipher_tobe->name,
5976 ssh_dialog_callback, ssh);
5977 if (s->dlgret < 0) {
5981 bombout(("Unexpected data from server while"
5982 " waiting for user response"));
5985 } while (pktin || inlen > 0);
5986 s->dlgret = ssh->user_response;
5988 ssh_set_frozen(ssh, 0);
5989 if (s->dlgret == 0) {
5990 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5996 if (s->ignorepkt) /* first_kex_packet_follows */
5997 crWaitUntilV(pktin); /* Ignore packet */
6000 if (ssh->kex->main_type == KEXTYPE_DH) {
6002 * Work out the number of bits of key we will need from the
6003 * key exchange. We start with the maximum key length of
6009 csbits = s->cscipher_tobe->keylen;
6010 scbits = s->sccipher_tobe->keylen;
6011 s->nbits = (csbits > scbits ? csbits : scbits);
6013 /* The keys only have hlen-bit entropy, since they're based on
6014 * a hash. So cap the key size at hlen bits. */
6015 if (s->nbits > ssh->kex->hash->hlen * 8)
6016 s->nbits = ssh->kex->hash->hlen * 8;
6019 * If we're doing Diffie-Hellman group exchange, start by
6020 * requesting a group.
6022 if (!ssh->kex->pdata) {
6023 logevent("Doing Diffie-Hellman group exchange");
6024 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6026 * Work out how big a DH group we will need to allow that
6029 s->pbits = 512 << ((s->nbits - 1) / 64);
6030 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6031 ssh2_pkt_adduint32(s->pktout, s->pbits);
6032 ssh2_pkt_send_noqueue(ssh, s->pktout);
6034 crWaitUntilV(pktin);
6035 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6036 bombout(("expected key exchange group packet from server"));
6039 s->p = ssh2_pkt_getmp(pktin);
6040 s->g = ssh2_pkt_getmp(pktin);
6041 if (!s->p || !s->g) {
6042 bombout(("unable to read mp-ints from incoming group packet"));
6045 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6046 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6047 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6049 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6050 ssh->kex_ctx = dh_setup_group(ssh->kex);
6051 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6052 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6053 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6054 ssh->kex->groupname);
6057 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6058 ssh->kex->hash->text_name);
6060 * Now generate and send e for Diffie-Hellman.
6062 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6063 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6064 s->pktout = ssh2_pkt_init(s->kex_init_value);
6065 ssh2_pkt_addmp(s->pktout, s->e);
6066 ssh2_pkt_send_noqueue(ssh, s->pktout);
6068 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6069 crWaitUntilV(pktin);
6070 if (pktin->type != s->kex_reply_value) {
6071 bombout(("expected key exchange reply packet from server"));
6074 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6075 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6076 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6077 s->f = ssh2_pkt_getmp(pktin);
6079 bombout(("unable to parse key exchange reply packet"));
6082 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6084 s->K = dh_find_K(ssh->kex_ctx, s->f);
6086 /* We assume everything from now on will be quick, and it might
6087 * involve user interaction. */
6088 set_busy_status(ssh->frontend, BUSY_NOT);
6090 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6091 if (!ssh->kex->pdata) {
6092 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6093 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6094 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6096 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6097 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6099 dh_cleanup(ssh->kex_ctx);
6101 if (!ssh->kex->pdata) {
6106 logeventf(ssh, "Doing RSA key exchange with hash %s",
6107 ssh->kex->hash->text_name);
6108 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6110 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6113 crWaitUntilV(pktin);
6114 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6115 bombout(("expected RSA public key packet from server"));
6119 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6120 hash_string(ssh->kex->hash, ssh->exhash,
6121 s->hostkeydata, s->hostkeylen);
6122 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6126 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6127 s->rsakeydata = snewn(s->rsakeylen, char);
6128 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6131 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6133 sfree(s->rsakeydata);
6134 bombout(("unable to parse RSA public key from server"));
6138 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6141 * Next, set up a shared secret K, of precisely KLEN -
6142 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6143 * RSA key modulus and HLEN is the bit length of the hash
6147 int klen = ssh_rsakex_klen(s->rsakey);
6148 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6150 unsigned char *kstr1, *kstr2, *outstr;
6151 int kstr1len, kstr2len, outstrlen;
6153 s->K = bn_power_2(nbits - 1);
6155 for (i = 0; i < nbits; i++) {
6157 byte = random_byte();
6159 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6163 * Encode this as an mpint.
6165 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6166 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6167 PUT_32BIT(kstr2, kstr1len);
6168 memcpy(kstr2 + 4, kstr1, kstr1len);
6171 * Encrypt it with the given RSA key.
6173 outstrlen = (klen + 7) / 8;
6174 outstr = snewn(outstrlen, unsigned char);
6175 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6176 outstr, outstrlen, s->rsakey);
6179 * And send it off in a return packet.
6181 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6182 ssh2_pkt_addstring_start(s->pktout);
6183 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6184 ssh2_pkt_send_noqueue(ssh, s->pktout);
6186 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6193 ssh_rsakex_freekey(s->rsakey);
6195 crWaitUntilV(pktin);
6196 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6197 sfree(s->rsakeydata);
6198 bombout(("expected signature packet from server"));
6202 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6204 sfree(s->rsakeydata);
6207 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6208 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6209 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6211 ssh->kex_ctx = NULL;
6214 debug(("Exchange hash is:\n"));
6215 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6219 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6220 (char *)s->exchange_hash,
6221 ssh->kex->hash->hlen)) {
6222 bombout(("Server's host key did not match the signature supplied"));
6227 * Authenticate remote host: verify host key. (We've already
6228 * checked the signature of the exchange hash.)
6230 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6231 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6232 ssh_set_frozen(ssh, 1);
6233 s->dlgret = verify_ssh_host_key(ssh->frontend,
6234 ssh->savedhost, ssh->savedport,
6235 ssh->hostkey->keytype, s->keystr,
6237 ssh_dialog_callback, ssh);
6238 if (s->dlgret < 0) {
6242 bombout(("Unexpected data from server while waiting"
6243 " for user host key response"));
6246 } while (pktin || inlen > 0);
6247 s->dlgret = ssh->user_response;
6249 ssh_set_frozen(ssh, 0);
6250 if (s->dlgret == 0) {
6251 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6255 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6256 logevent("Host key fingerprint is:");
6257 logevent(s->fingerprint);
6259 sfree(s->fingerprint);
6261 ssh->hostkey->freekey(s->hkey);
6264 * The exchange hash from the very first key exchange is also
6265 * the session id, used in session key construction and
6268 if (!s->got_session_id) {
6269 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6270 memcpy(ssh->v2_session_id, s->exchange_hash,
6271 sizeof(s->exchange_hash));
6272 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6273 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6274 s->got_session_id = TRUE;
6278 * Send SSH2_MSG_NEWKEYS.
6280 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6281 ssh2_pkt_send_noqueue(ssh, s->pktout);
6282 ssh->outgoing_data_size = 0; /* start counting from here */
6285 * We've sent client NEWKEYS, so create and initialise
6286 * client-to-server session keys.
6288 if (ssh->cs_cipher_ctx)
6289 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6290 ssh->cscipher = s->cscipher_tobe;
6291 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6293 if (ssh->cs_mac_ctx)
6294 ssh->csmac->free_context(ssh->cs_mac_ctx);
6295 ssh->csmac = s->csmac_tobe;
6296 ssh->cs_mac_ctx = ssh->csmac->make_context();
6298 if (ssh->cs_comp_ctx)
6299 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6300 ssh->cscomp = s->cscomp_tobe;
6301 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6304 * Set IVs on client-to-server keys. Here we use the exchange
6305 * hash from the _first_ key exchange.
6308 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6309 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6310 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6311 assert((ssh->cscipher->keylen+7) / 8 <=
6312 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6313 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6314 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6315 assert(ssh->cscipher->blksize <=
6316 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6317 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6318 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6319 assert(ssh->csmac->len <=
6320 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6321 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6322 smemclr(keyspace, sizeof(keyspace));
6325 logeventf(ssh, "Initialised %.200s client->server encryption",
6326 ssh->cscipher->text_name);
6327 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6328 ssh->csmac->text_name);
6329 if (ssh->cscomp->text_name)
6330 logeventf(ssh, "Initialised %s compression",
6331 ssh->cscomp->text_name);
6334 * Now our end of the key exchange is complete, we can send all
6335 * our queued higher-layer packets.
6337 ssh->queueing = FALSE;
6338 ssh2_pkt_queuesend(ssh);
6341 * Expect SSH2_MSG_NEWKEYS from server.
6343 crWaitUntilV(pktin);
6344 if (pktin->type != SSH2_MSG_NEWKEYS) {
6345 bombout(("expected new-keys packet from server"));
6348 ssh->incoming_data_size = 0; /* start counting from here */
6351 * We've seen server NEWKEYS, so create and initialise
6352 * server-to-client session keys.
6354 if (ssh->sc_cipher_ctx)
6355 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6356 ssh->sccipher = s->sccipher_tobe;
6357 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6359 if (ssh->sc_mac_ctx)
6360 ssh->scmac->free_context(ssh->sc_mac_ctx);
6361 ssh->scmac = s->scmac_tobe;
6362 ssh->sc_mac_ctx = ssh->scmac->make_context();
6364 if (ssh->sc_comp_ctx)
6365 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6366 ssh->sccomp = s->sccomp_tobe;
6367 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6370 * Set IVs on server-to-client keys. Here we use the exchange
6371 * hash from the _first_ key exchange.
6374 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6375 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6376 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6377 assert((ssh->sccipher->keylen+7) / 8 <=
6378 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6379 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6380 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6381 assert(ssh->sccipher->blksize <=
6382 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6383 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6384 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6385 assert(ssh->scmac->len <=
6386 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6387 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6388 smemclr(keyspace, sizeof(keyspace));
6390 logeventf(ssh, "Initialised %.200s server->client encryption",
6391 ssh->sccipher->text_name);
6392 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6393 ssh->scmac->text_name);
6394 if (ssh->sccomp->text_name)
6395 logeventf(ssh, "Initialised %s decompression",
6396 ssh->sccomp->text_name);
6399 * Free shared secret.
6404 * Key exchange is over. Loop straight back round if we have a
6405 * deferred rekey reason.
6407 if (ssh->deferred_rekey_reason) {
6408 logevent(ssh->deferred_rekey_reason);
6410 ssh->deferred_rekey_reason = NULL;
6411 goto begin_key_exchange;
6415 * Otherwise, schedule a timer for our next rekey.
6417 ssh->kex_in_progress = FALSE;
6418 ssh->last_rekey = GETTICKCOUNT();
6419 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6420 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6424 * Now we're encrypting. Begin returning 1 to the protocol main
6425 * function so that other things can run on top of the
6426 * transport. If we ever see a KEXINIT, we must go back to the
6429 * We _also_ go back to the start if we see pktin==NULL and
6430 * inlen negative, because this is a special signal meaning
6431 * `initiate client-driven rekey', and `in' contains a message
6432 * giving the reason for the rekey.
6434 * inlen==-1 means always initiate a rekey;
6435 * inlen==-2 means that userauth has completed successfully and
6436 * we should consider rekeying (for delayed compression).
6438 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6439 (!pktin && inlen < 0))) {
6441 if (!ssh->protocol_initial_phase_done) {
6442 ssh->protocol_initial_phase_done = TRUE;
6444 * Allow authconn to initialise itself.
6446 do_ssh2_authconn(ssh, NULL, 0, NULL);
6451 logevent("Server initiated key re-exchange");
6455 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6456 * delayed compression, if it's available.
6458 * draft-miller-secsh-compression-delayed-00 says that you
6459 * negotiate delayed compression in the first key exchange, and
6460 * both sides start compressing when the server has sent
6461 * USERAUTH_SUCCESS. This has a race condition -- the server
6462 * can't know when the client has seen it, and thus which incoming
6463 * packets it should treat as compressed.
6465 * Instead, we do the initial key exchange without offering the
6466 * delayed methods, but note if the server offers them; when we
6467 * get here, if a delayed method was available that was higher
6468 * on our list than what we got, we initiate a rekey in which we
6469 * _do_ list the delayed methods (and hopefully get it as a
6470 * result). Subsequent rekeys will do the same.
6472 assert(!s->userauth_succeeded); /* should only happen once */
6473 s->userauth_succeeded = TRUE;
6474 if (!s->pending_compression)
6475 /* Can't see any point rekeying. */
6476 goto wait_for_rekey; /* this is utterly horrid */
6477 /* else fall through to rekey... */
6478 s->pending_compression = FALSE;
6481 * Now we've decided to rekey.
6483 * Special case: if the server bug is set that doesn't
6484 * allow rekeying, we give a different log message and
6485 * continue waiting. (If such a server _initiates_ a rekey,
6486 * we process it anyway!)
6488 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6489 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6491 /* Reset the counters, so that at least this message doesn't
6492 * hit the event log _too_ often. */
6493 ssh->outgoing_data_size = 0;
6494 ssh->incoming_data_size = 0;
6495 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6497 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6500 goto wait_for_rekey; /* this is still utterly horrid */
6502 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6505 goto begin_key_exchange;
6511 * Add data to an SSH-2 channel output buffer.
6513 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6516 bufchain_add(&c->v.v2.outbuffer, buf, len);
6520 * Attempt to send data on an SSH-2 channel.
6522 static int ssh2_try_send(struct ssh_channel *c)
6525 struct Packet *pktout;
6528 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6531 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6532 if ((unsigned)len > c->v.v2.remwindow)
6533 len = c->v.v2.remwindow;
6534 if ((unsigned)len > c->v.v2.remmaxpkt)
6535 len = c->v.v2.remmaxpkt;
6536 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6537 ssh2_pkt_adduint32(pktout, c->remoteid);
6538 ssh2_pkt_addstring_start(pktout);
6539 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6540 ssh2_pkt_addstring_data(pktout, data, len);
6541 end_log_omission(ssh, pktout);
6542 ssh2_pkt_send(ssh, pktout);
6543 bufchain_consume(&c->v.v2.outbuffer, len);
6544 c->v.v2.remwindow -= len;
6548 * After having sent as much data as we can, return the amount
6551 ret = bufchain_size(&c->v.v2.outbuffer);
6554 * And if there's no data pending but we need to send an EOF, send
6557 if (!ret && c->pending_eof)
6558 ssh_channel_try_eof(c);
6563 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6566 if (c->closes & CLOSES_SENT_EOF)
6567 return; /* don't send on channels we've EOFed */
6568 bufsize = ssh2_try_send(c);
6571 case CHAN_MAINSESSION:
6572 /* stdin need not receive an unthrottle
6573 * notification since it will be polled */
6576 x11_unthrottle(c->u.x11.s);
6579 /* agent sockets are request/response and need no
6580 * buffer management */
6583 pfd_unthrottle(c->u.pfd.s);
6590 * Set up most of a new ssh_channel for SSH-2.
6592 static void ssh2_channel_init(struct ssh_channel *c)
6595 c->localid = alloc_channel_id(ssh);
6597 c->pending_eof = FALSE;
6598 c->throttling_conn = FALSE;
6599 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6600 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6601 c->v.v2.chanreq_head = NULL;
6602 c->v.v2.throttle_state = UNTHROTTLED;
6603 bufchain_init(&c->v.v2.outbuffer);
6607 * Construct the common parts of a CHANNEL_OPEN.
6609 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
6611 struct Packet *pktout;
6613 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6614 ssh2_pkt_addstring(pktout, type);
6615 ssh2_pkt_adduint32(pktout, c->localid);
6616 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
6617 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6622 * CHANNEL_FAILURE doesn't come with any indication of what message
6623 * caused it, so we have to keep track of the outstanding
6624 * CHANNEL_REQUESTs ourselves.
6626 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
6627 cchandler_fn_t handler, void *ctx)
6629 struct outstanding_channel_request *ocr =
6630 snew(struct outstanding_channel_request);
6632 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6633 ocr->handler = handler;
6636 if (!c->v.v2.chanreq_head)
6637 c->v.v2.chanreq_head = ocr;
6639 c->v.v2.chanreq_tail->next = ocr;
6640 c->v.v2.chanreq_tail = ocr;
6644 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6645 * NULL then a reply will be requested and the handler will be called
6646 * when it arrives. The returned packet is ready to have any
6647 * request-specific data added and be sent. Note that if a handler is
6648 * provided, it's essential that the request actually be sent.
6650 * The handler will usually be passed the response packet in pktin.
6651 * If pktin is NULL, this means that no reply will ever be forthcoming
6652 * (e.g. because the entire connection is being destroyed) and the
6653 * handler should free any storage it's holding.
6655 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
6656 cchandler_fn_t handler, void *ctx)
6658 struct Packet *pktout;
6660 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6661 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6662 ssh2_pkt_adduint32(pktout, c->remoteid);
6663 ssh2_pkt_addstring(pktout, type);
6664 ssh2_pkt_addbool(pktout, handler != NULL);
6665 if (handler != NULL)
6666 ssh2_queue_chanreq_handler(c, handler, ctx);
6671 * Potentially enlarge the window on an SSH-2 channel.
6673 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
6675 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6680 * Never send WINDOW_ADJUST for a channel that the remote side has
6681 * already sent EOF on; there's no point, since it won't be
6682 * sending any more data anyway. Ditto if _we've_ already sent
6685 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6689 * If the remote end has a habit of ignoring maxpkt, limit the
6690 * window so that it has no choice (assuming it doesn't ignore the
6693 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6694 newwin = OUR_V2_MAXPKT;
6697 * Only send a WINDOW_ADJUST if there's significantly more window
6698 * available than the other end thinks there is. This saves us
6699 * sending a WINDOW_ADJUST for every character in a shell session.
6701 * "Significant" is arbitrarily defined as half the window size.
6703 if (newwin / 2 >= c->v.v2.locwindow) {
6704 struct Packet *pktout;
6708 * In order to keep track of how much window the client
6709 * actually has available, we'd like it to acknowledge each
6710 * WINDOW_ADJUST. We can't do that directly, so we accompany
6711 * it with a CHANNEL_REQUEST that has to be acknowledged.
6713 * This is only necessary if we're opening the window wide.
6714 * If we're not, then throughput is being constrained by
6715 * something other than the maximum window size anyway.
6717 if (newwin == c->v.v2.locmaxwin &&
6718 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6719 up = snew(unsigned);
6720 *up = newwin - c->v.v2.locwindow;
6721 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
6722 ssh2_handle_winadj_response, up);
6723 ssh2_pkt_send(ssh, pktout);
6725 if (c->v.v2.throttle_state != UNTHROTTLED)
6726 c->v.v2.throttle_state = UNTHROTTLING;
6728 /* Pretend the WINDOW_ADJUST was acked immediately. */
6729 c->v.v2.remlocwin = newwin;
6730 c->v.v2.throttle_state = THROTTLED;
6732 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6733 ssh2_pkt_adduint32(pktout, c->remoteid);
6734 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6735 ssh2_pkt_send(ssh, pktout);
6736 c->v.v2.locwindow = newwin;
6741 * Find the channel associated with a message. If there's no channel,
6742 * or it's not properly open, make a noise about it and return NULL.
6744 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6746 unsigned localid = ssh_pkt_getuint32(pktin);
6747 struct ssh_channel *c;
6749 c = find234(ssh->channels, &localid, ssh_channelfind);
6751 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6752 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6753 char *buf = dupprintf("Received %s for %s channel %u",
6754 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6756 c ? "half-open" : "nonexistent", localid);
6757 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6764 static void ssh2_handle_winadj_response(struct ssh_channel *c,
6765 struct Packet *pktin, void *ctx)
6767 unsigned *sizep = ctx;
6770 * Winadj responses should always be failures. However, at least
6771 * one server ("boks_sshd") is known to return SUCCESS for channel
6772 * requests it's never heard of, such as "winadj@putty". Raised
6773 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6774 * life, we don't worry about what kind of response we got.
6777 c->v.v2.remlocwin += *sizep;
6780 * winadj messages are only sent when the window is fully open, so
6781 * if we get an ack of one, we know any pending unthrottle is
6784 if (c->v.v2.throttle_state == UNTHROTTLING)
6785 c->v.v2.throttle_state = UNTHROTTLED;
6788 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
6790 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
6791 struct outstanding_channel_request *ocr;
6794 ocr = c->v.v2.chanreq_head;
6796 ssh2_msg_unexpected(ssh, pktin);
6799 ocr->handler(c, pktin, ocr->ctx);
6800 c->v.v2.chanreq_head = ocr->next;
6803 * We may now initiate channel-closing procedures, if that
6804 * CHANNEL_REQUEST was the last thing outstanding before we send
6807 ssh2_channel_check_close(c);
6810 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6812 struct ssh_channel *c;
6813 c = ssh2_channel_msg(ssh, pktin);
6816 if (!(c->closes & CLOSES_SENT_EOF)) {
6817 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6818 ssh2_try_send_and_unthrottle(ssh, c);
6822 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6826 struct ssh_channel *c;
6827 c = ssh2_channel_msg(ssh, pktin);
6830 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6831 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6832 return; /* extended but not stderr */
6833 ssh_pkt_getstring(pktin, &data, &length);
6836 c->v.v2.locwindow -= length;
6837 c->v.v2.remlocwin -= length;
6839 case CHAN_MAINSESSION:
6841 from_backend(ssh->frontend, pktin->type ==
6842 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6846 bufsize = x11_send(c->u.x11.s, data, length);
6849 bufsize = pfd_send(c->u.pfd.s, data, length);
6852 while (length > 0) {
6853 if (c->u.a.lensofar < 4) {
6854 unsigned int l = min(4 - c->u.a.lensofar,
6856 memcpy(c->u.a.msglen + c->u.a.lensofar,
6860 c->u.a.lensofar += l;
6862 if (c->u.a.lensofar == 4) {
6864 4 + GET_32BIT(c->u.a.msglen);
6865 c->u.a.message = snewn(c->u.a.totallen,
6867 memcpy(c->u.a.message, c->u.a.msglen, 4);
6869 if (c->u.a.lensofar >= 4 && length > 0) {
6871 min(c->u.a.totallen - c->u.a.lensofar,
6873 memcpy(c->u.a.message + c->u.a.lensofar,
6877 c->u.a.lensofar += l;
6879 if (c->u.a.lensofar == c->u.a.totallen) {
6882 c->u.a.outstanding_requests++;
6883 if (agent_query(c->u.a.message,
6886 ssh_agentf_callback, c))
6887 ssh_agentf_callback(c, reply, replylen);
6888 sfree(c->u.a.message);
6889 c->u.a.message = NULL;
6890 c->u.a.lensofar = 0;
6897 * If it looks like the remote end hit the end of its window,
6898 * and we didn't want it to do that, think about using a
6901 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6902 c->v.v2.locmaxwin < 0x40000000)
6903 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6905 * If we are not buffering too much data,
6906 * enlarge the window again at the remote side.
6907 * If we are buffering too much, we may still
6908 * need to adjust the window if the server's
6911 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6912 c->v.v2.locmaxwin - bufsize : 0);
6914 * If we're either buffering way too much data, or if we're
6915 * buffering anything at all and we're in "simple" mode,
6916 * throttle the whole channel.
6918 if ((bufsize > c->v.v2.locmaxwin ||
6919 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6920 !c->throttling_conn) {
6921 c->throttling_conn = 1;
6922 ssh_throttle_conn(ssh, +1);
6927 static void ssh_channel_destroy(struct ssh_channel *c)
6932 case CHAN_MAINSESSION:
6933 ssh->mainchan = NULL;
6934 update_specials_menu(ssh->frontend);
6937 if (c->u.x11.s != NULL)
6938 x11_close(c->u.x11.s);
6939 logevent("Forwarded X11 connection terminated");
6942 sfree(c->u.a.message);
6945 if (c->u.pfd.s != NULL)
6946 pfd_close(c->u.pfd.s);
6947 logevent("Forwarded port closed");
6951 del234(ssh->channels, c);
6952 if (ssh->version == 2) {
6953 bufchain_clear(&c->v.v2.outbuffer);
6954 assert(c->v.v2.chanreq_head == NULL);
6959 * See if that was the last channel left open.
6960 * (This is only our termination condition if we're
6961 * not running in -N mode.)
6963 if (ssh->version == 2 &&
6964 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6965 count234(ssh->channels) == 0) {
6967 * We used to send SSH_MSG_DISCONNECT here,
6968 * because I'd believed that _every_ conforming
6969 * SSH-2 connection had to end with a disconnect
6970 * being sent by at least one side; apparently
6971 * I was wrong and it's perfectly OK to
6972 * unceremoniously slam the connection shut
6973 * when you're done, and indeed OpenSSH feels
6974 * this is more polite than sending a
6975 * DISCONNECT. So now we don't.
6977 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6981 static void ssh2_channel_check_close(struct ssh_channel *c)
6984 struct Packet *pktout;
6986 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
6987 c->type == CHAN_ZOMBIE) &&
6988 !c->v.v2.chanreq_head &&
6989 !(c->closes & CLOSES_SENT_CLOSE)) {
6991 * We have both sent and received EOF (or the channel is a
6992 * zombie), and we have no outstanding channel requests, which
6993 * means the channel is in final wind-up. But we haven't sent
6994 * CLOSE, so let's do so now.
6996 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6997 ssh2_pkt_adduint32(pktout, c->remoteid);
6998 ssh2_pkt_send(ssh, pktout);
6999 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7002 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7003 assert(c->v.v2.chanreq_head == NULL);
7005 * We have both sent and received CLOSE, which means we're
7006 * completely done with the channel.
7008 ssh_channel_destroy(c);
7012 static void ssh2_channel_got_eof(struct ssh_channel *c)
7014 if (c->closes & CLOSES_RCVD_EOF)
7015 return; /* already seen EOF */
7016 c->closes |= CLOSES_RCVD_EOF;
7018 if (c->type == CHAN_X11) {
7019 x11_send_eof(c->u.x11.s);
7020 } else if (c->type == CHAN_AGENT) {
7021 if (c->u.a.outstanding_requests == 0) {
7022 /* Manufacture an outgoing EOF in response to the incoming one. */
7023 sshfwd_write_eof(c);
7025 } else if (c->type == CHAN_SOCKDATA) {
7026 pfd_send_eof(c->u.pfd.s);
7027 } else if (c->type == CHAN_MAINSESSION) {
7030 if (!ssh->sent_console_eof &&
7031 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7033 * Either from_backend_eof told us that the front end
7034 * wants us to close the outgoing side of the connection
7035 * as soon as we see EOF from the far end, or else we've
7036 * unilaterally decided to do that because we've allocated
7037 * a remote pty and hence EOF isn't a particularly
7038 * meaningful concept.
7040 sshfwd_write_eof(c);
7042 ssh->sent_console_eof = TRUE;
7045 ssh2_channel_check_close(c);
7048 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7050 struct ssh_channel *c;
7052 c = ssh2_channel_msg(ssh, pktin);
7055 ssh2_channel_got_eof(c);
7058 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7060 struct ssh_channel *c;
7062 c = ssh2_channel_msg(ssh, pktin);
7067 * When we receive CLOSE on a channel, we assume it comes with an
7068 * implied EOF if we haven't seen EOF yet.
7070 ssh2_channel_got_eof(c);
7073 * And we also send an outgoing EOF, if we haven't already, on the
7074 * assumption that CLOSE is a pretty forceful announcement that
7075 * the remote side is doing away with the entire channel. (If it
7076 * had wanted to send us EOF and continue receiving data from us,
7077 * it would have just sent CHANNEL_EOF.)
7079 if (!(c->closes & CLOSES_SENT_EOF)) {
7081 * Make sure we don't read any more from whatever our local
7082 * data source is for this channel.
7085 case CHAN_MAINSESSION:
7086 ssh->send_ok = 0; /* stop trying to read from stdin */
7089 x11_override_throttle(c->u.x11.s, 1);
7092 pfd_override_throttle(c->u.pfd.s, 1);
7097 * Abandon any buffered data we still wanted to send to this
7098 * channel. Receiving a CHANNEL_CLOSE is an indication that
7099 * the server really wants to get on and _destroy_ this
7100 * channel, and it isn't going to send us any further
7101 * WINDOW_ADJUSTs to permit us to send pending stuff.
7103 bufchain_clear(&c->v.v2.outbuffer);
7106 * Send outgoing EOF.
7108 sshfwd_write_eof(c);
7112 * Now process the actual close.
7114 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7115 c->closes |= CLOSES_RCVD_CLOSE;
7116 ssh2_channel_check_close(c);
7120 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7122 struct ssh_channel *c;
7124 c = ssh2_channel_msg(ssh, pktin);
7127 if (c->type != CHAN_SOCKDATA_DORMANT)
7128 return; /* dunno why they're confirming this */
7129 c->remoteid = ssh_pkt_getuint32(pktin);
7130 c->halfopen = FALSE;
7131 c->type = CHAN_SOCKDATA;
7132 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7133 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7135 pfd_confirm(c->u.pfd.s);
7137 ssh_channel_try_eof(c);
7140 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7142 static const char *const reasons[] = {
7143 "<unknown reason code>",
7144 "Administratively prohibited",
7146 "Unknown channel type",
7147 "Resource shortage",
7149 unsigned reason_code;
7150 char *reason_string;
7152 struct ssh_channel *c;
7153 c = ssh2_channel_msg(ssh, pktin);
7156 if (c->type != CHAN_SOCKDATA_DORMANT)
7157 return; /* dunno why they're failing this */
7159 reason_code = ssh_pkt_getuint32(pktin);
7160 if (reason_code >= lenof(reasons))
7161 reason_code = 0; /* ensure reasons[reason_code] in range */
7162 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7163 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7164 reasons[reason_code], reason_length, reason_string);
7166 pfd_close(c->u.pfd.s);
7168 del234(ssh->channels, c);
7172 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7175 int typelen, want_reply;
7176 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7177 struct ssh_channel *c;
7178 struct Packet *pktout;
7180 c = ssh2_channel_msg(ssh, pktin);
7183 ssh_pkt_getstring(pktin, &type, &typelen);
7184 want_reply = ssh2_pkt_getbool(pktin);
7187 * Having got the channel number, we now look at
7188 * the request type string to see if it's something
7191 if (c == ssh->mainchan) {
7193 * We recognise "exit-status" and "exit-signal" on
7194 * the primary channel.
7196 if (typelen == 11 &&
7197 !memcmp(type, "exit-status", 11)) {
7199 ssh->exitcode = ssh_pkt_getuint32(pktin);
7200 logeventf(ssh, "Server sent command exit status %d",
7202 reply = SSH2_MSG_CHANNEL_SUCCESS;
7204 } else if (typelen == 11 &&
7205 !memcmp(type, "exit-signal", 11)) {
7207 int is_plausible = TRUE, is_int = FALSE;
7208 char *fmt_sig = "", *fmt_msg = "";
7210 int msglen = 0, core = FALSE;
7211 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7212 * provide an `int' for the signal, despite its
7213 * having been a `string' in the drafts of RFC 4254 since at
7214 * least 2001. (Fixed in session.c 1.147.) Try to
7215 * infer which we can safely parse it as. */
7217 unsigned char *p = pktin->body +
7219 long len = pktin->length - pktin->savedpos;
7220 unsigned long num = GET_32BIT(p); /* what is it? */
7221 /* If it's 0, it hardly matters; assume string */
7225 int maybe_int = FALSE, maybe_str = FALSE;
7226 #define CHECK_HYPOTHESIS(offset, result) \
7229 int q = toint(offset); \
7230 if (q >= 0 && q+4 <= len) { \
7231 q = toint(q + 4 + GET_32BIT(p+q)); \
7232 if (q >= 0 && q+4 <= len && \
7233 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7238 CHECK_HYPOTHESIS(4+1, maybe_int);
7239 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7240 #undef CHECK_HYPOTHESIS
7241 if (maybe_int && !maybe_str)
7243 else if (!maybe_int && maybe_str)
7246 /* Crikey. Either or neither. Panic. */
7247 is_plausible = FALSE;
7250 ssh->exitcode = 128; /* means `unknown signal' */
7253 /* Old non-standard OpenSSH. */
7254 int signum = ssh_pkt_getuint32(pktin);
7255 fmt_sig = dupprintf(" %d", signum);
7256 ssh->exitcode = 128 + signum;
7258 /* As per RFC 4254. */
7261 ssh_pkt_getstring(pktin, &sig, &siglen);
7262 /* Signal name isn't supposed to be blank, but
7263 * let's cope gracefully if it is. */
7265 fmt_sig = dupprintf(" \"%.*s\"",
7270 * Really hideous method of translating the
7271 * signal description back into a locally
7272 * meaningful number.
7277 #define TRANSLATE_SIGNAL(s) \
7278 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7279 ssh->exitcode = 128 + SIG ## s
7281 TRANSLATE_SIGNAL(ABRT);
7284 TRANSLATE_SIGNAL(ALRM);
7287 TRANSLATE_SIGNAL(FPE);
7290 TRANSLATE_SIGNAL(HUP);
7293 TRANSLATE_SIGNAL(ILL);
7296 TRANSLATE_SIGNAL(INT);
7299 TRANSLATE_SIGNAL(KILL);
7302 TRANSLATE_SIGNAL(PIPE);
7305 TRANSLATE_SIGNAL(QUIT);
7308 TRANSLATE_SIGNAL(SEGV);
7311 TRANSLATE_SIGNAL(TERM);
7314 TRANSLATE_SIGNAL(USR1);
7317 TRANSLATE_SIGNAL(USR2);
7319 #undef TRANSLATE_SIGNAL
7321 ssh->exitcode = 128;
7323 core = ssh2_pkt_getbool(pktin);
7324 ssh_pkt_getstring(pktin, &msg, &msglen);
7326 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7328 /* ignore lang tag */
7329 } /* else don't attempt to parse */
7330 logeventf(ssh, "Server exited on signal%s%s%s",
7331 fmt_sig, core ? " (core dumped)" : "",
7333 if (*fmt_sig) sfree(fmt_sig);
7334 if (*fmt_msg) sfree(fmt_msg);
7335 reply = SSH2_MSG_CHANNEL_SUCCESS;
7340 * This is a channel request we don't know
7341 * about, so we now either ignore the request
7342 * or respond with CHANNEL_FAILURE, depending
7345 reply = SSH2_MSG_CHANNEL_FAILURE;
7348 pktout = ssh2_pkt_init(reply);
7349 ssh2_pkt_adduint32(pktout, c->remoteid);
7350 ssh2_pkt_send(ssh, pktout);
7354 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7357 int typelen, want_reply;
7358 struct Packet *pktout;
7360 ssh_pkt_getstring(pktin, &type, &typelen);
7361 want_reply = ssh2_pkt_getbool(pktin);
7364 * We currently don't support any global requests
7365 * at all, so we either ignore the request or
7366 * respond with REQUEST_FAILURE, depending on
7370 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7371 ssh2_pkt_send(ssh, pktout);
7375 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7383 struct ssh_channel *c;
7384 unsigned remid, winsize, pktsize;
7385 struct Packet *pktout;
7387 ssh_pkt_getstring(pktin, &type, &typelen);
7388 c = snew(struct ssh_channel);
7391 remid = ssh_pkt_getuint32(pktin);
7392 winsize = ssh_pkt_getuint32(pktin);
7393 pktsize = ssh_pkt_getuint32(pktin);
7395 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7399 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7400 addrstr = snewn(peeraddrlen+1, char);
7401 memcpy(addrstr, peeraddr, peeraddrlen);
7402 addrstr[peeraddrlen] = '\0';
7403 peerport = ssh_pkt_getuint32(pktin);
7405 logeventf(ssh, "Received X11 connect request from %s:%d",
7408 if (!ssh->X11_fwd_enabled)
7409 error = "X11 forwarding is not enabled";
7410 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7411 addrstr, peerport, ssh->conf)) != NULL) {
7412 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7413 error = "Unable to open an X11 connection";
7415 logevent("Opening X11 forward connection succeeded");
7420 } else if (typelen == 15 &&
7421 !memcmp(type, "forwarded-tcpip", 15)) {
7422 struct ssh_rportfwd pf, *realpf;
7425 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7426 pf.sport = ssh_pkt_getuint32(pktin);
7427 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7428 peerport = ssh_pkt_getuint32(pktin);
7429 realpf = find234(ssh->rportfwds, &pf, NULL);
7430 logeventf(ssh, "Received remote port %d open request "
7431 "from %s:%d", pf.sport, peeraddr, peerport);
7432 if (realpf == NULL) {
7433 error = "Remote port is not recognised";
7435 const char *e = pfd_newconnect(&c->u.pfd.s,
7439 realpf->pfrec->addressfamily);
7440 logeventf(ssh, "Attempting to forward remote port to "
7441 "%s:%d", realpf->dhost, realpf->dport);
7443 logeventf(ssh, "Port open failed: %s", e);
7444 error = "Port open failed";
7446 logevent("Forwarded port opened successfully");
7447 c->type = CHAN_SOCKDATA;
7450 } else if (typelen == 22 &&
7451 !memcmp(type, "auth-agent@openssh.com", 22)) {
7452 if (!ssh->agentfwd_enabled)
7453 error = "Agent forwarding is not enabled";
7455 c->type = CHAN_AGENT; /* identify channel type */
7456 c->u.a.lensofar = 0;
7457 c->u.a.outstanding_requests = 0;
7460 error = "Unsupported channel type requested";
7463 c->remoteid = remid;
7464 c->halfopen = FALSE;
7466 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7467 ssh2_pkt_adduint32(pktout, c->remoteid);
7468 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7469 ssh2_pkt_addstring(pktout, error);
7470 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7471 ssh2_pkt_send(ssh, pktout);
7472 logeventf(ssh, "Rejected channel open: %s", error);
7475 ssh2_channel_init(c);
7476 c->v.v2.remwindow = winsize;
7477 c->v.v2.remmaxpkt = pktsize;
7478 add234(ssh->channels, c);
7479 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7480 ssh2_pkt_adduint32(pktout, c->remoteid);
7481 ssh2_pkt_adduint32(pktout, c->localid);
7482 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7483 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7484 ssh2_pkt_send(ssh, pktout);
7489 * Buffer banner messages for later display at some convenient point,
7490 * if we're going to display them.
7492 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7494 /* Arbitrary limit to prevent unbounded inflation of buffer */
7495 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7496 bufchain_size(&ssh->banner) <= 131072) {
7497 char *banner = NULL;
7499 ssh_pkt_getstring(pktin, &banner, &size);
7501 bufchain_add(&ssh->banner, banner, size);
7505 /* Helper function to deal with sending tty modes for "pty-req" */
7506 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7508 struct Packet *pktout = (struct Packet *)data;
7510 unsigned int arg = 0;
7511 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7512 if (i == lenof(ssh_ttymodes)) return;
7513 switch (ssh_ttymodes[i].type) {
7515 arg = ssh_tty_parse_specchar(val);
7518 arg = ssh_tty_parse_boolean(val);
7521 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7522 ssh2_pkt_adduint32(pktout, arg);
7525 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
7528 struct ssh2_setup_x11_state {
7532 struct Packet *pktout;
7533 crStateP(ssh2_setup_x11_state, ctx);
7537 logevent("Requesting X11 forwarding");
7538 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
7540 ssh2_pkt_addbool(pktout, 0); /* many connections */
7541 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthprotoname);
7543 * Note that while we blank the X authentication data here, we don't
7544 * take any special action to blank the start of an X11 channel,
7545 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
7546 * without having session blanking enabled is likely to leak your
7547 * cookie into the log.
7549 dont_log_password(ssh, pktout, PKTLOG_BLANK);
7550 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthdatastring);
7551 end_log_omission(ssh, pktout);
7552 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
7553 ssh2_pkt_send(ssh, pktout);
7555 /* Wait to be called back with either a response packet, or NULL
7556 * meaning clean up and free our data */
7560 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7561 logevent("X11 forwarding enabled");
7562 ssh->X11_fwd_enabled = TRUE;
7564 logevent("X11 forwarding refused");
7570 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
7573 struct ssh2_setup_agent_state {
7577 struct Packet *pktout;
7578 crStateP(ssh2_setup_agent_state, ctx);
7582 logevent("Requesting OpenSSH-style agent forwarding");
7583 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
7584 ssh2_setup_agent, s);
7585 ssh2_pkt_send(ssh, pktout);
7587 /* Wait to be called back with either a response packet, or NULL
7588 * meaning clean up and free our data */
7592 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7593 logevent("Agent forwarding enabled");
7594 ssh->agentfwd_enabled = TRUE;
7596 logevent("Agent forwarding refused");
7602 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
7605 struct ssh2_setup_pty_state {
7609 struct Packet *pktout;
7610 crStateP(ssh2_setup_pty_state, ctx);
7614 /* Unpick the terminal-speed string. */
7615 /* XXX perhaps we should allow no speeds to be sent. */
7616 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7617 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
7618 /* Build the pty request. */
7619 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
7621 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
7622 ssh2_pkt_adduint32(pktout, ssh->term_width);
7623 ssh2_pkt_adduint32(pktout, ssh->term_height);
7624 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
7625 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
7626 ssh2_pkt_addstring_start(pktout);
7627 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
7628 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
7629 ssh2_pkt_adduint32(pktout, ssh->ispeed);
7630 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
7631 ssh2_pkt_adduint32(pktout, ssh->ospeed);
7632 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
7633 ssh2_pkt_send(ssh, pktout);
7634 ssh->state = SSH_STATE_INTERMED;
7636 /* Wait to be called back with either a response packet, or NULL
7637 * meaning clean up and free our data */
7641 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7642 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7643 ssh->ospeed, ssh->ispeed);
7644 ssh->got_pty = TRUE;
7646 c_write_str(ssh, "Server refused to allocate pty\r\n");
7647 ssh->editing = ssh->echoing = 1;
7654 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
7657 struct ssh2_setup_env_state {
7659 int num_env, env_left, env_ok;
7662 struct Packet *pktout;
7663 crStateP(ssh2_setup_env_state, ctx);
7668 * Send environment variables.
7670 * Simplest thing here is to send all the requests at once, and
7671 * then wait for a whole bunch of successes or failures.
7677 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
7679 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
7680 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
7681 ssh2_pkt_addstring(pktout, key);
7682 ssh2_pkt_addstring(pktout, val);
7683 ssh2_pkt_send(ssh, pktout);
7688 logeventf(ssh, "Sent %d environment variables", s->num_env);
7693 s->env_left = s->num_env;
7695 while (s->env_left > 0) {
7696 /* Wait to be called back with either a response packet,
7697 * or NULL meaning clean up and free our data */
7699 if (!pktin) goto out;
7700 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
7705 if (s->env_ok == s->num_env) {
7706 logevent("All environment variables successfully set");
7707 } else if (s->env_ok == 0) {
7708 logevent("All environment variables refused");
7709 c_write_str(ssh, "Server refused to set environment variables\r\n");
7711 logeventf(ssh, "%d environment variables refused",
7712 s->num_env - s->env_ok);
7713 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7721 * Handle the SSH-2 userauth and connection layers.
7723 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7725 do_ssh2_authconn(ssh, NULL, 0, pktin);
7728 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
7731 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
7734 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7735 struct Packet *pktin)
7737 struct do_ssh2_authconn_state {
7741 AUTH_TYPE_PUBLICKEY,
7742 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7743 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7745 AUTH_TYPE_GSSAPI, /* always QUIET */
7746 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7747 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7749 int done_service_req;
7750 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7751 int tried_pubkey_config, done_agent;
7756 int kbd_inter_refused;
7757 int we_are_in, userauth_success;
7758 prompts_t *cur_prompt;
7763 void *publickey_blob;
7764 int publickey_bloblen;
7765 int publickey_encrypted;
7766 char *publickey_algorithm;
7767 char *publickey_comment;
7768 unsigned char agent_request[5], *agent_response, *agentp;
7769 int agent_responselen;
7770 unsigned char *pkblob_in_agent;
7772 char *pkblob, *alg, *commentp;
7773 int pklen, alglen, commentlen;
7774 int siglen, retlen, len;
7775 char *q, *agentreq, *ret;
7777 struct Packet *pktout;
7780 struct ssh_gss_library *gsslib;
7781 Ssh_gss_ctx gss_ctx;
7782 Ssh_gss_buf gss_buf;
7783 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7784 Ssh_gss_name gss_srv_name;
7785 Ssh_gss_stat gss_stat;
7788 crState(do_ssh2_authconn_state);
7792 /* Register as a handler for all the messages this coroutine handles. */
7793 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7794 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7795 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7796 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7797 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7798 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7799 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7800 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7801 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7802 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7803 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7804 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7805 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7806 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7807 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7808 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7809 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7810 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7811 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7812 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7814 s->done_service_req = FALSE;
7815 s->we_are_in = s->userauth_success = FALSE;
7817 s->tried_gssapi = FALSE;
7820 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7822 * Request userauth protocol, and await a response to it.
7824 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7825 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7826 ssh2_pkt_send(ssh, s->pktout);
7827 crWaitUntilV(pktin);
7828 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7829 s->done_service_req = TRUE;
7831 if (!s->done_service_req) {
7833 * Request connection protocol directly, without authentication.
7835 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7836 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7837 ssh2_pkt_send(ssh, s->pktout);
7838 crWaitUntilV(pktin);
7839 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7840 s->we_are_in = TRUE; /* no auth required */
7842 bombout(("Server refused service request"));
7847 /* Arrange to be able to deal with any BANNERs that come in.
7848 * (We do this now as packets may come in during the next bit.) */
7849 bufchain_init(&ssh->banner);
7850 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7851 ssh2_msg_userauth_banner;
7854 * Misc one-time setup for authentication.
7856 s->publickey_blob = NULL;
7857 if (!s->we_are_in) {
7860 * Load the public half of any configured public key file
7863 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7864 if (!filename_is_null(s->keyfile)) {
7866 logeventf(ssh, "Reading private key file \"%.150s\"",
7867 filename_to_str(s->keyfile));
7868 keytype = key_type(s->keyfile);
7869 if (keytype == SSH_KEYTYPE_SSH2) {
7872 ssh2_userkey_loadpub(s->keyfile,
7873 &s->publickey_algorithm,
7874 &s->publickey_bloblen,
7875 &s->publickey_comment, &error);
7876 if (s->publickey_blob) {
7877 s->publickey_encrypted =
7878 ssh2_userkey_encrypted(s->keyfile, NULL);
7881 logeventf(ssh, "Unable to load private key (%s)",
7883 msgbuf = dupprintf("Unable to load private key file "
7884 "\"%.150s\" (%s)\r\n",
7885 filename_to_str(s->keyfile),
7887 c_write_str(ssh, msgbuf);
7892 logeventf(ssh, "Unable to use this key file (%s)",
7893 key_type_to_str(keytype));
7894 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7896 filename_to_str(s->keyfile),
7897 key_type_to_str(keytype));
7898 c_write_str(ssh, msgbuf);
7900 s->publickey_blob = NULL;
7905 * Find out about any keys Pageant has (but if there's a
7906 * public key configured, filter out all others).
7909 s->agent_response = NULL;
7910 s->pkblob_in_agent = NULL;
7911 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7915 logevent("Pageant is running. Requesting keys.");
7917 /* Request the keys held by the agent. */
7918 PUT_32BIT(s->agent_request, 1);
7919 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7920 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7921 ssh_agent_callback, ssh)) {
7925 bombout(("Unexpected data from server while"
7926 " waiting for agent response"));
7929 } while (pktin || inlen > 0);
7930 r = ssh->agent_response;
7931 s->agent_responselen = ssh->agent_response_len;
7933 s->agent_response = (unsigned char *) r;
7934 if (s->agent_response && s->agent_responselen >= 5 &&
7935 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7938 p = s->agent_response + 5;
7939 s->nkeys = toint(GET_32BIT(p));
7942 * Vet the Pageant response to ensure that the key
7943 * count and blob lengths make sense.
7946 logeventf(ssh, "Pageant response contained a negative"
7947 " key count %d", s->nkeys);
7949 goto done_agent_query;
7951 unsigned char *q = p + 4;
7952 int lenleft = s->agent_responselen - 5 - 4;
7954 for (keyi = 0; keyi < s->nkeys; keyi++) {
7955 int bloblen, commentlen;
7957 logeventf(ssh, "Pageant response was truncated");
7959 goto done_agent_query;
7961 bloblen = toint(GET_32BIT(q));
7962 if (bloblen < 0 || bloblen > lenleft) {
7963 logeventf(ssh, "Pageant response was truncated");
7965 goto done_agent_query;
7967 lenleft -= 4 + bloblen;
7969 commentlen = toint(GET_32BIT(q));
7970 if (commentlen < 0 || commentlen > lenleft) {
7971 logeventf(ssh, "Pageant response was truncated");
7973 goto done_agent_query;
7975 lenleft -= 4 + commentlen;
7976 q += 4 + commentlen;
7981 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7982 if (s->publickey_blob) {
7983 /* See if configured key is in agent. */
7984 for (keyi = 0; keyi < s->nkeys; keyi++) {
7985 s->pklen = toint(GET_32BIT(p));
7986 if (s->pklen == s->publickey_bloblen &&
7987 !memcmp(p+4, s->publickey_blob,
7988 s->publickey_bloblen)) {
7989 logeventf(ssh, "Pageant key #%d matches "
7990 "configured key file", keyi);
7992 s->pkblob_in_agent = p;
7996 p += toint(GET_32BIT(p)) + 4; /* comment */
7998 if (!s->pkblob_in_agent) {
7999 logevent("Configured key file not in Pageant");
8004 logevent("Failed to get reply from Pageant");
8012 * We repeat this whole loop, including the username prompt,
8013 * until we manage a successful authentication. If the user
8014 * types the wrong _password_, they can be sent back to the
8015 * beginning to try another username, if this is configured on.
8016 * (If they specify a username in the config, they are never
8017 * asked, even if they do give a wrong password.)
8019 * I think this best serves the needs of
8021 * - the people who have no configuration, no keys, and just
8022 * want to try repeated (username,password) pairs until they
8023 * type both correctly
8025 * - people who have keys and configuration but occasionally
8026 * need to fall back to passwords
8028 * - people with a key held in Pageant, who might not have
8029 * logged in to a particular machine before; so they want to
8030 * type a username, and then _either_ their key will be
8031 * accepted, _or_ they will type a password. If they mistype
8032 * the username they will want to be able to get back and
8035 s->got_username = FALSE;
8036 while (!s->we_are_in) {
8040 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8042 * We got a username last time round this loop, and
8043 * with change_username turned off we don't try to get
8046 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8047 int ret; /* need not be kept over crReturn */
8048 s->cur_prompt = new_prompts(ssh->frontend);
8049 s->cur_prompt->to_server = TRUE;
8050 s->cur_prompt->name = dupstr("SSH login name");
8051 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8052 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8055 crWaitUntilV(!pktin);
8056 ret = get_userpass_input(s->cur_prompt, in, inlen);
8061 * get_userpass_input() failed to get a username.
8064 free_prompts(s->cur_prompt);
8065 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8068 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8069 free_prompts(s->cur_prompt);
8072 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8073 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8074 c_write_str(ssh, stuff);
8078 s->got_username = TRUE;
8081 * Send an authentication request using method "none": (a)
8082 * just in case it succeeds, and (b) so that we know what
8083 * authentication methods we can usefully try next.
8085 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8087 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8088 ssh2_pkt_addstring(s->pktout, ssh->username);
8089 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8090 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8091 ssh2_pkt_send(ssh, s->pktout);
8092 s->type = AUTH_TYPE_NONE;
8094 s->we_are_in = FALSE;
8096 s->tried_pubkey_config = FALSE;
8097 s->kbd_inter_refused = FALSE;
8099 /* Reset agent request state. */
8100 s->done_agent = FALSE;
8101 if (s->agent_response) {
8102 if (s->pkblob_in_agent) {
8103 s->agentp = s->pkblob_in_agent;
8105 s->agentp = s->agent_response + 5 + 4;
8111 char *methods = NULL;
8115 * Wait for the result of the last authentication request.
8118 crWaitUntilV(pktin);
8120 * Now is a convenient point to spew any banner material
8121 * that we've accumulated. (This should ensure that when
8122 * we exit the auth loop, we haven't any left to deal
8126 int size = bufchain_size(&ssh->banner);
8128 * Don't show the banner if we're operating in
8129 * non-verbose non-interactive mode. (It's probably
8130 * a script, which means nobody will read the
8131 * banner _anyway_, and moreover the printing of
8132 * the banner will screw up processing on the
8133 * output of (say) plink.)
8135 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8136 char *banner = snewn(size, char);
8137 bufchain_fetch(&ssh->banner, banner, size);
8138 c_write_untrusted(ssh, banner, size);
8141 bufchain_clear(&ssh->banner);
8143 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8144 logevent("Access granted");
8145 s->we_are_in = s->userauth_success = TRUE;
8149 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8150 bombout(("Strange packet received during authentication: "
8151 "type %d", pktin->type));
8158 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8159 * we can look at the string in it and know what we can
8160 * helpfully try next.
8162 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8163 ssh_pkt_getstring(pktin, &methods, &methlen);
8164 if (!ssh2_pkt_getbool(pktin)) {
8166 * We have received an unequivocal Access
8167 * Denied. This can translate to a variety of
8168 * messages, or no message at all.
8170 * For forms of authentication which are attempted
8171 * implicitly, by which I mean without printing
8172 * anything in the window indicating that we're
8173 * trying them, we should never print 'Access
8176 * If we do print a message saying that we're
8177 * attempting some kind of authentication, it's OK
8178 * to print a followup message saying it failed -
8179 * but the message may sometimes be more specific
8180 * than simply 'Access denied'.
8182 * Additionally, if we'd just tried password
8183 * authentication, we should break out of this
8184 * whole loop so as to go back to the username
8185 * prompt (iff we're configured to allow
8186 * username change attempts).
8188 if (s->type == AUTH_TYPE_NONE) {
8190 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8191 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8192 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8193 c_write_str(ssh, "Server refused our key\r\n");
8194 logevent("Server refused our key");
8195 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8196 /* This _shouldn't_ happen except by a
8197 * protocol bug causing client and server to
8198 * disagree on what is a correct signature. */
8199 c_write_str(ssh, "Server refused public-key signature"
8200 " despite accepting key!\r\n");
8201 logevent("Server refused public-key signature"
8202 " despite accepting key!");
8203 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8204 /* quiet, so no c_write */
8205 logevent("Server refused keyboard-interactive authentication");
8206 } else if (s->type==AUTH_TYPE_GSSAPI) {
8207 /* always quiet, so no c_write */
8208 /* also, the code down in the GSSAPI block has
8209 * already logged this in the Event Log */
8210 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8211 logevent("Keyboard-interactive authentication failed");
8212 c_write_str(ssh, "Access denied\r\n");
8214 assert(s->type == AUTH_TYPE_PASSWORD);
8215 logevent("Password authentication failed");
8216 c_write_str(ssh, "Access denied\r\n");
8218 if (conf_get_int(ssh->conf, CONF_change_username)) {
8219 /* XXX perhaps we should allow
8220 * keyboard-interactive to do this too? */
8221 s->we_are_in = FALSE;
8226 c_write_str(ssh, "Further authentication required\r\n");
8227 logevent("Further authentication required");
8231 in_commasep_string("publickey", methods, methlen);
8233 in_commasep_string("password", methods, methlen);
8234 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8235 in_commasep_string("keyboard-interactive", methods, methlen);
8238 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8239 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8240 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8241 ssh->gsslibs->nlibraries > 0;
8245 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8247 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8250 * Attempt public-key authentication using a key from Pageant.
8253 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8255 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8257 /* Unpack key from agent response */
8258 s->pklen = toint(GET_32BIT(s->agentp));
8260 s->pkblob = (char *)s->agentp;
8261 s->agentp += s->pklen;
8262 s->alglen = toint(GET_32BIT(s->pkblob));
8263 s->alg = s->pkblob + 4;
8264 s->commentlen = toint(GET_32BIT(s->agentp));
8266 s->commentp = (char *)s->agentp;
8267 s->agentp += s->commentlen;
8268 /* s->agentp now points at next key, if any */
8270 /* See if server will accept it */
8271 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8272 ssh2_pkt_addstring(s->pktout, ssh->username);
8273 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8274 /* service requested */
8275 ssh2_pkt_addstring(s->pktout, "publickey");
8277 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8278 ssh2_pkt_addstring_start(s->pktout);
8279 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8280 ssh2_pkt_addstring_start(s->pktout);
8281 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8282 ssh2_pkt_send(ssh, s->pktout);
8283 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8285 crWaitUntilV(pktin);
8286 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8288 /* Offer of key refused. */
8295 if (flags & FLAG_VERBOSE) {
8296 c_write_str(ssh, "Authenticating with "
8298 c_write(ssh, s->commentp, s->commentlen);
8299 c_write_str(ssh, "\" from agent\r\n");
8303 * Server is willing to accept the key.
8304 * Construct a SIGN_REQUEST.
8306 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8307 ssh2_pkt_addstring(s->pktout, ssh->username);
8308 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8309 /* service requested */
8310 ssh2_pkt_addstring(s->pktout, "publickey");
8312 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8313 ssh2_pkt_addstring_start(s->pktout);
8314 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8315 ssh2_pkt_addstring_start(s->pktout);
8316 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8318 /* Ask agent for signature. */
8319 s->siglen = s->pktout->length - 5 + 4 +
8320 ssh->v2_session_id_len;
8321 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8323 s->len = 1; /* message type */
8324 s->len += 4 + s->pklen; /* key blob */
8325 s->len += 4 + s->siglen; /* data to sign */
8326 s->len += 4; /* flags */
8327 s->agentreq = snewn(4 + s->len, char);
8328 PUT_32BIT(s->agentreq, s->len);
8329 s->q = s->agentreq + 4;
8330 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8331 PUT_32BIT(s->q, s->pklen);
8333 memcpy(s->q, s->pkblob, s->pklen);
8335 PUT_32BIT(s->q, s->siglen);
8337 /* Now the data to be signed... */
8338 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8339 PUT_32BIT(s->q, ssh->v2_session_id_len);
8342 memcpy(s->q, ssh->v2_session_id,
8343 ssh->v2_session_id_len);
8344 s->q += ssh->v2_session_id_len;
8345 memcpy(s->q, s->pktout->data + 5,
8346 s->pktout->length - 5);
8347 s->q += s->pktout->length - 5;
8348 /* And finally the (zero) flags word. */
8350 if (!agent_query(s->agentreq, s->len + 4,
8352 ssh_agent_callback, ssh)) {
8356 bombout(("Unexpected data from server"
8357 " while waiting for agent"
8361 } while (pktin || inlen > 0);
8362 vret = ssh->agent_response;
8363 s->retlen = ssh->agent_response_len;
8368 if (s->retlen >= 9 &&
8369 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
8370 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
8371 logevent("Sending Pageant's response");
8372 ssh2_add_sigblob(ssh, s->pktout,
8373 s->pkblob, s->pklen,
8375 GET_32BIT(s->ret + 5));
8376 ssh2_pkt_send(ssh, s->pktout);
8377 s->type = AUTH_TYPE_PUBLICKEY;
8379 /* FIXME: less drastic response */
8380 bombout(("Pageant failed to answer challenge"));
8386 /* Do we have any keys left to try? */
8387 if (s->pkblob_in_agent) {
8388 s->done_agent = TRUE;
8389 s->tried_pubkey_config = TRUE;
8392 if (s->keyi >= s->nkeys)
8393 s->done_agent = TRUE;
8396 } else if (s->can_pubkey && s->publickey_blob &&
8397 !s->tried_pubkey_config) {
8399 struct ssh2_userkey *key; /* not live over crReturn */
8400 char *passphrase; /* not live over crReturn */
8402 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8404 s->tried_pubkey_config = TRUE;
8407 * Try the public key supplied in the configuration.
8409 * First, offer the public blob to see if the server is
8410 * willing to accept it.
8412 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8413 ssh2_pkt_addstring(s->pktout, ssh->username);
8414 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8415 /* service requested */
8416 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8417 ssh2_pkt_addbool(s->pktout, FALSE);
8418 /* no signature included */
8419 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8420 ssh2_pkt_addstring_start(s->pktout);
8421 ssh2_pkt_addstring_data(s->pktout,
8422 (char *)s->publickey_blob,
8423 s->publickey_bloblen);
8424 ssh2_pkt_send(ssh, s->pktout);
8425 logevent("Offered public key");
8427 crWaitUntilV(pktin);
8428 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8429 /* Key refused. Give up. */
8430 s->gotit = TRUE; /* reconsider message next loop */
8431 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8432 continue; /* process this new message */
8434 logevent("Offer of public key accepted");
8437 * Actually attempt a serious authentication using
8440 if (flags & FLAG_VERBOSE) {
8441 c_write_str(ssh, "Authenticating with public key \"");
8442 c_write_str(ssh, s->publickey_comment);
8443 c_write_str(ssh, "\"\r\n");
8447 const char *error; /* not live over crReturn */
8448 if (s->publickey_encrypted) {
8450 * Get a passphrase from the user.
8452 int ret; /* need not be kept over crReturn */
8453 s->cur_prompt = new_prompts(ssh->frontend);
8454 s->cur_prompt->to_server = FALSE;
8455 s->cur_prompt->name = dupstr("SSH key passphrase");
8456 add_prompt(s->cur_prompt,
8457 dupprintf("Passphrase for key \"%.100s\": ",
8458 s->publickey_comment),
8460 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8463 crWaitUntilV(!pktin);
8464 ret = get_userpass_input(s->cur_prompt,
8469 /* Failed to get a passphrase. Terminate. */
8470 free_prompts(s->cur_prompt);
8471 ssh_disconnect(ssh, NULL,
8472 "Unable to authenticate",
8473 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8478 dupstr(s->cur_prompt->prompts[0]->result);
8479 free_prompts(s->cur_prompt);
8481 passphrase = NULL; /* no passphrase needed */
8485 * Try decrypting the key.
8487 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8488 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8490 /* burn the evidence */
8491 smemclr(passphrase, strlen(passphrase));
8494 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8496 (key == SSH2_WRONG_PASSPHRASE)) {
8497 c_write_str(ssh, "Wrong passphrase\r\n");
8499 /* and loop again */
8501 c_write_str(ssh, "Unable to load private key (");
8502 c_write_str(ssh, error);
8503 c_write_str(ssh, ")\r\n");
8505 break; /* try something else */
8511 unsigned char *pkblob, *sigblob, *sigdata;
8512 int pkblob_len, sigblob_len, sigdata_len;
8516 * We have loaded the private key and the server
8517 * has announced that it's willing to accept it.
8518 * Hallelujah. Generate a signature and send it.
8520 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8521 ssh2_pkt_addstring(s->pktout, ssh->username);
8522 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8523 /* service requested */
8524 ssh2_pkt_addstring(s->pktout, "publickey");
8526 ssh2_pkt_addbool(s->pktout, TRUE);
8527 /* signature follows */
8528 ssh2_pkt_addstring(s->pktout, key->alg->name);
8529 pkblob = key->alg->public_blob(key->data,
8531 ssh2_pkt_addstring_start(s->pktout);
8532 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8536 * The data to be signed is:
8540 * followed by everything so far placed in the
8543 sigdata_len = s->pktout->length - 5 + 4 +
8544 ssh->v2_session_id_len;
8545 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8547 sigdata = snewn(sigdata_len, unsigned char);
8549 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8550 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8553 memcpy(sigdata+p, ssh->v2_session_id,
8554 ssh->v2_session_id_len);
8555 p += ssh->v2_session_id_len;
8556 memcpy(sigdata+p, s->pktout->data + 5,
8557 s->pktout->length - 5);
8558 p += s->pktout->length - 5;
8559 assert(p == sigdata_len);
8560 sigblob = key->alg->sign(key->data, (char *)sigdata,
8561 sigdata_len, &sigblob_len);
8562 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8563 sigblob, sigblob_len);
8568 ssh2_pkt_send(ssh, s->pktout);
8569 logevent("Sent public key signature");
8570 s->type = AUTH_TYPE_PUBLICKEY;
8571 key->alg->freekey(key->data);
8575 } else if (s->can_gssapi && !s->tried_gssapi) {
8577 /* GSSAPI Authentication */
8582 s->type = AUTH_TYPE_GSSAPI;
8583 s->tried_gssapi = TRUE;
8585 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8588 * Pick the highest GSS library on the preference
8594 for (i = 0; i < ngsslibs; i++) {
8595 int want_id = conf_get_int_int(ssh->conf,
8596 CONF_ssh_gsslist, i);
8597 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8598 if (ssh->gsslibs->libraries[j].id == want_id) {
8599 s->gsslib = &ssh->gsslibs->libraries[j];
8600 goto got_gsslib; /* double break */
8605 * We always expect to have found something in
8606 * the above loop: we only came here if there
8607 * was at least one viable GSS library, and the
8608 * preference list should always mention
8609 * everything and only change the order.
8614 if (s->gsslib->gsslogmsg)
8615 logevent(s->gsslib->gsslogmsg);
8617 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8618 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8619 ssh2_pkt_addstring(s->pktout, ssh->username);
8620 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8621 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8622 logevent("Attempting GSSAPI authentication");
8624 /* add mechanism info */
8625 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8627 /* number of GSSAPI mechanisms */
8628 ssh2_pkt_adduint32(s->pktout,1);
8630 /* length of OID + 2 */
8631 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8632 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8635 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8637 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8639 ssh2_pkt_send(ssh, s->pktout);
8640 crWaitUntilV(pktin);
8641 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8642 logevent("GSSAPI authentication request refused");
8646 /* check returned packet ... */
8648 ssh_pkt_getstring(pktin, &data, &len);
8649 s->gss_rcvtok.value = data;
8650 s->gss_rcvtok.length = len;
8651 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8652 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8653 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8654 memcmp((char *)s->gss_rcvtok.value + 2,
8655 s->gss_buf.value,s->gss_buf.length) ) {
8656 logevent("GSSAPI authentication - wrong response from server");
8660 /* now start running */
8661 s->gss_stat = s->gsslib->import_name(s->gsslib,
8664 if (s->gss_stat != SSH_GSS_OK) {
8665 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8666 logevent("GSSAPI import name failed - Bad service name");
8668 logevent("GSSAPI import name failed");
8672 /* fetch TGT into GSS engine */
8673 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8675 if (s->gss_stat != SSH_GSS_OK) {
8676 logevent("GSSAPI authentication failed to get credentials");
8677 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8681 /* initial tokens are empty */
8682 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8683 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8685 /* now enter the loop */
8687 s->gss_stat = s->gsslib->init_sec_context
8691 conf_get_int(ssh->conf, CONF_gssapifwd),
8695 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8696 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8697 logevent("GSSAPI authentication initialisation failed");
8699 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8700 &s->gss_buf) == SSH_GSS_OK) {
8701 logevent(s->gss_buf.value);
8702 sfree(s->gss_buf.value);
8707 logevent("GSSAPI authentication initialised");
8709 /* Client and server now exchange tokens until GSSAPI
8710 * no longer says CONTINUE_NEEDED */
8712 if (s->gss_sndtok.length != 0) {
8713 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8714 ssh_pkt_addstring_start(s->pktout);
8715 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8716 ssh2_pkt_send(ssh, s->pktout);
8717 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8720 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8721 crWaitUntilV(pktin);
8722 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8723 logevent("GSSAPI authentication - bad server response");
8724 s->gss_stat = SSH_GSS_FAILURE;
8727 ssh_pkt_getstring(pktin, &data, &len);
8728 s->gss_rcvtok.value = data;
8729 s->gss_rcvtok.length = len;
8731 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8733 if (s->gss_stat != SSH_GSS_OK) {
8734 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8735 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8738 logevent("GSSAPI authentication loop finished OK");
8740 /* Now send the MIC */
8742 s->pktout = ssh2_pkt_init(0);
8743 micoffset = s->pktout->length;
8744 ssh_pkt_addstring_start(s->pktout);
8745 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8746 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8747 ssh_pkt_addstring(s->pktout, ssh->username);
8748 ssh_pkt_addstring(s->pktout, "ssh-connection");
8749 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8751 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8752 s->gss_buf.length = s->pktout->length - micoffset;
8754 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8755 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8756 ssh_pkt_addstring_start(s->pktout);
8757 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8758 ssh2_pkt_send(ssh, s->pktout);
8759 s->gsslib->free_mic(s->gsslib, &mic);
8763 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8764 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8767 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8770 * Keyboard-interactive authentication.
8773 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8775 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8777 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8778 ssh2_pkt_addstring(s->pktout, ssh->username);
8779 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8780 /* service requested */
8781 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8783 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8784 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8785 ssh2_pkt_send(ssh, s->pktout);
8787 logevent("Attempting keyboard-interactive authentication");
8789 crWaitUntilV(pktin);
8790 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8791 /* Server is not willing to do keyboard-interactive
8792 * at all (or, bizarrely but legally, accepts the
8793 * user without actually issuing any prompts).
8794 * Give up on it entirely. */
8796 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8797 s->kbd_inter_refused = TRUE; /* don't try it again */
8802 * Loop while the server continues to send INFO_REQUESTs.
8804 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8806 char *name, *inst, *lang;
8807 int name_len, inst_len, lang_len;
8811 * We've got a fresh USERAUTH_INFO_REQUEST.
8812 * Get the preamble and start building a prompt.
8814 ssh_pkt_getstring(pktin, &name, &name_len);
8815 ssh_pkt_getstring(pktin, &inst, &inst_len);
8816 ssh_pkt_getstring(pktin, &lang, &lang_len);
8817 s->cur_prompt = new_prompts(ssh->frontend);
8818 s->cur_prompt->to_server = TRUE;
8821 * Get any prompt(s) from the packet.
8823 s->num_prompts = ssh_pkt_getuint32(pktin);
8824 for (i = 0; i < s->num_prompts; i++) {
8828 static char noprompt[] =
8829 "<server failed to send prompt>: ";
8831 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8832 echo = ssh2_pkt_getbool(pktin);
8835 prompt_len = lenof(noprompt)-1;
8837 add_prompt(s->cur_prompt,
8838 dupprintf("%.*s", prompt_len, prompt),
8843 /* FIXME: better prefix to distinguish from
8845 s->cur_prompt->name =
8846 dupprintf("SSH server: %.*s", name_len, name);
8847 s->cur_prompt->name_reqd = TRUE;
8849 s->cur_prompt->name =
8850 dupstr("SSH server authentication");
8851 s->cur_prompt->name_reqd = FALSE;
8853 /* We add a prefix to try to make it clear that a prompt
8854 * has come from the server.
8855 * FIXME: ugly to print "Using..." in prompt _every_
8856 * time round. Can this be done more subtly? */
8857 /* Special case: for reasons best known to themselves,
8858 * some servers send k-i requests with no prompts and
8859 * nothing to display. Keep quiet in this case. */
8860 if (s->num_prompts || name_len || inst_len) {
8861 s->cur_prompt->instruction =
8862 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8863 inst_len ? "\n" : "", inst_len, inst);
8864 s->cur_prompt->instr_reqd = TRUE;
8866 s->cur_prompt->instr_reqd = FALSE;
8870 * Display any instructions, and get the user's
8874 int ret; /* not live over crReturn */
8875 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8878 crWaitUntilV(!pktin);
8879 ret = get_userpass_input(s->cur_prompt, in, inlen);
8884 * Failed to get responses. Terminate.
8886 free_prompts(s->cur_prompt);
8887 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8888 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8895 * Send the response(s) to the server.
8897 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8898 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8899 for (i=0; i < s->num_prompts; i++) {
8900 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8901 ssh2_pkt_addstring(s->pktout,
8902 s->cur_prompt->prompts[i]->result);
8903 end_log_omission(ssh, s->pktout);
8905 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8908 * Free the prompts structure from this iteration.
8909 * If there's another, a new one will be allocated
8910 * when we return to the top of this while loop.
8912 free_prompts(s->cur_prompt);
8915 * Get the next packet in case it's another
8918 crWaitUntilV(pktin);
8923 * We should have SUCCESS or FAILURE now.
8927 } else if (s->can_passwd) {
8930 * Plain old password authentication.
8932 int ret; /* not live over crReturn */
8933 int changereq_first_time; /* not live over crReturn */
8935 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8937 s->cur_prompt = new_prompts(ssh->frontend);
8938 s->cur_prompt->to_server = TRUE;
8939 s->cur_prompt->name = dupstr("SSH password");
8940 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8945 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8948 crWaitUntilV(!pktin);
8949 ret = get_userpass_input(s->cur_prompt, in, inlen);
8954 * Failed to get responses. Terminate.
8956 free_prompts(s->cur_prompt);
8957 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8958 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8963 * Squirrel away the password. (We may need it later if
8964 * asked to change it.)
8966 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8967 free_prompts(s->cur_prompt);
8970 * Send the password packet.
8972 * We pad out the password packet to 256 bytes to make
8973 * it harder for an attacker to find the length of the
8976 * Anyone using a password longer than 256 bytes
8977 * probably doesn't have much to worry about from
8978 * people who find out how long their password is!
8980 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8981 ssh2_pkt_addstring(s->pktout, ssh->username);
8982 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8983 /* service requested */
8984 ssh2_pkt_addstring(s->pktout, "password");
8985 ssh2_pkt_addbool(s->pktout, FALSE);
8986 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8987 ssh2_pkt_addstring(s->pktout, s->password);
8988 end_log_omission(ssh, s->pktout);
8989 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8990 logevent("Sent password");
8991 s->type = AUTH_TYPE_PASSWORD;
8994 * Wait for next packet, in case it's a password change
8997 crWaitUntilV(pktin);
8998 changereq_first_time = TRUE;
9000 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9003 * We're being asked for a new password
9004 * (perhaps not for the first time).
9005 * Loop until the server accepts it.
9008 int got_new = FALSE; /* not live over crReturn */
9009 char *prompt; /* not live over crReturn */
9010 int prompt_len; /* not live over crReturn */
9014 if (changereq_first_time)
9015 msg = "Server requested password change";
9017 msg = "Server rejected new password";
9019 c_write_str(ssh, msg);
9020 c_write_str(ssh, "\r\n");
9023 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9025 s->cur_prompt = new_prompts(ssh->frontend);
9026 s->cur_prompt->to_server = TRUE;
9027 s->cur_prompt->name = dupstr("New SSH password");
9028 s->cur_prompt->instruction =
9029 dupprintf("%.*s", prompt_len, prompt);
9030 s->cur_prompt->instr_reqd = TRUE;
9032 * There's no explicit requirement in the protocol
9033 * for the "old" passwords in the original and
9034 * password-change messages to be the same, and
9035 * apparently some Cisco kit supports password change
9036 * by the user entering a blank password originally
9037 * and the real password subsequently, so,
9038 * reluctantly, we prompt for the old password again.
9040 * (On the other hand, some servers don't even bother
9041 * to check this field.)
9043 add_prompt(s->cur_prompt,
9044 dupstr("Current password (blank for previously entered password): "),
9046 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9048 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9052 * Loop until the user manages to enter the same
9057 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9060 crWaitUntilV(!pktin);
9061 ret = get_userpass_input(s->cur_prompt, in, inlen);
9066 * Failed to get responses. Terminate.
9068 /* burn the evidence */
9069 free_prompts(s->cur_prompt);
9070 smemclr(s->password, strlen(s->password));
9072 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9073 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9079 * If the user specified a new original password
9080 * (IYSWIM), overwrite any previously specified
9082 * (A side effect is that the user doesn't have to
9083 * re-enter it if they louse up the new password.)
9085 if (s->cur_prompt->prompts[0]->result[0]) {
9086 smemclr(s->password, strlen(s->password));
9087 /* burn the evidence */
9090 dupstr(s->cur_prompt->prompts[0]->result);
9094 * Check the two new passwords match.
9096 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9097 s->cur_prompt->prompts[2]->result)
9100 /* They don't. Silly user. */
9101 c_write_str(ssh, "Passwords do not match\r\n");
9106 * Send the new password (along with the old one).
9107 * (see above for padding rationale)
9109 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9110 ssh2_pkt_addstring(s->pktout, ssh->username);
9111 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9112 /* service requested */
9113 ssh2_pkt_addstring(s->pktout, "password");
9114 ssh2_pkt_addbool(s->pktout, TRUE);
9115 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9116 ssh2_pkt_addstring(s->pktout, s->password);
9117 ssh2_pkt_addstring(s->pktout,
9118 s->cur_prompt->prompts[1]->result);
9119 free_prompts(s->cur_prompt);
9120 end_log_omission(ssh, s->pktout);
9121 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9122 logevent("Sent new password");
9125 * Now see what the server has to say about it.
9126 * (If it's CHANGEREQ again, it's not happy with the
9129 crWaitUntilV(pktin);
9130 changereq_first_time = FALSE;
9135 * We need to reexamine the current pktin at the top
9136 * of the loop. Either:
9137 * - we weren't asked to change password at all, in
9138 * which case it's a SUCCESS or FAILURE with the
9140 * - we sent a new password, and the server was
9141 * either OK with it (SUCCESS or FAILURE w/partial
9142 * success) or unhappy with the _old_ password
9143 * (FAILURE w/o partial success)
9144 * In any of these cases, we go back to the top of
9145 * the loop and start again.
9150 * We don't need the old password any more, in any
9151 * case. Burn the evidence.
9153 smemclr(s->password, strlen(s->password));
9157 char *str = dupprintf("No supported authentication methods available"
9158 " (server sent: %.*s)",
9161 ssh_disconnect(ssh, str,
9162 "No supported authentication methods available",
9163 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9173 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9175 /* Clear up various bits and pieces from authentication. */
9176 if (s->publickey_blob) {
9177 sfree(s->publickey_blob);
9178 sfree(s->publickey_comment);
9180 if (s->agent_response)
9181 sfree(s->agent_response);
9183 if (s->userauth_success) {
9185 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9186 * packets since. Signal the transport layer to consider enacting
9187 * delayed compression.
9189 * (Relying on we_are_in is not sufficient, as
9190 * draft-miller-secsh-compression-delayed is quite clear that it
9191 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9192 * become set for other reasons.)
9194 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9198 * Now the connection protocol has started, one way or another.
9201 ssh->channels = newtree234(ssh_channelcmp);
9204 * Set up handlers for some connection protocol messages, so we
9205 * don't have to handle them repeatedly in this coroutine.
9207 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9208 ssh2_msg_channel_window_adjust;
9209 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9210 ssh2_msg_global_request;
9213 * Create the main session channel.
9215 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9216 ssh->mainchan = NULL;
9218 ssh->mainchan = snew(struct ssh_channel);
9219 ssh->mainchan->ssh = ssh;
9220 ssh2_channel_init(ssh->mainchan);
9222 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9224 * Just start a direct-tcpip channel and use it as the main
9227 ssh_send_port_open(ssh->mainchan,
9228 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9229 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9233 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9234 logevent("Opening session as main channel");
9235 ssh2_pkt_send(ssh, s->pktout);
9236 ssh->ncmode = FALSE;
9238 crWaitUntilV(pktin);
9239 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9240 bombout(("Server refused to open channel"));
9242 /* FIXME: error data comes back in FAILURE packet */
9244 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9245 bombout(("Server's channel confirmation cited wrong channel"));
9248 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9249 ssh->mainchan->halfopen = FALSE;
9250 ssh->mainchan->type = CHAN_MAINSESSION;
9251 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9252 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9253 add234(ssh->channels, ssh->mainchan);
9254 update_specials_menu(ssh->frontend);
9255 logevent("Opened main channel");
9259 * Now we have a channel, make dispatch table entries for
9260 * general channel-based messages.
9262 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9263 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9264 ssh2_msg_channel_data;
9265 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9266 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9267 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9268 ssh2_msg_channel_open_confirmation;
9269 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9270 ssh2_msg_channel_open_failure;
9271 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9272 ssh2_msg_channel_request;
9273 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9274 ssh2_msg_channel_open;
9275 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9276 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9279 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9281 * This message indicates to the server that we promise
9282 * not to try to run any other channel in parallel with
9283 * this one, so it's safe for it to advertise a very large
9284 * window and leave the flow control to TCP.
9286 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9287 "simple@putty.projects.tartarus.org",
9289 ssh2_pkt_send(ssh, s->pktout);
9293 * Enable port forwardings.
9295 ssh_setup_portfwd(ssh, ssh->conf);
9297 if (ssh->mainchan && !ssh->ncmode) {
9299 * Send the CHANNEL_REQUESTS for the main session channel.
9300 * Each one is handled by its own little asynchronous
9304 /* Potentially enable X11 forwarding. */
9305 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
9307 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9308 conf_get_int(ssh->conf, CONF_x11_auth),
9310 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
9312 /* Potentially enable agent forwarding. */
9313 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists())
9314 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
9316 /* Now allocate a pty for the session. */
9317 if (!conf_get_int(ssh->conf, CONF_nopty))
9318 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
9320 /* Send environment variables. */
9321 ssh2_setup_env(ssh->mainchan, NULL, NULL);
9324 * Start a shell or a remote command. We may have to attempt
9325 * this twice if the config data has provided a second choice
9332 if (ssh->fallback_cmd) {
9333 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9334 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9336 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9337 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9341 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
9342 ssh2_response_authconn, NULL);
9343 ssh2_pkt_addstring(s->pktout, cmd);
9345 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
9346 ssh2_response_authconn, NULL);
9347 ssh2_pkt_addstring(s->pktout, cmd);
9349 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
9350 ssh2_response_authconn, NULL);
9352 ssh2_pkt_send(ssh, s->pktout);
9354 crWaitUntilV(pktin);
9356 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9357 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9358 bombout(("Unexpected response to shell/command request:"
9359 " packet type %d", pktin->type));
9363 * We failed to start the command. If this is the
9364 * fallback command, we really are finished; if it's
9365 * not, and if the fallback command exists, try falling
9366 * back to it before complaining.
9368 if (!ssh->fallback_cmd &&
9369 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9370 logevent("Primary command failed; attempting fallback");
9371 ssh->fallback_cmd = TRUE;
9374 bombout(("Server refused to start a shell/command"));
9377 logevent("Started a shell/command");
9382 ssh->editing = ssh->echoing = TRUE;
9385 ssh->state = SSH_STATE_SESSION;
9386 if (ssh->size_needed)
9387 ssh_size(ssh, ssh->term_width, ssh->term_height);
9388 if (ssh->eof_needed)
9389 ssh_special(ssh, TS_EOF);
9395 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9400 s->try_send = FALSE;
9404 * _All_ the connection-layer packets we expect to
9405 * receive are now handled by the dispatch table.
9406 * Anything that reaches here must be bogus.
9409 bombout(("Strange packet received: type %d", pktin->type));
9411 } else if (ssh->mainchan) {
9413 * We have spare data. Add it to the channel buffer.
9415 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9420 struct ssh_channel *c;
9422 * Try to send data on all channels if we can.
9424 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9425 ssh2_try_send_and_unthrottle(ssh, c);
9433 * Handlers for SSH-2 messages that might arrive at any moment.
9435 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9437 /* log reason code in disconnect message */
9441 reason = ssh_pkt_getuint32(pktin);
9442 ssh_pkt_getstring(pktin, &msg, &msglen);
9444 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9445 buf = dupprintf("Received disconnect message (%s)",
9446 ssh2_disconnect_reasons[reason]);
9448 buf = dupprintf("Received disconnect message (unknown"
9449 " type %d)", reason);
9453 buf = dupprintf("Disconnection message text: %.*s",
9456 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9458 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9459 ssh2_disconnect_reasons[reason] : "unknown",
9464 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9466 /* log the debug message */
9470 /* XXX maybe we should actually take notice of the return value */
9471 ssh2_pkt_getbool(pktin);
9472 ssh_pkt_getstring(pktin, &msg, &msglen);
9474 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9477 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9479 do_ssh2_transport(ssh, NULL, 0, pktin);
9483 * Called if we receive a packet that isn't allowed by the protocol.
9484 * This only applies to packets whose meaning PuTTY understands.
9485 * Entirely unknown packets are handled below.
9487 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9489 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9490 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9492 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9496 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9498 struct Packet *pktout;
9499 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9500 ssh2_pkt_adduint32(pktout, pktin->sequence);
9502 * UNIMPLEMENTED messages MUST appear in the same order as the
9503 * messages they respond to. Hence, never queue them.
9505 ssh2_pkt_send_noqueue(ssh, pktout);
9509 * Handle the top-level SSH-2 protocol.
9511 static void ssh2_protocol_setup(Ssh ssh)
9516 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9518 for (i = 0; i < 256; i++)
9519 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9522 * Initially, we only accept transport messages (and a few generic
9523 * ones). do_ssh2_authconn will add more when it starts.
9524 * Messages that are understood but not currently acceptable go to
9525 * ssh2_msg_unexpected.
9527 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9528 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9529 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9530 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9531 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9532 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9533 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9534 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9535 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9536 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9537 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9538 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9539 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9540 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9541 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9542 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9543 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9544 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9545 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9546 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9547 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9548 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9549 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9550 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9551 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9552 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9553 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9554 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9555 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9556 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9557 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9558 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9559 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9562 * These messages have a special handler from the start.
9564 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9565 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9566 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9569 static void ssh2_timer(void *ctx, unsigned long now)
9573 if (ssh->state == SSH_STATE_CLOSED)
9576 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9577 now == ssh->next_rekey) {
9578 do_ssh2_transport(ssh, "timeout", -1, NULL);
9582 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9583 struct Packet *pktin)
9585 unsigned char *in = (unsigned char *)vin;
9586 if (ssh->state == SSH_STATE_CLOSED)
9590 ssh->incoming_data_size += pktin->encrypted_len;
9591 if (!ssh->kex_in_progress &&
9592 ssh->max_data_size != 0 &&
9593 ssh->incoming_data_size > ssh->max_data_size)
9594 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9598 ssh->packet_dispatch[pktin->type](ssh, pktin);
9599 else if (!ssh->protocol_initial_phase_done)
9600 do_ssh2_transport(ssh, in, inlen, pktin);
9602 do_ssh2_authconn(ssh, in, inlen, pktin);
9605 static void ssh_cache_conf_values(Ssh ssh)
9607 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9611 * Called to set up the connection.
9613 * Returns an error message, or NULL on success.
9615 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9616 Conf *conf, char *host, int port, char **realhost,
9617 int nodelay, int keepalive)
9622 ssh = snew(struct ssh_tag);
9623 ssh->conf = conf_copy(conf);
9624 ssh_cache_conf_values(ssh);
9625 ssh->version = 0; /* when not ready yet */
9628 ssh->v1_cipher_ctx = NULL;
9629 ssh->crcda_ctx = NULL;
9630 ssh->cscipher = NULL;
9631 ssh->cs_cipher_ctx = NULL;
9632 ssh->sccipher = NULL;
9633 ssh->sc_cipher_ctx = NULL;
9635 ssh->cs_mac_ctx = NULL;
9637 ssh->sc_mac_ctx = NULL;
9639 ssh->cs_comp_ctx = NULL;
9641 ssh->sc_comp_ctx = NULL;
9643 ssh->kex_ctx = NULL;
9644 ssh->hostkey = NULL;
9646 ssh->close_expected = FALSE;
9647 ssh->clean_exit = FALSE;
9648 ssh->state = SSH_STATE_PREPACKET;
9649 ssh->size_needed = FALSE;
9650 ssh->eof_needed = FALSE;
9653 ssh->deferred_send_data = NULL;
9654 ssh->deferred_len = 0;
9655 ssh->deferred_size = 0;
9656 ssh->fallback_cmd = 0;
9657 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9658 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9659 ssh->x11disp = NULL;
9660 ssh->v1_compressing = FALSE;
9661 ssh->v2_outgoing_sequence = 0;
9662 ssh->ssh1_rdpkt_crstate = 0;
9663 ssh->ssh2_rdpkt_crstate = 0;
9664 ssh->ssh_gotdata_crstate = 0;
9665 ssh->do_ssh1_connection_crstate = 0;
9666 ssh->do_ssh_init_state = NULL;
9667 ssh->do_ssh1_login_state = NULL;
9668 ssh->do_ssh2_transport_state = NULL;
9669 ssh->do_ssh2_authconn_state = NULL;
9672 ssh->mainchan = NULL;
9673 ssh->throttled_all = 0;
9674 ssh->v1_stdout_throttling = 0;
9676 ssh->queuelen = ssh->queuesize = 0;
9677 ssh->queueing = FALSE;
9678 ssh->qhead = ssh->qtail = NULL;
9679 ssh->deferred_rekey_reason = NULL;
9680 bufchain_init(&ssh->queued_incoming_data);
9681 ssh->frozen = FALSE;
9682 ssh->username = NULL;
9683 ssh->sent_console_eof = FALSE;
9684 ssh->got_pty = FALSE;
9686 *backend_handle = ssh;
9689 if (crypto_startup() == 0)
9690 return "Microsoft high encryption pack not installed!";
9693 ssh->frontend = frontend_handle;
9694 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9695 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9697 ssh->channels = NULL;
9698 ssh->rportfwds = NULL;
9699 ssh->portfwds = NULL;
9704 ssh->conn_throttle_count = 0;
9705 ssh->overall_bufsize = 0;
9706 ssh->fallback_cmd = 0;
9708 ssh->protocol = NULL;
9710 ssh->protocol_initial_phase_done = FALSE;
9714 ssh->incoming_data_size = ssh->outgoing_data_size =
9715 ssh->deferred_data_size = 0L;
9716 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9717 CONF_ssh_rekey_data));
9718 ssh->kex_in_progress = FALSE;
9721 ssh->gsslibs = NULL;
9724 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9733 static void ssh_free(void *handle)
9735 Ssh ssh = (Ssh) handle;
9736 struct ssh_channel *c;
9737 struct ssh_rportfwd *pf;
9739 if (ssh->v1_cipher_ctx)
9740 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9741 if (ssh->cs_cipher_ctx)
9742 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9743 if (ssh->sc_cipher_ctx)
9744 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9745 if (ssh->cs_mac_ctx)
9746 ssh->csmac->free_context(ssh->cs_mac_ctx);
9747 if (ssh->sc_mac_ctx)
9748 ssh->scmac->free_context(ssh->sc_mac_ctx);
9749 if (ssh->cs_comp_ctx) {
9751 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9753 zlib_compress_cleanup(ssh->cs_comp_ctx);
9755 if (ssh->sc_comp_ctx) {
9757 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9759 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9762 dh_cleanup(ssh->kex_ctx);
9763 sfree(ssh->savedhost);
9765 while (ssh->queuelen-- > 0)
9766 ssh_free_packet(ssh->queue[ssh->queuelen]);
9769 while (ssh->qhead) {
9770 struct queued_handler *qh = ssh->qhead;
9771 ssh->qhead = qh->next;
9774 ssh->qhead = ssh->qtail = NULL;
9776 if (ssh->channels) {
9777 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9780 if (c->u.x11.s != NULL)
9781 x11_close(c->u.x11.s);
9784 case CHAN_SOCKDATA_DORMANT:
9785 if (c->u.pfd.s != NULL)
9786 pfd_close(c->u.pfd.s);
9789 if (ssh->version == 2) {
9790 struct outstanding_channel_request *ocr, *nocr;
9791 ocr = c->v.v2.chanreq_head;
9793 ocr->handler(c, NULL, ocr->ctx);
9798 bufchain_clear(&c->v.v2.outbuffer);
9802 freetree234(ssh->channels);
9803 ssh->channels = NULL;
9806 if (ssh->rportfwds) {
9807 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9809 freetree234(ssh->rportfwds);
9810 ssh->rportfwds = NULL;
9812 sfree(ssh->deferred_send_data);
9814 x11_free_display(ssh->x11disp);
9815 sfree(ssh->do_ssh_init_state);
9816 sfree(ssh->do_ssh1_login_state);
9817 sfree(ssh->do_ssh2_transport_state);
9818 sfree(ssh->do_ssh2_authconn_state);
9821 sfree(ssh->fullhostname);
9822 if (ssh->crcda_ctx) {
9823 crcda_free_context(ssh->crcda_ctx);
9824 ssh->crcda_ctx = NULL;
9827 ssh_do_close(ssh, TRUE);
9828 expire_timer_context(ssh);
9830 pinger_free(ssh->pinger);
9831 bufchain_clear(&ssh->queued_incoming_data);
9832 sfree(ssh->username);
9833 conf_free(ssh->conf);
9836 ssh_gss_cleanup(ssh->gsslibs);
9844 * Reconfigure the SSH backend.
9846 static void ssh_reconfig(void *handle, Conf *conf)
9848 Ssh ssh = (Ssh) handle;
9849 char *rekeying = NULL, rekey_mandatory = FALSE;
9850 unsigned long old_max_data_size;
9853 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9855 ssh_setup_portfwd(ssh, conf);
9857 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9858 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9860 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9861 unsigned long now = GETTICKCOUNT();
9863 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
9864 rekeying = "timeout shortened";
9866 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9870 old_max_data_size = ssh->max_data_size;
9871 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9872 CONF_ssh_rekey_data));
9873 if (old_max_data_size != ssh->max_data_size &&
9874 ssh->max_data_size != 0) {
9875 if (ssh->outgoing_data_size > ssh->max_data_size ||
9876 ssh->incoming_data_size > ssh->max_data_size)
9877 rekeying = "data limit lowered";
9880 if (conf_get_int(ssh->conf, CONF_compression) !=
9881 conf_get_int(conf, CONF_compression)) {
9882 rekeying = "compression setting changed";
9883 rekey_mandatory = TRUE;
9886 for (i = 0; i < CIPHER_MAX; i++)
9887 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9888 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9889 rekeying = "cipher settings changed";
9890 rekey_mandatory = TRUE;
9892 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9893 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9894 rekeying = "cipher settings changed";
9895 rekey_mandatory = TRUE;
9898 conf_free(ssh->conf);
9899 ssh->conf = conf_copy(conf);
9900 ssh_cache_conf_values(ssh);
9903 if (!ssh->kex_in_progress) {
9904 do_ssh2_transport(ssh, rekeying, -1, NULL);
9905 } else if (rekey_mandatory) {
9906 ssh->deferred_rekey_reason = rekeying;
9912 * Called to send data down the SSH connection.
9914 static int ssh_send(void *handle, char *buf, int len)
9916 Ssh ssh = (Ssh) handle;
9918 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9921 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9923 return ssh_sendbuffer(ssh);
9927 * Called to query the current amount of buffered stdin data.
9929 static int ssh_sendbuffer(void *handle)
9931 Ssh ssh = (Ssh) handle;
9934 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9938 * If the SSH socket itself has backed up, add the total backup
9939 * size on that to any individual buffer on the stdin channel.
9942 if (ssh->throttled_all)
9943 override_value = ssh->overall_bufsize;
9945 if (ssh->version == 1) {
9946 return override_value;
9947 } else if (ssh->version == 2) {
9949 return override_value;
9951 return (override_value +
9952 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9959 * Called to set the size of the window from SSH's POV.
9961 static void ssh_size(void *handle, int width, int height)
9963 Ssh ssh = (Ssh) handle;
9964 struct Packet *pktout;
9966 ssh->term_width = width;
9967 ssh->term_height = height;
9969 switch (ssh->state) {
9970 case SSH_STATE_BEFORE_SIZE:
9971 case SSH_STATE_PREPACKET:
9972 case SSH_STATE_CLOSED:
9973 break; /* do nothing */
9974 case SSH_STATE_INTERMED:
9975 ssh->size_needed = TRUE; /* buffer for later */
9977 case SSH_STATE_SESSION:
9978 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9979 if (ssh->version == 1) {
9980 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9981 PKT_INT, ssh->term_height,
9982 PKT_INT, ssh->term_width,
9983 PKT_INT, 0, PKT_INT, 0, PKT_END);
9984 } else if (ssh->mainchan) {
9985 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
9987 ssh2_pkt_adduint32(pktout, ssh->term_width);
9988 ssh2_pkt_adduint32(pktout, ssh->term_height);
9989 ssh2_pkt_adduint32(pktout, 0);
9990 ssh2_pkt_adduint32(pktout, 0);
9991 ssh2_pkt_send(ssh, pktout);
9999 * Return a list of the special codes that make sense in this
10002 static const struct telnet_special *ssh_get_specials(void *handle)
10004 static const struct telnet_special ssh1_ignore_special[] = {
10005 {"IGNORE message", TS_NOP}
10007 static const struct telnet_special ssh2_ignore_special[] = {
10008 {"IGNORE message", TS_NOP},
10010 static const struct telnet_special ssh2_rekey_special[] = {
10011 {"Repeat key exchange", TS_REKEY},
10013 static const struct telnet_special ssh2_session_specials[] = {
10016 /* These are the signal names defined by RFC 4254.
10017 * They include all the ISO C signals, but are a subset of the POSIX
10018 * required signals. */
10019 {"SIGINT (Interrupt)", TS_SIGINT},
10020 {"SIGTERM (Terminate)", TS_SIGTERM},
10021 {"SIGKILL (Kill)", TS_SIGKILL},
10022 {"SIGQUIT (Quit)", TS_SIGQUIT},
10023 {"SIGHUP (Hangup)", TS_SIGHUP},
10024 {"More signals", TS_SUBMENU},
10025 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10026 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10027 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10028 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10029 {NULL, TS_EXITMENU}
10031 static const struct telnet_special specials_end[] = {
10032 {NULL, TS_EXITMENU}
10034 /* XXX review this length for any changes: */
10035 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10036 lenof(ssh2_rekey_special) +
10037 lenof(ssh2_session_specials) +
10038 lenof(specials_end)];
10039 Ssh ssh = (Ssh) handle;
10041 #define ADD_SPECIALS(name) \
10043 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10044 memcpy(&ssh_specials[i], name, sizeof name); \
10045 i += lenof(name); \
10048 if (ssh->version == 1) {
10049 /* Don't bother offering IGNORE if we've decided the remote
10050 * won't cope with it, since we wouldn't bother sending it if
10052 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10053 ADD_SPECIALS(ssh1_ignore_special);
10054 } else if (ssh->version == 2) {
10055 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10056 ADD_SPECIALS(ssh2_ignore_special);
10057 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
10058 ADD_SPECIALS(ssh2_rekey_special);
10060 ADD_SPECIALS(ssh2_session_specials);
10061 } /* else we're not ready yet */
10064 ADD_SPECIALS(specials_end);
10065 return ssh_specials;
10069 #undef ADD_SPECIALS
10073 * Send special codes. TS_EOF is useful for `plink', so you
10074 * can send an EOF and collect resulting output (e.g. `plink
10077 static void ssh_special(void *handle, Telnet_Special code)
10079 Ssh ssh = (Ssh) handle;
10080 struct Packet *pktout;
10082 if (code == TS_EOF) {
10083 if (ssh->state != SSH_STATE_SESSION) {
10085 * Buffer the EOF in case we are pre-SESSION, so we can
10086 * send it as soon as we reach SESSION.
10088 if (code == TS_EOF)
10089 ssh->eof_needed = TRUE;
10092 if (ssh->version == 1) {
10093 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10094 } else if (ssh->mainchan) {
10095 sshfwd_write_eof(ssh->mainchan);
10096 ssh->send_ok = 0; /* now stop trying to read from stdin */
10098 logevent("Sent EOF message");
10099 } else if (code == TS_PING || code == TS_NOP) {
10100 if (ssh->state == SSH_STATE_CLOSED
10101 || ssh->state == SSH_STATE_PREPACKET) return;
10102 if (ssh->version == 1) {
10103 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10104 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10106 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10107 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10108 ssh2_pkt_addstring_start(pktout);
10109 ssh2_pkt_send_noqueue(ssh, pktout);
10112 } else if (code == TS_REKEY) {
10113 if (!ssh->kex_in_progress && ssh->version == 2) {
10114 do_ssh2_transport(ssh, "at user request", -1, NULL);
10116 } else if (code == TS_BRK) {
10117 if (ssh->state == SSH_STATE_CLOSED
10118 || ssh->state == SSH_STATE_PREPACKET) return;
10119 if (ssh->version == 1) {
10120 logevent("Unable to send BREAK signal in SSH-1");
10121 } else if (ssh->mainchan) {
10122 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10123 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10124 ssh2_pkt_send(ssh, pktout);
10127 /* Is is a POSIX signal? */
10128 char *signame = NULL;
10129 if (code == TS_SIGABRT) signame = "ABRT";
10130 if (code == TS_SIGALRM) signame = "ALRM";
10131 if (code == TS_SIGFPE) signame = "FPE";
10132 if (code == TS_SIGHUP) signame = "HUP";
10133 if (code == TS_SIGILL) signame = "ILL";
10134 if (code == TS_SIGINT) signame = "INT";
10135 if (code == TS_SIGKILL) signame = "KILL";
10136 if (code == TS_SIGPIPE) signame = "PIPE";
10137 if (code == TS_SIGQUIT) signame = "QUIT";
10138 if (code == TS_SIGSEGV) signame = "SEGV";
10139 if (code == TS_SIGTERM) signame = "TERM";
10140 if (code == TS_SIGUSR1) signame = "USR1";
10141 if (code == TS_SIGUSR2) signame = "USR2";
10142 /* The SSH-2 protocol does in principle support arbitrary named
10143 * signals, including signame@domain, but we don't support those. */
10145 /* It's a signal. */
10146 if (ssh->version == 2 && ssh->mainchan) {
10147 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10148 ssh2_pkt_addstring(pktout, signame);
10149 ssh2_pkt_send(ssh, pktout);
10150 logeventf(ssh, "Sent signal SIG%s", signame);
10153 /* Never heard of it. Do nothing */
10158 void *new_sock_channel(void *handle, Socket s)
10160 Ssh ssh = (Ssh) handle;
10161 struct ssh_channel *c;
10162 c = snew(struct ssh_channel);
10165 ssh2_channel_init(c);
10166 c->halfopen = TRUE;
10167 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10169 add234(ssh->channels, c);
10174 * This is called when stdout/stderr (the entity to which
10175 * from_backend sends data) manages to clear some backlog.
10177 static void ssh_unthrottle(void *handle, int bufsize)
10179 Ssh ssh = (Ssh) handle;
10182 if (ssh->version == 1) {
10183 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10184 ssh->v1_stdout_throttling = 0;
10185 ssh_throttle_conn(ssh, -1);
10188 if (ssh->mainchan) {
10189 ssh2_set_window(ssh->mainchan,
10190 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10191 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10192 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10195 buflimit = ssh->mainchan->v.v2.locmaxwin;
10196 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10197 ssh->mainchan->throttling_conn = 0;
10198 ssh_throttle_conn(ssh, -1);
10204 * Now process any SSH connection data that was stashed in our
10205 * queue while we were frozen.
10207 ssh_process_queued_incoming_data(ssh);
10210 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10212 struct ssh_channel *c = (struct ssh_channel *)channel;
10214 struct Packet *pktout;
10216 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
10218 if (ssh->version == 1) {
10219 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10220 PKT_INT, c->localid,
10223 /* PKT_STR, <org:orgport>, */
10226 pktout = ssh2_chanopen_init(c, "direct-tcpip");
10227 ssh2_pkt_addstring(pktout, hostname);
10228 ssh2_pkt_adduint32(pktout, port);
10230 * We make up values for the originator data; partly it's
10231 * too much hassle to keep track, and partly I'm not
10232 * convinced the server should be told details like that
10233 * about my local network configuration.
10234 * The "originator IP address" is syntactically a numeric
10235 * IP address, and some servers (e.g., Tectia) get upset
10236 * if it doesn't match this syntax.
10238 ssh2_pkt_addstring(pktout, "0.0.0.0");
10239 ssh2_pkt_adduint32(pktout, 0);
10240 ssh2_pkt_send(ssh, pktout);
10244 static int ssh_connected(void *handle)
10246 Ssh ssh = (Ssh) handle;
10247 return ssh->s != NULL;
10250 static int ssh_sendok(void *handle)
10252 Ssh ssh = (Ssh) handle;
10253 return ssh->send_ok;
10256 static int ssh_ldisc(void *handle, int option)
10258 Ssh ssh = (Ssh) handle;
10259 if (option == LD_ECHO)
10260 return ssh->echoing;
10261 if (option == LD_EDIT)
10262 return ssh->editing;
10266 static void ssh_provide_ldisc(void *handle, void *ldisc)
10268 Ssh ssh = (Ssh) handle;
10269 ssh->ldisc = ldisc;
10272 static void ssh_provide_logctx(void *handle, void *logctx)
10274 Ssh ssh = (Ssh) handle;
10275 ssh->logctx = logctx;
10278 static int ssh_return_exitcode(void *handle)
10280 Ssh ssh = (Ssh) handle;
10281 if (ssh->s != NULL)
10284 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10288 * cfg_info for SSH is the currently running version of the
10289 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10291 static int ssh_cfg_info(void *handle)
10293 Ssh ssh = (Ssh) handle;
10294 return ssh->version;
10298 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10299 * that fails. This variable is the means by which scp.c can reach
10300 * into the SSH code and find out which one it got.
10302 extern int ssh_fallback_cmd(void *handle)
10304 Ssh ssh = (Ssh) handle;
10305 return ssh->fallback_cmd;
10308 Backend ssh_backend = {
10318 ssh_return_exitcode,
10322 ssh_provide_logctx,