Another tweak to EOF policy: invent an outgoing EOF on receipt of an
[u/mdw/putty] / ssh.c
1 /*
2 * SSH backend.
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <assert.h>
9 #include <limits.h>
10 #include <signal.h>
11
12 #include "putty.h"
13 #include "tree234.h"
14 #include "ssh.h"
15 #ifndef NO_GSSAPI
16 #include "sshgssc.h"
17 #include "sshgss.h"
18 #endif
19
20 #ifndef FALSE
21 #define FALSE 0
22 #endif
23 #ifndef TRUE
24 #define TRUE 1
25 #endif
26
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 */
68
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 */
75
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 */
79
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
125
126 /*
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
129 */
130 typedef enum {
131 SSH2_PKTCTX_NOKEX,
132 SSH2_PKTCTX_DHGROUP,
133 SSH2_PKTCTX_DHGEX,
134 SSH2_PKTCTX_RSAKEX
135 } Pkt_KCtx;
136 typedef enum {
137 SSH2_PKTCTX_NOAUTH,
138 SSH2_PKTCTX_PUBLICKEY,
139 SSH2_PKTCTX_PASSWORD,
140 SSH2_PKTCTX_GSSAPI,
141 SSH2_PKTCTX_KBDINTER
142 } Pkt_ACtx;
143
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 */
159
160 static const char *const ssh2_disconnect_reasons[] = {
161 NULL,
162 "host not allowed to connect",
163 "protocol error",
164 "key exchange failed",
165 "host authentication failed",
166 "MAC error",
167 "compression error",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
171 "connection lost",
172 "by application",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
176 "illegal user name",
177 };
178
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 */
183
184 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
185
186 /*
187 * Various remote-bug flags.
188 */
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
200 /*
201 * Codes for terminal modes.
202 * Most of these are the same in SSH-1 and SSH-2.
203 * This list is derived from RFC 4254 and
204 * SSH-1 RFC-1.2.31.
205 */
206 static const struct {
207 const char* const mode;
208 int opcode;
209 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
210 } ssh_ttymodes[] = {
211 /* "V" prefix discarded for special characters relative to SSH specs */
212 { "INTR", 1, TTY_OP_CHAR },
213 { "QUIT", 2, TTY_OP_CHAR },
214 { "ERASE", 3, TTY_OP_CHAR },
215 { "KILL", 4, TTY_OP_CHAR },
216 { "EOF", 5, TTY_OP_CHAR },
217 { "EOL", 6, TTY_OP_CHAR },
218 { "EOL2", 7, TTY_OP_CHAR },
219 { "START", 8, TTY_OP_CHAR },
220 { "STOP", 9, TTY_OP_CHAR },
221 { "SUSP", 10, TTY_OP_CHAR },
222 { "DSUSP", 11, TTY_OP_CHAR },
223 { "REPRINT", 12, TTY_OP_CHAR },
224 { "WERASE", 13, TTY_OP_CHAR },
225 { "LNEXT", 14, TTY_OP_CHAR },
226 { "FLUSH", 15, TTY_OP_CHAR },
227 { "SWTCH", 16, TTY_OP_CHAR },
228 { "STATUS", 17, TTY_OP_CHAR },
229 { "DISCARD", 18, TTY_OP_CHAR },
230 { "IGNPAR", 30, TTY_OP_BOOL },
231 { "PARMRK", 31, TTY_OP_BOOL },
232 { "INPCK", 32, TTY_OP_BOOL },
233 { "ISTRIP", 33, TTY_OP_BOOL },
234 { "INLCR", 34, TTY_OP_BOOL },
235 { "IGNCR", 35, TTY_OP_BOOL },
236 { "ICRNL", 36, TTY_OP_BOOL },
237 { "IUCLC", 37, TTY_OP_BOOL },
238 { "IXON", 38, TTY_OP_BOOL },
239 { "IXANY", 39, TTY_OP_BOOL },
240 { "IXOFF", 40, TTY_OP_BOOL },
241 { "IMAXBEL", 41, TTY_OP_BOOL },
242 { "ISIG", 50, TTY_OP_BOOL },
243 { "ICANON", 51, TTY_OP_BOOL },
244 { "XCASE", 52, TTY_OP_BOOL },
245 { "ECHO", 53, TTY_OP_BOOL },
246 { "ECHOE", 54, TTY_OP_BOOL },
247 { "ECHOK", 55, TTY_OP_BOOL },
248 { "ECHONL", 56, TTY_OP_BOOL },
249 { "NOFLSH", 57, TTY_OP_BOOL },
250 { "TOSTOP", 58, TTY_OP_BOOL },
251 { "IEXTEN", 59, TTY_OP_BOOL },
252 { "ECHOCTL", 60, TTY_OP_BOOL },
253 { "ECHOKE", 61, TTY_OP_BOOL },
254 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
255 { "OPOST", 70, TTY_OP_BOOL },
256 { "OLCUC", 71, TTY_OP_BOOL },
257 { "ONLCR", 72, TTY_OP_BOOL },
258 { "OCRNL", 73, TTY_OP_BOOL },
259 { "ONOCR", 74, TTY_OP_BOOL },
260 { "ONLRET", 75, TTY_OP_BOOL },
261 { "CS7", 90, TTY_OP_BOOL },
262 { "CS8", 91, TTY_OP_BOOL },
263 { "PARENB", 92, TTY_OP_BOOL },
264 { "PARODD", 93, TTY_OP_BOOL }
265 };
266
267 /* Miscellaneous other tty-related constants. */
268 #define SSH_TTY_OP_END 0
269 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
270 #define SSH1_TTY_OP_ISPEED 192
271 #define SSH1_TTY_OP_OSPEED 193
272 #define SSH2_TTY_OP_ISPEED 128
273 #define SSH2_TTY_OP_OSPEED 129
274
275 /* Helper functions for parsing tty-related config. */
276 static unsigned int ssh_tty_parse_specchar(char *s)
277 {
278 unsigned int ret;
279 if (*s) {
280 char *next = NULL;
281 ret = ctrlparse(s, &next);
282 if (!next) ret = s[0];
283 } else {
284 ret = 255; /* special value meaning "don't set" */
285 }
286 return ret;
287 }
288 static unsigned int ssh_tty_parse_boolean(char *s)
289 {
290 if (stricmp(s, "yes") == 0 ||
291 stricmp(s, "on") == 0 ||
292 stricmp(s, "true") == 0 ||
293 stricmp(s, "+") == 0)
294 return 1; /* true */
295 else if (stricmp(s, "no") == 0 ||
296 stricmp(s, "off") == 0 ||
297 stricmp(s, "false") == 0 ||
298 stricmp(s, "-") == 0)
299 return 0; /* false */
300 else
301 return (atoi(s) != 0);
302 }
303
304 #define translate(x) if (type == x) return #x
305 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
306 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
307 static char *ssh1_pkt_type(int type)
308 {
309 translate(SSH1_MSG_DISCONNECT);
310 translate(SSH1_SMSG_PUBLIC_KEY);
311 translate(SSH1_CMSG_SESSION_KEY);
312 translate(SSH1_CMSG_USER);
313 translate(SSH1_CMSG_AUTH_RSA);
314 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
315 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
316 translate(SSH1_CMSG_AUTH_PASSWORD);
317 translate(SSH1_CMSG_REQUEST_PTY);
318 translate(SSH1_CMSG_WINDOW_SIZE);
319 translate(SSH1_CMSG_EXEC_SHELL);
320 translate(SSH1_CMSG_EXEC_CMD);
321 translate(SSH1_SMSG_SUCCESS);
322 translate(SSH1_SMSG_FAILURE);
323 translate(SSH1_CMSG_STDIN_DATA);
324 translate(SSH1_SMSG_STDOUT_DATA);
325 translate(SSH1_SMSG_STDERR_DATA);
326 translate(SSH1_CMSG_EOF);
327 translate(SSH1_SMSG_EXIT_STATUS);
328 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
329 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
330 translate(SSH1_MSG_CHANNEL_DATA);
331 translate(SSH1_MSG_CHANNEL_CLOSE);
332 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
333 translate(SSH1_SMSG_X11_OPEN);
334 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
335 translate(SSH1_MSG_PORT_OPEN);
336 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
337 translate(SSH1_SMSG_AGENT_OPEN);
338 translate(SSH1_MSG_IGNORE);
339 translate(SSH1_CMSG_EXIT_CONFIRMATION);
340 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
341 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
342 translate(SSH1_MSG_DEBUG);
343 translate(SSH1_CMSG_REQUEST_COMPRESSION);
344 translate(SSH1_CMSG_AUTH_TIS);
345 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
346 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
347 translate(SSH1_CMSG_AUTH_CCARD);
348 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
349 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
350 return "unknown";
351 }
352 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
353 {
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
360 translate(SSH2_MSG_DISCONNECT);
361 translate(SSH2_MSG_IGNORE);
362 translate(SSH2_MSG_UNIMPLEMENTED);
363 translate(SSH2_MSG_DEBUG);
364 translate(SSH2_MSG_SERVICE_REQUEST);
365 translate(SSH2_MSG_SERVICE_ACCEPT);
366 translate(SSH2_MSG_KEXINIT);
367 translate(SSH2_MSG_NEWKEYS);
368 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
369 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
371 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
375 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
377 translate(SSH2_MSG_USERAUTH_REQUEST);
378 translate(SSH2_MSG_USERAUTH_FAILURE);
379 translate(SSH2_MSG_USERAUTH_SUCCESS);
380 translate(SSH2_MSG_USERAUTH_BANNER);
381 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
382 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
383 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
384 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
385 translate(SSH2_MSG_GLOBAL_REQUEST);
386 translate(SSH2_MSG_REQUEST_SUCCESS);
387 translate(SSH2_MSG_REQUEST_FAILURE);
388 translate(SSH2_MSG_CHANNEL_OPEN);
389 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
390 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
391 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
392 translate(SSH2_MSG_CHANNEL_DATA);
393 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
394 translate(SSH2_MSG_CHANNEL_EOF);
395 translate(SSH2_MSG_CHANNEL_CLOSE);
396 translate(SSH2_MSG_CHANNEL_REQUEST);
397 translate(SSH2_MSG_CHANNEL_SUCCESS);
398 translate(SSH2_MSG_CHANNEL_FAILURE);
399 return "unknown";
400 }
401 #undef translate
402 #undef translatec
403
404 /* Enumeration values for fields in SSH-1 packets */
405 enum {
406 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
407 /* These values are for communicating relevant semantics of
408 * fields to the packet logging code. */
409 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
410 };
411
412 /*
413 * Coroutine mechanics for the sillier bits of the code. If these
414 * macros look impenetrable to you, you might find it helpful to
415 * read
416 *
417 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
418 *
419 * which explains the theory behind these macros.
420 *
421 * In particular, if you are getting `case expression not constant'
422 * errors when building with MS Visual Studio, this is because MS's
423 * Edit and Continue debugging feature causes their compiler to
424 * violate ANSI C. To disable Edit and Continue debugging:
425 *
426 * - right-click ssh.c in the FileView
427 * - click Settings
428 * - select the C/C++ tab and the General category
429 * - under `Debug info:', select anything _other_ than `Program
430 * Database for Edit and Continue'.
431 */
432 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
433 #define crState(t) \
434 struct t *s; \
435 if (!ssh->t) ssh->t = snew(struct t); \
436 s = ssh->t;
437 #define crFinish(z) } *crLine = 0; return (z); }
438 #define crFinishV } *crLine = 0; return; }
439 #define crReturn(z) \
440 do {\
441 *crLine =__LINE__; return (z); case __LINE__:;\
442 } while (0)
443 #define crReturnV \
444 do {\
445 *crLine=__LINE__; return; case __LINE__:;\
446 } while (0)
447 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
448 #define crStopV do{ *crLine = 0; return; }while(0)
449 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
450 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
451
452 typedef struct ssh_tag *Ssh;
453 struct Packet;
454
455 static struct Packet *ssh1_pkt_init(int pkt_type);
456 static struct Packet *ssh2_pkt_init(int pkt_type);
457 static void ssh_pkt_ensure(struct Packet *, int length);
458 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
459 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
460 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
461 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
462 static void ssh_pkt_addstring_start(struct Packet *);
463 static void ssh_pkt_addstring_str(struct Packet *, char *data);
464 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
465 static void ssh_pkt_addstring(struct Packet *, char *data);
466 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
467 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
468 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
469 static int ssh2_pkt_construct(Ssh, struct Packet *);
470 static void ssh2_pkt_send(Ssh, struct Packet *);
471 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
472 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
473 struct Packet *pktin);
474 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
475 struct Packet *pktin);
476 static void ssh2_channel_check_close(struct ssh_channel *c);
477 static void ssh_channel_destroy(struct ssh_channel *c);
478
479 /*
480 * Buffer management constants. There are several of these for
481 * various different purposes:
482 *
483 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
484 * on a local data stream before we throttle the whole SSH
485 * connection (in SSH-1 only). Throttling the whole connection is
486 * pretty drastic so we set this high in the hope it won't
487 * happen very often.
488 *
489 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
490 * on the SSH connection itself before we defensively throttle
491 * _all_ local data streams. This is pretty drastic too (though
492 * thankfully unlikely in SSH-2 since the window mechanism should
493 * ensure that the server never has any need to throttle its end
494 * of the connection), so we set this high as well.
495 *
496 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
497 * channels.
498 *
499 * - OUR_V2_BIGWIN is the window size we advertise for the only
500 * channel in a simple connection. It must be <= INT_MAX.
501 *
502 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
503 * to the remote side. This actually has nothing to do with the
504 * size of the _packet_, but is instead a limit on the amount
505 * of data we're willing to receive in a single SSH2 channel
506 * data message.
507 *
508 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
509 * _packet_ we're prepared to cope with. It must be a multiple
510 * of the cipher block size, and must be at least 35000.
511 */
512
513 #define SSH1_BUFFER_LIMIT 32768
514 #define SSH_MAX_BACKLOG 32768
515 #define OUR_V2_WINSIZE 16384
516 #define OUR_V2_BIGWIN 0x7fffffff
517 #define OUR_V2_MAXPKT 0x4000UL
518 #define OUR_V2_PACKETLIMIT 0x9000UL
519
520 /* Maximum length of passwords/passphrases (arbitrary) */
521 #define SSH_MAX_PASSWORD_LEN 100
522
523 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
524
525 const static struct ssh_mac *macs[] = {
526 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
527 };
528 const static struct ssh_mac *buggymacs[] = {
529 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
530 };
531
532 static void *ssh_comp_none_init(void)
533 {
534 return NULL;
535 }
536 static void ssh_comp_none_cleanup(void *handle)
537 {
538 }
539 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
540 unsigned char **outblock, int *outlen)
541 {
542 return 0;
543 }
544 static int ssh_comp_none_disable(void *handle)
545 {
546 return 0;
547 }
548 const static struct ssh_compress ssh_comp_none = {
549 "none", NULL,
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
553 };
554 extern const struct ssh_compress ssh_zlib;
555 const static struct ssh_compress *compressions[] = {
556 &ssh_zlib, &ssh_comp_none
557 };
558
559 enum { /* channel types */
560 CHAN_MAINSESSION,
561 CHAN_X11,
562 CHAN_AGENT,
563 CHAN_SOCKDATA,
564 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
565 };
566
567 /*
568 * little structure to keep track of outstanding WINDOW_ADJUSTs
569 */
570 struct winadj {
571 struct winadj *next;
572 unsigned size;
573 };
574
575 /*
576 * 2-3-4 tree storing channels.
577 */
578 struct ssh_channel {
579 Ssh ssh; /* pointer back to main context */
580 unsigned remoteid, localid;
581 int type;
582 /* True if we opened this channel but server hasn't confirmed. */
583 int halfopen;
584 /*
585 * In SSH-1, this value contains four bits:
586 *
587 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
588 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
589 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
590 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
591 *
592 * A channel is completely finished with when all four bits are set.
593 *
594 * In SSH-2, the four bits mean:
595 *
596 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
597 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
598 * 4 We have received SSH2_MSG_CHANNEL_EOF.
599 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
600 *
601 * A channel is completely finished with when we have both sent
602 * and received CLOSE.
603 *
604 * The symbolic constants below use the SSH-2 terminology, which
605 * is a bit confusing in SSH-1, but we have to use _something_.
606 */
607 #define CLOSES_SENT_EOF 1
608 #define CLOSES_SENT_CLOSE 2
609 #define CLOSES_RCVD_EOF 4
610 #define CLOSES_RCVD_CLOSE 8
611 int closes;
612
613 /*
614 * This flag indicates that an EOF is pending on the outgoing side
615 * of the channel: that is, wherever we're getting the data for
616 * this channel has sent us some data followed by EOF. We can't
617 * actually send the EOF until we've finished sending the data, so
618 * we set this flag instead to remind us to do so once our buffer
619 * is clear.
620 */
621 int pending_eof;
622
623 /*
624 * True if this channel is causing the underlying connection to be
625 * throttled.
626 */
627 int throttling_conn;
628 union {
629 struct ssh2_data_channel {
630 bufchain outbuffer;
631 unsigned remwindow, remmaxpkt;
632 /* locwindow is signed so we can cope with excess data. */
633 int locwindow, locmaxwin;
634 /*
635 * remlocwin is the amount of local window that we think
636 * the remote end had available to it after it sent the
637 * last data packet or window adjust ack.
638 */
639 int remlocwin;
640 /*
641 * These store the list of window adjusts that haven't
642 * been acked.
643 */
644 struct winadj *winadj_head, *winadj_tail;
645 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
646 } v2;
647 } v;
648 union {
649 struct ssh_agent_channel {
650 unsigned char *message;
651 unsigned char msglen[4];
652 unsigned lensofar, totallen;
653 } a;
654 struct ssh_x11_channel {
655 Socket s;
656 } x11;
657 struct ssh_pfd_channel {
658 Socket s;
659 } pfd;
660 } u;
661 };
662
663 /*
664 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
665 * use this structure in different ways, reflecting SSH-2's
666 * altogether saner approach to port forwarding.
667 *
668 * In SSH-1, you arrange a remote forwarding by sending the server
669 * the remote port number, and the local destination host:port.
670 * When a connection comes in, the server sends you back that
671 * host:port pair, and you connect to it. This is a ready-made
672 * security hole if you're not on the ball: a malicious server
673 * could send you back _any_ host:port pair, so if you trustingly
674 * connect to the address it gives you then you've just opened the
675 * entire inside of your corporate network just by connecting
676 * through it to a dodgy SSH server. Hence, we must store a list of
677 * host:port pairs we _are_ trying to forward to, and reject a
678 * connection request from the server if it's not in the list.
679 *
680 * In SSH-2, each side of the connection minds its own business and
681 * doesn't send unnecessary information to the other. You arrange a
682 * remote forwarding by sending the server just the remote port
683 * number. When a connection comes in, the server tells you which
684 * of its ports was connected to; and _you_ have to remember what
685 * local host:port pair went with that port number.
686 *
687 * Hence, in SSH-1 this structure is indexed by destination
688 * host:port pair, whereas in SSH-2 it is indexed by source port.
689 */
690 struct ssh_portfwd; /* forward declaration */
691
692 struct ssh_rportfwd {
693 unsigned sport, dport;
694 char dhost[256];
695 char *sportdesc;
696 struct ssh_portfwd *pfrec;
697 };
698 #define free_rportfwd(pf) ( \
699 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
700
701 /*
702 * Separately to the rportfwd tree (which is for looking up port
703 * open requests from the server), a tree of _these_ structures is
704 * used to keep track of all the currently open port forwardings,
705 * so that we can reconfigure in mid-session if the user requests
706 * it.
707 */
708 struct ssh_portfwd {
709 enum { DESTROY, KEEP, CREATE } status;
710 int type;
711 unsigned sport, dport;
712 char *saddr, *daddr;
713 char *sserv, *dserv;
714 struct ssh_rportfwd *remote;
715 int addressfamily;
716 void *local;
717 };
718 #define free_portfwd(pf) ( \
719 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
720 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
721
722 struct Packet {
723 long length; /* length of `data' actually used */
724 long forcepad; /* SSH-2: force padding to at least this length */
725 int type; /* only used for incoming packets */
726 unsigned long sequence; /* SSH-2 incoming sequence number */
727 unsigned char *data; /* allocated storage */
728 unsigned char *body; /* offset of payload within `data' */
729 long savedpos; /* temporary index into `data' (for strings) */
730 long maxlen; /* amount of storage allocated for `data' */
731 long encrypted_len; /* for SSH-2 total-size counting */
732
733 /*
734 * State associated with packet logging
735 */
736 int logmode;
737 int nblanks;
738 struct logblank_t *blanks;
739 };
740
741 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
742 struct Packet *pktin);
743 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
744 struct Packet *pktin);
745 static void ssh1_protocol_setup(Ssh ssh);
746 static void ssh2_protocol_setup(Ssh ssh);
747 static void ssh_size(void *handle, int width, int height);
748 static void ssh_special(void *handle, Telnet_Special);
749 static int ssh2_try_send(struct ssh_channel *c);
750 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
751 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
752 static void ssh2_set_window(struct ssh_channel *c, int newwin);
753 static int ssh_sendbuffer(void *handle);
754 static int ssh_do_close(Ssh ssh, int notify_exit);
755 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
756 static int ssh2_pkt_getbool(struct Packet *pkt);
757 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
758 static void ssh2_timer(void *ctx, long now);
759 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
760 struct Packet *pktin);
761
762 struct rdpkt1_state_tag {
763 long len, pad, biglen, to_read;
764 unsigned long realcrc, gotcrc;
765 unsigned char *p;
766 int i;
767 int chunk;
768 struct Packet *pktin;
769 };
770
771 struct rdpkt2_state_tag {
772 long len, pad, payload, packetlen, maclen;
773 int i;
774 int cipherblk;
775 unsigned long incoming_sequence;
776 struct Packet *pktin;
777 };
778
779 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
780 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
781
782 struct queued_handler;
783 struct queued_handler {
784 int msg1, msg2;
785 chandler_fn_t handler;
786 void *ctx;
787 struct queued_handler *next;
788 };
789
790 struct ssh_tag {
791 const struct plug_function_table *fn;
792 /* the above field _must_ be first in the structure */
793
794 char *v_c, *v_s;
795 void *exhash;
796
797 Socket s;
798
799 void *ldisc;
800 void *logctx;
801
802 unsigned char session_key[32];
803 int v1_compressing;
804 int v1_remote_protoflags;
805 int v1_local_protoflags;
806 int agentfwd_enabled;
807 int X11_fwd_enabled;
808 int remote_bugs;
809 const struct ssh_cipher *cipher;
810 void *v1_cipher_ctx;
811 void *crcda_ctx;
812 const struct ssh2_cipher *cscipher, *sccipher;
813 void *cs_cipher_ctx, *sc_cipher_ctx;
814 const struct ssh_mac *csmac, *scmac;
815 void *cs_mac_ctx, *sc_mac_ctx;
816 const struct ssh_compress *cscomp, *sccomp;
817 void *cs_comp_ctx, *sc_comp_ctx;
818 const struct ssh_kex *kex;
819 const struct ssh_signkey *hostkey;
820 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
821 int v2_session_id_len;
822 void *kex_ctx;
823
824 char *savedhost;
825 int savedport;
826 int send_ok;
827 int echoing, editing;
828
829 void *frontend;
830
831 int ospeed, ispeed; /* temporaries */
832 int term_width, term_height;
833
834 tree234 *channels; /* indexed by local id */
835 struct ssh_channel *mainchan; /* primary session channel */
836 int ncmode; /* is primary channel direct-tcpip? */
837 int exitcode;
838 int close_expected;
839 int clean_exit;
840
841 tree234 *rportfwds, *portfwds;
842
843 enum {
844 SSH_STATE_PREPACKET,
845 SSH_STATE_BEFORE_SIZE,
846 SSH_STATE_INTERMED,
847 SSH_STATE_SESSION,
848 SSH_STATE_CLOSED
849 } state;
850
851 int size_needed, eof_needed;
852 int sent_console_eof;
853 int got_pty; /* affects EOF behaviour on main channel */
854
855 struct Packet **queue;
856 int queuelen, queuesize;
857 int queueing;
858 unsigned char *deferred_send_data;
859 int deferred_len, deferred_size;
860
861 /*
862 * Gross hack: pscp will try to start SFTP but fall back to
863 * scp1 if that fails. This variable is the means by which
864 * scp.c can reach into the SSH code and find out which one it
865 * got.
866 */
867 int fallback_cmd;
868
869 bufchain banner; /* accumulates banners during do_ssh2_authconn */
870
871 Pkt_KCtx pkt_kctx;
872 Pkt_ACtx pkt_actx;
873
874 struct X11Display *x11disp;
875
876 int version;
877 int conn_throttle_count;
878 int overall_bufsize;
879 int throttled_all;
880 int v1_stdout_throttling;
881 unsigned long v2_outgoing_sequence;
882
883 int ssh1_rdpkt_crstate;
884 int ssh2_rdpkt_crstate;
885 int do_ssh_init_crstate;
886 int ssh_gotdata_crstate;
887 int do_ssh1_login_crstate;
888 int do_ssh1_connection_crstate;
889 int do_ssh2_transport_crstate;
890 int do_ssh2_authconn_crstate;
891
892 void *do_ssh_init_state;
893 void *do_ssh1_login_state;
894 void *do_ssh2_transport_state;
895 void *do_ssh2_authconn_state;
896
897 struct rdpkt1_state_tag rdpkt1_state;
898 struct rdpkt2_state_tag rdpkt2_state;
899
900 /* SSH-1 and SSH-2 use this for different things, but both use it */
901 int protocol_initial_phase_done;
902
903 void (*protocol) (Ssh ssh, void *vin, int inlen,
904 struct Packet *pkt);
905 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
906
907 /*
908 * We maintain our own copy of a Conf structure here. That way,
909 * when we're passed a new one for reconfiguration, we can check
910 * the differences and potentially reconfigure port forwardings
911 * etc in mid-session.
912 */
913 Conf *conf;
914
915 /*
916 * Values cached out of conf so as to avoid the tree234 lookup
917 * cost every time they're used.
918 */
919 int logomitdata;
920
921 /*
922 * Dynamically allocated username string created during SSH
923 * login. Stored in here rather than in the coroutine state so
924 * that it'll be reliably freed if we shut down the SSH session
925 * at some unexpected moment.
926 */
927 char *username;
928
929 /*
930 * Used to transfer data back from async callbacks.
931 */
932 void *agent_response;
933 int agent_response_len;
934 int user_response;
935
936 /*
937 * The SSH connection can be set as `frozen', meaning we are
938 * not currently accepting incoming data from the network. This
939 * is slightly more serious than setting the _socket_ as
940 * frozen, because we may already have had data passed to us
941 * from the network which we need to delay processing until
942 * after the freeze is lifted, so we also need a bufchain to
943 * store that data.
944 */
945 int frozen;
946 bufchain queued_incoming_data;
947
948 /*
949 * Dispatch table for packet types that we may have to deal
950 * with at any time.
951 */
952 handler_fn_t packet_dispatch[256];
953
954 /*
955 * Queues of one-off handler functions for success/failure
956 * indications from a request.
957 */
958 struct queued_handler *qhead, *qtail;
959
960 /*
961 * This module deals with sending keepalives.
962 */
963 Pinger pinger;
964
965 /*
966 * Track incoming and outgoing data sizes and time, for
967 * size-based rekeys.
968 */
969 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
970 unsigned long max_data_size;
971 int kex_in_progress;
972 long next_rekey, last_rekey;
973 char *deferred_rekey_reason; /* points to STATIC string; don't free */
974
975 /*
976 * Fully qualified host name, which we need if doing GSSAPI.
977 */
978 char *fullhostname;
979
980 #ifndef NO_GSSAPI
981 /*
982 * GSSAPI libraries for this session.
983 */
984 struct ssh_gss_liblist *gsslibs;
985 #endif
986 };
987
988 #define logevent(s) logevent(ssh->frontend, s)
989
990 /* logevent, only printf-formatted. */
991 static void logeventf(Ssh ssh, const char *fmt, ...)
992 {
993 va_list ap;
994 char *buf;
995
996 va_start(ap, fmt);
997 buf = dupvprintf(fmt, ap);
998 va_end(ap);
999 logevent(buf);
1000 sfree(buf);
1001 }
1002
1003 #define bombout(msg) \
1004 do { \
1005 char *text = dupprintf msg; \
1006 ssh_do_close(ssh, FALSE); \
1007 logevent(text); \
1008 connection_fatal(ssh->frontend, "%s", text); \
1009 sfree(text); \
1010 } while (0)
1011
1012 /* Functions to leave bits out of the SSH packet log file. */
1013
1014 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
1015 {
1016 if (conf_get_int(ssh->conf, CONF_logomitpass))
1017 pkt->logmode = blanktype;
1018 }
1019
1020 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
1021 {
1022 if (ssh->logomitdata)
1023 pkt->logmode = blanktype;
1024 }
1025
1026 static void end_log_omission(Ssh ssh, struct Packet *pkt)
1027 {
1028 pkt->logmode = PKTLOG_EMIT;
1029 }
1030
1031 /* Helper function for common bits of parsing ttymodes. */
1032 static void parse_ttymodes(Ssh ssh,
1033 void (*do_mode)(void *data, char *mode, char *val),
1034 void *data)
1035 {
1036 char *key, *val;
1037
1038 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1039 val != NULL;
1040 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1041 /*
1042 * val[0] is either 'V', indicating that an explicit value
1043 * follows it, or 'A' indicating that we should pass the
1044 * value through from the local environment via get_ttymode.
1045 */
1046 if (val[0] == 'A')
1047 val = get_ttymode(ssh->frontend, key);
1048 else
1049 val++; /* skip the 'V' */
1050 if (val)
1051 do_mode(data, key, val);
1052 }
1053 }
1054
1055 static int ssh_channelcmp(void *av, void *bv)
1056 {
1057 struct ssh_channel *a = (struct ssh_channel *) av;
1058 struct ssh_channel *b = (struct ssh_channel *) bv;
1059 if (a->localid < b->localid)
1060 return -1;
1061 if (a->localid > b->localid)
1062 return +1;
1063 return 0;
1064 }
1065 static int ssh_channelfind(void *av, void *bv)
1066 {
1067 unsigned *a = (unsigned *) av;
1068 struct ssh_channel *b = (struct ssh_channel *) bv;
1069 if (*a < b->localid)
1070 return -1;
1071 if (*a > b->localid)
1072 return +1;
1073 return 0;
1074 }
1075
1076 static int ssh_rportcmp_ssh1(void *av, void *bv)
1077 {
1078 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1079 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1080 int i;
1081 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1082 return i < 0 ? -1 : +1;
1083 if (a->dport > b->dport)
1084 return +1;
1085 if (a->dport < b->dport)
1086 return -1;
1087 return 0;
1088 }
1089
1090 static int ssh_rportcmp_ssh2(void *av, void *bv)
1091 {
1092 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1093 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1094
1095 if (a->sport > b->sport)
1096 return +1;
1097 if (a->sport < b->sport)
1098 return -1;
1099 return 0;
1100 }
1101
1102 /*
1103 * Special form of strcmp which can cope with NULL inputs. NULL is
1104 * defined to sort before even the empty string.
1105 */
1106 static int nullstrcmp(const char *a, const char *b)
1107 {
1108 if (a == NULL && b == NULL)
1109 return 0;
1110 if (a == NULL)
1111 return -1;
1112 if (b == NULL)
1113 return +1;
1114 return strcmp(a, b);
1115 }
1116
1117 static int ssh_portcmp(void *av, void *bv)
1118 {
1119 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1120 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1121 int i;
1122 if (a->type > b->type)
1123 return +1;
1124 if (a->type < b->type)
1125 return -1;
1126 if (a->addressfamily > b->addressfamily)
1127 return +1;
1128 if (a->addressfamily < b->addressfamily)
1129 return -1;
1130 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1131 return i < 0 ? -1 : +1;
1132 if (a->sport > b->sport)
1133 return +1;
1134 if (a->sport < b->sport)
1135 return -1;
1136 if (a->type != 'D') {
1137 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1138 return i < 0 ? -1 : +1;
1139 if (a->dport > b->dport)
1140 return +1;
1141 if (a->dport < b->dport)
1142 return -1;
1143 }
1144 return 0;
1145 }
1146
1147 static int alloc_channel_id(Ssh ssh)
1148 {
1149 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1150 unsigned low, high, mid;
1151 int tsize;
1152 struct ssh_channel *c;
1153
1154 /*
1155 * First-fit allocation of channel numbers: always pick the
1156 * lowest unused one. To do this, binary-search using the
1157 * counted B-tree to find the largest channel ID which is in a
1158 * contiguous sequence from the beginning. (Precisely
1159 * everything in that sequence must have ID equal to its tree
1160 * index plus CHANNEL_NUMBER_OFFSET.)
1161 */
1162 tsize = count234(ssh->channels);
1163
1164 low = -1;
1165 high = tsize;
1166 while (high - low > 1) {
1167 mid = (high + low) / 2;
1168 c = index234(ssh->channels, mid);
1169 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1170 low = mid; /* this one is fine */
1171 else
1172 high = mid; /* this one is past it */
1173 }
1174 /*
1175 * Now low points to either -1, or the tree index of the
1176 * largest ID in the initial sequence.
1177 */
1178 {
1179 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1180 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1181 }
1182 return low + 1 + CHANNEL_NUMBER_OFFSET;
1183 }
1184
1185 static void c_write_stderr(int trusted, const char *buf, int len)
1186 {
1187 int i;
1188 for (i = 0; i < len; i++)
1189 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1190 fputc(buf[i], stderr);
1191 }
1192
1193 static void c_write(Ssh ssh, const char *buf, int len)
1194 {
1195 if (flags & FLAG_STDERR)
1196 c_write_stderr(1, buf, len);
1197 else
1198 from_backend(ssh->frontend, 1, buf, len);
1199 }
1200
1201 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1202 {
1203 if (flags & FLAG_STDERR)
1204 c_write_stderr(0, buf, len);
1205 else
1206 from_backend_untrusted(ssh->frontend, buf, len);
1207 }
1208
1209 static void c_write_str(Ssh ssh, const char *buf)
1210 {
1211 c_write(ssh, buf, strlen(buf));
1212 }
1213
1214 static void ssh_free_packet(struct Packet *pkt)
1215 {
1216 sfree(pkt->data);
1217 sfree(pkt);
1218 }
1219 static struct Packet *ssh_new_packet(void)
1220 {
1221 struct Packet *pkt = snew(struct Packet);
1222
1223 pkt->body = pkt->data = NULL;
1224 pkt->maxlen = 0;
1225 pkt->logmode = PKTLOG_EMIT;
1226 pkt->nblanks = 0;
1227 pkt->blanks = NULL;
1228
1229 return pkt;
1230 }
1231
1232 /*
1233 * Collect incoming data in the incoming packet buffer.
1234 * Decipher and verify the packet when it is completely read.
1235 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1236 * Update the *data and *datalen variables.
1237 * Return a Packet structure when a packet is completed.
1238 */
1239 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1240 {
1241 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1242
1243 crBegin(ssh->ssh1_rdpkt_crstate);
1244
1245 st->pktin = ssh_new_packet();
1246
1247 st->pktin->type = 0;
1248 st->pktin->length = 0;
1249
1250 for (st->i = st->len = 0; st->i < 4; st->i++) {
1251 while ((*datalen) == 0)
1252 crReturn(NULL);
1253 st->len = (st->len << 8) + **data;
1254 (*data)++, (*datalen)--;
1255 }
1256
1257 st->pad = 8 - (st->len % 8);
1258 st->biglen = st->len + st->pad;
1259 st->pktin->length = st->len - 5;
1260
1261 if (st->biglen < 0) {
1262 bombout(("Extremely large packet length from server suggests"
1263 " data stream corruption"));
1264 ssh_free_packet(st->pktin);
1265 crStop(NULL);
1266 }
1267
1268 st->pktin->maxlen = st->biglen;
1269 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1270
1271 st->to_read = st->biglen;
1272 st->p = st->pktin->data;
1273 while (st->to_read > 0) {
1274 st->chunk = st->to_read;
1275 while ((*datalen) == 0)
1276 crReturn(NULL);
1277 if (st->chunk > (*datalen))
1278 st->chunk = (*datalen);
1279 memcpy(st->p, *data, st->chunk);
1280 *data += st->chunk;
1281 *datalen -= st->chunk;
1282 st->p += st->chunk;
1283 st->to_read -= st->chunk;
1284 }
1285
1286 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1287 st->biglen, NULL)) {
1288 bombout(("Network attack (CRC compensation) detected!"));
1289 ssh_free_packet(st->pktin);
1290 crStop(NULL);
1291 }
1292
1293 if (ssh->cipher)
1294 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1295
1296 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1297 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1298 if (st->gotcrc != st->realcrc) {
1299 bombout(("Incorrect CRC received on packet"));
1300 ssh_free_packet(st->pktin);
1301 crStop(NULL);
1302 }
1303
1304 st->pktin->body = st->pktin->data + st->pad + 1;
1305 st->pktin->savedpos = 0;
1306
1307 if (ssh->v1_compressing) {
1308 unsigned char *decompblk;
1309 int decomplen;
1310 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1311 st->pktin->body - 1, st->pktin->length + 1,
1312 &decompblk, &decomplen)) {
1313 bombout(("Zlib decompression encountered invalid data"));
1314 ssh_free_packet(st->pktin);
1315 crStop(NULL);
1316 }
1317
1318 if (st->pktin->maxlen < st->pad + decomplen) {
1319 st->pktin->maxlen = st->pad + decomplen;
1320 st->pktin->data = sresize(st->pktin->data,
1321 st->pktin->maxlen + APIEXTRA,
1322 unsigned char);
1323 st->pktin->body = st->pktin->data + st->pad + 1;
1324 }
1325
1326 memcpy(st->pktin->body - 1, decompblk, decomplen);
1327 sfree(decompblk);
1328 st->pktin->length = decomplen - 1;
1329 }
1330
1331 st->pktin->type = st->pktin->body[-1];
1332
1333 /*
1334 * Log incoming packet, possibly omitting sensitive fields.
1335 */
1336 if (ssh->logctx) {
1337 int nblanks = 0;
1338 struct logblank_t blank;
1339 if (ssh->logomitdata) {
1340 int do_blank = FALSE, blank_prefix = 0;
1341 /* "Session data" packets - omit the data field */
1342 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1343 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1344 do_blank = TRUE; blank_prefix = 4;
1345 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1346 do_blank = TRUE; blank_prefix = 8;
1347 }
1348 if (do_blank) {
1349 blank.offset = blank_prefix;
1350 blank.len = st->pktin->length;
1351 blank.type = PKTLOG_OMIT;
1352 nblanks = 1;
1353 }
1354 }
1355 log_packet(ssh->logctx,
1356 PKT_INCOMING, st->pktin->type,
1357 ssh1_pkt_type(st->pktin->type),
1358 st->pktin->body, st->pktin->length,
1359 nblanks, &blank, NULL);
1360 }
1361
1362 crFinish(st->pktin);
1363 }
1364
1365 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1366 {
1367 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1368
1369 crBegin(ssh->ssh2_rdpkt_crstate);
1370
1371 st->pktin = ssh_new_packet();
1372
1373 st->pktin->type = 0;
1374 st->pktin->length = 0;
1375 if (ssh->sccipher)
1376 st->cipherblk = ssh->sccipher->blksize;
1377 else
1378 st->cipherblk = 8;
1379 if (st->cipherblk < 8)
1380 st->cipherblk = 8;
1381 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1382
1383 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1384 ssh->scmac) {
1385 /*
1386 * When dealing with a CBC-mode cipher, we want to avoid the
1387 * possibility of an attacker's tweaking the ciphertext stream
1388 * so as to cause us to feed the same block to the block
1389 * cipher more than once and thus leak information
1390 * (VU#958563). The way we do this is not to take any
1391 * decisions on the basis of anything we've decrypted until
1392 * we've verified it with a MAC. That includes the packet
1393 * length, so we just read data and check the MAC repeatedly,
1394 * and when the MAC passes, see if the length we've got is
1395 * plausible.
1396 */
1397
1398 /* May as well allocate the whole lot now. */
1399 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1400 unsigned char);
1401
1402 /* Read an amount corresponding to the MAC. */
1403 for (st->i = 0; st->i < st->maclen; st->i++) {
1404 while ((*datalen) == 0)
1405 crReturn(NULL);
1406 st->pktin->data[st->i] = *(*data)++;
1407 (*datalen)--;
1408 }
1409
1410 st->packetlen = 0;
1411 {
1412 unsigned char seq[4];
1413 ssh->scmac->start(ssh->sc_mac_ctx);
1414 PUT_32BIT(seq, st->incoming_sequence);
1415 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1416 }
1417
1418 for (;;) { /* Once around this loop per cipher block. */
1419 /* Read another cipher-block's worth, and tack it onto the end. */
1420 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1421 while ((*datalen) == 0)
1422 crReturn(NULL);
1423 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1424 (*datalen)--;
1425 }
1426 /* Decrypt one more block (a little further back in the stream). */
1427 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1428 st->pktin->data + st->packetlen,
1429 st->cipherblk);
1430 /* Feed that block to the MAC. */
1431 ssh->scmac->bytes(ssh->sc_mac_ctx,
1432 st->pktin->data + st->packetlen, st->cipherblk);
1433 st->packetlen += st->cipherblk;
1434 /* See if that gives us a valid packet. */
1435 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1436 st->pktin->data + st->packetlen) &&
1437 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1438 break;
1439 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1440 bombout(("No valid incoming packet found"));
1441 ssh_free_packet(st->pktin);
1442 crStop(NULL);
1443 }
1444 }
1445 st->pktin->maxlen = st->packetlen + st->maclen;
1446 st->pktin->data = sresize(st->pktin->data,
1447 st->pktin->maxlen + APIEXTRA,
1448 unsigned char);
1449 } else {
1450 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1451
1452 /*
1453 * Acquire and decrypt the first block of the packet. This will
1454 * contain the length and padding details.
1455 */
1456 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1457 while ((*datalen) == 0)
1458 crReturn(NULL);
1459 st->pktin->data[st->i] = *(*data)++;
1460 (*datalen)--;
1461 }
1462
1463 if (ssh->sccipher)
1464 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1465 st->pktin->data, st->cipherblk);
1466
1467 /*
1468 * Now get the length figure.
1469 */
1470 st->len = GET_32BIT(st->pktin->data);
1471
1472 /*
1473 * _Completely_ silly lengths should be stomped on before they
1474 * do us any more damage.
1475 */
1476 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1477 (st->len + 4) % st->cipherblk != 0) {
1478 bombout(("Incoming packet was garbled on decryption"));
1479 ssh_free_packet(st->pktin);
1480 crStop(NULL);
1481 }
1482
1483 /*
1484 * So now we can work out the total packet length.
1485 */
1486 st->packetlen = st->len + 4;
1487
1488 /*
1489 * Allocate memory for the rest of the packet.
1490 */
1491 st->pktin->maxlen = st->packetlen + st->maclen;
1492 st->pktin->data = sresize(st->pktin->data,
1493 st->pktin->maxlen + APIEXTRA,
1494 unsigned char);
1495
1496 /*
1497 * Read and decrypt the remainder of the packet.
1498 */
1499 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1500 st->i++) {
1501 while ((*datalen) == 0)
1502 crReturn(NULL);
1503 st->pktin->data[st->i] = *(*data)++;
1504 (*datalen)--;
1505 }
1506 /* Decrypt everything _except_ the MAC. */
1507 if (ssh->sccipher)
1508 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1509 st->pktin->data + st->cipherblk,
1510 st->packetlen - st->cipherblk);
1511
1512 /*
1513 * Check the MAC.
1514 */
1515 if (ssh->scmac
1516 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1517 st->len + 4, st->incoming_sequence)) {
1518 bombout(("Incorrect MAC received on packet"));
1519 ssh_free_packet(st->pktin);
1520 crStop(NULL);
1521 }
1522 }
1523 /* Get and sanity-check the amount of random padding. */
1524 st->pad = st->pktin->data[4];
1525 if (st->pad < 4 || st->len - st->pad < 1) {
1526 bombout(("Invalid padding length on received packet"));
1527 ssh_free_packet(st->pktin);
1528 crStop(NULL);
1529 }
1530 /*
1531 * This enables us to deduce the payload length.
1532 */
1533 st->payload = st->len - st->pad - 1;
1534
1535 st->pktin->length = st->payload + 5;
1536 st->pktin->encrypted_len = st->packetlen;
1537
1538 st->pktin->sequence = st->incoming_sequence++;
1539
1540 /*
1541 * Decompress packet payload.
1542 */
1543 {
1544 unsigned char *newpayload;
1545 int newlen;
1546 if (ssh->sccomp &&
1547 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1548 st->pktin->data + 5, st->pktin->length - 5,
1549 &newpayload, &newlen)) {
1550 if (st->pktin->maxlen < newlen + 5) {
1551 st->pktin->maxlen = newlen + 5;
1552 st->pktin->data = sresize(st->pktin->data,
1553 st->pktin->maxlen + APIEXTRA,
1554 unsigned char);
1555 }
1556 st->pktin->length = 5 + newlen;
1557 memcpy(st->pktin->data + 5, newpayload, newlen);
1558 sfree(newpayload);
1559 }
1560 }
1561
1562 st->pktin->savedpos = 6;
1563 st->pktin->body = st->pktin->data;
1564 st->pktin->type = st->pktin->data[5];
1565
1566 /*
1567 * Log incoming packet, possibly omitting sensitive fields.
1568 */
1569 if (ssh->logctx) {
1570 int nblanks = 0;
1571 struct logblank_t blank;
1572 if (ssh->logomitdata) {
1573 int do_blank = FALSE, blank_prefix = 0;
1574 /* "Session data" packets - omit the data field */
1575 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1576 do_blank = TRUE; blank_prefix = 8;
1577 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1578 do_blank = TRUE; blank_prefix = 12;
1579 }
1580 if (do_blank) {
1581 blank.offset = blank_prefix;
1582 blank.len = (st->pktin->length-6) - blank_prefix;
1583 blank.type = PKTLOG_OMIT;
1584 nblanks = 1;
1585 }
1586 }
1587 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1588 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1589 st->pktin->type),
1590 st->pktin->data+6, st->pktin->length-6,
1591 nblanks, &blank, &st->pktin->sequence);
1592 }
1593
1594 crFinish(st->pktin);
1595 }
1596
1597 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1598 {
1599 int pad, biglen, i, pktoffs;
1600 unsigned long crc;
1601 #ifdef __SC__
1602 /*
1603 * XXX various versions of SC (including 8.8.4) screw up the
1604 * register allocation in this function and use the same register
1605 * (D6) for len and as a temporary, with predictable results. The
1606 * following sledgehammer prevents this.
1607 */
1608 volatile
1609 #endif
1610 int len;
1611
1612 if (ssh->logctx)
1613 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1614 ssh1_pkt_type(pkt->data[12]),
1615 pkt->body, pkt->length - (pkt->body - pkt->data),
1616 pkt->nblanks, pkt->blanks, NULL);
1617 sfree(pkt->blanks); pkt->blanks = NULL;
1618 pkt->nblanks = 0;
1619
1620 if (ssh->v1_compressing) {
1621 unsigned char *compblk;
1622 int complen;
1623 zlib_compress_block(ssh->cs_comp_ctx,
1624 pkt->data + 12, pkt->length - 12,
1625 &compblk, &complen);
1626 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1627 memcpy(pkt->data + 12, compblk, complen);
1628 sfree(compblk);
1629 pkt->length = complen + 12;
1630 }
1631
1632 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1633 pkt->length += 4;
1634 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1635 pad = 8 - (len % 8);
1636 pktoffs = 8 - pad;
1637 biglen = len + pad; /* len(padding+type+data+CRC) */
1638
1639 for (i = pktoffs; i < 4+8; i++)
1640 pkt->data[i] = random_byte();
1641 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1642 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1643 PUT_32BIT(pkt->data + pktoffs, len);
1644
1645 if (ssh->cipher)
1646 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1647 pkt->data + pktoffs + 4, biglen);
1648
1649 if (offset_p) *offset_p = pktoffs;
1650 return biglen + 4; /* len(length+padding+type+data+CRC) */
1651 }
1652
1653 static int s_write(Ssh ssh, void *data, int len)
1654 {
1655 if (ssh->logctx)
1656 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1657 0, NULL, NULL);
1658 return sk_write(ssh->s, (char *)data, len);
1659 }
1660
1661 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1662 {
1663 int len, backlog, offset;
1664 len = s_wrpkt_prepare(ssh, pkt, &offset);
1665 backlog = s_write(ssh, pkt->data + offset, len);
1666 if (backlog > SSH_MAX_BACKLOG)
1667 ssh_throttle_all(ssh, 1, backlog);
1668 ssh_free_packet(pkt);
1669 }
1670
1671 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1672 {
1673 int len, offset;
1674 len = s_wrpkt_prepare(ssh, pkt, &offset);
1675 if (ssh->deferred_len + len > ssh->deferred_size) {
1676 ssh->deferred_size = ssh->deferred_len + len + 128;
1677 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1678 ssh->deferred_size,
1679 unsigned char);
1680 }
1681 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1682 pkt->data + offset, len);
1683 ssh->deferred_len += len;
1684 ssh_free_packet(pkt);
1685 }
1686
1687 /*
1688 * Construct a SSH-1 packet with the specified contents.
1689 * (This all-at-once interface used to be the only one, but now SSH-1
1690 * packets can also be constructed incrementally.)
1691 */
1692 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1693 {
1694 int argtype;
1695 Bignum bn;
1696 struct Packet *pkt;
1697
1698 pkt = ssh1_pkt_init(pkttype);
1699
1700 while ((argtype = va_arg(ap, int)) != PKT_END) {
1701 unsigned char *argp, argchar;
1702 char *sargp;
1703 unsigned long argint;
1704 int arglen;
1705 switch (argtype) {
1706 /* Actual fields in the packet */
1707 case PKT_INT:
1708 argint = va_arg(ap, int);
1709 ssh_pkt_adduint32(pkt, argint);
1710 break;
1711 case PKT_CHAR:
1712 argchar = (unsigned char) va_arg(ap, int);
1713 ssh_pkt_addbyte(pkt, argchar);
1714 break;
1715 case PKT_DATA:
1716 argp = va_arg(ap, unsigned char *);
1717 arglen = va_arg(ap, int);
1718 ssh_pkt_adddata(pkt, argp, arglen);
1719 break;
1720 case PKT_STR:
1721 sargp = va_arg(ap, char *);
1722 ssh_pkt_addstring(pkt, sargp);
1723 break;
1724 case PKT_BIGNUM:
1725 bn = va_arg(ap, Bignum);
1726 ssh1_pkt_addmp(pkt, bn);
1727 break;
1728 /* Tokens for modifications to packet logging */
1729 case PKTT_PASSWORD:
1730 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1731 break;
1732 case PKTT_DATA:
1733 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1734 break;
1735 case PKTT_OTHER:
1736 end_log_omission(ssh, pkt);
1737 break;
1738 }
1739 }
1740
1741 return pkt;
1742 }
1743
1744 static void send_packet(Ssh ssh, int pkttype, ...)
1745 {
1746 struct Packet *pkt;
1747 va_list ap;
1748 va_start(ap, pkttype);
1749 pkt = construct_packet(ssh, pkttype, ap);
1750 va_end(ap);
1751 s_wrpkt(ssh, pkt);
1752 }
1753
1754 static void defer_packet(Ssh ssh, int pkttype, ...)
1755 {
1756 struct Packet *pkt;
1757 va_list ap;
1758 va_start(ap, pkttype);
1759 pkt = construct_packet(ssh, pkttype, ap);
1760 va_end(ap);
1761 s_wrpkt_defer(ssh, pkt);
1762 }
1763
1764 static int ssh_versioncmp(char *a, char *b)
1765 {
1766 char *ae, *be;
1767 unsigned long av, bv;
1768
1769 av = strtoul(a, &ae, 10);
1770 bv = strtoul(b, &be, 10);
1771 if (av != bv)
1772 return (av < bv ? -1 : +1);
1773 if (*ae == '.')
1774 ae++;
1775 if (*be == '.')
1776 be++;
1777 av = strtoul(ae, &ae, 10);
1778 bv = strtoul(be, &be, 10);
1779 if (av != bv)
1780 return (av < bv ? -1 : +1);
1781 return 0;
1782 }
1783
1784 /*
1785 * Utility routines for putting an SSH-protocol `string' and
1786 * `uint32' into a hash state.
1787 */
1788 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1789 {
1790 unsigned char lenblk[4];
1791 PUT_32BIT(lenblk, len);
1792 h->bytes(s, lenblk, 4);
1793 h->bytes(s, str, len);
1794 }
1795
1796 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1797 {
1798 unsigned char intblk[4];
1799 PUT_32BIT(intblk, i);
1800 h->bytes(s, intblk, 4);
1801 }
1802
1803 /*
1804 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1805 */
1806 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1807 {
1808 if (pkt->maxlen < length) {
1809 unsigned char *body = pkt->body;
1810 int offset = body ? body - pkt->data : 0;
1811 pkt->maxlen = length + 256;
1812 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1813 if (body) pkt->body = pkt->data + offset;
1814 }
1815 }
1816 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1817 {
1818 if (pkt->logmode != PKTLOG_EMIT) {
1819 pkt->nblanks++;
1820 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1821 assert(pkt->body);
1822 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1823 (pkt->body - pkt->data);
1824 pkt->blanks[pkt->nblanks-1].len = len;
1825 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1826 }
1827 pkt->length += len;
1828 ssh_pkt_ensure(pkt, pkt->length);
1829 memcpy(pkt->data + pkt->length - len, data, len);
1830 }
1831 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1832 {
1833 ssh_pkt_adddata(pkt, &byte, 1);
1834 }
1835 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1836 {
1837 ssh_pkt_adddata(pkt, &value, 1);
1838 }
1839 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1840 {
1841 unsigned char x[4];
1842 PUT_32BIT(x, value);
1843 ssh_pkt_adddata(pkt, x, 4);
1844 }
1845 static void ssh_pkt_addstring_start(struct Packet *pkt)
1846 {
1847 ssh_pkt_adduint32(pkt, 0);
1848 pkt->savedpos = pkt->length;
1849 }
1850 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1851 {
1852 ssh_pkt_adddata(pkt, data, strlen(data));
1853 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1854 }
1855 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1856 {
1857 ssh_pkt_adddata(pkt, data, len);
1858 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1859 }
1860 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1861 {
1862 ssh_pkt_addstring_start(pkt);
1863 ssh_pkt_addstring_str(pkt, data);
1864 }
1865 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1866 {
1867 int len = ssh1_bignum_length(b);
1868 unsigned char *data = snewn(len, unsigned char);
1869 (void) ssh1_write_bignum(data, b);
1870 ssh_pkt_adddata(pkt, data, len);
1871 sfree(data);
1872 }
1873 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1874 {
1875 unsigned char *p;
1876 int i, n = (bignum_bitcount(b) + 7) / 8;
1877 p = snewn(n + 1, unsigned char);
1878 p[0] = 0;
1879 for (i = 1; i <= n; i++)
1880 p[i] = bignum_byte(b, n - i);
1881 i = 0;
1882 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1883 i++;
1884 memmove(p, p + i, n + 1 - i);
1885 *len = n + 1 - i;
1886 return p;
1887 }
1888 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1889 {
1890 unsigned char *p;
1891 int len;
1892 p = ssh2_mpint_fmt(b, &len);
1893 ssh_pkt_addstring_start(pkt);
1894 ssh_pkt_addstring_data(pkt, (char *)p, len);
1895 sfree(p);
1896 }
1897
1898 static struct Packet *ssh1_pkt_init(int pkt_type)
1899 {
1900 struct Packet *pkt = ssh_new_packet();
1901 pkt->length = 4 + 8; /* space for length + max padding */
1902 ssh_pkt_addbyte(pkt, pkt_type);
1903 pkt->body = pkt->data + pkt->length;
1904 return pkt;
1905 }
1906
1907 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1908 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1909 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1910 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1911 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1912 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1913 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1914 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1915 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1916
1917 static struct Packet *ssh2_pkt_init(int pkt_type)
1918 {
1919 struct Packet *pkt = ssh_new_packet();
1920 pkt->length = 5; /* space for packet length + padding length */
1921 pkt->forcepad = 0;
1922 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1923 pkt->body = pkt->data + pkt->length; /* after packet type */
1924 return pkt;
1925 }
1926
1927 /*
1928 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1929 * put the MAC on it. Final packet, ready to be sent, is stored in
1930 * pkt->data. Total length is returned.
1931 */
1932 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1933 {
1934 int cipherblk, maclen, padding, i;
1935
1936 if (ssh->logctx)
1937 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1938 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1939 pkt->body, pkt->length - (pkt->body - pkt->data),
1940 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1941 sfree(pkt->blanks); pkt->blanks = NULL;
1942 pkt->nblanks = 0;
1943
1944 /*
1945 * Compress packet payload.
1946 */
1947 {
1948 unsigned char *newpayload;
1949 int newlen;
1950 if (ssh->cscomp &&
1951 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1952 pkt->length - 5,
1953 &newpayload, &newlen)) {
1954 pkt->length = 5;
1955 ssh2_pkt_adddata(pkt, newpayload, newlen);
1956 sfree(newpayload);
1957 }
1958 }
1959
1960 /*
1961 * Add padding. At least four bytes, and must also bring total
1962 * length (minus MAC) up to a multiple of the block size.
1963 * If pkt->forcepad is set, make sure the packet is at least that size
1964 * after padding.
1965 */
1966 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1967 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1968 padding = 4;
1969 if (pkt->length + padding < pkt->forcepad)
1970 padding = pkt->forcepad - pkt->length;
1971 padding +=
1972 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1973 assert(padding <= 255);
1974 maclen = ssh->csmac ? ssh->csmac->len : 0;
1975 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1976 pkt->data[4] = padding;
1977 for (i = 0; i < padding; i++)
1978 pkt->data[pkt->length + i] = random_byte();
1979 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1980 if (ssh->csmac)
1981 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1982 pkt->length + padding,
1983 ssh->v2_outgoing_sequence);
1984 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1985
1986 if (ssh->cscipher)
1987 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1988 pkt->data, pkt->length + padding);
1989
1990 pkt->encrypted_len = pkt->length + padding;
1991
1992 /* Ready-to-send packet starts at pkt->data. We return length. */
1993 return pkt->length + padding + maclen;
1994 }
1995
1996 /*
1997 * Routines called from the main SSH code to send packets. There
1998 * are quite a few of these, because we have two separate
1999 * mechanisms for delaying the sending of packets:
2000 *
2001 * - In order to send an IGNORE message and a password message in
2002 * a single fixed-length blob, we require the ability to
2003 * concatenate the encrypted forms of those two packets _into_ a
2004 * single blob and then pass it to our <network.h> transport
2005 * layer in one go. Hence, there's a deferment mechanism which
2006 * works after packet encryption.
2007 *
2008 * - In order to avoid sending any connection-layer messages
2009 * during repeat key exchange, we have to queue up any such
2010 * outgoing messages _before_ they are encrypted (and in
2011 * particular before they're allocated sequence numbers), and
2012 * then send them once we've finished.
2013 *
2014 * I call these mechanisms `defer' and `queue' respectively, so as
2015 * to distinguish them reasonably easily.
2016 *
2017 * The functions send_noqueue() and defer_noqueue() free the packet
2018 * structure they are passed. Every outgoing packet goes through
2019 * precisely one of these functions in its life; packets passed to
2020 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2021 * these or get queued, and then when the queue is later emptied
2022 * the packets are all passed to defer_noqueue().
2023 *
2024 * When using a CBC-mode cipher, it's necessary to ensure that an
2025 * attacker can't provide data to be encrypted using an IV that they
2026 * know. We ensure this by prefixing each packet that might contain
2027 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2028 * mechanism, so in this case send_noqueue() ends up redirecting to
2029 * defer_noqueue(). If you don't like this inefficiency, don't use
2030 * CBC.
2031 */
2032
2033 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2034 static void ssh_pkt_defersend(Ssh);
2035
2036 /*
2037 * Send an SSH-2 packet immediately, without queuing or deferring.
2038 */
2039 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2040 {
2041 int len;
2042 int backlog;
2043 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2044 /* We need to send two packets, so use the deferral mechanism. */
2045 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2046 ssh_pkt_defersend(ssh);
2047 return;
2048 }
2049 len = ssh2_pkt_construct(ssh, pkt);
2050 backlog = s_write(ssh, pkt->data, len);
2051 if (backlog > SSH_MAX_BACKLOG)
2052 ssh_throttle_all(ssh, 1, backlog);
2053
2054 ssh->outgoing_data_size += pkt->encrypted_len;
2055 if (!ssh->kex_in_progress &&
2056 ssh->max_data_size != 0 &&
2057 ssh->outgoing_data_size > ssh->max_data_size)
2058 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2059
2060 ssh_free_packet(pkt);
2061 }
2062
2063 /*
2064 * Defer an SSH-2 packet.
2065 */
2066 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2067 {
2068 int len;
2069 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2070 ssh->deferred_len == 0 && !noignore &&
2071 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2072 /*
2073 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2074 * get encrypted with a known IV.
2075 */
2076 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2077 ssh2_pkt_addstring_start(ipkt);
2078 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2079 }
2080 len = ssh2_pkt_construct(ssh, pkt);
2081 if (ssh->deferred_len + len > ssh->deferred_size) {
2082 ssh->deferred_size = ssh->deferred_len + len + 128;
2083 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2084 ssh->deferred_size,
2085 unsigned char);
2086 }
2087 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2088 ssh->deferred_len += len;
2089 ssh->deferred_data_size += pkt->encrypted_len;
2090 ssh_free_packet(pkt);
2091 }
2092
2093 /*
2094 * Queue an SSH-2 packet.
2095 */
2096 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2097 {
2098 assert(ssh->queueing);
2099
2100 if (ssh->queuelen >= ssh->queuesize) {
2101 ssh->queuesize = ssh->queuelen + 32;
2102 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2103 }
2104
2105 ssh->queue[ssh->queuelen++] = pkt;
2106 }
2107
2108 /*
2109 * Either queue or send a packet, depending on whether queueing is
2110 * set.
2111 */
2112 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2113 {
2114 if (ssh->queueing)
2115 ssh2_pkt_queue(ssh, pkt);
2116 else
2117 ssh2_pkt_send_noqueue(ssh, pkt);
2118 }
2119
2120 /*
2121 * Either queue or defer a packet, depending on whether queueing is
2122 * set.
2123 */
2124 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2125 {
2126 if (ssh->queueing)
2127 ssh2_pkt_queue(ssh, pkt);
2128 else
2129 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2130 }
2131
2132 /*
2133 * Send the whole deferred data block constructed by
2134 * ssh2_pkt_defer() or SSH-1's defer_packet().
2135 *
2136 * The expected use of the defer mechanism is that you call
2137 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2138 * not currently queueing, this simply sets up deferred_send_data
2139 * and then sends it. If we _are_ currently queueing, the calls to
2140 * ssh2_pkt_defer() put the deferred packets on to the queue
2141 * instead, and therefore ssh_pkt_defersend() has no deferred data
2142 * to send. Hence, there's no need to make it conditional on
2143 * ssh->queueing.
2144 */
2145 static void ssh_pkt_defersend(Ssh ssh)
2146 {
2147 int backlog;
2148 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2149 ssh->deferred_len = ssh->deferred_size = 0;
2150 sfree(ssh->deferred_send_data);
2151 ssh->deferred_send_data = NULL;
2152 if (backlog > SSH_MAX_BACKLOG)
2153 ssh_throttle_all(ssh, 1, backlog);
2154
2155 ssh->outgoing_data_size += ssh->deferred_data_size;
2156 if (!ssh->kex_in_progress &&
2157 ssh->max_data_size != 0 &&
2158 ssh->outgoing_data_size > ssh->max_data_size)
2159 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2160 ssh->deferred_data_size = 0;
2161 }
2162
2163 /*
2164 * Send a packet whose length needs to be disguised (typically
2165 * passwords or keyboard-interactive responses).
2166 */
2167 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2168 int padsize)
2169 {
2170 #if 0
2171 if (0) {
2172 /*
2173 * The simplest way to do this is to adjust the
2174 * variable-length padding field in the outgoing packet.
2175 *
2176 * Currently compiled out, because some Cisco SSH servers
2177 * don't like excessively padded packets (bah, why's it
2178 * always Cisco?)
2179 */
2180 pkt->forcepad = padsize;
2181 ssh2_pkt_send(ssh, pkt);
2182 } else
2183 #endif
2184 {
2185 /*
2186 * If we can't do that, however, an alternative approach is
2187 * to use the pkt_defer mechanism to bundle the packet
2188 * tightly together with an SSH_MSG_IGNORE such that their
2189 * combined length is a constant. So first we construct the
2190 * final form of this packet and defer its sending.
2191 */
2192 ssh2_pkt_defer(ssh, pkt);
2193
2194 /*
2195 * Now construct an SSH_MSG_IGNORE which includes a string
2196 * that's an exact multiple of the cipher block size. (If
2197 * the cipher is NULL so that the block size is
2198 * unavailable, we don't do this trick at all, because we
2199 * gain nothing by it.)
2200 */
2201 if (ssh->cscipher &&
2202 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2203 int stringlen, i;
2204
2205 stringlen = (256 - ssh->deferred_len);
2206 stringlen += ssh->cscipher->blksize - 1;
2207 stringlen -= (stringlen % ssh->cscipher->blksize);
2208 if (ssh->cscomp) {
2209 /*
2210 * Temporarily disable actual compression, so we
2211 * can guarantee to get this string exactly the
2212 * length we want it. The compression-disabling
2213 * routine should return an integer indicating how
2214 * many bytes we should adjust our string length
2215 * by.
2216 */
2217 stringlen -=
2218 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2219 }
2220 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2221 ssh2_pkt_addstring_start(pkt);
2222 for (i = 0; i < stringlen; i++) {
2223 char c = (char) random_byte();
2224 ssh2_pkt_addstring_data(pkt, &c, 1);
2225 }
2226 ssh2_pkt_defer(ssh, pkt);
2227 }
2228 ssh_pkt_defersend(ssh);
2229 }
2230 }
2231
2232 /*
2233 * Send all queued SSH-2 packets. We send them by means of
2234 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2235 * packets that needed to be lumped together.
2236 */
2237 static void ssh2_pkt_queuesend(Ssh ssh)
2238 {
2239 int i;
2240
2241 assert(!ssh->queueing);
2242
2243 for (i = 0; i < ssh->queuelen; i++)
2244 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2245 ssh->queuelen = 0;
2246
2247 ssh_pkt_defersend(ssh);
2248 }
2249
2250 #if 0
2251 void bndebug(char *string, Bignum b)
2252 {
2253 unsigned char *p;
2254 int i, len;
2255 p = ssh2_mpint_fmt(b, &len);
2256 debug(("%s", string));
2257 for (i = 0; i < len; i++)
2258 debug((" %02x", p[i]));
2259 debug(("\n"));
2260 sfree(p);
2261 }
2262 #endif
2263
2264 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2265 {
2266 unsigned char *p;
2267 int len;
2268 p = ssh2_mpint_fmt(b, &len);
2269 hash_string(h, s, p, len);
2270 sfree(p);
2271 }
2272
2273 /*
2274 * Packet decode functions for both SSH-1 and SSH-2.
2275 */
2276 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2277 {
2278 unsigned long value;
2279 if (pkt->length - pkt->savedpos < 4)
2280 return 0; /* arrgh, no way to decline (FIXME?) */
2281 value = GET_32BIT(pkt->body + pkt->savedpos);
2282 pkt->savedpos += 4;
2283 return value;
2284 }
2285 static int ssh2_pkt_getbool(struct Packet *pkt)
2286 {
2287 unsigned long value;
2288 if (pkt->length - pkt->savedpos < 1)
2289 return 0; /* arrgh, no way to decline (FIXME?) */
2290 value = pkt->body[pkt->savedpos] != 0;
2291 pkt->savedpos++;
2292 return value;
2293 }
2294 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2295 {
2296 int len;
2297 *p = NULL;
2298 *length = 0;
2299 if (pkt->length - pkt->savedpos < 4)
2300 return;
2301 len = GET_32BIT(pkt->body + pkt->savedpos);
2302 if (len < 0)
2303 return;
2304 *length = len;
2305 pkt->savedpos += 4;
2306 if (pkt->length - pkt->savedpos < *length)
2307 return;
2308 *p = (char *)(pkt->body + pkt->savedpos);
2309 pkt->savedpos += *length;
2310 }
2311 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2312 {
2313 if (pkt->length - pkt->savedpos < length)
2314 return NULL;
2315 pkt->savedpos += length;
2316 return pkt->body + (pkt->savedpos - length);
2317 }
2318 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2319 unsigned char **keystr)
2320 {
2321 int j;
2322
2323 j = makekey(pkt->body + pkt->savedpos,
2324 pkt->length - pkt->savedpos,
2325 key, keystr, 0);
2326
2327 if (j < 0)
2328 return FALSE;
2329
2330 pkt->savedpos += j;
2331 assert(pkt->savedpos < pkt->length);
2332
2333 return TRUE;
2334 }
2335 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2336 {
2337 int j;
2338 Bignum b;
2339
2340 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2341 pkt->length - pkt->savedpos, &b);
2342
2343 if (j < 0)
2344 return NULL;
2345
2346 pkt->savedpos += j;
2347 return b;
2348 }
2349 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2350 {
2351 char *p;
2352 int length;
2353 Bignum b;
2354
2355 ssh_pkt_getstring(pkt, &p, &length);
2356 if (!p)
2357 return NULL;
2358 if (p[0] & 0x80)
2359 return NULL;
2360 b = bignum_from_bytes((unsigned char *)p, length);
2361 return b;
2362 }
2363
2364 /*
2365 * Helper function to add an SSH-2 signature blob to a packet.
2366 * Expects to be shown the public key blob as well as the signature
2367 * blob. Normally works just like ssh2_pkt_addstring, but will
2368 * fiddle with the signature packet if necessary for
2369 * BUG_SSH2_RSA_PADDING.
2370 */
2371 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2372 void *pkblob_v, int pkblob_len,
2373 void *sigblob_v, int sigblob_len)
2374 {
2375 unsigned char *pkblob = (unsigned char *)pkblob_v;
2376 unsigned char *sigblob = (unsigned char *)sigblob_v;
2377
2378 /* dmemdump(pkblob, pkblob_len); */
2379 /* dmemdump(sigblob, sigblob_len); */
2380
2381 /*
2382 * See if this is in fact an ssh-rsa signature and a buggy
2383 * server; otherwise we can just do this the easy way.
2384 */
2385 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2386 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2387 int pos, len, siglen;
2388
2389 /*
2390 * Find the byte length of the modulus.
2391 */
2392
2393 pos = 4+7; /* skip over "ssh-rsa" */
2394 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2395 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2396 pos += 4; /* find modulus itself */
2397 while (len > 0 && pkblob[pos] == 0)
2398 len--, pos++;
2399 /* debug(("modulus length is %d\n", len)); */
2400
2401 /*
2402 * Now find the signature integer.
2403 */
2404 pos = 4+7; /* skip over "ssh-rsa" */
2405 siglen = GET_32BIT(sigblob+pos);
2406 /* debug(("signature length is %d\n", siglen)); */
2407
2408 if (len != siglen) {
2409 unsigned char newlen[4];
2410 ssh2_pkt_addstring_start(pkt);
2411 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2412 /* dmemdump(sigblob, pos); */
2413 pos += 4; /* point to start of actual sig */
2414 PUT_32BIT(newlen, len);
2415 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2416 /* dmemdump(newlen, 4); */
2417 newlen[0] = 0;
2418 while (len-- > siglen) {
2419 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2420 /* dmemdump(newlen, 1); */
2421 }
2422 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2423 /* dmemdump(sigblob+pos, siglen); */
2424 return;
2425 }
2426
2427 /* Otherwise fall through and do it the easy way. */
2428 }
2429
2430 ssh2_pkt_addstring_start(pkt);
2431 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2432 }
2433
2434 /*
2435 * Examine the remote side's version string and compare it against
2436 * a list of known buggy implementations.
2437 */
2438 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2439 {
2440 char *imp; /* pointer to implementation part */
2441 imp = vstring;
2442 imp += strcspn(imp, "-");
2443 if (*imp) imp++;
2444 imp += strcspn(imp, "-");
2445 if (*imp) imp++;
2446
2447 ssh->remote_bugs = 0;
2448
2449 /*
2450 * General notes on server version strings:
2451 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2452 * here -- in particular, we've heard of one that's perfectly happy
2453 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2454 * so we can't distinguish them.
2455 */
2456 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2457 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2458 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2459 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2460 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2461 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2462 /*
2463 * These versions don't support SSH1_MSG_IGNORE, so we have
2464 * to use a different defence against password length
2465 * sniffing.
2466 */
2467 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2468 logevent("We believe remote version has SSH-1 ignore bug");
2469 }
2470
2471 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2472 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2473 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2474 /*
2475 * These versions need a plain password sent; they can't
2476 * handle having a null and a random length of data after
2477 * the password.
2478 */
2479 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2480 logevent("We believe remote version needs a plain SSH-1 password");
2481 }
2482
2483 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2484 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2485 (!strcmp(imp, "Cisco-1.25")))) {
2486 /*
2487 * These versions apparently have no clue whatever about
2488 * RSA authentication and will panic and die if they see
2489 * an AUTH_RSA message.
2490 */
2491 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2492 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2493 }
2494
2495 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2496 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2497 !wc_match("* VShell", imp) &&
2498 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2499 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2500 wc_match("2.1 *", imp)))) {
2501 /*
2502 * These versions have the HMAC bug.
2503 */
2504 ssh->remote_bugs |= BUG_SSH2_HMAC;
2505 logevent("We believe remote version has SSH-2 HMAC bug");
2506 }
2507
2508 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2509 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2510 !wc_match("* VShell", imp) &&
2511 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2512 /*
2513 * These versions have the key-derivation bug (failing to
2514 * include the literal shared secret in the hashes that
2515 * generate the keys).
2516 */
2517 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2518 logevent("We believe remote version has SSH-2 key-derivation bug");
2519 }
2520
2521 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2522 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2523 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2524 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2525 /*
2526 * These versions have the SSH-2 RSA padding bug.
2527 */
2528 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2529 logevent("We believe remote version has SSH-2 RSA padding bug");
2530 }
2531
2532 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2533 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2534 wc_match("OpenSSH_2.[0-2]*", imp))) {
2535 /*
2536 * These versions have the SSH-2 session-ID bug in
2537 * public-key authentication.
2538 */
2539 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2540 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2541 }
2542
2543 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2544 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2545 (wc_match("DigiSSH_2.0", imp) ||
2546 wc_match("OpenSSH_2.[0-4]*", imp) ||
2547 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2548 wc_match("Sun_SSH_1.0", imp) ||
2549 wc_match("Sun_SSH_1.0.1", imp) ||
2550 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2551 wc_match("WeOnlyDo-*", imp)))) {
2552 /*
2553 * These versions have the SSH-2 rekey bug.
2554 */
2555 ssh->remote_bugs |= BUG_SSH2_REKEY;
2556 logevent("We believe remote version has SSH-2 rekey bug");
2557 }
2558
2559 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2560 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2561 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2562 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2563 /*
2564 * This version ignores our makpkt and needs to be throttled.
2565 */
2566 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2567 logevent("We believe remote version ignores SSH-2 maximum packet size");
2568 }
2569
2570 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2571 /*
2572 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2573 * none detected automatically.
2574 */
2575 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2576 logevent("We believe remote version has SSH-2 ignore bug");
2577 }
2578 }
2579
2580 /*
2581 * The `software version' part of an SSH version string is required
2582 * to contain no spaces or minus signs.
2583 */
2584 static void ssh_fix_verstring(char *str)
2585 {
2586 /* Eat "SSH-<protoversion>-". */
2587 assert(*str == 'S'); str++;
2588 assert(*str == 'S'); str++;
2589 assert(*str == 'H'); str++;
2590 assert(*str == '-'); str++;
2591 while (*str && *str != '-') str++;
2592 assert(*str == '-'); str++;
2593
2594 /* Convert minus signs and spaces in the remaining string into
2595 * underscores. */
2596 while (*str) {
2597 if (*str == '-' || *str == ' ')
2598 *str = '_';
2599 str++;
2600 }
2601 }
2602
2603 /*
2604 * Send an appropriate SSH version string.
2605 */
2606 static void ssh_send_verstring(Ssh ssh, char *svers)
2607 {
2608 char *verstring;
2609
2610 if (ssh->version == 2) {
2611 /*
2612 * Construct a v2 version string.
2613 */
2614 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2615 } else {
2616 /*
2617 * Construct a v1 version string.
2618 */
2619 verstring = dupprintf("SSH-%s-%s\012",
2620 (ssh_versioncmp(svers, "1.5") <= 0 ?
2621 svers : "1.5"),
2622 sshver);
2623 }
2624
2625 ssh_fix_verstring(verstring);
2626
2627 if (ssh->version == 2) {
2628 size_t len;
2629 /*
2630 * Record our version string.
2631 */
2632 len = strcspn(verstring, "\015\012");
2633 ssh->v_c = snewn(len + 1, char);
2634 memcpy(ssh->v_c, verstring, len);
2635 ssh->v_c[len] = 0;
2636 }
2637
2638 logeventf(ssh, "We claim version: %.*s",
2639 strcspn(verstring, "\015\012"), verstring);
2640 s_write(ssh, verstring, strlen(verstring));
2641 sfree(verstring);
2642 }
2643
2644 static int do_ssh_init(Ssh ssh, unsigned char c)
2645 {
2646 struct do_ssh_init_state {
2647 int vslen;
2648 char version[10];
2649 char *vstring;
2650 int vstrsize;
2651 int i;
2652 int proto1, proto2;
2653 };
2654 crState(do_ssh_init_state);
2655
2656 crBegin(ssh->do_ssh_init_crstate);
2657
2658 /* Search for a line beginning with the string "SSH-" in the input. */
2659 for (;;) {
2660 if (c != 'S') goto no;
2661 crReturn(1);
2662 if (c != 'S') goto no;
2663 crReturn(1);
2664 if (c != 'H') goto no;
2665 crReturn(1);
2666 if (c != '-') goto no;
2667 break;
2668 no:
2669 while (c != '\012')
2670 crReturn(1);
2671 crReturn(1);
2672 }
2673
2674 s->vstrsize = 16;
2675 s->vstring = snewn(s->vstrsize, char);
2676 strcpy(s->vstring, "SSH-");
2677 s->vslen = 4;
2678 s->i = 0;
2679 while (1) {
2680 crReturn(1); /* get another char */
2681 if (s->vslen >= s->vstrsize - 1) {
2682 s->vstrsize += 16;
2683 s->vstring = sresize(s->vstring, s->vstrsize, char);
2684 }
2685 s->vstring[s->vslen++] = c;
2686 if (s->i >= 0) {
2687 if (c == '-') {
2688 s->version[s->i] = '\0';
2689 s->i = -1;
2690 } else if (s->i < sizeof(s->version) - 1)
2691 s->version[s->i++] = c;
2692 } else if (c == '\012')
2693 break;
2694 }
2695
2696 ssh->agentfwd_enabled = FALSE;
2697 ssh->rdpkt2_state.incoming_sequence = 0;
2698
2699 s->vstring[s->vslen] = 0;
2700 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2701 logeventf(ssh, "Server version: %s", s->vstring);
2702 ssh_detect_bugs(ssh, s->vstring);
2703
2704 /*
2705 * Decide which SSH protocol version to support.
2706 */
2707
2708 /* Anything strictly below "2.0" means protocol 1 is supported. */
2709 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2710 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2711 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2712
2713 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2714 bombout(("SSH protocol version 1 required by user but not provided by server"));
2715 crStop(0);
2716 }
2717 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2718 bombout(("SSH protocol version 2 required by user but not provided by server"));
2719 crStop(0);
2720 }
2721
2722 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2723 ssh->version = 2;
2724 else
2725 ssh->version = 1;
2726
2727 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2728
2729 /* Send the version string, if we haven't already */
2730 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2731 ssh_send_verstring(ssh, s->version);
2732
2733 if (ssh->version == 2) {
2734 size_t len;
2735 /*
2736 * Record their version string.
2737 */
2738 len = strcspn(s->vstring, "\015\012");
2739 ssh->v_s = snewn(len + 1, char);
2740 memcpy(ssh->v_s, s->vstring, len);
2741 ssh->v_s[len] = 0;
2742
2743 /*
2744 * Initialise SSH-2 protocol.
2745 */
2746 ssh->protocol = ssh2_protocol;
2747 ssh2_protocol_setup(ssh);
2748 ssh->s_rdpkt = ssh2_rdpkt;
2749 } else {
2750 /*
2751 * Initialise SSH-1 protocol.
2752 */
2753 ssh->protocol = ssh1_protocol;
2754 ssh1_protocol_setup(ssh);
2755 ssh->s_rdpkt = ssh1_rdpkt;
2756 }
2757 if (ssh->version == 2)
2758 do_ssh2_transport(ssh, NULL, -1, NULL);
2759
2760 update_specials_menu(ssh->frontend);
2761 ssh->state = SSH_STATE_BEFORE_SIZE;
2762 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2763
2764 sfree(s->vstring);
2765
2766 crFinish(0);
2767 }
2768
2769 static void ssh_process_incoming_data(Ssh ssh,
2770 unsigned char **data, int *datalen)
2771 {
2772 struct Packet *pktin;
2773
2774 pktin = ssh->s_rdpkt(ssh, data, datalen);
2775 if (pktin) {
2776 ssh->protocol(ssh, NULL, 0, pktin);
2777 ssh_free_packet(pktin);
2778 }
2779 }
2780
2781 static void ssh_queue_incoming_data(Ssh ssh,
2782 unsigned char **data, int *datalen)
2783 {
2784 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2785 *data += *datalen;
2786 *datalen = 0;
2787 }
2788
2789 static void ssh_process_queued_incoming_data(Ssh ssh)
2790 {
2791 void *vdata;
2792 unsigned char *data;
2793 int len, origlen;
2794
2795 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2796 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2797 data = vdata;
2798 origlen = len;
2799
2800 while (!ssh->frozen && len > 0)
2801 ssh_process_incoming_data(ssh, &data, &len);
2802
2803 if (origlen > len)
2804 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2805 }
2806 }
2807
2808 static void ssh_set_frozen(Ssh ssh, int frozen)
2809 {
2810 if (ssh->s)
2811 sk_set_frozen(ssh->s, frozen);
2812 ssh->frozen = frozen;
2813 }
2814
2815 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2816 {
2817 /* Log raw data, if we're in that mode. */
2818 if (ssh->logctx)
2819 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2820 0, NULL, NULL);
2821
2822 crBegin(ssh->ssh_gotdata_crstate);
2823
2824 /*
2825 * To begin with, feed the characters one by one to the
2826 * protocol initialisation / selection function do_ssh_init().
2827 * When that returns 0, we're done with the initial greeting
2828 * exchange and can move on to packet discipline.
2829 */
2830 while (1) {
2831 int ret; /* need not be kept across crReturn */
2832 if (datalen == 0)
2833 crReturnV; /* more data please */
2834 ret = do_ssh_init(ssh, *data);
2835 data++;
2836 datalen--;
2837 if (ret == 0)
2838 break;
2839 }
2840
2841 /*
2842 * We emerge from that loop when the initial negotiation is
2843 * over and we have selected an s_rdpkt function. Now pass
2844 * everything to s_rdpkt, and then pass the resulting packets
2845 * to the proper protocol handler.
2846 */
2847
2848 while (1) {
2849 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2850 if (ssh->frozen) {
2851 ssh_queue_incoming_data(ssh, &data, &datalen);
2852 /* This uses up all data and cannot cause anything interesting
2853 * to happen; indeed, for anything to happen at all, we must
2854 * return, so break out. */
2855 break;
2856 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2857 /* This uses up some or all data, and may freeze the
2858 * session. */
2859 ssh_process_queued_incoming_data(ssh);
2860 } else {
2861 /* This uses up some or all data, and may freeze the
2862 * session. */
2863 ssh_process_incoming_data(ssh, &data, &datalen);
2864 }
2865 /* FIXME this is probably EBW. */
2866 if (ssh->state == SSH_STATE_CLOSED)
2867 return;
2868 }
2869 /* We're out of data. Go and get some more. */
2870 crReturnV;
2871 }
2872 crFinishV;
2873 }
2874
2875 static int ssh_do_close(Ssh ssh, int notify_exit)
2876 {
2877 int ret = 0;
2878 struct ssh_channel *c;
2879
2880 ssh->state = SSH_STATE_CLOSED;
2881 expire_timer_context(ssh);
2882 if (ssh->s) {
2883 sk_close(ssh->s);
2884 ssh->s = NULL;
2885 if (notify_exit)
2886 notify_remote_exit(ssh->frontend);
2887 else
2888 ret = 1;
2889 }
2890 /*
2891 * Now we must shut down any port- and X-forwarded channels going
2892 * through this connection.
2893 */
2894 if (ssh->channels) {
2895 while (NULL != (c = index234(ssh->channels, 0))) {
2896 switch (c->type) {
2897 case CHAN_X11:
2898 x11_close(c->u.x11.s);
2899 break;
2900 case CHAN_SOCKDATA:
2901 case CHAN_SOCKDATA_DORMANT:
2902 pfd_close(c->u.pfd.s);
2903 break;
2904 }
2905 del234(ssh->channels, c); /* moving next one to index 0 */
2906 if (ssh->version == 2)
2907 bufchain_clear(&c->v.v2.outbuffer);
2908 sfree(c);
2909 }
2910 }
2911 /*
2912 * Go through port-forwardings, and close any associated
2913 * listening sockets.
2914 */
2915 if (ssh->portfwds) {
2916 struct ssh_portfwd *pf;
2917 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2918 /* Dispose of any listening socket. */
2919 if (pf->local)
2920 pfd_terminate(pf->local);
2921 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2922 free_portfwd(pf);
2923 }
2924 freetree234(ssh->portfwds);
2925 ssh->portfwds = NULL;
2926 }
2927
2928 return ret;
2929 }
2930
2931 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2932 const char *error_msg, int error_code)
2933 {
2934 Ssh ssh = (Ssh) plug;
2935 char addrbuf[256], *msg;
2936
2937 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2938
2939 if (type == 0)
2940 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2941 else
2942 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2943
2944 logevent(msg);
2945 sfree(msg);
2946 }
2947
2948 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2949 int calling_back)
2950 {
2951 Ssh ssh = (Ssh) plug;
2952 int need_notify = ssh_do_close(ssh, FALSE);
2953
2954 if (!error_msg) {
2955 if (!ssh->close_expected)
2956 error_msg = "Server unexpectedly closed network connection";
2957 else
2958 error_msg = "Server closed network connection";
2959 }
2960
2961 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2962 ssh->exitcode = 0;
2963
2964 if (need_notify)
2965 notify_remote_exit(ssh->frontend);
2966
2967 if (error_msg)
2968 logevent(error_msg);
2969 if (!ssh->close_expected || !ssh->clean_exit)
2970 connection_fatal(ssh->frontend, "%s", error_msg);
2971 return 0;
2972 }
2973
2974 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2975 {
2976 Ssh ssh = (Ssh) plug;
2977 ssh_gotdata(ssh, (unsigned char *)data, len);
2978 if (ssh->state == SSH_STATE_CLOSED) {
2979 ssh_do_close(ssh, TRUE);
2980 return 0;
2981 }
2982 return 1;
2983 }
2984
2985 static void ssh_sent(Plug plug, int bufsize)
2986 {
2987 Ssh ssh = (Ssh) plug;
2988 /*
2989 * If the send backlog on the SSH socket itself clears, we
2990 * should unthrottle the whole world if it was throttled.
2991 */
2992 if (bufsize < SSH_MAX_BACKLOG)
2993 ssh_throttle_all(ssh, 0, bufsize);
2994 }
2995
2996 /*
2997 * Connect to specified host and port.
2998 * Returns an error message, or NULL on success.
2999 * Also places the canonical host name into `realhost'. It must be
3000 * freed by the caller.
3001 */
3002 static const char *connect_to_host(Ssh ssh, char *host, int port,
3003 char **realhost, int nodelay, int keepalive)
3004 {
3005 static const struct plug_function_table fn_table = {
3006 ssh_log,
3007 ssh_closing,
3008 ssh_receive,
3009 ssh_sent,
3010 NULL
3011 };
3012
3013 SockAddr addr;
3014 const char *err;
3015 char *loghost;
3016 int addressfamily, sshprot;
3017
3018 loghost = conf_get_str(ssh->conf, CONF_loghost);
3019 if (*loghost) {
3020 char *colon;
3021
3022 ssh->savedhost = dupstr(loghost);
3023 ssh->savedport = 22; /* default ssh port */
3024
3025 /*
3026 * A colon suffix on savedhost also lets us affect
3027 * savedport.
3028 *
3029 * (FIXME: do something about IPv6 address literals here.)
3030 */
3031 colon = strrchr(ssh->savedhost, ':');
3032 if (colon) {
3033 *colon++ = '\0';
3034 if (*colon)
3035 ssh->savedport = atoi(colon);
3036 }
3037 } else {
3038 ssh->savedhost = dupstr(host);
3039 if (port < 0)
3040 port = 22; /* default ssh port */
3041 ssh->savedport = port;
3042 }
3043
3044 /*
3045 * Try to find host.
3046 */
3047 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3048 logeventf(ssh, "Looking up host \"%s\"%s", host,
3049 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3050 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3051 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3052 if ((err = sk_addr_error(addr)) != NULL) {
3053 sk_addr_free(addr);
3054 return err;
3055 }
3056 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3057
3058 /*
3059 * Open socket.
3060 */
3061 ssh->fn = &fn_table;
3062 ssh->s = new_connection(addr, *realhost, port,
3063 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3064 if ((err = sk_socket_error(ssh->s)) != NULL) {
3065 ssh->s = NULL;
3066 notify_remote_exit(ssh->frontend);
3067 return err;
3068 }
3069
3070 /*
3071 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3072 * send the version string too.
3073 */
3074 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3075 if (sshprot == 0)
3076 ssh->version = 1;
3077 if (sshprot == 3) {
3078 ssh->version = 2;
3079 ssh_send_verstring(ssh, NULL);
3080 }
3081
3082 /*
3083 * loghost, if configured, overrides realhost.
3084 */
3085 if (*loghost) {
3086 sfree(*realhost);
3087 *realhost = dupstr(loghost);
3088 }
3089
3090 return NULL;
3091 }
3092
3093 /*
3094 * Throttle or unthrottle the SSH connection.
3095 */
3096 static void ssh_throttle_conn(Ssh ssh, int adjust)
3097 {
3098 int old_count = ssh->conn_throttle_count;
3099 ssh->conn_throttle_count += adjust;
3100 assert(ssh->conn_throttle_count >= 0);
3101 if (ssh->conn_throttle_count && !old_count) {
3102 ssh_set_frozen(ssh, 1);
3103 } else if (!ssh->conn_throttle_count && old_count) {
3104 ssh_set_frozen(ssh, 0);
3105 }
3106 }
3107
3108 /*
3109 * Throttle or unthrottle _all_ local data streams (for when sends
3110 * on the SSH connection itself back up).
3111 */
3112 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3113 {
3114 int i;
3115 struct ssh_channel *c;
3116
3117 if (enable == ssh->throttled_all)
3118 return;
3119 ssh->throttled_all = enable;
3120 ssh->overall_bufsize = bufsize;
3121 if (!ssh->channels)
3122 return;
3123 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3124 switch (c->type) {
3125 case CHAN_MAINSESSION:
3126 /*
3127 * This is treated separately, outside the switch.
3128 */
3129 break;
3130 case CHAN_X11:
3131 x11_override_throttle(c->u.x11.s, enable);
3132 break;
3133 case CHAN_AGENT:
3134 /* Agent channels require no buffer management. */
3135 break;
3136 case CHAN_SOCKDATA:
3137 pfd_override_throttle(c->u.pfd.s, enable);
3138 break;
3139 }
3140 }
3141 }
3142
3143 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3144 {
3145 Ssh ssh = (Ssh) sshv;
3146
3147 ssh->agent_response = reply;
3148 ssh->agent_response_len = replylen;
3149
3150 if (ssh->version == 1)
3151 do_ssh1_login(ssh, NULL, -1, NULL);
3152 else
3153 do_ssh2_authconn(ssh, NULL, -1, NULL);
3154 }
3155
3156 static void ssh_dialog_callback(void *sshv, int ret)
3157 {
3158 Ssh ssh = (Ssh) sshv;
3159
3160 ssh->user_response = ret;
3161
3162 if (ssh->version == 1)
3163 do_ssh1_login(ssh, NULL, -1, NULL);
3164 else
3165 do_ssh2_transport(ssh, NULL, -1, NULL);
3166
3167 /*
3168 * This may have unfrozen the SSH connection, so do a
3169 * queued-data run.
3170 */
3171 ssh_process_queued_incoming_data(ssh);
3172 }
3173
3174 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3175 {
3176 struct ssh_channel *c = (struct ssh_channel *)cv;
3177 Ssh ssh = c->ssh;
3178 void *sentreply = reply;
3179
3180 if (!sentreply) {
3181 /* Fake SSH_AGENT_FAILURE. */
3182 sentreply = "\0\0\0\1\5";
3183 replylen = 5;
3184 }
3185 if (ssh->version == 2) {
3186 ssh2_add_channel_data(c, sentreply, replylen);
3187 ssh2_try_send(c);
3188 } else {
3189 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3190 PKT_INT, c->remoteid,
3191 PKT_INT, replylen,
3192 PKTT_DATA,
3193 PKT_DATA, sentreply, replylen,
3194 PKTT_OTHER,
3195 PKT_END);
3196 }
3197 if (reply)
3198 sfree(reply);
3199 }
3200
3201 /*
3202 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3203 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3204 * => log `wire_reason'.
3205 */
3206 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3207 int code, int clean_exit)
3208 {
3209 char *error;
3210 if (!client_reason)
3211 client_reason = wire_reason;
3212 if (client_reason)
3213 error = dupprintf("Disconnected: %s", client_reason);
3214 else
3215 error = dupstr("Disconnected");
3216 if (wire_reason) {
3217 if (ssh->version == 1) {
3218 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3219 PKT_END);
3220 } else if (ssh->version == 2) {
3221 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3222 ssh2_pkt_adduint32(pktout, code);
3223 ssh2_pkt_addstring(pktout, wire_reason);
3224 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3225 ssh2_pkt_send_noqueue(ssh, pktout);
3226 }
3227 }
3228 ssh->close_expected = TRUE;
3229 ssh->clean_exit = clean_exit;
3230 ssh_closing((Plug)ssh, error, 0, 0);
3231 sfree(error);
3232 }
3233
3234 /*
3235 * Handle the key exchange and user authentication phases.
3236 */
3237 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3238 struct Packet *pktin)
3239 {
3240 int i, j, ret;
3241 unsigned char cookie[8], *ptr;
3242 struct RSAKey servkey, hostkey;
3243 struct MD5Context md5c;
3244 struct do_ssh1_login_state {
3245 int len;
3246 unsigned char *rsabuf, *keystr1, *keystr2;
3247 unsigned long supported_ciphers_mask, supported_auths_mask;
3248 int tried_publickey, tried_agent;
3249 int tis_auth_refused, ccard_auth_refused;
3250 unsigned char session_id[16];
3251 int cipher_type;
3252 void *publickey_blob;
3253 int publickey_bloblen;
3254 char *publickey_comment;
3255 int publickey_encrypted;
3256 prompts_t *cur_prompt;
3257 char c;
3258 int pwpkt_type;
3259 unsigned char request[5], *response, *p;
3260 int responselen;
3261 int keyi, nkeys;
3262 int authed;
3263 struct RSAKey key;
3264 Bignum challenge;
3265 char *commentp;
3266 int commentlen;
3267 int dlgret;
3268 Filename *keyfile;
3269 };
3270 crState(do_ssh1_login_state);
3271
3272 crBegin(ssh->do_ssh1_login_crstate);
3273
3274 if (!pktin)
3275 crWaitUntil(pktin);
3276
3277 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3278 bombout(("Public key packet not received"));
3279 crStop(0);
3280 }
3281
3282 logevent("Received public keys");
3283
3284 ptr = ssh_pkt_getdata(pktin, 8);
3285 if (!ptr) {
3286 bombout(("SSH-1 public key packet stopped before random cookie"));
3287 crStop(0);
3288 }
3289 memcpy(cookie, ptr, 8);
3290
3291 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3292 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3293 bombout(("Failed to read SSH-1 public keys from public key packet"));
3294 crStop(0);
3295 }
3296
3297 /*
3298 * Log the host key fingerprint.
3299 */
3300 {
3301 char logmsg[80];
3302 logevent("Host key fingerprint is:");
3303 strcpy(logmsg, " ");
3304 hostkey.comment = NULL;
3305 rsa_fingerprint(logmsg + strlen(logmsg),
3306 sizeof(logmsg) - strlen(logmsg), &hostkey);
3307 logevent(logmsg);
3308 }
3309
3310 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3311 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3312 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3313 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3314 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3315
3316 ssh->v1_local_protoflags =
3317 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3318 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3319
3320 MD5Init(&md5c);
3321 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3322 MD5Update(&md5c, s->keystr1, servkey.bytes);
3323 MD5Update(&md5c, cookie, 8);
3324 MD5Final(s->session_id, &md5c);
3325
3326 for (i = 0; i < 32; i++)
3327 ssh->session_key[i] = random_byte();
3328
3329 /*
3330 * Verify that the `bits' and `bytes' parameters match.
3331 */
3332 if (hostkey.bits > hostkey.bytes * 8 ||
3333 servkey.bits > servkey.bytes * 8) {
3334 bombout(("SSH-1 public keys were badly formatted"));
3335 crStop(0);
3336 }
3337
3338 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3339
3340 s->rsabuf = snewn(s->len, unsigned char);
3341
3342 /*
3343 * Verify the host key.
3344 */
3345 {
3346 /*
3347 * First format the key into a string.
3348 */
3349 int len = rsastr_len(&hostkey);
3350 char fingerprint[100];
3351 char *keystr = snewn(len, char);
3352 rsastr_fmt(keystr, &hostkey);
3353 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3354
3355 ssh_set_frozen(ssh, 1);
3356 s->dlgret = verify_ssh_host_key(ssh->frontend,
3357 ssh->savedhost, ssh->savedport,
3358 "rsa", keystr, fingerprint,
3359 ssh_dialog_callback, ssh);
3360 sfree(keystr);
3361 if (s->dlgret < 0) {
3362 do {
3363 crReturn(0);
3364 if (pktin) {
3365 bombout(("Unexpected data from server while waiting"
3366 " for user host key response"));
3367 crStop(0);
3368 }
3369 } while (pktin || inlen > 0);
3370 s->dlgret = ssh->user_response;
3371 }
3372 ssh_set_frozen(ssh, 0);
3373
3374 if (s->dlgret == 0) {
3375 ssh_disconnect(ssh, "User aborted at host key verification",
3376 NULL, 0, TRUE);
3377 crStop(0);
3378 }
3379 }
3380
3381 for (i = 0; i < 32; i++) {
3382 s->rsabuf[i] = ssh->session_key[i];
3383 if (i < 16)
3384 s->rsabuf[i] ^= s->session_id[i];
3385 }
3386
3387 if (hostkey.bytes > servkey.bytes) {
3388 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3389 if (ret)
3390 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3391 } else {
3392 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3393 if (ret)
3394 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3395 }
3396 if (!ret) {
3397 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3398 crStop(0);
3399 }
3400
3401 logevent("Encrypted session key");
3402
3403 {
3404 int cipher_chosen = 0, warn = 0;
3405 char *cipher_string = NULL;
3406 int i;
3407 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3408 int next_cipher = conf_get_int_int(ssh->conf,
3409 CONF_ssh_cipherlist, i);
3410 if (next_cipher == CIPHER_WARN) {
3411 /* If/when we choose a cipher, warn about it */
3412 warn = 1;
3413 } else if (next_cipher == CIPHER_AES) {
3414 /* XXX Probably don't need to mention this. */
3415 logevent("AES not supported in SSH-1, skipping");
3416 } else {
3417 switch (next_cipher) {
3418 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3419 cipher_string = "3DES"; break;
3420 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3421 cipher_string = "Blowfish"; break;
3422 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3423 cipher_string = "single-DES"; break;
3424 }
3425 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3426 cipher_chosen = 1;
3427 }
3428 }
3429 if (!cipher_chosen) {
3430 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3431 bombout(("Server violates SSH-1 protocol by not "
3432 "supporting 3DES encryption"));
3433 else
3434 /* shouldn't happen */
3435 bombout(("No supported ciphers found"));
3436 crStop(0);
3437 }
3438
3439 /* Warn about chosen cipher if necessary. */
3440 if (warn) {
3441 ssh_set_frozen(ssh, 1);
3442 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3443 ssh_dialog_callback, ssh);
3444 if (s->dlgret < 0) {
3445 do {
3446 crReturn(0);
3447 if (pktin) {
3448 bombout(("Unexpected data from server while waiting"
3449 " for user response"));
3450 crStop(0);
3451 }
3452 } while (pktin || inlen > 0);
3453 s->dlgret = ssh->user_response;
3454 }
3455 ssh_set_frozen(ssh, 0);
3456 if (s->dlgret == 0) {
3457 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3458 0, TRUE);
3459 crStop(0);
3460 }
3461 }
3462 }
3463
3464 switch (s->cipher_type) {
3465 case SSH_CIPHER_3DES:
3466 logevent("Using 3DES encryption");
3467 break;
3468 case SSH_CIPHER_DES:
3469 logevent("Using single-DES encryption");
3470 break;
3471 case SSH_CIPHER_BLOWFISH:
3472 logevent("Using Blowfish encryption");
3473 break;
3474 }
3475
3476 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3477 PKT_CHAR, s->cipher_type,
3478 PKT_DATA, cookie, 8,
3479 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3480 PKT_DATA, s->rsabuf, s->len,
3481 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3482
3483 logevent("Trying to enable encryption...");
3484
3485 sfree(s->rsabuf);
3486
3487 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3488 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3489 &ssh_3des);
3490 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3491 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3492 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3493
3494 ssh->crcda_ctx = crcda_make_context();
3495 logevent("Installing CRC compensation attack detector");
3496
3497 if (servkey.modulus) {
3498 sfree(servkey.modulus);
3499 servkey.modulus = NULL;
3500 }
3501 if (servkey.exponent) {
3502 sfree(servkey.exponent);
3503 servkey.exponent = NULL;
3504 }
3505 if (hostkey.modulus) {
3506 sfree(hostkey.modulus);
3507 hostkey.modulus = NULL;
3508 }
3509 if (hostkey.exponent) {
3510 sfree(hostkey.exponent);
3511 hostkey.exponent = NULL;
3512 }
3513 crWaitUntil(pktin);
3514
3515 if (pktin->type != SSH1_SMSG_SUCCESS) {
3516 bombout(("Encryption not successfully enabled"));
3517 crStop(0);
3518 }
3519
3520 logevent("Successfully started encryption");
3521
3522 fflush(stdout); /* FIXME eh? */
3523 {
3524 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3525 int ret; /* need not be kept over crReturn */
3526 s->cur_prompt = new_prompts(ssh->frontend);
3527 s->cur_prompt->to_server = TRUE;
3528 s->cur_prompt->name = dupstr("SSH login name");
3529 /* 512 is an arbitrary upper limit on username size */
3530 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
3531 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3532 while (ret < 0) {
3533 ssh->send_ok = 1;
3534 crWaitUntil(!pktin);
3535 ret = get_userpass_input(s->cur_prompt, in, inlen);
3536 ssh->send_ok = 0;
3537 }
3538 if (!ret) {
3539 /*
3540 * Failed to get a username. Terminate.
3541 */
3542 free_prompts(s->cur_prompt);
3543 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3544 crStop(0);
3545 }
3546 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3547 free_prompts(s->cur_prompt);
3548 }
3549
3550 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3551 {
3552 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3553 logevent(userlog);
3554 if (flags & FLAG_INTERACTIVE &&
3555 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3556 c_write_str(ssh, userlog);
3557 c_write_str(ssh, "\r\n");
3558 }
3559 sfree(userlog);
3560 }
3561 }
3562
3563 crWaitUntil(pktin);
3564
3565 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3566 /* We must not attempt PK auth. Pretend we've already tried it. */
3567 s->tried_publickey = s->tried_agent = 1;
3568 } else {
3569 s->tried_publickey = s->tried_agent = 0;
3570 }
3571 s->tis_auth_refused = s->ccard_auth_refused = 0;
3572 /*
3573 * Load the public half of any configured keyfile for later use.
3574 */
3575 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3576 if (!filename_is_null(*s->keyfile)) {
3577 int keytype;
3578 logeventf(ssh, "Reading private key file \"%.150s\"",
3579 filename_to_str(s->keyfile));
3580 keytype = key_type(s->keyfile);
3581 if (keytype == SSH_KEYTYPE_SSH1) {
3582 const char *error;
3583 if (rsakey_pubblob(s->keyfile,
3584 &s->publickey_blob, &s->publickey_bloblen,
3585 &s->publickey_comment, &error)) {
3586 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3587 NULL);
3588 } else {
3589 char *msgbuf;
3590 logeventf(ssh, "Unable to load private key (%s)", error);
3591 msgbuf = dupprintf("Unable to load private key file "
3592 "\"%.150s\" (%s)\r\n",
3593 filename_to_str(s->keyfile),
3594 error);
3595 c_write_str(ssh, msgbuf);
3596 sfree(msgbuf);
3597 s->publickey_blob = NULL;
3598 }
3599 } else {
3600 char *msgbuf;
3601 logeventf(ssh, "Unable to use this key file (%s)",
3602 key_type_to_str(keytype));
3603 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3604 " (%s)\r\n",
3605 filename_to_str(s->keyfile),
3606 key_type_to_str(keytype));
3607 c_write_str(ssh, msgbuf);
3608 sfree(msgbuf);
3609 s->publickey_blob = NULL;
3610 }
3611 } else
3612 s->publickey_blob = NULL;
3613
3614 while (pktin->type == SSH1_SMSG_FAILURE) {
3615 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3616
3617 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3618 /*
3619 * Attempt RSA authentication using Pageant.
3620 */
3621 void *r;
3622
3623 s->authed = FALSE;
3624 s->tried_agent = 1;
3625 logevent("Pageant is running. Requesting keys.");
3626
3627 /* Request the keys held by the agent. */
3628 PUT_32BIT(s->request, 1);
3629 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3630 if (!agent_query(s->request, 5, &r, &s->responselen,
3631 ssh_agent_callback, ssh)) {
3632 do {
3633 crReturn(0);
3634 if (pktin) {
3635 bombout(("Unexpected data from server while waiting"
3636 " for agent response"));
3637 crStop(0);
3638 }
3639 } while (pktin || inlen > 0);
3640 r = ssh->agent_response;
3641 s->responselen = ssh->agent_response_len;
3642 }
3643 s->response = (unsigned char *) r;
3644 if (s->response && s->responselen >= 5 &&
3645 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3646 s->p = s->response + 5;
3647 s->nkeys = GET_32BIT(s->p);
3648 s->p += 4;
3649 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3650 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3651 unsigned char *pkblob = s->p;
3652 s->p += 4;
3653 {
3654 int n, ok = FALSE;
3655 do { /* do while (0) to make breaking easy */
3656 n = ssh1_read_bignum
3657 (s->p, s->responselen-(s->p-s->response),
3658 &s->key.exponent);
3659 if (n < 0)
3660 break;
3661 s->p += n;
3662 n = ssh1_read_bignum
3663 (s->p, s->responselen-(s->p-s->response),
3664 &s->key.modulus);
3665 if (n < 0)
3666 break;
3667 s->p += n;
3668 if (s->responselen - (s->p-s->response) < 4)
3669 break;
3670 s->commentlen = GET_32BIT(s->p);
3671 s->p += 4;
3672 if (s->responselen - (s->p-s->response) <
3673 s->commentlen)
3674 break;
3675 s->commentp = (char *)s->p;
3676 s->p += s->commentlen;
3677 ok = TRUE;
3678 } while (0);
3679 if (!ok) {
3680 logevent("Pageant key list packet was truncated");
3681 break;
3682 }
3683 }
3684 if (s->publickey_blob) {
3685 if (!memcmp(pkblob, s->publickey_blob,
3686 s->publickey_bloblen)) {
3687 logeventf(ssh, "Pageant key #%d matches "
3688 "configured key file", s->keyi);
3689 s->tried_publickey = 1;
3690 } else
3691 /* Skip non-configured key */
3692 continue;
3693 }
3694 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3695 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3696 PKT_BIGNUM, s->key.modulus, PKT_END);
3697 crWaitUntil(pktin);
3698 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3699 logevent("Key refused");
3700 continue;
3701 }
3702 logevent("Received RSA challenge");
3703 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3704 bombout(("Server's RSA challenge was badly formatted"));
3705 crStop(0);
3706 }
3707
3708 {
3709 char *agentreq, *q, *ret;
3710 void *vret;
3711 int len, retlen;
3712 len = 1 + 4; /* message type, bit count */
3713 len += ssh1_bignum_length(s->key.exponent);
3714 len += ssh1_bignum_length(s->key.modulus);
3715 len += ssh1_bignum_length(s->challenge);
3716 len += 16; /* session id */
3717 len += 4; /* response format */
3718 agentreq = snewn(4 + len, char);
3719 PUT_32BIT(agentreq, len);
3720 q = agentreq + 4;
3721 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3722 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3723 q += 4;
3724 q += ssh1_write_bignum(q, s->key.exponent);
3725 q += ssh1_write_bignum(q, s->key.modulus);
3726 q += ssh1_write_bignum(q, s->challenge);
3727 memcpy(q, s->session_id, 16);
3728 q += 16;
3729 PUT_32BIT(q, 1); /* response format */
3730 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3731 ssh_agent_callback, ssh)) {
3732 sfree(agentreq);
3733 do {
3734 crReturn(0);
3735 if (pktin) {
3736 bombout(("Unexpected data from server"
3737 " while waiting for agent"
3738 " response"));
3739 crStop(0);
3740 }
3741 } while (pktin || inlen > 0);
3742 vret = ssh->agent_response;
3743 retlen = ssh->agent_response_len;
3744 } else
3745 sfree(agentreq);
3746 ret = vret;
3747 if (ret) {
3748 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3749 logevent("Sending Pageant's response");
3750 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3751 PKT_DATA, ret + 5, 16,
3752 PKT_END);
3753 sfree(ret);
3754 crWaitUntil(pktin);
3755 if (pktin->type == SSH1_SMSG_SUCCESS) {
3756 logevent
3757 ("Pageant's response accepted");
3758 if (flags & FLAG_VERBOSE) {
3759 c_write_str(ssh, "Authenticated using"
3760 " RSA key \"");
3761 c_write(ssh, s->commentp,
3762 s->commentlen);
3763 c_write_str(ssh, "\" from agent\r\n");
3764 }
3765 s->authed = TRUE;
3766 } else
3767 logevent
3768 ("Pageant's response not accepted");
3769 } else {
3770 logevent
3771 ("Pageant failed to answer challenge");
3772 sfree(ret);
3773 }
3774 } else {
3775 logevent("No reply received from Pageant");
3776 }
3777 }
3778 freebn(s->key.exponent);
3779 freebn(s->key.modulus);
3780 freebn(s->challenge);
3781 if (s->authed)
3782 break;
3783 }
3784 sfree(s->response);
3785 if (s->publickey_blob && !s->tried_publickey)
3786 logevent("Configured key file not in Pageant");
3787 } else {
3788 logevent("Failed to get reply from Pageant");
3789 }
3790 if (s->authed)
3791 break;
3792 }
3793 if (s->publickey_blob && !s->tried_publickey) {
3794 /*
3795 * Try public key authentication with the specified
3796 * key file.
3797 */
3798 int got_passphrase; /* need not be kept over crReturn */
3799 if (flags & FLAG_VERBOSE)
3800 c_write_str(ssh, "Trying public key authentication.\r\n");
3801 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3802 logeventf(ssh, "Trying public key \"%s\"",
3803 filename_to_str(s->keyfile));
3804 s->tried_publickey = 1;
3805 got_passphrase = FALSE;
3806 while (!got_passphrase) {
3807 /*
3808 * Get a passphrase, if necessary.
3809 */
3810 char *passphrase = NULL; /* only written after crReturn */
3811 const char *error;
3812 if (!s->publickey_encrypted) {
3813 if (flags & FLAG_VERBOSE)
3814 c_write_str(ssh, "No passphrase required.\r\n");
3815 passphrase = NULL;
3816 } else {
3817 int ret; /* need not be kept over crReturn */
3818 s->cur_prompt = new_prompts(ssh->frontend);
3819 s->cur_prompt->to_server = FALSE;
3820 s->cur_prompt->name = dupstr("SSH key passphrase");
3821 add_prompt(s->cur_prompt,
3822 dupprintf("Passphrase for key \"%.100s\": ",
3823 s->publickey_comment),
3824 FALSE, SSH_MAX_PASSWORD_LEN);
3825 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3826 while (ret < 0) {
3827 ssh->send_ok = 1;
3828 crWaitUntil(!pktin);
3829 ret = get_userpass_input(s->cur_prompt, in, inlen);
3830 ssh->send_ok = 0;
3831 }
3832 if (!ret) {
3833 /* Failed to get a passphrase. Terminate. */
3834 free_prompts(s->cur_prompt);
3835 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3836 0, TRUE);
3837 crStop(0);
3838 }
3839 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3840 free_prompts(s->cur_prompt);
3841 }
3842 /*
3843 * Try decrypting key with passphrase.
3844 */
3845 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3846 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3847 &error);
3848 if (passphrase) {
3849 memset(passphrase, 0, strlen(passphrase));
3850 sfree(passphrase);
3851 }
3852 if (ret == 1) {
3853 /* Correct passphrase. */
3854 got_passphrase = TRUE;
3855 } else if (ret == 0) {
3856 c_write_str(ssh, "Couldn't load private key from ");
3857 c_write_str(ssh, filename_to_str(s->keyfile));
3858 c_write_str(ssh, " (");
3859 c_write_str(ssh, error);
3860 c_write_str(ssh, ").\r\n");
3861 got_passphrase = FALSE;
3862 break; /* go and try something else */
3863 } else if (ret == -1) {
3864 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3865 got_passphrase = FALSE;
3866 /* and try again */
3867 } else {
3868 assert(0 && "unexpected return from loadrsakey()");
3869 got_passphrase = FALSE; /* placate optimisers */
3870 }
3871 }
3872
3873 if (got_passphrase) {
3874
3875 /*
3876 * Send a public key attempt.
3877 */
3878 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3879 PKT_BIGNUM, s->key.modulus, PKT_END);
3880
3881 crWaitUntil(pktin);
3882 if (pktin->type == SSH1_SMSG_FAILURE) {
3883 c_write_str(ssh, "Server refused our public key.\r\n");
3884 continue; /* go and try something else */
3885 }
3886 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3887 bombout(("Bizarre response to offer of public key"));
3888 crStop(0);
3889 }
3890
3891 {
3892 int i;
3893 unsigned char buffer[32];
3894 Bignum challenge, response;
3895
3896 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3897 bombout(("Server's RSA challenge was badly formatted"));
3898 crStop(0);
3899 }
3900 response = rsadecrypt(challenge, &s->key);
3901 freebn(s->key.private_exponent);/* burn the evidence */
3902
3903 for (i = 0; i < 32; i++) {
3904 buffer[i] = bignum_byte(response, 31 - i);
3905 }
3906
3907 MD5Init(&md5c);
3908 MD5Update(&md5c, buffer, 32);
3909 MD5Update(&md5c, s->session_id, 16);
3910 MD5Final(buffer, &md5c);
3911
3912 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3913 PKT_DATA, buffer, 16, PKT_END);
3914
3915 freebn(challenge);
3916 freebn(response);
3917 }
3918
3919 crWaitUntil(pktin);
3920 if (pktin->type == SSH1_SMSG_FAILURE) {
3921 if (flags & FLAG_VERBOSE)
3922 c_write_str(ssh, "Failed to authenticate with"
3923 " our public key.\r\n");
3924 continue; /* go and try something else */
3925 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3926 bombout(("Bizarre response to RSA authentication response"));
3927 crStop(0);
3928 }
3929
3930 break; /* we're through! */
3931 }
3932
3933 }
3934
3935 /*
3936 * Otherwise, try various forms of password-like authentication.
3937 */
3938 s->cur_prompt = new_prompts(ssh->frontend);
3939
3940 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3941 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3942 !s->tis_auth_refused) {
3943 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3944 logevent("Requested TIS authentication");
3945 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3946 crWaitUntil(pktin);
3947 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3948 logevent("TIS authentication declined");
3949 if (flags & FLAG_INTERACTIVE)
3950 c_write_str(ssh, "TIS authentication refused.\r\n");
3951 s->tis_auth_refused = 1;
3952 continue;
3953 } else {
3954 char *challenge;
3955 int challengelen;
3956 char *instr_suf, *prompt;
3957
3958 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3959 if (!challenge) {
3960 bombout(("TIS challenge packet was badly formed"));
3961 crStop(0);
3962 }
3963 logevent("Received TIS challenge");
3964 s->cur_prompt->to_server = TRUE;
3965 s->cur_prompt->name = dupstr("SSH TIS authentication");
3966 /* Prompt heuristic comes from OpenSSH */
3967 if (memchr(challenge, '\n', challengelen)) {
3968 instr_suf = dupstr("");
3969 prompt = dupprintf("%.*s", challengelen, challenge);
3970 } else {
3971 instr_suf = dupprintf("%.*s", challengelen, challenge);
3972 prompt = dupstr("Response: ");
3973 }
3974 s->cur_prompt->instruction =
3975 dupprintf("Using TIS authentication.%s%s",
3976 (*instr_suf) ? "\n" : "",
3977 instr_suf);
3978 s->cur_prompt->instr_reqd = TRUE;
3979 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3980 sfree(instr_suf);
3981 }
3982 }
3983 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3984 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3985 !s->ccard_auth_refused) {
3986 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3987 logevent("Requested CryptoCard authentication");
3988 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3989 crWaitUntil(pktin);
3990 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3991 logevent("CryptoCard authentication declined");
3992 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3993 s->ccard_auth_refused = 1;
3994 continue;
3995 } else {
3996 char *challenge;
3997 int challengelen;
3998 char *instr_suf, *prompt;
3999
4000 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4001 if (!challenge) {
4002 bombout(("CryptoCard challenge packet was badly formed"));
4003 crStop(0);
4004 }
4005 logevent("Received CryptoCard challenge");
4006 s->cur_prompt->to_server = TRUE;
4007 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4008 s->cur_prompt->name_reqd = FALSE;
4009 /* Prompt heuristic comes from OpenSSH */
4010 if (memchr(challenge, '\n', challengelen)) {
4011 instr_suf = dupstr("");
4012 prompt = dupprintf("%.*s", challengelen, challenge);
4013 } else {
4014 instr_suf = dupprintf("%.*s", challengelen, challenge);
4015 prompt = dupstr("Response: ");
4016 }
4017 s->cur_prompt->instruction =
4018 dupprintf("Using CryptoCard authentication.%s%s",
4019 (*instr_suf) ? "\n" : "",
4020 instr_suf);
4021 s->cur_prompt->instr_reqd = TRUE;
4022 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
4023 sfree(instr_suf);
4024 }
4025 }
4026 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4027 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4028 bombout(("No supported authentication methods available"));
4029 crStop(0);
4030 }
4031 s->cur_prompt->to_server = TRUE;
4032 s->cur_prompt->name = dupstr("SSH password");
4033 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4034 ssh->username, ssh->savedhost),
4035 FALSE, SSH_MAX_PASSWORD_LEN);
4036 }
4037
4038 /*
4039 * Show password prompt, having first obtained it via a TIS
4040 * or CryptoCard exchange if we're doing TIS or CryptoCard
4041 * authentication.
4042 */
4043 {
4044 int ret; /* need not be kept over crReturn */
4045 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4046 while (ret < 0) {
4047 ssh->send_ok = 1;
4048 crWaitUntil(!pktin);
4049 ret = get_userpass_input(s->cur_prompt, in, inlen);
4050 ssh->send_ok = 0;
4051 }
4052 if (!ret) {
4053 /*
4054 * Failed to get a password (for example
4055 * because one was supplied on the command line
4056 * which has already failed to work). Terminate.
4057 */
4058 free_prompts(s->cur_prompt);
4059 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4060 crStop(0);
4061 }
4062 }
4063
4064 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4065 /*
4066 * Defence against traffic analysis: we send a
4067 * whole bunch of packets containing strings of
4068 * different lengths. One of these strings is the
4069 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4070 * The others are all random data in
4071 * SSH1_MSG_IGNORE packets. This way a passive
4072 * listener can't tell which is the password, and
4073 * hence can't deduce the password length.
4074 *
4075 * Anybody with a password length greater than 16
4076 * bytes is going to have enough entropy in their
4077 * password that a listener won't find it _that_
4078 * much help to know how long it is. So what we'll
4079 * do is:
4080 *
4081 * - if password length < 16, we send 15 packets
4082 * containing string lengths 1 through 15
4083 *
4084 * - otherwise, we let N be the nearest multiple
4085 * of 8 below the password length, and send 8
4086 * packets containing string lengths N through
4087 * N+7. This won't obscure the order of
4088 * magnitude of the password length, but it will
4089 * introduce a bit of extra uncertainty.
4090 *
4091 * A few servers can't deal with SSH1_MSG_IGNORE, at
4092 * least in this context. For these servers, we need
4093 * an alternative defence. We make use of the fact
4094 * that the password is interpreted as a C string:
4095 * so we can append a NUL, then some random data.
4096 *
4097 * A few servers can deal with neither SSH1_MSG_IGNORE
4098 * here _nor_ a padded password string.
4099 * For these servers we are left with no defences
4100 * against password length sniffing.
4101 */
4102 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4103 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4104 /*
4105 * The server can deal with SSH1_MSG_IGNORE, so
4106 * we can use the primary defence.
4107 */
4108 int bottom, top, pwlen, i;
4109 char *randomstr;
4110
4111 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4112 if (pwlen < 16) {
4113 bottom = 0; /* zero length passwords are OK! :-) */
4114 top = 15;
4115 } else {
4116 bottom = pwlen & ~7;
4117 top = bottom + 7;
4118 }
4119
4120 assert(pwlen >= bottom && pwlen <= top);
4121
4122 randomstr = snewn(top + 1, char);
4123
4124 for (i = bottom; i <= top; i++) {
4125 if (i == pwlen) {
4126 defer_packet(ssh, s->pwpkt_type,
4127 PKTT_PASSWORD, PKT_STR,
4128 s->cur_prompt->prompts[0]->result,
4129 PKTT_OTHER, PKT_END);
4130 } else {
4131 for (j = 0; j < i; j++) {
4132 do {
4133 randomstr[j] = random_byte();
4134 } while (randomstr[j] == '\0');
4135 }
4136 randomstr[i] = '\0';
4137 defer_packet(ssh, SSH1_MSG_IGNORE,
4138 PKT_STR, randomstr, PKT_END);
4139 }
4140 }
4141 logevent("Sending password with camouflage packets");
4142 ssh_pkt_defersend(ssh);
4143 sfree(randomstr);
4144 }
4145 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4146 /*
4147 * The server can't deal with SSH1_MSG_IGNORE
4148 * but can deal with padded passwords, so we
4149 * can use the secondary defence.
4150 */
4151 char string[64];
4152 char *ss;
4153 int len;
4154
4155 len = strlen(s->cur_prompt->prompts[0]->result);
4156 if (len < sizeof(string)) {
4157 ss = string;
4158 strcpy(string, s->cur_prompt->prompts[0]->result);
4159 len++; /* cover the zero byte */
4160 while (len < sizeof(string)) {
4161 string[len++] = (char) random_byte();
4162 }
4163 } else {
4164 ss = s->cur_prompt->prompts[0]->result;
4165 }
4166 logevent("Sending length-padded password");
4167 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4168 PKT_INT, len, PKT_DATA, ss, len,
4169 PKTT_OTHER, PKT_END);
4170 } else {
4171 /*
4172 * The server is believed unable to cope with
4173 * any of our password camouflage methods.
4174 */
4175 int len;
4176 len = strlen(s->cur_prompt->prompts[0]->result);
4177 logevent("Sending unpadded password");
4178 send_packet(ssh, s->pwpkt_type,
4179 PKTT_PASSWORD, PKT_INT, len,
4180 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4181 PKTT_OTHER, PKT_END);
4182 }
4183 } else {
4184 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4185 PKT_STR, s->cur_prompt->prompts[0]->result,
4186 PKTT_OTHER, PKT_END);
4187 }
4188 logevent("Sent password");
4189 free_prompts(s->cur_prompt);
4190 crWaitUntil(pktin);
4191 if (pktin->type == SSH1_SMSG_FAILURE) {
4192 if (flags & FLAG_VERBOSE)
4193 c_write_str(ssh, "Access denied\r\n");
4194 logevent("Authentication refused");
4195 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4196 bombout(("Strange packet received, type %d", pktin->type));
4197 crStop(0);
4198 }
4199 }
4200
4201 /* Clear up */
4202 if (s->publickey_blob) {
4203 sfree(s->publickey_blob);
4204 sfree(s->publickey_comment);
4205 }
4206
4207 logevent("Authentication successful");
4208
4209 crFinish(1);
4210 }
4211
4212 static void ssh_channel_try_eof(struct ssh_channel *c)
4213 {
4214 Ssh ssh = c->ssh;
4215 assert(c->pending_eof); /* precondition for calling us */
4216 if (c->halfopen)
4217 return; /* can't close: not even opened yet */
4218 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4219 return; /* can't send EOF: pending outgoing data */
4220
4221 if (ssh->version == 1) {
4222 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4223 PKT_END);
4224 c->closes |= CLOSES_SENT_EOF;
4225 } else {
4226 struct Packet *pktout;
4227 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4228 ssh2_pkt_adduint32(pktout, c->remoteid);
4229 ssh2_pkt_send(ssh, pktout);
4230 c->closes |= CLOSES_SENT_EOF;
4231 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4232 /*
4233 * Also send MSG_CLOSE.
4234 */
4235 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4236 ssh2_pkt_adduint32(pktout, c->remoteid);
4237 ssh2_pkt_send(ssh, pktout);
4238 c->closes |= CLOSES_SENT_CLOSE;
4239 }
4240 }
4241 c->pending_eof = FALSE; /* we've sent it now */
4242 }
4243
4244 void sshfwd_write_eof(struct ssh_channel *c)
4245 {
4246 Ssh ssh = c->ssh;
4247
4248 if (ssh->state == SSH_STATE_CLOSED)
4249 return;
4250
4251 if (c->closes & CLOSES_SENT_EOF)
4252 return;
4253
4254 c->pending_eof = TRUE;
4255 ssh_channel_try_eof(c);
4256 }
4257
4258 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4259 {
4260 Ssh ssh = c->ssh;
4261
4262 if (ssh->state == SSH_STATE_CLOSED)
4263 return 0;
4264
4265 if (ssh->version == 1) {
4266 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4267 PKT_INT, c->remoteid,
4268 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4269 PKTT_OTHER, PKT_END);
4270 /*
4271 * In SSH-1 we can return 0 here - implying that forwarded
4272 * connections are never individually throttled - because
4273 * the only circumstance that can cause throttling will be
4274 * the whole SSH connection backing up, in which case
4275 * _everything_ will be throttled as a whole.
4276 */
4277 return 0;
4278 } else {
4279 ssh2_add_channel_data(c, buf, len);
4280 return ssh2_try_send(c);
4281 }
4282 }
4283
4284 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4285 {
4286 Ssh ssh = c->ssh;
4287 int buflimit;
4288
4289 if (ssh->state == SSH_STATE_CLOSED)
4290 return;
4291
4292 if (ssh->version == 1) {
4293 buflimit = SSH1_BUFFER_LIMIT;
4294 } else {
4295 buflimit = c->v.v2.locmaxwin;
4296 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4297 }
4298 if (c->throttling_conn && bufsize <= buflimit) {
4299 c->throttling_conn = 0;
4300 ssh_throttle_conn(ssh, -1);
4301 }
4302 }
4303
4304 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4305 {
4306 struct queued_handler *qh = ssh->qhead;
4307
4308 assert(qh != NULL);
4309
4310 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4311
4312 if (qh->msg1 > 0) {
4313 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4314 ssh->packet_dispatch[qh->msg1] = NULL;
4315 }
4316 if (qh->msg2 > 0) {
4317 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4318 ssh->packet_dispatch[qh->msg2] = NULL;
4319 }
4320
4321 if (qh->next) {
4322 ssh->qhead = qh->next;
4323
4324 if (ssh->qhead->msg1 > 0) {
4325 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4326 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4327 }
4328 if (ssh->qhead->msg2 > 0) {
4329 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4330 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4331 }
4332 } else {
4333 ssh->qhead = ssh->qtail = NULL;
4334 ssh->packet_dispatch[pktin->type] = NULL;
4335 }
4336
4337 qh->handler(ssh, pktin, qh->ctx);
4338
4339 sfree(qh);
4340 }
4341
4342 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4343 chandler_fn_t handler, void *ctx)
4344 {
4345 struct queued_handler *qh;
4346
4347 qh = snew(struct queued_handler);
4348 qh->msg1 = msg1;
4349 qh->msg2 = msg2;
4350 qh->handler = handler;
4351 qh->ctx = ctx;
4352 qh->next = NULL;
4353
4354 if (ssh->qtail == NULL) {
4355 ssh->qhead = qh;
4356
4357 if (qh->msg1 > 0) {
4358 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4359 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4360 }
4361 if (qh->msg2 > 0) {
4362 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4363 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4364 }
4365 } else {
4366 ssh->qtail->next = qh;
4367 }
4368 ssh->qtail = qh;
4369 }
4370
4371 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4372 {
4373 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4374
4375 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4376 SSH2_MSG_REQUEST_SUCCESS)) {
4377 logeventf(ssh, "Remote port forwarding from %s enabled",
4378 pf->sportdesc);
4379 } else {
4380 logeventf(ssh, "Remote port forwarding from %s refused",
4381 pf->sportdesc);
4382
4383 rpf = del234(ssh->rportfwds, pf);
4384 assert(rpf == pf);
4385 pf->pfrec->remote = NULL;
4386 free_rportfwd(pf);
4387 }
4388 }
4389
4390 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4391 {
4392 struct ssh_portfwd *epf;
4393 int i;
4394 char *key, *val;
4395
4396 if (!ssh->portfwds) {
4397 ssh->portfwds = newtree234(ssh_portcmp);
4398 } else {
4399 /*
4400 * Go through the existing port forwardings and tag them
4401 * with status==DESTROY. Any that we want to keep will be
4402 * re-enabled (status==KEEP) as we go through the
4403 * configuration and find out which bits are the same as
4404 * they were before.
4405 */
4406 struct ssh_portfwd *epf;
4407 int i;
4408 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4409 epf->status = DESTROY;
4410 }
4411
4412 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4413 val != NULL;
4414 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4415 char *kp, *kp2, *vp, *vp2;
4416 char address_family, type;
4417 int sport,dport,sserv,dserv;
4418 char *sports, *dports, *saddr, *host;
4419
4420 kp = key;
4421
4422 address_family = 'A';
4423 type = 'L';
4424 if (*kp == 'A' || *kp == '4' || *kp == '6')
4425 address_family = *kp++;
4426 if (*kp == 'L' || *kp == 'R')
4427 type = *kp++;
4428
4429 if ((kp2 = strchr(kp, ':')) != NULL) {
4430 /*
4431 * There's a colon in the middle of the source port
4432 * string, which means that the part before it is
4433 * actually a source address.
4434 */
4435 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4436 sports = kp2+1;
4437 } else {
4438 saddr = NULL;
4439 sports = kp;
4440 }
4441 sport = atoi(sports);
4442 sserv = 0;
4443 if (sport == 0) {
4444 sserv = 1;
4445 sport = net_service_lookup(sports);
4446 if (!sport) {
4447 logeventf(ssh, "Service lookup failed for source"
4448 " port \"%s\"", sports);
4449 }
4450 }
4451
4452 if (type == 'L' && !strcmp(val, "D")) {
4453 /* dynamic forwarding */
4454 host = NULL;
4455 dports = NULL;
4456 dport = -1;
4457 dserv = 0;
4458 type = 'D';
4459 } else {
4460 /* ordinary forwarding */
4461 vp = val;
4462 vp2 = vp + strcspn(vp, ":");
4463 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4464 if (vp2)
4465 vp2++;
4466 dports = vp2;
4467 dport = atoi(dports);
4468 dserv = 0;
4469 if (dport == 0) {
4470 dserv = 1;
4471 dport = net_service_lookup(dports);
4472 if (!dport) {
4473 logeventf(ssh, "Service lookup failed for destination"
4474 " port \"%s\"", dports);
4475 }
4476 }
4477 }
4478
4479 if (sport && dport) {
4480 /* Set up a description of the source port. */
4481 struct ssh_portfwd *pfrec, *epfrec;
4482
4483 pfrec = snew(struct ssh_portfwd);
4484 pfrec->type = type;
4485 pfrec->saddr = saddr;
4486 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4487 pfrec->sport = sport;
4488 pfrec->daddr = host;
4489 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4490 pfrec->dport = dport;
4491 pfrec->local = NULL;
4492 pfrec->remote = NULL;
4493 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4494 address_family == '6' ? ADDRTYPE_IPV6 :
4495 ADDRTYPE_UNSPEC);
4496
4497 epfrec = add234(ssh->portfwds, pfrec);
4498 if (epfrec != pfrec) {
4499 if (epfrec->status == DESTROY) {
4500 /*
4501 * We already have a port forwarding up and running
4502 * with precisely these parameters. Hence, no need
4503 * to do anything; simply re-tag the existing one
4504 * as KEEP.
4505 */
4506 epfrec->status = KEEP;
4507 }
4508 /*
4509 * Anything else indicates that there was a duplicate
4510 * in our input, which we'll silently ignore.
4511 */
4512 free_portfwd(pfrec);
4513 } else {
4514 pfrec->status = CREATE;
4515 }
4516 } else {
4517 sfree(saddr);
4518 sfree(host);
4519 }
4520 }
4521
4522 /*
4523 * Now go through and destroy any port forwardings which were
4524 * not re-enabled.
4525 */
4526 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4527 if (epf->status == DESTROY) {
4528 char *message;
4529
4530 message = dupprintf("%s port forwarding from %s%s%d",
4531 epf->type == 'L' ? "local" :
4532 epf->type == 'R' ? "remote" : "dynamic",
4533 epf->saddr ? epf->saddr : "",
4534 epf->saddr ? ":" : "",
4535 epf->sport);
4536
4537 if (epf->type != 'D') {
4538 char *msg2 = dupprintf("%s to %s:%d", message,
4539 epf->daddr, epf->dport);
4540 sfree(message);
4541 message = msg2;
4542 }
4543
4544 logeventf(ssh, "Cancelling %s", message);
4545 sfree(message);
4546
4547 /* epf->remote or epf->local may be NULL if setting up a
4548 * forwarding failed. */
4549 if (epf->remote) {
4550 struct ssh_rportfwd *rpf = epf->remote;
4551 struct Packet *pktout;
4552
4553 /*
4554 * Cancel the port forwarding at the server
4555 * end.
4556 */
4557 if (ssh->version == 1) {
4558 /*
4559 * We cannot cancel listening ports on the
4560 * server side in SSH-1! There's no message
4561 * to support it. Instead, we simply remove
4562 * the rportfwd record from the local end
4563 * so that any connections the server tries
4564 * to make on it are rejected.
4565 */
4566 } else {
4567 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4568 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4569 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4570 if (epf->saddr) {
4571 ssh2_pkt_addstring(pktout, epf->saddr);
4572 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4573 /* XXX: rport_acceptall may not represent
4574 * what was used to open the original connection,
4575 * since it's reconfigurable. */
4576 ssh2_pkt_addstring(pktout, "0.0.0.0");
4577 } else {
4578 ssh2_pkt_addstring(pktout, "127.0.0.1");
4579 }
4580 ssh2_pkt_adduint32(pktout, epf->sport);
4581 ssh2_pkt_send(ssh, pktout);
4582 }
4583
4584 del234(ssh->rportfwds, rpf);
4585 free_rportfwd(rpf);
4586 } else if (epf->local) {
4587 pfd_terminate(epf->local);
4588 }
4589
4590 delpos234(ssh->portfwds, i);
4591 free_portfwd(epf);
4592 i--; /* so we don't skip one in the list */
4593 }
4594
4595 /*
4596 * And finally, set up any new port forwardings (status==CREATE).
4597 */
4598 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4599 if (epf->status == CREATE) {
4600 char *sportdesc, *dportdesc;
4601 sportdesc = dupprintf("%s%s%s%s%d%s",
4602 epf->saddr ? epf->saddr : "",
4603 epf->saddr ? ":" : "",
4604 epf->sserv ? epf->sserv : "",
4605 epf->sserv ? "(" : "",
4606 epf->sport,
4607 epf->sserv ? ")" : "");
4608 if (epf->type == 'D') {
4609 dportdesc = NULL;
4610 } else {
4611 dportdesc = dupprintf("%s:%s%s%d%s",
4612 epf->daddr,
4613 epf->dserv ? epf->dserv : "",
4614 epf->dserv ? "(" : "",
4615 epf->dport,
4616 epf->dserv ? ")" : "");
4617 }
4618
4619 if (epf->type == 'L') {
4620 const char *err = pfd_addforward(epf->daddr, epf->dport,
4621 epf->saddr, epf->sport,
4622 ssh, conf,
4623 &epf->local,
4624 epf->addressfamily);
4625
4626 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4627 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4628 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4629 sportdesc, dportdesc,
4630 err ? " failed: " : "", err ? err : "");
4631 } else if (epf->type == 'D') {
4632 const char *err = pfd_addforward(NULL, -1,
4633 epf->saddr, epf->sport,
4634 ssh, conf,
4635 &epf->local,
4636 epf->addressfamily);
4637
4638 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4639 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4640 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4641 sportdesc,
4642 err ? " failed: " : "", err ? err : "");
4643 } else {
4644 struct ssh_rportfwd *pf;
4645
4646 /*
4647 * Ensure the remote port forwardings tree exists.
4648 */
4649 if (!ssh->rportfwds) {
4650 if (ssh->version == 1)
4651 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4652 else
4653 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4654 }
4655
4656 pf = snew(struct ssh_rportfwd);
4657 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4658 pf->dhost[lenof(pf->dhost)-1] = '\0';
4659 pf->dport = epf->dport;
4660 pf->sport = epf->sport;
4661 if (add234(ssh->rportfwds, pf) != pf) {
4662 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4663 epf->daddr, epf->dport);
4664 sfree(pf);
4665 } else {
4666 logeventf(ssh, "Requesting remote port %s"
4667 " forward to %s", sportdesc, dportdesc);
4668
4669 pf->sportdesc = sportdesc;
4670 sportdesc = NULL;
4671 epf->remote = pf;
4672 pf->pfrec = epf;
4673
4674 if (ssh->version == 1) {
4675 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4676 PKT_INT, epf->sport,
4677 PKT_STR, epf->daddr,
4678 PKT_INT, epf->dport,
4679 PKT_END);
4680 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4681 SSH1_SMSG_FAILURE,
4682 ssh_rportfwd_succfail, pf);
4683 } else {
4684 struct Packet *pktout;
4685 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4686 ssh2_pkt_addstring(pktout, "tcpip-forward");
4687 ssh2_pkt_addbool(pktout, 1);/* want reply */
4688 if (epf->saddr) {
4689 ssh2_pkt_addstring(pktout, epf->saddr);
4690 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4691 ssh2_pkt_addstring(pktout, "0.0.0.0");
4692 } else {
4693 ssh2_pkt_addstring(pktout, "127.0.0.1");
4694 }
4695 ssh2_pkt_adduint32(pktout, epf->sport);
4696 ssh2_pkt_send(ssh, pktout);
4697
4698 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4699 SSH2_MSG_REQUEST_FAILURE,
4700 ssh_rportfwd_succfail, pf);
4701 }
4702 }
4703 }
4704 sfree(sportdesc);
4705 sfree(dportdesc);
4706 }
4707 }
4708
4709 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4710 {
4711 char *string;
4712 int stringlen, bufsize;
4713
4714 ssh_pkt_getstring(pktin, &string, &stringlen);
4715 if (string == NULL) {
4716 bombout(("Incoming terminal data packet was badly formed"));
4717 return;
4718 }
4719
4720 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4721 string, stringlen);
4722 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4723 ssh->v1_stdout_throttling = 1;
4724 ssh_throttle_conn(ssh, +1);
4725 }
4726 }
4727
4728 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4729 {
4730 /* Remote side is trying to open a channel to talk to our
4731 * X-Server. Give them back a local channel number. */
4732 struct ssh_channel *c;
4733 int remoteid = ssh_pkt_getuint32(pktin);
4734
4735 logevent("Received X11 connect request");
4736 /* Refuse if X11 forwarding is disabled. */
4737 if (!ssh->X11_fwd_enabled) {
4738 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4739 PKT_INT, remoteid, PKT_END);
4740 logevent("Rejected X11 connect request");
4741 } else {
4742 c = snew(struct ssh_channel);
4743 c->ssh = ssh;
4744
4745 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4746 NULL, -1, ssh->conf) != NULL) {
4747 logevent("Opening X11 forward connection failed");
4748 sfree(c);
4749 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4750 PKT_INT, remoteid, PKT_END);
4751 } else {
4752 logevent
4753 ("Opening X11 forward connection succeeded");
4754 c->remoteid = remoteid;
4755 c->halfopen = FALSE;
4756 c->localid = alloc_channel_id(ssh);
4757 c->closes = 0;
4758 c->pending_eof = FALSE;
4759 c->throttling_conn = 0;
4760 c->type = CHAN_X11; /* identify channel type */
4761 add234(ssh->channels, c);
4762 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4763 PKT_INT, c->remoteid, PKT_INT,
4764 c->localid, PKT_END);
4765 logevent("Opened X11 forward channel");
4766 }
4767 }
4768 }
4769
4770 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4771 {
4772 /* Remote side is trying to open a channel to talk to our
4773 * agent. Give them back a local channel number. */
4774 struct ssh_channel *c;
4775 int remoteid = ssh_pkt_getuint32(pktin);
4776
4777 /* Refuse if agent forwarding is disabled. */
4778 if (!ssh->agentfwd_enabled) {
4779 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4780 PKT_INT, remoteid, PKT_END);
4781 } else {
4782 c = snew(struct ssh_channel);
4783 c->ssh = ssh;
4784 c->remoteid = remoteid;
4785 c->halfopen = FALSE;
4786 c->localid = alloc_channel_id(ssh);
4787 c->closes = 0;
4788 c->pending_eof = FALSE;
4789 c->throttling_conn = 0;
4790 c->type = CHAN_AGENT; /* identify channel type */
4791 c->u.a.lensofar = 0;
4792 c->u.a.message = NULL;
4793 add234(ssh->channels, c);
4794 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4795 PKT_INT, c->remoteid, PKT_INT, c->localid,
4796 PKT_END);
4797 }
4798 }
4799
4800 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4801 {
4802 /* Remote side is trying to open a channel to talk to a
4803 * forwarded port. Give them back a local channel number. */
4804 struct ssh_channel *c;
4805 struct ssh_rportfwd pf, *pfp;
4806 int remoteid;
4807 int hostsize, port;
4808 char *host;
4809 const char *e;
4810 c = snew(struct ssh_channel);
4811 c->ssh = ssh;
4812
4813 remoteid = ssh_pkt_getuint32(pktin);
4814 ssh_pkt_getstring(pktin, &host, &hostsize);
4815 port = ssh_pkt_getuint32(pktin);
4816
4817 if (hostsize >= lenof(pf.dhost))
4818 hostsize = lenof(pf.dhost)-1;
4819 memcpy(pf.dhost, host, hostsize);
4820 pf.dhost[hostsize] = '\0';
4821 pf.dport = port;
4822 pfp = find234(ssh->rportfwds, &pf, NULL);
4823
4824 if (pfp == NULL) {
4825 logeventf(ssh, "Rejected remote port open request for %s:%d",
4826 pf.dhost, port);
4827 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4828 PKT_INT, remoteid, PKT_END);
4829 } else {
4830 logeventf(ssh, "Received remote port open request for %s:%d",
4831 pf.dhost, port);
4832 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4833 c, ssh->conf, pfp->pfrec->addressfamily);
4834 if (e != NULL) {
4835 logeventf(ssh, "Port open failed: %s", e);
4836 sfree(c);
4837 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4838 PKT_INT, remoteid, PKT_END);
4839 } else {
4840 c->remoteid = remoteid;
4841 c->halfopen = FALSE;
4842 c->localid = alloc_channel_id(ssh);
4843 c->closes = 0;
4844 c->pending_eof = FALSE;
4845 c->throttling_conn = 0;
4846 c->type = CHAN_SOCKDATA; /* identify channel type */
4847 add234(ssh->channels, c);
4848 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4849 PKT_INT, c->remoteid, PKT_INT,
4850 c->localid, PKT_END);
4851 logevent("Forwarded port opened successfully");
4852 }
4853 }
4854 }
4855
4856 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4857 {
4858 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4859 unsigned int localid = ssh_pkt_getuint32(pktin);
4860 struct ssh_channel *c;
4861
4862 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4863 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4864 c->remoteid = localid;
4865 c->halfopen = FALSE;
4866 c->type = CHAN_SOCKDATA;
4867 c->throttling_conn = 0;
4868 pfd_confirm(c->u.pfd.s);
4869 }
4870
4871 if (c && c->pending_eof) {
4872 /*
4873 * We have a pending close on this channel,
4874 * which we decided on before the server acked
4875 * the channel open. So now we know the
4876 * remoteid, we can close it again.
4877 */
4878 ssh_channel_try_eof(c);
4879 }
4880 }
4881
4882 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4883 {
4884 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4885 struct ssh_channel *c;
4886
4887 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4888 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4889 logevent("Forwarded connection refused by server");
4890 pfd_close(c->u.pfd.s);
4891 del234(ssh->channels, c);
4892 sfree(c);
4893 }
4894 }
4895
4896 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4897 {
4898 /* Remote side closes a channel. */
4899 unsigned i = ssh_pkt_getuint32(pktin);
4900 struct ssh_channel *c;
4901 c = find234(ssh->channels, &i, ssh_channelfind);
4902 if (c && !c->halfopen) {
4903
4904 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4905 !(c->closes & CLOSES_RCVD_EOF)) {
4906 /*
4907 * Received CHANNEL_CLOSE, which we translate into
4908 * outgoing EOF.
4909 */
4910 int send_close = FALSE;
4911
4912 c->closes |= CLOSES_RCVD_EOF;
4913
4914 switch (c->type) {
4915 case CHAN_X11:
4916 if (c->u.x11.s)
4917 x11_send_eof(c->u.x11.s);
4918 else
4919 send_close = TRUE;
4920 case CHAN_SOCKDATA:
4921 if (c->u.pfd.s)
4922 x11_send_eof(c->u.pfd.s);
4923 else
4924 send_close = TRUE;
4925 case CHAN_AGENT:
4926 send_close = TRUE;
4927 }
4928
4929 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4930 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4931 PKT_END);
4932 c->closes |= CLOSES_SENT_EOF;
4933 }
4934 }
4935
4936 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4937 !(c->closes & CLOSES_RCVD_CLOSE)) {
4938
4939 if (!(c->closes & CLOSES_SENT_EOF)) {
4940 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4941 " for which we never sent CHANNEL_CLOSE\n", i));
4942 }
4943
4944 c->closes |= CLOSES_RCVD_CLOSE;
4945 }
4946
4947 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4948 !(c->closes & CLOSES_SENT_CLOSE)) {
4949 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4950 PKT_INT, c->remoteid, PKT_END);
4951 c->closes |= CLOSES_SENT_CLOSE;
4952 }
4953
4954 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4955 ssh_channel_destroy(c);
4956 } else {
4957 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4958 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4959 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4960 i));
4961 }
4962 }
4963
4964 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4965 {
4966 /* Data sent down one of our channels. */
4967 int i = ssh_pkt_getuint32(pktin);
4968 char *p;
4969 int len;
4970 struct ssh_channel *c;
4971
4972 ssh_pkt_getstring(pktin, &p, &len);
4973
4974 c = find234(ssh->channels, &i, ssh_channelfind);
4975 if (c) {
4976 int bufsize = 0;
4977 switch (c->type) {
4978 case CHAN_X11:
4979 bufsize = x11_send(c->u.x11.s, p, len);
4980 break;
4981 case CHAN_SOCKDATA:
4982 bufsize = pfd_send(c->u.pfd.s, p, len);
4983 break;
4984 case CHAN_AGENT:
4985 /* Data for an agent message. Buffer it. */
4986 while (len > 0) {
4987 if (c->u.a.lensofar < 4) {
4988 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4989 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4990 l);
4991 p += l;
4992 len -= l;
4993 c->u.a.lensofar += l;
4994 }
4995 if (c->u.a.lensofar == 4) {
4996 c->u.a.totallen =
4997 4 + GET_32BIT(c->u.a.msglen);
4998 c->u.a.message = snewn(c->u.a.totallen,
4999 unsigned char);
5000 memcpy(c->u.a.message, c->u.a.msglen, 4);
5001 }
5002 if (c->u.a.lensofar >= 4 && len > 0) {
5003 unsigned int l =
5004 min(c->u.a.totallen - c->u.a.lensofar,
5005 (unsigned)len);
5006 memcpy(c->u.a.message + c->u.a.lensofar, p,
5007 l);
5008 p += l;
5009 len -= l;
5010 c->u.a.lensofar += l;
5011 }
5012 if (c->u.a.lensofar == c->u.a.totallen) {
5013 void *reply;
5014 int replylen;
5015 if (agent_query(c->u.a.message,
5016 c->u.a.totallen,
5017 &reply, &replylen,
5018 ssh_agentf_callback, c))
5019 ssh_agentf_callback(c, reply, replylen);
5020 sfree(c->u.a.message);
5021 c->u.a.lensofar = 0;
5022 }
5023 }
5024 bufsize = 0; /* agent channels never back up */
5025 break;
5026 }
5027 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5028 c->throttling_conn = 1;
5029 ssh_throttle_conn(ssh, +1);
5030 }
5031 }
5032 }
5033
5034 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5035 {
5036 ssh->exitcode = ssh_pkt_getuint32(pktin);
5037 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5038 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5039 /*
5040 * In case `helpful' firewalls or proxies tack
5041 * extra human-readable text on the end of the
5042 * session which we might mistake for another
5043 * encrypted packet, we close the session once
5044 * we've sent EXIT_CONFIRMATION.
5045 */
5046 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5047 }
5048
5049 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5050 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5051 {
5052 struct Packet *pktout = (struct Packet *)data;
5053 int i = 0;
5054 unsigned int arg = 0;
5055 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5056 if (i == lenof(ssh_ttymodes)) return;
5057 switch (ssh_ttymodes[i].type) {
5058 case TTY_OP_CHAR:
5059 arg = ssh_tty_parse_specchar(val);
5060 break;
5061 case TTY_OP_BOOL:
5062 arg = ssh_tty_parse_boolean(val);
5063 break;
5064 }
5065 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5066 ssh2_pkt_addbyte(pktout, arg);
5067 }
5068
5069
5070 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5071 struct Packet *pktin)
5072 {
5073 crBegin(ssh->do_ssh1_connection_crstate);
5074
5075 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5076 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5077 ssh1_smsg_stdout_stderr_data;
5078
5079 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5080 ssh1_msg_channel_open_confirmation;
5081 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5082 ssh1_msg_channel_open_failure;
5083 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5084 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5085 ssh1_msg_channel_close;
5086 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5087 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5088
5089 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5090 logevent("Requesting agent forwarding");
5091 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5092 do {
5093 crReturnV;
5094 } while (!pktin);
5095 if (pktin->type != SSH1_SMSG_SUCCESS
5096 && pktin->type != SSH1_SMSG_FAILURE) {
5097 bombout(("Protocol confusion"));
5098 crStopV;
5099 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5100 logevent("Agent forwarding refused");
5101 } else {
5102 logevent("Agent forwarding enabled");
5103 ssh->agentfwd_enabled = TRUE;
5104 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5105 }
5106 }
5107
5108 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5109 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5110 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5111 logevent("Requesting X11 forwarding");
5112 /*
5113 * Note that while we blank the X authentication data here, we don't
5114 * take any special action to blank the start of an X11 channel,
5115 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5116 * without having session blanking enabled is likely to leak your
5117 * cookie into the log.
5118 */
5119 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5120 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5121 PKT_STR, ssh->x11disp->remoteauthprotoname,
5122 PKTT_PASSWORD,
5123 PKT_STR, ssh->x11disp->remoteauthdatastring,
5124 PKTT_OTHER,
5125 PKT_INT, ssh->x11disp->screennum,
5126 PKT_END);
5127 } else {
5128 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5129 PKT_STR, ssh->x11disp->remoteauthprotoname,
5130 PKTT_PASSWORD,
5131 PKT_STR, ssh->x11disp->remoteauthdatastring,
5132 PKTT_OTHER,
5133 PKT_END);
5134 }
5135 do {
5136 crReturnV;
5137 } while (!pktin);
5138 if (pktin->type != SSH1_SMSG_SUCCESS
5139 && pktin->type != SSH1_SMSG_FAILURE) {
5140 bombout(("Protocol confusion"));
5141 crStopV;
5142 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5143 logevent("X11 forwarding refused");
5144 } else {
5145 logevent("X11 forwarding enabled");
5146 ssh->X11_fwd_enabled = TRUE;
5147 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5148 }
5149 }
5150
5151 ssh_setup_portfwd(ssh, ssh->conf);
5152 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5153
5154 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5155 struct Packet *pkt;
5156 /* Unpick the terminal-speed string. */
5157 /* XXX perhaps we should allow no speeds to be sent. */
5158 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5159 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5160 /* Send the pty request. */
5161 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5162 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5163 ssh_pkt_adduint32(pkt, ssh->term_height);
5164 ssh_pkt_adduint32(pkt, ssh->term_width);
5165 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5166 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5167 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5168 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5169 ssh_pkt_adduint32(pkt, ssh->ispeed);
5170 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5171 ssh_pkt_adduint32(pkt, ssh->ospeed);
5172 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5173 s_wrpkt(ssh, pkt);
5174 ssh->state = SSH_STATE_INTERMED;
5175 do {
5176 crReturnV;
5177 } while (!pktin);
5178 if (pktin->type != SSH1_SMSG_SUCCESS
5179 && pktin->type != SSH1_SMSG_FAILURE) {
5180 bombout(("Protocol confusion"));
5181 crStopV;
5182 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5183 c_write_str(ssh, "Server refused to allocate pty\r\n");
5184 ssh->editing = ssh->echoing = 1;
5185 } else {
5186 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5187 ssh->ospeed, ssh->ispeed);
5188 ssh->got_pty = TRUE;
5189 }
5190 } else {
5191 ssh->editing = ssh->echoing = 1;
5192 }
5193
5194 if (conf_get_int(ssh->conf, CONF_compression)) {
5195 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5196 do {
5197 crReturnV;
5198 } while (!pktin);
5199 if (pktin->type != SSH1_SMSG_SUCCESS
5200 && pktin->type != SSH1_SMSG_FAILURE) {
5201 bombout(("Protocol confusion"));
5202 crStopV;
5203 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5204 c_write_str(ssh, "Server refused to compress\r\n");
5205 }
5206 logevent("Started compression");
5207 ssh->v1_compressing = TRUE;
5208 ssh->cs_comp_ctx = zlib_compress_init();
5209 logevent("Initialised zlib (RFC1950) compression");
5210 ssh->sc_comp_ctx = zlib_decompress_init();
5211 logevent("Initialised zlib (RFC1950) decompression");
5212 }
5213
5214 /*
5215 * Start the shell or command.
5216 *
5217 * Special case: if the first-choice command is an SSH-2
5218 * subsystem (hence not usable here) and the second choice
5219 * exists, we fall straight back to that.
5220 */
5221 {
5222 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5223
5224 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5225 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5226 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5227 ssh->fallback_cmd = TRUE;
5228 }
5229 if (*cmd)
5230 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5231 else
5232 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5233 logevent("Started session");
5234 }
5235
5236 ssh->state = SSH_STATE_SESSION;
5237 if (ssh->size_needed)
5238 ssh_size(ssh, ssh->term_width, ssh->term_height);
5239 if (ssh->eof_needed)
5240 ssh_special(ssh, TS_EOF);
5241
5242 if (ssh->ldisc)
5243 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5244 ssh->send_ok = 1;
5245 ssh->channels = newtree234(ssh_channelcmp);
5246 while (1) {
5247
5248 /*
5249 * By this point, most incoming packets are already being
5250 * handled by the dispatch table, and we need only pay
5251 * attention to the unusual ones.
5252 */
5253
5254 crReturnV;
5255 if (pktin) {
5256 if (pktin->type == SSH1_SMSG_SUCCESS) {
5257 /* may be from EXEC_SHELL on some servers */
5258 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5259 /* may be from EXEC_SHELL on some servers
5260 * if no pty is available or in other odd cases. Ignore */
5261 } else {
5262 bombout(("Strange packet received: type %d", pktin->type));
5263 crStopV;
5264 }
5265 } else {
5266 while (inlen > 0) {
5267 int len = min(inlen, 512);
5268 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5269 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5270 PKTT_OTHER, PKT_END);
5271 in += len;
5272 inlen -= len;
5273 }
5274 }
5275 }
5276
5277 crFinishV;
5278 }
5279
5280 /*
5281 * Handle the top-level SSH-2 protocol.
5282 */
5283 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5284 {
5285 char *msg;
5286 int msglen;
5287
5288 ssh_pkt_getstring(pktin, &msg, &msglen);
5289 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5290 }
5291
5292 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5293 {
5294 /* log reason code in disconnect message */
5295 char *msg;
5296 int msglen;
5297
5298 ssh_pkt_getstring(pktin, &msg, &msglen);
5299 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5300 }
5301
5302 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5303 {
5304 /* Do nothing, because we're ignoring it! Duhh. */
5305 }
5306
5307 static void ssh1_protocol_setup(Ssh ssh)
5308 {
5309 int i;
5310
5311 /*
5312 * Most messages are handled by the coroutines.
5313 */
5314 for (i = 0; i < 256; i++)
5315 ssh->packet_dispatch[i] = NULL;
5316
5317 /*
5318 * These special message types we install handlers for.
5319 */
5320 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5321 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5322 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5323 }
5324
5325 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5326 struct Packet *pktin)
5327 {
5328 unsigned char *in=(unsigned char*)vin;
5329 if (ssh->state == SSH_STATE_CLOSED)
5330 return;
5331
5332 if (pktin && ssh->packet_dispatch[pktin->type]) {
5333 ssh->packet_dispatch[pktin->type](ssh, pktin);
5334 return;
5335 }
5336
5337 if (!ssh->protocol_initial_phase_done) {
5338 if (do_ssh1_login(ssh, in, inlen, pktin))
5339 ssh->protocol_initial_phase_done = TRUE;
5340 else
5341 return;
5342 }
5343
5344 do_ssh1_connection(ssh, in, inlen, pktin);
5345 }
5346
5347 /*
5348 * Utility routine for decoding comma-separated strings in KEXINIT.
5349 */
5350 static int in_commasep_string(char *needle, char *haystack, int haylen)
5351 {
5352 int needlen;
5353 if (!needle || !haystack) /* protect against null pointers */
5354 return 0;
5355 needlen = strlen(needle);
5356 while (1) {
5357 /*
5358 * Is it at the start of the string?
5359 */
5360 if (haylen >= needlen && /* haystack is long enough */
5361 !memcmp(needle, haystack, needlen) && /* initial match */
5362 (haylen == needlen || haystack[needlen] == ',')
5363 /* either , or EOS follows */
5364 )
5365 return 1;
5366 /*
5367 * If not, search for the next comma and resume after that.
5368 * If no comma found, terminate.
5369 */
5370 while (haylen > 0 && *haystack != ',')
5371 haylen--, haystack++;
5372 if (haylen == 0)
5373 return 0;
5374 haylen--, haystack++; /* skip over comma itself */
5375 }
5376 }
5377
5378 /*
5379 * Similar routine for checking whether we have the first string in a list.
5380 */
5381 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5382 {
5383 int needlen;
5384 if (!needle || !haystack) /* protect against null pointers */
5385 return 0;
5386 needlen = strlen(needle);
5387 /*
5388 * Is it at the start of the string?
5389 */
5390 if (haylen >= needlen && /* haystack is long enough */
5391 !memcmp(needle, haystack, needlen) && /* initial match */
5392 (haylen == needlen || haystack[needlen] == ',')
5393 /* either , or EOS follows */
5394 )
5395 return 1;
5396 return 0;
5397 }
5398
5399
5400 /*
5401 * SSH-2 key creation method.
5402 * (Currently assumes 2 lots of any hash are sufficient to generate
5403 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5404 */
5405 #define SSH2_MKKEY_ITERS (2)
5406 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5407 unsigned char *keyspace)
5408 {
5409 const struct ssh_hash *h = ssh->kex->hash;
5410 void *s;
5411 /* First hlen bytes. */
5412 s = h->init();
5413 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5414 hash_mpint(h, s, K);
5415 h->bytes(s, H, h->hlen);
5416 h->bytes(s, &chr, 1);
5417 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5418 h->final(s, keyspace);
5419 /* Next hlen bytes. */
5420 s = h->init();
5421 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5422 hash_mpint(h, s, K);
5423 h->bytes(s, H, h->hlen);
5424 h->bytes(s, keyspace, h->hlen);
5425 h->final(s, keyspace + h->hlen);
5426 }
5427
5428 /*
5429 * Handle the SSH-2 transport layer.
5430 */
5431 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5432 struct Packet *pktin)
5433 {
5434 unsigned char *in = (unsigned char *)vin;
5435 struct do_ssh2_transport_state {
5436 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5437 Bignum p, g, e, f, K;
5438 void *our_kexinit;
5439 int our_kexinitlen;
5440 int kex_init_value, kex_reply_value;
5441 const struct ssh_mac **maclist;
5442 int nmacs;
5443 const struct ssh2_cipher *cscipher_tobe;
5444 const struct ssh2_cipher *sccipher_tobe;
5445 const struct ssh_mac *csmac_tobe;
5446 const struct ssh_mac *scmac_tobe;
5447 const struct ssh_compress *cscomp_tobe;
5448 const struct ssh_compress *sccomp_tobe;
5449 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5450 int hostkeylen, siglen, rsakeylen;
5451 void *hkey; /* actual host key */
5452 void *rsakey; /* for RSA kex */
5453 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5454 int n_preferred_kex;
5455 const struct ssh_kexes *preferred_kex[KEX_MAX];
5456 int n_preferred_ciphers;
5457 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5458 const struct ssh_compress *preferred_comp;
5459 int userauth_succeeded; /* for delayed compression */
5460 int pending_compression;
5461 int got_session_id, activated_authconn;
5462 struct Packet *pktout;
5463 int dlgret;
5464 int guessok;
5465 int ignorepkt;
5466 };
5467 crState(do_ssh2_transport_state);
5468
5469 crBegin(ssh->do_ssh2_transport_crstate);
5470
5471 s->cscipher_tobe = s->sccipher_tobe = NULL;
5472 s->csmac_tobe = s->scmac_tobe = NULL;
5473 s->cscomp_tobe = s->sccomp_tobe = NULL;
5474
5475 s->got_session_id = s->activated_authconn = FALSE;
5476 s->userauth_succeeded = FALSE;
5477 s->pending_compression = FALSE;
5478
5479 /*
5480 * Be prepared to work around the buggy MAC problem.
5481 */
5482 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5483 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5484 else
5485 s->maclist = macs, s->nmacs = lenof(macs);
5486
5487 begin_key_exchange:
5488 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5489 {
5490 int i, j, commalist_started;
5491
5492 /*
5493 * Set up the preferred key exchange. (NULL => warn below here)
5494 */
5495 s->n_preferred_kex = 0;
5496 for (i = 0; i < KEX_MAX; i++) {
5497 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5498 case KEX_DHGEX:
5499 s->preferred_kex[s->n_preferred_kex++] =
5500 &ssh_diffiehellman_gex;
5501 break;
5502 case KEX_DHGROUP14:
5503 s->preferred_kex[s->n_preferred_kex++] =
5504 &ssh_diffiehellman_group14;
5505 break;
5506 case KEX_DHGROUP1:
5507 s->preferred_kex[s->n_preferred_kex++] =
5508 &ssh_diffiehellman_group1;
5509 break;
5510 case KEX_RSA:
5511 s->preferred_kex[s->n_preferred_kex++] =
5512 &ssh_rsa_kex;
5513 break;
5514 case KEX_WARN:
5515 /* Flag for later. Don't bother if it's the last in
5516 * the list. */
5517 if (i < KEX_MAX - 1) {
5518 s->preferred_kex[s->n_preferred_kex++] = NULL;
5519 }
5520 break;
5521 }
5522 }
5523
5524 /*
5525 * Set up the preferred ciphers. (NULL => warn below here)
5526 */
5527 s->n_preferred_ciphers = 0;
5528 for (i = 0; i < CIPHER_MAX; i++) {
5529 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5530 case CIPHER_BLOWFISH:
5531 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5532 break;
5533 case CIPHER_DES:
5534 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5535 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5536 }
5537 break;
5538 case CIPHER_3DES:
5539 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5540 break;
5541 case CIPHER_AES:
5542 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5543 break;
5544 case CIPHER_ARCFOUR:
5545 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5546 break;
5547 case CIPHER_WARN:
5548 /* Flag for later. Don't bother if it's the last in
5549 * the list. */
5550 if (i < CIPHER_MAX - 1) {
5551 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5552 }
5553 break;
5554 }
5555 }
5556
5557 /*
5558 * Set up preferred compression.
5559 */
5560 if (conf_get_int(ssh->conf, CONF_compression))
5561 s->preferred_comp = &ssh_zlib;
5562 else
5563 s->preferred_comp = &ssh_comp_none;
5564
5565 /*
5566 * Enable queueing of outgoing auth- or connection-layer
5567 * packets while we are in the middle of a key exchange.
5568 */
5569 ssh->queueing = TRUE;
5570
5571 /*
5572 * Flag that KEX is in progress.
5573 */
5574 ssh->kex_in_progress = TRUE;
5575
5576 /*
5577 * Construct and send our key exchange packet.
5578 */
5579 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5580 for (i = 0; i < 16; i++)
5581 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5582 /* List key exchange algorithms. */
5583 ssh2_pkt_addstring_start(s->pktout);
5584 commalist_started = 0;
5585 for (i = 0; i < s->n_preferred_kex; i++) {
5586 const struct ssh_kexes *k = s->preferred_kex[i];
5587 if (!k) continue; /* warning flag */
5588 for (j = 0; j < k->nkexes; j++) {
5589 if (commalist_started)
5590 ssh2_pkt_addstring_str(s->pktout, ",");
5591 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5592 commalist_started = 1;
5593 }
5594 }
5595 /* List server host key algorithms. */
5596 ssh2_pkt_addstring_start(s->pktout);
5597 for (i = 0; i < lenof(hostkey_algs); i++) {
5598 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5599 if (i < lenof(hostkey_algs) - 1)
5600 ssh2_pkt_addstring_str(s->pktout, ",");
5601 }
5602 /* List client->server encryption algorithms. */
5603 ssh2_pkt_addstring_start(s->pktout);
5604 commalist_started = 0;
5605 for (i = 0; i < s->n_preferred_ciphers; i++) {
5606 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5607 if (!c) continue; /* warning flag */
5608 for (j = 0; j < c->nciphers; j++) {
5609 if (commalist_started)
5610 ssh2_pkt_addstring_str(s->pktout, ",");
5611 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5612 commalist_started = 1;
5613 }
5614 }
5615 /* List server->client encryption algorithms. */
5616 ssh2_pkt_addstring_start(s->pktout);
5617 commalist_started = 0;
5618 for (i = 0; i < s->n_preferred_ciphers; i++) {
5619 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5620 if (!c) continue; /* warning flag */
5621 for (j = 0; j < c->nciphers; j++) {
5622 if (commalist_started)
5623 ssh2_pkt_addstring_str(s->pktout, ",");
5624 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5625 commalist_started = 1;
5626 }
5627 }
5628 /* List client->server MAC algorithms. */
5629 ssh2_pkt_addstring_start(s->pktout);
5630 for (i = 0; i < s->nmacs; i++) {
5631 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5632 if (i < s->nmacs - 1)
5633 ssh2_pkt_addstring_str(s->pktout, ",");
5634 }
5635 /* List server->client MAC algorithms. */
5636 ssh2_pkt_addstring_start(s->pktout);
5637 for (i = 0; i < s->nmacs; i++) {
5638 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5639 if (i < s->nmacs - 1)
5640 ssh2_pkt_addstring_str(s->pktout, ",");
5641 }
5642 /* List client->server compression algorithms,
5643 * then server->client compression algorithms. (We use the
5644 * same set twice.) */
5645 for (j = 0; j < 2; j++) {
5646 ssh2_pkt_addstring_start(s->pktout);
5647 assert(lenof(compressions) > 1);
5648 /* Prefer non-delayed versions */
5649 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5650 /* We don't even list delayed versions of algorithms until
5651 * they're allowed to be used, to avoid a race. See the end of
5652 * this function. */
5653 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5654 ssh2_pkt_addstring_str(s->pktout, ",");
5655 ssh2_pkt_addstring_str(s->pktout,
5656 s->preferred_comp->delayed_name);
5657 }
5658 for (i = 0; i < lenof(compressions); i++) {
5659 const struct ssh_compress *c = compressions[i];
5660 if (c != s->preferred_comp) {
5661 ssh2_pkt_addstring_str(s->pktout, ",");
5662 ssh2_pkt_addstring_str(s->pktout, c->name);
5663 if (s->userauth_succeeded && c->delayed_name) {
5664 ssh2_pkt_addstring_str(s->pktout, ",");
5665 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5666 }
5667 }
5668 }
5669 }
5670 /* List client->server languages. Empty list. */
5671 ssh2_pkt_addstring_start(s->pktout);
5672 /* List server->client languages. Empty list. */
5673 ssh2_pkt_addstring_start(s->pktout);
5674 /* First KEX packet does _not_ follow, because we're not that brave. */
5675 ssh2_pkt_addbool(s->pktout, FALSE);
5676 /* Reserved. */
5677 ssh2_pkt_adduint32(s->pktout, 0);
5678 }
5679
5680 s->our_kexinitlen = s->pktout->length - 5;
5681 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5682 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5683
5684 ssh2_pkt_send_noqueue(ssh, s->pktout);
5685
5686 if (!pktin)
5687 crWaitUntil(pktin);
5688
5689 /*
5690 * Now examine the other side's KEXINIT to see what we're up
5691 * to.
5692 */
5693 {
5694 char *str, *preferred;
5695 int i, j, len;
5696
5697 if (pktin->type != SSH2_MSG_KEXINIT) {
5698 bombout(("expected key exchange packet from server"));
5699 crStop(0);
5700 }
5701 ssh->kex = NULL;
5702 ssh->hostkey = NULL;
5703 s->cscipher_tobe = NULL;
5704 s->sccipher_tobe = NULL;
5705 s->csmac_tobe = NULL;
5706 s->scmac_tobe = NULL;
5707 s->cscomp_tobe = NULL;
5708 s->sccomp_tobe = NULL;
5709 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5710
5711 pktin->savedpos += 16; /* skip garbage cookie */
5712 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5713
5714 preferred = NULL;
5715 for (i = 0; i < s->n_preferred_kex; i++) {
5716 const struct ssh_kexes *k = s->preferred_kex[i];
5717 if (!k) {
5718 s->warn_kex = TRUE;
5719 } else {
5720 for (j = 0; j < k->nkexes; j++) {
5721 if (!preferred) preferred = k->list[j]->name;
5722 if (in_commasep_string(k->list[j]->name, str, len)) {
5723 ssh->kex = k->list[j];
5724 break;
5725 }
5726 }
5727 }
5728 if (ssh->kex)
5729 break;
5730 }
5731 if (!ssh->kex) {
5732 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5733 str ? str : "(null)"));
5734 crStop(0);
5735 }
5736 /*
5737 * Note that the server's guess is considered wrong if it doesn't match
5738 * the first algorithm in our list, even if it's still the algorithm
5739 * we end up using.
5740 */
5741 s->guessok = first_in_commasep_string(preferred, str, len);
5742 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5743 for (i = 0; i < lenof(hostkey_algs); i++) {
5744 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5745 ssh->hostkey = hostkey_algs[i];
5746 break;
5747 }
5748 }
5749 s->guessok = s->guessok &&
5750 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5751 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5752 for (i = 0; i < s->n_preferred_ciphers; i++) {
5753 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5754 if (!c) {
5755 s->warn_cscipher = TRUE;
5756 } else {
5757 for (j = 0; j < c->nciphers; j++) {
5758 if (in_commasep_string(c->list[j]->name, str, len)) {
5759 s->cscipher_tobe = c->list[j];
5760 break;
5761 }
5762 }
5763 }
5764 if (s->cscipher_tobe)
5765 break;
5766 }
5767 if (!s->cscipher_tobe) {
5768 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5769 str ? str : "(null)"));
5770 crStop(0);
5771 }
5772
5773 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5774 for (i = 0; i < s->n_preferred_ciphers; i++) {
5775 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5776 if (!c) {
5777 s->warn_sccipher = TRUE;
5778 } else {
5779 for (j = 0; j < c->nciphers; j++) {
5780 if (in_commasep_string(c->list[j]->name, str, len)) {
5781 s->sccipher_tobe = c->list[j];
5782 break;
5783 }
5784 }
5785 }
5786 if (s->sccipher_tobe)
5787 break;
5788 }
5789 if (!s->sccipher_tobe) {
5790 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5791 str ? str : "(null)"));
5792 crStop(0);
5793 }
5794
5795 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5796 for (i = 0; i < s->nmacs; i++) {
5797 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5798 s->csmac_tobe = s->maclist[i];
5799 break;
5800 }
5801 }
5802 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5803 for (i = 0; i < s->nmacs; i++) {
5804 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5805 s->scmac_tobe = s->maclist[i];
5806 break;
5807 }
5808 }
5809 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5810 for (i = 0; i < lenof(compressions) + 1; i++) {
5811 const struct ssh_compress *c =
5812 i == 0 ? s->preferred_comp : compressions[i - 1];
5813 if (in_commasep_string(c->name, str, len)) {
5814 s->cscomp_tobe = c;
5815 break;
5816 } else if (in_commasep_string(c->delayed_name, str, len)) {
5817 if (s->userauth_succeeded) {
5818 s->cscomp_tobe = c;
5819 break;
5820 } else {
5821 s->pending_compression = TRUE; /* try this later */
5822 }
5823 }
5824 }
5825 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5826 for (i = 0; i < lenof(compressions) + 1; i++) {
5827 const struct ssh_compress *c =
5828 i == 0 ? s->preferred_comp : compressions[i - 1];
5829 if (in_commasep_string(c->name, str, len)) {
5830 s->sccomp_tobe = c;
5831 break;
5832 } else if (in_commasep_string(c->delayed_name, str, len)) {
5833 if (s->userauth_succeeded) {
5834 s->sccomp_tobe = c;
5835 break;
5836 } else {
5837 s->pending_compression = TRUE; /* try this later */
5838 }
5839 }
5840 }
5841 if (s->pending_compression) {
5842 logevent("Server supports delayed compression; "
5843 "will try this later");
5844 }
5845 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5846 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5847 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5848
5849 if (s->warn_kex) {
5850 ssh_set_frozen(ssh, 1);
5851 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5852 ssh->kex->name,
5853 ssh_dialog_callback, ssh);
5854 if (s->dlgret < 0) {
5855 do {
5856 crReturn(0);
5857 if (pktin) {
5858 bombout(("Unexpected data from server while"
5859 " waiting for user response"));
5860 crStop(0);
5861 }
5862 } while (pktin || inlen > 0);
5863 s->dlgret = ssh->user_response;
5864 }
5865 ssh_set_frozen(ssh, 0);
5866 if (s->dlgret == 0) {
5867 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5868 0, TRUE);
5869 crStop(0);
5870 }
5871 }
5872
5873 if (s->warn_cscipher) {
5874 ssh_set_frozen(ssh, 1);
5875 s->dlgret = askalg(ssh->frontend,
5876 "client-to-server cipher",
5877 s->cscipher_tobe->name,
5878 ssh_dialog_callback, ssh);
5879 if (s->dlgret < 0) {
5880 do {
5881 crReturn(0);
5882 if (pktin) {
5883 bombout(("Unexpected data from server while"
5884 " waiting for user response"));
5885 crStop(0);
5886 }
5887 } while (pktin || inlen > 0);
5888 s->dlgret = ssh->user_response;
5889 }
5890 ssh_set_frozen(ssh, 0);
5891 if (s->dlgret == 0) {
5892 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5893 0, TRUE);
5894 crStop(0);
5895 }
5896 }
5897
5898 if (s->warn_sccipher) {
5899 ssh_set_frozen(ssh, 1);
5900 s->dlgret = askalg(ssh->frontend,
5901 "server-to-client cipher",
5902 s->sccipher_tobe->name,
5903 ssh_dialog_callback, ssh);
5904 if (s->dlgret < 0) {
5905 do {
5906 crReturn(0);
5907 if (pktin) {
5908 bombout(("Unexpected data from server while"
5909 " waiting for user response"));
5910 crStop(0);
5911 }
5912 } while (pktin || inlen > 0);
5913 s->dlgret = ssh->user_response;
5914 }
5915 ssh_set_frozen(ssh, 0);
5916 if (s->dlgret == 0) {
5917 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5918 0, TRUE);
5919 crStop(0);
5920 }
5921 }
5922
5923 ssh->exhash = ssh->kex->hash->init();
5924 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5925 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5926 hash_string(ssh->kex->hash, ssh->exhash,
5927 s->our_kexinit, s->our_kexinitlen);
5928 sfree(s->our_kexinit);
5929 if (pktin->length > 5)
5930 hash_string(ssh->kex->hash, ssh->exhash,
5931 pktin->data + 5, pktin->length - 5);
5932
5933 if (s->ignorepkt) /* first_kex_packet_follows */
5934 crWaitUntil(pktin); /* Ignore packet */
5935 }
5936
5937 if (ssh->kex->main_type == KEXTYPE_DH) {
5938 /*
5939 * Work out the number of bits of key we will need from the
5940 * key exchange. We start with the maximum key length of
5941 * either cipher...
5942 */
5943 {
5944 int csbits, scbits;
5945
5946 csbits = s->cscipher_tobe->keylen;
5947 scbits = s->sccipher_tobe->keylen;
5948 s->nbits = (csbits > scbits ? csbits : scbits);
5949 }
5950 /* The keys only have hlen-bit entropy, since they're based on
5951 * a hash. So cap the key size at hlen bits. */
5952 if (s->nbits > ssh->kex->hash->hlen * 8)
5953 s->nbits = ssh->kex->hash->hlen * 8;
5954
5955 /*
5956 * If we're doing Diffie-Hellman group exchange, start by
5957 * requesting a group.
5958 */
5959 if (!ssh->kex->pdata) {
5960 logevent("Doing Diffie-Hellman group exchange");
5961 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5962 /*
5963 * Work out how big a DH group we will need to allow that
5964 * much data.
5965 */
5966 s->pbits = 512 << ((s->nbits - 1) / 64);
5967 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5968 ssh2_pkt_adduint32(s->pktout, s->pbits);
5969 ssh2_pkt_send_noqueue(ssh, s->pktout);
5970
5971 crWaitUntil(pktin);
5972 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5973 bombout(("expected key exchange group packet from server"));
5974 crStop(0);
5975 }
5976 s->p = ssh2_pkt_getmp(pktin);
5977 s->g = ssh2_pkt_getmp(pktin);
5978 if (!s->p || !s->g) {
5979 bombout(("unable to read mp-ints from incoming group packet"));
5980 crStop(0);
5981 }
5982 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5983 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5984 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5985 } else {
5986 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5987 ssh->kex_ctx = dh_setup_group(ssh->kex);
5988 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5989 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5990 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5991 ssh->kex->groupname);
5992 }
5993
5994 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5995 ssh->kex->hash->text_name);
5996 /*
5997 * Now generate and send e for Diffie-Hellman.
5998 */
5999 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6000 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6001 s->pktout = ssh2_pkt_init(s->kex_init_value);
6002 ssh2_pkt_addmp(s->pktout, s->e);
6003 ssh2_pkt_send_noqueue(ssh, s->pktout);
6004
6005 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6006 crWaitUntil(pktin);
6007 if (pktin->type != s->kex_reply_value) {
6008 bombout(("expected key exchange reply packet from server"));
6009 crStop(0);
6010 }
6011 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6012 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6013 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6014 s->f = ssh2_pkt_getmp(pktin);
6015 if (!s->f) {
6016 bombout(("unable to parse key exchange reply packet"));
6017 crStop(0);
6018 }
6019 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6020
6021 s->K = dh_find_K(ssh->kex_ctx, s->f);
6022
6023 /* We assume everything from now on will be quick, and it might
6024 * involve user interaction. */
6025 set_busy_status(ssh->frontend, BUSY_NOT);
6026
6027 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6028 if (!ssh->kex->pdata) {
6029 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6030 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6031 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6032 }
6033 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6034 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6035
6036 dh_cleanup(ssh->kex_ctx);
6037 freebn(s->f);
6038 if (!ssh->kex->pdata) {
6039 freebn(s->g);
6040 freebn(s->p);
6041 }
6042 } else {
6043 logeventf(ssh, "Doing RSA key exchange with hash %s",
6044 ssh->kex->hash->text_name);
6045 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6046 /*
6047 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6048 * from the server.
6049 */
6050 crWaitUntil(pktin);
6051 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6052 bombout(("expected RSA public key packet from server"));
6053 crStop(0);
6054 }
6055
6056 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6057 hash_string(ssh->kex->hash, ssh->exhash,
6058 s->hostkeydata, s->hostkeylen);
6059 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6060
6061 {
6062 char *keydata;
6063 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6064 s->rsakeydata = snewn(s->rsakeylen, char);
6065 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6066 }
6067
6068 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6069 if (!s->rsakey) {
6070 sfree(s->rsakeydata);
6071 bombout(("unable to parse RSA public key from server"));
6072 crStop(0);
6073 }
6074
6075 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6076
6077 /*
6078 * Next, set up a shared secret K, of precisely KLEN -
6079 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6080 * RSA key modulus and HLEN is the bit length of the hash
6081 * we're using.
6082 */
6083 {
6084 int klen = ssh_rsakex_klen(s->rsakey);
6085 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6086 int i, byte = 0;
6087 unsigned char *kstr1, *kstr2, *outstr;
6088 int kstr1len, kstr2len, outstrlen;
6089
6090 s->K = bn_power_2(nbits - 1);
6091
6092 for (i = 0; i < nbits; i++) {
6093 if ((i & 7) == 0) {
6094 byte = random_byte();
6095 }
6096 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6097 }
6098
6099 /*
6100 * Encode this as an mpint.
6101 */
6102 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6103 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6104 PUT_32BIT(kstr2, kstr1len);
6105 memcpy(kstr2 + 4, kstr1, kstr1len);
6106
6107 /*
6108 * Encrypt it with the given RSA key.
6109 */
6110 outstrlen = (klen + 7) / 8;
6111 outstr = snewn(outstrlen, unsigned char);
6112 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6113 outstr, outstrlen, s->rsakey);
6114
6115 /*
6116 * And send it off in a return packet.
6117 */
6118 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6119 ssh2_pkt_addstring_start(s->pktout);
6120 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6121 ssh2_pkt_send_noqueue(ssh, s->pktout);
6122
6123 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6124
6125 sfree(kstr2);
6126 sfree(kstr1);
6127 sfree(outstr);
6128 }
6129
6130 ssh_rsakex_freekey(s->rsakey);
6131
6132 crWaitUntil(pktin);
6133 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6134 sfree(s->rsakeydata);
6135 bombout(("expected signature packet from server"));
6136 crStop(0);
6137 }
6138
6139 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6140
6141 sfree(s->rsakeydata);
6142 }
6143
6144 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6145 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6146 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6147
6148 ssh->kex_ctx = NULL;
6149
6150 #if 0
6151 debug(("Exchange hash is:\n"));
6152 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6153 #endif
6154
6155 if (!s->hkey ||
6156 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6157 (char *)s->exchange_hash,
6158 ssh->kex->hash->hlen)) {
6159 bombout(("Server's host key did not match the signature supplied"));
6160 crStop(0);
6161 }
6162
6163 /*
6164 * Authenticate remote host: verify host key. (We've already
6165 * checked the signature of the exchange hash.)
6166 */
6167 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6168 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6169 ssh_set_frozen(ssh, 1);
6170 s->dlgret = verify_ssh_host_key(ssh->frontend,
6171 ssh->savedhost, ssh->savedport,
6172 ssh->hostkey->keytype, s->keystr,
6173 s->fingerprint,
6174 ssh_dialog_callback, ssh);
6175 if (s->dlgret < 0) {
6176 do {
6177 crReturn(0);
6178 if (pktin) {
6179 bombout(("Unexpected data from server while waiting"
6180 " for user host key response"));
6181 crStop(0);
6182 }
6183 } while (pktin || inlen > 0);
6184 s->dlgret = ssh->user_response;
6185 }
6186 ssh_set_frozen(ssh, 0);
6187 if (s->dlgret == 0) {
6188 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6189 0, TRUE);
6190 crStop(0);
6191 }
6192 if (!s->got_session_id) { /* don't bother logging this in rekeys */
6193 logevent("Host key fingerprint is:");
6194 logevent(s->fingerprint);
6195 }
6196 sfree(s->fingerprint);
6197 sfree(s->keystr);
6198 ssh->hostkey->freekey(s->hkey);
6199
6200 /*
6201 * The exchange hash from the very first key exchange is also
6202 * the session id, used in session key construction and
6203 * authentication.
6204 */
6205 if (!s->got_session_id) {
6206 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6207 memcpy(ssh->v2_session_id, s->exchange_hash,
6208 sizeof(s->exchange_hash));
6209 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6210 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6211 s->got_session_id = TRUE;
6212 }
6213
6214 /*
6215 * Send SSH2_MSG_NEWKEYS.
6216 */
6217 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6218 ssh2_pkt_send_noqueue(ssh, s->pktout);
6219 ssh->outgoing_data_size = 0; /* start counting from here */
6220
6221 /*
6222 * We've sent client NEWKEYS, so create and initialise
6223 * client-to-server session keys.
6224 */
6225 if (ssh->cs_cipher_ctx)
6226 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6227 ssh->cscipher = s->cscipher_tobe;
6228 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6229
6230 if (ssh->cs_mac_ctx)
6231 ssh->csmac->free_context(ssh->cs_mac_ctx);
6232 ssh->csmac = s->csmac_tobe;
6233 ssh->cs_mac_ctx = ssh->csmac->make_context();
6234
6235 if (ssh->cs_comp_ctx)
6236 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6237 ssh->cscomp = s->cscomp_tobe;
6238 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6239
6240 /*
6241 * Set IVs on client-to-server keys. Here we use the exchange
6242 * hash from the _first_ key exchange.
6243 */
6244 {
6245 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6246 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6247 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6248 assert((ssh->cscipher->keylen+7) / 8 <=
6249 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6250 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6251 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6252 assert(ssh->cscipher->blksize <=
6253 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6254 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6255 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6256 assert(ssh->csmac->len <=
6257 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6258 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6259 memset(keyspace, 0, sizeof(keyspace));
6260 }
6261
6262 logeventf(ssh, "Initialised %.200s client->server encryption",
6263 ssh->cscipher->text_name);
6264 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6265 ssh->csmac->text_name);
6266 if (ssh->cscomp->text_name)
6267 logeventf(ssh, "Initialised %s compression",
6268 ssh->cscomp->text_name);
6269
6270 /*
6271 * Now our end of the key exchange is complete, we can send all
6272 * our queued higher-layer packets.
6273 */
6274 ssh->queueing = FALSE;
6275 ssh2_pkt_queuesend(ssh);
6276
6277 /*
6278 * Expect SSH2_MSG_NEWKEYS from server.
6279 */
6280 crWaitUntil(pktin);
6281 if (pktin->type != SSH2_MSG_NEWKEYS) {
6282 bombout(("expected new-keys packet from server"));
6283 crStop(0);
6284 }
6285 ssh->incoming_data_size = 0; /* start counting from here */
6286
6287 /*
6288 * We've seen server NEWKEYS, so create and initialise
6289 * server-to-client session keys.
6290 */
6291 if (ssh->sc_cipher_ctx)
6292 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6293 ssh->sccipher = s->sccipher_tobe;
6294 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6295
6296 if (ssh->sc_mac_ctx)
6297 ssh->scmac->free_context(ssh->sc_mac_ctx);
6298 ssh->scmac = s->scmac_tobe;
6299 ssh->sc_mac_ctx = ssh->scmac->make_context();
6300
6301 if (ssh->sc_comp_ctx)
6302 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6303 ssh->sccomp = s->sccomp_tobe;
6304 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6305
6306 /*
6307 * Set IVs on server-to-client keys. Here we use the exchange
6308 * hash from the _first_ key exchange.
6309 */
6310 {
6311 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6312 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6313 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6314 assert((ssh->sccipher->keylen+7) / 8 <=
6315 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6316 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6317 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6318 assert(ssh->sccipher->blksize <=
6319 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6320 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6321 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6322 assert(ssh->scmac->len <=
6323 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6324 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6325 memset(keyspace, 0, sizeof(keyspace));
6326 }
6327 logeventf(ssh, "Initialised %.200s server->client encryption",
6328 ssh->sccipher->text_name);
6329 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6330 ssh->scmac->text_name);
6331 if (ssh->sccomp->text_name)
6332 logeventf(ssh, "Initialised %s decompression",
6333 ssh->sccomp->text_name);
6334
6335 /*
6336 * Free shared secret.
6337 */
6338 freebn(s->K);
6339
6340 /*
6341 * Key exchange is over. Loop straight back round if we have a
6342 * deferred rekey reason.
6343 */
6344 if (ssh->deferred_rekey_reason) {
6345 logevent(ssh->deferred_rekey_reason);
6346 pktin = NULL;
6347 ssh->deferred_rekey_reason = NULL;
6348 goto begin_key_exchange;
6349 }
6350
6351 /*
6352 * Otherwise, schedule a timer for our next rekey.
6353 */
6354 ssh->kex_in_progress = FALSE;
6355 ssh->last_rekey = GETTICKCOUNT();
6356 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6357 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6358 ssh2_timer, ssh);
6359
6360 /*
6361 * If this is the first key exchange phase, we must pass the
6362 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6363 * wants to see it but because it will need time to initialise
6364 * itself before it sees an actual packet. In subsequent key
6365 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6366 * it would only confuse the layer above.
6367 */
6368 if (s->activated_authconn) {
6369 crReturn(0);
6370 }
6371 s->activated_authconn = TRUE;
6372
6373 /*
6374 * Now we're encrypting. Begin returning 1 to the protocol main
6375 * function so that other things can run on top of the
6376 * transport. If we ever see a KEXINIT, we must go back to the
6377 * start.
6378 *
6379 * We _also_ go back to the start if we see pktin==NULL and
6380 * inlen negative, because this is a special signal meaning
6381 * `initiate client-driven rekey', and `in' contains a message
6382 * giving the reason for the rekey.
6383 *
6384 * inlen==-1 means always initiate a rekey;
6385 * inlen==-2 means that userauth has completed successfully and
6386 * we should consider rekeying (for delayed compression).
6387 */
6388 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6389 (!pktin && inlen < 0))) {
6390 wait_for_rekey:
6391 crReturn(1);
6392 }
6393 if (pktin) {
6394 logevent("Server initiated key re-exchange");
6395 } else {
6396 if (inlen == -2) {
6397 /*
6398 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6399 * delayed compression, if it's available.
6400 *
6401 * draft-miller-secsh-compression-delayed-00 says that you
6402 * negotiate delayed compression in the first key exchange, and
6403 * both sides start compressing when the server has sent
6404 * USERAUTH_SUCCESS. This has a race condition -- the server
6405 * can't know when the client has seen it, and thus which incoming
6406 * packets it should treat as compressed.
6407 *
6408 * Instead, we do the initial key exchange without offering the
6409 * delayed methods, but note if the server offers them; when we
6410 * get here, if a delayed method was available that was higher
6411 * on our list than what we got, we initiate a rekey in which we
6412 * _do_ list the delayed methods (and hopefully get it as a
6413 * result). Subsequent rekeys will do the same.
6414 */
6415 assert(!s->userauth_succeeded); /* should only happen once */
6416 s->userauth_succeeded = TRUE;
6417 if (!s->pending_compression)
6418 /* Can't see any point rekeying. */
6419 goto wait_for_rekey; /* this is utterly horrid */
6420 /* else fall through to rekey... */
6421 s->pending_compression = FALSE;
6422 }
6423 /*
6424 * Now we've decided to rekey.
6425 *
6426 * Special case: if the server bug is set that doesn't
6427 * allow rekeying, we give a different log message and
6428 * continue waiting. (If such a server _initiates_ a rekey,
6429 * we process it anyway!)
6430 */
6431 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6432 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6433 (char *)in);
6434 /* Reset the counters, so that at least this message doesn't
6435 * hit the event log _too_ often. */
6436 ssh->outgoing_data_size = 0;
6437 ssh->incoming_data_size = 0;
6438 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6439 ssh->next_rekey =
6440 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6441 ssh2_timer, ssh);
6442 }
6443 goto wait_for_rekey; /* this is still utterly horrid */
6444 } else {
6445 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6446 }
6447 }
6448 goto begin_key_exchange;
6449
6450 crFinish(1);
6451 }
6452
6453 /*
6454 * Add data to an SSH-2 channel output buffer.
6455 */
6456 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6457 int len)
6458 {
6459 bufchain_add(&c->v.v2.outbuffer, buf, len);
6460 }
6461
6462 /*
6463 * Attempt to send data on an SSH-2 channel.
6464 */
6465 static int ssh2_try_send(struct ssh_channel *c)
6466 {
6467 Ssh ssh = c->ssh;
6468 struct Packet *pktout;
6469 int ret;
6470
6471 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6472 int len;
6473 void *data;
6474 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6475 if ((unsigned)len > c->v.v2.remwindow)
6476 len = c->v.v2.remwindow;
6477 if ((unsigned)len > c->v.v2.remmaxpkt)
6478 len = c->v.v2.remmaxpkt;
6479 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6480 ssh2_pkt_adduint32(pktout, c->remoteid);
6481 ssh2_pkt_addstring_start(pktout);
6482 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6483 ssh2_pkt_addstring_data(pktout, data, len);
6484 end_log_omission(ssh, pktout);
6485 ssh2_pkt_send(ssh, pktout);
6486 bufchain_consume(&c->v.v2.outbuffer, len);
6487 c->v.v2.remwindow -= len;
6488 }
6489
6490 /*
6491 * After having sent as much data as we can, return the amount
6492 * still buffered.
6493 */
6494 ret = bufchain_size(&c->v.v2.outbuffer);
6495
6496 /*
6497 * And if there's no data pending but we need to send an EOF, send
6498 * it.
6499 */
6500 if (!ret && c->pending_eof)
6501 ssh_channel_try_eof(c);
6502
6503 return ret;
6504 }
6505
6506 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6507 {
6508 int bufsize;
6509 if (c->closes & CLOSES_SENT_EOF)
6510 return; /* don't send on channels we've EOFed */
6511 bufsize = ssh2_try_send(c);
6512 if (bufsize == 0) {
6513 switch (c->type) {
6514 case CHAN_MAINSESSION:
6515 /* stdin need not receive an unthrottle
6516 * notification since it will be polled */
6517 break;
6518 case CHAN_X11:
6519 x11_unthrottle(c->u.x11.s);
6520 break;
6521 case CHAN_AGENT:
6522 /* agent sockets are request/response and need no
6523 * buffer management */
6524 break;
6525 case CHAN_SOCKDATA:
6526 pfd_unthrottle(c->u.pfd.s);
6527 break;
6528 }
6529 }
6530 }
6531
6532 /*
6533 * Set up most of a new ssh_channel for SSH-2.
6534 */
6535 static void ssh2_channel_init(struct ssh_channel *c)
6536 {
6537 Ssh ssh = c->ssh;
6538 c->localid = alloc_channel_id(ssh);
6539 c->closes = 0;
6540 c->pending_eof = FALSE;
6541 c->throttling_conn = FALSE;
6542 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6543 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6544 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6545 c->v.v2.throttle_state = UNTHROTTLED;
6546 bufchain_init(&c->v.v2.outbuffer);
6547 }
6548
6549 /*
6550 * Potentially enlarge the window on an SSH-2 channel.
6551 */
6552 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6553 {
6554 Ssh ssh = c->ssh;
6555
6556 /*
6557 * Never send WINDOW_ADJUST for a channel that the remote side has
6558 * already sent EOF on; there's no point, since it won't be
6559 * sending any more data anyway.
6560 */
6561 if (c->closes & CLOSES_RCVD_EOF)
6562 return;
6563
6564 /*
6565 * If the remote end has a habit of ignoring maxpkt, limit the
6566 * window so that it has no choice (assuming it doesn't ignore the
6567 * window as well).
6568 */
6569 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6570 newwin = OUR_V2_MAXPKT;
6571
6572
6573 /*
6574 * Only send a WINDOW_ADJUST if there's significantly more window
6575 * available than the other end thinks there is. This saves us
6576 * sending a WINDOW_ADJUST for every character in a shell session.
6577 *
6578 * "Significant" is arbitrarily defined as half the window size.
6579 */
6580 if (newwin / 2 >= c->v.v2.locwindow) {
6581 struct Packet *pktout;
6582 struct winadj *wa;
6583
6584 /*
6585 * In order to keep track of how much window the client
6586 * actually has available, we'd like it to acknowledge each
6587 * WINDOW_ADJUST. We can't do that directly, so we accompany
6588 * it with a CHANNEL_REQUEST that has to be acknowledged.
6589 *
6590 * This is only necessary if we're opening the window wide.
6591 * If we're not, then throughput is being constrained by
6592 * something other than the maximum window size anyway.
6593 *
6594 * We also only send this if the main channel has finished its
6595 * initial CHANNEL_REQUESTs and installed the default
6596 * CHANNEL_FAILURE handler, so as not to risk giving it
6597 * unexpected CHANNEL_FAILUREs.
6598 */
6599 if (newwin == c->v.v2.locmaxwin &&
6600 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6601 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6602 ssh2_pkt_adduint32(pktout, c->remoteid);
6603 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6604 ssh2_pkt_addbool(pktout, TRUE);
6605 ssh2_pkt_send(ssh, pktout);
6606
6607 /*
6608 * CHANNEL_FAILURE doesn't come with any indication of
6609 * what message caused it, so we have to keep track of the
6610 * outstanding CHANNEL_REQUESTs ourselves.
6611 */
6612 wa = snew(struct winadj);
6613 wa->size = newwin - c->v.v2.locwindow;
6614 wa->next = NULL;
6615 if (!c->v.v2.winadj_head)
6616 c->v.v2.winadj_head = wa;
6617 else
6618 c->v.v2.winadj_tail->next = wa;
6619 c->v.v2.winadj_tail = wa;
6620 if (c->v.v2.throttle_state != UNTHROTTLED)
6621 c->v.v2.throttle_state = UNTHROTTLING;
6622 } else {
6623 /* Pretend the WINDOW_ADJUST was acked immediately. */
6624 c->v.v2.remlocwin = newwin;
6625 c->v.v2.throttle_state = THROTTLED;
6626 }
6627 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6628 ssh2_pkt_adduint32(pktout, c->remoteid);
6629 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6630 ssh2_pkt_send(ssh, pktout);
6631 c->v.v2.locwindow = newwin;
6632 }
6633 }
6634
6635 /*
6636 * Find the channel associated with a message. If there's no channel,
6637 * or it's not properly open, make a noise about it and return NULL.
6638 */
6639 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6640 {
6641 unsigned localid = ssh_pkt_getuint32(pktin);
6642 struct ssh_channel *c;
6643
6644 c = find234(ssh->channels, &localid, ssh_channelfind);
6645 if (!c ||
6646 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6647 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6648 char *buf = dupprintf("Received %s for %s channel %u",
6649 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6650 pktin->type),
6651 c ? "half-open" : "nonexistent", localid);
6652 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6653 sfree(buf);
6654 return NULL;
6655 }
6656 return c;
6657 }
6658
6659 static int ssh2_handle_winadj_response(struct ssh_channel *c)
6660 {
6661 struct winadj *wa = c->v.v2.winadj_head;
6662 if (!wa)
6663 return FALSE;
6664 c->v.v2.winadj_head = wa->next;
6665 c->v.v2.remlocwin += wa->size;
6666 sfree(wa);
6667 /*
6668 * winadj messages are only sent when the window is fully open, so
6669 * if we get an ack of one, we know any pending unthrottle is
6670 * complete.
6671 */
6672 if (c->v.v2.throttle_state == UNTHROTTLING)
6673 c->v.v2.throttle_state = UNTHROTTLED;
6674 /*
6675 * We may now initiate channel-closing procedures, if that winadj
6676 * was the last thing outstanding before we send CHANNEL_CLOSE.
6677 */
6678 ssh2_channel_check_close(c);
6679 return TRUE;
6680 }
6681
6682 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6683 {
6684 /*
6685 * This should never get called. All channel requests are either
6686 * sent with want_reply false, are sent before this handler gets
6687 * installed, or are "winadj@putty" requests, which servers should
6688 * never respond to with success.
6689 *
6690 * However, at least one server ("boks_sshd") is known to return
6691 * SUCCESS for channel requests it's never heard of, such as
6692 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6693 * for the sake of a quiet life, we handle it just the same as the
6694 * expected FAILURE.
6695 */
6696 struct ssh_channel *c;
6697
6698 c = ssh2_channel_msg(ssh, pktin);
6699 if (!c)
6700 return;
6701 if (!ssh2_handle_winadj_response(c))
6702 ssh_disconnect(ssh, NULL,
6703 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6704 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6705 }
6706
6707 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6708 {
6709 /*
6710 * The only time this should get called is for "winadj@putty"
6711 * messages sent above. All other channel requests are either
6712 * sent with want_reply false or are sent before this handler gets
6713 * installed.
6714 */
6715 struct ssh_channel *c;
6716
6717 c = ssh2_channel_msg(ssh, pktin);
6718 if (!c)
6719 return;
6720 if (!ssh2_handle_winadj_response(c))
6721 ssh_disconnect(ssh, NULL,
6722 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6723 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6724 }
6725
6726 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6727 {
6728 struct ssh_channel *c;
6729 c = ssh2_channel_msg(ssh, pktin);
6730 if (!c)
6731 return;
6732 if (!(c->closes & CLOSES_SENT_EOF)) {
6733 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6734 ssh2_try_send_and_unthrottle(ssh, c);
6735 }
6736 }
6737
6738 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6739 {
6740 char *data;
6741 int length;
6742 struct ssh_channel *c;
6743 c = ssh2_channel_msg(ssh, pktin);
6744 if (!c)
6745 return;
6746 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6747 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6748 return; /* extended but not stderr */
6749 ssh_pkt_getstring(pktin, &data, &length);
6750 if (data) {
6751 int bufsize = 0;
6752 c->v.v2.locwindow -= length;
6753 c->v.v2.remlocwin -= length;
6754 switch (c->type) {
6755 case CHAN_MAINSESSION:
6756 bufsize =
6757 from_backend(ssh->frontend, pktin->type ==
6758 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6759 data, length);
6760 break;
6761 case CHAN_X11:
6762 bufsize = x11_send(c->u.x11.s, data, length);
6763 break;
6764 case CHAN_SOCKDATA:
6765 bufsize = pfd_send(c->u.pfd.s, data, length);
6766 break;
6767 case CHAN_AGENT:
6768 while (length > 0) {
6769 if (c->u.a.lensofar < 4) {
6770 unsigned int l = min(4 - c->u.a.lensofar,
6771 (unsigned)length);
6772 memcpy(c->u.a.msglen + c->u.a.lensofar,
6773 data, l);
6774 data += l;
6775 length -= l;
6776 c->u.a.lensofar += l;
6777 }
6778 if (c->u.a.lensofar == 4) {
6779 c->u.a.totallen =
6780 4 + GET_32BIT(c->u.a.msglen);
6781 c->u.a.message = snewn(c->u.a.totallen,
6782 unsigned char);
6783 memcpy(c->u.a.message, c->u.a.msglen, 4);
6784 }
6785 if (c->u.a.lensofar >= 4 && length > 0) {
6786 unsigned int l =
6787 min(c->u.a.totallen - c->u.a.lensofar,
6788 (unsigned)length);
6789 memcpy(c->u.a.message + c->u.a.lensofar,
6790 data, l);
6791 data += l;
6792 length -= l;
6793 c->u.a.lensofar += l;
6794 }
6795 if (c->u.a.lensofar == c->u.a.totallen) {
6796 void *reply;
6797 int replylen;
6798 if (agent_query(c->u.a.message,
6799 c->u.a.totallen,
6800 &reply, &replylen,
6801 ssh_agentf_callback, c))
6802 ssh_agentf_callback(c, reply, replylen);
6803 sfree(c->u.a.message);
6804 c->u.a.message = NULL;
6805 c->u.a.lensofar = 0;
6806 }
6807 }
6808 bufsize = 0;
6809 break;
6810 }
6811 /*
6812 * If it looks like the remote end hit the end of its window,
6813 * and we didn't want it to do that, think about using a
6814 * larger window.
6815 */
6816 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6817 c->v.v2.locmaxwin < 0x40000000)
6818 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6819 /*
6820 * If we are not buffering too much data,
6821 * enlarge the window again at the remote side.
6822 * If we are buffering too much, we may still
6823 * need to adjust the window if the server's
6824 * sent excess data.
6825 */
6826 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6827 c->v.v2.locmaxwin - bufsize : 0);
6828 /*
6829 * If we're either buffering way too much data, or if we're
6830 * buffering anything at all and we're in "simple" mode,
6831 * throttle the whole channel.
6832 */
6833 if ((bufsize > c->v.v2.locmaxwin ||
6834 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6835 !c->throttling_conn) {
6836 c->throttling_conn = 1;
6837 ssh_throttle_conn(ssh, +1);
6838 }
6839 }
6840 }
6841
6842 static void ssh_channel_destroy(struct ssh_channel *c)
6843 {
6844 Ssh ssh = c->ssh;
6845
6846 switch (c->type) {
6847 case CHAN_MAINSESSION:
6848 ssh->mainchan = NULL;
6849 update_specials_menu(ssh->frontend);
6850 break;
6851 case CHAN_X11:
6852 if (c->u.x11.s != NULL)
6853 x11_close(c->u.x11.s);
6854 logevent("Forwarded X11 connection terminated");
6855 break;
6856 case CHAN_AGENT:
6857 sfree(c->u.a.message);
6858 break;
6859 case CHAN_SOCKDATA:
6860 if (c->u.pfd.s != NULL)
6861 pfd_close(c->u.pfd.s);
6862 logevent("Forwarded port closed");
6863 break;
6864 }
6865
6866 del234(ssh->channels, c);
6867 if (ssh->version == 2)
6868 bufchain_clear(&c->v.v2.outbuffer);
6869 sfree(c);
6870
6871 /*
6872 * See if that was the last channel left open.
6873 * (This is only our termination condition if we're
6874 * not running in -N mode.)
6875 */
6876 if (ssh->version == 2 &&
6877 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6878 count234(ssh->channels) == 0) {
6879 /*
6880 * We used to send SSH_MSG_DISCONNECT here,
6881 * because I'd believed that _every_ conforming
6882 * SSH-2 connection had to end with a disconnect
6883 * being sent by at least one side; apparently
6884 * I was wrong and it's perfectly OK to
6885 * unceremoniously slam the connection shut
6886 * when you're done, and indeed OpenSSH feels
6887 * this is more polite than sending a
6888 * DISCONNECT. So now we don't.
6889 */
6890 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6891 }
6892 }
6893
6894 static void ssh2_channel_check_close(struct ssh_channel *c)
6895 {
6896 Ssh ssh = c->ssh;
6897 struct Packet *pktout;
6898
6899 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6900 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
6901 /*
6902 * We have both sent and received EOF, and we have no
6903 * outstanding winadj channel requests, which means the
6904 * channel is in final wind-up. But we haven't sent CLOSE, so
6905 * let's do so now.
6906 */
6907 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6908 ssh2_pkt_adduint32(pktout, c->remoteid);
6909 ssh2_pkt_send(ssh, pktout);
6910 c->closes |= CLOSES_SENT_CLOSE;
6911 }
6912
6913 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6914 /*
6915 * We have both sent and received CLOSE, which means we're
6916 * completely done with the channel.
6917 */
6918 ssh_channel_destroy(c);
6919 }
6920 }
6921
6922 static void ssh2_channel_got_eof(struct ssh_channel *c)
6923 {
6924 if (c->closes & CLOSES_RCVD_EOF)
6925 return; /* already seen EOF */
6926 c->closes |= CLOSES_RCVD_EOF;
6927
6928 if (c->type == CHAN_X11) {
6929 x11_send_eof(c->u.x11.s);
6930 } else if (c->type == CHAN_AGENT) {
6931 /* Manufacture an outgoing EOF in response to the incoming one. */
6932 sshfwd_write_eof(c);
6933 } else if (c->type == CHAN_SOCKDATA) {
6934 pfd_send_eof(c->u.pfd.s);
6935 } else if (c->type == CHAN_MAINSESSION) {
6936 Ssh ssh = c->ssh;
6937
6938 if (!ssh->sent_console_eof &&
6939 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6940 /*
6941 * Either from_backend_eof told us that the front end
6942 * wants us to close the outgoing side of the connection
6943 * as soon as we see EOF from the far end, or else we've
6944 * unilaterally decided to do that because we've allocated
6945 * a remote pty and hence EOF isn't a particularly
6946 * meaningful concept.
6947 */
6948 sshfwd_write_eof(c);
6949 }
6950 ssh->sent_console_eof = TRUE;
6951 }
6952
6953 ssh2_channel_check_close(c);
6954 }
6955
6956 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6957 {
6958 struct ssh_channel *c;
6959
6960 c = ssh2_channel_msg(ssh, pktin);
6961 if (!c)
6962 return;
6963 ssh2_channel_got_eof(c);
6964 }
6965
6966 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6967 {
6968 struct ssh_channel *c;
6969
6970 c = ssh2_channel_msg(ssh, pktin);
6971 if (!c)
6972 return;
6973
6974 /*
6975 * When we receive CLOSE on a channel, we assume it comes with an
6976 * implied EOF if we haven't seen EOF yet.
6977 */
6978 ssh2_channel_got_eof(c);
6979
6980 /*
6981 * And we also send an outgoing EOF, if we haven't already, on the
6982 * assumption that CLOSE is a pretty forceful announcement that
6983 * the remote side is doing away with the entire channel. (If it
6984 * had wanted to send us EOF and continue receiving data from us,
6985 * it would have just sent CHANNEL_EOF.)
6986 *
6987 * For the moment, this policy applies to the main session channel
6988 * only, because we have a convenient mechanism (ssh->send_ok) for
6989 * ceasing to read from our local data source. Ideally I think
6990 * we'd do this for auxiliary channels too, which would need an
6991 * extra API call in the forwarding modules.
6992 */
6993 if (c->type == CHAN_MAINSESSION && !(c->closes & CLOSES_SENT_EOF)) {
6994 sshfwd_write_eof(ssh->mainchan);
6995 ssh->send_ok = 0; /* now stop trying to read from stdin */
6996 }
6997
6998 /*
6999 * Now process the actual close.
7000 */
7001 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7002 c->closes |= CLOSES_RCVD_CLOSE;
7003 ssh2_channel_check_close(c);
7004 }
7005 }
7006
7007 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7008 {
7009 struct ssh_channel *c;
7010
7011 c = ssh2_channel_msg(ssh, pktin);
7012 if (!c)
7013 return;
7014 if (c->type != CHAN_SOCKDATA_DORMANT)
7015 return; /* dunno why they're confirming this */
7016 c->remoteid = ssh_pkt_getuint32(pktin);
7017 c->halfopen = FALSE;
7018 c->type = CHAN_SOCKDATA;
7019 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7020 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7021 if (c->u.pfd.s)
7022 pfd_confirm(c->u.pfd.s);
7023 if (c->pending_eof)
7024 ssh_channel_try_eof(c);
7025 }
7026
7027 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7028 {
7029 static const char *const reasons[] = {
7030 "<unknown reason code>",
7031 "Administratively prohibited",
7032 "Connect failed",
7033 "Unknown channel type",
7034 "Resource shortage",
7035 };
7036 unsigned reason_code;
7037 char *reason_string;
7038 int reason_length;
7039 struct ssh_channel *c;
7040 c = ssh2_channel_msg(ssh, pktin);
7041 if (!c)
7042 return;
7043 if (c->type != CHAN_SOCKDATA_DORMANT)
7044 return; /* dunno why they're failing this */
7045
7046 reason_code = ssh_pkt_getuint32(pktin);
7047 if (reason_code >= lenof(reasons))
7048 reason_code = 0; /* ensure reasons[reason_code] in range */
7049 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7050 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7051 reasons[reason_code], reason_length, reason_string);
7052
7053 pfd_close(c->u.pfd.s);
7054
7055 del234(ssh->channels, c);
7056 sfree(c);
7057 }
7058
7059 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7060 {
7061 char *type;
7062 int typelen, want_reply;
7063 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7064 struct ssh_channel *c;
7065 struct Packet *pktout;
7066
7067 c = ssh2_channel_msg(ssh, pktin);
7068 if (!c)
7069 return;
7070 ssh_pkt_getstring(pktin, &type, &typelen);
7071 want_reply = ssh2_pkt_getbool(pktin);
7072
7073 /*
7074 * Having got the channel number, we now look at
7075 * the request type string to see if it's something
7076 * we recognise.
7077 */
7078 if (c == ssh->mainchan) {
7079 /*
7080 * We recognise "exit-status" and "exit-signal" on
7081 * the primary channel.
7082 */
7083 if (typelen == 11 &&
7084 !memcmp(type, "exit-status", 11)) {
7085
7086 ssh->exitcode = ssh_pkt_getuint32(pktin);
7087 logeventf(ssh, "Server sent command exit status %d",
7088 ssh->exitcode);
7089 reply = SSH2_MSG_CHANNEL_SUCCESS;
7090
7091 } else if (typelen == 11 &&
7092 !memcmp(type, "exit-signal", 11)) {
7093
7094 int is_plausible = TRUE, is_int = FALSE;
7095 char *fmt_sig = "", *fmt_msg = "";
7096 char *msg;
7097 int msglen = 0, core = FALSE;
7098 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7099 * provide an `int' for the signal, despite its
7100 * having been a `string' in the drafts of RFC 4254 since at
7101 * least 2001. (Fixed in session.c 1.147.) Try to
7102 * infer which we can safely parse it as. */
7103 {
7104 unsigned char *p = pktin->body +
7105 pktin->savedpos;
7106 long len = pktin->length - pktin->savedpos;
7107 unsigned long num = GET_32BIT(p); /* what is it? */
7108 /* If it's 0, it hardly matters; assume string */
7109 if (num == 0) {
7110 is_int = FALSE;
7111 } else {
7112 int maybe_int = FALSE, maybe_str = FALSE;
7113 #define CHECK_HYPOTHESIS(offset, result) \
7114 do { \
7115 long q = offset; \
7116 if (q >= 0 && q+4 <= len) { \
7117 q = q + 4 + GET_32BIT(p+q); \
7118 if (q >= 0 && q+4 <= len && \
7119 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7120 result = TRUE; \
7121 } \
7122 } while(0)
7123 CHECK_HYPOTHESIS(4+1, maybe_int);
7124 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7125 #undef CHECK_HYPOTHESIS
7126 if (maybe_int && !maybe_str)
7127 is_int = TRUE;
7128 else if (!maybe_int && maybe_str)
7129 is_int = FALSE;
7130 else
7131 /* Crikey. Either or neither. Panic. */
7132 is_plausible = FALSE;
7133 }
7134 }
7135 ssh->exitcode = 128; /* means `unknown signal' */
7136 if (is_plausible) {
7137 if (is_int) {
7138 /* Old non-standard OpenSSH. */
7139 int signum = ssh_pkt_getuint32(pktin);
7140 fmt_sig = dupprintf(" %d", signum);
7141 ssh->exitcode = 128 + signum;
7142 } else {
7143 /* As per RFC 4254. */
7144 char *sig;
7145 int siglen;
7146 ssh_pkt_getstring(pktin, &sig, &siglen);
7147 /* Signal name isn't supposed to be blank, but
7148 * let's cope gracefully if it is. */
7149 if (siglen) {
7150 fmt_sig = dupprintf(" \"%.*s\"",
7151 siglen, sig);
7152 }
7153
7154 /*
7155 * Really hideous method of translating the
7156 * signal description back into a locally
7157 * meaningful number.
7158 */
7159
7160 if (0)
7161 ;
7162 #define TRANSLATE_SIGNAL(s) \
7163 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7164 ssh->exitcode = 128 + SIG ## s
7165 #ifdef SIGABRT
7166 TRANSLATE_SIGNAL(ABRT);
7167 #endif
7168 #ifdef SIGALRM
7169 TRANSLATE_SIGNAL(ALRM);
7170 #endif
7171 #ifdef SIGFPE
7172 TRANSLATE_SIGNAL(FPE);
7173 #endif
7174 #ifdef SIGHUP
7175 TRANSLATE_SIGNAL(HUP);
7176 #endif
7177 #ifdef SIGILL
7178 TRANSLATE_SIGNAL(ILL);
7179 #endif
7180 #ifdef SIGINT
7181 TRANSLATE_SIGNAL(INT);
7182 #endif
7183 #ifdef SIGKILL
7184 TRANSLATE_SIGNAL(KILL);
7185 #endif
7186 #ifdef SIGPIPE
7187 TRANSLATE_SIGNAL(PIPE);
7188 #endif
7189 #ifdef SIGQUIT
7190 TRANSLATE_SIGNAL(QUIT);
7191 #endif
7192 #ifdef SIGSEGV
7193 TRANSLATE_SIGNAL(SEGV);
7194 #endif
7195 #ifdef SIGTERM
7196 TRANSLATE_SIGNAL(TERM);
7197 #endif
7198 #ifdef SIGUSR1
7199 TRANSLATE_SIGNAL(USR1);
7200 #endif
7201 #ifdef SIGUSR2
7202 TRANSLATE_SIGNAL(USR2);
7203 #endif
7204 #undef TRANSLATE_SIGNAL
7205 else
7206 ssh->exitcode = 128;
7207 }
7208 core = ssh2_pkt_getbool(pktin);
7209 ssh_pkt_getstring(pktin, &msg, &msglen);
7210 if (msglen) {
7211 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7212 }
7213 /* ignore lang tag */
7214 } /* else don't attempt to parse */
7215 logeventf(ssh, "Server exited on signal%s%s%s",
7216 fmt_sig, core ? " (core dumped)" : "",
7217 fmt_msg);
7218 if (*fmt_sig) sfree(fmt_sig);
7219 if (*fmt_msg) sfree(fmt_msg);
7220 reply = SSH2_MSG_CHANNEL_SUCCESS;
7221
7222 }
7223 } else {
7224 /*
7225 * This is a channel request we don't know
7226 * about, so we now either ignore the request
7227 * or respond with CHANNEL_FAILURE, depending
7228 * on want_reply.
7229 */
7230 reply = SSH2_MSG_CHANNEL_FAILURE;
7231 }
7232 if (want_reply) {
7233 pktout = ssh2_pkt_init(reply);
7234 ssh2_pkt_adduint32(pktout, c->remoteid);
7235 ssh2_pkt_send(ssh, pktout);
7236 }
7237 }
7238
7239 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7240 {
7241 char *type;
7242 int typelen, want_reply;
7243 struct Packet *pktout;
7244
7245 ssh_pkt_getstring(pktin, &type, &typelen);
7246 want_reply = ssh2_pkt_getbool(pktin);
7247
7248 /*
7249 * We currently don't support any global requests
7250 * at all, so we either ignore the request or
7251 * respond with REQUEST_FAILURE, depending on
7252 * want_reply.
7253 */
7254 if (want_reply) {
7255 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7256 ssh2_pkt_send(ssh, pktout);
7257 }
7258 }
7259
7260 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7261 {
7262 char *type;
7263 int typelen;
7264 char *peeraddr;
7265 int peeraddrlen;
7266 int peerport;
7267 char *error = NULL;
7268 struct ssh_channel *c;
7269 unsigned remid, winsize, pktsize;
7270 struct Packet *pktout;
7271
7272 ssh_pkt_getstring(pktin, &type, &typelen);
7273 c = snew(struct ssh_channel);
7274 c->ssh = ssh;
7275
7276 remid = ssh_pkt_getuint32(pktin);
7277 winsize = ssh_pkt_getuint32(pktin);
7278 pktsize = ssh_pkt_getuint32(pktin);
7279
7280 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7281 char *addrstr;
7282 const char *x11err;
7283
7284 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7285 addrstr = snewn(peeraddrlen+1, char);
7286 memcpy(addrstr, peeraddr, peeraddrlen);
7287 addrstr[peeraddrlen] = '\0';
7288 peerport = ssh_pkt_getuint32(pktin);
7289
7290 logeventf(ssh, "Received X11 connect request from %s:%d",
7291 addrstr, peerport);
7292
7293 if (!ssh->X11_fwd_enabled)
7294 error = "X11 forwarding is not enabled";
7295 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7296 addrstr, peerport, ssh->conf)) != NULL) {
7297 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7298 error = "Unable to open an X11 connection";
7299 } else {
7300 logevent("Opening X11 forward connection succeeded");
7301 c->type = CHAN_X11;
7302 }
7303
7304 sfree(addrstr);
7305 } else if (typelen == 15 &&
7306 !memcmp(type, "forwarded-tcpip", 15)) {
7307 struct ssh_rportfwd pf, *realpf;
7308 char *dummy;
7309 int dummylen;
7310 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7311 pf.sport = ssh_pkt_getuint32(pktin);
7312 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7313 peerport = ssh_pkt_getuint32(pktin);
7314 realpf = find234(ssh->rportfwds, &pf, NULL);
7315 logeventf(ssh, "Received remote port %d open request "
7316 "from %s:%d", pf.sport, peeraddr, peerport);
7317 if (realpf == NULL) {
7318 error = "Remote port is not recognised";
7319 } else {
7320 const char *e = pfd_newconnect(&c->u.pfd.s,
7321 realpf->dhost,
7322 realpf->dport, c,
7323 ssh->conf,
7324 realpf->pfrec->addressfamily);
7325 logeventf(ssh, "Attempting to forward remote port to "
7326 "%s:%d", realpf->dhost, realpf->dport);
7327 if (e != NULL) {
7328 logeventf(ssh, "Port open failed: %s", e);
7329 error = "Port open failed";
7330 } else {
7331 logevent("Forwarded port opened successfully");
7332 c->type = CHAN_SOCKDATA;
7333 }
7334 }
7335 } else if (typelen == 22 &&
7336 !memcmp(type, "auth-agent@openssh.com", 22)) {
7337 if (!ssh->agentfwd_enabled)
7338 error = "Agent forwarding is not enabled";
7339 else {
7340 c->type = CHAN_AGENT; /* identify channel type */
7341 c->u.a.lensofar = 0;
7342 }
7343 } else {
7344 error = "Unsupported channel type requested";
7345 }
7346
7347 c->remoteid = remid;
7348 c->halfopen = FALSE;
7349 if (error) {
7350 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7351 ssh2_pkt_adduint32(pktout, c->remoteid);
7352 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7353 ssh2_pkt_addstring(pktout, error);
7354 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7355 ssh2_pkt_send(ssh, pktout);
7356 logeventf(ssh, "Rejected channel open: %s", error);
7357 sfree(c);
7358 } else {
7359 ssh2_channel_init(c);
7360 c->v.v2.remwindow = winsize;
7361 c->v.v2.remmaxpkt = pktsize;
7362 add234(ssh->channels, c);
7363 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7364 ssh2_pkt_adduint32(pktout, c->remoteid);
7365 ssh2_pkt_adduint32(pktout, c->localid);
7366 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7367 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7368 ssh2_pkt_send(ssh, pktout);
7369 }
7370 }
7371
7372 /*
7373 * Buffer banner messages for later display at some convenient point,
7374 * if we're going to display them.
7375 */
7376 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7377 {
7378 /* Arbitrary limit to prevent unbounded inflation of buffer */
7379 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7380 bufchain_size(&ssh->banner) <= 131072) {
7381 char *banner = NULL;
7382 int size = 0;
7383 ssh_pkt_getstring(pktin, &banner, &size);
7384 if (banner)
7385 bufchain_add(&ssh->banner, banner, size);
7386 }
7387 }
7388
7389 /* Helper function to deal with sending tty modes for "pty-req" */
7390 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7391 {
7392 struct Packet *pktout = (struct Packet *)data;
7393 int i = 0;
7394 unsigned int arg = 0;
7395 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7396 if (i == lenof(ssh_ttymodes)) return;
7397 switch (ssh_ttymodes[i].type) {
7398 case TTY_OP_CHAR:
7399 arg = ssh_tty_parse_specchar(val);
7400 break;
7401 case TTY_OP_BOOL:
7402 arg = ssh_tty_parse_boolean(val);
7403 break;
7404 }
7405 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7406 ssh2_pkt_adduint32(pktout, arg);
7407 }
7408
7409 /*
7410 * Handle the SSH-2 userauth and connection layers.
7411 */
7412 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7413 struct Packet *pktin)
7414 {
7415 struct do_ssh2_authconn_state {
7416 enum {
7417 AUTH_TYPE_NONE,
7418 AUTH_TYPE_PUBLICKEY,
7419 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7420 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7421 AUTH_TYPE_PASSWORD,
7422 AUTH_TYPE_GSSAPI, /* always QUIET */
7423 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7424 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7425 } type;
7426 int done_service_req;
7427 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7428 int tried_pubkey_config, done_agent;
7429 #ifndef NO_GSSAPI
7430 int can_gssapi;
7431 int tried_gssapi;
7432 #endif
7433 int kbd_inter_refused;
7434 int we_are_in, userauth_success;
7435 prompts_t *cur_prompt;
7436 int num_prompts;
7437 char *username;
7438 char *password;
7439 int got_username;
7440 void *publickey_blob;
7441 int publickey_bloblen;
7442 int publickey_encrypted;
7443 char *publickey_algorithm;
7444 char *publickey_comment;
7445 unsigned char agent_request[5], *agent_response, *agentp;
7446 int agent_responselen;
7447 unsigned char *pkblob_in_agent;
7448 int keyi, nkeys;
7449 char *pkblob, *alg, *commentp;
7450 int pklen, alglen, commentlen;
7451 int siglen, retlen, len;
7452 char *q, *agentreq, *ret;
7453 int try_send;
7454 int num_env, env_left, env_ok;
7455 struct Packet *pktout;
7456 Filename *keyfile;
7457 #ifndef NO_GSSAPI
7458 struct ssh_gss_library *gsslib;
7459 Ssh_gss_ctx gss_ctx;
7460 Ssh_gss_buf gss_buf;
7461 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7462 Ssh_gss_name gss_srv_name;
7463 Ssh_gss_stat gss_stat;
7464 #endif
7465 };
7466 crState(do_ssh2_authconn_state);
7467
7468 crBegin(ssh->do_ssh2_authconn_crstate);
7469
7470 s->done_service_req = FALSE;
7471 s->we_are_in = s->userauth_success = FALSE;
7472 #ifndef NO_GSSAPI
7473 s->tried_gssapi = FALSE;
7474 #endif
7475
7476 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7477 /*
7478 * Request userauth protocol, and await a response to it.
7479 */
7480 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7481 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7482 ssh2_pkt_send(ssh, s->pktout);
7483 crWaitUntilV(pktin);
7484 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7485 s->done_service_req = TRUE;
7486 }
7487 if (!s->done_service_req) {
7488 /*
7489 * Request connection protocol directly, without authentication.
7490 */
7491 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7492 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7493 ssh2_pkt_send(ssh, s->pktout);
7494 crWaitUntilV(pktin);
7495 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7496 s->we_are_in = TRUE; /* no auth required */
7497 } else {
7498 bombout(("Server refused service request"));
7499 crStopV;
7500 }
7501 }
7502
7503 /* Arrange to be able to deal with any BANNERs that come in.
7504 * (We do this now as packets may come in during the next bit.) */
7505 bufchain_init(&ssh->banner);
7506 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7507 ssh2_msg_userauth_banner;
7508
7509 /*
7510 * Misc one-time setup for authentication.
7511 */
7512 s->publickey_blob = NULL;
7513 if (!s->we_are_in) {
7514
7515 /*
7516 * Load the public half of any configured public key file
7517 * for later use.
7518 */
7519 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7520 if (!filename_is_null(*s->keyfile)) {
7521 int keytype;
7522 logeventf(ssh, "Reading private key file \"%.150s\"",
7523 filename_to_str(s->keyfile));
7524 keytype = key_type(s->keyfile);
7525 if (keytype == SSH_KEYTYPE_SSH2) {
7526 const char *error;
7527 s->publickey_blob =
7528 ssh2_userkey_loadpub(s->keyfile,
7529 &s->publickey_algorithm,
7530 &s->publickey_bloblen,
7531 &s->publickey_comment, &error);
7532 if (s->publickey_blob) {
7533 s->publickey_encrypted =
7534 ssh2_userkey_encrypted(s->keyfile, NULL);
7535 } else {
7536 char *msgbuf;
7537 logeventf(ssh, "Unable to load private key (%s)",
7538 error);
7539 msgbuf = dupprintf("Unable to load private key file "
7540 "\"%.150s\" (%s)\r\n",
7541 filename_to_str(s->keyfile),
7542 error);
7543 c_write_str(ssh, msgbuf);
7544 sfree(msgbuf);
7545 }
7546 } else {
7547 char *msgbuf;
7548 logeventf(ssh, "Unable to use this key file (%s)",
7549 key_type_to_str(keytype));
7550 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7551 " (%s)\r\n",
7552 filename_to_str(s->keyfile),
7553 key_type_to_str(keytype));
7554 c_write_str(ssh, msgbuf);
7555 sfree(msgbuf);
7556 s->publickey_blob = NULL;
7557 }
7558 }
7559
7560 /*
7561 * Find out about any keys Pageant has (but if there's a
7562 * public key configured, filter out all others).
7563 */
7564 s->nkeys = 0;
7565 s->agent_response = NULL;
7566 s->pkblob_in_agent = NULL;
7567 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7568
7569 void *r;
7570
7571 logevent("Pageant is running. Requesting keys.");
7572
7573 /* Request the keys held by the agent. */
7574 PUT_32BIT(s->agent_request, 1);
7575 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7576 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7577 ssh_agent_callback, ssh)) {
7578 do {
7579 crReturnV;
7580 if (pktin) {
7581 bombout(("Unexpected data from server while"
7582 " waiting for agent response"));
7583 crStopV;
7584 }
7585 } while (pktin || inlen > 0);
7586 r = ssh->agent_response;
7587 s->agent_responselen = ssh->agent_response_len;
7588 }
7589 s->agent_response = (unsigned char *) r;
7590 if (s->agent_response && s->agent_responselen >= 5 &&
7591 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7592 int keyi;
7593 unsigned char *p;
7594 p = s->agent_response + 5;
7595 s->nkeys = GET_32BIT(p);
7596 p += 4;
7597 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7598 if (s->publickey_blob) {
7599 /* See if configured key is in agent. */
7600 for (keyi = 0; keyi < s->nkeys; keyi++) {
7601 s->pklen = GET_32BIT(p);
7602 if (s->pklen == s->publickey_bloblen &&
7603 !memcmp(p+4, s->publickey_blob,
7604 s->publickey_bloblen)) {
7605 logeventf(ssh, "Pageant key #%d matches "
7606 "configured key file", keyi);
7607 s->keyi = keyi;
7608 s->pkblob_in_agent = p;
7609 break;
7610 }
7611 p += 4 + s->pklen;
7612 p += GET_32BIT(p) + 4; /* comment */
7613 }
7614 if (!s->pkblob_in_agent) {
7615 logevent("Configured key file not in Pageant");
7616 s->nkeys = 0;
7617 }
7618 }
7619 } else {
7620 logevent("Failed to get reply from Pageant");
7621 }
7622 }
7623
7624 }
7625
7626 /*
7627 * We repeat this whole loop, including the username prompt,
7628 * until we manage a successful authentication. If the user
7629 * types the wrong _password_, they can be sent back to the
7630 * beginning to try another username, if this is configured on.
7631 * (If they specify a username in the config, they are never
7632 * asked, even if they do give a wrong password.)
7633 *
7634 * I think this best serves the needs of
7635 *
7636 * - the people who have no configuration, no keys, and just
7637 * want to try repeated (username,password) pairs until they
7638 * type both correctly
7639 *
7640 * - people who have keys and configuration but occasionally
7641 * need to fall back to passwords
7642 *
7643 * - people with a key held in Pageant, who might not have
7644 * logged in to a particular machine before; so they want to
7645 * type a username, and then _either_ their key will be
7646 * accepted, _or_ they will type a password. If they mistype
7647 * the username they will want to be able to get back and
7648 * retype it!
7649 */
7650 s->got_username = FALSE;
7651 while (!s->we_are_in) {
7652 /*
7653 * Get a username.
7654 */
7655 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
7656 /*
7657 * We got a username last time round this loop, and
7658 * with change_username turned off we don't try to get
7659 * it again.
7660 */
7661 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
7662 int ret; /* need not be kept over crReturn */
7663 s->cur_prompt = new_prompts(ssh->frontend);
7664 s->cur_prompt->to_server = TRUE;
7665 s->cur_prompt->name = dupstr("SSH login name");
7666 /* 512 is an arbitrary limit :-( */
7667 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE, 512);
7668 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7669 while (ret < 0) {
7670 ssh->send_ok = 1;
7671 crWaitUntilV(!pktin);
7672 ret = get_userpass_input(s->cur_prompt, in, inlen);
7673 ssh->send_ok = 0;
7674 }
7675 if (!ret) {
7676 /*
7677 * get_userpass_input() failed to get a username.
7678 * Terminate.
7679 */
7680 free_prompts(s->cur_prompt);
7681 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7682 crStopV;
7683 }
7684 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
7685 free_prompts(s->cur_prompt);
7686 } else {
7687 char *stuff;
7688 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7689 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
7690 c_write_str(ssh, stuff);
7691 sfree(stuff);
7692 }
7693 }
7694 s->got_username = TRUE;
7695
7696 /*
7697 * Send an authentication request using method "none": (a)
7698 * just in case it succeeds, and (b) so that we know what
7699 * authentication methods we can usefully try next.
7700 */
7701 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7702
7703 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7704 ssh2_pkt_addstring(s->pktout, ssh->username);
7705 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7706 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7707 ssh2_pkt_send(ssh, s->pktout);
7708 s->type = AUTH_TYPE_NONE;
7709 s->gotit = FALSE;
7710 s->we_are_in = FALSE;
7711
7712 s->tried_pubkey_config = FALSE;
7713 s->kbd_inter_refused = FALSE;
7714
7715 /* Reset agent request state. */
7716 s->done_agent = FALSE;
7717 if (s->agent_response) {
7718 if (s->pkblob_in_agent) {
7719 s->agentp = s->pkblob_in_agent;
7720 } else {
7721 s->agentp = s->agent_response + 5 + 4;
7722 s->keyi = 0;
7723 }
7724 }
7725
7726 while (1) {
7727 char *methods = NULL;
7728 int methlen = 0;
7729
7730 /*
7731 * Wait for the result of the last authentication request.
7732 */
7733 if (!s->gotit)
7734 crWaitUntilV(pktin);
7735 /*
7736 * Now is a convenient point to spew any banner material
7737 * that we've accumulated. (This should ensure that when
7738 * we exit the auth loop, we haven't any left to deal
7739 * with.)
7740 */
7741 {
7742 int size = bufchain_size(&ssh->banner);
7743 /*
7744 * Don't show the banner if we're operating in
7745 * non-verbose non-interactive mode. (It's probably
7746 * a script, which means nobody will read the
7747 * banner _anyway_, and moreover the printing of
7748 * the banner will screw up processing on the
7749 * output of (say) plink.)
7750 */
7751 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7752 char *banner = snewn(size, char);
7753 bufchain_fetch(&ssh->banner, banner, size);
7754 c_write_untrusted(ssh, banner, size);
7755 sfree(banner);
7756 }
7757 bufchain_clear(&ssh->banner);
7758 }
7759 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7760 logevent("Access granted");
7761 s->we_are_in = s->userauth_success = TRUE;
7762 break;
7763 }
7764
7765 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7766 bombout(("Strange packet received during authentication: "
7767 "type %d", pktin->type));
7768 crStopV;
7769 }
7770
7771 s->gotit = FALSE;
7772
7773 /*
7774 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7775 * we can look at the string in it and know what we can
7776 * helpfully try next.
7777 */
7778 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7779 ssh_pkt_getstring(pktin, &methods, &methlen);
7780 if (!ssh2_pkt_getbool(pktin)) {
7781 /*
7782 * We have received an unequivocal Access
7783 * Denied. This can translate to a variety of
7784 * messages, or no message at all.
7785 *
7786 * For forms of authentication which are attempted
7787 * implicitly, by which I mean without printing
7788 * anything in the window indicating that we're
7789 * trying them, we should never print 'Access
7790 * denied'.
7791 *
7792 * If we do print a message saying that we're
7793 * attempting some kind of authentication, it's OK
7794 * to print a followup message saying it failed -
7795 * but the message may sometimes be more specific
7796 * than simply 'Access denied'.
7797 *
7798 * Additionally, if we'd just tried password
7799 * authentication, we should break out of this
7800 * whole loop so as to go back to the username
7801 * prompt (iff we're configured to allow
7802 * username change attempts).
7803 */
7804 if (s->type == AUTH_TYPE_NONE) {
7805 /* do nothing */
7806 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7807 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7808 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7809 c_write_str(ssh, "Server refused our key\r\n");
7810 logevent("Server refused our key");
7811 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7812 /* This _shouldn't_ happen except by a
7813 * protocol bug causing client and server to
7814 * disagree on what is a correct signature. */
7815 c_write_str(ssh, "Server refused public-key signature"
7816 " despite accepting key!\r\n");
7817 logevent("Server refused public-key signature"
7818 " despite accepting key!");
7819 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7820 /* quiet, so no c_write */
7821 logevent("Server refused keyboard-interactive authentication");
7822 } else if (s->type==AUTH_TYPE_GSSAPI) {
7823 /* always quiet, so no c_write */
7824 /* also, the code down in the GSSAPI block has
7825 * already logged this in the Event Log */
7826 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7827 logevent("Keyboard-interactive authentication failed");
7828 c_write_str(ssh, "Access denied\r\n");
7829 } else {
7830 assert(s->type == AUTH_TYPE_PASSWORD);
7831 logevent("Password authentication failed");
7832 c_write_str(ssh, "Access denied\r\n");
7833
7834 if (conf_get_int(ssh->conf, CONF_change_username)) {
7835 /* XXX perhaps we should allow
7836 * keyboard-interactive to do this too? */
7837 s->we_are_in = FALSE;
7838 break;
7839 }
7840 }
7841 } else {
7842 c_write_str(ssh, "Further authentication required\r\n");
7843 logevent("Further authentication required");
7844 }
7845
7846 s->can_pubkey =
7847 in_commasep_string("publickey", methods, methlen);
7848 s->can_passwd =
7849 in_commasep_string("password", methods, methlen);
7850 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
7851 in_commasep_string("keyboard-interactive", methods, methlen);
7852 #ifndef NO_GSSAPI
7853 if (!ssh->gsslibs)
7854 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7855 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
7856 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7857 ssh->gsslibs->nlibraries > 0;
7858 #endif
7859 }
7860
7861 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7862
7863 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7864
7865 /*
7866 * Attempt public-key authentication using a key from Pageant.
7867 */
7868
7869 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7870
7871 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7872
7873 /* Unpack key from agent response */
7874 s->pklen = GET_32BIT(s->agentp);
7875 s->agentp += 4;
7876 s->pkblob = (char *)s->agentp;
7877 s->agentp += s->pklen;
7878 s->alglen = GET_32BIT(s->pkblob);
7879 s->alg = s->pkblob + 4;
7880 s->commentlen = GET_32BIT(s->agentp);
7881 s->agentp += 4;
7882 s->commentp = (char *)s->agentp;
7883 s->agentp += s->commentlen;
7884 /* s->agentp now points at next key, if any */
7885
7886 /* See if server will accept it */
7887 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7888 ssh2_pkt_addstring(s->pktout, ssh->username);
7889 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7890 /* service requested */
7891 ssh2_pkt_addstring(s->pktout, "publickey");
7892 /* method */
7893 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7894 ssh2_pkt_addstring_start(s->pktout);
7895 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7896 ssh2_pkt_addstring_start(s->pktout);
7897 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7898 ssh2_pkt_send(ssh, s->pktout);
7899 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7900
7901 crWaitUntilV(pktin);
7902 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7903
7904 /* Offer of key refused. */
7905 s->gotit = TRUE;
7906
7907 } else {
7908
7909 void *vret;
7910
7911 if (flags & FLAG_VERBOSE) {
7912 c_write_str(ssh, "Authenticating with "
7913 "public key \"");
7914 c_write(ssh, s->commentp, s->commentlen);
7915 c_write_str(ssh, "\" from agent\r\n");
7916 }
7917
7918 /*
7919 * Server is willing to accept the key.
7920 * Construct a SIGN_REQUEST.
7921 */
7922 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7923 ssh2_pkt_addstring(s->pktout, ssh->username);
7924 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7925 /* service requested */
7926 ssh2_pkt_addstring(s->pktout, "publickey");
7927 /* method */
7928 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7929 ssh2_pkt_addstring_start(s->pktout);
7930 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7931 ssh2_pkt_addstring_start(s->pktout);
7932 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7933
7934 /* Ask agent for signature. */
7935 s->siglen = s->pktout->length - 5 + 4 +
7936 ssh->v2_session_id_len;
7937 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7938 s->siglen -= 4;
7939 s->len = 1; /* message type */
7940 s->len += 4 + s->pklen; /* key blob */
7941 s->len += 4 + s->siglen; /* data to sign */
7942 s->len += 4; /* flags */
7943 s->agentreq = snewn(4 + s->len, char);
7944 PUT_32BIT(s->agentreq, s->len);
7945 s->q = s->agentreq + 4;
7946 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7947 PUT_32BIT(s->q, s->pklen);
7948 s->q += 4;
7949 memcpy(s->q, s->pkblob, s->pklen);
7950 s->q += s->pklen;
7951 PUT_32BIT(s->q, s->siglen);
7952 s->q += 4;
7953 /* Now the data to be signed... */
7954 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7955 PUT_32BIT(s->q, ssh->v2_session_id_len);
7956 s->q += 4;
7957 }
7958 memcpy(s->q, ssh->v2_session_id,
7959 ssh->v2_session_id_len);
7960 s->q += ssh->v2_session_id_len;
7961 memcpy(s->q, s->pktout->data + 5,
7962 s->pktout->length - 5);
7963 s->q += s->pktout->length - 5;
7964 /* And finally the (zero) flags word. */
7965 PUT_32BIT(s->q, 0);
7966 if (!agent_query(s->agentreq, s->len + 4,
7967 &vret, &s->retlen,
7968 ssh_agent_callback, ssh)) {
7969 do {
7970 crReturnV;
7971 if (pktin) {
7972 bombout(("Unexpected data from server"
7973 " while waiting for agent"
7974 " response"));
7975 crStopV;
7976 }
7977 } while (pktin || inlen > 0);
7978 vret = ssh->agent_response;
7979 s->retlen = ssh->agent_response_len;
7980 }
7981 s->ret = vret;
7982 sfree(s->agentreq);
7983 if (s->ret) {
7984 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7985 logevent("Sending Pageant's response");
7986 ssh2_add_sigblob(ssh, s->pktout,
7987 s->pkblob, s->pklen,
7988 s->ret + 9,
7989 GET_32BIT(s->ret + 5));
7990 ssh2_pkt_send(ssh, s->pktout);
7991 s->type = AUTH_TYPE_PUBLICKEY;
7992 } else {
7993 /* FIXME: less drastic response */
7994 bombout(("Pageant failed to answer challenge"));
7995 crStopV;
7996 }
7997 }
7998 }
7999
8000 /* Do we have any keys left to try? */
8001 if (s->pkblob_in_agent) {
8002 s->done_agent = TRUE;
8003 s->tried_pubkey_config = TRUE;
8004 } else {
8005 s->keyi++;
8006 if (s->keyi >= s->nkeys)
8007 s->done_agent = TRUE;
8008 }
8009
8010 } else if (s->can_pubkey && s->publickey_blob &&
8011 !s->tried_pubkey_config) {
8012
8013 struct ssh2_userkey *key; /* not live over crReturn */
8014 char *passphrase; /* not live over crReturn */
8015
8016 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8017
8018 s->tried_pubkey_config = TRUE;
8019
8020 /*
8021 * Try the public key supplied in the configuration.
8022 *
8023 * First, offer the public blob to see if the server is
8024 * willing to accept it.
8025 */
8026 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8027 ssh2_pkt_addstring(s->pktout, ssh->username);
8028 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8029 /* service requested */
8030 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8031 ssh2_pkt_addbool(s->pktout, FALSE);
8032 /* no signature included */
8033 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8034 ssh2_pkt_addstring_start(s->pktout);
8035 ssh2_pkt_addstring_data(s->pktout,
8036 (char *)s->publickey_blob,
8037 s->publickey_bloblen);
8038 ssh2_pkt_send(ssh, s->pktout);
8039 logevent("Offered public key");
8040
8041 crWaitUntilV(pktin);
8042 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8043 /* Key refused. Give up. */
8044 s->gotit = TRUE; /* reconsider message next loop */
8045 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8046 continue; /* process this new message */
8047 }
8048 logevent("Offer of public key accepted");
8049
8050 /*
8051 * Actually attempt a serious authentication using
8052 * the key.
8053 */
8054 if (flags & FLAG_VERBOSE) {
8055 c_write_str(ssh, "Authenticating with public key \"");
8056 c_write_str(ssh, s->publickey_comment);
8057 c_write_str(ssh, "\"\r\n");
8058 }
8059 key = NULL;
8060 while (!key) {
8061 const char *error; /* not live over crReturn */
8062 if (s->publickey_encrypted) {
8063 /*
8064 * Get a passphrase from the user.
8065 */
8066 int ret; /* need not be kept over crReturn */
8067 s->cur_prompt = new_prompts(ssh->frontend);
8068 s->cur_prompt->to_server = FALSE;
8069 s->cur_prompt->name = dupstr("SSH key passphrase");
8070 add_prompt(s->cur_prompt,
8071 dupprintf("Passphrase for key \"%.100s\": ",
8072 s->publickey_comment),
8073 FALSE, SSH_MAX_PASSWORD_LEN);
8074 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8075 while (ret < 0) {
8076 ssh->send_ok = 1;
8077 crWaitUntilV(!pktin);
8078 ret = get_userpass_input(s->cur_prompt,
8079 in, inlen);
8080 ssh->send_ok = 0;
8081 }
8082 if (!ret) {
8083 /* Failed to get a passphrase. Terminate. */
8084 free_prompts(s->cur_prompt);
8085 ssh_disconnect(ssh, NULL,
8086 "Unable to authenticate",
8087 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8088 TRUE);
8089 crStopV;
8090 }
8091 passphrase =
8092 dupstr(s->cur_prompt->prompts[0]->result);
8093 free_prompts(s->cur_prompt);
8094 } else {
8095 passphrase = NULL; /* no passphrase needed */
8096 }
8097
8098 /*
8099 * Try decrypting the key.
8100 */
8101 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8102 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8103 if (passphrase) {
8104 /* burn the evidence */
8105 memset(passphrase, 0, strlen(passphrase));
8106 sfree(passphrase);
8107 }
8108 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8109 if (passphrase &&
8110 (key == SSH2_WRONG_PASSPHRASE)) {
8111 c_write_str(ssh, "Wrong passphrase\r\n");
8112 key = NULL;
8113 /* and loop again */
8114 } else {
8115 c_write_str(ssh, "Unable to load private key (");
8116 c_write_str(ssh, error);
8117 c_write_str(ssh, ")\r\n");
8118 key = NULL;
8119 break; /* try something else */
8120 }
8121 }
8122 }
8123
8124 if (key) {
8125 unsigned char *pkblob, *sigblob, *sigdata;
8126 int pkblob_len, sigblob_len, sigdata_len;
8127 int p;
8128
8129 /*
8130 * We have loaded the private key and the server
8131 * has announced that it's willing to accept it.
8132 * Hallelujah. Generate a signature and send it.
8133 */
8134 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8135 ssh2_pkt_addstring(s->pktout, ssh->username);
8136 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8137 /* service requested */
8138 ssh2_pkt_addstring(s->pktout, "publickey");
8139 /* method */
8140 ssh2_pkt_addbool(s->pktout, TRUE);
8141 /* signature follows */
8142 ssh2_pkt_addstring(s->pktout, key->alg->name);
8143 pkblob = key->alg->public_blob(key->data,
8144 &pkblob_len);
8145 ssh2_pkt_addstring_start(s->pktout);
8146 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8147 pkblob_len);
8148
8149 /*
8150 * The data to be signed is:
8151 *
8152 * string session-id
8153 *
8154 * followed by everything so far placed in the
8155 * outgoing packet.
8156 */
8157 sigdata_len = s->pktout->length - 5 + 4 +
8158 ssh->v2_session_id_len;
8159 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8160 sigdata_len -= 4;
8161 sigdata = snewn(sigdata_len, unsigned char);
8162 p = 0;
8163 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8164 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8165 p += 4;
8166 }
8167 memcpy(sigdata+p, ssh->v2_session_id,
8168 ssh->v2_session_id_len);
8169 p += ssh->v2_session_id_len;
8170 memcpy(sigdata+p, s->pktout->data + 5,
8171 s->pktout->length - 5);
8172 p += s->pktout->length - 5;
8173 assert(p == sigdata_len);
8174 sigblob = key->alg->sign(key->data, (char *)sigdata,
8175 sigdata_len, &sigblob_len);
8176 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8177 sigblob, sigblob_len);
8178 sfree(pkblob);
8179 sfree(sigblob);
8180 sfree(sigdata);
8181
8182 ssh2_pkt_send(ssh, s->pktout);
8183 logevent("Sent public key signature");
8184 s->type = AUTH_TYPE_PUBLICKEY;
8185 key->alg->freekey(key->data);
8186 }
8187
8188 #ifndef NO_GSSAPI
8189 } else if (s->can_gssapi && !s->tried_gssapi) {
8190
8191 /* GSSAPI Authentication */
8192
8193 int micoffset, len;
8194 char *data;
8195 Ssh_gss_buf mic;
8196 s->type = AUTH_TYPE_GSSAPI;
8197 s->tried_gssapi = TRUE;
8198 s->gotit = TRUE;
8199 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8200
8201 /*
8202 * Pick the highest GSS library on the preference
8203 * list.
8204 */
8205 {
8206 int i, j;
8207 s->gsslib = NULL;
8208 for (i = 0; i < ngsslibs; i++) {
8209 int want_id = conf_get_int_int(ssh->conf,
8210 CONF_ssh_gsslist, i);
8211 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8212 if (ssh->gsslibs->libraries[j].id == want_id) {
8213 s->gsslib = &ssh->gsslibs->libraries[j];
8214 goto got_gsslib; /* double break */
8215 }
8216 }
8217 got_gsslib:
8218 /*
8219 * We always expect to have found something in
8220 * the above loop: we only came here if there
8221 * was at least one viable GSS library, and the
8222 * preference list should always mention
8223 * everything and only change the order.
8224 */
8225 assert(s->gsslib);
8226 }
8227
8228 if (s->gsslib->gsslogmsg)
8229 logevent(s->gsslib->gsslogmsg);
8230
8231 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8232 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8233 ssh2_pkt_addstring(s->pktout, ssh->username);
8234 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8235 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8236 logevent("Attempting GSSAPI authentication");
8237
8238 /* add mechanism info */
8239 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8240
8241 /* number of GSSAPI mechanisms */
8242 ssh2_pkt_adduint32(s->pktout,1);
8243
8244 /* length of OID + 2 */
8245 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8246 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8247
8248 /* length of OID */
8249 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8250
8251 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8252 s->gss_buf.length);
8253 ssh2_pkt_send(ssh, s->pktout);
8254 crWaitUntilV(pktin);
8255 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8256 logevent("GSSAPI authentication request refused");
8257 continue;
8258 }
8259
8260 /* check returned packet ... */
8261
8262 ssh_pkt_getstring(pktin, &data, &len);
8263 s->gss_rcvtok.value = data;
8264 s->gss_rcvtok.length = len;
8265 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8266 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8267 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8268 memcmp((char *)s->gss_rcvtok.value + 2,
8269 s->gss_buf.value,s->gss_buf.length) ) {
8270 logevent("GSSAPI authentication - wrong response from server");
8271 continue;
8272 }
8273
8274 /* now start running */
8275 s->gss_stat = s->gsslib->import_name(s->gsslib,
8276 ssh->fullhostname,
8277 &s->gss_srv_name);
8278 if (s->gss_stat != SSH_GSS_OK) {
8279 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8280 logevent("GSSAPI import name failed - Bad service name");
8281 else
8282 logevent("GSSAPI import name failed");
8283 continue;
8284 }
8285
8286 /* fetch TGT into GSS engine */
8287 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8288
8289 if (s->gss_stat != SSH_GSS_OK) {
8290 logevent("GSSAPI authentication failed to get credentials");
8291 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8292 continue;
8293 }
8294
8295 /* initial tokens are empty */
8296 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8297 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8298
8299 /* now enter the loop */
8300 do {
8301 s->gss_stat = s->gsslib->init_sec_context
8302 (s->gsslib,
8303 &s->gss_ctx,
8304 s->gss_srv_name,
8305 conf_get_int(ssh->conf, CONF_gssapifwd),
8306 &s->gss_rcvtok,
8307 &s->gss_sndtok);
8308
8309 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8310 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8311 logevent("GSSAPI authentication initialisation failed");
8312
8313 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8314 &s->gss_buf) == SSH_GSS_OK) {
8315 logevent(s->gss_buf.value);
8316 sfree(s->gss_buf.value);
8317 }
8318
8319 break;
8320 }
8321 logevent("GSSAPI authentication initialised");
8322
8323 /* Client and server now exchange tokens until GSSAPI
8324 * no longer says CONTINUE_NEEDED */
8325
8326 if (s->gss_sndtok.length != 0) {
8327 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8328 ssh_pkt_addstring_start(s->pktout);
8329 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8330 ssh2_pkt_send(ssh, s->pktout);
8331 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8332 }
8333
8334 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8335 crWaitUntilV(pktin);
8336 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8337 logevent("GSSAPI authentication - bad server response");
8338 s->gss_stat = SSH_GSS_FAILURE;
8339 break;
8340 }
8341 ssh_pkt_getstring(pktin, &data, &len);
8342 s->gss_rcvtok.value = data;
8343 s->gss_rcvtok.length = len;
8344 }
8345 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8346
8347 if (s->gss_stat != SSH_GSS_OK) {
8348 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8349 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8350 continue;
8351 }
8352 logevent("GSSAPI authentication loop finished OK");
8353
8354 /* Now send the MIC */
8355
8356 s->pktout = ssh2_pkt_init(0);
8357 micoffset = s->pktout->length;
8358 ssh_pkt_addstring_start(s->pktout);
8359 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8360 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8361 ssh_pkt_addstring(s->pktout, ssh->username);
8362 ssh_pkt_addstring(s->pktout, "ssh-connection");
8363 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8364
8365 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8366 s->gss_buf.length = s->pktout->length - micoffset;
8367
8368 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8369 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8370 ssh_pkt_addstring_start(s->pktout);
8371 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8372 ssh2_pkt_send(ssh, s->pktout);
8373 s->gsslib->free_mic(s->gsslib, &mic);
8374
8375 s->gotit = FALSE;
8376
8377 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8378 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8379 continue;
8380 #endif
8381 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8382
8383 /*
8384 * Keyboard-interactive authentication.
8385 */
8386
8387 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8388
8389 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8390
8391 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8392 ssh2_pkt_addstring(s->pktout, ssh->username);
8393 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8394 /* service requested */
8395 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8396 /* method */
8397 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8398 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8399 ssh2_pkt_send(ssh, s->pktout);
8400
8401 logevent("Attempting keyboard-interactive authentication");
8402
8403 crWaitUntilV(pktin);
8404 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8405 /* Server is not willing to do keyboard-interactive
8406 * at all (or, bizarrely but legally, accepts the
8407 * user without actually issuing any prompts).
8408 * Give up on it entirely. */
8409 s->gotit = TRUE;
8410 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8411 s->kbd_inter_refused = TRUE; /* don't try it again */
8412 continue;
8413 }
8414
8415 /*
8416 * Loop while the server continues to send INFO_REQUESTs.
8417 */
8418 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8419
8420 char *name, *inst, *lang;
8421 int name_len, inst_len, lang_len;
8422 int i;
8423
8424 /*
8425 * We've got a fresh USERAUTH_INFO_REQUEST.
8426 * Get the preamble and start building a prompt.
8427 */
8428 ssh_pkt_getstring(pktin, &name, &name_len);
8429 ssh_pkt_getstring(pktin, &inst, &inst_len);
8430 ssh_pkt_getstring(pktin, &lang, &lang_len);
8431 s->cur_prompt = new_prompts(ssh->frontend);
8432 s->cur_prompt->to_server = TRUE;
8433
8434 /*
8435 * Get any prompt(s) from the packet.
8436 */
8437 s->num_prompts = ssh_pkt_getuint32(pktin);
8438 for (i = 0; i < s->num_prompts; i++) {
8439 char *prompt;
8440 int prompt_len;
8441 int echo;
8442 static char noprompt[] =
8443 "<server failed to send prompt>: ";
8444
8445 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8446 echo = ssh2_pkt_getbool(pktin);
8447 if (!prompt_len) {
8448 prompt = noprompt;
8449 prompt_len = lenof(noprompt)-1;
8450 }
8451 add_prompt(s->cur_prompt,
8452 dupprintf("%.*s", prompt_len, prompt),
8453 echo, SSH_MAX_PASSWORD_LEN);
8454 }
8455
8456 if (name_len) {
8457 /* FIXME: better prefix to distinguish from
8458 * local prompts? */
8459 s->cur_prompt->name =
8460 dupprintf("SSH server: %.*s", name_len, name);
8461 s->cur_prompt->name_reqd = TRUE;
8462 } else {
8463 s->cur_prompt->name =
8464 dupstr("SSH server authentication");
8465 s->cur_prompt->name_reqd = FALSE;
8466 }
8467 /* We add a prefix to try to make it clear that a prompt
8468 * has come from the server.
8469 * FIXME: ugly to print "Using..." in prompt _every_
8470 * time round. Can this be done more subtly? */
8471 /* Special case: for reasons best known to themselves,
8472 * some servers send k-i requests with no prompts and
8473 * nothing to display. Keep quiet in this case. */
8474 if (s->num_prompts || name_len || inst_len) {
8475 s->cur_prompt->instruction =
8476 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8477 inst_len ? "\n" : "", inst_len, inst);
8478 s->cur_prompt->instr_reqd = TRUE;
8479 } else {
8480 s->cur_prompt->instr_reqd = FALSE;
8481 }
8482
8483 /*
8484 * Display any instructions, and get the user's
8485 * response(s).
8486 */
8487 {
8488 int ret; /* not live over crReturn */
8489 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8490 while (ret < 0) {
8491 ssh->send_ok = 1;
8492 crWaitUntilV(!pktin);
8493 ret = get_userpass_input(s->cur_prompt, in, inlen);
8494 ssh->send_ok = 0;
8495 }
8496 if (!ret) {
8497 /*
8498 * Failed to get responses. Terminate.
8499 */
8500 free_prompts(s->cur_prompt);
8501 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8502 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8503 TRUE);
8504 crStopV;
8505 }
8506 }
8507
8508 /*
8509 * Send the response(s) to the server.
8510 */
8511 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8512 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8513 for (i=0; i < s->num_prompts; i++) {
8514 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8515 ssh2_pkt_addstring(s->pktout,
8516 s->cur_prompt->prompts[i]->result);
8517 end_log_omission(ssh, s->pktout);
8518 }
8519 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8520
8521 /*
8522 * Get the next packet in case it's another
8523 * INFO_REQUEST.
8524 */
8525 crWaitUntilV(pktin);
8526
8527 }
8528
8529 /*
8530 * We should have SUCCESS or FAILURE now.
8531 */
8532 s->gotit = TRUE;
8533
8534 } else if (s->can_passwd) {
8535
8536 /*
8537 * Plain old password authentication.
8538 */
8539 int ret; /* not live over crReturn */
8540 int changereq_first_time; /* not live over crReturn */
8541
8542 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8543
8544 s->cur_prompt = new_prompts(ssh->frontend);
8545 s->cur_prompt->to_server = TRUE;
8546 s->cur_prompt->name = dupstr("SSH password");
8547 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8548 ssh->username,
8549 ssh->savedhost),
8550 FALSE, SSH_MAX_PASSWORD_LEN);
8551
8552 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8553 while (ret < 0) {
8554 ssh->send_ok = 1;
8555 crWaitUntilV(!pktin);
8556 ret = get_userpass_input(s->cur_prompt, in, inlen);
8557 ssh->send_ok = 0;
8558 }
8559 if (!ret) {
8560 /*
8561 * Failed to get responses. Terminate.
8562 */
8563 free_prompts(s->cur_prompt);
8564 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8565 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8566 TRUE);
8567 crStopV;
8568 }
8569 /*
8570 * Squirrel away the password. (We may need it later if
8571 * asked to change it.)
8572 */
8573 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8574 free_prompts(s->cur_prompt);
8575
8576 /*
8577 * Send the password packet.
8578 *
8579 * We pad out the password packet to 256 bytes to make
8580 * it harder for an attacker to find the length of the
8581 * user's password.
8582 *
8583 * Anyone using a password longer than 256 bytes
8584 * probably doesn't have much to worry about from
8585 * people who find out how long their password is!
8586 */
8587 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8588 ssh2_pkt_addstring(s->pktout, ssh->username);
8589 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8590 /* service requested */
8591 ssh2_pkt_addstring(s->pktout, "password");
8592 ssh2_pkt_addbool(s->pktout, FALSE);
8593 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8594 ssh2_pkt_addstring(s->pktout, s->password);
8595 end_log_omission(ssh, s->pktout);
8596 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8597 logevent("Sent password");
8598 s->type = AUTH_TYPE_PASSWORD;
8599
8600 /*
8601 * Wait for next packet, in case it's a password change
8602 * request.
8603 */
8604 crWaitUntilV(pktin);
8605 changereq_first_time = TRUE;
8606
8607 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8608
8609 /*
8610 * We're being asked for a new password
8611 * (perhaps not for the first time).
8612 * Loop until the server accepts it.
8613 */
8614
8615 int got_new = FALSE; /* not live over crReturn */
8616 char *prompt; /* not live over crReturn */
8617 int prompt_len; /* not live over crReturn */
8618
8619 {
8620 char *msg;
8621 if (changereq_first_time)
8622 msg = "Server requested password change";
8623 else
8624 msg = "Server rejected new password";
8625 logevent(msg);
8626 c_write_str(ssh, msg);
8627 c_write_str(ssh, "\r\n");
8628 }
8629
8630 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8631
8632 s->cur_prompt = new_prompts(ssh->frontend);
8633 s->cur_prompt->to_server = TRUE;
8634 s->cur_prompt->name = dupstr("New SSH password");
8635 s->cur_prompt->instruction =
8636 dupprintf("%.*s", prompt_len, prompt);
8637 s->cur_prompt->instr_reqd = TRUE;
8638 /*
8639 * There's no explicit requirement in the protocol
8640 * for the "old" passwords in the original and
8641 * password-change messages to be the same, and
8642 * apparently some Cisco kit supports password change
8643 * by the user entering a blank password originally
8644 * and the real password subsequently, so,
8645 * reluctantly, we prompt for the old password again.
8646 *
8647 * (On the other hand, some servers don't even bother
8648 * to check this field.)
8649 */
8650 add_prompt(s->cur_prompt,
8651 dupstr("Current password (blank for previously entered password): "),
8652 FALSE, SSH_MAX_PASSWORD_LEN);
8653 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8654 FALSE, SSH_MAX_PASSWORD_LEN);
8655 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8656 FALSE, SSH_MAX_PASSWORD_LEN);
8657
8658 /*
8659 * Loop until the user manages to enter the same
8660 * password twice.
8661 */
8662 while (!got_new) {
8663
8664 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8665 while (ret < 0) {
8666 ssh->send_ok = 1;
8667 crWaitUntilV(!pktin);
8668 ret = get_userpass_input(s->cur_prompt, in, inlen);
8669 ssh->send_ok = 0;
8670 }
8671 if (!ret) {
8672 /*
8673 * Failed to get responses. Terminate.
8674 */
8675 /* burn the evidence */
8676 free_prompts(s->cur_prompt);
8677 memset(s->password, 0, strlen(s->password));
8678 sfree(s->password);
8679 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8680 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8681 TRUE);
8682 crStopV;
8683 }
8684
8685 /*
8686 * If the user specified a new original password
8687 * (IYSWIM), overwrite any previously specified
8688 * one.
8689 * (A side effect is that the user doesn't have to
8690 * re-enter it if they louse up the new password.)
8691 */
8692 if (s->cur_prompt->prompts[0]->result[0]) {
8693 memset(s->password, 0, strlen(s->password));
8694 /* burn the evidence */
8695 sfree(s->password);
8696 s->password =
8697 dupstr(s->cur_prompt->prompts[0]->result);
8698 }
8699
8700 /*
8701 * Check the two new passwords match.
8702 */
8703 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8704 s->cur_prompt->prompts[2]->result)
8705 == 0);
8706 if (!got_new)
8707 /* They don't. Silly user. */
8708 c_write_str(ssh, "Passwords do not match\r\n");
8709
8710 }
8711
8712 /*
8713 * Send the new password (along with the old one).
8714 * (see above for padding rationale)
8715 */
8716 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8717 ssh2_pkt_addstring(s->pktout, ssh->username);
8718 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8719 /* service requested */
8720 ssh2_pkt_addstring(s->pktout, "password");
8721 ssh2_pkt_addbool(s->pktout, TRUE);
8722 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8723 ssh2_pkt_addstring(s->pktout, s->password);
8724 ssh2_pkt_addstring(s->pktout,
8725 s->cur_prompt->prompts[1]->result);
8726 free_prompts(s->cur_prompt);
8727 end_log_omission(ssh, s->pktout);
8728 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8729 logevent("Sent new password");
8730
8731 /*
8732 * Now see what the server has to say about it.
8733 * (If it's CHANGEREQ again, it's not happy with the
8734 * new password.)
8735 */
8736 crWaitUntilV(pktin);
8737 changereq_first_time = FALSE;
8738
8739 }
8740
8741 /*
8742 * We need to reexamine the current pktin at the top
8743 * of the loop. Either:
8744 * - we weren't asked to change password at all, in
8745 * which case it's a SUCCESS or FAILURE with the
8746 * usual meaning
8747 * - we sent a new password, and the server was
8748 * either OK with it (SUCCESS or FAILURE w/partial
8749 * success) or unhappy with the _old_ password
8750 * (FAILURE w/o partial success)
8751 * In any of these cases, we go back to the top of
8752 * the loop and start again.
8753 */
8754 s->gotit = TRUE;
8755
8756 /*
8757 * We don't need the old password any more, in any
8758 * case. Burn the evidence.
8759 */
8760 memset(s->password, 0, strlen(s->password));
8761 sfree(s->password);
8762
8763 } else {
8764 char *str = dupprintf("No supported authentication methods available"
8765 " (server sent: %.*s)",
8766 methlen, methods);
8767
8768 ssh_disconnect(ssh, str,
8769 "No supported authentication methods available",
8770 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8771 FALSE);
8772 sfree(str);
8773
8774 crStopV;
8775
8776 }
8777
8778 }
8779 }
8780 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8781
8782 /* Clear up various bits and pieces from authentication. */
8783 if (s->publickey_blob) {
8784 sfree(s->publickey_blob);
8785 sfree(s->publickey_comment);
8786 }
8787 if (s->agent_response)
8788 sfree(s->agent_response);
8789
8790 if (s->userauth_success) {
8791 /*
8792 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8793 * packets since. Signal the transport layer to consider enacting
8794 * delayed compression.
8795 *
8796 * (Relying on we_are_in is not sufficient, as
8797 * draft-miller-secsh-compression-delayed is quite clear that it
8798 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8799 * become set for other reasons.)
8800 */
8801 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8802 }
8803
8804 /*
8805 * Now the connection protocol has started, one way or another.
8806 */
8807
8808 ssh->channels = newtree234(ssh_channelcmp);
8809
8810 /*
8811 * Set up handlers for some connection protocol messages, so we
8812 * don't have to handle them repeatedly in this coroutine.
8813 */
8814 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8815 ssh2_msg_channel_window_adjust;
8816 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8817 ssh2_msg_global_request;
8818
8819 /*
8820 * Create the main session channel.
8821 */
8822 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
8823 ssh->mainchan = NULL;
8824 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
8825 /*
8826 * Just start a direct-tcpip channel and use it as the main
8827 * channel.
8828 */
8829 ssh->mainchan = snew(struct ssh_channel);
8830 ssh->mainchan->ssh = ssh;
8831 ssh2_channel_init(ssh->mainchan);
8832 logeventf(ssh,
8833 "Opening direct-tcpip channel to %s:%d in place of session",
8834 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8835 conf_get_int(ssh->conf, CONF_ssh_nc_port));
8836 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8837 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8838 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8839 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8840 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8841 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8842 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
8843 /*
8844 * There's nothing meaningful to put in the originator
8845 * fields, but some servers insist on syntactically correct
8846 * information.
8847 */
8848 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8849 ssh2_pkt_adduint32(s->pktout, 0);
8850 ssh2_pkt_send(ssh, s->pktout);
8851
8852 crWaitUntilV(pktin);
8853 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8854 bombout(("Server refused to open a direct-tcpip channel"));
8855 crStopV;
8856 /* FIXME: error data comes back in FAILURE packet */
8857 }
8858 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8859 bombout(("Server's channel confirmation cited wrong channel"));
8860 crStopV;
8861 }
8862 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8863 ssh->mainchan->halfopen = FALSE;
8864 ssh->mainchan->type = CHAN_MAINSESSION;
8865 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8866 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8867 add234(ssh->channels, ssh->mainchan);
8868 update_specials_menu(ssh->frontend);
8869 logevent("Opened direct-tcpip channel");
8870 ssh->ncmode = TRUE;
8871 } else {
8872 ssh->mainchan = snew(struct ssh_channel);
8873 ssh->mainchan->ssh = ssh;
8874 ssh2_channel_init(ssh->mainchan);
8875 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8876 ssh2_pkt_addstring(s->pktout, "session");
8877 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8878 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8879 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8880 ssh2_pkt_send(ssh, s->pktout);
8881 crWaitUntilV(pktin);
8882 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8883 bombout(("Server refused to open a session"));
8884 crStopV;
8885 /* FIXME: error data comes back in FAILURE packet */
8886 }
8887 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8888 bombout(("Server's channel confirmation cited wrong channel"));
8889 crStopV;
8890 }
8891 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8892 ssh->mainchan->halfopen = FALSE;
8893 ssh->mainchan->type = CHAN_MAINSESSION;
8894 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8895 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8896 add234(ssh->channels, ssh->mainchan);
8897 update_specials_menu(ssh->frontend);
8898 logevent("Opened channel for session");
8899 ssh->ncmode = FALSE;
8900 }
8901
8902 /*
8903 * Now we have a channel, make dispatch table entries for
8904 * general channel-based messages.
8905 */
8906 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8907 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8908 ssh2_msg_channel_data;
8909 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8910 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8911 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8912 ssh2_msg_channel_open_confirmation;
8913 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8914 ssh2_msg_channel_open_failure;
8915 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8916 ssh2_msg_channel_request;
8917 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8918 ssh2_msg_channel_open;
8919
8920 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
8921 /*
8922 * This message indicates to the server that we promise
8923 * not to try to run any other channel in parallel with
8924 * this one, so it's safe for it to advertise a very large
8925 * window and leave the flow control to TCP.
8926 */
8927 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8928 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8929 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8930 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8931 ssh2_pkt_send(ssh, s->pktout);
8932 }
8933
8934 /*
8935 * Potentially enable X11 forwarding.
8936 */
8937 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
8938 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
8939 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
8940 logevent("Requesting X11 forwarding");
8941 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8942 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8943 ssh2_pkt_addstring(s->pktout, "x11-req");
8944 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8945 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8946 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8947 /*
8948 * Note that while we blank the X authentication data here, we don't
8949 * take any special action to blank the start of an X11 channel,
8950 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8951 * without having session blanking enabled is likely to leak your
8952 * cookie into the log.
8953 */
8954 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8955 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8956 end_log_omission(ssh, s->pktout);
8957 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8958 ssh2_pkt_send(ssh, s->pktout);
8959
8960 crWaitUntilV(pktin);
8961
8962 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8963 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8964 bombout(("Unexpected response to X11 forwarding request:"
8965 " packet type %d", pktin->type));
8966 crStopV;
8967 }
8968 logevent("X11 forwarding refused");
8969 } else {
8970 logevent("X11 forwarding enabled");
8971 ssh->X11_fwd_enabled = TRUE;
8972 }
8973 }
8974
8975 /*
8976 * Enable port forwardings.
8977 */
8978 ssh_setup_portfwd(ssh, ssh->conf);
8979
8980 /*
8981 * Potentially enable agent forwarding.
8982 */
8983 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
8984 logevent("Requesting OpenSSH-style agent forwarding");
8985 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8986 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8987 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8988 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8989 ssh2_pkt_send(ssh, s->pktout);
8990
8991 crWaitUntilV(pktin);
8992
8993 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8994 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8995 bombout(("Unexpected response to agent forwarding request:"
8996 " packet type %d", pktin->type));
8997 crStopV;
8998 }
8999 logevent("Agent forwarding refused");
9000 } else {
9001 logevent("Agent forwarding enabled");
9002 ssh->agentfwd_enabled = TRUE;
9003 }
9004 }
9005
9006 /*
9007 * Now allocate a pty for the session.
9008 */
9009 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
9010 /* Unpick the terminal-speed string. */
9011 /* XXX perhaps we should allow no speeds to be sent. */
9012 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9013 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9014 /* Build the pty request. */
9015 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9016 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9017 ssh2_pkt_addstring(s->pktout, "pty-req");
9018 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9019 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
9020 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
9021 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
9022 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
9023 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
9024 ssh2_pkt_addstring_start(s->pktout);
9025 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
9026 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
9027 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
9028 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
9029 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9030 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9031 ssh2_pkt_send(ssh, s->pktout);
9032 ssh->state = SSH_STATE_INTERMED;
9033
9034 crWaitUntilV(pktin);
9035
9036 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9037 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9038 bombout(("Unexpected response to pty request:"
9039 " packet type %d", pktin->type));
9040 crStopV;
9041 }
9042 c_write_str(ssh, "Server refused to allocate pty\r\n");
9043 ssh->editing = ssh->echoing = 1;
9044 } else {
9045 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9046 ssh->ospeed, ssh->ispeed);
9047 ssh->got_pty = TRUE;
9048 }
9049 } else {
9050 ssh->editing = ssh->echoing = 1;
9051 }
9052
9053 /*
9054 * Send environment variables.
9055 *
9056 * Simplest thing here is to send all the requests at once, and
9057 * then wait for a whole bunch of successes or failures.
9058 */
9059 if (ssh->mainchan && !ssh->ncmode) {
9060 char *key, *val;
9061
9062 s->num_env = 0;
9063
9064 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9065 val != NULL;
9066 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9067 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9068 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9069 ssh2_pkt_addstring(s->pktout, "env");
9070 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9071 ssh2_pkt_addstring(s->pktout, key);
9072 ssh2_pkt_addstring(s->pktout, val);
9073 ssh2_pkt_send(ssh, s->pktout);
9074
9075 s->num_env++;
9076 }
9077
9078 if (s->num_env) {
9079 logeventf(ssh, "Sent %d environment variables", s->num_env);
9080
9081 s->env_ok = 0;
9082 s->env_left = s->num_env;
9083
9084 while (s->env_left > 0) {
9085 crWaitUntilV(pktin);
9086
9087 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9088 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9089 bombout(("Unexpected response to environment request:"
9090 " packet type %d", pktin->type));
9091 crStopV;
9092 }
9093 } else {
9094 s->env_ok++;
9095 }
9096
9097 s->env_left--;
9098 }
9099
9100 if (s->env_ok == s->num_env) {
9101 logevent("All environment variables successfully set");
9102 } else if (s->env_ok == 0) {
9103 logevent("All environment variables refused");
9104 c_write_str(ssh, "Server refused to set environment variables\r\n");
9105 } else {
9106 logeventf(ssh, "%d environment variables refused",
9107 s->num_env - s->env_ok);
9108 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9109 }
9110 }
9111 }
9112
9113 /*
9114 * Start a shell or a remote command. We may have to attempt
9115 * this twice if the config data has provided a second choice
9116 * of command.
9117 */
9118 if (ssh->mainchan && !ssh->ncmode) while (1) {
9119 int subsys;
9120 char *cmd;
9121
9122 if (ssh->fallback_cmd) {
9123 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9124 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9125 } else {
9126 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9127 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9128 }
9129
9130 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9131 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9132 if (subsys) {
9133 ssh2_pkt_addstring(s->pktout, "subsystem");
9134 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9135 ssh2_pkt_addstring(s->pktout, cmd);
9136 } else if (*cmd) {
9137 ssh2_pkt_addstring(s->pktout, "exec");
9138 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9139 ssh2_pkt_addstring(s->pktout, cmd);
9140 } else {
9141 ssh2_pkt_addstring(s->pktout, "shell");
9142 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9143 }
9144 ssh2_pkt_send(ssh, s->pktout);
9145
9146 crWaitUntilV(pktin);
9147
9148 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9149 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9150 bombout(("Unexpected response to shell/command request:"
9151 " packet type %d", pktin->type));
9152 crStopV;
9153 }
9154 /*
9155 * We failed to start the command. If this is the
9156 * fallback command, we really are finished; if it's
9157 * not, and if the fallback command exists, try falling
9158 * back to it before complaining.
9159 */
9160 if (!ssh->fallback_cmd &&
9161 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9162 logevent("Primary command failed; attempting fallback");
9163 ssh->fallback_cmd = TRUE;
9164 continue;
9165 }
9166 bombout(("Server refused to start a shell/command"));
9167 crStopV;
9168 } else {
9169 logevent("Started a shell/command");
9170 }
9171 break;
9172 }
9173
9174 ssh->state = SSH_STATE_SESSION;
9175 if (ssh->size_needed)
9176 ssh_size(ssh, ssh->term_width, ssh->term_height);
9177 if (ssh->eof_needed)
9178 ssh_special(ssh, TS_EOF);
9179
9180 /*
9181 * All the initial channel requests are done, so install the default
9182 * failure handler.
9183 */
9184 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
9185 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9186
9187 /*
9188 * Transfer data!
9189 */
9190 if (ssh->ldisc)
9191 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9192 if (ssh->mainchan)
9193 ssh->send_ok = 1;
9194 while (1) {
9195 crReturnV;
9196 s->try_send = FALSE;
9197 if (pktin) {
9198
9199 /*
9200 * _All_ the connection-layer packets we expect to
9201 * receive are now handled by the dispatch table.
9202 * Anything that reaches here must be bogus.
9203 */
9204
9205 bombout(("Strange packet received: type %d", pktin->type));
9206 crStopV;
9207 } else if (ssh->mainchan) {
9208 /*
9209 * We have spare data. Add it to the channel buffer.
9210 */
9211 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9212 s->try_send = TRUE;
9213 }
9214 if (s->try_send) {
9215 int i;
9216 struct ssh_channel *c;
9217 /*
9218 * Try to send data on all channels if we can.
9219 */
9220 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9221 ssh2_try_send_and_unthrottle(ssh, c);
9222 }
9223 }
9224
9225 crFinishV;
9226 }
9227
9228 /*
9229 * Handlers for SSH-2 messages that might arrive at any moment.
9230 */
9231 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9232 {
9233 /* log reason code in disconnect message */
9234 char *buf, *msg;
9235 int reason, msglen;
9236
9237 reason = ssh_pkt_getuint32(pktin);
9238 ssh_pkt_getstring(pktin, &msg, &msglen);
9239
9240 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9241 buf = dupprintf("Received disconnect message (%s)",
9242 ssh2_disconnect_reasons[reason]);
9243 } else {
9244 buf = dupprintf("Received disconnect message (unknown"
9245 " type %d)", reason);
9246 }
9247 logevent(buf);
9248 sfree(buf);
9249 buf = dupprintf("Disconnection message text: %.*s",
9250 msglen, msg);
9251 logevent(buf);
9252 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9253 reason,
9254 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9255 ssh2_disconnect_reasons[reason] : "unknown",
9256 msglen, msg));
9257 sfree(buf);
9258 }
9259
9260 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9261 {
9262 /* log the debug message */
9263 char *msg;
9264 int msglen;
9265
9266 /* XXX maybe we should actually take notice of the return value */
9267 ssh2_pkt_getbool(pktin);
9268 ssh_pkt_getstring(pktin, &msg, &msglen);
9269
9270 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9271 }
9272
9273 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9274 {
9275 struct Packet *pktout;
9276 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9277 ssh2_pkt_adduint32(pktout, pktin->sequence);
9278 /*
9279 * UNIMPLEMENTED messages MUST appear in the same order as the
9280 * messages they respond to. Hence, never queue them.
9281 */
9282 ssh2_pkt_send_noqueue(ssh, pktout);
9283 }
9284
9285 /*
9286 * Handle the top-level SSH-2 protocol.
9287 */
9288 static void ssh2_protocol_setup(Ssh ssh)
9289 {
9290 int i;
9291
9292 /*
9293 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9294 */
9295 for (i = 0; i < 256; i++)
9296 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9297
9298 /*
9299 * Any message we actually understand, we set to NULL so that
9300 * the coroutines will get it.
9301 */
9302 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9303 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9304 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9305 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9306 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9307 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9308 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9309 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9310 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9311 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9312 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9313 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9314 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9315 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9316 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9317 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9318 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9319 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9320 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9321 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9322 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9323 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9324 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9325 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9326 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9327 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9328 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9329 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9330 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9331 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9332 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9333 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9334 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9335
9336 /*
9337 * These special message types we install handlers for.
9338 */
9339 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9340 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9341 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9342 }
9343
9344 static void ssh2_timer(void *ctx, long now)
9345 {
9346 Ssh ssh = (Ssh)ctx;
9347
9348 if (ssh->state == SSH_STATE_CLOSED)
9349 return;
9350
9351 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9352 now - ssh->next_rekey >= 0) {
9353 do_ssh2_transport(ssh, "timeout", -1, NULL);
9354 }
9355 }
9356
9357 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9358 struct Packet *pktin)
9359 {
9360 unsigned char *in = (unsigned char *)vin;
9361 if (ssh->state == SSH_STATE_CLOSED)
9362 return;
9363
9364 if (pktin) {
9365 ssh->incoming_data_size += pktin->encrypted_len;
9366 if (!ssh->kex_in_progress &&
9367 ssh->max_data_size != 0 &&
9368 ssh->incoming_data_size > ssh->max_data_size)
9369 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9370 }
9371
9372 if (pktin && ssh->packet_dispatch[pktin->type]) {
9373 ssh->packet_dispatch[pktin->type](ssh, pktin);
9374 return;
9375 }
9376
9377 if (!ssh->protocol_initial_phase_done ||
9378 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9379 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9380 !ssh->protocol_initial_phase_done) {
9381 ssh->protocol_initial_phase_done = TRUE;
9382 /*
9383 * Allow authconn to initialise itself.
9384 */
9385 do_ssh2_authconn(ssh, NULL, 0, NULL);
9386 }
9387 } else {
9388 do_ssh2_authconn(ssh, in, inlen, pktin);
9389 }
9390 }
9391
9392 static void ssh_cache_conf_values(Ssh ssh)
9393 {
9394 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9395 }
9396
9397 /*
9398 * Called to set up the connection.
9399 *
9400 * Returns an error message, or NULL on success.
9401 */
9402 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9403 Conf *conf, char *host, int port, char **realhost,
9404 int nodelay, int keepalive)
9405 {
9406 const char *p;
9407 Ssh ssh;
9408
9409 ssh = snew(struct ssh_tag);
9410 ssh->conf = conf_copy(conf);
9411 ssh_cache_conf_values(ssh);
9412 ssh->version = 0; /* when not ready yet */
9413 ssh->s = NULL;
9414 ssh->cipher = NULL;
9415 ssh->v1_cipher_ctx = NULL;
9416 ssh->crcda_ctx = NULL;
9417 ssh->cscipher = NULL;
9418 ssh->cs_cipher_ctx = NULL;
9419 ssh->sccipher = NULL;
9420 ssh->sc_cipher_ctx = NULL;
9421 ssh->csmac = NULL;
9422 ssh->cs_mac_ctx = NULL;
9423 ssh->scmac = NULL;
9424 ssh->sc_mac_ctx = NULL;
9425 ssh->cscomp = NULL;
9426 ssh->cs_comp_ctx = NULL;
9427 ssh->sccomp = NULL;
9428 ssh->sc_comp_ctx = NULL;
9429 ssh->kex = NULL;
9430 ssh->kex_ctx = NULL;
9431 ssh->hostkey = NULL;
9432 ssh->exitcode = -1;
9433 ssh->close_expected = FALSE;
9434 ssh->clean_exit = FALSE;
9435 ssh->state = SSH_STATE_PREPACKET;
9436 ssh->size_needed = FALSE;
9437 ssh->eof_needed = FALSE;
9438 ssh->ldisc = NULL;
9439 ssh->logctx = NULL;
9440 ssh->deferred_send_data = NULL;
9441 ssh->deferred_len = 0;
9442 ssh->deferred_size = 0;
9443 ssh->fallback_cmd = 0;
9444 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9445 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9446 ssh->x11disp = NULL;
9447 ssh->v1_compressing = FALSE;
9448 ssh->v2_outgoing_sequence = 0;
9449 ssh->ssh1_rdpkt_crstate = 0;
9450 ssh->ssh2_rdpkt_crstate = 0;
9451 ssh->do_ssh_init_crstate = 0;
9452 ssh->ssh_gotdata_crstate = 0;
9453 ssh->do_ssh1_connection_crstate = 0;
9454 ssh->do_ssh1_login_crstate = 0;
9455 ssh->do_ssh2_transport_crstate = 0;
9456 ssh->do_ssh2_authconn_crstate = 0;
9457 ssh->do_ssh_init_state = NULL;
9458 ssh->do_ssh1_login_state = NULL;
9459 ssh->do_ssh2_transport_state = NULL;
9460 ssh->do_ssh2_authconn_state = NULL;
9461 ssh->v_c = NULL;
9462 ssh->v_s = NULL;
9463 ssh->mainchan = NULL;
9464 ssh->throttled_all = 0;
9465 ssh->v1_stdout_throttling = 0;
9466 ssh->queue = NULL;
9467 ssh->queuelen = ssh->queuesize = 0;
9468 ssh->queueing = FALSE;
9469 ssh->qhead = ssh->qtail = NULL;
9470 ssh->deferred_rekey_reason = NULL;
9471 bufchain_init(&ssh->queued_incoming_data);
9472 ssh->frozen = FALSE;
9473 ssh->username = NULL;
9474 ssh->sent_console_eof = FALSE;
9475 ssh->got_pty = FALSE;
9476
9477 *backend_handle = ssh;
9478
9479 #ifdef MSCRYPTOAPI
9480 if (crypto_startup() == 0)
9481 return "Microsoft high encryption pack not installed!";
9482 #endif
9483
9484 ssh->frontend = frontend_handle;
9485 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9486 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9487
9488 ssh->channels = NULL;
9489 ssh->rportfwds = NULL;
9490 ssh->portfwds = NULL;
9491
9492 ssh->send_ok = 0;
9493 ssh->editing = 0;
9494 ssh->echoing = 0;
9495 ssh->conn_throttle_count = 0;
9496 ssh->overall_bufsize = 0;
9497 ssh->fallback_cmd = 0;
9498
9499 ssh->protocol = NULL;
9500
9501 ssh->protocol_initial_phase_done = FALSE;
9502
9503 ssh->pinger = NULL;
9504
9505 ssh->incoming_data_size = ssh->outgoing_data_size =
9506 ssh->deferred_data_size = 0L;
9507 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9508 CONF_ssh_rekey_data));
9509 ssh->kex_in_progress = FALSE;
9510
9511 #ifndef NO_GSSAPI
9512 ssh->gsslibs = NULL;
9513 #endif
9514
9515 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9516 if (p != NULL)
9517 return p;
9518
9519 random_ref();
9520
9521 return NULL;
9522 }
9523
9524 static void ssh_free(void *handle)
9525 {
9526 Ssh ssh = (Ssh) handle;
9527 struct ssh_channel *c;
9528 struct ssh_rportfwd *pf;
9529
9530 if (ssh->v1_cipher_ctx)
9531 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9532 if (ssh->cs_cipher_ctx)
9533 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9534 if (ssh->sc_cipher_ctx)
9535 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9536 if (ssh->cs_mac_ctx)
9537 ssh->csmac->free_context(ssh->cs_mac_ctx);
9538 if (ssh->sc_mac_ctx)
9539 ssh->scmac->free_context(ssh->sc_mac_ctx);
9540 if (ssh->cs_comp_ctx) {
9541 if (ssh->cscomp)
9542 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9543 else
9544 zlib_compress_cleanup(ssh->cs_comp_ctx);
9545 }
9546 if (ssh->sc_comp_ctx) {
9547 if (ssh->sccomp)
9548 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9549 else
9550 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9551 }
9552 if (ssh->kex_ctx)
9553 dh_cleanup(ssh->kex_ctx);
9554 sfree(ssh->savedhost);
9555
9556 while (ssh->queuelen-- > 0)
9557 ssh_free_packet(ssh->queue[ssh->queuelen]);
9558 sfree(ssh->queue);
9559
9560 while (ssh->qhead) {
9561 struct queued_handler *qh = ssh->qhead;
9562 ssh->qhead = qh->next;
9563 sfree(ssh->qhead);
9564 }
9565 ssh->qhead = ssh->qtail = NULL;
9566
9567 if (ssh->channels) {
9568 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9569 switch (c->type) {
9570 case CHAN_X11:
9571 if (c->u.x11.s != NULL)
9572 x11_close(c->u.x11.s);
9573 break;
9574 case CHAN_SOCKDATA:
9575 case CHAN_SOCKDATA_DORMANT:
9576 if (c->u.pfd.s != NULL)
9577 pfd_close(c->u.pfd.s);
9578 break;
9579 }
9580 sfree(c);
9581 }
9582 freetree234(ssh->channels);
9583 ssh->channels = NULL;
9584 }
9585
9586 if (ssh->rportfwds) {
9587 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9588 free_rportfwd(pf);
9589 freetree234(ssh->rportfwds);
9590 ssh->rportfwds = NULL;
9591 }
9592 sfree(ssh->deferred_send_data);
9593 if (ssh->x11disp)
9594 x11_free_display(ssh->x11disp);
9595 sfree(ssh->do_ssh_init_state);
9596 sfree(ssh->do_ssh1_login_state);
9597 sfree(ssh->do_ssh2_transport_state);
9598 sfree(ssh->do_ssh2_authconn_state);
9599 sfree(ssh->v_c);
9600 sfree(ssh->v_s);
9601 sfree(ssh->fullhostname);
9602 if (ssh->crcda_ctx) {
9603 crcda_free_context(ssh->crcda_ctx);
9604 ssh->crcda_ctx = NULL;
9605 }
9606 if (ssh->s)
9607 ssh_do_close(ssh, TRUE);
9608 expire_timer_context(ssh);
9609 if (ssh->pinger)
9610 pinger_free(ssh->pinger);
9611 bufchain_clear(&ssh->queued_incoming_data);
9612 sfree(ssh->username);
9613 conf_free(ssh->conf);
9614 #ifndef NO_GSSAPI
9615 if (ssh->gsslibs)
9616 ssh_gss_cleanup(ssh->gsslibs);
9617 #endif
9618 sfree(ssh);
9619
9620 random_unref();
9621 }
9622
9623 /*
9624 * Reconfigure the SSH backend.
9625 */
9626 static void ssh_reconfig(void *handle, Conf *conf)
9627 {
9628 Ssh ssh = (Ssh) handle;
9629 char *rekeying = NULL, rekey_mandatory = FALSE;
9630 unsigned long old_max_data_size;
9631 int i, rekey_time;
9632
9633 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9634 if (ssh->portfwds)
9635 ssh_setup_portfwd(ssh, conf);
9636
9637 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9638 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9639 rekey_time != 0) {
9640 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9641 long now = GETTICKCOUNT();
9642
9643 if (new_next - now < 0) {
9644 rekeying = "timeout shortened";
9645 } else {
9646 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9647 }
9648 }
9649
9650 old_max_data_size = ssh->max_data_size;
9651 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9652 CONF_ssh_rekey_data));
9653 if (old_max_data_size != ssh->max_data_size &&
9654 ssh->max_data_size != 0) {
9655 if (ssh->outgoing_data_size > ssh->max_data_size ||
9656 ssh->incoming_data_size > ssh->max_data_size)
9657 rekeying = "data limit lowered";
9658 }
9659
9660 if (conf_get_int(ssh->conf, CONF_compression) !=
9661 conf_get_int(conf, CONF_compression)) {
9662 rekeying = "compression setting changed";
9663 rekey_mandatory = TRUE;
9664 }
9665
9666 for (i = 0; i < CIPHER_MAX; i++)
9667 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9668 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9669 rekeying = "cipher settings changed";
9670 rekey_mandatory = TRUE;
9671 }
9672 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9673 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9674 rekeying = "cipher settings changed";
9675 rekey_mandatory = TRUE;
9676 }
9677
9678 conf_free(ssh->conf);
9679 ssh->conf = conf_copy(conf);
9680 ssh_cache_conf_values(ssh);
9681
9682 if (rekeying) {
9683 if (!ssh->kex_in_progress) {
9684 do_ssh2_transport(ssh, rekeying, -1, NULL);
9685 } else if (rekey_mandatory) {
9686 ssh->deferred_rekey_reason = rekeying;
9687 }
9688 }
9689 }
9690
9691 /*
9692 * Called to send data down the SSH connection.
9693 */
9694 static int ssh_send(void *handle, char *buf, int len)
9695 {
9696 Ssh ssh = (Ssh) handle;
9697
9698 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9699 return 0;
9700
9701 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9702
9703 return ssh_sendbuffer(ssh);
9704 }
9705
9706 /*
9707 * Called to query the current amount of buffered stdin data.
9708 */
9709 static int ssh_sendbuffer(void *handle)
9710 {
9711 Ssh ssh = (Ssh) handle;
9712 int override_value;
9713
9714 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9715 return 0;
9716
9717 /*
9718 * If the SSH socket itself has backed up, add the total backup
9719 * size on that to any individual buffer on the stdin channel.
9720 */
9721 override_value = 0;
9722 if (ssh->throttled_all)
9723 override_value = ssh->overall_bufsize;
9724
9725 if (ssh->version == 1) {
9726 return override_value;
9727 } else if (ssh->version == 2) {
9728 if (!ssh->mainchan)
9729 return override_value;
9730 else
9731 return (override_value +
9732 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9733 }
9734
9735 return 0;
9736 }
9737
9738 /*
9739 * Called to set the size of the window from SSH's POV.
9740 */
9741 static void ssh_size(void *handle, int width, int height)
9742 {
9743 Ssh ssh = (Ssh) handle;
9744 struct Packet *pktout;
9745
9746 ssh->term_width = width;
9747 ssh->term_height = height;
9748
9749 switch (ssh->state) {
9750 case SSH_STATE_BEFORE_SIZE:
9751 case SSH_STATE_PREPACKET:
9752 case SSH_STATE_CLOSED:
9753 break; /* do nothing */
9754 case SSH_STATE_INTERMED:
9755 ssh->size_needed = TRUE; /* buffer for later */
9756 break;
9757 case SSH_STATE_SESSION:
9758 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9759 if (ssh->version == 1) {
9760 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9761 PKT_INT, ssh->term_height,
9762 PKT_INT, ssh->term_width,
9763 PKT_INT, 0, PKT_INT, 0, PKT_END);
9764 } else if (ssh->mainchan) {
9765 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9766 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9767 ssh2_pkt_addstring(pktout, "window-change");
9768 ssh2_pkt_addbool(pktout, 0);
9769 ssh2_pkt_adduint32(pktout, ssh->term_width);
9770 ssh2_pkt_adduint32(pktout, ssh->term_height);
9771 ssh2_pkt_adduint32(pktout, 0);
9772 ssh2_pkt_adduint32(pktout, 0);
9773 ssh2_pkt_send(ssh, pktout);
9774 }
9775 }
9776 break;
9777 }
9778 }
9779
9780 /*
9781 * Return a list of the special codes that make sense in this
9782 * protocol.
9783 */
9784 static const struct telnet_special *ssh_get_specials(void *handle)
9785 {
9786 static const struct telnet_special ssh1_ignore_special[] = {
9787 {"IGNORE message", TS_NOP}
9788 };
9789 static const struct telnet_special ssh2_ignore_special[] = {
9790 {"IGNORE message", TS_NOP},
9791 };
9792 static const struct telnet_special ssh2_rekey_special[] = {
9793 {"Repeat key exchange", TS_REKEY},
9794 };
9795 static const struct telnet_special ssh2_session_specials[] = {
9796 {NULL, TS_SEP},
9797 {"Break", TS_BRK},
9798 /* These are the signal names defined by RFC 4254.
9799 * They include all the ISO C signals, but are a subset of the POSIX
9800 * required signals. */
9801 {"SIGINT (Interrupt)", TS_SIGINT},
9802 {"SIGTERM (Terminate)", TS_SIGTERM},
9803 {"SIGKILL (Kill)", TS_SIGKILL},
9804 {"SIGQUIT (Quit)", TS_SIGQUIT},
9805 {"SIGHUP (Hangup)", TS_SIGHUP},
9806 {"More signals", TS_SUBMENU},
9807 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9808 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9809 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9810 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9811 {NULL, TS_EXITMENU}
9812 };
9813 static const struct telnet_special specials_end[] = {
9814 {NULL, TS_EXITMENU}
9815 };
9816 /* XXX review this length for any changes: */
9817 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9818 lenof(ssh2_rekey_special) +
9819 lenof(ssh2_session_specials) +
9820 lenof(specials_end)];
9821 Ssh ssh = (Ssh) handle;
9822 int i = 0;
9823 #define ADD_SPECIALS(name) \
9824 do { \
9825 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9826 memcpy(&ssh_specials[i], name, sizeof name); \
9827 i += lenof(name); \
9828 } while(0)
9829
9830 if (ssh->version == 1) {
9831 /* Don't bother offering IGNORE if we've decided the remote
9832 * won't cope with it, since we wouldn't bother sending it if
9833 * asked anyway. */
9834 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9835 ADD_SPECIALS(ssh1_ignore_special);
9836 } else if (ssh->version == 2) {
9837 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9838 ADD_SPECIALS(ssh2_ignore_special);
9839 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9840 ADD_SPECIALS(ssh2_rekey_special);
9841 if (ssh->mainchan)
9842 ADD_SPECIALS(ssh2_session_specials);
9843 } /* else we're not ready yet */
9844
9845 if (i) {
9846 ADD_SPECIALS(specials_end);
9847 return ssh_specials;
9848 } else {
9849 return NULL;
9850 }
9851 #undef ADD_SPECIALS
9852 }
9853
9854 /*
9855 * Send special codes. TS_EOF is useful for `plink', so you
9856 * can send an EOF and collect resulting output (e.g. `plink
9857 * hostname sort').
9858 */
9859 static void ssh_special(void *handle, Telnet_Special code)
9860 {
9861 Ssh ssh = (Ssh) handle;
9862 struct Packet *pktout;
9863
9864 if (code == TS_EOF) {
9865 if (ssh->state != SSH_STATE_SESSION) {
9866 /*
9867 * Buffer the EOF in case we are pre-SESSION, so we can
9868 * send it as soon as we reach SESSION.
9869 */
9870 if (code == TS_EOF)
9871 ssh->eof_needed = TRUE;
9872 return;
9873 }
9874 if (ssh->version == 1) {
9875 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9876 } else if (ssh->mainchan) {
9877 sshfwd_write_eof(ssh->mainchan);
9878 ssh->send_ok = 0; /* now stop trying to read from stdin */
9879 }
9880 logevent("Sent EOF message");
9881 } else if (code == TS_PING || code == TS_NOP) {
9882 if (ssh->state == SSH_STATE_CLOSED
9883 || ssh->state == SSH_STATE_PREPACKET) return;
9884 if (ssh->version == 1) {
9885 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9886 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9887 } else {
9888 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9889 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9890 ssh2_pkt_addstring_start(pktout);
9891 ssh2_pkt_send_noqueue(ssh, pktout);
9892 }
9893 }
9894 } else if (code == TS_REKEY) {
9895 if (!ssh->kex_in_progress && ssh->version == 2) {
9896 do_ssh2_transport(ssh, "at user request", -1, NULL);
9897 }
9898 } else if (code == TS_BRK) {
9899 if (ssh->state == SSH_STATE_CLOSED
9900 || ssh->state == SSH_STATE_PREPACKET) return;
9901 if (ssh->version == 1) {
9902 logevent("Unable to send BREAK signal in SSH-1");
9903 } else if (ssh->mainchan) {
9904 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9905 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9906 ssh2_pkt_addstring(pktout, "break");
9907 ssh2_pkt_addbool(pktout, 0);
9908 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9909 ssh2_pkt_send(ssh, pktout);
9910 }
9911 } else {
9912 /* Is is a POSIX signal? */
9913 char *signame = NULL;
9914 if (code == TS_SIGABRT) signame = "ABRT";
9915 if (code == TS_SIGALRM) signame = "ALRM";
9916 if (code == TS_SIGFPE) signame = "FPE";
9917 if (code == TS_SIGHUP) signame = "HUP";
9918 if (code == TS_SIGILL) signame = "ILL";
9919 if (code == TS_SIGINT) signame = "INT";
9920 if (code == TS_SIGKILL) signame = "KILL";
9921 if (code == TS_SIGPIPE) signame = "PIPE";
9922 if (code == TS_SIGQUIT) signame = "QUIT";
9923 if (code == TS_SIGSEGV) signame = "SEGV";
9924 if (code == TS_SIGTERM) signame = "TERM";
9925 if (code == TS_SIGUSR1) signame = "USR1";
9926 if (code == TS_SIGUSR2) signame = "USR2";
9927 /* The SSH-2 protocol does in principle support arbitrary named
9928 * signals, including signame@domain, but we don't support those. */
9929 if (signame) {
9930 /* It's a signal. */
9931 if (ssh->version == 2 && ssh->mainchan) {
9932 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9933 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9934 ssh2_pkt_addstring(pktout, "signal");
9935 ssh2_pkt_addbool(pktout, 0);
9936 ssh2_pkt_addstring(pktout, signame);
9937 ssh2_pkt_send(ssh, pktout);
9938 logeventf(ssh, "Sent signal SIG%s", signame);
9939 }
9940 } else {
9941 /* Never heard of it. Do nothing */
9942 }
9943 }
9944 }
9945
9946 void *new_sock_channel(void *handle, Socket s)
9947 {
9948 Ssh ssh = (Ssh) handle;
9949 struct ssh_channel *c;
9950 c = snew(struct ssh_channel);
9951
9952 c->ssh = ssh;
9953 ssh2_channel_init(c);
9954 c->halfopen = TRUE;
9955 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9956 c->u.pfd.s = s;
9957 add234(ssh->channels, c);
9958 return c;
9959 }
9960
9961 /*
9962 * This is called when stdout/stderr (the entity to which
9963 * from_backend sends data) manages to clear some backlog.
9964 */
9965 static void ssh_unthrottle(void *handle, int bufsize)
9966 {
9967 Ssh ssh = (Ssh) handle;
9968 int buflimit;
9969
9970 if (ssh->version == 1) {
9971 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9972 ssh->v1_stdout_throttling = 0;
9973 ssh_throttle_conn(ssh, -1);
9974 }
9975 } else {
9976 if (ssh->mainchan) {
9977 ssh2_set_window(ssh->mainchan,
9978 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9979 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9980 if (conf_get_int(ssh->conf, CONF_ssh_simple))
9981 buflimit = 0;
9982 else
9983 buflimit = ssh->mainchan->v.v2.locmaxwin;
9984 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9985 ssh->mainchan->throttling_conn = 0;
9986 ssh_throttle_conn(ssh, -1);
9987 }
9988 }
9989 }
9990 }
9991
9992 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9993 {
9994 struct ssh_channel *c = (struct ssh_channel *)channel;
9995 Ssh ssh = c->ssh;
9996 struct Packet *pktout;
9997
9998 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9999
10000 if (ssh->version == 1) {
10001 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10002 PKT_INT, c->localid,
10003 PKT_STR, hostname,
10004 PKT_INT, port,
10005 /* PKT_STR, <org:orgport>, */
10006 PKT_END);
10007 } else {
10008 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
10009 ssh2_pkt_addstring(pktout, "direct-tcpip");
10010 ssh2_pkt_adduint32(pktout, c->localid);
10011 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
10012 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
10013 ssh2_pkt_addstring(pktout, hostname);
10014 ssh2_pkt_adduint32(pktout, port);
10015 /*
10016 * We make up values for the originator data; partly it's
10017 * too much hassle to keep track, and partly I'm not
10018 * convinced the server should be told details like that
10019 * about my local network configuration.
10020 * The "originator IP address" is syntactically a numeric
10021 * IP address, and some servers (e.g., Tectia) get upset
10022 * if it doesn't match this syntax.
10023 */
10024 ssh2_pkt_addstring(pktout, "0.0.0.0");
10025 ssh2_pkt_adduint32(pktout, 0);
10026 ssh2_pkt_send(ssh, pktout);
10027 }
10028 }
10029
10030 static int ssh_connected(void *handle)
10031 {
10032 Ssh ssh = (Ssh) handle;
10033 return ssh->s != NULL;
10034 }
10035
10036 static int ssh_sendok(void *handle)
10037 {
10038 Ssh ssh = (Ssh) handle;
10039 return ssh->send_ok;
10040 }
10041
10042 static int ssh_ldisc(void *handle, int option)
10043 {
10044 Ssh ssh = (Ssh) handle;
10045 if (option == LD_ECHO)
10046 return ssh->echoing;
10047 if (option == LD_EDIT)
10048 return ssh->editing;
10049 return FALSE;
10050 }
10051
10052 static void ssh_provide_ldisc(void *handle, void *ldisc)
10053 {
10054 Ssh ssh = (Ssh) handle;
10055 ssh->ldisc = ldisc;
10056 }
10057
10058 static void ssh_provide_logctx(void *handle, void *logctx)
10059 {
10060 Ssh ssh = (Ssh) handle;
10061 ssh->logctx = logctx;
10062 }
10063
10064 static int ssh_return_exitcode(void *handle)
10065 {
10066 Ssh ssh = (Ssh) handle;
10067 if (ssh->s != NULL)
10068 return -1;
10069 else
10070 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10071 }
10072
10073 /*
10074 * cfg_info for SSH is the currently running version of the
10075 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10076 */
10077 static int ssh_cfg_info(void *handle)
10078 {
10079 Ssh ssh = (Ssh) handle;
10080 return ssh->version;
10081 }
10082
10083 /*
10084 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10085 * that fails. This variable is the means by which scp.c can reach
10086 * into the SSH code and find out which one it got.
10087 */
10088 extern int ssh_fallback_cmd(void *handle)
10089 {
10090 Ssh ssh = (Ssh) handle;
10091 return ssh->fallback_cmd;
10092 }
10093
10094 Backend ssh_backend = {
10095 ssh_init,
10096 ssh_free,
10097 ssh_reconfig,
10098 ssh_send,
10099 ssh_sendbuffer,
10100 ssh_size,
10101 ssh_special,
10102 ssh_get_specials,
10103 ssh_connected,
10104 ssh_return_exitcode,
10105 ssh_sendok,
10106 ssh_ldisc,
10107 ssh_provide_ldisc,
10108 ssh_provide_logctx,
10109 ssh_unthrottle,
10110 ssh_cfg_info,
10111 "ssh",
10112 PROT_SSH,
10113 22
10114 };