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 crReturn(z) \
444 *crLine =__LINE__; return (z); case __LINE__:;\
448 *crLine=__LINE__; return; case __LINE__:;\
450 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
451 #define crStopV do{ *crLine = 0; return; }while(0)
452 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
453 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
455 typedef struct ssh_tag *Ssh;
458 static struct Packet *ssh1_pkt_init(int pkt_type);
459 static struct Packet *ssh2_pkt_init(int pkt_type);
460 static void ssh_pkt_ensure(struct Packet *, int length);
461 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
462 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
463 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
464 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
465 static void ssh_pkt_addstring_start(struct Packet *);
466 static void ssh_pkt_addstring_str(struct Packet *, char *data);
467 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
468 static void ssh_pkt_addstring(struct Packet *, char *data);
469 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
470 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
471 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
472 static int ssh2_pkt_construct(Ssh, struct Packet *);
473 static void ssh2_pkt_send(Ssh, struct Packet *);
474 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
475 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
476 struct Packet *pktin);
477 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
478 struct Packet *pktin);
479 static void ssh2_channel_check_close(struct ssh_channel *c);
480 static void ssh_channel_destroy(struct ssh_channel *c);
483 * Buffer management constants. There are several of these for
484 * various different purposes:
486 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
487 * on a local data stream before we throttle the whole SSH
488 * connection (in SSH-1 only). Throttling the whole connection is
489 * pretty drastic so we set this high in the hope it won't
492 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
493 * on the SSH connection itself before we defensively throttle
494 * _all_ local data streams. This is pretty drastic too (though
495 * thankfully unlikely in SSH-2 since the window mechanism should
496 * ensure that the server never has any need to throttle its end
497 * of the connection), so we set this high as well.
499 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
502 * - OUR_V2_BIGWIN is the window size we advertise for the only
503 * channel in a simple connection. It must be <= INT_MAX.
505 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
506 * to the remote side. This actually has nothing to do with the
507 * size of the _packet_, but is instead a limit on the amount
508 * of data we're willing to receive in a single SSH2 channel
511 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
512 * _packet_ we're prepared to cope with. It must be a multiple
513 * of the cipher block size, and must be at least 35000.
516 #define SSH1_BUFFER_LIMIT 32768
517 #define SSH_MAX_BACKLOG 32768
518 #define OUR_V2_WINSIZE 16384
519 #define OUR_V2_BIGWIN 0x7fffffff
520 #define OUR_V2_MAXPKT 0x4000UL
521 #define OUR_V2_PACKETLIMIT 0x9000UL
523 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
525 const static struct ssh_mac *macs[] = {
526 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
528 const static struct ssh_mac *buggymacs[] = {
529 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
532 static void *ssh_comp_none_init(void)
536 static void ssh_comp_none_cleanup(void *handle)
539 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
540 unsigned char **outblock, int *outlen)
544 static int ssh_comp_none_disable(void *handle)
548 const static struct ssh_compress ssh_comp_none = {
550 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
551 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
552 ssh_comp_none_disable, NULL
554 extern const struct ssh_compress ssh_zlib;
555 const static struct ssh_compress *compressions[] = {
556 &ssh_zlib, &ssh_comp_none
559 enum { /* channel types */
564 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
566 * CHAN_ZOMBIE is used to indicate a channel for which we've
567 * already destroyed the local data source: for instance, if a
568 * forwarded port experiences a socket error on the local side, we
569 * immediately destroy its local socket and turn the SSH channel
576 * little structure to keep track of outstanding WINDOW_ADJUSTs
584 * 2-3-4 tree storing channels.
587 Ssh ssh; /* pointer back to main context */
588 unsigned remoteid, localid;
590 /* True if we opened this channel but server hasn't confirmed. */
593 * In SSH-1, this value contains four bits:
595 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
596 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
597 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
598 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
600 * A channel is completely finished with when all four bits are set.
602 * In SSH-2, the four bits mean:
604 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
605 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
606 * 4 We have received SSH2_MSG_CHANNEL_EOF.
607 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
609 * A channel is completely finished with when we have both sent
610 * and received CLOSE.
612 * The symbolic constants below use the SSH-2 terminology, which
613 * is a bit confusing in SSH-1, but we have to use _something_.
615 #define CLOSES_SENT_EOF 1
616 #define CLOSES_SENT_CLOSE 2
617 #define CLOSES_RCVD_EOF 4
618 #define CLOSES_RCVD_CLOSE 8
622 * This flag indicates that an EOF is pending on the outgoing side
623 * of the channel: that is, wherever we're getting the data for
624 * this channel has sent us some data followed by EOF. We can't
625 * actually send the EOF until we've finished sending the data, so
626 * we set this flag instead to remind us to do so once our buffer
632 * True if this channel is causing the underlying connection to be
637 struct ssh2_data_channel {
639 unsigned remwindow, remmaxpkt;
640 /* locwindow is signed so we can cope with excess data. */
641 int locwindow, locmaxwin;
643 * remlocwin is the amount of local window that we think
644 * the remote end had available to it after it sent the
645 * last data packet or window adjust ack.
649 * These store the list of window adjusts that haven't
652 struct winadj *winadj_head, *winadj_tail;
653 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
657 struct ssh_agent_channel {
658 unsigned char *message;
659 unsigned char msglen[4];
660 unsigned lensofar, totallen;
662 struct ssh_x11_channel {
665 struct ssh_pfd_channel {
672 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
673 * use this structure in different ways, reflecting SSH-2's
674 * altogether saner approach to port forwarding.
676 * In SSH-1, you arrange a remote forwarding by sending the server
677 * the remote port number, and the local destination host:port.
678 * When a connection comes in, the server sends you back that
679 * host:port pair, and you connect to it. This is a ready-made
680 * security hole if you're not on the ball: a malicious server
681 * could send you back _any_ host:port pair, so if you trustingly
682 * connect to the address it gives you then you've just opened the
683 * entire inside of your corporate network just by connecting
684 * through it to a dodgy SSH server. Hence, we must store a list of
685 * host:port pairs we _are_ trying to forward to, and reject a
686 * connection request from the server if it's not in the list.
688 * In SSH-2, each side of the connection minds its own business and
689 * doesn't send unnecessary information to the other. You arrange a
690 * remote forwarding by sending the server just the remote port
691 * number. When a connection comes in, the server tells you which
692 * of its ports was connected to; and _you_ have to remember what
693 * local host:port pair went with that port number.
695 * Hence, in SSH-1 this structure is indexed by destination
696 * host:port pair, whereas in SSH-2 it is indexed by source port.
698 struct ssh_portfwd; /* forward declaration */
700 struct ssh_rportfwd {
701 unsigned sport, dport;
704 struct ssh_portfwd *pfrec;
706 #define free_rportfwd(pf) ( \
707 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
710 * Separately to the rportfwd tree (which is for looking up port
711 * open requests from the server), a tree of _these_ structures is
712 * used to keep track of all the currently open port forwardings,
713 * so that we can reconfigure in mid-session if the user requests
717 enum { DESTROY, KEEP, CREATE } status;
719 unsigned sport, dport;
722 struct ssh_rportfwd *remote;
726 #define free_portfwd(pf) ( \
727 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
728 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
731 long length; /* length of `data' actually used */
732 long forcepad; /* SSH-2: force padding to at least this length */
733 int type; /* only used for incoming packets */
734 unsigned long sequence; /* SSH-2 incoming sequence number */
735 unsigned char *data; /* allocated storage */
736 unsigned char *body; /* offset of payload within `data' */
737 long savedpos; /* temporary index into `data' (for strings) */
738 long maxlen; /* amount of storage allocated for `data' */
739 long encrypted_len; /* for SSH-2 total-size counting */
742 * State associated with packet logging
746 struct logblank_t *blanks;
749 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
750 struct Packet *pktin);
751 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
752 struct Packet *pktin);
753 static void ssh1_protocol_setup(Ssh ssh);
754 static void ssh2_protocol_setup(Ssh ssh);
755 static void ssh_size(void *handle, int width, int height);
756 static void ssh_special(void *handle, Telnet_Special);
757 static int ssh2_try_send(struct ssh_channel *c);
758 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
759 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
760 static void ssh2_set_window(struct ssh_channel *c, int newwin);
761 static int ssh_sendbuffer(void *handle);
762 static int ssh_do_close(Ssh ssh, int notify_exit);
763 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
764 static int ssh2_pkt_getbool(struct Packet *pkt);
765 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
766 static void ssh2_timer(void *ctx, long now);
767 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
768 struct Packet *pktin);
770 struct rdpkt1_state_tag {
771 long len, pad, biglen, to_read;
772 unsigned long realcrc, gotcrc;
776 struct Packet *pktin;
779 struct rdpkt2_state_tag {
780 long len, pad, payload, packetlen, maclen;
783 unsigned long incoming_sequence;
784 struct Packet *pktin;
787 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
788 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
790 struct queued_handler;
791 struct queued_handler {
793 chandler_fn_t handler;
795 struct queued_handler *next;
799 const struct plug_function_table *fn;
800 /* the above field _must_ be first in the structure */
810 unsigned char session_key[32];
812 int v1_remote_protoflags;
813 int v1_local_protoflags;
814 int agentfwd_enabled;
817 const struct ssh_cipher *cipher;
820 const struct ssh2_cipher *cscipher, *sccipher;
821 void *cs_cipher_ctx, *sc_cipher_ctx;
822 const struct ssh_mac *csmac, *scmac;
823 void *cs_mac_ctx, *sc_mac_ctx;
824 const struct ssh_compress *cscomp, *sccomp;
825 void *cs_comp_ctx, *sc_comp_ctx;
826 const struct ssh_kex *kex;
827 const struct ssh_signkey *hostkey;
828 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
829 int v2_session_id_len;
835 int echoing, editing;
839 int ospeed, ispeed; /* temporaries */
840 int term_width, term_height;
842 tree234 *channels; /* indexed by local id */
843 struct ssh_channel *mainchan; /* primary session channel */
844 int ncmode; /* is primary channel direct-tcpip? */
849 tree234 *rportfwds, *portfwds;
853 SSH_STATE_BEFORE_SIZE,
859 int size_needed, eof_needed;
860 int sent_console_eof;
861 int got_pty; /* affects EOF behaviour on main channel */
863 struct Packet **queue;
864 int queuelen, queuesize;
866 unsigned char *deferred_send_data;
867 int deferred_len, deferred_size;
870 * Gross hack: pscp will try to start SFTP but fall back to
871 * scp1 if that fails. This variable is the means by which
872 * scp.c can reach into the SSH code and find out which one it
877 bufchain banner; /* accumulates banners during do_ssh2_authconn */
882 struct X11Display *x11disp;
885 int conn_throttle_count;
888 int v1_stdout_throttling;
889 unsigned long v2_outgoing_sequence;
891 int ssh1_rdpkt_crstate;
892 int ssh2_rdpkt_crstate;
893 int ssh_gotdata_crstate;
894 int do_ssh1_connection_crstate;
896 void *do_ssh_init_state;
897 void *do_ssh1_login_state;
898 void *do_ssh2_transport_state;
899 void *do_ssh2_authconn_state;
901 struct rdpkt1_state_tag rdpkt1_state;
902 struct rdpkt2_state_tag rdpkt2_state;
904 /* SSH-1 and SSH-2 use this for different things, but both use it */
905 int protocol_initial_phase_done;
907 void (*protocol) (Ssh ssh, void *vin, int inlen,
909 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
912 * We maintain our own copy of a Conf structure here. That way,
913 * when we're passed a new one for reconfiguration, we can check
914 * the differences and potentially reconfigure port forwardings
915 * etc in mid-session.
920 * Values cached out of conf so as to avoid the tree234 lookup
921 * cost every time they're used.
926 * Dynamically allocated username string created during SSH
927 * login. Stored in here rather than in the coroutine state so
928 * that it'll be reliably freed if we shut down the SSH session
929 * at some unexpected moment.
934 * Used to transfer data back from async callbacks.
936 void *agent_response;
937 int agent_response_len;
941 * The SSH connection can be set as `frozen', meaning we are
942 * not currently accepting incoming data from the network. This
943 * is slightly more serious than setting the _socket_ as
944 * frozen, because we may already have had data passed to us
945 * from the network which we need to delay processing until
946 * after the freeze is lifted, so we also need a bufchain to
950 bufchain queued_incoming_data;
953 * Dispatch table for packet types that we may have to deal
956 handler_fn_t packet_dispatch[256];
959 * Queues of one-off handler functions for success/failure
960 * indications from a request.
962 struct queued_handler *qhead, *qtail;
963 handler_fn_t q_saved_handler1, q_saved_handler2;
966 * This module deals with sending keepalives.
971 * Track incoming and outgoing data sizes and time, for
974 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
975 unsigned long max_data_size;
977 long next_rekey, last_rekey;
978 char *deferred_rekey_reason; /* points to STATIC string; don't free */
981 * Fully qualified host name, which we need if doing GSSAPI.
987 * GSSAPI libraries for this session.
989 struct ssh_gss_liblist *gsslibs;
993 #define logevent(s) logevent(ssh->frontend, s)
995 /* logevent, only printf-formatted. */
996 static void logeventf(Ssh ssh, const char *fmt, ...)
1002 buf = dupvprintf(fmt, ap);
1008 #define bombout(msg) \
1010 char *text = dupprintf msg; \
1011 ssh_do_close(ssh, FALSE); \
1013 connection_fatal(ssh->frontend, "%s", text); \
1017 /* Functions to leave bits out of the SSH packet log file. */
1019 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1021 if (conf_get_int(ssh->conf, CONF_logomitpass))
1022 pkt->logmode = blanktype;
1025 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1027 if (ssh->logomitdata)
1028 pkt->logmode = blanktype;
1031 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1033 pkt->logmode = PKTLOG_EMIT;
1036 /* Helper function for common bits of parsing ttymodes. */
1037 static void parse_ttymodes(Ssh ssh,
1038 void (*do_mode)(void *data, char *mode, char *val),
1043 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1045 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1047 * val[0] is either 'V', indicating that an explicit value
1048 * follows it, or 'A' indicating that we should pass the
1049 * value through from the local environment via get_ttymode.
1052 val = get_ttymode(ssh->frontend, key);
1054 val++; /* skip the 'V' */
1056 do_mode(data, key, val);
1060 static int ssh_channelcmp(void *av, void *bv)
1062 struct ssh_channel *a = (struct ssh_channel *) av;
1063 struct ssh_channel *b = (struct ssh_channel *) bv;
1064 if (a->localid < b->localid)
1066 if (a->localid > b->localid)
1070 static int ssh_channelfind(void *av, void *bv)
1072 unsigned *a = (unsigned *) av;
1073 struct ssh_channel *b = (struct ssh_channel *) bv;
1074 if (*a < b->localid)
1076 if (*a > b->localid)
1081 static int ssh_rportcmp_ssh1(void *av, void *bv)
1083 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1084 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1086 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1087 return i < 0 ? -1 : +1;
1088 if (a->dport > b->dport)
1090 if (a->dport < b->dport)
1095 static int ssh_rportcmp_ssh2(void *av, void *bv)
1097 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1098 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1100 if (a->sport > b->sport)
1102 if (a->sport < b->sport)
1108 * Special form of strcmp which can cope with NULL inputs. NULL is
1109 * defined to sort before even the empty string.
1111 static int nullstrcmp(const char *a, const char *b)
1113 if (a == NULL && b == NULL)
1119 return strcmp(a, b);
1122 static int ssh_portcmp(void *av, void *bv)
1124 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1125 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1127 if (a->type > b->type)
1129 if (a->type < b->type)
1131 if (a->addressfamily > b->addressfamily)
1133 if (a->addressfamily < b->addressfamily)
1135 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1136 return i < 0 ? -1 : +1;
1137 if (a->sport > b->sport)
1139 if (a->sport < b->sport)
1141 if (a->type != 'D') {
1142 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1143 return i < 0 ? -1 : +1;
1144 if (a->dport > b->dport)
1146 if (a->dport < b->dport)
1152 static int alloc_channel_id(Ssh ssh)
1154 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1155 unsigned low, high, mid;
1157 struct ssh_channel *c;
1160 * First-fit allocation of channel numbers: always pick the
1161 * lowest unused one. To do this, binary-search using the
1162 * counted B-tree to find the largest channel ID which is in a
1163 * contiguous sequence from the beginning. (Precisely
1164 * everything in that sequence must have ID equal to its tree
1165 * index plus CHANNEL_NUMBER_OFFSET.)
1167 tsize = count234(ssh->channels);
1171 while (high - low > 1) {
1172 mid = (high + low) / 2;
1173 c = index234(ssh->channels, mid);
1174 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1175 low = mid; /* this one is fine */
1177 high = mid; /* this one is past it */
1180 * Now low points to either -1, or the tree index of the
1181 * largest ID in the initial sequence.
1184 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1185 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1187 return low + 1 + CHANNEL_NUMBER_OFFSET;
1190 static void c_write_stderr(int trusted, const char *buf, int len)
1193 for (i = 0; i < len; i++)
1194 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1195 fputc(buf[i], stderr);
1198 static void c_write(Ssh ssh, const char *buf, int len)
1200 if (flags & FLAG_STDERR)
1201 c_write_stderr(1, buf, len);
1203 from_backend(ssh->frontend, 1, buf, len);
1206 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1208 if (flags & FLAG_STDERR)
1209 c_write_stderr(0, buf, len);
1211 from_backend_untrusted(ssh->frontend, buf, len);
1214 static void c_write_str(Ssh ssh, const char *buf)
1216 c_write(ssh, buf, strlen(buf));
1219 static void ssh_free_packet(struct Packet *pkt)
1224 static struct Packet *ssh_new_packet(void)
1226 struct Packet *pkt = snew(struct Packet);
1228 pkt->body = pkt->data = NULL;
1230 pkt->logmode = PKTLOG_EMIT;
1238 * Collect incoming data in the incoming packet buffer.
1239 * Decipher and verify the packet when it is completely read.
1240 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1241 * Update the *data and *datalen variables.
1242 * Return a Packet structure when a packet is completed.
1244 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1246 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1248 crBegin(ssh->ssh1_rdpkt_crstate);
1250 st->pktin = ssh_new_packet();
1252 st->pktin->type = 0;
1253 st->pktin->length = 0;
1255 for (st->i = st->len = 0; st->i < 4; st->i++) {
1256 while ((*datalen) == 0)
1258 st->len = (st->len << 8) + **data;
1259 (*data)++, (*datalen)--;
1262 st->pad = 8 - (st->len % 8);
1263 st->biglen = st->len + st->pad;
1264 st->pktin->length = st->len - 5;
1266 if (st->biglen < 0) {
1267 bombout(("Extremely large packet length from server suggests"
1268 " data stream corruption"));
1269 ssh_free_packet(st->pktin);
1273 st->pktin->maxlen = st->biglen;
1274 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1276 st->to_read = st->biglen;
1277 st->p = st->pktin->data;
1278 while (st->to_read > 0) {
1279 st->chunk = st->to_read;
1280 while ((*datalen) == 0)
1282 if (st->chunk > (*datalen))
1283 st->chunk = (*datalen);
1284 memcpy(st->p, *data, st->chunk);
1286 *datalen -= st->chunk;
1288 st->to_read -= st->chunk;
1291 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1292 st->biglen, NULL)) {
1293 bombout(("Network attack (CRC compensation) detected!"));
1294 ssh_free_packet(st->pktin);
1299 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1301 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1302 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1303 if (st->gotcrc != st->realcrc) {
1304 bombout(("Incorrect CRC received on packet"));
1305 ssh_free_packet(st->pktin);
1309 st->pktin->body = st->pktin->data + st->pad + 1;
1310 st->pktin->savedpos = 0;
1312 if (ssh->v1_compressing) {
1313 unsigned char *decompblk;
1315 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1316 st->pktin->body - 1, st->pktin->length + 1,
1317 &decompblk, &decomplen)) {
1318 bombout(("Zlib decompression encountered invalid data"));
1319 ssh_free_packet(st->pktin);
1323 if (st->pktin->maxlen < st->pad + decomplen) {
1324 st->pktin->maxlen = st->pad + decomplen;
1325 st->pktin->data = sresize(st->pktin->data,
1326 st->pktin->maxlen + APIEXTRA,
1328 st->pktin->body = st->pktin->data + st->pad + 1;
1331 memcpy(st->pktin->body - 1, decompblk, decomplen);
1333 st->pktin->length = decomplen - 1;
1336 st->pktin->type = st->pktin->body[-1];
1339 * Log incoming packet, possibly omitting sensitive fields.
1343 struct logblank_t blank;
1344 if (ssh->logomitdata) {
1345 int do_blank = FALSE, blank_prefix = 0;
1346 /* "Session data" packets - omit the data field */
1347 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1348 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1349 do_blank = TRUE; blank_prefix = 4;
1350 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1351 do_blank = TRUE; blank_prefix = 8;
1354 blank.offset = blank_prefix;
1355 blank.len = st->pktin->length;
1356 blank.type = PKTLOG_OMIT;
1360 log_packet(ssh->logctx,
1361 PKT_INCOMING, st->pktin->type,
1362 ssh1_pkt_type(st->pktin->type),
1363 st->pktin->body, st->pktin->length,
1364 nblanks, &blank, NULL);
1367 crFinish(st->pktin);
1370 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1372 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1374 crBegin(ssh->ssh2_rdpkt_crstate);
1376 st->pktin = ssh_new_packet();
1378 st->pktin->type = 0;
1379 st->pktin->length = 0;
1381 st->cipherblk = ssh->sccipher->blksize;
1384 if (st->cipherblk < 8)
1386 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1388 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1391 * When dealing with a CBC-mode cipher, we want to avoid the
1392 * possibility of an attacker's tweaking the ciphertext stream
1393 * so as to cause us to feed the same block to the block
1394 * cipher more than once and thus leak information
1395 * (VU#958563). The way we do this is not to take any
1396 * decisions on the basis of anything we've decrypted until
1397 * we've verified it with a MAC. That includes the packet
1398 * length, so we just read data and check the MAC repeatedly,
1399 * and when the MAC passes, see if the length we've got is
1403 /* May as well allocate the whole lot now. */
1404 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1407 /* Read an amount corresponding to the MAC. */
1408 for (st->i = 0; st->i < st->maclen; st->i++) {
1409 while ((*datalen) == 0)
1411 st->pktin->data[st->i] = *(*data)++;
1417 unsigned char seq[4];
1418 ssh->scmac->start(ssh->sc_mac_ctx);
1419 PUT_32BIT(seq, st->incoming_sequence);
1420 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1423 for (;;) { /* Once around this loop per cipher block. */
1424 /* Read another cipher-block's worth, and tack it onto the end. */
1425 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1426 while ((*datalen) == 0)
1428 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1431 /* Decrypt one more block (a little further back in the stream). */
1432 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1433 st->pktin->data + st->packetlen,
1435 /* Feed that block to the MAC. */
1436 ssh->scmac->bytes(ssh->sc_mac_ctx,
1437 st->pktin->data + st->packetlen, st->cipherblk);
1438 st->packetlen += st->cipherblk;
1439 /* See if that gives us a valid packet. */
1440 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1441 st->pktin->data + st->packetlen) &&
1442 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1444 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1445 bombout(("No valid incoming packet found"));
1446 ssh_free_packet(st->pktin);
1450 st->pktin->maxlen = st->packetlen + st->maclen;
1451 st->pktin->data = sresize(st->pktin->data,
1452 st->pktin->maxlen + APIEXTRA,
1455 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1458 * Acquire and decrypt the first block of the packet. This will
1459 * contain the length and padding details.
1461 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1462 while ((*datalen) == 0)
1464 st->pktin->data[st->i] = *(*data)++;
1469 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1470 st->pktin->data, st->cipherblk);
1473 * Now get the length figure.
1475 st->len = GET_32BIT(st->pktin->data);
1478 * _Completely_ silly lengths should be stomped on before they
1479 * do us any more damage.
1481 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1482 (st->len + 4) % st->cipherblk != 0) {
1483 bombout(("Incoming packet was garbled on decryption"));
1484 ssh_free_packet(st->pktin);
1489 * So now we can work out the total packet length.
1491 st->packetlen = st->len + 4;
1494 * Allocate memory for the rest of the packet.
1496 st->pktin->maxlen = st->packetlen + st->maclen;
1497 st->pktin->data = sresize(st->pktin->data,
1498 st->pktin->maxlen + APIEXTRA,
1502 * Read and decrypt the remainder of the packet.
1504 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1506 while ((*datalen) == 0)
1508 st->pktin->data[st->i] = *(*data)++;
1511 /* Decrypt everything _except_ the MAC. */
1513 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1514 st->pktin->data + st->cipherblk,
1515 st->packetlen - st->cipherblk);
1521 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1522 st->len + 4, st->incoming_sequence)) {
1523 bombout(("Incorrect MAC received on packet"));
1524 ssh_free_packet(st->pktin);
1528 /* Get and sanity-check the amount of random padding. */
1529 st->pad = st->pktin->data[4];
1530 if (st->pad < 4 || st->len - st->pad < 1) {
1531 bombout(("Invalid padding length on received packet"));
1532 ssh_free_packet(st->pktin);
1536 * This enables us to deduce the payload length.
1538 st->payload = st->len - st->pad - 1;
1540 st->pktin->length = st->payload + 5;
1541 st->pktin->encrypted_len = st->packetlen;
1543 st->pktin->sequence = st->incoming_sequence++;
1546 * Decompress packet payload.
1549 unsigned char *newpayload;
1552 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1553 st->pktin->data + 5, st->pktin->length - 5,
1554 &newpayload, &newlen)) {
1555 if (st->pktin->maxlen < newlen + 5) {
1556 st->pktin->maxlen = newlen + 5;
1557 st->pktin->data = sresize(st->pktin->data,
1558 st->pktin->maxlen + APIEXTRA,
1561 st->pktin->length = 5 + newlen;
1562 memcpy(st->pktin->data + 5, newpayload, newlen);
1567 st->pktin->savedpos = 6;
1568 st->pktin->body = st->pktin->data;
1569 st->pktin->type = st->pktin->data[5];
1572 * Log incoming packet, possibly omitting sensitive fields.
1576 struct logblank_t blank;
1577 if (ssh->logomitdata) {
1578 int do_blank = FALSE, blank_prefix = 0;
1579 /* "Session data" packets - omit the data field */
1580 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1581 do_blank = TRUE; blank_prefix = 8;
1582 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1583 do_blank = TRUE; blank_prefix = 12;
1586 blank.offset = blank_prefix;
1587 blank.len = (st->pktin->length-6) - blank_prefix;
1588 blank.type = PKTLOG_OMIT;
1592 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1593 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1595 st->pktin->data+6, st->pktin->length-6,
1596 nblanks, &blank, &st->pktin->sequence);
1599 crFinish(st->pktin);
1602 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1604 int pad, biglen, i, pktoffs;
1608 * XXX various versions of SC (including 8.8.4) screw up the
1609 * register allocation in this function and use the same register
1610 * (D6) for len and as a temporary, with predictable results. The
1611 * following sledgehammer prevents this.
1618 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1619 ssh1_pkt_type(pkt->data[12]),
1620 pkt->body, pkt->length - (pkt->body - pkt->data),
1621 pkt->nblanks, pkt->blanks, NULL);
1622 sfree(pkt->blanks); pkt->blanks = NULL;
1625 if (ssh->v1_compressing) {
1626 unsigned char *compblk;
1628 zlib_compress_block(ssh->cs_comp_ctx,
1629 pkt->data + 12, pkt->length - 12,
1630 &compblk, &complen);
1631 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1632 memcpy(pkt->data + 12, compblk, complen);
1634 pkt->length = complen + 12;
1637 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1639 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1640 pad = 8 - (len % 8);
1642 biglen = len + pad; /* len(padding+type+data+CRC) */
1644 for (i = pktoffs; i < 4+8; i++)
1645 pkt->data[i] = random_byte();
1646 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1647 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1648 PUT_32BIT(pkt->data + pktoffs, len);
1651 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1652 pkt->data + pktoffs + 4, biglen);
1654 if (offset_p) *offset_p = pktoffs;
1655 return biglen + 4; /* len(length+padding+type+data+CRC) */
1658 static int s_write(Ssh ssh, void *data, int len)
1661 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1663 return sk_write(ssh->s, (char *)data, len);
1666 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1668 int len, backlog, offset;
1669 len = s_wrpkt_prepare(ssh, pkt, &offset);
1670 backlog = s_write(ssh, pkt->data + offset, len);
1671 if (backlog > SSH_MAX_BACKLOG)
1672 ssh_throttle_all(ssh, 1, backlog);
1673 ssh_free_packet(pkt);
1676 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1679 len = s_wrpkt_prepare(ssh, pkt, &offset);
1680 if (ssh->deferred_len + len > ssh->deferred_size) {
1681 ssh->deferred_size = ssh->deferred_len + len + 128;
1682 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1686 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1687 pkt->data + offset, len);
1688 ssh->deferred_len += len;
1689 ssh_free_packet(pkt);
1693 * Construct a SSH-1 packet with the specified contents.
1694 * (This all-at-once interface used to be the only one, but now SSH-1
1695 * packets can also be constructed incrementally.)
1697 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1703 pkt = ssh1_pkt_init(pkttype);
1705 while ((argtype = va_arg(ap, int)) != PKT_END) {
1706 unsigned char *argp, argchar;
1708 unsigned long argint;
1711 /* Actual fields in the packet */
1713 argint = va_arg(ap, int);
1714 ssh_pkt_adduint32(pkt, argint);
1717 argchar = (unsigned char) va_arg(ap, int);
1718 ssh_pkt_addbyte(pkt, argchar);
1721 argp = va_arg(ap, unsigned char *);
1722 arglen = va_arg(ap, int);
1723 ssh_pkt_adddata(pkt, argp, arglen);
1726 sargp = va_arg(ap, char *);
1727 ssh_pkt_addstring(pkt, sargp);
1730 bn = va_arg(ap, Bignum);
1731 ssh1_pkt_addmp(pkt, bn);
1733 /* Tokens for modifications to packet logging */
1735 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1738 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1741 end_log_omission(ssh, pkt);
1749 static void send_packet(Ssh ssh, int pkttype, ...)
1753 va_start(ap, pkttype);
1754 pkt = construct_packet(ssh, pkttype, ap);
1759 static void defer_packet(Ssh ssh, int pkttype, ...)
1763 va_start(ap, pkttype);
1764 pkt = construct_packet(ssh, pkttype, ap);
1766 s_wrpkt_defer(ssh, pkt);
1769 static int ssh_versioncmp(char *a, char *b)
1772 unsigned long av, bv;
1774 av = strtoul(a, &ae, 10);
1775 bv = strtoul(b, &be, 10);
1777 return (av < bv ? -1 : +1);
1782 av = strtoul(ae, &ae, 10);
1783 bv = strtoul(be, &be, 10);
1785 return (av < bv ? -1 : +1);
1790 * Utility routines for putting an SSH-protocol `string' and
1791 * `uint32' into a hash state.
1793 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1795 unsigned char lenblk[4];
1796 PUT_32BIT(lenblk, len);
1797 h->bytes(s, lenblk, 4);
1798 h->bytes(s, str, len);
1801 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1803 unsigned char intblk[4];
1804 PUT_32BIT(intblk, i);
1805 h->bytes(s, intblk, 4);
1809 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1811 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1813 if (pkt->maxlen < length) {
1814 unsigned char *body = pkt->body;
1815 int offset = body ? body - pkt->data : 0;
1816 pkt->maxlen = length + 256;
1817 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1818 if (body) pkt->body = pkt->data + offset;
1821 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1823 if (pkt->logmode != PKTLOG_EMIT) {
1825 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1827 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1828 (pkt->body - pkt->data);
1829 pkt->blanks[pkt->nblanks-1].len = len;
1830 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1833 ssh_pkt_ensure(pkt, pkt->length);
1834 memcpy(pkt->data + pkt->length - len, data, len);
1836 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1838 ssh_pkt_adddata(pkt, &byte, 1);
1840 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1842 ssh_pkt_adddata(pkt, &value, 1);
1844 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1847 PUT_32BIT(x, value);
1848 ssh_pkt_adddata(pkt, x, 4);
1850 static void ssh_pkt_addstring_start(struct Packet *pkt)
1852 ssh_pkt_adduint32(pkt, 0);
1853 pkt->savedpos = pkt->length;
1855 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1857 ssh_pkt_adddata(pkt, data, strlen(data));
1858 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1860 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1862 ssh_pkt_adddata(pkt, data, len);
1863 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1865 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1867 ssh_pkt_addstring_start(pkt);
1868 ssh_pkt_addstring_str(pkt, data);
1870 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1872 int len = ssh1_bignum_length(b);
1873 unsigned char *data = snewn(len, unsigned char);
1874 (void) ssh1_write_bignum(data, b);
1875 ssh_pkt_adddata(pkt, data, len);
1878 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1881 int i, n = (bignum_bitcount(b) + 7) / 8;
1882 p = snewn(n + 1, unsigned char);
1884 for (i = 1; i <= n; i++)
1885 p[i] = bignum_byte(b, n - i);
1887 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1889 memmove(p, p + i, n + 1 - i);
1893 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1897 p = ssh2_mpint_fmt(b, &len);
1898 ssh_pkt_addstring_start(pkt);
1899 ssh_pkt_addstring_data(pkt, (char *)p, len);
1903 static struct Packet *ssh1_pkt_init(int pkt_type)
1905 struct Packet *pkt = ssh_new_packet();
1906 pkt->length = 4 + 8; /* space for length + max padding */
1907 ssh_pkt_addbyte(pkt, pkt_type);
1908 pkt->body = pkt->data + pkt->length;
1912 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1913 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1914 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1915 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1916 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1917 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1918 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1919 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1920 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1922 static struct Packet *ssh2_pkt_init(int pkt_type)
1924 struct Packet *pkt = ssh_new_packet();
1925 pkt->length = 5; /* space for packet length + padding length */
1927 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1928 pkt->body = pkt->data + pkt->length; /* after packet type */
1933 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1934 * put the MAC on it. Final packet, ready to be sent, is stored in
1935 * pkt->data. Total length is returned.
1937 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1939 int cipherblk, maclen, padding, i;
1942 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1943 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1944 pkt->body, pkt->length - (pkt->body - pkt->data),
1945 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1946 sfree(pkt->blanks); pkt->blanks = NULL;
1950 * Compress packet payload.
1953 unsigned char *newpayload;
1956 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1958 &newpayload, &newlen)) {
1960 ssh2_pkt_adddata(pkt, newpayload, newlen);
1966 * Add padding. At least four bytes, and must also bring total
1967 * length (minus MAC) up to a multiple of the block size.
1968 * If pkt->forcepad is set, make sure the packet is at least that size
1971 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1972 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1974 if (pkt->length + padding < pkt->forcepad)
1975 padding = pkt->forcepad - pkt->length;
1977 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1978 assert(padding <= 255);
1979 maclen = ssh->csmac ? ssh->csmac->len : 0;
1980 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1981 pkt->data[4] = padding;
1982 for (i = 0; i < padding; i++)
1983 pkt->data[pkt->length + i] = random_byte();
1984 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1986 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1987 pkt->length + padding,
1988 ssh->v2_outgoing_sequence);
1989 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1992 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1993 pkt->data, pkt->length + padding);
1995 pkt->encrypted_len = pkt->length + padding;
1997 /* Ready-to-send packet starts at pkt->data. We return length. */
1998 return pkt->length + padding + maclen;
2002 * Routines called from the main SSH code to send packets. There
2003 * are quite a few of these, because we have two separate
2004 * mechanisms for delaying the sending of packets:
2006 * - In order to send an IGNORE message and a password message in
2007 * a single fixed-length blob, we require the ability to
2008 * concatenate the encrypted forms of those two packets _into_ a
2009 * single blob and then pass it to our <network.h> transport
2010 * layer in one go. Hence, there's a deferment mechanism which
2011 * works after packet encryption.
2013 * - In order to avoid sending any connection-layer messages
2014 * during repeat key exchange, we have to queue up any such
2015 * outgoing messages _before_ they are encrypted (and in
2016 * particular before they're allocated sequence numbers), and
2017 * then send them once we've finished.
2019 * I call these mechanisms `defer' and `queue' respectively, so as
2020 * to distinguish them reasonably easily.
2022 * The functions send_noqueue() and defer_noqueue() free the packet
2023 * structure they are passed. Every outgoing packet goes through
2024 * precisely one of these functions in its life; packets passed to
2025 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2026 * these or get queued, and then when the queue is later emptied
2027 * the packets are all passed to defer_noqueue().
2029 * When using a CBC-mode cipher, it's necessary to ensure that an
2030 * attacker can't provide data to be encrypted using an IV that they
2031 * know. We ensure this by prefixing each packet that might contain
2032 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2033 * mechanism, so in this case send_noqueue() ends up redirecting to
2034 * defer_noqueue(). If you don't like this inefficiency, don't use
2038 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2039 static void ssh_pkt_defersend(Ssh);
2042 * Send an SSH-2 packet immediately, without queuing or deferring.
2044 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2048 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2049 /* We need to send two packets, so use the deferral mechanism. */
2050 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2051 ssh_pkt_defersend(ssh);
2054 len = ssh2_pkt_construct(ssh, pkt);
2055 backlog = s_write(ssh, pkt->data, len);
2056 if (backlog > SSH_MAX_BACKLOG)
2057 ssh_throttle_all(ssh, 1, backlog);
2059 ssh->outgoing_data_size += pkt->encrypted_len;
2060 if (!ssh->kex_in_progress &&
2061 ssh->max_data_size != 0 &&
2062 ssh->outgoing_data_size > ssh->max_data_size)
2063 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2065 ssh_free_packet(pkt);
2069 * Defer an SSH-2 packet.
2071 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2074 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2075 ssh->deferred_len == 0 && !noignore &&
2076 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2078 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2079 * get encrypted with a known IV.
2081 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2082 ssh2_pkt_addstring_start(ipkt);
2083 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2085 len = ssh2_pkt_construct(ssh, pkt);
2086 if (ssh->deferred_len + len > ssh->deferred_size) {
2087 ssh->deferred_size = ssh->deferred_len + len + 128;
2088 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2092 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2093 ssh->deferred_len += len;
2094 ssh->deferred_data_size += pkt->encrypted_len;
2095 ssh_free_packet(pkt);
2099 * Queue an SSH-2 packet.
2101 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2103 assert(ssh->queueing);
2105 if (ssh->queuelen >= ssh->queuesize) {
2106 ssh->queuesize = ssh->queuelen + 32;
2107 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2110 ssh->queue[ssh->queuelen++] = pkt;
2114 * Either queue or send a packet, depending on whether queueing is
2117 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2120 ssh2_pkt_queue(ssh, pkt);
2122 ssh2_pkt_send_noqueue(ssh, pkt);
2126 * Either queue or defer a packet, depending on whether queueing is
2129 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2132 ssh2_pkt_queue(ssh, pkt);
2134 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2138 * Send the whole deferred data block constructed by
2139 * ssh2_pkt_defer() or SSH-1's defer_packet().
2141 * The expected use of the defer mechanism is that you call
2142 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2143 * not currently queueing, this simply sets up deferred_send_data
2144 * and then sends it. If we _are_ currently queueing, the calls to
2145 * ssh2_pkt_defer() put the deferred packets on to the queue
2146 * instead, and therefore ssh_pkt_defersend() has no deferred data
2147 * to send. Hence, there's no need to make it conditional on
2150 static void ssh_pkt_defersend(Ssh ssh)
2153 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2154 ssh->deferred_len = ssh->deferred_size = 0;
2155 sfree(ssh->deferred_send_data);
2156 ssh->deferred_send_data = NULL;
2157 if (backlog > SSH_MAX_BACKLOG)
2158 ssh_throttle_all(ssh, 1, backlog);
2160 ssh->outgoing_data_size += ssh->deferred_data_size;
2161 if (!ssh->kex_in_progress &&
2162 ssh->max_data_size != 0 &&
2163 ssh->outgoing_data_size > ssh->max_data_size)
2164 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2165 ssh->deferred_data_size = 0;
2169 * Send a packet whose length needs to be disguised (typically
2170 * passwords or keyboard-interactive responses).
2172 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2178 * The simplest way to do this is to adjust the
2179 * variable-length padding field in the outgoing packet.
2181 * Currently compiled out, because some Cisco SSH servers
2182 * don't like excessively padded packets (bah, why's it
2185 pkt->forcepad = padsize;
2186 ssh2_pkt_send(ssh, pkt);
2191 * If we can't do that, however, an alternative approach is
2192 * to use the pkt_defer mechanism to bundle the packet
2193 * tightly together with an SSH_MSG_IGNORE such that their
2194 * combined length is a constant. So first we construct the
2195 * final form of this packet and defer its sending.
2197 ssh2_pkt_defer(ssh, pkt);
2200 * Now construct an SSH_MSG_IGNORE which includes a string
2201 * that's an exact multiple of the cipher block size. (If
2202 * the cipher is NULL so that the block size is
2203 * unavailable, we don't do this trick at all, because we
2204 * gain nothing by it.)
2206 if (ssh->cscipher &&
2207 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2210 stringlen = (256 - ssh->deferred_len);
2211 stringlen += ssh->cscipher->blksize - 1;
2212 stringlen -= (stringlen % ssh->cscipher->blksize);
2215 * Temporarily disable actual compression, so we
2216 * can guarantee to get this string exactly the
2217 * length we want it. The compression-disabling
2218 * routine should return an integer indicating how
2219 * many bytes we should adjust our string length
2223 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2225 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2226 ssh2_pkt_addstring_start(pkt);
2227 for (i = 0; i < stringlen; i++) {
2228 char c = (char) random_byte();
2229 ssh2_pkt_addstring_data(pkt, &c, 1);
2231 ssh2_pkt_defer(ssh, pkt);
2233 ssh_pkt_defersend(ssh);
2238 * Send all queued SSH-2 packets. We send them by means of
2239 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2240 * packets that needed to be lumped together.
2242 static void ssh2_pkt_queuesend(Ssh ssh)
2246 assert(!ssh->queueing);
2248 for (i = 0; i < ssh->queuelen; i++)
2249 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2252 ssh_pkt_defersend(ssh);
2256 void bndebug(char *string, Bignum b)
2260 p = ssh2_mpint_fmt(b, &len);
2261 debug(("%s", string));
2262 for (i = 0; i < len; i++)
2263 debug((" %02x", p[i]));
2269 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2273 p = ssh2_mpint_fmt(b, &len);
2274 hash_string(h, s, p, len);
2279 * Packet decode functions for both SSH-1 and SSH-2.
2281 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2283 unsigned long value;
2284 if (pkt->length - pkt->savedpos < 4)
2285 return 0; /* arrgh, no way to decline (FIXME?) */
2286 value = GET_32BIT(pkt->body + pkt->savedpos);
2290 static int ssh2_pkt_getbool(struct Packet *pkt)
2292 unsigned long value;
2293 if (pkt->length - pkt->savedpos < 1)
2294 return 0; /* arrgh, no way to decline (FIXME?) */
2295 value = pkt->body[pkt->savedpos] != 0;
2299 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2304 if (pkt->length - pkt->savedpos < 4)
2306 len = GET_32BIT(pkt->body + pkt->savedpos);
2311 if (pkt->length - pkt->savedpos < *length)
2313 *p = (char *)(pkt->body + pkt->savedpos);
2314 pkt->savedpos += *length;
2316 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2318 if (pkt->length - pkt->savedpos < length)
2320 pkt->savedpos += length;
2321 return pkt->body + (pkt->savedpos - length);
2323 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2324 unsigned char **keystr)
2328 j = makekey(pkt->body + pkt->savedpos,
2329 pkt->length - pkt->savedpos,
2336 assert(pkt->savedpos < pkt->length);
2340 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2345 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2346 pkt->length - pkt->savedpos, &b);
2354 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2360 ssh_pkt_getstring(pkt, &p, &length);
2365 b = bignum_from_bytes((unsigned char *)p, length);
2370 * Helper function to add an SSH-2 signature blob to a packet.
2371 * Expects to be shown the public key blob as well as the signature
2372 * blob. Normally works just like ssh2_pkt_addstring, but will
2373 * fiddle with the signature packet if necessary for
2374 * BUG_SSH2_RSA_PADDING.
2376 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2377 void *pkblob_v, int pkblob_len,
2378 void *sigblob_v, int sigblob_len)
2380 unsigned char *pkblob = (unsigned char *)pkblob_v;
2381 unsigned char *sigblob = (unsigned char *)sigblob_v;
2383 /* dmemdump(pkblob, pkblob_len); */
2384 /* dmemdump(sigblob, sigblob_len); */
2387 * See if this is in fact an ssh-rsa signature and a buggy
2388 * server; otherwise we can just do this the easy way.
2390 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2391 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2392 int pos, len, siglen;
2395 * Find the byte length of the modulus.
2398 pos = 4+7; /* skip over "ssh-rsa" */
2399 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2400 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2401 pos += 4; /* find modulus itself */
2402 while (len > 0 && pkblob[pos] == 0)
2404 /* debug(("modulus length is %d\n", len)); */
2407 * Now find the signature integer.
2409 pos = 4+7; /* skip over "ssh-rsa" */
2410 siglen = GET_32BIT(sigblob+pos);
2411 /* debug(("signature length is %d\n", siglen)); */
2413 if (len != siglen) {
2414 unsigned char newlen[4];
2415 ssh2_pkt_addstring_start(pkt);
2416 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2417 /* dmemdump(sigblob, pos); */
2418 pos += 4; /* point to start of actual sig */
2419 PUT_32BIT(newlen, len);
2420 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2421 /* dmemdump(newlen, 4); */
2423 while (len-- > siglen) {
2424 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2425 /* dmemdump(newlen, 1); */
2427 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2428 /* dmemdump(sigblob+pos, siglen); */
2432 /* Otherwise fall through and do it the easy way. */
2435 ssh2_pkt_addstring_start(pkt);
2436 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2440 * Examine the remote side's version string and compare it against
2441 * a list of known buggy implementations.
2443 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2445 char *imp; /* pointer to implementation part */
2447 imp += strcspn(imp, "-");
2449 imp += strcspn(imp, "-");
2452 ssh->remote_bugs = 0;
2455 * General notes on server version strings:
2456 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2457 * here -- in particular, we've heard of one that's perfectly happy
2458 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2459 * so we can't distinguish them.
2461 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2462 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2463 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2464 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2465 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2466 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2468 * These versions don't support SSH1_MSG_IGNORE, so we have
2469 * to use a different defence against password length
2472 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2473 logevent("We believe remote version has SSH-1 ignore bug");
2476 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2477 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2478 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2480 * These versions need a plain password sent; they can't
2481 * handle having a null and a random length of data after
2484 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2485 logevent("We believe remote version needs a plain SSH-1 password");
2488 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2489 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2490 (!strcmp(imp, "Cisco-1.25")))) {
2492 * These versions apparently have no clue whatever about
2493 * RSA authentication and will panic and die if they see
2494 * an AUTH_RSA message.
2496 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2497 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2500 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2501 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2502 !wc_match("* VShell", imp) &&
2503 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2504 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2505 wc_match("2.1 *", imp)))) {
2507 * These versions have the HMAC bug.
2509 ssh->remote_bugs |= BUG_SSH2_HMAC;
2510 logevent("We believe remote version has SSH-2 HMAC bug");
2513 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2514 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2515 !wc_match("* VShell", imp) &&
2516 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2518 * These versions have the key-derivation bug (failing to
2519 * include the literal shared secret in the hashes that
2520 * generate the keys).
2522 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2523 logevent("We believe remote version has SSH-2 key-derivation bug");
2526 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2527 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2528 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2529 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2531 * These versions have the SSH-2 RSA padding bug.
2533 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2534 logevent("We believe remote version has SSH-2 RSA padding bug");
2537 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2538 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2539 wc_match("OpenSSH_2.[0-2]*", imp))) {
2541 * These versions have the SSH-2 session-ID bug in
2542 * public-key authentication.
2544 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2545 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2548 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2549 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2550 (wc_match("DigiSSH_2.0", imp) ||
2551 wc_match("OpenSSH_2.[0-4]*", imp) ||
2552 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2553 wc_match("Sun_SSH_1.0", imp) ||
2554 wc_match("Sun_SSH_1.0.1", imp) ||
2555 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2556 wc_match("WeOnlyDo-*", imp)))) {
2558 * These versions have the SSH-2 rekey bug.
2560 ssh->remote_bugs |= BUG_SSH2_REKEY;
2561 logevent("We believe remote version has SSH-2 rekey bug");
2564 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2565 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2566 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2567 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2569 * This version ignores our makpkt and needs to be throttled.
2571 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2572 logevent("We believe remote version ignores SSH-2 maximum packet size");
2575 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2577 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2578 * none detected automatically.
2580 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2581 logevent("We believe remote version has SSH-2 ignore bug");
2584 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2586 * Servers that don't support our winadj request for one
2587 * reason or another. Currently, none detected automatically.
2589 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2590 logevent("We believe remote version has winadj bug");
2595 * The `software version' part of an SSH version string is required
2596 * to contain no spaces or minus signs.
2598 static void ssh_fix_verstring(char *str)
2600 /* Eat "SSH-<protoversion>-". */
2601 assert(*str == 'S'); str++;
2602 assert(*str == 'S'); str++;
2603 assert(*str == 'H'); str++;
2604 assert(*str == '-'); str++;
2605 while (*str && *str != '-') str++;
2606 assert(*str == '-'); str++;
2608 /* Convert minus signs and spaces in the remaining string into
2611 if (*str == '-' || *str == ' ')
2618 * Send an appropriate SSH version string.
2620 static void ssh_send_verstring(Ssh ssh, char *svers)
2624 if (ssh->version == 2) {
2626 * Construct a v2 version string.
2628 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2631 * Construct a v1 version string.
2633 verstring = dupprintf("SSH-%s-%s\012",
2634 (ssh_versioncmp(svers, "1.5") <= 0 ?
2639 ssh_fix_verstring(verstring);
2641 if (ssh->version == 2) {
2644 * Record our version string.
2646 len = strcspn(verstring, "\015\012");
2647 ssh->v_c = snewn(len + 1, char);
2648 memcpy(ssh->v_c, verstring, len);
2652 logeventf(ssh, "We claim version: %.*s",
2653 strcspn(verstring, "\015\012"), verstring);
2654 s_write(ssh, verstring, strlen(verstring));
2658 static int do_ssh_init(Ssh ssh, unsigned char c)
2660 struct do_ssh_init_state {
2669 crState(do_ssh_init_state);
2673 /* Search for a line beginning with the string "SSH-" in the input. */
2675 if (c != 'S') goto no;
2677 if (c != 'S') goto no;
2679 if (c != 'H') goto no;
2681 if (c != '-') goto no;
2690 s->vstring = snewn(s->vstrsize, char);
2691 strcpy(s->vstring, "SSH-");
2695 crReturn(1); /* get another char */
2696 if (s->vslen >= s->vstrsize - 1) {
2698 s->vstring = sresize(s->vstring, s->vstrsize, char);
2700 s->vstring[s->vslen++] = c;
2703 s->version[s->i] = '\0';
2705 } else if (s->i < sizeof(s->version) - 1)
2706 s->version[s->i++] = c;
2707 } else if (c == '\012')
2711 ssh->agentfwd_enabled = FALSE;
2712 ssh->rdpkt2_state.incoming_sequence = 0;
2714 s->vstring[s->vslen] = 0;
2715 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2716 logeventf(ssh, "Server version: %s", s->vstring);
2717 ssh_detect_bugs(ssh, s->vstring);
2720 * Decide which SSH protocol version to support.
2723 /* Anything strictly below "2.0" means protocol 1 is supported. */
2724 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2725 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2726 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2728 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2729 bombout(("SSH protocol version 1 required by user but not provided by server"));
2732 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2733 bombout(("SSH protocol version 2 required by user but not provided by server"));
2737 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2742 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2744 /* Send the version string, if we haven't already */
2745 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2746 ssh_send_verstring(ssh, s->version);
2748 if (ssh->version == 2) {
2751 * Record their version string.
2753 len = strcspn(s->vstring, "\015\012");
2754 ssh->v_s = snewn(len + 1, char);
2755 memcpy(ssh->v_s, s->vstring, len);
2759 * Initialise SSH-2 protocol.
2761 ssh->protocol = ssh2_protocol;
2762 ssh2_protocol_setup(ssh);
2763 ssh->s_rdpkt = ssh2_rdpkt;
2766 * Initialise SSH-1 protocol.
2768 ssh->protocol = ssh1_protocol;
2769 ssh1_protocol_setup(ssh);
2770 ssh->s_rdpkt = ssh1_rdpkt;
2772 if (ssh->version == 2)
2773 do_ssh2_transport(ssh, NULL, -1, NULL);
2775 update_specials_menu(ssh->frontend);
2776 ssh->state = SSH_STATE_BEFORE_SIZE;
2777 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2784 static void ssh_process_incoming_data(Ssh ssh,
2785 unsigned char **data, int *datalen)
2787 struct Packet *pktin;
2789 pktin = ssh->s_rdpkt(ssh, data, datalen);
2791 ssh->protocol(ssh, NULL, 0, pktin);
2792 ssh_free_packet(pktin);
2796 static void ssh_queue_incoming_data(Ssh ssh,
2797 unsigned char **data, int *datalen)
2799 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2804 static void ssh_process_queued_incoming_data(Ssh ssh)
2807 unsigned char *data;
2810 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2811 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2815 while (!ssh->frozen && len > 0)
2816 ssh_process_incoming_data(ssh, &data, &len);
2819 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2823 static void ssh_set_frozen(Ssh ssh, int frozen)
2826 sk_set_frozen(ssh->s, frozen);
2827 ssh->frozen = frozen;
2830 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2832 /* Log raw data, if we're in that mode. */
2834 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2837 crBegin(ssh->ssh_gotdata_crstate);
2840 * To begin with, feed the characters one by one to the
2841 * protocol initialisation / selection function do_ssh_init().
2842 * When that returns 0, we're done with the initial greeting
2843 * exchange and can move on to packet discipline.
2846 int ret; /* need not be kept across crReturn */
2848 crReturnV; /* more data please */
2849 ret = do_ssh_init(ssh, *data);
2857 * We emerge from that loop when the initial negotiation is
2858 * over and we have selected an s_rdpkt function. Now pass
2859 * everything to s_rdpkt, and then pass the resulting packets
2860 * to the proper protocol handler.
2864 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2866 ssh_queue_incoming_data(ssh, &data, &datalen);
2867 /* This uses up all data and cannot cause anything interesting
2868 * to happen; indeed, for anything to happen at all, we must
2869 * return, so break out. */
2871 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2872 /* This uses up some or all data, and may freeze the
2874 ssh_process_queued_incoming_data(ssh);
2876 /* This uses up some or all data, and may freeze the
2878 ssh_process_incoming_data(ssh, &data, &datalen);
2880 /* FIXME this is probably EBW. */
2881 if (ssh->state == SSH_STATE_CLOSED)
2884 /* We're out of data. Go and get some more. */
2890 static int ssh_do_close(Ssh ssh, int notify_exit)
2893 struct ssh_channel *c;
2895 ssh->state = SSH_STATE_CLOSED;
2896 expire_timer_context(ssh);
2901 notify_remote_exit(ssh->frontend);
2906 * Now we must shut down any port- and X-forwarded channels going
2907 * through this connection.
2909 if (ssh->channels) {
2910 while (NULL != (c = index234(ssh->channels, 0))) {
2913 x11_close(c->u.x11.s);
2916 case CHAN_SOCKDATA_DORMANT:
2917 pfd_close(c->u.pfd.s);
2920 del234(ssh->channels, c); /* moving next one to index 0 */
2921 if (ssh->version == 2)
2922 bufchain_clear(&c->v.v2.outbuffer);
2927 * Go through port-forwardings, and close any associated
2928 * listening sockets.
2930 if (ssh->portfwds) {
2931 struct ssh_portfwd *pf;
2932 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2933 /* Dispose of any listening socket. */
2935 pfd_terminate(pf->local);
2936 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2939 freetree234(ssh->portfwds);
2940 ssh->portfwds = NULL;
2946 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2947 const char *error_msg, int error_code)
2949 Ssh ssh = (Ssh) plug;
2950 char addrbuf[256], *msg;
2952 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2955 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2957 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2963 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2966 Ssh ssh = (Ssh) plug;
2967 int need_notify = ssh_do_close(ssh, FALSE);
2970 if (!ssh->close_expected)
2971 error_msg = "Server unexpectedly closed network connection";
2973 error_msg = "Server closed network connection";
2976 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2980 notify_remote_exit(ssh->frontend);
2983 logevent(error_msg);
2984 if (!ssh->close_expected || !ssh->clean_exit)
2985 connection_fatal(ssh->frontend, "%s", error_msg);
2989 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2991 Ssh ssh = (Ssh) plug;
2992 ssh_gotdata(ssh, (unsigned char *)data, len);
2993 if (ssh->state == SSH_STATE_CLOSED) {
2994 ssh_do_close(ssh, TRUE);
3000 static void ssh_sent(Plug plug, int bufsize)
3002 Ssh ssh = (Ssh) plug;
3004 * If the send backlog on the SSH socket itself clears, we
3005 * should unthrottle the whole world if it was throttled.
3007 if (bufsize < SSH_MAX_BACKLOG)
3008 ssh_throttle_all(ssh, 0, bufsize);
3012 * Connect to specified host and port.
3013 * Returns an error message, or NULL on success.
3014 * Also places the canonical host name into `realhost'. It must be
3015 * freed by the caller.
3017 static const char *connect_to_host(Ssh ssh, char *host, int port,
3018 char **realhost, int nodelay, int keepalive)
3020 static const struct plug_function_table fn_table = {
3031 int addressfamily, sshprot;
3033 loghost = conf_get_str(ssh->conf, CONF_loghost);
3037 ssh->savedhost = dupstr(loghost);
3038 ssh->savedport = 22; /* default ssh port */
3041 * A colon suffix on savedhost also lets us affect
3044 * (FIXME: do something about IPv6 address literals here.)
3046 colon = strrchr(ssh->savedhost, ':');
3050 ssh->savedport = atoi(colon);
3053 ssh->savedhost = dupstr(host);
3055 port = 22; /* default ssh port */
3056 ssh->savedport = port;
3062 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3063 logeventf(ssh, "Looking up host \"%s\"%s", host,
3064 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3065 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3066 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3067 if ((err = sk_addr_error(addr)) != NULL) {
3071 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3076 ssh->fn = &fn_table;
3077 ssh->s = new_connection(addr, *realhost, port,
3078 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3079 if ((err = sk_socket_error(ssh->s)) != NULL) {
3081 notify_remote_exit(ssh->frontend);
3086 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3087 * send the version string too.
3089 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3094 ssh_send_verstring(ssh, NULL);
3098 * loghost, if configured, overrides realhost.
3102 *realhost = dupstr(loghost);
3109 * Throttle or unthrottle the SSH connection.
3111 static void ssh_throttle_conn(Ssh ssh, int adjust)
3113 int old_count = ssh->conn_throttle_count;
3114 ssh->conn_throttle_count += adjust;
3115 assert(ssh->conn_throttle_count >= 0);
3116 if (ssh->conn_throttle_count && !old_count) {
3117 ssh_set_frozen(ssh, 1);
3118 } else if (!ssh->conn_throttle_count && old_count) {
3119 ssh_set_frozen(ssh, 0);
3124 * Throttle or unthrottle _all_ local data streams (for when sends
3125 * on the SSH connection itself back up).
3127 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3130 struct ssh_channel *c;
3132 if (enable == ssh->throttled_all)
3134 ssh->throttled_all = enable;
3135 ssh->overall_bufsize = bufsize;
3138 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3140 case CHAN_MAINSESSION:
3142 * This is treated separately, outside the switch.
3146 x11_override_throttle(c->u.x11.s, enable);
3149 /* Agent channels require no buffer management. */
3152 pfd_override_throttle(c->u.pfd.s, enable);
3158 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3160 Ssh ssh = (Ssh) sshv;
3162 ssh->agent_response = reply;
3163 ssh->agent_response_len = replylen;
3165 if (ssh->version == 1)
3166 do_ssh1_login(ssh, NULL, -1, NULL);
3168 do_ssh2_authconn(ssh, NULL, -1, NULL);
3171 static void ssh_dialog_callback(void *sshv, int ret)
3173 Ssh ssh = (Ssh) sshv;
3175 ssh->user_response = ret;
3177 if (ssh->version == 1)
3178 do_ssh1_login(ssh, NULL, -1, NULL);
3180 do_ssh2_transport(ssh, NULL, -1, NULL);
3183 * This may have unfrozen the SSH connection, so do a
3186 ssh_process_queued_incoming_data(ssh);
3189 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3191 struct ssh_channel *c = (struct ssh_channel *)cv;
3193 void *sentreply = reply;
3196 /* Fake SSH_AGENT_FAILURE. */
3197 sentreply = "\0\0\0\1\5";
3200 if (ssh->version == 2) {
3201 ssh2_add_channel_data(c, sentreply, replylen);
3204 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3205 PKT_INT, c->remoteid,
3208 PKT_DATA, sentreply, replylen,
3217 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3218 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3219 * => log `wire_reason'.
3221 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3222 int code, int clean_exit)
3226 client_reason = wire_reason;
3228 error = dupprintf("Disconnected: %s", client_reason);
3230 error = dupstr("Disconnected");
3232 if (ssh->version == 1) {
3233 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3235 } else if (ssh->version == 2) {
3236 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3237 ssh2_pkt_adduint32(pktout, code);
3238 ssh2_pkt_addstring(pktout, wire_reason);
3239 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3240 ssh2_pkt_send_noqueue(ssh, pktout);
3243 ssh->close_expected = TRUE;
3244 ssh->clean_exit = clean_exit;
3245 ssh_closing((Plug)ssh, error, 0, 0);
3250 * Handle the key exchange and user authentication phases.
3252 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3253 struct Packet *pktin)
3256 unsigned char cookie[8], *ptr;
3257 struct RSAKey servkey, hostkey;
3258 struct MD5Context md5c;
3259 struct do_ssh1_login_state {
3262 unsigned char *rsabuf, *keystr1, *keystr2;
3263 unsigned long supported_ciphers_mask, supported_auths_mask;
3264 int tried_publickey, tried_agent;
3265 int tis_auth_refused, ccard_auth_refused;
3266 unsigned char session_id[16];
3268 void *publickey_blob;
3269 int publickey_bloblen;
3270 char *publickey_comment;
3271 int publickey_encrypted;
3272 prompts_t *cur_prompt;
3275 unsigned char request[5], *response, *p;
3286 crState(do_ssh1_login_state);
3293 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3294 bombout(("Public key packet not received"));
3298 logevent("Received public keys");
3300 ptr = ssh_pkt_getdata(pktin, 8);
3302 bombout(("SSH-1 public key packet stopped before random cookie"));
3305 memcpy(cookie, ptr, 8);
3307 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3308 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3309 bombout(("Failed to read SSH-1 public keys from public key packet"));
3314 * Log the host key fingerprint.
3318 logevent("Host key fingerprint is:");
3319 strcpy(logmsg, " ");
3320 hostkey.comment = NULL;
3321 rsa_fingerprint(logmsg + strlen(logmsg),
3322 sizeof(logmsg) - strlen(logmsg), &hostkey);
3326 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3327 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3328 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3329 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3330 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3332 ssh->v1_local_protoflags =
3333 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3334 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3337 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3338 MD5Update(&md5c, s->keystr1, servkey.bytes);
3339 MD5Update(&md5c, cookie, 8);
3340 MD5Final(s->session_id, &md5c);
3342 for (i = 0; i < 32; i++)
3343 ssh->session_key[i] = random_byte();
3346 * Verify that the `bits' and `bytes' parameters match.
3348 if (hostkey.bits > hostkey.bytes * 8 ||
3349 servkey.bits > servkey.bytes * 8) {
3350 bombout(("SSH-1 public keys were badly formatted"));
3354 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3356 s->rsabuf = snewn(s->len, unsigned char);
3359 * Verify the host key.
3363 * First format the key into a string.
3365 int len = rsastr_len(&hostkey);
3366 char fingerprint[100];
3367 char *keystr = snewn(len, char);
3368 rsastr_fmt(keystr, &hostkey);
3369 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3371 ssh_set_frozen(ssh, 1);
3372 s->dlgret = verify_ssh_host_key(ssh->frontend,
3373 ssh->savedhost, ssh->savedport,
3374 "rsa", keystr, fingerprint,
3375 ssh_dialog_callback, ssh);
3377 if (s->dlgret < 0) {
3381 bombout(("Unexpected data from server while waiting"
3382 " for user host key response"));
3385 } while (pktin || inlen > 0);
3386 s->dlgret = ssh->user_response;
3388 ssh_set_frozen(ssh, 0);
3390 if (s->dlgret == 0) {
3391 ssh_disconnect(ssh, "User aborted at host key verification",
3397 for (i = 0; i < 32; i++) {
3398 s->rsabuf[i] = ssh->session_key[i];
3400 s->rsabuf[i] ^= s->session_id[i];
3403 if (hostkey.bytes > servkey.bytes) {
3404 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3406 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3408 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3410 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3413 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3417 logevent("Encrypted session key");
3420 int cipher_chosen = 0, warn = 0;
3421 char *cipher_string = NULL;
3423 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3424 int next_cipher = conf_get_int_int(ssh->conf,
3425 CONF_ssh_cipherlist, i);
3426 if (next_cipher == CIPHER_WARN) {
3427 /* If/when we choose a cipher, warn about it */
3429 } else if (next_cipher == CIPHER_AES) {
3430 /* XXX Probably don't need to mention this. */
3431 logevent("AES not supported in SSH-1, skipping");
3433 switch (next_cipher) {
3434 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3435 cipher_string = "3DES"; break;
3436 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3437 cipher_string = "Blowfish"; break;
3438 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3439 cipher_string = "single-DES"; break;
3441 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3445 if (!cipher_chosen) {
3446 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3447 bombout(("Server violates SSH-1 protocol by not "
3448 "supporting 3DES encryption"));
3450 /* shouldn't happen */
3451 bombout(("No supported ciphers found"));
3455 /* Warn about chosen cipher if necessary. */
3457 ssh_set_frozen(ssh, 1);
3458 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3459 ssh_dialog_callback, ssh);
3460 if (s->dlgret < 0) {
3464 bombout(("Unexpected data from server while waiting"
3465 " for user response"));
3468 } while (pktin || inlen > 0);
3469 s->dlgret = ssh->user_response;
3471 ssh_set_frozen(ssh, 0);
3472 if (s->dlgret == 0) {
3473 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3480 switch (s->cipher_type) {
3481 case SSH_CIPHER_3DES:
3482 logevent("Using 3DES encryption");
3484 case SSH_CIPHER_DES:
3485 logevent("Using single-DES encryption");
3487 case SSH_CIPHER_BLOWFISH:
3488 logevent("Using Blowfish encryption");
3492 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3493 PKT_CHAR, s->cipher_type,
3494 PKT_DATA, cookie, 8,
3495 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3496 PKT_DATA, s->rsabuf, s->len,
3497 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3499 logevent("Trying to enable encryption...");
3503 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3504 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3506 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3507 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3508 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3510 ssh->crcda_ctx = crcda_make_context();
3511 logevent("Installing CRC compensation attack detector");
3513 if (servkey.modulus) {
3514 sfree(servkey.modulus);
3515 servkey.modulus = NULL;
3517 if (servkey.exponent) {
3518 sfree(servkey.exponent);
3519 servkey.exponent = NULL;
3521 if (hostkey.modulus) {
3522 sfree(hostkey.modulus);
3523 hostkey.modulus = NULL;
3525 if (hostkey.exponent) {
3526 sfree(hostkey.exponent);
3527 hostkey.exponent = NULL;
3531 if (pktin->type != SSH1_SMSG_SUCCESS) {
3532 bombout(("Encryption not successfully enabled"));
3536 logevent("Successfully started encryption");
3538 fflush(stdout); /* FIXME eh? */
3540 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3541 int ret; /* need not be kept over crReturn */
3542 s->cur_prompt = new_prompts(ssh->frontend);
3543 s->cur_prompt->to_server = TRUE;
3544 s->cur_prompt->name = dupstr("SSH login name");
3545 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3546 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3549 crWaitUntil(!pktin);
3550 ret = get_userpass_input(s->cur_prompt, in, inlen);
3555 * Failed to get a username. Terminate.
3557 free_prompts(s->cur_prompt);
3558 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3561 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3562 free_prompts(s->cur_prompt);
3565 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3567 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3569 if (flags & FLAG_INTERACTIVE &&
3570 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3571 c_write_str(ssh, userlog);
3572 c_write_str(ssh, "\r\n");
3580 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3581 /* We must not attempt PK auth. Pretend we've already tried it. */
3582 s->tried_publickey = s->tried_agent = 1;
3584 s->tried_publickey = s->tried_agent = 0;
3586 s->tis_auth_refused = s->ccard_auth_refused = 0;
3588 * Load the public half of any configured keyfile for later use.
3590 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3591 if (!filename_is_null(s->keyfile)) {
3593 logeventf(ssh, "Reading private key file \"%.150s\"",
3594 filename_to_str(s->keyfile));
3595 keytype = key_type(s->keyfile);
3596 if (keytype == SSH_KEYTYPE_SSH1) {
3598 if (rsakey_pubblob(s->keyfile,
3599 &s->publickey_blob, &s->publickey_bloblen,
3600 &s->publickey_comment, &error)) {
3601 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3605 logeventf(ssh, "Unable to load private key (%s)", error);
3606 msgbuf = dupprintf("Unable to load private key file "
3607 "\"%.150s\" (%s)\r\n",
3608 filename_to_str(s->keyfile),
3610 c_write_str(ssh, msgbuf);
3612 s->publickey_blob = NULL;
3616 logeventf(ssh, "Unable to use this key file (%s)",
3617 key_type_to_str(keytype));
3618 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3620 filename_to_str(s->keyfile),
3621 key_type_to_str(keytype));
3622 c_write_str(ssh, msgbuf);
3624 s->publickey_blob = NULL;
3627 s->publickey_blob = NULL;
3629 while (pktin->type == SSH1_SMSG_FAILURE) {
3630 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3632 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3634 * Attempt RSA authentication using Pageant.
3640 logevent("Pageant is running. Requesting keys.");
3642 /* Request the keys held by the agent. */
3643 PUT_32BIT(s->request, 1);
3644 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3645 if (!agent_query(s->request, 5, &r, &s->responselen,
3646 ssh_agent_callback, ssh)) {
3650 bombout(("Unexpected data from server while waiting"
3651 " for agent response"));
3654 } while (pktin || inlen > 0);
3655 r = ssh->agent_response;
3656 s->responselen = ssh->agent_response_len;
3658 s->response = (unsigned char *) r;
3659 if (s->response && s->responselen >= 5 &&
3660 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3661 s->p = s->response + 5;
3662 s->nkeys = GET_32BIT(s->p);
3664 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3665 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3666 unsigned char *pkblob = s->p;
3670 do { /* do while (0) to make breaking easy */
3671 n = ssh1_read_bignum
3672 (s->p, s->responselen-(s->p-s->response),
3677 n = ssh1_read_bignum
3678 (s->p, s->responselen-(s->p-s->response),
3683 if (s->responselen - (s->p-s->response) < 4)
3685 s->commentlen = GET_32BIT(s->p);
3687 if (s->responselen - (s->p-s->response) <
3690 s->commentp = (char *)s->p;
3691 s->p += s->commentlen;
3695 logevent("Pageant key list packet was truncated");
3699 if (s->publickey_blob) {
3700 if (!memcmp(pkblob, s->publickey_blob,
3701 s->publickey_bloblen)) {
3702 logeventf(ssh, "Pageant key #%d matches "
3703 "configured key file", s->keyi);
3704 s->tried_publickey = 1;
3706 /* Skip non-configured key */
3709 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3710 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3711 PKT_BIGNUM, s->key.modulus, PKT_END);
3713 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3714 logevent("Key refused");
3717 logevent("Received RSA challenge");
3718 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3719 bombout(("Server's RSA challenge was badly formatted"));
3724 char *agentreq, *q, *ret;
3727 len = 1 + 4; /* message type, bit count */
3728 len += ssh1_bignum_length(s->key.exponent);
3729 len += ssh1_bignum_length(s->key.modulus);
3730 len += ssh1_bignum_length(s->challenge);
3731 len += 16; /* session id */
3732 len += 4; /* response format */
3733 agentreq = snewn(4 + len, char);
3734 PUT_32BIT(agentreq, len);
3736 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3737 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3739 q += ssh1_write_bignum(q, s->key.exponent);
3740 q += ssh1_write_bignum(q, s->key.modulus);
3741 q += ssh1_write_bignum(q, s->challenge);
3742 memcpy(q, s->session_id, 16);
3744 PUT_32BIT(q, 1); /* response format */
3745 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3746 ssh_agent_callback, ssh)) {
3751 bombout(("Unexpected data from server"
3752 " while waiting for agent"
3756 } while (pktin || inlen > 0);
3757 vret = ssh->agent_response;
3758 retlen = ssh->agent_response_len;
3763 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3764 logevent("Sending Pageant's response");
3765 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3766 PKT_DATA, ret + 5, 16,
3770 if (pktin->type == SSH1_SMSG_SUCCESS) {
3772 ("Pageant's response accepted");
3773 if (flags & FLAG_VERBOSE) {
3774 c_write_str(ssh, "Authenticated using"
3776 c_write(ssh, s->commentp,
3778 c_write_str(ssh, "\" from agent\r\n");
3783 ("Pageant's response not accepted");
3786 ("Pageant failed to answer challenge");
3790 logevent("No reply received from Pageant");
3793 freebn(s->key.exponent);
3794 freebn(s->key.modulus);
3795 freebn(s->challenge);
3800 if (s->publickey_blob && !s->tried_publickey)
3801 logevent("Configured key file not in Pageant");
3803 logevent("Failed to get reply from Pageant");
3808 if (s->publickey_blob && !s->tried_publickey) {
3810 * Try public key authentication with the specified
3813 int got_passphrase; /* need not be kept over crReturn */
3814 if (flags & FLAG_VERBOSE)
3815 c_write_str(ssh, "Trying public key authentication.\r\n");
3816 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3817 logeventf(ssh, "Trying public key \"%s\"",
3818 filename_to_str(s->keyfile));
3819 s->tried_publickey = 1;
3820 got_passphrase = FALSE;
3821 while (!got_passphrase) {
3823 * Get a passphrase, if necessary.
3825 char *passphrase = NULL; /* only written after crReturn */
3827 if (!s->publickey_encrypted) {
3828 if (flags & FLAG_VERBOSE)
3829 c_write_str(ssh, "No passphrase required.\r\n");
3832 int ret; /* need not be kept over crReturn */
3833 s->cur_prompt = new_prompts(ssh->frontend);
3834 s->cur_prompt->to_server = FALSE;
3835 s->cur_prompt->name = dupstr("SSH key passphrase");
3836 add_prompt(s->cur_prompt,
3837 dupprintf("Passphrase for key \"%.100s\": ",
3838 s->publickey_comment), FALSE);
3839 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3842 crWaitUntil(!pktin);
3843 ret = get_userpass_input(s->cur_prompt, in, inlen);
3847 /* Failed to get a passphrase. Terminate. */
3848 free_prompts(s->cur_prompt);
3849 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3853 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3854 free_prompts(s->cur_prompt);
3857 * Try decrypting key with passphrase.
3859 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3860 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3863 smemclr(passphrase, strlen(passphrase));
3867 /* Correct passphrase. */
3868 got_passphrase = TRUE;
3869 } else if (ret == 0) {
3870 c_write_str(ssh, "Couldn't load private key from ");
3871 c_write_str(ssh, filename_to_str(s->keyfile));
3872 c_write_str(ssh, " (");
3873 c_write_str(ssh, error);
3874 c_write_str(ssh, ").\r\n");
3875 got_passphrase = FALSE;
3876 break; /* go and try something else */
3877 } else if (ret == -1) {
3878 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3879 got_passphrase = FALSE;
3882 assert(0 && "unexpected return from loadrsakey()");
3883 got_passphrase = FALSE; /* placate optimisers */
3887 if (got_passphrase) {
3890 * Send a public key attempt.
3892 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3893 PKT_BIGNUM, s->key.modulus, PKT_END);
3896 if (pktin->type == SSH1_SMSG_FAILURE) {
3897 c_write_str(ssh, "Server refused our public key.\r\n");
3898 continue; /* go and try something else */
3900 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3901 bombout(("Bizarre response to offer of public key"));
3907 unsigned char buffer[32];
3908 Bignum challenge, response;
3910 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3911 bombout(("Server's RSA challenge was badly formatted"));
3914 response = rsadecrypt(challenge, &s->key);
3915 freebn(s->key.private_exponent);/* burn the evidence */
3917 for (i = 0; i < 32; i++) {
3918 buffer[i] = bignum_byte(response, 31 - i);
3922 MD5Update(&md5c, buffer, 32);
3923 MD5Update(&md5c, s->session_id, 16);
3924 MD5Final(buffer, &md5c);
3926 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3927 PKT_DATA, buffer, 16, PKT_END);
3934 if (pktin->type == SSH1_SMSG_FAILURE) {
3935 if (flags & FLAG_VERBOSE)
3936 c_write_str(ssh, "Failed to authenticate with"
3937 " our public key.\r\n");
3938 continue; /* go and try something else */
3939 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3940 bombout(("Bizarre response to RSA authentication response"));
3944 break; /* we're through! */
3950 * Otherwise, try various forms of password-like authentication.
3952 s->cur_prompt = new_prompts(ssh->frontend);
3954 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3955 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3956 !s->tis_auth_refused) {
3957 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3958 logevent("Requested TIS authentication");
3959 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3961 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3962 logevent("TIS authentication declined");
3963 if (flags & FLAG_INTERACTIVE)
3964 c_write_str(ssh, "TIS authentication refused.\r\n");
3965 s->tis_auth_refused = 1;
3970 char *instr_suf, *prompt;
3972 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3974 bombout(("TIS challenge packet was badly formed"));
3977 logevent("Received TIS challenge");
3978 s->cur_prompt->to_server = TRUE;
3979 s->cur_prompt->name = dupstr("SSH TIS authentication");
3980 /* Prompt heuristic comes from OpenSSH */
3981 if (memchr(challenge, '\n', challengelen)) {
3982 instr_suf = dupstr("");
3983 prompt = dupprintf("%.*s", challengelen, challenge);
3985 instr_suf = dupprintf("%.*s", challengelen, challenge);
3986 prompt = dupstr("Response: ");
3988 s->cur_prompt->instruction =
3989 dupprintf("Using TIS authentication.%s%s",
3990 (*instr_suf) ? "\n" : "",
3992 s->cur_prompt->instr_reqd = TRUE;
3993 add_prompt(s->cur_prompt, prompt, FALSE);
3997 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3998 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3999 !s->ccard_auth_refused) {
4000 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4001 logevent("Requested CryptoCard authentication");
4002 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4004 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4005 logevent("CryptoCard authentication declined");
4006 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4007 s->ccard_auth_refused = 1;
4012 char *instr_suf, *prompt;
4014 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4016 bombout(("CryptoCard challenge packet was badly formed"));
4019 logevent("Received CryptoCard challenge");
4020 s->cur_prompt->to_server = TRUE;
4021 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4022 s->cur_prompt->name_reqd = FALSE;
4023 /* Prompt heuristic comes from OpenSSH */
4024 if (memchr(challenge, '\n', challengelen)) {
4025 instr_suf = dupstr("");
4026 prompt = dupprintf("%.*s", challengelen, challenge);
4028 instr_suf = dupprintf("%.*s", challengelen, challenge);
4029 prompt = dupstr("Response: ");
4031 s->cur_prompt->instruction =
4032 dupprintf("Using CryptoCard authentication.%s%s",
4033 (*instr_suf) ? "\n" : "",
4035 s->cur_prompt->instr_reqd = TRUE;
4036 add_prompt(s->cur_prompt, prompt, FALSE);
4040 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4041 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4042 bombout(("No supported authentication methods available"));
4045 s->cur_prompt->to_server = TRUE;
4046 s->cur_prompt->name = dupstr("SSH password");
4047 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4048 ssh->username, ssh->savedhost),
4053 * Show password prompt, having first obtained it via a TIS
4054 * or CryptoCard exchange if we're doing TIS or CryptoCard
4058 int ret; /* need not be kept over crReturn */
4059 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4062 crWaitUntil(!pktin);
4063 ret = get_userpass_input(s->cur_prompt, in, inlen);
4068 * Failed to get a password (for example
4069 * because one was supplied on the command line
4070 * which has already failed to work). Terminate.
4072 free_prompts(s->cur_prompt);
4073 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4078 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4080 * Defence against traffic analysis: we send a
4081 * whole bunch of packets containing strings of
4082 * different lengths. One of these strings is the
4083 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4084 * The others are all random data in
4085 * SSH1_MSG_IGNORE packets. This way a passive
4086 * listener can't tell which is the password, and
4087 * hence can't deduce the password length.
4089 * Anybody with a password length greater than 16
4090 * bytes is going to have enough entropy in their
4091 * password that a listener won't find it _that_
4092 * much help to know how long it is. So what we'll
4095 * - if password length < 16, we send 15 packets
4096 * containing string lengths 1 through 15
4098 * - otherwise, we let N be the nearest multiple
4099 * of 8 below the password length, and send 8
4100 * packets containing string lengths N through
4101 * N+7. This won't obscure the order of
4102 * magnitude of the password length, but it will
4103 * introduce a bit of extra uncertainty.
4105 * A few servers can't deal with SSH1_MSG_IGNORE, at
4106 * least in this context. For these servers, we need
4107 * an alternative defence. We make use of the fact
4108 * that the password is interpreted as a C string:
4109 * so we can append a NUL, then some random data.
4111 * A few servers can deal with neither SSH1_MSG_IGNORE
4112 * here _nor_ a padded password string.
4113 * For these servers we are left with no defences
4114 * against password length sniffing.
4116 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4117 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4119 * The server can deal with SSH1_MSG_IGNORE, so
4120 * we can use the primary defence.
4122 int bottom, top, pwlen, i;
4125 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4127 bottom = 0; /* zero length passwords are OK! :-) */
4130 bottom = pwlen & ~7;
4134 assert(pwlen >= bottom && pwlen <= top);
4136 randomstr = snewn(top + 1, char);
4138 for (i = bottom; i <= top; i++) {
4140 defer_packet(ssh, s->pwpkt_type,
4141 PKTT_PASSWORD, PKT_STR,
4142 s->cur_prompt->prompts[0]->result,
4143 PKTT_OTHER, PKT_END);
4145 for (j = 0; j < i; j++) {
4147 randomstr[j] = random_byte();
4148 } while (randomstr[j] == '\0');
4150 randomstr[i] = '\0';
4151 defer_packet(ssh, SSH1_MSG_IGNORE,
4152 PKT_STR, randomstr, PKT_END);
4155 logevent("Sending password with camouflage packets");
4156 ssh_pkt_defersend(ssh);
4159 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4161 * The server can't deal with SSH1_MSG_IGNORE
4162 * but can deal with padded passwords, so we
4163 * can use the secondary defence.
4169 len = strlen(s->cur_prompt->prompts[0]->result);
4170 if (len < sizeof(string)) {
4172 strcpy(string, s->cur_prompt->prompts[0]->result);
4173 len++; /* cover the zero byte */
4174 while (len < sizeof(string)) {
4175 string[len++] = (char) random_byte();
4178 ss = s->cur_prompt->prompts[0]->result;
4180 logevent("Sending length-padded password");
4181 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4182 PKT_INT, len, PKT_DATA, ss, len,
4183 PKTT_OTHER, PKT_END);
4186 * The server is believed unable to cope with
4187 * any of our password camouflage methods.
4190 len = strlen(s->cur_prompt->prompts[0]->result);
4191 logevent("Sending unpadded password");
4192 send_packet(ssh, s->pwpkt_type,
4193 PKTT_PASSWORD, PKT_INT, len,
4194 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4195 PKTT_OTHER, PKT_END);
4198 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4199 PKT_STR, s->cur_prompt->prompts[0]->result,
4200 PKTT_OTHER, PKT_END);
4202 logevent("Sent password");
4203 free_prompts(s->cur_prompt);
4205 if (pktin->type == SSH1_SMSG_FAILURE) {
4206 if (flags & FLAG_VERBOSE)
4207 c_write_str(ssh, "Access denied\r\n");
4208 logevent("Authentication refused");
4209 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4210 bombout(("Strange packet received, type %d", pktin->type));
4216 if (s->publickey_blob) {
4217 sfree(s->publickey_blob);
4218 sfree(s->publickey_comment);
4221 logevent("Authentication successful");
4226 static void ssh_channel_try_eof(struct ssh_channel *c)
4229 assert(c->pending_eof); /* precondition for calling us */
4231 return; /* can't close: not even opened yet */
4232 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4233 return; /* can't send EOF: pending outgoing data */
4235 if (ssh->version == 1) {
4236 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4238 c->closes |= CLOSES_SENT_EOF;
4240 struct Packet *pktout;
4241 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4242 ssh2_pkt_adduint32(pktout, c->remoteid);
4243 ssh2_pkt_send(ssh, pktout);
4244 c->closes |= CLOSES_SENT_EOF;
4245 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4247 * Also send MSG_CLOSE.
4249 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4250 ssh2_pkt_adduint32(pktout, c->remoteid);
4251 ssh2_pkt_send(ssh, pktout);
4252 c->closes |= CLOSES_SENT_CLOSE;
4255 c->pending_eof = FALSE; /* we've sent it now */
4258 void sshfwd_write_eof(struct ssh_channel *c)
4262 if (ssh->state == SSH_STATE_CLOSED)
4265 if (c->closes & CLOSES_SENT_EOF)
4268 c->pending_eof = TRUE;
4269 ssh_channel_try_eof(c);
4272 void sshfwd_unclean_close(struct ssh_channel *c)
4275 struct Packet *pktout;
4277 if (ssh->state == SSH_STATE_CLOSED)
4280 if (!(c->closes & CLOSES_SENT_CLOSE)) {
4281 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4282 ssh2_pkt_adduint32(pktout, c->remoteid);
4283 ssh2_pkt_send(ssh, pktout);
4284 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
4289 x11_close(c->u.x11.s);
4292 case CHAN_SOCKDATA_DORMANT:
4293 pfd_close(c->u.pfd.s);
4296 c->type = CHAN_ZOMBIE;
4298 ssh2_channel_check_close(c);
4301 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4305 if (ssh->state == SSH_STATE_CLOSED)
4308 if (ssh->version == 1) {
4309 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4310 PKT_INT, c->remoteid,
4311 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4312 PKTT_OTHER, PKT_END);
4314 * In SSH-1 we can return 0 here - implying that forwarded
4315 * connections are never individually throttled - because
4316 * the only circumstance that can cause throttling will be
4317 * the whole SSH connection backing up, in which case
4318 * _everything_ will be throttled as a whole.
4322 ssh2_add_channel_data(c, buf, len);
4323 return ssh2_try_send(c);
4327 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4332 if (ssh->state == SSH_STATE_CLOSED)
4335 if (ssh->version == 1) {
4336 buflimit = SSH1_BUFFER_LIMIT;
4338 buflimit = c->v.v2.locmaxwin;
4339 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4341 if (c->throttling_conn && bufsize <= buflimit) {
4342 c->throttling_conn = 0;
4343 ssh_throttle_conn(ssh, -1);
4347 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4349 struct queued_handler *qh = ssh->qhead;
4353 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4356 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4357 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4360 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4361 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4365 ssh->qhead = qh->next;
4367 if (ssh->qhead->msg1 > 0) {
4368 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4369 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4371 if (ssh->qhead->msg2 > 0) {
4372 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4373 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4376 ssh->qhead = ssh->qtail = NULL;
4379 qh->handler(ssh, pktin, qh->ctx);
4384 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4385 chandler_fn_t handler, void *ctx)
4387 struct queued_handler *qh;
4389 qh = snew(struct queued_handler);
4392 qh->handler = handler;
4396 if (ssh->qtail == NULL) {
4400 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4401 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4404 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4405 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4408 ssh->qtail->next = qh;
4413 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4415 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4417 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4418 SSH2_MSG_REQUEST_SUCCESS)) {
4419 logeventf(ssh, "Remote port forwarding from %s enabled",
4422 logeventf(ssh, "Remote port forwarding from %s refused",
4425 rpf = del234(ssh->rportfwds, pf);
4427 pf->pfrec->remote = NULL;
4432 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4434 struct ssh_portfwd *epf;
4438 if (!ssh->portfwds) {
4439 ssh->portfwds = newtree234(ssh_portcmp);
4442 * Go through the existing port forwardings and tag them
4443 * with status==DESTROY. Any that we want to keep will be
4444 * re-enabled (status==KEEP) as we go through the
4445 * configuration and find out which bits are the same as
4448 struct ssh_portfwd *epf;
4450 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4451 epf->status = DESTROY;
4454 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4456 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4457 char *kp, *kp2, *vp, *vp2;
4458 char address_family, type;
4459 int sport,dport,sserv,dserv;
4460 char *sports, *dports, *saddr, *host;
4464 address_family = 'A';
4466 if (*kp == 'A' || *kp == '4' || *kp == '6')
4467 address_family = *kp++;
4468 if (*kp == 'L' || *kp == 'R')
4471 if ((kp2 = strchr(kp, ':')) != NULL) {
4473 * There's a colon in the middle of the source port
4474 * string, which means that the part before it is
4475 * actually a source address.
4477 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4483 sport = atoi(sports);
4487 sport = net_service_lookup(sports);
4489 logeventf(ssh, "Service lookup failed for source"
4490 " port \"%s\"", sports);
4494 if (type == 'L' && !strcmp(val, "D")) {
4495 /* dynamic forwarding */
4502 /* ordinary forwarding */
4504 vp2 = vp + strcspn(vp, ":");
4505 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4509 dport = atoi(dports);
4513 dport = net_service_lookup(dports);
4515 logeventf(ssh, "Service lookup failed for destination"
4516 " port \"%s\"", dports);
4521 if (sport && dport) {
4522 /* Set up a description of the source port. */
4523 struct ssh_portfwd *pfrec, *epfrec;
4525 pfrec = snew(struct ssh_portfwd);
4527 pfrec->saddr = saddr;
4528 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4529 pfrec->sport = sport;
4530 pfrec->daddr = host;
4531 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4532 pfrec->dport = dport;
4533 pfrec->local = NULL;
4534 pfrec->remote = NULL;
4535 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4536 address_family == '6' ? ADDRTYPE_IPV6 :
4539 epfrec = add234(ssh->portfwds, pfrec);
4540 if (epfrec != pfrec) {
4541 if (epfrec->status == DESTROY) {
4543 * We already have a port forwarding up and running
4544 * with precisely these parameters. Hence, no need
4545 * to do anything; simply re-tag the existing one
4548 epfrec->status = KEEP;
4551 * Anything else indicates that there was a duplicate
4552 * in our input, which we'll silently ignore.
4554 free_portfwd(pfrec);
4556 pfrec->status = CREATE;
4565 * Now go through and destroy any port forwardings which were
4568 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4569 if (epf->status == DESTROY) {
4572 message = dupprintf("%s port forwarding from %s%s%d",
4573 epf->type == 'L' ? "local" :
4574 epf->type == 'R' ? "remote" : "dynamic",
4575 epf->saddr ? epf->saddr : "",
4576 epf->saddr ? ":" : "",
4579 if (epf->type != 'D') {
4580 char *msg2 = dupprintf("%s to %s:%d", message,
4581 epf->daddr, epf->dport);
4586 logeventf(ssh, "Cancelling %s", message);
4589 /* epf->remote or epf->local may be NULL if setting up a
4590 * forwarding failed. */
4592 struct ssh_rportfwd *rpf = epf->remote;
4593 struct Packet *pktout;
4596 * Cancel the port forwarding at the server
4599 if (ssh->version == 1) {
4601 * We cannot cancel listening ports on the
4602 * server side in SSH-1! There's no message
4603 * to support it. Instead, we simply remove
4604 * the rportfwd record from the local end
4605 * so that any connections the server tries
4606 * to make on it are rejected.
4609 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4610 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4611 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4613 ssh2_pkt_addstring(pktout, epf->saddr);
4614 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4615 /* XXX: rport_acceptall may not represent
4616 * what was used to open the original connection,
4617 * since it's reconfigurable. */
4618 ssh2_pkt_addstring(pktout, "0.0.0.0");
4620 ssh2_pkt_addstring(pktout, "127.0.0.1");
4622 ssh2_pkt_adduint32(pktout, epf->sport);
4623 ssh2_pkt_send(ssh, pktout);
4626 del234(ssh->rportfwds, rpf);
4628 } else if (epf->local) {
4629 pfd_terminate(epf->local);
4632 delpos234(ssh->portfwds, i);
4634 i--; /* so we don't skip one in the list */
4638 * And finally, set up any new port forwardings (status==CREATE).
4640 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4641 if (epf->status == CREATE) {
4642 char *sportdesc, *dportdesc;
4643 sportdesc = dupprintf("%s%s%s%s%d%s",
4644 epf->saddr ? epf->saddr : "",
4645 epf->saddr ? ":" : "",
4646 epf->sserv ? epf->sserv : "",
4647 epf->sserv ? "(" : "",
4649 epf->sserv ? ")" : "");
4650 if (epf->type == 'D') {
4653 dportdesc = dupprintf("%s:%s%s%d%s",
4655 epf->dserv ? epf->dserv : "",
4656 epf->dserv ? "(" : "",
4658 epf->dserv ? ")" : "");
4661 if (epf->type == 'L') {
4662 const char *err = pfd_addforward(epf->daddr, epf->dport,
4663 epf->saddr, epf->sport,
4666 epf->addressfamily);
4668 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4669 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4670 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4671 sportdesc, dportdesc,
4672 err ? " failed: " : "", err ? err : "");
4673 } else if (epf->type == 'D') {
4674 const char *err = pfd_addforward(NULL, -1,
4675 epf->saddr, epf->sport,
4678 epf->addressfamily);
4680 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4681 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4682 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4684 err ? " failed: " : "", err ? err : "");
4686 struct ssh_rportfwd *pf;
4689 * Ensure the remote port forwardings tree exists.
4691 if (!ssh->rportfwds) {
4692 if (ssh->version == 1)
4693 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4695 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4698 pf = snew(struct ssh_rportfwd);
4699 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4700 pf->dhost[lenof(pf->dhost)-1] = '\0';
4701 pf->dport = epf->dport;
4702 pf->sport = epf->sport;
4703 if (add234(ssh->rportfwds, pf) != pf) {
4704 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4705 epf->daddr, epf->dport);
4708 logeventf(ssh, "Requesting remote port %s"
4709 " forward to %s", sportdesc, dportdesc);
4711 pf->sportdesc = sportdesc;
4716 if (ssh->version == 1) {
4717 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4718 PKT_INT, epf->sport,
4719 PKT_STR, epf->daddr,
4720 PKT_INT, epf->dport,
4722 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4724 ssh_rportfwd_succfail, pf);
4726 struct Packet *pktout;
4727 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4728 ssh2_pkt_addstring(pktout, "tcpip-forward");
4729 ssh2_pkt_addbool(pktout, 1);/* want reply */
4731 ssh2_pkt_addstring(pktout, epf->saddr);
4732 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4733 ssh2_pkt_addstring(pktout, "0.0.0.0");
4735 ssh2_pkt_addstring(pktout, "127.0.0.1");
4737 ssh2_pkt_adduint32(pktout, epf->sport);
4738 ssh2_pkt_send(ssh, pktout);
4740 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4741 SSH2_MSG_REQUEST_FAILURE,
4742 ssh_rportfwd_succfail, pf);
4751 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4754 int stringlen, bufsize;
4756 ssh_pkt_getstring(pktin, &string, &stringlen);
4757 if (string == NULL) {
4758 bombout(("Incoming terminal data packet was badly formed"));
4762 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4764 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4765 ssh->v1_stdout_throttling = 1;
4766 ssh_throttle_conn(ssh, +1);
4770 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4772 /* Remote side is trying to open a channel to talk to our
4773 * X-Server. Give them back a local channel number. */
4774 struct ssh_channel *c;
4775 int remoteid = ssh_pkt_getuint32(pktin);
4777 logevent("Received X11 connect request");
4778 /* Refuse if X11 forwarding is disabled. */
4779 if (!ssh->X11_fwd_enabled) {
4780 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4781 PKT_INT, remoteid, PKT_END);
4782 logevent("Rejected X11 connect request");
4784 c = snew(struct ssh_channel);
4787 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4788 NULL, -1, ssh->conf) != NULL) {
4789 logevent("Opening X11 forward connection failed");
4791 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4792 PKT_INT, remoteid, PKT_END);
4795 ("Opening X11 forward connection succeeded");
4796 c->remoteid = remoteid;
4797 c->halfopen = FALSE;
4798 c->localid = alloc_channel_id(ssh);
4800 c->pending_eof = FALSE;
4801 c->throttling_conn = 0;
4802 c->type = CHAN_X11; /* identify channel type */
4803 add234(ssh->channels, c);
4804 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4805 PKT_INT, c->remoteid, PKT_INT,
4806 c->localid, PKT_END);
4807 logevent("Opened X11 forward channel");
4812 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4814 /* Remote side is trying to open a channel to talk to our
4815 * agent. Give them back a local channel number. */
4816 struct ssh_channel *c;
4817 int remoteid = ssh_pkt_getuint32(pktin);
4819 /* Refuse if agent forwarding is disabled. */
4820 if (!ssh->agentfwd_enabled) {
4821 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4822 PKT_INT, remoteid, PKT_END);
4824 c = snew(struct ssh_channel);
4826 c->remoteid = remoteid;
4827 c->halfopen = FALSE;
4828 c->localid = alloc_channel_id(ssh);
4830 c->pending_eof = FALSE;
4831 c->throttling_conn = 0;
4832 c->type = CHAN_AGENT; /* identify channel type */
4833 c->u.a.lensofar = 0;
4834 c->u.a.message = NULL;
4835 add234(ssh->channels, c);
4836 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4837 PKT_INT, c->remoteid, PKT_INT, c->localid,
4842 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4844 /* Remote side is trying to open a channel to talk to a
4845 * forwarded port. Give them back a local channel number. */
4846 struct ssh_channel *c;
4847 struct ssh_rportfwd pf, *pfp;
4852 c = snew(struct ssh_channel);
4855 remoteid = ssh_pkt_getuint32(pktin);
4856 ssh_pkt_getstring(pktin, &host, &hostsize);
4857 port = ssh_pkt_getuint32(pktin);
4859 if (hostsize >= lenof(pf.dhost))
4860 hostsize = lenof(pf.dhost)-1;
4861 memcpy(pf.dhost, host, hostsize);
4862 pf.dhost[hostsize] = '\0';
4864 pfp = find234(ssh->rportfwds, &pf, NULL);
4867 logeventf(ssh, "Rejected remote port open request for %s:%d",
4869 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4870 PKT_INT, remoteid, PKT_END);
4872 logeventf(ssh, "Received remote port open request for %s:%d",
4874 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4875 c, ssh->conf, pfp->pfrec->addressfamily);
4877 logeventf(ssh, "Port open failed: %s", e);
4879 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4880 PKT_INT, remoteid, PKT_END);
4882 c->remoteid = remoteid;
4883 c->halfopen = FALSE;
4884 c->localid = alloc_channel_id(ssh);
4886 c->pending_eof = FALSE;
4887 c->throttling_conn = 0;
4888 c->type = CHAN_SOCKDATA; /* identify channel type */
4889 add234(ssh->channels, c);
4890 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4891 PKT_INT, c->remoteid, PKT_INT,
4892 c->localid, PKT_END);
4893 logevent("Forwarded port opened successfully");
4898 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4900 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4901 unsigned int localid = ssh_pkt_getuint32(pktin);
4902 struct ssh_channel *c;
4904 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4905 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4906 c->remoteid = localid;
4907 c->halfopen = FALSE;
4908 c->type = CHAN_SOCKDATA;
4909 c->throttling_conn = 0;
4910 pfd_confirm(c->u.pfd.s);
4913 if (c && c->pending_eof) {
4915 * We have a pending close on this channel,
4916 * which we decided on before the server acked
4917 * the channel open. So now we know the
4918 * remoteid, we can close it again.
4920 ssh_channel_try_eof(c);
4924 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4926 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4927 struct ssh_channel *c;
4929 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4930 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4931 logevent("Forwarded connection refused by server");
4932 pfd_close(c->u.pfd.s);
4933 del234(ssh->channels, c);
4938 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4940 /* Remote side closes a channel. */
4941 unsigned i = ssh_pkt_getuint32(pktin);
4942 struct ssh_channel *c;
4943 c = find234(ssh->channels, &i, ssh_channelfind);
4944 if (c && !c->halfopen) {
4946 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4947 !(c->closes & CLOSES_RCVD_EOF)) {
4949 * Received CHANNEL_CLOSE, which we translate into
4952 int send_close = FALSE;
4954 c->closes |= CLOSES_RCVD_EOF;
4959 x11_send_eof(c->u.x11.s);
4965 pfd_send_eof(c->u.pfd.s);
4974 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4975 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4977 c->closes |= CLOSES_SENT_EOF;
4981 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4982 !(c->closes & CLOSES_RCVD_CLOSE)) {
4984 if (!(c->closes & CLOSES_SENT_EOF)) {
4985 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4986 " for which we never sent CHANNEL_CLOSE\n", i));
4989 c->closes |= CLOSES_RCVD_CLOSE;
4992 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4993 !(c->closes & CLOSES_SENT_CLOSE)) {
4994 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4995 PKT_INT, c->remoteid, PKT_END);
4996 c->closes |= CLOSES_SENT_CLOSE;
4999 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5000 ssh_channel_destroy(c);
5002 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5003 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5004 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5009 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5011 /* Data sent down one of our channels. */
5012 int i = ssh_pkt_getuint32(pktin);
5015 struct ssh_channel *c;
5017 ssh_pkt_getstring(pktin, &p, &len);
5019 c = find234(ssh->channels, &i, ssh_channelfind);
5024 bufsize = x11_send(c->u.x11.s, p, len);
5027 bufsize = pfd_send(c->u.pfd.s, p, len);
5030 /* Data for an agent message. Buffer it. */
5032 if (c->u.a.lensofar < 4) {
5033 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5034 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5038 c->u.a.lensofar += l;
5040 if (c->u.a.lensofar == 4) {
5042 4 + GET_32BIT(c->u.a.msglen);
5043 c->u.a.message = snewn(c->u.a.totallen,
5045 memcpy(c->u.a.message, c->u.a.msglen, 4);
5047 if (c->u.a.lensofar >= 4 && len > 0) {
5049 min(c->u.a.totallen - c->u.a.lensofar,
5051 memcpy(c->u.a.message + c->u.a.lensofar, p,
5055 c->u.a.lensofar += l;
5057 if (c->u.a.lensofar == c->u.a.totallen) {
5060 if (agent_query(c->u.a.message,
5063 ssh_agentf_callback, c))
5064 ssh_agentf_callback(c, reply, replylen);
5065 sfree(c->u.a.message);
5066 c->u.a.lensofar = 0;
5069 bufsize = 0; /* agent channels never back up */
5072 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5073 c->throttling_conn = 1;
5074 ssh_throttle_conn(ssh, +1);
5079 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5081 ssh->exitcode = ssh_pkt_getuint32(pktin);
5082 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5083 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5085 * In case `helpful' firewalls or proxies tack
5086 * extra human-readable text on the end of the
5087 * session which we might mistake for another
5088 * encrypted packet, we close the session once
5089 * we've sent EXIT_CONFIRMATION.
5091 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5094 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5095 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5097 struct Packet *pktout = (struct Packet *)data;
5099 unsigned int arg = 0;
5100 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5101 if (i == lenof(ssh_ttymodes)) return;
5102 switch (ssh_ttymodes[i].type) {
5104 arg = ssh_tty_parse_specchar(val);
5107 arg = ssh_tty_parse_boolean(val);
5110 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5111 ssh2_pkt_addbyte(pktout, arg);
5115 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5116 struct Packet *pktin)
5118 crBegin(ssh->do_ssh1_connection_crstate);
5120 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5121 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5122 ssh1_smsg_stdout_stderr_data;
5124 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5125 ssh1_msg_channel_open_confirmation;
5126 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5127 ssh1_msg_channel_open_failure;
5128 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5129 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5130 ssh1_msg_channel_close;
5131 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5132 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5134 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5135 logevent("Requesting agent forwarding");
5136 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5140 if (pktin->type != SSH1_SMSG_SUCCESS
5141 && pktin->type != SSH1_SMSG_FAILURE) {
5142 bombout(("Protocol confusion"));
5144 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5145 logevent("Agent forwarding refused");
5147 logevent("Agent forwarding enabled");
5148 ssh->agentfwd_enabled = TRUE;
5149 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5153 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5154 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5155 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5156 logevent("Requesting X11 forwarding");
5158 * Note that while we blank the X authentication data here, we don't
5159 * take any special action to blank the start of an X11 channel,
5160 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5161 * without having session blanking enabled is likely to leak your
5162 * cookie into the log.
5164 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5165 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5166 PKT_STR, ssh->x11disp->remoteauthprotoname,
5168 PKT_STR, ssh->x11disp->remoteauthdatastring,
5170 PKT_INT, ssh->x11disp->screennum,
5173 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5174 PKT_STR, ssh->x11disp->remoteauthprotoname,
5176 PKT_STR, ssh->x11disp->remoteauthdatastring,
5183 if (pktin->type != SSH1_SMSG_SUCCESS
5184 && pktin->type != SSH1_SMSG_FAILURE) {
5185 bombout(("Protocol confusion"));
5187 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5188 logevent("X11 forwarding refused");
5190 logevent("X11 forwarding enabled");
5191 ssh->X11_fwd_enabled = TRUE;
5192 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5196 ssh_setup_portfwd(ssh, ssh->conf);
5197 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5199 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5201 /* Unpick the terminal-speed string. */
5202 /* XXX perhaps we should allow no speeds to be sent. */
5203 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5204 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5205 /* Send the pty request. */
5206 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5207 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5208 ssh_pkt_adduint32(pkt, ssh->term_height);
5209 ssh_pkt_adduint32(pkt, ssh->term_width);
5210 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5211 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5212 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5213 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5214 ssh_pkt_adduint32(pkt, ssh->ispeed);
5215 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5216 ssh_pkt_adduint32(pkt, ssh->ospeed);
5217 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5219 ssh->state = SSH_STATE_INTERMED;
5223 if (pktin->type != SSH1_SMSG_SUCCESS
5224 && pktin->type != SSH1_SMSG_FAILURE) {
5225 bombout(("Protocol confusion"));
5227 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5228 c_write_str(ssh, "Server refused to allocate pty\r\n");
5229 ssh->editing = ssh->echoing = 1;
5231 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5232 ssh->ospeed, ssh->ispeed);
5233 ssh->got_pty = TRUE;
5236 ssh->editing = ssh->echoing = 1;
5239 if (conf_get_int(ssh->conf, CONF_compression)) {
5240 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5244 if (pktin->type != SSH1_SMSG_SUCCESS
5245 && pktin->type != SSH1_SMSG_FAILURE) {
5246 bombout(("Protocol confusion"));
5248 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5249 c_write_str(ssh, "Server refused to compress\r\n");
5251 logevent("Started compression");
5252 ssh->v1_compressing = TRUE;
5253 ssh->cs_comp_ctx = zlib_compress_init();
5254 logevent("Initialised zlib (RFC1950) compression");
5255 ssh->sc_comp_ctx = zlib_decompress_init();
5256 logevent("Initialised zlib (RFC1950) decompression");
5260 * Start the shell or command.
5262 * Special case: if the first-choice command is an SSH-2
5263 * subsystem (hence not usable here) and the second choice
5264 * exists, we fall straight back to that.
5267 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5269 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5270 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5271 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5272 ssh->fallback_cmd = TRUE;
5275 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5277 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5278 logevent("Started session");
5281 ssh->state = SSH_STATE_SESSION;
5282 if (ssh->size_needed)
5283 ssh_size(ssh, ssh->term_width, ssh->term_height);
5284 if (ssh->eof_needed)
5285 ssh_special(ssh, TS_EOF);
5288 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5290 ssh->channels = newtree234(ssh_channelcmp);
5294 * By this point, most incoming packets are already being
5295 * handled by the dispatch table, and we need only pay
5296 * attention to the unusual ones.
5301 if (pktin->type == SSH1_SMSG_SUCCESS) {
5302 /* may be from EXEC_SHELL on some servers */
5303 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5304 /* may be from EXEC_SHELL on some servers
5305 * if no pty is available or in other odd cases. Ignore */
5307 bombout(("Strange packet received: type %d", pktin->type));
5312 int len = min(inlen, 512);
5313 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5314 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5315 PKTT_OTHER, PKT_END);
5326 * Handle the top-level SSH-2 protocol.
5328 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5333 ssh_pkt_getstring(pktin, &msg, &msglen);
5334 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5337 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5339 /* log reason code in disconnect message */
5343 ssh_pkt_getstring(pktin, &msg, &msglen);
5344 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5347 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5349 /* Do nothing, because we're ignoring it! Duhh. */
5352 static void ssh1_protocol_setup(Ssh ssh)
5357 * Most messages are handled by the coroutines.
5359 for (i = 0; i < 256; i++)
5360 ssh->packet_dispatch[i] = NULL;
5363 * These special message types we install handlers for.
5365 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5366 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5367 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5370 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5371 struct Packet *pktin)
5373 unsigned char *in=(unsigned char*)vin;
5374 if (ssh->state == SSH_STATE_CLOSED)
5377 if (pktin && ssh->packet_dispatch[pktin->type]) {
5378 ssh->packet_dispatch[pktin->type](ssh, pktin);
5382 if (!ssh->protocol_initial_phase_done) {
5383 if (do_ssh1_login(ssh, in, inlen, pktin))
5384 ssh->protocol_initial_phase_done = TRUE;
5389 do_ssh1_connection(ssh, in, inlen, pktin);
5393 * Utility routine for decoding comma-separated strings in KEXINIT.
5395 static int in_commasep_string(char *needle, char *haystack, int haylen)
5398 if (!needle || !haystack) /* protect against null pointers */
5400 needlen = strlen(needle);
5403 * Is it at the start of the string?
5405 if (haylen >= needlen && /* haystack is long enough */
5406 !memcmp(needle, haystack, needlen) && /* initial match */
5407 (haylen == needlen || haystack[needlen] == ',')
5408 /* either , or EOS follows */
5412 * If not, search for the next comma and resume after that.
5413 * If no comma found, terminate.
5415 while (haylen > 0 && *haystack != ',')
5416 haylen--, haystack++;
5419 haylen--, haystack++; /* skip over comma itself */
5424 * Similar routine for checking whether we have the first string in a list.
5426 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5429 if (!needle || !haystack) /* protect against null pointers */
5431 needlen = strlen(needle);
5433 * Is it at the start of the string?
5435 if (haylen >= needlen && /* haystack is long enough */
5436 !memcmp(needle, haystack, needlen) && /* initial match */
5437 (haylen == needlen || haystack[needlen] == ',')
5438 /* either , or EOS follows */
5446 * SSH-2 key creation method.
5447 * (Currently assumes 2 lots of any hash are sufficient to generate
5448 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5450 #define SSH2_MKKEY_ITERS (2)
5451 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5452 unsigned char *keyspace)
5454 const struct ssh_hash *h = ssh->kex->hash;
5456 /* First hlen bytes. */
5458 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5459 hash_mpint(h, s, K);
5460 h->bytes(s, H, h->hlen);
5461 h->bytes(s, &chr, 1);
5462 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5463 h->final(s, keyspace);
5464 /* Next hlen bytes. */
5466 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5467 hash_mpint(h, s, K);
5468 h->bytes(s, H, h->hlen);
5469 h->bytes(s, keyspace, h->hlen);
5470 h->final(s, keyspace + h->hlen);
5474 * Handle the SSH-2 transport layer.
5476 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5477 struct Packet *pktin)
5479 unsigned char *in = (unsigned char *)vin;
5480 struct do_ssh2_transport_state {
5482 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5483 Bignum p, g, e, f, K;
5486 int kex_init_value, kex_reply_value;
5487 const struct ssh_mac **maclist;
5489 const struct ssh2_cipher *cscipher_tobe;
5490 const struct ssh2_cipher *sccipher_tobe;
5491 const struct ssh_mac *csmac_tobe;
5492 const struct ssh_mac *scmac_tobe;
5493 const struct ssh_compress *cscomp_tobe;
5494 const struct ssh_compress *sccomp_tobe;
5495 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5496 int hostkeylen, siglen, rsakeylen;
5497 void *hkey; /* actual host key */
5498 void *rsakey; /* for RSA kex */
5499 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5500 int n_preferred_kex;
5501 const struct ssh_kexes *preferred_kex[KEX_MAX];
5502 int n_preferred_ciphers;
5503 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5504 const struct ssh_compress *preferred_comp;
5505 int userauth_succeeded; /* for delayed compression */
5506 int pending_compression;
5507 int got_session_id, activated_authconn;
5508 struct Packet *pktout;
5513 crState(do_ssh2_transport_state);
5517 s->cscipher_tobe = s->sccipher_tobe = NULL;
5518 s->csmac_tobe = s->scmac_tobe = NULL;
5519 s->cscomp_tobe = s->sccomp_tobe = NULL;
5521 s->got_session_id = s->activated_authconn = FALSE;
5522 s->userauth_succeeded = FALSE;
5523 s->pending_compression = FALSE;
5526 * Be prepared to work around the buggy MAC problem.
5528 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5529 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5531 s->maclist = macs, s->nmacs = lenof(macs);
5534 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5536 int i, j, k, commalist_started;
5539 * Set up the preferred key exchange. (NULL => warn below here)
5541 s->n_preferred_kex = 0;
5542 for (i = 0; i < KEX_MAX; i++) {
5543 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5545 s->preferred_kex[s->n_preferred_kex++] =
5546 &ssh_diffiehellman_gex;
5549 s->preferred_kex[s->n_preferred_kex++] =
5550 &ssh_diffiehellman_group14;
5553 s->preferred_kex[s->n_preferred_kex++] =
5554 &ssh_diffiehellman_group1;
5557 s->preferred_kex[s->n_preferred_kex++] =
5561 /* Flag for later. Don't bother if it's the last in
5563 if (i < KEX_MAX - 1) {
5564 s->preferred_kex[s->n_preferred_kex++] = NULL;
5571 * Set up the preferred ciphers. (NULL => warn below here)
5573 s->n_preferred_ciphers = 0;
5574 for (i = 0; i < CIPHER_MAX; i++) {
5575 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5576 case CIPHER_BLOWFISH:
5577 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5580 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5581 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5585 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5588 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5590 case CIPHER_ARCFOUR:
5591 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5594 /* Flag for later. Don't bother if it's the last in
5596 if (i < CIPHER_MAX - 1) {
5597 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5604 * Set up preferred compression.
5606 if (conf_get_int(ssh->conf, CONF_compression))
5607 s->preferred_comp = &ssh_zlib;
5609 s->preferred_comp = &ssh_comp_none;
5612 * Enable queueing of outgoing auth- or connection-layer
5613 * packets while we are in the middle of a key exchange.
5615 ssh->queueing = TRUE;
5618 * Flag that KEX is in progress.
5620 ssh->kex_in_progress = TRUE;
5623 * Construct and send our key exchange packet.
5625 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5626 for (i = 0; i < 16; i++)
5627 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5628 /* List key exchange algorithms. */
5629 ssh2_pkt_addstring_start(s->pktout);
5630 commalist_started = 0;
5631 for (i = 0; i < s->n_preferred_kex; i++) {
5632 const struct ssh_kexes *k = s->preferred_kex[i];
5633 if (!k) continue; /* warning flag */
5634 for (j = 0; j < k->nkexes; j++) {
5635 if (commalist_started)
5636 ssh2_pkt_addstring_str(s->pktout, ",");
5637 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5638 commalist_started = 1;
5641 /* List server host key algorithms. */
5642 ssh2_pkt_addstring_start(s->pktout);
5643 for (i = 0; i < lenof(hostkey_algs); i++) {
5644 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5645 if (i < lenof(hostkey_algs) - 1)
5646 ssh2_pkt_addstring_str(s->pktout, ",");
5648 /* List encryption algorithms (client->server then server->client). */
5649 for (k = 0; k < 2; k++) {
5650 ssh2_pkt_addstring_start(s->pktout);
5651 commalist_started = 0;
5652 for (i = 0; i < s->n_preferred_ciphers; i++) {
5653 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5654 if (!c) continue; /* warning flag */
5655 for (j = 0; j < c->nciphers; j++) {
5656 if (commalist_started)
5657 ssh2_pkt_addstring_str(s->pktout, ",");
5658 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5659 commalist_started = 1;
5663 /* List MAC algorithms (client->server then server->client). */
5664 for (j = 0; j < 2; j++) {
5665 ssh2_pkt_addstring_start(s->pktout);
5666 for (i = 0; i < s->nmacs; i++) {
5667 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5668 if (i < s->nmacs - 1)
5669 ssh2_pkt_addstring_str(s->pktout, ",");
5672 /* List client->server compression algorithms,
5673 * then server->client compression algorithms. (We use the
5674 * same set twice.) */
5675 for (j = 0; j < 2; j++) {
5676 ssh2_pkt_addstring_start(s->pktout);
5677 assert(lenof(compressions) > 1);
5678 /* Prefer non-delayed versions */
5679 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5680 /* We don't even list delayed versions of algorithms until
5681 * they're allowed to be used, to avoid a race. See the end of
5683 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5684 ssh2_pkt_addstring_str(s->pktout, ",");
5685 ssh2_pkt_addstring_str(s->pktout,
5686 s->preferred_comp->delayed_name);
5688 for (i = 0; i < lenof(compressions); i++) {
5689 const struct ssh_compress *c = compressions[i];
5690 if (c != s->preferred_comp) {
5691 ssh2_pkt_addstring_str(s->pktout, ",");
5692 ssh2_pkt_addstring_str(s->pktout, c->name);
5693 if (s->userauth_succeeded && c->delayed_name) {
5694 ssh2_pkt_addstring_str(s->pktout, ",");
5695 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5700 /* List client->server languages. Empty list. */
5701 ssh2_pkt_addstring_start(s->pktout);
5702 /* List server->client languages. Empty list. */
5703 ssh2_pkt_addstring_start(s->pktout);
5704 /* First KEX packet does _not_ follow, because we're not that brave. */
5705 ssh2_pkt_addbool(s->pktout, FALSE);
5707 ssh2_pkt_adduint32(s->pktout, 0);
5710 s->our_kexinitlen = s->pktout->length - 5;
5711 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5712 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5714 ssh2_pkt_send_noqueue(ssh, s->pktout);
5720 * Now examine the other side's KEXINIT to see what we're up
5724 char *str, *preferred;
5727 if (pktin->type != SSH2_MSG_KEXINIT) {
5728 bombout(("expected key exchange packet from server"));
5732 ssh->hostkey = NULL;
5733 s->cscipher_tobe = NULL;
5734 s->sccipher_tobe = NULL;
5735 s->csmac_tobe = NULL;
5736 s->scmac_tobe = NULL;
5737 s->cscomp_tobe = NULL;
5738 s->sccomp_tobe = NULL;
5739 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5741 pktin->savedpos += 16; /* skip garbage cookie */
5742 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5745 for (i = 0; i < s->n_preferred_kex; i++) {
5746 const struct ssh_kexes *k = s->preferred_kex[i];
5750 for (j = 0; j < k->nkexes; j++) {
5751 if (!preferred) preferred = k->list[j]->name;
5752 if (in_commasep_string(k->list[j]->name, str, len)) {
5753 ssh->kex = k->list[j];
5762 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5763 str ? str : "(null)"));
5767 * Note that the server's guess is considered wrong if it doesn't match
5768 * the first algorithm in our list, even if it's still the algorithm
5771 s->guessok = first_in_commasep_string(preferred, str, len);
5772 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5773 for (i = 0; i < lenof(hostkey_algs); i++) {
5774 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5775 ssh->hostkey = hostkey_algs[i];
5779 if (!ssh->hostkey) {
5780 bombout(("Couldn't agree a host key algorithm (available: %s)",
5781 str ? str : "(null)"));
5785 s->guessok = s->guessok &&
5786 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5787 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5788 for (i = 0; i < s->n_preferred_ciphers; i++) {
5789 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5791 s->warn_cscipher = TRUE;
5793 for (j = 0; j < c->nciphers; j++) {
5794 if (in_commasep_string(c->list[j]->name, str, len)) {
5795 s->cscipher_tobe = c->list[j];
5800 if (s->cscipher_tobe)
5803 if (!s->cscipher_tobe) {
5804 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5805 str ? str : "(null)"));
5809 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5810 for (i = 0; i < s->n_preferred_ciphers; i++) {
5811 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5813 s->warn_sccipher = TRUE;
5815 for (j = 0; j < c->nciphers; j++) {
5816 if (in_commasep_string(c->list[j]->name, str, len)) {
5817 s->sccipher_tobe = c->list[j];
5822 if (s->sccipher_tobe)
5825 if (!s->sccipher_tobe) {
5826 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5827 str ? str : "(null)"));
5831 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5832 for (i = 0; i < s->nmacs; i++) {
5833 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5834 s->csmac_tobe = s->maclist[i];
5838 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5839 for (i = 0; i < s->nmacs; i++) {
5840 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5841 s->scmac_tobe = s->maclist[i];
5845 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5846 for (i = 0; i < lenof(compressions) + 1; i++) {
5847 const struct ssh_compress *c =
5848 i == 0 ? s->preferred_comp : compressions[i - 1];
5849 if (in_commasep_string(c->name, str, len)) {
5852 } else if (in_commasep_string(c->delayed_name, str, len)) {
5853 if (s->userauth_succeeded) {
5857 s->pending_compression = TRUE; /* try this later */
5861 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5862 for (i = 0; i < lenof(compressions) + 1; i++) {
5863 const struct ssh_compress *c =
5864 i == 0 ? s->preferred_comp : compressions[i - 1];
5865 if (in_commasep_string(c->name, str, len)) {
5868 } else if (in_commasep_string(c->delayed_name, str, len)) {
5869 if (s->userauth_succeeded) {
5873 s->pending_compression = TRUE; /* try this later */
5877 if (s->pending_compression) {
5878 logevent("Server supports delayed compression; "
5879 "will try this later");
5881 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5882 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5883 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5886 ssh_set_frozen(ssh, 1);
5887 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5889 ssh_dialog_callback, ssh);
5890 if (s->dlgret < 0) {
5894 bombout(("Unexpected data from server while"
5895 " waiting for user response"));
5898 } while (pktin || inlen > 0);
5899 s->dlgret = ssh->user_response;
5901 ssh_set_frozen(ssh, 0);
5902 if (s->dlgret == 0) {
5903 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5909 if (s->warn_cscipher) {
5910 ssh_set_frozen(ssh, 1);
5911 s->dlgret = askalg(ssh->frontend,
5912 "client-to-server cipher",
5913 s->cscipher_tobe->name,
5914 ssh_dialog_callback, ssh);
5915 if (s->dlgret < 0) {
5919 bombout(("Unexpected data from server while"
5920 " waiting for user response"));
5923 } while (pktin || inlen > 0);
5924 s->dlgret = ssh->user_response;
5926 ssh_set_frozen(ssh, 0);
5927 if (s->dlgret == 0) {
5928 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5934 if (s->warn_sccipher) {
5935 ssh_set_frozen(ssh, 1);
5936 s->dlgret = askalg(ssh->frontend,
5937 "server-to-client cipher",
5938 s->sccipher_tobe->name,
5939 ssh_dialog_callback, ssh);
5940 if (s->dlgret < 0) {
5944 bombout(("Unexpected data from server while"
5945 " waiting for user response"));
5948 } while (pktin || inlen > 0);
5949 s->dlgret = ssh->user_response;
5951 ssh_set_frozen(ssh, 0);
5952 if (s->dlgret == 0) {
5953 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5959 ssh->exhash = ssh->kex->hash->init();
5960 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5961 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5962 hash_string(ssh->kex->hash, ssh->exhash,
5963 s->our_kexinit, s->our_kexinitlen);
5964 sfree(s->our_kexinit);
5965 if (pktin->length > 5)
5966 hash_string(ssh->kex->hash, ssh->exhash,
5967 pktin->data + 5, pktin->length - 5);
5969 if (s->ignorepkt) /* first_kex_packet_follows */
5970 crWaitUntil(pktin); /* Ignore packet */
5973 if (ssh->kex->main_type == KEXTYPE_DH) {
5975 * Work out the number of bits of key we will need from the
5976 * key exchange. We start with the maximum key length of
5982 csbits = s->cscipher_tobe->keylen;
5983 scbits = s->sccipher_tobe->keylen;
5984 s->nbits = (csbits > scbits ? csbits : scbits);
5986 /* The keys only have hlen-bit entropy, since they're based on
5987 * a hash. So cap the key size at hlen bits. */
5988 if (s->nbits > ssh->kex->hash->hlen * 8)
5989 s->nbits = ssh->kex->hash->hlen * 8;
5992 * If we're doing Diffie-Hellman group exchange, start by
5993 * requesting a group.
5995 if (!ssh->kex->pdata) {
5996 logevent("Doing Diffie-Hellman group exchange");
5997 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5999 * Work out how big a DH group we will need to allow that
6002 s->pbits = 512 << ((s->nbits - 1) / 64);
6003 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6004 ssh2_pkt_adduint32(s->pktout, s->pbits);
6005 ssh2_pkt_send_noqueue(ssh, s->pktout);
6008 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6009 bombout(("expected key exchange group packet from server"));
6012 s->p = ssh2_pkt_getmp(pktin);
6013 s->g = ssh2_pkt_getmp(pktin);
6014 if (!s->p || !s->g) {
6015 bombout(("unable to read mp-ints from incoming group packet"));
6018 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6019 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6020 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6022 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6023 ssh->kex_ctx = dh_setup_group(ssh->kex);
6024 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6025 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6026 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6027 ssh->kex->groupname);
6030 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6031 ssh->kex->hash->text_name);
6033 * Now generate and send e for Diffie-Hellman.
6035 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6036 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6037 s->pktout = ssh2_pkt_init(s->kex_init_value);
6038 ssh2_pkt_addmp(s->pktout, s->e);
6039 ssh2_pkt_send_noqueue(ssh, s->pktout);
6041 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6043 if (pktin->type != s->kex_reply_value) {
6044 bombout(("expected key exchange reply packet from server"));
6047 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6048 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6049 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6050 s->f = ssh2_pkt_getmp(pktin);
6052 bombout(("unable to parse key exchange reply packet"));
6055 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6057 s->K = dh_find_K(ssh->kex_ctx, s->f);
6059 /* We assume everything from now on will be quick, and it might
6060 * involve user interaction. */
6061 set_busy_status(ssh->frontend, BUSY_NOT);
6063 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6064 if (!ssh->kex->pdata) {
6065 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6066 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6067 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6069 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6070 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6072 dh_cleanup(ssh->kex_ctx);
6074 if (!ssh->kex->pdata) {
6079 logeventf(ssh, "Doing RSA key exchange with hash %s",
6080 ssh->kex->hash->text_name);
6081 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6083 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6087 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6088 bombout(("expected RSA public key packet from server"));
6092 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6093 hash_string(ssh->kex->hash, ssh->exhash,
6094 s->hostkeydata, s->hostkeylen);
6095 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6099 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6100 s->rsakeydata = snewn(s->rsakeylen, char);
6101 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6104 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6106 sfree(s->rsakeydata);
6107 bombout(("unable to parse RSA public key from server"));
6111 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6114 * Next, set up a shared secret K, of precisely KLEN -
6115 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6116 * RSA key modulus and HLEN is the bit length of the hash
6120 int klen = ssh_rsakex_klen(s->rsakey);
6121 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6123 unsigned char *kstr1, *kstr2, *outstr;
6124 int kstr1len, kstr2len, outstrlen;
6126 s->K = bn_power_2(nbits - 1);
6128 for (i = 0; i < nbits; i++) {
6130 byte = random_byte();
6132 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6136 * Encode this as an mpint.
6138 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6139 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6140 PUT_32BIT(kstr2, kstr1len);
6141 memcpy(kstr2 + 4, kstr1, kstr1len);
6144 * Encrypt it with the given RSA key.
6146 outstrlen = (klen + 7) / 8;
6147 outstr = snewn(outstrlen, unsigned char);
6148 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6149 outstr, outstrlen, s->rsakey);
6152 * And send it off in a return packet.
6154 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6155 ssh2_pkt_addstring_start(s->pktout);
6156 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6157 ssh2_pkt_send_noqueue(ssh, s->pktout);
6159 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6166 ssh_rsakex_freekey(s->rsakey);
6169 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6170 sfree(s->rsakeydata);
6171 bombout(("expected signature packet from server"));
6175 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6177 sfree(s->rsakeydata);
6180 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6181 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6182 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6184 ssh->kex_ctx = NULL;
6187 debug(("Exchange hash is:\n"));
6188 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6192 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6193 (char *)s->exchange_hash,
6194 ssh->kex->hash->hlen)) {
6195 bombout(("Server's host key did not match the signature supplied"));
6200 * Authenticate remote host: verify host key. (We've already
6201 * checked the signature of the exchange hash.)
6203 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6204 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6205 ssh_set_frozen(ssh, 1);
6206 s->dlgret = verify_ssh_host_key(ssh->frontend,
6207 ssh->savedhost, ssh->savedport,
6208 ssh->hostkey->keytype, s->keystr,
6210 ssh_dialog_callback, ssh);
6211 if (s->dlgret < 0) {
6215 bombout(("Unexpected data from server while waiting"
6216 " for user host key response"));
6219 } while (pktin || inlen > 0);
6220 s->dlgret = ssh->user_response;
6222 ssh_set_frozen(ssh, 0);
6223 if (s->dlgret == 0) {
6224 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6228 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6229 logevent("Host key fingerprint is:");
6230 logevent(s->fingerprint);
6232 sfree(s->fingerprint);
6234 ssh->hostkey->freekey(s->hkey);
6237 * The exchange hash from the very first key exchange is also
6238 * the session id, used in session key construction and
6241 if (!s->got_session_id) {
6242 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6243 memcpy(ssh->v2_session_id, s->exchange_hash,
6244 sizeof(s->exchange_hash));
6245 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6246 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6247 s->got_session_id = TRUE;
6251 * Send SSH2_MSG_NEWKEYS.
6253 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6254 ssh2_pkt_send_noqueue(ssh, s->pktout);
6255 ssh->outgoing_data_size = 0; /* start counting from here */
6258 * We've sent client NEWKEYS, so create and initialise
6259 * client-to-server session keys.
6261 if (ssh->cs_cipher_ctx)
6262 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6263 ssh->cscipher = s->cscipher_tobe;
6264 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6266 if (ssh->cs_mac_ctx)
6267 ssh->csmac->free_context(ssh->cs_mac_ctx);
6268 ssh->csmac = s->csmac_tobe;
6269 ssh->cs_mac_ctx = ssh->csmac->make_context();
6271 if (ssh->cs_comp_ctx)
6272 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6273 ssh->cscomp = s->cscomp_tobe;
6274 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6277 * Set IVs on client-to-server keys. Here we use the exchange
6278 * hash from the _first_ key exchange.
6281 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6282 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6283 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6284 assert((ssh->cscipher->keylen+7) / 8 <=
6285 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6286 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6287 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6288 assert(ssh->cscipher->blksize <=
6289 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6290 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6291 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6292 assert(ssh->csmac->len <=
6293 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6294 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6295 smemclr(keyspace, sizeof(keyspace));
6298 logeventf(ssh, "Initialised %.200s client->server encryption",
6299 ssh->cscipher->text_name);
6300 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6301 ssh->csmac->text_name);
6302 if (ssh->cscomp->text_name)
6303 logeventf(ssh, "Initialised %s compression",
6304 ssh->cscomp->text_name);
6307 * Now our end of the key exchange is complete, we can send all
6308 * our queued higher-layer packets.
6310 ssh->queueing = FALSE;
6311 ssh2_pkt_queuesend(ssh);
6314 * Expect SSH2_MSG_NEWKEYS from server.
6317 if (pktin->type != SSH2_MSG_NEWKEYS) {
6318 bombout(("expected new-keys packet from server"));
6321 ssh->incoming_data_size = 0; /* start counting from here */
6324 * We've seen server NEWKEYS, so create and initialise
6325 * server-to-client session keys.
6327 if (ssh->sc_cipher_ctx)
6328 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6329 ssh->sccipher = s->sccipher_tobe;
6330 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6332 if (ssh->sc_mac_ctx)
6333 ssh->scmac->free_context(ssh->sc_mac_ctx);
6334 ssh->scmac = s->scmac_tobe;
6335 ssh->sc_mac_ctx = ssh->scmac->make_context();
6337 if (ssh->sc_comp_ctx)
6338 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6339 ssh->sccomp = s->sccomp_tobe;
6340 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6343 * Set IVs on server-to-client keys. Here we use the exchange
6344 * hash from the _first_ key exchange.
6347 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6348 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6349 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6350 assert((ssh->sccipher->keylen+7) / 8 <=
6351 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6352 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6353 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6354 assert(ssh->sccipher->blksize <=
6355 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6356 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6357 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6358 assert(ssh->scmac->len <=
6359 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6360 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6361 smemclr(keyspace, sizeof(keyspace));
6363 logeventf(ssh, "Initialised %.200s server->client encryption",
6364 ssh->sccipher->text_name);
6365 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6366 ssh->scmac->text_name);
6367 if (ssh->sccomp->text_name)
6368 logeventf(ssh, "Initialised %s decompression",
6369 ssh->sccomp->text_name);
6372 * Free shared secret.
6377 * Key exchange is over. Loop straight back round if we have a
6378 * deferred rekey reason.
6380 if (ssh->deferred_rekey_reason) {
6381 logevent(ssh->deferred_rekey_reason);
6383 ssh->deferred_rekey_reason = NULL;
6384 goto begin_key_exchange;
6388 * Otherwise, schedule a timer for our next rekey.
6390 ssh->kex_in_progress = FALSE;
6391 ssh->last_rekey = GETTICKCOUNT();
6392 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6393 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6397 * Now we're encrypting. Begin returning 1 to the protocol main
6398 * function so that other things can run on top of the
6399 * transport. If we ever see a KEXINIT, we must go back to the
6402 * We _also_ go back to the start if we see pktin==NULL and
6403 * inlen negative, because this is a special signal meaning
6404 * `initiate client-driven rekey', and `in' contains a message
6405 * giving the reason for the rekey.
6407 * inlen==-1 means always initiate a rekey;
6408 * inlen==-2 means that userauth has completed successfully and
6409 * we should consider rekeying (for delayed compression).
6411 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6412 (!pktin && inlen < 0))) {
6414 if (!ssh->protocol_initial_phase_done) {
6415 ssh->protocol_initial_phase_done = TRUE;
6417 * Allow authconn to initialise itself.
6419 do_ssh2_authconn(ssh, NULL, 0, NULL);
6424 logevent("Server initiated key re-exchange");
6428 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6429 * delayed compression, if it's available.
6431 * draft-miller-secsh-compression-delayed-00 says that you
6432 * negotiate delayed compression in the first key exchange, and
6433 * both sides start compressing when the server has sent
6434 * USERAUTH_SUCCESS. This has a race condition -- the server
6435 * can't know when the client has seen it, and thus which incoming
6436 * packets it should treat as compressed.
6438 * Instead, we do the initial key exchange without offering the
6439 * delayed methods, but note if the server offers them; when we
6440 * get here, if a delayed method was available that was higher
6441 * on our list than what we got, we initiate a rekey in which we
6442 * _do_ list the delayed methods (and hopefully get it as a
6443 * result). Subsequent rekeys will do the same.
6445 assert(!s->userauth_succeeded); /* should only happen once */
6446 s->userauth_succeeded = TRUE;
6447 if (!s->pending_compression)
6448 /* Can't see any point rekeying. */
6449 goto wait_for_rekey; /* this is utterly horrid */
6450 /* else fall through to rekey... */
6451 s->pending_compression = FALSE;
6454 * Now we've decided to rekey.
6456 * Special case: if the server bug is set that doesn't
6457 * allow rekeying, we give a different log message and
6458 * continue waiting. (If such a server _initiates_ a rekey,
6459 * we process it anyway!)
6461 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6462 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6464 /* Reset the counters, so that at least this message doesn't
6465 * hit the event log _too_ often. */
6466 ssh->outgoing_data_size = 0;
6467 ssh->incoming_data_size = 0;
6468 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6470 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6473 goto wait_for_rekey; /* this is still utterly horrid */
6475 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6478 goto begin_key_exchange;
6484 * Add data to an SSH-2 channel output buffer.
6486 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6489 bufchain_add(&c->v.v2.outbuffer, buf, len);
6493 * Attempt to send data on an SSH-2 channel.
6495 static int ssh2_try_send(struct ssh_channel *c)
6498 struct Packet *pktout;
6501 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6504 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6505 if ((unsigned)len > c->v.v2.remwindow)
6506 len = c->v.v2.remwindow;
6507 if ((unsigned)len > c->v.v2.remmaxpkt)
6508 len = c->v.v2.remmaxpkt;
6509 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6510 ssh2_pkt_adduint32(pktout, c->remoteid);
6511 ssh2_pkt_addstring_start(pktout);
6512 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6513 ssh2_pkt_addstring_data(pktout, data, len);
6514 end_log_omission(ssh, pktout);
6515 ssh2_pkt_send(ssh, pktout);
6516 bufchain_consume(&c->v.v2.outbuffer, len);
6517 c->v.v2.remwindow -= len;
6521 * After having sent as much data as we can, return the amount
6524 ret = bufchain_size(&c->v.v2.outbuffer);
6527 * And if there's no data pending but we need to send an EOF, send
6530 if (!ret && c->pending_eof)
6531 ssh_channel_try_eof(c);
6536 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6539 if (c->closes & CLOSES_SENT_EOF)
6540 return; /* don't send on channels we've EOFed */
6541 bufsize = ssh2_try_send(c);
6544 case CHAN_MAINSESSION:
6545 /* stdin need not receive an unthrottle
6546 * notification since it will be polled */
6549 x11_unthrottle(c->u.x11.s);
6552 /* agent sockets are request/response and need no
6553 * buffer management */
6556 pfd_unthrottle(c->u.pfd.s);
6563 * Set up most of a new ssh_channel for SSH-2.
6565 static void ssh2_channel_init(struct ssh_channel *c)
6568 c->localid = alloc_channel_id(ssh);
6570 c->pending_eof = FALSE;
6571 c->throttling_conn = FALSE;
6572 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6573 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6574 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6575 c->v.v2.throttle_state = UNTHROTTLED;
6576 bufchain_init(&c->v.v2.outbuffer);
6580 * Potentially enlarge the window on an SSH-2 channel.
6582 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6587 * Never send WINDOW_ADJUST for a channel that the remote side has
6588 * already sent EOF on; there's no point, since it won't be
6589 * sending any more data anyway. Ditto if _we've_ already sent
6592 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6596 * If the remote end has a habit of ignoring maxpkt, limit the
6597 * window so that it has no choice (assuming it doesn't ignore the
6600 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6601 newwin = OUR_V2_MAXPKT;
6604 * Only send a WINDOW_ADJUST if there's significantly more window
6605 * available than the other end thinks there is. This saves us
6606 * sending a WINDOW_ADJUST for every character in a shell session.
6608 * "Significant" is arbitrarily defined as half the window size.
6610 if (newwin / 2 >= c->v.v2.locwindow) {
6611 struct Packet *pktout;
6615 * In order to keep track of how much window the client
6616 * actually has available, we'd like it to acknowledge each
6617 * WINDOW_ADJUST. We can't do that directly, so we accompany
6618 * it with a CHANNEL_REQUEST that has to be acknowledged.
6620 * This is only necessary if we're opening the window wide.
6621 * If we're not, then throughput is being constrained by
6622 * something other than the maximum window size anyway.
6624 * We also only send this if the main channel has finished its
6625 * initial CHANNEL_REQUESTs and installed the default
6626 * CHANNEL_FAILURE handler, so as not to risk giving it
6627 * unexpected CHANNEL_FAILUREs.
6629 if (newwin == c->v.v2.locmaxwin &&
6630 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] &&
6631 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6632 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6633 ssh2_pkt_adduint32(pktout, c->remoteid);
6634 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6635 ssh2_pkt_addbool(pktout, TRUE);
6636 ssh2_pkt_send(ssh, pktout);
6639 * CHANNEL_FAILURE doesn't come with any indication of
6640 * what message caused it, so we have to keep track of the
6641 * outstanding CHANNEL_REQUESTs ourselves.
6643 wa = snew(struct winadj);
6644 wa->size = newwin - c->v.v2.locwindow;
6646 if (!c->v.v2.winadj_head)
6647 c->v.v2.winadj_head = wa;
6649 c->v.v2.winadj_tail->next = wa;
6650 c->v.v2.winadj_tail = wa;
6651 if (c->v.v2.throttle_state != UNTHROTTLED)
6652 c->v.v2.throttle_state = UNTHROTTLING;
6654 /* Pretend the WINDOW_ADJUST was acked immediately. */
6655 c->v.v2.remlocwin = newwin;
6656 c->v.v2.throttle_state = THROTTLED;
6658 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6659 ssh2_pkt_adduint32(pktout, c->remoteid);
6660 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6661 ssh2_pkt_send(ssh, pktout);
6662 c->v.v2.locwindow = newwin;
6667 * Find the channel associated with a message. If there's no channel,
6668 * or it's not properly open, make a noise about it and return NULL.
6670 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6672 unsigned localid = ssh_pkt_getuint32(pktin);
6673 struct ssh_channel *c;
6675 c = find234(ssh->channels, &localid, ssh_channelfind);
6677 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6678 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6679 char *buf = dupprintf("Received %s for %s channel %u",
6680 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6682 c ? "half-open" : "nonexistent", localid);
6683 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6690 static int ssh2_handle_winadj_response(struct ssh_channel *c)
6692 struct winadj *wa = c->v.v2.winadj_head;
6695 c->v.v2.winadj_head = wa->next;
6696 c->v.v2.remlocwin += wa->size;
6699 * winadj messages are only sent when the window is fully open, so
6700 * if we get an ack of one, we know any pending unthrottle is
6703 if (c->v.v2.throttle_state == UNTHROTTLING)
6704 c->v.v2.throttle_state = UNTHROTTLED;
6706 * We may now initiate channel-closing procedures, if that winadj
6707 * was the last thing outstanding before we send CHANNEL_CLOSE.
6709 ssh2_channel_check_close(c);
6713 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6716 * This should never get called. All channel requests are either
6717 * sent with want_reply false, are sent before this handler gets
6718 * installed, or are "winadj@putty" requests, which servers should
6719 * never respond to with success.
6721 * However, at least one server ("boks_sshd") is known to return
6722 * SUCCESS for channel requests it's never heard of, such as
6723 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6724 * for the sake of a quiet life, we handle it just the same as the
6727 struct ssh_channel *c;
6729 c = ssh2_channel_msg(ssh, pktin);
6732 if (!ssh2_handle_winadj_response(c))
6733 ssh_disconnect(ssh, NULL,
6734 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6735 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6738 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6741 * The only time this should get called is for "winadj@putty"
6742 * messages sent above. All other channel requests are either
6743 * sent with want_reply false or are sent before this handler gets
6746 struct ssh_channel *c;
6748 c = ssh2_channel_msg(ssh, pktin);
6751 if (!ssh2_handle_winadj_response(c))
6752 ssh_disconnect(ssh, NULL,
6753 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6754 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6757 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6759 struct ssh_channel *c;
6760 c = ssh2_channel_msg(ssh, pktin);
6763 if (!(c->closes & CLOSES_SENT_EOF)) {
6764 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6765 ssh2_try_send_and_unthrottle(ssh, c);
6769 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6773 struct ssh_channel *c;
6774 c = ssh2_channel_msg(ssh, pktin);
6777 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6778 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6779 return; /* extended but not stderr */
6780 ssh_pkt_getstring(pktin, &data, &length);
6783 c->v.v2.locwindow -= length;
6784 c->v.v2.remlocwin -= length;
6786 case CHAN_MAINSESSION:
6788 from_backend(ssh->frontend, pktin->type ==
6789 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6793 bufsize = x11_send(c->u.x11.s, data, length);
6796 bufsize = pfd_send(c->u.pfd.s, data, length);
6799 while (length > 0) {
6800 if (c->u.a.lensofar < 4) {
6801 unsigned int l = min(4 - c->u.a.lensofar,
6803 memcpy(c->u.a.msglen + c->u.a.lensofar,
6807 c->u.a.lensofar += l;
6809 if (c->u.a.lensofar == 4) {
6811 4 + GET_32BIT(c->u.a.msglen);
6812 c->u.a.message = snewn(c->u.a.totallen,
6814 memcpy(c->u.a.message, c->u.a.msglen, 4);
6816 if (c->u.a.lensofar >= 4 && length > 0) {
6818 min(c->u.a.totallen - c->u.a.lensofar,
6820 memcpy(c->u.a.message + c->u.a.lensofar,
6824 c->u.a.lensofar += l;
6826 if (c->u.a.lensofar == c->u.a.totallen) {
6829 if (agent_query(c->u.a.message,
6832 ssh_agentf_callback, c))
6833 ssh_agentf_callback(c, reply, replylen);
6834 sfree(c->u.a.message);
6835 c->u.a.message = NULL;
6836 c->u.a.lensofar = 0;
6843 * If it looks like the remote end hit the end of its window,
6844 * and we didn't want it to do that, think about using a
6847 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6848 c->v.v2.locmaxwin < 0x40000000)
6849 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6851 * If we are not buffering too much data,
6852 * enlarge the window again at the remote side.
6853 * If we are buffering too much, we may still
6854 * need to adjust the window if the server's
6857 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6858 c->v.v2.locmaxwin - bufsize : 0);
6860 * If we're either buffering way too much data, or if we're
6861 * buffering anything at all and we're in "simple" mode,
6862 * throttle the whole channel.
6864 if ((bufsize > c->v.v2.locmaxwin ||
6865 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6866 !c->throttling_conn) {
6867 c->throttling_conn = 1;
6868 ssh_throttle_conn(ssh, +1);
6873 static void ssh_channel_destroy(struct ssh_channel *c)
6878 case CHAN_MAINSESSION:
6879 ssh->mainchan = NULL;
6880 update_specials_menu(ssh->frontend);
6883 if (c->u.x11.s != NULL)
6884 x11_close(c->u.x11.s);
6885 logevent("Forwarded X11 connection terminated");
6888 sfree(c->u.a.message);
6891 if (c->u.pfd.s != NULL)
6892 pfd_close(c->u.pfd.s);
6893 logevent("Forwarded port closed");
6897 del234(ssh->channels, c);
6898 if (ssh->version == 2)
6899 bufchain_clear(&c->v.v2.outbuffer);
6903 * See if that was the last channel left open.
6904 * (This is only our termination condition if we're
6905 * not running in -N mode.)
6907 if (ssh->version == 2 &&
6908 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6909 count234(ssh->channels) == 0) {
6911 * We used to send SSH_MSG_DISCONNECT here,
6912 * because I'd believed that _every_ conforming
6913 * SSH-2 connection had to end with a disconnect
6914 * being sent by at least one side; apparently
6915 * I was wrong and it's perfectly OK to
6916 * unceremoniously slam the connection shut
6917 * when you're done, and indeed OpenSSH feels
6918 * this is more polite than sending a
6919 * DISCONNECT. So now we don't.
6921 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6925 static void ssh2_channel_check_close(struct ssh_channel *c)
6928 struct Packet *pktout;
6930 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6931 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
6933 * We have both sent and received EOF, and we have no
6934 * outstanding winadj channel requests, which means the
6935 * channel is in final wind-up. But we haven't sent CLOSE, so
6938 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6939 ssh2_pkt_adduint32(pktout, c->remoteid);
6940 ssh2_pkt_send(ssh, pktout);
6941 c->closes |= CLOSES_SENT_CLOSE;
6944 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6946 * We have both sent and received CLOSE, which means we're
6947 * completely done with the channel.
6949 ssh_channel_destroy(c);
6953 static void ssh2_channel_got_eof(struct ssh_channel *c)
6955 if (c->closes & CLOSES_RCVD_EOF)
6956 return; /* already seen EOF */
6957 c->closes |= CLOSES_RCVD_EOF;
6959 if (c->type == CHAN_X11) {
6960 x11_send_eof(c->u.x11.s);
6961 } else if (c->type == CHAN_AGENT) {
6962 /* Manufacture an outgoing EOF in response to the incoming one. */
6963 sshfwd_write_eof(c);
6964 } else if (c->type == CHAN_SOCKDATA) {
6965 pfd_send_eof(c->u.pfd.s);
6966 } else if (c->type == CHAN_MAINSESSION) {
6969 if (!ssh->sent_console_eof &&
6970 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6972 * Either from_backend_eof told us that the front end
6973 * wants us to close the outgoing side of the connection
6974 * as soon as we see EOF from the far end, or else we've
6975 * unilaterally decided to do that because we've allocated
6976 * a remote pty and hence EOF isn't a particularly
6977 * meaningful concept.
6979 sshfwd_write_eof(c);
6981 ssh->sent_console_eof = TRUE;
6984 ssh2_channel_check_close(c);
6987 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6989 struct ssh_channel *c;
6991 c = ssh2_channel_msg(ssh, pktin);
6994 ssh2_channel_got_eof(c);
6997 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6999 struct ssh_channel *c;
7001 c = ssh2_channel_msg(ssh, pktin);
7006 * When we receive CLOSE on a channel, we assume it comes with an
7007 * implied EOF if we haven't seen EOF yet.
7009 ssh2_channel_got_eof(c);
7012 * And we also send an outgoing EOF, if we haven't already, on the
7013 * assumption that CLOSE is a pretty forceful announcement that
7014 * the remote side is doing away with the entire channel. (If it
7015 * had wanted to send us EOF and continue receiving data from us,
7016 * it would have just sent CHANNEL_EOF.)
7018 if (!(c->closes & CLOSES_SENT_EOF)) {
7020 * Make sure we don't read any more from whatever our local
7021 * data source is for this channel.
7024 case CHAN_MAINSESSION:
7025 ssh->send_ok = 0; /* stop trying to read from stdin */
7028 x11_override_throttle(c->u.x11.s, 1);
7031 pfd_override_throttle(c->u.pfd.s, 1);
7036 * Send outgoing EOF.
7038 sshfwd_write_eof(c);
7042 * Now process the actual close.
7044 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7045 c->closes |= CLOSES_RCVD_CLOSE;
7046 ssh2_channel_check_close(c);
7050 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7052 struct ssh_channel *c;
7054 c = ssh2_channel_msg(ssh, pktin);
7057 if (c->type != CHAN_SOCKDATA_DORMANT)
7058 return; /* dunno why they're confirming this */
7059 c->remoteid = ssh_pkt_getuint32(pktin);
7060 c->halfopen = FALSE;
7061 c->type = CHAN_SOCKDATA;
7062 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7063 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7065 pfd_confirm(c->u.pfd.s);
7067 ssh_channel_try_eof(c);
7070 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7072 static const char *const reasons[] = {
7073 "<unknown reason code>",
7074 "Administratively prohibited",
7076 "Unknown channel type",
7077 "Resource shortage",
7079 unsigned reason_code;
7080 char *reason_string;
7082 struct ssh_channel *c;
7083 c = ssh2_channel_msg(ssh, pktin);
7086 if (c->type != CHAN_SOCKDATA_DORMANT)
7087 return; /* dunno why they're failing this */
7089 reason_code = ssh_pkt_getuint32(pktin);
7090 if (reason_code >= lenof(reasons))
7091 reason_code = 0; /* ensure reasons[reason_code] in range */
7092 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7093 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7094 reasons[reason_code], reason_length, reason_string);
7096 pfd_close(c->u.pfd.s);
7098 del234(ssh->channels, c);
7102 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7105 int typelen, want_reply;
7106 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7107 struct ssh_channel *c;
7108 struct Packet *pktout;
7110 c = ssh2_channel_msg(ssh, pktin);
7113 ssh_pkt_getstring(pktin, &type, &typelen);
7114 want_reply = ssh2_pkt_getbool(pktin);
7117 * Having got the channel number, we now look at
7118 * the request type string to see if it's something
7121 if (c == ssh->mainchan) {
7123 * We recognise "exit-status" and "exit-signal" on
7124 * the primary channel.
7126 if (typelen == 11 &&
7127 !memcmp(type, "exit-status", 11)) {
7129 ssh->exitcode = ssh_pkt_getuint32(pktin);
7130 logeventf(ssh, "Server sent command exit status %d",
7132 reply = SSH2_MSG_CHANNEL_SUCCESS;
7134 } else if (typelen == 11 &&
7135 !memcmp(type, "exit-signal", 11)) {
7137 int is_plausible = TRUE, is_int = FALSE;
7138 char *fmt_sig = "", *fmt_msg = "";
7140 int msglen = 0, core = FALSE;
7141 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7142 * provide an `int' for the signal, despite its
7143 * having been a `string' in the drafts of RFC 4254 since at
7144 * least 2001. (Fixed in session.c 1.147.) Try to
7145 * infer which we can safely parse it as. */
7147 unsigned char *p = pktin->body +
7149 long len = pktin->length - pktin->savedpos;
7150 unsigned long num = GET_32BIT(p); /* what is it? */
7151 /* If it's 0, it hardly matters; assume string */
7155 int maybe_int = FALSE, maybe_str = FALSE;
7156 #define CHECK_HYPOTHESIS(offset, result) \
7159 if (q >= 0 && q+4 <= len) { \
7160 q = q + 4 + GET_32BIT(p+q); \
7161 if (q >= 0 && q+4 <= len && \
7162 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7166 CHECK_HYPOTHESIS(4+1, maybe_int);
7167 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7168 #undef CHECK_HYPOTHESIS
7169 if (maybe_int && !maybe_str)
7171 else if (!maybe_int && maybe_str)
7174 /* Crikey. Either or neither. Panic. */
7175 is_plausible = FALSE;
7178 ssh->exitcode = 128; /* means `unknown signal' */
7181 /* Old non-standard OpenSSH. */
7182 int signum = ssh_pkt_getuint32(pktin);
7183 fmt_sig = dupprintf(" %d", signum);
7184 ssh->exitcode = 128 + signum;
7186 /* As per RFC 4254. */
7189 ssh_pkt_getstring(pktin, &sig, &siglen);
7190 /* Signal name isn't supposed to be blank, but
7191 * let's cope gracefully if it is. */
7193 fmt_sig = dupprintf(" \"%.*s\"",
7198 * Really hideous method of translating the
7199 * signal description back into a locally
7200 * meaningful number.
7205 #define TRANSLATE_SIGNAL(s) \
7206 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7207 ssh->exitcode = 128 + SIG ## s
7209 TRANSLATE_SIGNAL(ABRT);
7212 TRANSLATE_SIGNAL(ALRM);
7215 TRANSLATE_SIGNAL(FPE);
7218 TRANSLATE_SIGNAL(HUP);
7221 TRANSLATE_SIGNAL(ILL);
7224 TRANSLATE_SIGNAL(INT);
7227 TRANSLATE_SIGNAL(KILL);
7230 TRANSLATE_SIGNAL(PIPE);
7233 TRANSLATE_SIGNAL(QUIT);
7236 TRANSLATE_SIGNAL(SEGV);
7239 TRANSLATE_SIGNAL(TERM);
7242 TRANSLATE_SIGNAL(USR1);
7245 TRANSLATE_SIGNAL(USR2);
7247 #undef TRANSLATE_SIGNAL
7249 ssh->exitcode = 128;
7251 core = ssh2_pkt_getbool(pktin);
7252 ssh_pkt_getstring(pktin, &msg, &msglen);
7254 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7256 /* ignore lang tag */
7257 } /* else don't attempt to parse */
7258 logeventf(ssh, "Server exited on signal%s%s%s",
7259 fmt_sig, core ? " (core dumped)" : "",
7261 if (*fmt_sig) sfree(fmt_sig);
7262 if (*fmt_msg) sfree(fmt_msg);
7263 reply = SSH2_MSG_CHANNEL_SUCCESS;
7268 * This is a channel request we don't know
7269 * about, so we now either ignore the request
7270 * or respond with CHANNEL_FAILURE, depending
7273 reply = SSH2_MSG_CHANNEL_FAILURE;
7276 pktout = ssh2_pkt_init(reply);
7277 ssh2_pkt_adduint32(pktout, c->remoteid);
7278 ssh2_pkt_send(ssh, pktout);
7282 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7285 int typelen, want_reply;
7286 struct Packet *pktout;
7288 ssh_pkt_getstring(pktin, &type, &typelen);
7289 want_reply = ssh2_pkt_getbool(pktin);
7292 * We currently don't support any global requests
7293 * at all, so we either ignore the request or
7294 * respond with REQUEST_FAILURE, depending on
7298 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7299 ssh2_pkt_send(ssh, pktout);
7303 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7311 struct ssh_channel *c;
7312 unsigned remid, winsize, pktsize;
7313 struct Packet *pktout;
7315 ssh_pkt_getstring(pktin, &type, &typelen);
7316 c = snew(struct ssh_channel);
7319 remid = ssh_pkt_getuint32(pktin);
7320 winsize = ssh_pkt_getuint32(pktin);
7321 pktsize = ssh_pkt_getuint32(pktin);
7323 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7327 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7328 addrstr = snewn(peeraddrlen+1, char);
7329 memcpy(addrstr, peeraddr, peeraddrlen);
7330 addrstr[peeraddrlen] = '\0';
7331 peerport = ssh_pkt_getuint32(pktin);
7333 logeventf(ssh, "Received X11 connect request from %s:%d",
7336 if (!ssh->X11_fwd_enabled)
7337 error = "X11 forwarding is not enabled";
7338 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7339 addrstr, peerport, ssh->conf)) != NULL) {
7340 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7341 error = "Unable to open an X11 connection";
7343 logevent("Opening X11 forward connection succeeded");
7348 } else if (typelen == 15 &&
7349 !memcmp(type, "forwarded-tcpip", 15)) {
7350 struct ssh_rportfwd pf, *realpf;
7353 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7354 pf.sport = ssh_pkt_getuint32(pktin);
7355 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7356 peerport = ssh_pkt_getuint32(pktin);
7357 realpf = find234(ssh->rportfwds, &pf, NULL);
7358 logeventf(ssh, "Received remote port %d open request "
7359 "from %s:%d", pf.sport, peeraddr, peerport);
7360 if (realpf == NULL) {
7361 error = "Remote port is not recognised";
7363 const char *e = pfd_newconnect(&c->u.pfd.s,
7367 realpf->pfrec->addressfamily);
7368 logeventf(ssh, "Attempting to forward remote port to "
7369 "%s:%d", realpf->dhost, realpf->dport);
7371 logeventf(ssh, "Port open failed: %s", e);
7372 error = "Port open failed";
7374 logevent("Forwarded port opened successfully");
7375 c->type = CHAN_SOCKDATA;
7378 } else if (typelen == 22 &&
7379 !memcmp(type, "auth-agent@openssh.com", 22)) {
7380 if (!ssh->agentfwd_enabled)
7381 error = "Agent forwarding is not enabled";
7383 c->type = CHAN_AGENT; /* identify channel type */
7384 c->u.a.lensofar = 0;
7387 error = "Unsupported channel type requested";
7390 c->remoteid = remid;
7391 c->halfopen = FALSE;
7393 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7394 ssh2_pkt_adduint32(pktout, c->remoteid);
7395 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7396 ssh2_pkt_addstring(pktout, error);
7397 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7398 ssh2_pkt_send(ssh, pktout);
7399 logeventf(ssh, "Rejected channel open: %s", error);
7402 ssh2_channel_init(c);
7403 c->v.v2.remwindow = winsize;
7404 c->v.v2.remmaxpkt = pktsize;
7405 add234(ssh->channels, c);
7406 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7407 ssh2_pkt_adduint32(pktout, c->remoteid);
7408 ssh2_pkt_adduint32(pktout, c->localid);
7409 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7410 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7411 ssh2_pkt_send(ssh, pktout);
7416 * Buffer banner messages for later display at some convenient point,
7417 * if we're going to display them.
7419 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7421 /* Arbitrary limit to prevent unbounded inflation of buffer */
7422 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7423 bufchain_size(&ssh->banner) <= 131072) {
7424 char *banner = NULL;
7426 ssh_pkt_getstring(pktin, &banner, &size);
7428 bufchain_add(&ssh->banner, banner, size);
7432 /* Helper function to deal with sending tty modes for "pty-req" */
7433 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7435 struct Packet *pktout = (struct Packet *)data;
7437 unsigned int arg = 0;
7438 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7439 if (i == lenof(ssh_ttymodes)) return;
7440 switch (ssh_ttymodes[i].type) {
7442 arg = ssh_tty_parse_specchar(val);
7445 arg = ssh_tty_parse_boolean(val);
7448 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7449 ssh2_pkt_adduint32(pktout, arg);
7453 * Handle the SSH-2 userauth and connection layers.
7455 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7457 do_ssh2_authconn(ssh, NULL, 0, pktin);
7460 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7461 struct Packet *pktin)
7463 struct do_ssh2_authconn_state {
7467 AUTH_TYPE_PUBLICKEY,
7468 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7469 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7471 AUTH_TYPE_GSSAPI, /* always QUIET */
7472 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7473 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7475 int done_service_req;
7476 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7477 int tried_pubkey_config, done_agent;
7482 int kbd_inter_refused;
7483 int we_are_in, userauth_success;
7484 prompts_t *cur_prompt;
7489 void *publickey_blob;
7490 int publickey_bloblen;
7491 int publickey_encrypted;
7492 char *publickey_algorithm;
7493 char *publickey_comment;
7494 unsigned char agent_request[5], *agent_response, *agentp;
7495 int agent_responselen;
7496 unsigned char *pkblob_in_agent;
7498 char *pkblob, *alg, *commentp;
7499 int pklen, alglen, commentlen;
7500 int siglen, retlen, len;
7501 char *q, *agentreq, *ret;
7504 int requested_agent;
7506 int num_env, env_left, env_ok;
7507 struct Packet *pktout;
7510 struct ssh_gss_library *gsslib;
7511 Ssh_gss_ctx gss_ctx;
7512 Ssh_gss_buf gss_buf;
7513 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7514 Ssh_gss_name gss_srv_name;
7515 Ssh_gss_stat gss_stat;
7518 crState(do_ssh2_authconn_state);
7522 /* Register as a handler for all the messages this coroutine handles. */
7523 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7524 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7525 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7526 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7527 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7528 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7529 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7530 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7531 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7532 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7533 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7534 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7535 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7536 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7537 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7538 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7539 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7540 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7541 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7542 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7543 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_authconn;
7544 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_authconn;
7545 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_authconn;
7547 s->done_service_req = FALSE;
7548 s->we_are_in = s->userauth_success = FALSE;
7550 s->tried_gssapi = FALSE;
7553 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7555 * Request userauth protocol, and await a response to it.
7557 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7558 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7559 ssh2_pkt_send(ssh, s->pktout);
7560 crWaitUntilV(pktin);
7561 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7562 s->done_service_req = TRUE;
7564 if (!s->done_service_req) {
7566 * Request connection protocol directly, without authentication.
7568 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7569 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7570 ssh2_pkt_send(ssh, s->pktout);
7571 crWaitUntilV(pktin);
7572 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7573 s->we_are_in = TRUE; /* no auth required */
7575 bombout(("Server refused service request"));
7580 /* Arrange to be able to deal with any BANNERs that come in.
7581 * (We do this now as packets may come in during the next bit.) */
7582 bufchain_init(&ssh->banner);
7583 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7584 ssh2_msg_userauth_banner;
7587 * Misc one-time setup for authentication.
7589 s->publickey_blob = NULL;
7590 if (!s->we_are_in) {
7593 * Load the public half of any configured public key file
7596 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7597 if (!filename_is_null(s->keyfile)) {
7599 logeventf(ssh, "Reading private key file \"%.150s\"",
7600 filename_to_str(s->keyfile));
7601 keytype = key_type(s->keyfile);
7602 if (keytype == SSH_KEYTYPE_SSH2) {
7605 ssh2_userkey_loadpub(s->keyfile,
7606 &s->publickey_algorithm,
7607 &s->publickey_bloblen,
7608 &s->publickey_comment, &error);
7609 if (s->publickey_blob) {
7610 s->publickey_encrypted =
7611 ssh2_userkey_encrypted(s->keyfile, NULL);
7614 logeventf(ssh, "Unable to load private key (%s)",
7616 msgbuf = dupprintf("Unable to load private key file "
7617 "\"%.150s\" (%s)\r\n",
7618 filename_to_str(s->keyfile),
7620 c_write_str(ssh, msgbuf);
7625 logeventf(ssh, "Unable to use this key file (%s)",
7626 key_type_to_str(keytype));
7627 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7629 filename_to_str(s->keyfile),
7630 key_type_to_str(keytype));
7631 c_write_str(ssh, msgbuf);
7633 s->publickey_blob = NULL;
7638 * Find out about any keys Pageant has (but if there's a
7639 * public key configured, filter out all others).
7642 s->agent_response = NULL;
7643 s->pkblob_in_agent = NULL;
7644 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7648 logevent("Pageant is running. Requesting keys.");
7650 /* Request the keys held by the agent. */
7651 PUT_32BIT(s->agent_request, 1);
7652 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7653 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7654 ssh_agent_callback, ssh)) {
7658 bombout(("Unexpected data from server while"
7659 " waiting for agent response"));
7662 } while (pktin || inlen > 0);
7663 r = ssh->agent_response;
7664 s->agent_responselen = ssh->agent_response_len;
7666 s->agent_response = (unsigned char *) r;
7667 if (s->agent_response && s->agent_responselen >= 5 &&
7668 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7671 p = s->agent_response + 5;
7672 s->nkeys = GET_32BIT(p);
7674 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7675 if (s->publickey_blob) {
7676 /* See if configured key is in agent. */
7677 for (keyi = 0; keyi < s->nkeys; keyi++) {
7678 s->pklen = GET_32BIT(p);
7679 if (s->pklen == s->publickey_bloblen &&
7680 !memcmp(p+4, s->publickey_blob,
7681 s->publickey_bloblen)) {
7682 logeventf(ssh, "Pageant key #%d matches "
7683 "configured key file", keyi);
7685 s->pkblob_in_agent = p;
7689 p += GET_32BIT(p) + 4; /* comment */
7691 if (!s->pkblob_in_agent) {
7692 logevent("Configured key file not in Pageant");
7697 logevent("Failed to get reply from Pageant");
7704 * We repeat this whole loop, including the username prompt,
7705 * until we manage a successful authentication. If the user
7706 * types the wrong _password_, they can be sent back to the
7707 * beginning to try another username, if this is configured on.
7708 * (If they specify a username in the config, they are never
7709 * asked, even if they do give a wrong password.)
7711 * I think this best serves the needs of
7713 * - the people who have no configuration, no keys, and just
7714 * want to try repeated (username,password) pairs until they
7715 * type both correctly
7717 * - people who have keys and configuration but occasionally
7718 * need to fall back to passwords
7720 * - people with a key held in Pageant, who might not have
7721 * logged in to a particular machine before; so they want to
7722 * type a username, and then _either_ their key will be
7723 * accepted, _or_ they will type a password. If they mistype
7724 * the username they will want to be able to get back and
7727 s->got_username = FALSE;
7728 while (!s->we_are_in) {
7732 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
7734 * We got a username last time round this loop, and
7735 * with change_username turned off we don't try to get
7738 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
7739 int ret; /* need not be kept over crReturn */
7740 s->cur_prompt = new_prompts(ssh->frontend);
7741 s->cur_prompt->to_server = TRUE;
7742 s->cur_prompt->name = dupstr("SSH login name");
7743 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
7744 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7747 crWaitUntilV(!pktin);
7748 ret = get_userpass_input(s->cur_prompt, in, inlen);
7753 * get_userpass_input() failed to get a username.
7756 free_prompts(s->cur_prompt);
7757 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7760 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
7761 free_prompts(s->cur_prompt);
7764 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7765 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
7766 c_write_str(ssh, stuff);
7770 s->got_username = TRUE;
7773 * Send an authentication request using method "none": (a)
7774 * just in case it succeeds, and (b) so that we know what
7775 * authentication methods we can usefully try next.
7777 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7779 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7780 ssh2_pkt_addstring(s->pktout, ssh->username);
7781 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7782 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7783 ssh2_pkt_send(ssh, s->pktout);
7784 s->type = AUTH_TYPE_NONE;
7786 s->we_are_in = FALSE;
7788 s->tried_pubkey_config = FALSE;
7789 s->kbd_inter_refused = FALSE;
7791 /* Reset agent request state. */
7792 s->done_agent = FALSE;
7793 if (s->agent_response) {
7794 if (s->pkblob_in_agent) {
7795 s->agentp = s->pkblob_in_agent;
7797 s->agentp = s->agent_response + 5 + 4;
7803 char *methods = NULL;
7807 * Wait for the result of the last authentication request.
7810 crWaitUntilV(pktin);
7812 * Now is a convenient point to spew any banner material
7813 * that we've accumulated. (This should ensure that when
7814 * we exit the auth loop, we haven't any left to deal
7818 int size = bufchain_size(&ssh->banner);
7820 * Don't show the banner if we're operating in
7821 * non-verbose non-interactive mode. (It's probably
7822 * a script, which means nobody will read the
7823 * banner _anyway_, and moreover the printing of
7824 * the banner will screw up processing on the
7825 * output of (say) plink.)
7827 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7828 char *banner = snewn(size, char);
7829 bufchain_fetch(&ssh->banner, banner, size);
7830 c_write_untrusted(ssh, banner, size);
7833 bufchain_clear(&ssh->banner);
7835 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7836 logevent("Access granted");
7837 s->we_are_in = s->userauth_success = TRUE;
7841 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7842 bombout(("Strange packet received during authentication: "
7843 "type %d", pktin->type));
7850 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7851 * we can look at the string in it and know what we can
7852 * helpfully try next.
7854 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7855 ssh_pkt_getstring(pktin, &methods, &methlen);
7856 if (!ssh2_pkt_getbool(pktin)) {
7858 * We have received an unequivocal Access
7859 * Denied. This can translate to a variety of
7860 * messages, or no message at all.
7862 * For forms of authentication which are attempted
7863 * implicitly, by which I mean without printing
7864 * anything in the window indicating that we're
7865 * trying them, we should never print 'Access
7868 * If we do print a message saying that we're
7869 * attempting some kind of authentication, it's OK
7870 * to print a followup message saying it failed -
7871 * but the message may sometimes be more specific
7872 * than simply 'Access denied'.
7874 * Additionally, if we'd just tried password
7875 * authentication, we should break out of this
7876 * whole loop so as to go back to the username
7877 * prompt (iff we're configured to allow
7878 * username change attempts).
7880 if (s->type == AUTH_TYPE_NONE) {
7882 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7883 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7884 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7885 c_write_str(ssh, "Server refused our key\r\n");
7886 logevent("Server refused our key");
7887 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7888 /* This _shouldn't_ happen except by a
7889 * protocol bug causing client and server to
7890 * disagree on what is a correct signature. */
7891 c_write_str(ssh, "Server refused public-key signature"
7892 " despite accepting key!\r\n");
7893 logevent("Server refused public-key signature"
7894 " despite accepting key!");
7895 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7896 /* quiet, so no c_write */
7897 logevent("Server refused keyboard-interactive authentication");
7898 } else if (s->type==AUTH_TYPE_GSSAPI) {
7899 /* always quiet, so no c_write */
7900 /* also, the code down in the GSSAPI block has
7901 * already logged this in the Event Log */
7902 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7903 logevent("Keyboard-interactive authentication failed");
7904 c_write_str(ssh, "Access denied\r\n");
7906 assert(s->type == AUTH_TYPE_PASSWORD);
7907 logevent("Password authentication failed");
7908 c_write_str(ssh, "Access denied\r\n");
7910 if (conf_get_int(ssh->conf, CONF_change_username)) {
7911 /* XXX perhaps we should allow
7912 * keyboard-interactive to do this too? */
7913 s->we_are_in = FALSE;
7918 c_write_str(ssh, "Further authentication required\r\n");
7919 logevent("Further authentication required");
7923 in_commasep_string("publickey", methods, methlen);
7925 in_commasep_string("password", methods, methlen);
7926 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
7927 in_commasep_string("keyboard-interactive", methods, methlen);
7930 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7931 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
7932 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7933 ssh->gsslibs->nlibraries > 0;
7937 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7939 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7942 * Attempt public-key authentication using a key from Pageant.
7945 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7947 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7949 /* Unpack key from agent response */
7950 s->pklen = GET_32BIT(s->agentp);
7952 s->pkblob = (char *)s->agentp;
7953 s->agentp += s->pklen;
7954 s->alglen = GET_32BIT(s->pkblob);
7955 s->alg = s->pkblob + 4;
7956 s->commentlen = GET_32BIT(s->agentp);
7958 s->commentp = (char *)s->agentp;
7959 s->agentp += s->commentlen;
7960 /* s->agentp now points at next key, if any */
7962 /* See if server will accept it */
7963 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7964 ssh2_pkt_addstring(s->pktout, ssh->username);
7965 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7966 /* service requested */
7967 ssh2_pkt_addstring(s->pktout, "publickey");
7969 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7970 ssh2_pkt_addstring_start(s->pktout);
7971 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7972 ssh2_pkt_addstring_start(s->pktout);
7973 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7974 ssh2_pkt_send(ssh, s->pktout);
7975 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7977 crWaitUntilV(pktin);
7978 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7980 /* Offer of key refused. */
7987 if (flags & FLAG_VERBOSE) {
7988 c_write_str(ssh, "Authenticating with "
7990 c_write(ssh, s->commentp, s->commentlen);
7991 c_write_str(ssh, "\" from agent\r\n");
7995 * Server is willing to accept the key.
7996 * Construct a SIGN_REQUEST.
7998 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7999 ssh2_pkt_addstring(s->pktout, ssh->username);
8000 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8001 /* service requested */
8002 ssh2_pkt_addstring(s->pktout, "publickey");
8004 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8005 ssh2_pkt_addstring_start(s->pktout);
8006 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8007 ssh2_pkt_addstring_start(s->pktout);
8008 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8010 /* Ask agent for signature. */
8011 s->siglen = s->pktout->length - 5 + 4 +
8012 ssh->v2_session_id_len;
8013 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8015 s->len = 1; /* message type */
8016 s->len += 4 + s->pklen; /* key blob */
8017 s->len += 4 + s->siglen; /* data to sign */
8018 s->len += 4; /* flags */
8019 s->agentreq = snewn(4 + s->len, char);
8020 PUT_32BIT(s->agentreq, s->len);
8021 s->q = s->agentreq + 4;
8022 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8023 PUT_32BIT(s->q, s->pklen);
8025 memcpy(s->q, s->pkblob, s->pklen);
8027 PUT_32BIT(s->q, s->siglen);
8029 /* Now the data to be signed... */
8030 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8031 PUT_32BIT(s->q, ssh->v2_session_id_len);
8034 memcpy(s->q, ssh->v2_session_id,
8035 ssh->v2_session_id_len);
8036 s->q += ssh->v2_session_id_len;
8037 memcpy(s->q, s->pktout->data + 5,
8038 s->pktout->length - 5);
8039 s->q += s->pktout->length - 5;
8040 /* And finally the (zero) flags word. */
8042 if (!agent_query(s->agentreq, s->len + 4,
8044 ssh_agent_callback, ssh)) {
8048 bombout(("Unexpected data from server"
8049 " while waiting for agent"
8053 } while (pktin || inlen > 0);
8054 vret = ssh->agent_response;
8055 s->retlen = ssh->agent_response_len;
8060 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
8061 logevent("Sending Pageant's response");
8062 ssh2_add_sigblob(ssh, s->pktout,
8063 s->pkblob, s->pklen,
8065 GET_32BIT(s->ret + 5));
8066 ssh2_pkt_send(ssh, s->pktout);
8067 s->type = AUTH_TYPE_PUBLICKEY;
8069 /* FIXME: less drastic response */
8070 bombout(("Pageant failed to answer challenge"));
8076 /* Do we have any keys left to try? */
8077 if (s->pkblob_in_agent) {
8078 s->done_agent = TRUE;
8079 s->tried_pubkey_config = TRUE;
8082 if (s->keyi >= s->nkeys)
8083 s->done_agent = TRUE;
8086 } else if (s->can_pubkey && s->publickey_blob &&
8087 !s->tried_pubkey_config) {
8089 struct ssh2_userkey *key; /* not live over crReturn */
8090 char *passphrase; /* not live over crReturn */
8092 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8094 s->tried_pubkey_config = TRUE;
8097 * Try the public key supplied in the configuration.
8099 * First, offer the public blob to see if the server is
8100 * willing to accept it.
8102 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8103 ssh2_pkt_addstring(s->pktout, ssh->username);
8104 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8105 /* service requested */
8106 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8107 ssh2_pkt_addbool(s->pktout, FALSE);
8108 /* no signature included */
8109 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8110 ssh2_pkt_addstring_start(s->pktout);
8111 ssh2_pkt_addstring_data(s->pktout,
8112 (char *)s->publickey_blob,
8113 s->publickey_bloblen);
8114 ssh2_pkt_send(ssh, s->pktout);
8115 logevent("Offered public key");
8117 crWaitUntilV(pktin);
8118 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8119 /* Key refused. Give up. */
8120 s->gotit = TRUE; /* reconsider message next loop */
8121 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8122 continue; /* process this new message */
8124 logevent("Offer of public key accepted");
8127 * Actually attempt a serious authentication using
8130 if (flags & FLAG_VERBOSE) {
8131 c_write_str(ssh, "Authenticating with public key \"");
8132 c_write_str(ssh, s->publickey_comment);
8133 c_write_str(ssh, "\"\r\n");
8137 const char *error; /* not live over crReturn */
8138 if (s->publickey_encrypted) {
8140 * Get a passphrase from the user.
8142 int ret; /* need not be kept over crReturn */
8143 s->cur_prompt = new_prompts(ssh->frontend);
8144 s->cur_prompt->to_server = FALSE;
8145 s->cur_prompt->name = dupstr("SSH key passphrase");
8146 add_prompt(s->cur_prompt,
8147 dupprintf("Passphrase for key \"%.100s\": ",
8148 s->publickey_comment),
8150 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8153 crWaitUntilV(!pktin);
8154 ret = get_userpass_input(s->cur_prompt,
8159 /* Failed to get a passphrase. Terminate. */
8160 free_prompts(s->cur_prompt);
8161 ssh_disconnect(ssh, NULL,
8162 "Unable to authenticate",
8163 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8168 dupstr(s->cur_prompt->prompts[0]->result);
8169 free_prompts(s->cur_prompt);
8171 passphrase = NULL; /* no passphrase needed */
8175 * Try decrypting the key.
8177 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8178 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8180 /* burn the evidence */
8181 smemclr(passphrase, strlen(passphrase));
8184 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8186 (key == SSH2_WRONG_PASSPHRASE)) {
8187 c_write_str(ssh, "Wrong passphrase\r\n");
8189 /* and loop again */
8191 c_write_str(ssh, "Unable to load private key (");
8192 c_write_str(ssh, error);
8193 c_write_str(ssh, ")\r\n");
8195 break; /* try something else */
8201 unsigned char *pkblob, *sigblob, *sigdata;
8202 int pkblob_len, sigblob_len, sigdata_len;
8206 * We have loaded the private key and the server
8207 * has announced that it's willing to accept it.
8208 * Hallelujah. Generate a signature and send it.
8210 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8211 ssh2_pkt_addstring(s->pktout, ssh->username);
8212 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8213 /* service requested */
8214 ssh2_pkt_addstring(s->pktout, "publickey");
8216 ssh2_pkt_addbool(s->pktout, TRUE);
8217 /* signature follows */
8218 ssh2_pkt_addstring(s->pktout, key->alg->name);
8219 pkblob = key->alg->public_blob(key->data,
8221 ssh2_pkt_addstring_start(s->pktout);
8222 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8226 * The data to be signed is:
8230 * followed by everything so far placed in the
8233 sigdata_len = s->pktout->length - 5 + 4 +
8234 ssh->v2_session_id_len;
8235 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8237 sigdata = snewn(sigdata_len, unsigned char);
8239 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8240 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8243 memcpy(sigdata+p, ssh->v2_session_id,
8244 ssh->v2_session_id_len);
8245 p += ssh->v2_session_id_len;
8246 memcpy(sigdata+p, s->pktout->data + 5,
8247 s->pktout->length - 5);
8248 p += s->pktout->length - 5;
8249 assert(p == sigdata_len);
8250 sigblob = key->alg->sign(key->data, (char *)sigdata,
8251 sigdata_len, &sigblob_len);
8252 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8253 sigblob, sigblob_len);
8258 ssh2_pkt_send(ssh, s->pktout);
8259 logevent("Sent public key signature");
8260 s->type = AUTH_TYPE_PUBLICKEY;
8261 key->alg->freekey(key->data);
8265 } else if (s->can_gssapi && !s->tried_gssapi) {
8267 /* GSSAPI Authentication */
8272 s->type = AUTH_TYPE_GSSAPI;
8273 s->tried_gssapi = TRUE;
8275 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8278 * Pick the highest GSS library on the preference
8284 for (i = 0; i < ngsslibs; i++) {
8285 int want_id = conf_get_int_int(ssh->conf,
8286 CONF_ssh_gsslist, i);
8287 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8288 if (ssh->gsslibs->libraries[j].id == want_id) {
8289 s->gsslib = &ssh->gsslibs->libraries[j];
8290 goto got_gsslib; /* double break */
8295 * We always expect to have found something in
8296 * the above loop: we only came here if there
8297 * was at least one viable GSS library, and the
8298 * preference list should always mention
8299 * everything and only change the order.
8304 if (s->gsslib->gsslogmsg)
8305 logevent(s->gsslib->gsslogmsg);
8307 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8308 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8309 ssh2_pkt_addstring(s->pktout, ssh->username);
8310 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8311 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8312 logevent("Attempting GSSAPI authentication");
8314 /* add mechanism info */
8315 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8317 /* number of GSSAPI mechanisms */
8318 ssh2_pkt_adduint32(s->pktout,1);
8320 /* length of OID + 2 */
8321 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8322 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8325 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8327 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8329 ssh2_pkt_send(ssh, s->pktout);
8330 crWaitUntilV(pktin);
8331 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8332 logevent("GSSAPI authentication request refused");
8336 /* check returned packet ... */
8338 ssh_pkt_getstring(pktin, &data, &len);
8339 s->gss_rcvtok.value = data;
8340 s->gss_rcvtok.length = len;
8341 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8342 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8343 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8344 memcmp((char *)s->gss_rcvtok.value + 2,
8345 s->gss_buf.value,s->gss_buf.length) ) {
8346 logevent("GSSAPI authentication - wrong response from server");
8350 /* now start running */
8351 s->gss_stat = s->gsslib->import_name(s->gsslib,
8354 if (s->gss_stat != SSH_GSS_OK) {
8355 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8356 logevent("GSSAPI import name failed - Bad service name");
8358 logevent("GSSAPI import name failed");
8362 /* fetch TGT into GSS engine */
8363 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8365 if (s->gss_stat != SSH_GSS_OK) {
8366 logevent("GSSAPI authentication failed to get credentials");
8367 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8371 /* initial tokens are empty */
8372 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8373 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8375 /* now enter the loop */
8377 s->gss_stat = s->gsslib->init_sec_context
8381 conf_get_int(ssh->conf, CONF_gssapifwd),
8385 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8386 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8387 logevent("GSSAPI authentication initialisation failed");
8389 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8390 &s->gss_buf) == SSH_GSS_OK) {
8391 logevent(s->gss_buf.value);
8392 sfree(s->gss_buf.value);
8397 logevent("GSSAPI authentication initialised");
8399 /* Client and server now exchange tokens until GSSAPI
8400 * no longer says CONTINUE_NEEDED */
8402 if (s->gss_sndtok.length != 0) {
8403 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8404 ssh_pkt_addstring_start(s->pktout);
8405 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8406 ssh2_pkt_send(ssh, s->pktout);
8407 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8410 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8411 crWaitUntilV(pktin);
8412 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8413 logevent("GSSAPI authentication - bad server response");
8414 s->gss_stat = SSH_GSS_FAILURE;
8417 ssh_pkt_getstring(pktin, &data, &len);
8418 s->gss_rcvtok.value = data;
8419 s->gss_rcvtok.length = len;
8421 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8423 if (s->gss_stat != SSH_GSS_OK) {
8424 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8425 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8428 logevent("GSSAPI authentication loop finished OK");
8430 /* Now send the MIC */
8432 s->pktout = ssh2_pkt_init(0);
8433 micoffset = s->pktout->length;
8434 ssh_pkt_addstring_start(s->pktout);
8435 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8436 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8437 ssh_pkt_addstring(s->pktout, ssh->username);
8438 ssh_pkt_addstring(s->pktout, "ssh-connection");
8439 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8441 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8442 s->gss_buf.length = s->pktout->length - micoffset;
8444 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8445 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8446 ssh_pkt_addstring_start(s->pktout);
8447 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8448 ssh2_pkt_send(ssh, s->pktout);
8449 s->gsslib->free_mic(s->gsslib, &mic);
8453 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8454 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8457 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8460 * Keyboard-interactive authentication.
8463 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8465 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8467 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8468 ssh2_pkt_addstring(s->pktout, ssh->username);
8469 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8470 /* service requested */
8471 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8473 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8474 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8475 ssh2_pkt_send(ssh, s->pktout);
8477 logevent("Attempting keyboard-interactive authentication");
8479 crWaitUntilV(pktin);
8480 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8481 /* Server is not willing to do keyboard-interactive
8482 * at all (or, bizarrely but legally, accepts the
8483 * user without actually issuing any prompts).
8484 * Give up on it entirely. */
8486 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8487 s->kbd_inter_refused = TRUE; /* don't try it again */
8492 * Loop while the server continues to send INFO_REQUESTs.
8494 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8496 char *name, *inst, *lang;
8497 int name_len, inst_len, lang_len;
8501 * We've got a fresh USERAUTH_INFO_REQUEST.
8502 * Get the preamble and start building a prompt.
8504 ssh_pkt_getstring(pktin, &name, &name_len);
8505 ssh_pkt_getstring(pktin, &inst, &inst_len);
8506 ssh_pkt_getstring(pktin, &lang, &lang_len);
8507 s->cur_prompt = new_prompts(ssh->frontend);
8508 s->cur_prompt->to_server = TRUE;
8511 * Get any prompt(s) from the packet.
8513 s->num_prompts = ssh_pkt_getuint32(pktin);
8514 for (i = 0; i < s->num_prompts; i++) {
8518 static char noprompt[] =
8519 "<server failed to send prompt>: ";
8521 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8522 echo = ssh2_pkt_getbool(pktin);
8525 prompt_len = lenof(noprompt)-1;
8527 add_prompt(s->cur_prompt,
8528 dupprintf("%.*s", prompt_len, prompt),
8533 /* FIXME: better prefix to distinguish from
8535 s->cur_prompt->name =
8536 dupprintf("SSH server: %.*s", name_len, name);
8537 s->cur_prompt->name_reqd = TRUE;
8539 s->cur_prompt->name =
8540 dupstr("SSH server authentication");
8541 s->cur_prompt->name_reqd = FALSE;
8543 /* We add a prefix to try to make it clear that a prompt
8544 * has come from the server.
8545 * FIXME: ugly to print "Using..." in prompt _every_
8546 * time round. Can this be done more subtly? */
8547 /* Special case: for reasons best known to themselves,
8548 * some servers send k-i requests with no prompts and
8549 * nothing to display. Keep quiet in this case. */
8550 if (s->num_prompts || name_len || inst_len) {
8551 s->cur_prompt->instruction =
8552 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8553 inst_len ? "\n" : "", inst_len, inst);
8554 s->cur_prompt->instr_reqd = TRUE;
8556 s->cur_prompt->instr_reqd = FALSE;
8560 * Display any instructions, and get the user's
8564 int ret; /* not live over crReturn */
8565 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8568 crWaitUntilV(!pktin);
8569 ret = get_userpass_input(s->cur_prompt, in, inlen);
8574 * Failed to get responses. Terminate.
8576 free_prompts(s->cur_prompt);
8577 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8578 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8585 * Send the response(s) to the server.
8587 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8588 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8589 for (i=0; i < s->num_prompts; i++) {
8590 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8591 ssh2_pkt_addstring(s->pktout,
8592 s->cur_prompt->prompts[i]->result);
8593 end_log_omission(ssh, s->pktout);
8595 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8598 * Free the prompts structure from this iteration.
8599 * If there's another, a new one will be allocated
8600 * when we return to the top of this while loop.
8602 free_prompts(s->cur_prompt);
8605 * Get the next packet in case it's another
8608 crWaitUntilV(pktin);
8613 * We should have SUCCESS or FAILURE now.
8617 } else if (s->can_passwd) {
8620 * Plain old password authentication.
8622 int ret; /* not live over crReturn */
8623 int changereq_first_time; /* not live over crReturn */
8625 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8627 s->cur_prompt = new_prompts(ssh->frontend);
8628 s->cur_prompt->to_server = TRUE;
8629 s->cur_prompt->name = dupstr("SSH password");
8630 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8635 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8638 crWaitUntilV(!pktin);
8639 ret = get_userpass_input(s->cur_prompt, in, inlen);
8644 * Failed to get responses. Terminate.
8646 free_prompts(s->cur_prompt);
8647 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8648 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8653 * Squirrel away the password. (We may need it later if
8654 * asked to change it.)
8656 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8657 free_prompts(s->cur_prompt);
8660 * Send the password packet.
8662 * We pad out the password packet to 256 bytes to make
8663 * it harder for an attacker to find the length of the
8666 * Anyone using a password longer than 256 bytes
8667 * probably doesn't have much to worry about from
8668 * people who find out how long their password is!
8670 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8671 ssh2_pkt_addstring(s->pktout, ssh->username);
8672 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8673 /* service requested */
8674 ssh2_pkt_addstring(s->pktout, "password");
8675 ssh2_pkt_addbool(s->pktout, FALSE);
8676 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8677 ssh2_pkt_addstring(s->pktout, s->password);
8678 end_log_omission(ssh, s->pktout);
8679 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8680 logevent("Sent password");
8681 s->type = AUTH_TYPE_PASSWORD;
8684 * Wait for next packet, in case it's a password change
8687 crWaitUntilV(pktin);
8688 changereq_first_time = TRUE;
8690 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8693 * We're being asked for a new password
8694 * (perhaps not for the first time).
8695 * Loop until the server accepts it.
8698 int got_new = FALSE; /* not live over crReturn */
8699 char *prompt; /* not live over crReturn */
8700 int prompt_len; /* not live over crReturn */
8704 if (changereq_first_time)
8705 msg = "Server requested password change";
8707 msg = "Server rejected new password";
8709 c_write_str(ssh, msg);
8710 c_write_str(ssh, "\r\n");
8713 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8715 s->cur_prompt = new_prompts(ssh->frontend);
8716 s->cur_prompt->to_server = TRUE;
8717 s->cur_prompt->name = dupstr("New SSH password");
8718 s->cur_prompt->instruction =
8719 dupprintf("%.*s", prompt_len, prompt);
8720 s->cur_prompt->instr_reqd = TRUE;
8722 * There's no explicit requirement in the protocol
8723 * for the "old" passwords in the original and
8724 * password-change messages to be the same, and
8725 * apparently some Cisco kit supports password change
8726 * by the user entering a blank password originally
8727 * and the real password subsequently, so,
8728 * reluctantly, we prompt for the old password again.
8730 * (On the other hand, some servers don't even bother
8731 * to check this field.)
8733 add_prompt(s->cur_prompt,
8734 dupstr("Current password (blank for previously entered password): "),
8736 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8738 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8742 * Loop until the user manages to enter the same
8747 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8750 crWaitUntilV(!pktin);
8751 ret = get_userpass_input(s->cur_prompt, in, inlen);
8756 * Failed to get responses. Terminate.
8758 /* burn the evidence */
8759 free_prompts(s->cur_prompt);
8760 smemclr(s->password, strlen(s->password));
8762 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8763 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8769 * If the user specified a new original password
8770 * (IYSWIM), overwrite any previously specified
8772 * (A side effect is that the user doesn't have to
8773 * re-enter it if they louse up the new password.)
8775 if (s->cur_prompt->prompts[0]->result[0]) {
8776 smemclr(s->password, strlen(s->password));
8777 /* burn the evidence */
8780 dupstr(s->cur_prompt->prompts[0]->result);
8784 * Check the two new passwords match.
8786 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8787 s->cur_prompt->prompts[2]->result)
8790 /* They don't. Silly user. */
8791 c_write_str(ssh, "Passwords do not match\r\n");
8796 * Send the new password (along with the old one).
8797 * (see above for padding rationale)
8799 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8800 ssh2_pkt_addstring(s->pktout, ssh->username);
8801 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8802 /* service requested */
8803 ssh2_pkt_addstring(s->pktout, "password");
8804 ssh2_pkt_addbool(s->pktout, TRUE);
8805 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8806 ssh2_pkt_addstring(s->pktout, s->password);
8807 ssh2_pkt_addstring(s->pktout,
8808 s->cur_prompt->prompts[1]->result);
8809 free_prompts(s->cur_prompt);
8810 end_log_omission(ssh, s->pktout);
8811 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8812 logevent("Sent new password");
8815 * Now see what the server has to say about it.
8816 * (If it's CHANGEREQ again, it's not happy with the
8819 crWaitUntilV(pktin);
8820 changereq_first_time = FALSE;
8825 * We need to reexamine the current pktin at the top
8826 * of the loop. Either:
8827 * - we weren't asked to change password at all, in
8828 * which case it's a SUCCESS or FAILURE with the
8830 * - we sent a new password, and the server was
8831 * either OK with it (SUCCESS or FAILURE w/partial
8832 * success) or unhappy with the _old_ password
8833 * (FAILURE w/o partial success)
8834 * In any of these cases, we go back to the top of
8835 * the loop and start again.
8840 * We don't need the old password any more, in any
8841 * case. Burn the evidence.
8843 smemclr(s->password, strlen(s->password));
8847 char *str = dupprintf("No supported authentication methods available"
8848 " (server sent: %.*s)",
8851 ssh_disconnect(ssh, str,
8852 "No supported authentication methods available",
8853 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8863 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8865 /* Clear up various bits and pieces from authentication. */
8866 if (s->publickey_blob) {
8867 sfree(s->publickey_blob);
8868 sfree(s->publickey_comment);
8870 if (s->agent_response)
8871 sfree(s->agent_response);
8873 if (s->userauth_success) {
8875 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8876 * packets since. Signal the transport layer to consider enacting
8877 * delayed compression.
8879 * (Relying on we_are_in is not sufficient, as
8880 * draft-miller-secsh-compression-delayed is quite clear that it
8881 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8882 * become set for other reasons.)
8884 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8888 * Now the connection protocol has started, one way or another.
8891 ssh->channels = newtree234(ssh_channelcmp);
8894 * Set up handlers for some connection protocol messages, so we
8895 * don't have to handle them repeatedly in this coroutine.
8897 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8898 ssh2_msg_channel_window_adjust;
8899 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8900 ssh2_msg_global_request;
8903 * Create the main session channel.
8905 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
8906 ssh->mainchan = NULL;
8907 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
8909 * Just start a direct-tcpip channel and use it as the main
8912 ssh->mainchan = snew(struct ssh_channel);
8913 ssh->mainchan->ssh = ssh;
8914 ssh2_channel_init(ssh->mainchan);
8916 "Opening direct-tcpip channel to %s:%d in place of session",
8917 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8918 conf_get_int(ssh->conf, CONF_ssh_nc_port));
8919 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8920 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8921 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8922 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8923 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8924 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8925 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
8927 * There's nothing meaningful to put in the originator
8928 * fields, but some servers insist on syntactically correct
8931 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8932 ssh2_pkt_adduint32(s->pktout, 0);
8933 ssh2_pkt_send(ssh, s->pktout);
8935 crWaitUntilV(pktin);
8936 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8937 bombout(("Server refused to open a direct-tcpip channel"));
8939 /* FIXME: error data comes back in FAILURE packet */
8941 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8942 bombout(("Server's channel confirmation cited wrong channel"));
8945 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8946 ssh->mainchan->halfopen = FALSE;
8947 ssh->mainchan->type = CHAN_MAINSESSION;
8948 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8949 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8950 add234(ssh->channels, ssh->mainchan);
8951 update_specials_menu(ssh->frontend);
8952 logevent("Opened direct-tcpip channel");
8955 ssh->mainchan = snew(struct ssh_channel);
8956 ssh->mainchan->ssh = ssh;
8957 ssh2_channel_init(ssh->mainchan);
8958 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8959 ssh2_pkt_addstring(s->pktout, "session");
8960 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8961 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8962 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8963 ssh2_pkt_send(ssh, s->pktout);
8964 crWaitUntilV(pktin);
8965 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8966 bombout(("Server refused to open a session"));
8968 /* FIXME: error data comes back in FAILURE packet */
8970 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8971 bombout(("Server's channel confirmation cited wrong channel"));
8974 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8975 ssh->mainchan->halfopen = FALSE;
8976 ssh->mainchan->type = CHAN_MAINSESSION;
8977 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8978 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8979 add234(ssh->channels, ssh->mainchan);
8980 update_specials_menu(ssh->frontend);
8981 logevent("Opened channel for session");
8982 ssh->ncmode = FALSE;
8986 * Now we have a channel, make dispatch table entries for
8987 * general channel-based messages.
8989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8991 ssh2_msg_channel_data;
8992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8995 ssh2_msg_channel_open_confirmation;
8996 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8997 ssh2_msg_channel_open_failure;
8998 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8999 ssh2_msg_channel_request;
9000 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9001 ssh2_msg_channel_open;
9003 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9005 * This message indicates to the server that we promise
9006 * not to try to run any other channel in parallel with
9007 * this one, so it's safe for it to advertise a very large
9008 * window and leave the flow control to TCP.
9010 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9011 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9012 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
9013 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
9014 ssh2_pkt_send(ssh, s->pktout);
9018 * Enable port forwardings.
9020 ssh_setup_portfwd(ssh, ssh->conf);
9023 * Send the CHANNEL_REQUESTS for the main channel. We send them all
9024 * and then start looking for responses, so it's important that the
9025 * sending and receiving code below it is kept in sync.
9029 * Potentially enable X11 forwarding.
9031 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
9032 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9033 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
9034 logevent("Requesting X11 forwarding");
9035 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9036 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9037 ssh2_pkt_addstring(s->pktout, "x11-req");
9038 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9039 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
9040 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
9042 * Note that while we blank the X authentication data here, we don't
9043 * take any special action to blank the start of an X11 channel,
9044 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
9045 * without having session blanking enabled is likely to leak your
9046 * cookie into the log.
9048 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9049 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
9050 end_log_omission(ssh, s->pktout);
9051 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
9052 ssh2_pkt_send(ssh, s->pktout);
9053 s->requested_x11 = TRUE;
9055 s->requested_x11 = FALSE;
9058 * Potentially enable agent forwarding.
9060 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
9061 logevent("Requesting OpenSSH-style agent forwarding");
9062 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9063 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9064 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
9065 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9066 ssh2_pkt_send(ssh, s->pktout);
9067 s->requested_agent = TRUE;
9069 s->requested_agent = FALSE;
9072 * Now allocate a pty for the session.
9074 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
9075 /* Unpick the terminal-speed string. */
9076 /* XXX perhaps we should allow no speeds to be sent. */
9077 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9078 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9079 /* Build the pty request. */
9080 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9081 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9082 ssh2_pkt_addstring(s->pktout, "pty-req");
9083 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9084 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
9085 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
9086 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
9087 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
9088 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
9089 ssh2_pkt_addstring_start(s->pktout);
9090 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
9091 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
9092 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
9093 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
9094 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9095 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9096 ssh2_pkt_send(ssh, s->pktout);
9097 ssh->state = SSH_STATE_INTERMED;
9098 s->requested_tty = TRUE;
9100 s->requested_tty = FALSE;
9103 * Send environment variables.
9105 * Simplest thing here is to send all the requests at once, and
9106 * then wait for a whole bunch of successes or failures.
9109 if (ssh->mainchan && !ssh->ncmode) {
9112 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9114 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9115 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9116 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9117 ssh2_pkt_addstring(s->pktout, "env");
9118 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9119 ssh2_pkt_addstring(s->pktout, key);
9120 ssh2_pkt_addstring(s->pktout, val);
9121 ssh2_pkt_send(ssh, s->pktout);
9126 logeventf(ssh, "Sent %d environment variables", s->num_env);
9130 * All CHANNEL_REQUESTs sent. Now collect up the replies. These
9131 * must be in precisely the same order as the requests.
9134 if (s->requested_x11) {
9135 crWaitUntilV(pktin);
9137 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9138 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9139 bombout(("Unexpected response to X11 forwarding request:"
9140 " packet type %d", pktin->type));
9143 logevent("X11 forwarding refused");
9145 logevent("X11 forwarding enabled");
9146 ssh->X11_fwd_enabled = TRUE;
9150 if (s->requested_agent) {
9151 crWaitUntilV(pktin);
9153 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9154 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9155 bombout(("Unexpected response to agent forwarding request:"
9156 " packet type %d", pktin->type));
9159 logevent("Agent forwarding refused");
9161 logevent("Agent forwarding enabled");
9162 ssh->agentfwd_enabled = TRUE;
9166 if (s->requested_tty) {
9167 crWaitUntilV(pktin);
9169 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9170 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9171 bombout(("Unexpected response to pty request:"
9172 " packet type %d", pktin->type));
9175 c_write_str(ssh, "Server refused to allocate pty\r\n");
9176 ssh->editing = ssh->echoing = 1;
9178 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9179 ssh->ospeed, ssh->ispeed);
9180 ssh->got_pty = TRUE;
9183 ssh->editing = ssh->echoing = 1;
9188 s->env_left = s->num_env;
9190 while (s->env_left > 0) {
9191 crWaitUntilV(pktin);
9193 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9194 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9195 bombout(("Unexpected response to environment request:"
9196 " packet type %d", pktin->type));
9206 if (s->env_ok == s->num_env) {
9207 logevent("All environment variables successfully set");
9208 } else if (s->env_ok == 0) {
9209 logevent("All environment variables refused");
9210 c_write_str(ssh, "Server refused to set environment variables\r\n");
9212 logeventf(ssh, "%d environment variables refused",
9213 s->num_env - s->env_ok);
9214 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9219 * Start a shell or a remote command. We may have to attempt
9220 * this twice if the config data has provided a second choice
9223 if (ssh->mainchan && !ssh->ncmode) while (1) {
9227 if (ssh->fallback_cmd) {
9228 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9229 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9231 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9232 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9235 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9236 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9238 ssh2_pkt_addstring(s->pktout, "subsystem");
9239 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9240 ssh2_pkt_addstring(s->pktout, cmd);
9242 ssh2_pkt_addstring(s->pktout, "exec");
9243 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9244 ssh2_pkt_addstring(s->pktout, cmd);
9246 ssh2_pkt_addstring(s->pktout, "shell");
9247 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9249 ssh2_pkt_send(ssh, s->pktout);
9251 crWaitUntilV(pktin);
9253 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9254 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9255 bombout(("Unexpected response to shell/command request:"
9256 " packet type %d", pktin->type));
9260 * We failed to start the command. If this is the
9261 * fallback command, we really are finished; if it's
9262 * not, and if the fallback command exists, try falling
9263 * back to it before complaining.
9265 if (!ssh->fallback_cmd &&
9266 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9267 logevent("Primary command failed; attempting fallback");
9268 ssh->fallback_cmd = TRUE;
9271 bombout(("Server refused to start a shell/command"));
9274 logevent("Started a shell/command");
9279 ssh->state = SSH_STATE_SESSION;
9280 if (ssh->size_needed)
9281 ssh_size(ssh, ssh->term_width, ssh->term_height);
9282 if (ssh->eof_needed)
9283 ssh_special(ssh, TS_EOF);
9286 * All the initial channel requests are done, so install the default
9289 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
9290 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9296 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9301 s->try_send = FALSE;
9305 * _All_ the connection-layer packets we expect to
9306 * receive are now handled by the dispatch table.
9307 * Anything that reaches here must be bogus.
9310 bombout(("Strange packet received: type %d", pktin->type));
9312 } else if (ssh->mainchan) {
9314 * We have spare data. Add it to the channel buffer.
9316 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9321 struct ssh_channel *c;
9323 * Try to send data on all channels if we can.
9325 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9326 ssh2_try_send_and_unthrottle(ssh, c);
9334 * Handlers for SSH-2 messages that might arrive at any moment.
9336 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9338 /* log reason code in disconnect message */
9342 reason = ssh_pkt_getuint32(pktin);
9343 ssh_pkt_getstring(pktin, &msg, &msglen);
9345 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9346 buf = dupprintf("Received disconnect message (%s)",
9347 ssh2_disconnect_reasons[reason]);
9349 buf = dupprintf("Received disconnect message (unknown"
9350 " type %d)", reason);
9354 buf = dupprintf("Disconnection message text: %.*s",
9357 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9359 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9360 ssh2_disconnect_reasons[reason] : "unknown",
9365 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9367 /* log the debug message */
9371 /* XXX maybe we should actually take notice of the return value */
9372 ssh2_pkt_getbool(pktin);
9373 ssh_pkt_getstring(pktin, &msg, &msglen);
9375 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9378 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9380 do_ssh2_transport(ssh, NULL, 0, pktin);
9384 * Called if we receive a packet that isn't allowed by the protocol.
9385 * This only applies to packets whose meaning PuTTY understands.
9386 * Entirely unknown packets are handled below.
9388 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9390 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9391 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9393 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9396 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9398 struct Packet *pktout;
9399 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9400 ssh2_pkt_adduint32(pktout, pktin->sequence);
9402 * UNIMPLEMENTED messages MUST appear in the same order as the
9403 * messages they respond to. Hence, never queue them.
9405 ssh2_pkt_send_noqueue(ssh, pktout);
9409 * Handle the top-level SSH-2 protocol.
9411 static void ssh2_protocol_setup(Ssh ssh)
9416 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9418 for (i = 0; i < 256; i++)
9419 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9422 * Initially, we only accept transport messages (and a few generic
9423 * ones). do_ssh2_authconn will add more when it starts.
9424 * Messages that are understood but not currently acceptable go to
9425 * ssh2_msg_unexpected.
9427 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9428 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9429 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9430 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9431 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9432 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9433 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9434 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9435 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9436 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9437 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9438 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9439 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9440 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9441 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9442 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9443 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9444 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9445 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9446 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9447 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9448 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9449 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9450 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9451 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9452 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9453 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9454 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9455 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9456 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9457 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9458 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9459 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9462 * These messages have a special handler from the start.
9464 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9465 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9466 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9469 static void ssh2_timer(void *ctx, long now)
9473 if (ssh->state == SSH_STATE_CLOSED)
9476 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9477 now - ssh->next_rekey >= 0) {
9478 do_ssh2_transport(ssh, "timeout", -1, NULL);
9482 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9483 struct Packet *pktin)
9485 unsigned char *in = (unsigned char *)vin;
9486 if (ssh->state == SSH_STATE_CLOSED)
9490 ssh->incoming_data_size += pktin->encrypted_len;
9491 if (!ssh->kex_in_progress &&
9492 ssh->max_data_size != 0 &&
9493 ssh->incoming_data_size > ssh->max_data_size)
9494 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9498 ssh->packet_dispatch[pktin->type](ssh, pktin);
9499 else if (!ssh->protocol_initial_phase_done)
9500 do_ssh2_transport(ssh, in, inlen, pktin);
9502 do_ssh2_authconn(ssh, in, inlen, pktin);
9505 static void ssh_cache_conf_values(Ssh ssh)
9507 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9511 * Called to set up the connection.
9513 * Returns an error message, or NULL on success.
9515 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9516 Conf *conf, char *host, int port, char **realhost,
9517 int nodelay, int keepalive)
9522 ssh = snew(struct ssh_tag);
9523 ssh->conf = conf_copy(conf);
9524 ssh_cache_conf_values(ssh);
9525 ssh->version = 0; /* when not ready yet */
9528 ssh->v1_cipher_ctx = NULL;
9529 ssh->crcda_ctx = NULL;
9530 ssh->cscipher = NULL;
9531 ssh->cs_cipher_ctx = NULL;
9532 ssh->sccipher = NULL;
9533 ssh->sc_cipher_ctx = NULL;
9535 ssh->cs_mac_ctx = NULL;
9537 ssh->sc_mac_ctx = NULL;
9539 ssh->cs_comp_ctx = NULL;
9541 ssh->sc_comp_ctx = NULL;
9543 ssh->kex_ctx = NULL;
9544 ssh->hostkey = NULL;
9546 ssh->close_expected = FALSE;
9547 ssh->clean_exit = FALSE;
9548 ssh->state = SSH_STATE_PREPACKET;
9549 ssh->size_needed = FALSE;
9550 ssh->eof_needed = FALSE;
9553 ssh->deferred_send_data = NULL;
9554 ssh->deferred_len = 0;
9555 ssh->deferred_size = 0;
9556 ssh->fallback_cmd = 0;
9557 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9558 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9559 ssh->x11disp = NULL;
9560 ssh->v1_compressing = FALSE;
9561 ssh->v2_outgoing_sequence = 0;
9562 ssh->ssh1_rdpkt_crstate = 0;
9563 ssh->ssh2_rdpkt_crstate = 0;
9564 ssh->ssh_gotdata_crstate = 0;
9565 ssh->do_ssh1_connection_crstate = 0;
9566 ssh->do_ssh_init_state = NULL;
9567 ssh->do_ssh1_login_state = NULL;
9568 ssh->do_ssh2_transport_state = NULL;
9569 ssh->do_ssh2_authconn_state = NULL;
9572 ssh->mainchan = NULL;
9573 ssh->throttled_all = 0;
9574 ssh->v1_stdout_throttling = 0;
9576 ssh->queuelen = ssh->queuesize = 0;
9577 ssh->queueing = FALSE;
9578 ssh->qhead = ssh->qtail = NULL;
9579 ssh->deferred_rekey_reason = NULL;
9580 bufchain_init(&ssh->queued_incoming_data);
9581 ssh->frozen = FALSE;
9582 ssh->username = NULL;
9583 ssh->sent_console_eof = FALSE;
9584 ssh->got_pty = FALSE;
9586 *backend_handle = ssh;
9589 if (crypto_startup() == 0)
9590 return "Microsoft high encryption pack not installed!";
9593 ssh->frontend = frontend_handle;
9594 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9595 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9597 ssh->channels = NULL;
9598 ssh->rportfwds = NULL;
9599 ssh->portfwds = NULL;
9604 ssh->conn_throttle_count = 0;
9605 ssh->overall_bufsize = 0;
9606 ssh->fallback_cmd = 0;
9608 ssh->protocol = NULL;
9610 ssh->protocol_initial_phase_done = FALSE;
9614 ssh->incoming_data_size = ssh->outgoing_data_size =
9615 ssh->deferred_data_size = 0L;
9616 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9617 CONF_ssh_rekey_data));
9618 ssh->kex_in_progress = FALSE;
9621 ssh->gsslibs = NULL;
9624 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9633 static void ssh_free(void *handle)
9635 Ssh ssh = (Ssh) handle;
9636 struct ssh_channel *c;
9637 struct ssh_rportfwd *pf;
9639 if (ssh->v1_cipher_ctx)
9640 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9641 if (ssh->cs_cipher_ctx)
9642 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9643 if (ssh->sc_cipher_ctx)
9644 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9645 if (ssh->cs_mac_ctx)
9646 ssh->csmac->free_context(ssh->cs_mac_ctx);
9647 if (ssh->sc_mac_ctx)
9648 ssh->scmac->free_context(ssh->sc_mac_ctx);
9649 if (ssh->cs_comp_ctx) {
9651 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9653 zlib_compress_cleanup(ssh->cs_comp_ctx);
9655 if (ssh->sc_comp_ctx) {
9657 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9659 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9662 dh_cleanup(ssh->kex_ctx);
9663 sfree(ssh->savedhost);
9665 while (ssh->queuelen-- > 0)
9666 ssh_free_packet(ssh->queue[ssh->queuelen]);
9669 while (ssh->qhead) {
9670 struct queued_handler *qh = ssh->qhead;
9671 ssh->qhead = qh->next;
9674 ssh->qhead = ssh->qtail = NULL;
9676 if (ssh->channels) {
9677 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9680 if (c->u.x11.s != NULL)
9681 x11_close(c->u.x11.s);
9684 case CHAN_SOCKDATA_DORMANT:
9685 if (c->u.pfd.s != NULL)
9686 pfd_close(c->u.pfd.s);
9691 freetree234(ssh->channels);
9692 ssh->channels = NULL;
9695 if (ssh->rportfwds) {
9696 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9698 freetree234(ssh->rportfwds);
9699 ssh->rportfwds = NULL;
9701 sfree(ssh->deferred_send_data);
9703 x11_free_display(ssh->x11disp);
9704 sfree(ssh->do_ssh_init_state);
9705 sfree(ssh->do_ssh1_login_state);
9706 sfree(ssh->do_ssh2_transport_state);
9707 sfree(ssh->do_ssh2_authconn_state);
9710 sfree(ssh->fullhostname);
9711 if (ssh->crcda_ctx) {
9712 crcda_free_context(ssh->crcda_ctx);
9713 ssh->crcda_ctx = NULL;
9716 ssh_do_close(ssh, TRUE);
9717 expire_timer_context(ssh);
9719 pinger_free(ssh->pinger);
9720 bufchain_clear(&ssh->queued_incoming_data);
9721 sfree(ssh->username);
9722 conf_free(ssh->conf);
9725 ssh_gss_cleanup(ssh->gsslibs);
9733 * Reconfigure the SSH backend.
9735 static void ssh_reconfig(void *handle, Conf *conf)
9737 Ssh ssh = (Ssh) handle;
9738 char *rekeying = NULL, rekey_mandatory = FALSE;
9739 unsigned long old_max_data_size;
9742 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9744 ssh_setup_portfwd(ssh, conf);
9746 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9747 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9749 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9750 long now = GETTICKCOUNT();
9752 if (new_next - now < 0) {
9753 rekeying = "timeout shortened";
9755 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9759 old_max_data_size = ssh->max_data_size;
9760 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9761 CONF_ssh_rekey_data));
9762 if (old_max_data_size != ssh->max_data_size &&
9763 ssh->max_data_size != 0) {
9764 if (ssh->outgoing_data_size > ssh->max_data_size ||
9765 ssh->incoming_data_size > ssh->max_data_size)
9766 rekeying = "data limit lowered";
9769 if (conf_get_int(ssh->conf, CONF_compression) !=
9770 conf_get_int(conf, CONF_compression)) {
9771 rekeying = "compression setting changed";
9772 rekey_mandatory = TRUE;
9775 for (i = 0; i < CIPHER_MAX; i++)
9776 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9777 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9778 rekeying = "cipher settings changed";
9779 rekey_mandatory = TRUE;
9781 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9782 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9783 rekeying = "cipher settings changed";
9784 rekey_mandatory = TRUE;
9787 conf_free(ssh->conf);
9788 ssh->conf = conf_copy(conf);
9789 ssh_cache_conf_values(ssh);
9792 if (!ssh->kex_in_progress) {
9793 do_ssh2_transport(ssh, rekeying, -1, NULL);
9794 } else if (rekey_mandatory) {
9795 ssh->deferred_rekey_reason = rekeying;
9801 * Called to send data down the SSH connection.
9803 static int ssh_send(void *handle, char *buf, int len)
9805 Ssh ssh = (Ssh) handle;
9807 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9810 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9812 return ssh_sendbuffer(ssh);
9816 * Called to query the current amount of buffered stdin data.
9818 static int ssh_sendbuffer(void *handle)
9820 Ssh ssh = (Ssh) handle;
9823 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9827 * If the SSH socket itself has backed up, add the total backup
9828 * size on that to any individual buffer on the stdin channel.
9831 if (ssh->throttled_all)
9832 override_value = ssh->overall_bufsize;
9834 if (ssh->version == 1) {
9835 return override_value;
9836 } else if (ssh->version == 2) {
9838 return override_value;
9840 return (override_value +
9841 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9848 * Called to set the size of the window from SSH's POV.
9850 static void ssh_size(void *handle, int width, int height)
9852 Ssh ssh = (Ssh) handle;
9853 struct Packet *pktout;
9855 ssh->term_width = width;
9856 ssh->term_height = height;
9858 switch (ssh->state) {
9859 case SSH_STATE_BEFORE_SIZE:
9860 case SSH_STATE_PREPACKET:
9861 case SSH_STATE_CLOSED:
9862 break; /* do nothing */
9863 case SSH_STATE_INTERMED:
9864 ssh->size_needed = TRUE; /* buffer for later */
9866 case SSH_STATE_SESSION:
9867 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9868 if (ssh->version == 1) {
9869 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9870 PKT_INT, ssh->term_height,
9871 PKT_INT, ssh->term_width,
9872 PKT_INT, 0, PKT_INT, 0, PKT_END);
9873 } else if (ssh->mainchan) {
9874 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9875 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9876 ssh2_pkt_addstring(pktout, "window-change");
9877 ssh2_pkt_addbool(pktout, 0);
9878 ssh2_pkt_adduint32(pktout, ssh->term_width);
9879 ssh2_pkt_adduint32(pktout, ssh->term_height);
9880 ssh2_pkt_adduint32(pktout, 0);
9881 ssh2_pkt_adduint32(pktout, 0);
9882 ssh2_pkt_send(ssh, pktout);
9890 * Return a list of the special codes that make sense in this
9893 static const struct telnet_special *ssh_get_specials(void *handle)
9895 static const struct telnet_special ssh1_ignore_special[] = {
9896 {"IGNORE message", TS_NOP}
9898 static const struct telnet_special ssh2_ignore_special[] = {
9899 {"IGNORE message", TS_NOP},
9901 static const struct telnet_special ssh2_rekey_special[] = {
9902 {"Repeat key exchange", TS_REKEY},
9904 static const struct telnet_special ssh2_session_specials[] = {
9907 /* These are the signal names defined by RFC 4254.
9908 * They include all the ISO C signals, but are a subset of the POSIX
9909 * required signals. */
9910 {"SIGINT (Interrupt)", TS_SIGINT},
9911 {"SIGTERM (Terminate)", TS_SIGTERM},
9912 {"SIGKILL (Kill)", TS_SIGKILL},
9913 {"SIGQUIT (Quit)", TS_SIGQUIT},
9914 {"SIGHUP (Hangup)", TS_SIGHUP},
9915 {"More signals", TS_SUBMENU},
9916 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9917 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9918 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9919 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9922 static const struct telnet_special specials_end[] = {
9925 /* XXX review this length for any changes: */
9926 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9927 lenof(ssh2_rekey_special) +
9928 lenof(ssh2_session_specials) +
9929 lenof(specials_end)];
9930 Ssh ssh = (Ssh) handle;
9932 #define ADD_SPECIALS(name) \
9934 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9935 memcpy(&ssh_specials[i], name, sizeof name); \
9939 if (ssh->version == 1) {
9940 /* Don't bother offering IGNORE if we've decided the remote
9941 * won't cope with it, since we wouldn't bother sending it if
9943 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9944 ADD_SPECIALS(ssh1_ignore_special);
9945 } else if (ssh->version == 2) {
9946 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9947 ADD_SPECIALS(ssh2_ignore_special);
9948 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9949 ADD_SPECIALS(ssh2_rekey_special);
9951 ADD_SPECIALS(ssh2_session_specials);
9952 } /* else we're not ready yet */
9955 ADD_SPECIALS(specials_end);
9956 return ssh_specials;
9964 * Send special codes. TS_EOF is useful for `plink', so you
9965 * can send an EOF and collect resulting output (e.g. `plink
9968 static void ssh_special(void *handle, Telnet_Special code)
9970 Ssh ssh = (Ssh) handle;
9971 struct Packet *pktout;
9973 if (code == TS_EOF) {
9974 if (ssh->state != SSH_STATE_SESSION) {
9976 * Buffer the EOF in case we are pre-SESSION, so we can
9977 * send it as soon as we reach SESSION.
9980 ssh->eof_needed = TRUE;
9983 if (ssh->version == 1) {
9984 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9985 } else if (ssh->mainchan) {
9986 sshfwd_write_eof(ssh->mainchan);
9987 ssh->send_ok = 0; /* now stop trying to read from stdin */
9989 logevent("Sent EOF message");
9990 } else if (code == TS_PING || code == TS_NOP) {
9991 if (ssh->state == SSH_STATE_CLOSED
9992 || ssh->state == SSH_STATE_PREPACKET) return;
9993 if (ssh->version == 1) {
9994 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9995 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9997 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9998 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9999 ssh2_pkt_addstring_start(pktout);
10000 ssh2_pkt_send_noqueue(ssh, pktout);
10003 } else if (code == TS_REKEY) {
10004 if (!ssh->kex_in_progress && ssh->version == 2) {
10005 do_ssh2_transport(ssh, "at user request", -1, NULL);
10007 } else if (code == TS_BRK) {
10008 if (ssh->state == SSH_STATE_CLOSED
10009 || ssh->state == SSH_STATE_PREPACKET) return;
10010 if (ssh->version == 1) {
10011 logevent("Unable to send BREAK signal in SSH-1");
10012 } else if (ssh->mainchan) {
10013 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
10014 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
10015 ssh2_pkt_addstring(pktout, "break");
10016 ssh2_pkt_addbool(pktout, 0);
10017 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10018 ssh2_pkt_send(ssh, pktout);
10021 /* Is is a POSIX signal? */
10022 char *signame = NULL;
10023 if (code == TS_SIGABRT) signame = "ABRT";
10024 if (code == TS_SIGALRM) signame = "ALRM";
10025 if (code == TS_SIGFPE) signame = "FPE";
10026 if (code == TS_SIGHUP) signame = "HUP";
10027 if (code == TS_SIGILL) signame = "ILL";
10028 if (code == TS_SIGINT) signame = "INT";
10029 if (code == TS_SIGKILL) signame = "KILL";
10030 if (code == TS_SIGPIPE) signame = "PIPE";
10031 if (code == TS_SIGQUIT) signame = "QUIT";
10032 if (code == TS_SIGSEGV) signame = "SEGV";
10033 if (code == TS_SIGTERM) signame = "TERM";
10034 if (code == TS_SIGUSR1) signame = "USR1";
10035 if (code == TS_SIGUSR2) signame = "USR2";
10036 /* The SSH-2 protocol does in principle support arbitrary named
10037 * signals, including signame@domain, but we don't support those. */
10039 /* It's a signal. */
10040 if (ssh->version == 2 && ssh->mainchan) {
10041 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
10042 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
10043 ssh2_pkt_addstring(pktout, "signal");
10044 ssh2_pkt_addbool(pktout, 0);
10045 ssh2_pkt_addstring(pktout, signame);
10046 ssh2_pkt_send(ssh, pktout);
10047 logeventf(ssh, "Sent signal SIG%s", signame);
10050 /* Never heard of it. Do nothing */
10055 void *new_sock_channel(void *handle, Socket s)
10057 Ssh ssh = (Ssh) handle;
10058 struct ssh_channel *c;
10059 c = snew(struct ssh_channel);
10062 ssh2_channel_init(c);
10063 c->halfopen = TRUE;
10064 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10066 add234(ssh->channels, c);
10071 * This is called when stdout/stderr (the entity to which
10072 * from_backend sends data) manages to clear some backlog.
10074 static void ssh_unthrottle(void *handle, int bufsize)
10076 Ssh ssh = (Ssh) handle;
10079 if (ssh->version == 1) {
10080 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10081 ssh->v1_stdout_throttling = 0;
10082 ssh_throttle_conn(ssh, -1);
10085 if (ssh->mainchan) {
10086 ssh2_set_window(ssh->mainchan,
10087 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10088 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10089 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10092 buflimit = ssh->mainchan->v.v2.locmaxwin;
10093 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10094 ssh->mainchan->throttling_conn = 0;
10095 ssh_throttle_conn(ssh, -1);
10101 * Now process any SSH connection data that was stashed in our
10102 * queue while we were frozen.
10104 ssh_process_queued_incoming_data(ssh);
10107 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10109 struct ssh_channel *c = (struct ssh_channel *)channel;
10111 struct Packet *pktout;
10113 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
10115 if (ssh->version == 1) {
10116 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10117 PKT_INT, c->localid,
10120 /* PKT_STR, <org:orgport>, */
10123 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
10124 ssh2_pkt_addstring(pktout, "direct-tcpip");
10125 ssh2_pkt_adduint32(pktout, c->localid);
10126 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
10127 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
10128 ssh2_pkt_addstring(pktout, hostname);
10129 ssh2_pkt_adduint32(pktout, port);
10131 * We make up values for the originator data; partly it's
10132 * too much hassle to keep track, and partly I'm not
10133 * convinced the server should be told details like that
10134 * about my local network configuration.
10135 * The "originator IP address" is syntactically a numeric
10136 * IP address, and some servers (e.g., Tectia) get upset
10137 * if it doesn't match this syntax.
10139 ssh2_pkt_addstring(pktout, "0.0.0.0");
10140 ssh2_pkt_adduint32(pktout, 0);
10141 ssh2_pkt_send(ssh, pktout);
10145 static int ssh_connected(void *handle)
10147 Ssh ssh = (Ssh) handle;
10148 return ssh->s != NULL;
10151 static int ssh_sendok(void *handle)
10153 Ssh ssh = (Ssh) handle;
10154 return ssh->send_ok;
10157 static int ssh_ldisc(void *handle, int option)
10159 Ssh ssh = (Ssh) handle;
10160 if (option == LD_ECHO)
10161 return ssh->echoing;
10162 if (option == LD_EDIT)
10163 return ssh->editing;
10167 static void ssh_provide_ldisc(void *handle, void *ldisc)
10169 Ssh ssh = (Ssh) handle;
10170 ssh->ldisc = ldisc;
10173 static void ssh_provide_logctx(void *handle, void *logctx)
10175 Ssh ssh = (Ssh) handle;
10176 ssh->logctx = logctx;
10179 static int ssh_return_exitcode(void *handle)
10181 Ssh ssh = (Ssh) handle;
10182 if (ssh->s != NULL)
10185 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10189 * cfg_info for SSH is the currently running version of the
10190 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10192 static int ssh_cfg_info(void *handle)
10194 Ssh ssh = (Ssh) handle;
10195 return ssh->version;
10199 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10200 * that fails. This variable is the means by which scp.c can reach
10201 * into the SSH code and find out which one it got.
10203 extern int ssh_fallback_cmd(void *handle)
10205 Ssh ssh = (Ssh) handle;
10206 return ssh->fallback_cmd;
10209 Backend ssh_backend = {
10219 ssh_return_exitcode,
10223 ssh_provide_logctx,