SSH ciphers now use dynamically allocated contexts.
[u/mdw/putty] / ssh.c
1 #include <windows.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdarg.h>
5 #include <assert.h>
6
7 #include "putty.h"
8 #include "tree234.h"
9 #include "ssh.h"
10
11 #ifndef FALSE
12 #define FALSE 0
13 #endif
14 #ifndef TRUE
15 #define TRUE 1
16 #endif
17
18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
21
22 /* logevent, only printf-formatted. */
23 void logeventf(char *fmt, ...)
24 {
25 va_list ap;
26 char stuff[200];
27
28 va_start(ap, fmt);
29 vsprintf(stuff, fmt, ap);
30 va_end(ap);
31 logevent(stuff);
32 }
33
34 #define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
35 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
36 logeventf msg, connection_fatal msg )
37
38 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
39 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
40 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
41 #define SSH1_CMSG_USER 4 /* 0x4 */
42 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
43 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
44 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
45 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
46 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
47 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
48 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
49 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
50 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
51 #define SSH1_SMSG_FAILURE 15 /* 0xf */
52 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
53 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
54 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
55 #define SSH1_CMSG_EOF 19 /* 0x13 */
56 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
57 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
58 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
59 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
60 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
61 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
62 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
63 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
64 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
65 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
66 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
67 #define SSH1_MSG_IGNORE 32 /* 0x20 */
68 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
69 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
70 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
71 #define SSH1_MSG_DEBUG 36 /* 0x24 */
72 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
73 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
74 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
75 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
76 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
77 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
78 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
79
80 #define SSH1_AUTH_TIS 5 /* 0x5 */
81 #define SSH1_AUTH_CCARD 16 /* 0x10 */
82
83 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
84 /* Mask for protoflags we will echo back to server if seen */
85 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
86
87 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
88 #define SSH2_MSG_IGNORE 2 /* 0x2 */
89 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
90 #define SSH2_MSG_DEBUG 4 /* 0x4 */
91 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
92 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
93 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
94 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
95 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
96 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
97 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
98 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
99 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
100 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
101 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
102 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
103 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
104 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
105 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
106 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
107 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
109 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
110 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
111 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
112 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
113 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
114 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
115 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
116 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
117 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
118 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
119 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
120 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
121 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
122 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
123
124 /*
125 * Packet type contexts, so that ssh2_pkt_type can correctly decode
126 * the ambiguous type numbers back into the correct type strings.
127 */
128 #define SSH2_PKTCTX_DHGROUP1 0x0001
129 #define SSH2_PKTCTX_DHGEX 0x0002
130 #define SSH2_PKTCTX_PUBLICKEY 0x0010
131 #define SSH2_PKTCTX_PASSWORD 0x0020
132 #define SSH2_PKTCTX_KBDINTER 0x0040
133 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
134
135 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
136 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
137 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
138 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
139 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
140 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
141 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
142 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
143 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
144 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
145 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
146 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
147 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
148 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
149 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
150
151 static const char *const ssh2_disconnect_reasons[] = {
152 NULL,
153 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
154 "SSH_DISCONNECT_PROTOCOL_ERROR",
155 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
156 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
157 "SSH_DISCONNECT_MAC_ERROR",
158 "SSH_DISCONNECT_COMPRESSION_ERROR",
159 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
160 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
161 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
162 "SSH_DISCONNECT_CONNECTION_LOST",
163 "SSH_DISCONNECT_BY_APPLICATION",
164 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
165 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
166 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
167 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
168 };
169
170 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
171 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
172 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
173 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
174
175 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
176
177 /*
178 * Various remote-bug flags.
179 */
180 #define BUG_CHOKES_ON_SSH1_IGNORE 1
181 #define BUG_SSH2_HMAC 2
182 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
183 #define BUG_CHOKES_ON_RSA 8
184 #define BUG_SSH2_RSA_PADDING 16
185 #define BUG_SSH2_DERIVEKEY 32
186 #define BUG_SSH2_DH_GEX 64
187
188 #define translate(x) if (type == x) return #x
189 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
190 char *ssh1_pkt_type(int type)
191 {
192 translate(SSH1_MSG_DISCONNECT);
193 translate(SSH1_SMSG_PUBLIC_KEY);
194 translate(SSH1_CMSG_SESSION_KEY);
195 translate(SSH1_CMSG_USER);
196 translate(SSH1_CMSG_AUTH_RSA);
197 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
198 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
199 translate(SSH1_CMSG_AUTH_PASSWORD);
200 translate(SSH1_CMSG_REQUEST_PTY);
201 translate(SSH1_CMSG_WINDOW_SIZE);
202 translate(SSH1_CMSG_EXEC_SHELL);
203 translate(SSH1_CMSG_EXEC_CMD);
204 translate(SSH1_SMSG_SUCCESS);
205 translate(SSH1_SMSG_FAILURE);
206 translate(SSH1_CMSG_STDIN_DATA);
207 translate(SSH1_SMSG_STDOUT_DATA);
208 translate(SSH1_SMSG_STDERR_DATA);
209 translate(SSH1_CMSG_EOF);
210 translate(SSH1_SMSG_EXIT_STATUS);
211 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
212 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
213 translate(SSH1_MSG_CHANNEL_DATA);
214 translate(SSH1_MSG_CHANNEL_CLOSE);
215 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
216 translate(SSH1_SMSG_X11_OPEN);
217 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
218 translate(SSH1_MSG_PORT_OPEN);
219 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
220 translate(SSH1_SMSG_AGENT_OPEN);
221 translate(SSH1_MSG_IGNORE);
222 translate(SSH1_CMSG_EXIT_CONFIRMATION);
223 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
224 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
225 translate(SSH1_MSG_DEBUG);
226 translate(SSH1_CMSG_REQUEST_COMPRESSION);
227 translate(SSH1_CMSG_AUTH_TIS);
228 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
229 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
230 translate(SSH1_CMSG_AUTH_CCARD);
231 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
232 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
233 return "unknown";
234 }
235 char *ssh2_pkt_type(int pkt_ctx, int type)
236 {
237 translate(SSH2_MSG_DISCONNECT);
238 translate(SSH2_MSG_IGNORE);
239 translate(SSH2_MSG_UNIMPLEMENTED);
240 translate(SSH2_MSG_DEBUG);
241 translate(SSH2_MSG_SERVICE_REQUEST);
242 translate(SSH2_MSG_SERVICE_ACCEPT);
243 translate(SSH2_MSG_KEXINIT);
244 translate(SSH2_MSG_NEWKEYS);
245 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
246 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
247 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
248 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
249 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
250 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
251 translate(SSH2_MSG_USERAUTH_REQUEST);
252 translate(SSH2_MSG_USERAUTH_FAILURE);
253 translate(SSH2_MSG_USERAUTH_SUCCESS);
254 translate(SSH2_MSG_USERAUTH_BANNER);
255 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
256 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
257 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
258 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
259 translate(SSH2_MSG_GLOBAL_REQUEST);
260 translate(SSH2_MSG_REQUEST_SUCCESS);
261 translate(SSH2_MSG_REQUEST_FAILURE);
262 translate(SSH2_MSG_CHANNEL_OPEN);
263 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
264 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
265 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
266 translate(SSH2_MSG_CHANNEL_DATA);
267 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
268 translate(SSH2_MSG_CHANNEL_EOF);
269 translate(SSH2_MSG_CHANNEL_CLOSE);
270 translate(SSH2_MSG_CHANNEL_REQUEST);
271 translate(SSH2_MSG_CHANNEL_SUCCESS);
272 translate(SSH2_MSG_CHANNEL_FAILURE);
273 return "unknown";
274 }
275 #undef translate
276 #undef translatec
277
278 #define GET_32BIT(cp) \
279 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
280 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
281 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
282 ((unsigned long)(unsigned char)(cp)[3]))
283
284 #define PUT_32BIT(cp, value) { \
285 (cp)[0] = (unsigned char)((value) >> 24); \
286 (cp)[1] = (unsigned char)((value) >> 16); \
287 (cp)[2] = (unsigned char)((value) >> 8); \
288 (cp)[3] = (unsigned char)(value); }
289
290 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
291
292 /* Coroutine mechanics for the sillier bits of the code */
293 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
294 #define crState(t) \
295 struct t *s; \
296 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
297 s = ssh->t;
298 #define crFinish(z) } *crLine = 0; return (z); }
299 #define crFinishV } *crLine = 0; return; }
300 #define crReturn(z) \
301 do {\
302 *crLine =__LINE__; return (z); case __LINE__:;\
303 } while (0)
304 #define crReturnV \
305 do {\
306 *crLine=__LINE__; return; case __LINE__:;\
307 } while (0)
308 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
309 #define crStopV do{ *crLine = 0; return; }while(0)
310 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
311 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
312
313 typedef struct ssh_tag *Ssh;
314
315 extern char *x11_init(Socket *, char *, void *);
316 extern void x11_close(Socket);
317 extern int x11_send(Socket, char *, int);
318 extern void x11_invent_auth(char *, int, char *, int);
319 extern void x11_unthrottle(Socket s);
320 extern void x11_override_throttle(Socket s, int enable);
321
322 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
323 extern char *pfd_addforward(char *desthost, int destport, int port);
324 extern void pfd_close(Socket s);
325 extern int pfd_send(Socket s, char *data, int len);
326 extern void pfd_confirm(Socket s);
327 extern void pfd_unthrottle(Socket s);
328 extern void pfd_override_throttle(Socket s, int enable);
329
330 static void ssh2_pkt_init(Ssh, int pkt_type);
331 static void ssh2_pkt_addbool(Ssh, unsigned char value);
332 static void ssh2_pkt_adduint32(Ssh, unsigned long value);
333 static void ssh2_pkt_addstring_start(Ssh);
334 static void ssh2_pkt_addstring_str(Ssh, char *data);
335 static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
336 static void ssh2_pkt_addstring(Ssh, char *data);
337 static char *ssh2_mpint_fmt(Bignum b, int *len);
338 static void ssh2_pkt_addmp(Ssh, Bignum b);
339 static int ssh2_pkt_construct(Ssh);
340 static void ssh2_pkt_send(Ssh);
341
342 /*
343 * Buffer management constants. There are several of these for
344 * various different purposes:
345 *
346 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
347 * on a local data stream before we throttle the whole SSH
348 * connection (in SSH1 only). Throttling the whole connection is
349 * pretty drastic so we set this high in the hope it won't
350 * happen very often.
351 *
352 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
353 * on the SSH connection itself before we defensively throttle
354 * _all_ local data streams. This is pretty drastic too (though
355 * thankfully unlikely in SSH2 since the window mechanism should
356 * ensure that the server never has any need to throttle its end
357 * of the connection), so we set this high as well.
358 *
359 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
360 * channels.
361 */
362
363 #define SSH1_BUFFER_LIMIT 32768
364 #define SSH_MAX_BACKLOG 32768
365 #define OUR_V2_WINSIZE 16384
366
367 const static struct ssh_kex *kex_algs[] = {
368 &ssh_diffiehellman_gex,
369 &ssh_diffiehellman
370 };
371
372 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
373
374 static void nullmac_key(unsigned char *key)
375 {
376 }
377 static void nullmac_generate(unsigned char *blk, int len,
378 unsigned long seq)
379 {
380 }
381 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
382 {
383 return 1;
384 }
385 const static struct ssh_mac ssh_mac_none = {
386 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
387 };
388 const static struct ssh_mac *macs[] = {
389 &ssh_sha1, &ssh_md5, &ssh_mac_none
390 };
391 const static struct ssh_mac *buggymacs[] = {
392 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
393 };
394
395 static void ssh_comp_none_init(void)
396 {
397 }
398 static int ssh_comp_none_block(unsigned char *block, int len,
399 unsigned char **outblock, int *outlen)
400 {
401 return 0;
402 }
403 static int ssh_comp_none_disable(void)
404 {
405 return 0;
406 }
407 const static struct ssh_compress ssh_comp_none = {
408 "none",
409 ssh_comp_none_init, ssh_comp_none_block,
410 ssh_comp_none_init, ssh_comp_none_block,
411 ssh_comp_none_disable
412 };
413 extern const struct ssh_compress ssh_zlib;
414 const static struct ssh_compress *compressions[] = {
415 &ssh_zlib, &ssh_comp_none
416 };
417
418 enum { /* channel types */
419 CHAN_MAINSESSION,
420 CHAN_X11,
421 CHAN_AGENT,
422 CHAN_SOCKDATA,
423 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
424 };
425
426 /*
427 * 2-3-4 tree storing channels.
428 */
429 struct ssh_channel {
430 Ssh ssh; /* pointer back to main context */
431 unsigned remoteid, localid;
432 int type;
433 /*
434 * In SSH1, this value contains four bits:
435 *
436 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
437 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
438 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
439 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
440 *
441 * A channel is completely finished with when all four bits are set.
442 */
443 int closes;
444 union {
445 struct ssh1_data_channel {
446 int throttling;
447 } v1;
448 struct ssh2_data_channel {
449 bufchain outbuffer;
450 unsigned remwindow, remmaxpkt;
451 unsigned locwindow;
452 } v2;
453 } v;
454 union {
455 struct ssh_agent_channel {
456 unsigned char *message;
457 unsigned char msglen[4];
458 int lensofar, totallen;
459 } a;
460 struct ssh_x11_channel {
461 Socket s;
462 } x11;
463 struct ssh_pfd_channel {
464 Socket s;
465 } pfd;
466 } u;
467 };
468
469 /*
470 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
471 * 2 use this structure in different ways, reflecting SSH 2's
472 * altogether saner approach to port forwarding.
473 *
474 * In SSH 1, you arrange a remote forwarding by sending the server
475 * the remote port number, and the local destination host:port.
476 * When a connection comes in, the server sends you back that
477 * host:port pair, and you connect to it. This is a ready-made
478 * security hole if you're not on the ball: a malicious server
479 * could send you back _any_ host:port pair, so if you trustingly
480 * connect to the address it gives you then you've just opened the
481 * entire inside of your corporate network just by connecting
482 * through it to a dodgy SSH server. Hence, we must store a list of
483 * host:port pairs we _are_ trying to forward to, and reject a
484 * connection request from the server if it's not in the list.
485 *
486 * In SSH 2, each side of the connection minds its own business and
487 * doesn't send unnecessary information to the other. You arrange a
488 * remote forwarding by sending the server just the remote port
489 * number. When a connection comes in, the server tells you which
490 * of its ports was connected to; and _you_ have to remember what
491 * local host:port pair went with that port number.
492 *
493 * Hence: in SSH 1 this structure stores host:port pairs we intend
494 * to allow connections to, and is indexed by those host:port
495 * pairs. In SSH 2 it stores a mapping from source port to
496 * destination host:port pair, and is indexed by source port.
497 */
498 struct ssh_rportfwd {
499 unsigned sport, dport;
500 char dhost[256];
501 };
502
503 struct Packet {
504 long length;
505 int type;
506 unsigned char *data;
507 unsigned char *body;
508 long savedpos;
509 long maxlen;
510 };
511
512 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
513 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
514 static void ssh_size(void *handle, int width, int height);
515 static void ssh_special(void *handle, Telnet_Special);
516 static int ssh2_try_send(struct ssh_channel *c);
517 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
518 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
519 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
520 static int ssh_sendbuffer(void *handle);
521
522 struct rdpkt1_state_tag {
523 long len, pad, biglen, to_read;
524 unsigned long realcrc, gotcrc;
525 unsigned char *p;
526 int i;
527 int chunk;
528 };
529
530 struct rdpkt2_state_tag {
531 long len, pad, payload, packetlen, maclen;
532 int i;
533 int cipherblk;
534 unsigned long incoming_sequence;
535 };
536
537 struct ssh_tag {
538 const struct plug_function_table *fn;
539 /* the above field _must_ be first in the structure */
540
541 SHA_State exhash, exhashbase;
542
543 Socket s;
544
545 unsigned char session_key[32];
546 int v1_compressing;
547 int v1_remote_protoflags;
548 int v1_local_protoflags;
549 int agentfwd_enabled;
550 int X11_fwd_enabled;
551 int remote_bugs;
552 const struct ssh_cipher *cipher;
553 void *v1_cipher_ctx;
554 const struct ssh2_cipher *cscipher, *sccipher;
555 void *cs_cipher_ctx, *sc_cipher_ctx;
556 const struct ssh_mac *csmac, *scmac;
557 const struct ssh_compress *cscomp, *sccomp;
558 const struct ssh_kex *kex;
559 const struct ssh_signkey *hostkey;
560 unsigned char v2_session_id[20];
561
562 char *savedhost;
563 int savedport;
564 int send_ok;
565 int echoing, editing;
566
567 void *frontend;
568
569 int term_width, term_height;
570
571 tree234 *channels; /* indexed by local id */
572 struct ssh_channel *mainchan; /* primary session channel */
573 int exitcode;
574
575 tree234 *rportfwds;
576
577 enum {
578 SSH_STATE_PREPACKET,
579 SSH_STATE_BEFORE_SIZE,
580 SSH_STATE_INTERMED,
581 SSH_STATE_SESSION,
582 SSH_STATE_CLOSED
583 } state;
584
585 int size_needed, eof_needed;
586
587 struct Packet pktin;
588 struct Packet pktout;
589 unsigned char *deferred_send_data;
590 int deferred_len, deferred_size;
591
592 /*
593 * Gross hack: pscp will try to start SFTP but fall back to
594 * scp1 if that fails. This variable is the means by which
595 * scp.c can reach into the SSH code and find out which one it
596 * got.
597 */
598 int fallback_cmd;
599
600 /*
601 * Used for username and password input.
602 */
603 char *userpass_input_buffer;
604 int userpass_input_buflen;
605 int userpass_input_bufpos;
606 int userpass_input_echo;
607
608 char *portfwd_strptr;
609 int pkt_ctx;
610
611 int version;
612 int v1_throttle_count;
613 int overall_bufsize;
614 int throttled_all;
615 int v1_stdout_throttling;
616 int v2_outgoing_sequence;
617
618 int ssh1_rdpkt_crstate;
619 int ssh2_rdpkt_crstate;
620 int do_ssh_init_crstate;
621 int ssh_gotdata_crstate;
622 int ssh1_protocol_crstate;
623 int do_ssh1_login_crstate;
624 int do_ssh2_transport_crstate;
625 int do_ssh2_authconn_crstate;
626
627 void *do_ssh_init_state;
628 void *do_ssh1_login_state;
629 void *do_ssh2_transport_state;
630 void *do_ssh2_authconn_state;
631
632 struct rdpkt1_state_tag rdpkt1_state;
633 struct rdpkt2_state_tag rdpkt2_state;
634
635 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
636 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
637 };
638
639 static int ssh_channelcmp(void *av, void *bv)
640 {
641 struct ssh_channel *a = (struct ssh_channel *) av;
642 struct ssh_channel *b = (struct ssh_channel *) bv;
643 if (a->localid < b->localid)
644 return -1;
645 if (a->localid > b->localid)
646 return +1;
647 return 0;
648 }
649 static int ssh_channelfind(void *av, void *bv)
650 {
651 unsigned *a = (unsigned *) av;
652 struct ssh_channel *b = (struct ssh_channel *) bv;
653 if (*a < b->localid)
654 return -1;
655 if (*a > b->localid)
656 return +1;
657 return 0;
658 }
659
660 static int ssh_rportcmp_ssh1(void *av, void *bv)
661 {
662 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
663 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
664 int i;
665 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
666 return i < 0 ? -1 : +1;
667 if (a->dport > b->dport)
668 return +1;
669 if (a->dport < b->dport)
670 return -1;
671 return 0;
672 }
673
674 static int ssh_rportcmp_ssh2(void *av, void *bv)
675 {
676 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
677 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
678
679 if (a->sport > b->sport)
680 return +1;
681 if (a->sport < b->sport)
682 return -1;
683 return 0;
684 }
685
686 static int alloc_channel_id(Ssh ssh)
687 {
688 const unsigned CHANNEL_NUMBER_OFFSET = 256;
689 unsigned low, high, mid;
690 int tsize;
691 struct ssh_channel *c;
692
693 /*
694 * First-fit allocation of channel numbers: always pick the
695 * lowest unused one. To do this, binary-search using the
696 * counted B-tree to find the largest channel ID which is in a
697 * contiguous sequence from the beginning. (Precisely
698 * everything in that sequence must have ID equal to its tree
699 * index plus CHANNEL_NUMBER_OFFSET.)
700 */
701 tsize = count234(ssh->channels);
702
703 low = -1;
704 high = tsize;
705 while (high - low > 1) {
706 mid = (high + low) / 2;
707 c = index234(ssh->channels, mid);
708 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
709 low = mid; /* this one is fine */
710 else
711 high = mid; /* this one is past it */
712 }
713 /*
714 * Now low points to either -1, or the tree index of the
715 * largest ID in the initial sequence.
716 */
717 {
718 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
719 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
720 }
721 return low + 1 + CHANNEL_NUMBER_OFFSET;
722 }
723
724 static void c_write(Ssh ssh, char *buf, int len)
725 {
726 if ((flags & FLAG_STDERR)) {
727 int i;
728 for (i = 0; i < len; i++)
729 if (buf[i] != '\r')
730 fputc(buf[i], stderr);
731 return;
732 }
733 from_backend(ssh->frontend, 1, buf, len);
734 }
735
736 static void c_write_untrusted(Ssh ssh, char *buf, int len)
737 {
738 int i;
739 for (i = 0; i < len; i++) {
740 if (buf[i] == '\n')
741 c_write(ssh, "\r\n", 2);
742 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
743 c_write(ssh, buf + i, 1);
744 }
745 }
746
747 static void c_write_str(Ssh ssh, char *buf)
748 {
749 c_write(ssh, buf, strlen(buf));
750 }
751
752 /*
753 * Collect incoming data in the incoming packet buffer.
754 * Decipher and verify the packet when it is completely read.
755 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
756 * Update the *data and *datalen variables.
757 * Return the additional nr of bytes needed, or 0 when
758 * a complete packet is available.
759 */
760 static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
761 {
762 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
763
764 crBegin(ssh->ssh1_rdpkt_crstate);
765
766 next_packet:
767
768 ssh->pktin.type = 0;
769 ssh->pktin.length = 0;
770
771 for (st->i = st->len = 0; st->i < 4; st->i++) {
772 while ((*datalen) == 0)
773 crReturn(4 - st->i);
774 st->len = (st->len << 8) + **data;
775 (*data)++, (*datalen)--;
776 }
777
778 st->pad = 8 - (st->len % 8);
779 st->biglen = st->len + st->pad;
780 ssh->pktin.length = st->len - 5;
781
782 if (ssh->pktin.maxlen < st->biglen) {
783 ssh->pktin.maxlen = st->biglen;
784 ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
785 }
786
787 st->to_read = st->biglen;
788 st->p = ssh->pktin.data;
789 while (st->to_read > 0) {
790 st->chunk = st->to_read;
791 while ((*datalen) == 0)
792 crReturn(st->to_read);
793 if (st->chunk > (*datalen))
794 st->chunk = (*datalen);
795 memcpy(st->p, *data, st->chunk);
796 *data += st->chunk;
797 *datalen -= st->chunk;
798 st->p += st->chunk;
799 st->to_read -= st->chunk;
800 }
801
802 if (ssh->cipher && detect_attack(ssh->pktin.data, st->biglen, NULL)) {
803 bombout(("Network attack (CRC compensation) detected!"));
804 crReturn(0);
805 }
806
807 if (ssh->cipher)
808 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
809
810 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
811 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
812 if (st->gotcrc != st->realcrc) {
813 bombout(("Incorrect CRC received on packet"));
814 crReturn(0);
815 }
816
817 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
818
819 if (ssh->v1_compressing) {
820 unsigned char *decompblk;
821 int decomplen;
822 zlib_decompress_block(ssh->pktin.body - 1, ssh->pktin.length + 1,
823 &decompblk, &decomplen);
824
825 if (ssh->pktin.maxlen < st->pad + decomplen) {
826 ssh->pktin.maxlen = st->pad + decomplen;
827 ssh->pktin.data = srealloc(ssh->pktin.data,
828 ssh->pktin.maxlen + APIEXTRA);
829 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
830 }
831
832 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
833 sfree(decompblk);
834 ssh->pktin.length = decomplen - 1;
835 }
836
837 ssh->pktin.type = ssh->pktin.body[-1];
838
839 log_packet(PKT_INCOMING, ssh->pktin.type, ssh1_pkt_type(ssh->pktin.type),
840 ssh->pktin.body, ssh->pktin.length);
841
842 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
843 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
844 ssh->pktin.type == SSH1_MSG_DEBUG ||
845 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
846 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
847 long stringlen = GET_32BIT(ssh->pktin.body);
848 if (stringlen + 4 != ssh->pktin.length) {
849 bombout(("Received data packet with bogus string length"));
850 crReturn(0);
851 }
852 }
853
854 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
855 /* log debug message */
856 char buf[512];
857 int stringlen = GET_32BIT(ssh->pktin.body);
858 strcpy(buf, "Remote debug message: ");
859 if (stringlen > 480)
860 stringlen = 480;
861 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
862 buf[8 + stringlen] = '\0';
863 logevent(buf);
864 goto next_packet;
865 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
866 /* do nothing */
867 goto next_packet;
868 }
869
870 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
871 /* log reason code in disconnect message */
872 char buf[256];
873 unsigned msglen = GET_32BIT(ssh->pktin.body);
874 unsigned nowlen;
875 strcpy(buf, "Remote sent disconnect: ");
876 nowlen = strlen(buf);
877 if (msglen > sizeof(buf) - nowlen - 1)
878 msglen = sizeof(buf) - nowlen - 1;
879 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
880 buf[nowlen + msglen] = '\0';
881 /* logevent(buf); (this is now done within the bombout macro) */
882 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
883 crReturn(0);
884 }
885
886 crFinish(0);
887 }
888
889 static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
890 {
891 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
892
893 crBegin(ssh->ssh2_rdpkt_crstate);
894
895 next_packet:
896 ssh->pktin.type = 0;
897 ssh->pktin.length = 0;
898 if (ssh->sccipher)
899 st->cipherblk = ssh->sccipher->blksize;
900 else
901 st->cipherblk = 8;
902 if (st->cipherblk < 8)
903 st->cipherblk = 8;
904
905 if (ssh->pktin.maxlen < st->cipherblk) {
906 ssh->pktin.maxlen = st->cipherblk;
907 ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
908 }
909
910 /*
911 * Acquire and decrypt the first block of the packet. This will
912 * contain the length and padding details.
913 */
914 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
915 while ((*datalen) == 0)
916 crReturn(st->cipherblk - st->i);
917 ssh->pktin.data[st->i] = *(*data)++;
918 (*datalen)--;
919 }
920
921 if (ssh->sccipher)
922 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
923 ssh->pktin.data, st->cipherblk);
924
925 /*
926 * Now get the length and padding figures.
927 */
928 st->len = GET_32BIT(ssh->pktin.data);
929 st->pad = ssh->pktin.data[4];
930
931 /*
932 * _Completely_ silly lengths should be stomped on before they
933 * do us any more damage.
934 */
935 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
936 bombout(("Incoming packet was garbled on decryption"));
937 crReturn(0);
938 }
939
940 /*
941 * This enables us to deduce the payload length.
942 */
943 st->payload = st->len - st->pad - 1;
944
945 ssh->pktin.length = st->payload + 5;
946
947 /*
948 * So now we can work out the total packet length.
949 */
950 st->packetlen = st->len + 4;
951 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
952
953 /*
954 * Adjust memory allocation if packet is too big.
955 */
956 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
957 ssh->pktin.maxlen = st->packetlen + st->maclen;
958 ssh->pktin.data = srealloc(ssh->pktin.data,
959 ssh->pktin.maxlen + APIEXTRA);
960 }
961
962 /*
963 * Read and decrypt the remainder of the packet.
964 */
965 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
966 st->i++) {
967 while ((*datalen) == 0)
968 crReturn(st->packetlen + st->maclen - st->i);
969 ssh->pktin.data[st->i] = *(*data)++;
970 (*datalen)--;
971 }
972 /* Decrypt everything _except_ the MAC. */
973 if (ssh->sccipher)
974 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
975 ssh->pktin.data + st->cipherblk,
976 st->packetlen - st->cipherblk);
977
978 /*
979 * Check the MAC.
980 */
981 if (ssh->scmac
982 && !ssh->scmac->verify(ssh->pktin.data, st->len + 4,
983 st->incoming_sequence)) {
984 bombout(("Incorrect MAC received on packet"));
985 crReturn(0);
986 }
987 st->incoming_sequence++; /* whether or not we MACed */
988
989 /*
990 * Decompress packet payload.
991 */
992 {
993 unsigned char *newpayload;
994 int newlen;
995 if (ssh->sccomp &&
996 ssh->sccomp->decompress(ssh->pktin.data + 5, ssh->pktin.length - 5,
997 &newpayload, &newlen)) {
998 if (ssh->pktin.maxlen < newlen + 5) {
999 ssh->pktin.maxlen = newlen + 5;
1000 ssh->pktin.data = srealloc(ssh->pktin.data,
1001 ssh->pktin.maxlen + APIEXTRA);
1002 }
1003 ssh->pktin.length = 5 + newlen;
1004 memcpy(ssh->pktin.data + 5, newpayload, newlen);
1005 sfree(newpayload);
1006 }
1007 }
1008
1009 ssh->pktin.savedpos = 6;
1010 ssh->pktin.type = ssh->pktin.data[5];
1011
1012 log_packet(PKT_INCOMING, ssh->pktin.type,
1013 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1014 ssh->pktin.data+6, ssh->pktin.length-6);
1015
1016 switch (ssh->pktin.type) {
1017 /*
1018 * These packets we must handle instantly.
1019 */
1020 case SSH2_MSG_DISCONNECT:
1021 {
1022 /* log reason code in disconnect message */
1023 char buf[256];
1024 int reason = GET_32BIT(ssh->pktin.data + 6);
1025 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
1026 unsigned nowlen;
1027 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1028 sprintf(buf, "Received disconnect message (%s)",
1029 ssh2_disconnect_reasons[reason]);
1030 } else {
1031 sprintf(buf, "Received disconnect message (unknown type %d)",
1032 reason);
1033 }
1034 logevent(buf);
1035 strcpy(buf, "Disconnection message text: ");
1036 nowlen = strlen(buf);
1037 if (msglen > sizeof(buf) - nowlen - 1)
1038 msglen = sizeof(buf) - nowlen - 1;
1039 memcpy(buf + nowlen, ssh->pktin.data + 14, msglen);
1040 buf[nowlen + msglen] = '\0';
1041 logevent(buf);
1042 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1043 reason,
1044 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1045 ssh2_disconnect_reasons[reason] : "unknown",
1046 buf+nowlen));
1047 crReturn(0);
1048 }
1049 break;
1050 case SSH2_MSG_IGNORE:
1051 goto next_packet;
1052 case SSH2_MSG_DEBUG:
1053 {
1054 /* log the debug message */
1055 char buf[512];
1056 /* int display = ssh->pktin.body[6]; */
1057 int stringlen = GET_32BIT(ssh->pktin.data+7);
1058 int prefix;
1059 strcpy(buf, "Remote debug message: ");
1060 prefix = strlen(buf);
1061 if (stringlen > (int)(sizeof(buf)-prefix-1))
1062 stringlen = sizeof(buf)-prefix-1;
1063 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
1064 buf[prefix + stringlen] = '\0';
1065 logevent(buf);
1066 }
1067 goto next_packet; /* FIXME: print the debug message */
1068
1069 /*
1070 * These packets we need do nothing about here.
1071 */
1072 case SSH2_MSG_UNIMPLEMENTED:
1073 case SSH2_MSG_SERVICE_REQUEST:
1074 case SSH2_MSG_SERVICE_ACCEPT:
1075 case SSH2_MSG_KEXINIT:
1076 case SSH2_MSG_NEWKEYS:
1077 case SSH2_MSG_KEXDH_INIT:
1078 case SSH2_MSG_KEXDH_REPLY:
1079 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1080 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1081 case SSH2_MSG_KEX_DH_GEX_INIT:
1082 case SSH2_MSG_KEX_DH_GEX_REPLY:
1083 case SSH2_MSG_USERAUTH_REQUEST:
1084 case SSH2_MSG_USERAUTH_FAILURE:
1085 case SSH2_MSG_USERAUTH_SUCCESS:
1086 case SSH2_MSG_USERAUTH_BANNER:
1087 case SSH2_MSG_USERAUTH_PK_OK:
1088 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1089 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1090 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1091 case SSH2_MSG_GLOBAL_REQUEST:
1092 case SSH2_MSG_REQUEST_SUCCESS:
1093 case SSH2_MSG_REQUEST_FAILURE:
1094 case SSH2_MSG_CHANNEL_OPEN:
1095 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1096 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1097 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1098 case SSH2_MSG_CHANNEL_DATA:
1099 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1100 case SSH2_MSG_CHANNEL_EOF:
1101 case SSH2_MSG_CHANNEL_CLOSE:
1102 case SSH2_MSG_CHANNEL_REQUEST:
1103 case SSH2_MSG_CHANNEL_SUCCESS:
1104 case SSH2_MSG_CHANNEL_FAILURE:
1105 break;
1106
1107 /*
1108 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1109 */
1110 default:
1111 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1112 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1113 ssh2_pkt_send(ssh);
1114 break;
1115 }
1116
1117 crFinish(0);
1118 }
1119
1120 static void ssh1_pktout_size(Ssh ssh, int len)
1121 {
1122 int pad, biglen;
1123
1124 len += 5; /* type and CRC */
1125 pad = 8 - (len % 8);
1126 biglen = len + pad;
1127
1128 ssh->pktout.length = len - 5;
1129 if (ssh->pktout.maxlen < biglen) {
1130 ssh->pktout.maxlen = biglen;
1131 #ifdef MSCRYPTOAPI
1132 /* Allocate enough buffer space for extra block
1133 * for MS CryptEncrypt() */
1134 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
1135 #else
1136 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
1137 #endif
1138 }
1139 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
1140 }
1141
1142 static void s_wrpkt_start(Ssh ssh, int type, int len)
1143 {
1144 ssh1_pktout_size(ssh, len);
1145 ssh->pktout.type = type;
1146 }
1147
1148 static int s_wrpkt_prepare(Ssh ssh)
1149 {
1150 int pad, len, biglen, i;
1151 unsigned long crc;
1152
1153 ssh->pktout.body[-1] = ssh->pktout.type;
1154
1155 log_packet(PKT_OUTGOING, ssh->pktout.type, ssh1_pkt_type(ssh->pktout.type),
1156 ssh->pktout.body, ssh->pktout.length);
1157
1158 if (ssh->v1_compressing) {
1159 unsigned char *compblk;
1160 int complen;
1161 zlib_compress_block(ssh->pktout.body - 1, ssh->pktout.length + 1,
1162 &compblk, &complen);
1163 ssh1_pktout_size(ssh, complen - 1);
1164 memcpy(ssh->pktout.body - 1, compblk, complen);
1165 sfree(compblk);
1166 }
1167
1168 len = ssh->pktout.length + 5; /* type and CRC */
1169 pad = 8 - (len % 8);
1170 biglen = len + pad;
1171
1172 for (i = 0; i < pad; i++)
1173 ssh->pktout.data[i + 4] = random_byte();
1174 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1175 PUT_32BIT(ssh->pktout.data + biglen, crc);
1176 PUT_32BIT(ssh->pktout.data, len);
1177
1178 if (ssh->cipher)
1179 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
1180
1181 return biglen + 4;
1182 }
1183
1184 static void s_wrpkt(Ssh ssh)
1185 {
1186 int len, backlog;
1187 len = s_wrpkt_prepare(ssh);
1188 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1189 if (backlog > SSH_MAX_BACKLOG)
1190 ssh_throttle_all(ssh, 1, backlog);
1191 }
1192
1193 static void s_wrpkt_defer(Ssh ssh)
1194 {
1195 int len;
1196 len = s_wrpkt_prepare(ssh);
1197 if (ssh->deferred_len + len > ssh->deferred_size) {
1198 ssh->deferred_size = ssh->deferred_len + len + 128;
1199 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1200 ssh->deferred_size);
1201 }
1202 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1203 ssh->deferred_len += len;
1204 }
1205
1206 /*
1207 * Construct a packet with the specified contents.
1208 */
1209 static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
1210 {
1211 unsigned char *p, *argp, argchar;
1212 unsigned long argint;
1213 int pktlen, argtype, arglen;
1214 Bignum bn;
1215
1216 pktlen = 0;
1217 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1218 switch (argtype) {
1219 case PKT_INT:
1220 (void) va_arg(ap1, int);
1221 pktlen += 4;
1222 break;
1223 case PKT_CHAR:
1224 (void) va_arg(ap1, char);
1225 pktlen++;
1226 break;
1227 case PKT_DATA:
1228 (void) va_arg(ap1, unsigned char *);
1229 arglen = va_arg(ap1, int);
1230 pktlen += arglen;
1231 break;
1232 case PKT_STR:
1233 argp = va_arg(ap1, unsigned char *);
1234 arglen = strlen(argp);
1235 pktlen += 4 + arglen;
1236 break;
1237 case PKT_BIGNUM:
1238 bn = va_arg(ap1, Bignum);
1239 pktlen += ssh1_bignum_length(bn);
1240 break;
1241 default:
1242 assert(0);
1243 }
1244 }
1245
1246 s_wrpkt_start(ssh, pkttype, pktlen);
1247 p = ssh->pktout.body;
1248
1249 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1250 switch (argtype) {
1251 case PKT_INT:
1252 argint = va_arg(ap2, int);
1253 PUT_32BIT(p, argint);
1254 p += 4;
1255 break;
1256 case PKT_CHAR:
1257 argchar = va_arg(ap2, unsigned char);
1258 *p = argchar;
1259 p++;
1260 break;
1261 case PKT_DATA:
1262 argp = va_arg(ap2, unsigned char *);
1263 arglen = va_arg(ap2, int);
1264 memcpy(p, argp, arglen);
1265 p += arglen;
1266 break;
1267 case PKT_STR:
1268 argp = va_arg(ap2, unsigned char *);
1269 arglen = strlen(argp);
1270 PUT_32BIT(p, arglen);
1271 memcpy(p + 4, argp, arglen);
1272 p += 4 + arglen;
1273 break;
1274 case PKT_BIGNUM:
1275 bn = va_arg(ap2, Bignum);
1276 p += ssh1_write_bignum(p, bn);
1277 break;
1278 }
1279 }
1280 }
1281
1282 static void send_packet(Ssh ssh, int pkttype, ...)
1283 {
1284 va_list ap1, ap2;
1285 va_start(ap1, pkttype);
1286 va_start(ap2, pkttype);
1287 construct_packet(ssh, pkttype, ap1, ap2);
1288 s_wrpkt(ssh);
1289 }
1290
1291 static void defer_packet(Ssh ssh, int pkttype, ...)
1292 {
1293 va_list ap1, ap2;
1294 va_start(ap1, pkttype);
1295 va_start(ap2, pkttype);
1296 construct_packet(ssh, pkttype, ap1, ap2);
1297 s_wrpkt_defer(ssh);
1298 }
1299
1300 static int ssh_versioncmp(char *a, char *b)
1301 {
1302 char *ae, *be;
1303 unsigned long av, bv;
1304
1305 av = strtoul(a, &ae, 10);
1306 bv = strtoul(b, &be, 10);
1307 if (av != bv)
1308 return (av < bv ? -1 : +1);
1309 if (*ae == '.')
1310 ae++;
1311 if (*be == '.')
1312 be++;
1313 av = strtoul(ae, &ae, 10);
1314 bv = strtoul(be, &be, 10);
1315 if (av != bv)
1316 return (av < bv ? -1 : +1);
1317 return 0;
1318 }
1319
1320 /*
1321 * Utility routines for putting an SSH-protocol `string' and
1322 * `uint32' into a SHA state.
1323 */
1324 #include <stdio.h>
1325 static void sha_string(SHA_State * s, void *str, int len)
1326 {
1327 unsigned char lenblk[4];
1328 PUT_32BIT(lenblk, len);
1329 SHA_Bytes(s, lenblk, 4);
1330 SHA_Bytes(s, str, len);
1331 }
1332
1333 static void sha_uint32(SHA_State * s, unsigned i)
1334 {
1335 unsigned char intblk[4];
1336 PUT_32BIT(intblk, i);
1337 SHA_Bytes(s, intblk, 4);
1338 }
1339
1340 /*
1341 * SSH2 packet construction functions.
1342 */
1343 static void ssh2_pkt_ensure(Ssh ssh, int length)
1344 {
1345 if (ssh->pktout.maxlen < length) {
1346 ssh->pktout.maxlen = length + 256;
1347 ssh->pktout.data = srealloc(ssh->pktout.data,
1348 ssh->pktout.maxlen + APIEXTRA);
1349 if (!ssh->pktout.data)
1350 fatalbox("Out of memory");
1351 }
1352 }
1353 static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
1354 {
1355 ssh->pktout.length += len;
1356 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1357 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
1358 }
1359 static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
1360 {
1361 ssh2_pkt_adddata(ssh, &byte, 1);
1362 }
1363 static void ssh2_pkt_init(Ssh ssh, int pkt_type)
1364 {
1365 ssh->pktout.length = 5;
1366 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
1367 }
1368 static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
1369 {
1370 ssh2_pkt_adddata(ssh, &value, 1);
1371 }
1372 static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
1373 {
1374 unsigned char x[4];
1375 PUT_32BIT(x, value);
1376 ssh2_pkt_adddata(ssh, x, 4);
1377 }
1378 static void ssh2_pkt_addstring_start(Ssh ssh)
1379 {
1380 ssh2_pkt_adduint32(ssh, 0);
1381 ssh->pktout.savedpos = ssh->pktout.length;
1382 }
1383 static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
1384 {
1385 ssh2_pkt_adddata(ssh, data, strlen(data));
1386 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1387 ssh->pktout.length - ssh->pktout.savedpos);
1388 }
1389 static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
1390 {
1391 ssh2_pkt_adddata(ssh, data, len);
1392 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1393 ssh->pktout.length - ssh->pktout.savedpos);
1394 }
1395 static void ssh2_pkt_addstring(Ssh ssh, char *data)
1396 {
1397 ssh2_pkt_addstring_start(ssh);
1398 ssh2_pkt_addstring_str(ssh, data);
1399 }
1400 static char *ssh2_mpint_fmt(Bignum b, int *len)
1401 {
1402 unsigned char *p;
1403 int i, n = (bignum_bitcount(b) + 7) / 8;
1404 p = smalloc(n + 1);
1405 if (!p)
1406 fatalbox("out of memory");
1407 p[0] = 0;
1408 for (i = 1; i <= n; i++)
1409 p[i] = bignum_byte(b, n - i);
1410 i = 0;
1411 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1412 i++;
1413 memmove(p, p + i, n + 1 - i);
1414 *len = n + 1 - i;
1415 return p;
1416 }
1417 static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
1418 {
1419 unsigned char *p;
1420 int len;
1421 p = ssh2_mpint_fmt(b, &len);
1422 ssh2_pkt_addstring_start(ssh);
1423 ssh2_pkt_addstring_data(ssh, p, len);
1424 sfree(p);
1425 }
1426
1427 /*
1428 * Construct an SSH2 final-form packet: compress it, encrypt it,
1429 * put the MAC on it. Final packet, ready to be sent, is stored in
1430 * ssh->pktout.data. Total length is returned.
1431 */
1432 static int ssh2_pkt_construct(Ssh ssh)
1433 {
1434 int cipherblk, maclen, padding, i;
1435
1436 log_packet(PKT_OUTGOING, ssh->pktout.data[5],
1437 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1438 ssh->pktout.data + 6, ssh->pktout.length - 6);
1439
1440 /*
1441 * Compress packet payload.
1442 */
1443 {
1444 unsigned char *newpayload;
1445 int newlen;
1446 if (ssh->cscomp &&
1447 ssh->cscomp->compress(ssh->pktout.data + 5, ssh->pktout.length - 5,
1448 &newpayload, &newlen)) {
1449 ssh->pktout.length = 5;
1450 ssh2_pkt_adddata(ssh, newpayload, newlen);
1451 sfree(newpayload);
1452 }
1453 }
1454
1455 /*
1456 * Add padding. At least four bytes, and must also bring total
1457 * length (minus MAC) up to a multiple of the block size.
1458 */
1459 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1460 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1461 padding = 4;
1462 padding +=
1463 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1464 maclen = ssh->csmac ? ssh->csmac->len : 0;
1465 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1466 ssh->pktout.data[4] = padding;
1467 for (i = 0; i < padding; i++)
1468 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1469 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1470 if (ssh->csmac)
1471 ssh->csmac->generate(ssh->pktout.data, ssh->pktout.length + padding,
1472 ssh->v2_outgoing_sequence);
1473 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1474
1475 if (ssh->cscipher)
1476 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1477 ssh->pktout.data, ssh->pktout.length + padding);
1478
1479 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1480 return ssh->pktout.length + padding + maclen;
1481 }
1482
1483 /*
1484 * Construct and send an SSH2 packet immediately.
1485 */
1486 static void ssh2_pkt_send(Ssh ssh)
1487 {
1488 int len;
1489 int backlog;
1490 len = ssh2_pkt_construct(ssh);
1491 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1492 if (backlog > SSH_MAX_BACKLOG)
1493 ssh_throttle_all(ssh, 1, backlog);
1494 }
1495
1496 /*
1497 * Construct an SSH2 packet and add it to a deferred data block.
1498 * Useful for sending multiple packets in a single sk_write() call,
1499 * to prevent a traffic-analysing listener from being able to work
1500 * out the length of any particular packet (such as the password
1501 * packet).
1502 *
1503 * Note that because SSH2 sequence-numbers its packets, this can
1504 * NOT be used as an m4-style `defer' allowing packets to be
1505 * constructed in one order and sent in another.
1506 */
1507 static void ssh2_pkt_defer(Ssh ssh)
1508 {
1509 int len = ssh2_pkt_construct(ssh);
1510 if (ssh->deferred_len + len > ssh->deferred_size) {
1511 ssh->deferred_size = ssh->deferred_len + len + 128;
1512 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1513 ssh->deferred_size);
1514 }
1515 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1516 ssh->deferred_len += len;
1517 }
1518
1519 /*
1520 * Send the whole deferred data block constructed by
1521 * ssh2_pkt_defer() or SSH1's defer_packet().
1522 */
1523 static void ssh_pkt_defersend(Ssh ssh)
1524 {
1525 int backlog;
1526 backlog = sk_write(ssh->s, ssh->deferred_send_data, ssh->deferred_len);
1527 ssh->deferred_len = ssh->deferred_size = 0;
1528 sfree(ssh->deferred_send_data);
1529 ssh->deferred_send_data = NULL;
1530 if (backlog > SSH_MAX_BACKLOG)
1531 ssh_throttle_all(ssh, 1, backlog);
1532 }
1533
1534 #if 0
1535 void bndebug(char *string, Bignum b)
1536 {
1537 unsigned char *p;
1538 int i, len;
1539 p = ssh2_mpint_fmt(b, &len);
1540 debug(("%s", string));
1541 for (i = 0; i < len; i++)
1542 debug((" %02x", p[i]));
1543 debug(("\n"));
1544 sfree(p);
1545 }
1546 #endif
1547
1548 static void sha_mpint(SHA_State * s, Bignum b)
1549 {
1550 unsigned char *p;
1551 int len;
1552 p = ssh2_mpint_fmt(b, &len);
1553 sha_string(s, p, len);
1554 sfree(p);
1555 }
1556
1557 /*
1558 * SSH2 packet decode functions.
1559 */
1560 static unsigned long ssh2_pkt_getuint32(Ssh ssh)
1561 {
1562 unsigned long value;
1563 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1564 return 0; /* arrgh, no way to decline (FIXME?) */
1565 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1566 ssh->pktin.savedpos += 4;
1567 return value;
1568 }
1569 static int ssh2_pkt_getbool(Ssh ssh)
1570 {
1571 unsigned long value;
1572 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
1573 return 0; /* arrgh, no way to decline (FIXME?) */
1574 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1575 ssh->pktin.savedpos++;
1576 return value;
1577 }
1578 static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
1579 {
1580 *p = NULL;
1581 *length = 0;
1582 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1583 return;
1584 *length = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1585 ssh->pktin.savedpos += 4;
1586 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
1587 return;
1588 *p = ssh->pktin.data + ssh->pktin.savedpos;
1589 ssh->pktin.savedpos += *length;
1590 }
1591 static Bignum ssh2_pkt_getmp(Ssh ssh)
1592 {
1593 char *p;
1594 int length;
1595 Bignum b;
1596
1597 ssh2_pkt_getstring(ssh, &p, &length);
1598 if (!p)
1599 return NULL;
1600 if (p[0] & 0x80) {
1601 bombout(("internal error: Can't handle negative mpints"));
1602 return NULL;
1603 }
1604 b = bignum_from_bytes(p, length);
1605 return b;
1606 }
1607
1608 /*
1609 * Helper function to add an SSH2 signature blob to a packet.
1610 * Expects to be shown the public key blob as well as the signature
1611 * blob. Normally works just like ssh2_pkt_addstring, but will
1612 * fiddle with the signature packet if necessary for
1613 * BUG_SSH2_RSA_PADDING.
1614 */
1615 static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1616 void *sigblob_v, int sigblob_len)
1617 {
1618 unsigned char *pkblob = (unsigned char *)pkblob_v;
1619 unsigned char *sigblob = (unsigned char *)sigblob_v;
1620
1621 /* dmemdump(pkblob, pkblob_len); */
1622 /* dmemdump(sigblob, sigblob_len); */
1623
1624 /*
1625 * See if this is in fact an ssh-rsa signature and a buggy
1626 * server; otherwise we can just do this the easy way.
1627 */
1628 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1629 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1630 int pos, len, siglen;
1631
1632 /*
1633 * Find the byte length of the modulus.
1634 */
1635
1636 pos = 4+7; /* skip over "ssh-rsa" */
1637 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1638 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1639 pos += 4; /* find modulus itself */
1640 while (len > 0 && pkblob[pos] == 0)
1641 len--, pos++;
1642 /* debug(("modulus length is %d\n", len)); */
1643
1644 /*
1645 * Now find the signature integer.
1646 */
1647 pos = 4+7; /* skip over "ssh-rsa" */
1648 siglen = GET_32BIT(sigblob+pos);
1649 /* debug(("signature length is %d\n", siglen)); */
1650
1651 if (len != siglen) {
1652 unsigned char newlen[4];
1653 ssh2_pkt_addstring_start(ssh);
1654 ssh2_pkt_addstring_data(ssh, sigblob, pos);
1655 /* dmemdump(sigblob, pos); */
1656 pos += 4; /* point to start of actual sig */
1657 PUT_32BIT(newlen, len);
1658 ssh2_pkt_addstring_data(ssh, newlen, 4);
1659 /* dmemdump(newlen, 4); */
1660 newlen[0] = 0;
1661 while (len-- > siglen) {
1662 ssh2_pkt_addstring_data(ssh, newlen, 1);
1663 /* dmemdump(newlen, 1); */
1664 }
1665 ssh2_pkt_addstring_data(ssh, sigblob+pos, siglen);
1666 /* dmemdump(sigblob+pos, siglen); */
1667 return;
1668 }
1669
1670 /* Otherwise fall through and do it the easy way. */
1671 }
1672
1673 ssh2_pkt_addstring_start(ssh);
1674 ssh2_pkt_addstring_data(ssh, sigblob, sigblob_len);
1675 }
1676
1677 /*
1678 * Examine the remote side's version string and compare it against
1679 * a list of known buggy implementations.
1680 */
1681 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1682 {
1683 char *imp; /* pointer to implementation part */
1684 imp = vstring;
1685 imp += strcspn(imp, "-");
1686 if (*imp) imp++;
1687 imp += strcspn(imp, "-");
1688 if (*imp) imp++;
1689
1690 ssh->remote_bugs = 0;
1691
1692 if (cfg.sshbug_ignore1 == BUG_ON ||
1693 (cfg.sshbug_ignore1 == BUG_AUTO &&
1694 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1695 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1696 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1697 /*
1698 * These versions don't support SSH1_MSG_IGNORE, so we have
1699 * to use a different defence against password length
1700 * sniffing.
1701 */
1702 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1703 logevent("We believe remote version has SSH1 ignore bug");
1704 }
1705
1706 if (cfg.sshbug_plainpw1 == BUG_ON ||
1707 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1708 (!strcmp(imp, "Cisco-1.25")))) {
1709 /*
1710 * These versions need a plain password sent; they can't
1711 * handle having a null and a random length of data after
1712 * the password.
1713 */
1714 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1715 logevent("We believe remote version needs a plain SSH1 password");
1716 }
1717
1718 if (cfg.sshbug_rsa1 == BUG_ON ||
1719 (cfg.sshbug_rsa1 == BUG_AUTO &&
1720 (!strcmp(imp, "Cisco-1.25")))) {
1721 /*
1722 * These versions apparently have no clue whatever about
1723 * RSA authentication and will panic and die if they see
1724 * an AUTH_RSA message.
1725 */
1726 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
1727 logevent("We believe remote version can't handle RSA authentication");
1728 }
1729
1730 if (cfg.sshbug_hmac2 == BUG_ON ||
1731 (cfg.sshbug_hmac2 == BUG_AUTO &&
1732 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1733 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1734 !strncmp(imp, "2.1 ", 4)))) {
1735 /*
1736 * These versions have the HMAC bug.
1737 */
1738 ssh->remote_bugs |= BUG_SSH2_HMAC;
1739 logevent("We believe remote version has SSH2 HMAC bug");
1740 }
1741
1742 if (cfg.sshbug_derivekey2 == BUG_ON ||
1743 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1744 (!strncmp(imp, "2.0.", 4)))) {
1745 /*
1746 * These versions have the key-derivation bug (failing to
1747 * include the literal shared secret in the hashes that
1748 * generate the keys).
1749 */
1750 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
1751 logevent("We believe remote version has SSH2 key-derivation bug");
1752 }
1753
1754 if (cfg.sshbug_rsapad2 == BUG_ON ||
1755 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1756 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1757 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1758 /*
1759 * These versions have the SSH2 RSA padding bug.
1760 */
1761 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1762 logevent("We believe remote version has SSH2 RSA padding bug");
1763 }
1764
1765 if (cfg.sshbug_dhgex2 == BUG_ON) {
1766 /*
1767 * These versions have the SSH2 DH GEX bug.
1768 */
1769 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
1770 logevent("We believe remote version has SSH2 DH group exchange bug");
1771 }
1772 }
1773
1774 static int do_ssh_init(Ssh ssh, unsigned char c)
1775 {
1776 struct do_ssh_init_state {
1777 int vslen;
1778 char version[10];
1779 char *vstring;
1780 int vstrsize;
1781 int i;
1782 int proto1, proto2;
1783 };
1784 crState(do_ssh_init_state);
1785
1786 crBegin(ssh->do_ssh_init_crstate);
1787
1788 /* Search for the string "SSH-" in the input. */
1789 s->i = 0;
1790 while (1) {
1791 static const int transS[] = { 1, 2, 2, 1 };
1792 static const int transH[] = { 0, 0, 3, 0 };
1793 static const int transminus[] = { 0, 0, 0, -1 };
1794 if (c == 'S')
1795 s->i = transS[s->i];
1796 else if (c == 'H')
1797 s->i = transH[s->i];
1798 else if (c == '-')
1799 s->i = transminus[s->i];
1800 else
1801 s->i = 0;
1802 if (s->i < 0)
1803 break;
1804 crReturn(1); /* get another character */
1805 }
1806
1807 s->vstrsize = 16;
1808 s->vstring = smalloc(s->vstrsize);
1809 strcpy(s->vstring, "SSH-");
1810 s->vslen = 4;
1811 s->i = 0;
1812 while (1) {
1813 crReturn(1); /* get another char */
1814 if (s->vslen >= s->vstrsize - 1) {
1815 s->vstrsize += 16;
1816 s->vstring = srealloc(s->vstring, s->vstrsize);
1817 }
1818 s->vstring[s->vslen++] = c;
1819 if (s->i >= 0) {
1820 if (c == '-') {
1821 s->version[s->i] = '\0';
1822 s->i = -1;
1823 } else if (s->i < sizeof(s->version) - 1)
1824 s->version[s->i++] = c;
1825 } else if (c == '\n')
1826 break;
1827 }
1828
1829 ssh->agentfwd_enabled = FALSE;
1830 ssh->rdpkt2_state.incoming_sequence = 0;
1831
1832 s->vstring[s->vslen] = 0;
1833 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1834 {
1835 char *vlog;
1836 vlog = smalloc(20 + s->vslen);
1837 sprintf(vlog, "Server version: %s", s->vstring);
1838 logevent(vlog);
1839 sfree(vlog);
1840 }
1841 ssh_detect_bugs(ssh, s->vstring);
1842
1843 /*
1844 * Decide which SSH protocol version to support.
1845 */
1846
1847 /* Anything strictly below "2.0" means protocol 1 is supported. */
1848 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
1849 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1850 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
1851
1852 if (cfg.sshprot == 0 && !s->proto1) {
1853 bombout(("SSH protocol version 1 required by user but not provided by server"));
1854 crReturn(0);
1855 }
1856 if (cfg.sshprot == 3 && !s->proto2) {
1857 bombout(("SSH protocol version 2 required by user but not provided by server"));
1858 crReturn(0);
1859 }
1860
1861 if (s->proto2 && (cfg.sshprot >= 2 || !s->proto1)) {
1862 /*
1863 * Use v2 protocol.
1864 */
1865 char verstring[80], vlog[100];
1866 sprintf(verstring, "SSH-2.0-%s", sshver);
1867 SHA_Init(&ssh->exhashbase);
1868 /*
1869 * Hash our version string and their version string.
1870 */
1871 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1872 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
1873 sprintf(vlog, "We claim version: %s", verstring);
1874 logevent(vlog);
1875 strcat(verstring, "\n");
1876 logevent("Using SSH protocol version 2");
1877 sk_write(ssh->s, verstring, strlen(verstring));
1878 ssh->protocol = ssh2_protocol;
1879 ssh->version = 2;
1880 ssh->s_rdpkt = ssh2_rdpkt;
1881 } else {
1882 /*
1883 * Use v1 protocol.
1884 */
1885 char verstring[80], vlog[100];
1886 sprintf(verstring, "SSH-%s-%s",
1887 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
1888 sshver);
1889 sprintf(vlog, "We claim version: %s", verstring);
1890 logevent(vlog);
1891 strcat(verstring, "\n");
1892
1893 logevent("Using SSH protocol version 1");
1894 sk_write(ssh->s, verstring, strlen(verstring));
1895 ssh->protocol = ssh1_protocol;
1896 ssh->version = 1;
1897 ssh->s_rdpkt = ssh1_rdpkt;
1898 }
1899 ssh->state = SSH_STATE_BEFORE_SIZE;
1900
1901 sfree(s->vstring);
1902
1903 crFinish(0);
1904 }
1905
1906 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
1907 {
1908 crBegin(ssh->ssh_gotdata_crstate);
1909
1910 /*
1911 * To begin with, feed the characters one by one to the
1912 * protocol initialisation / selection function do_ssh_init().
1913 * When that returns 0, we're done with the initial greeting
1914 * exchange and can move on to packet discipline.
1915 */
1916 while (1) {
1917 int ret; /* need not be kept across crReturn */
1918 if (datalen == 0)
1919 crReturnV; /* more data please */
1920 ret = do_ssh_init(ssh, *data);
1921 data++;
1922 datalen--;
1923 if (ret == 0)
1924 break;
1925 }
1926
1927 /*
1928 * We emerge from that loop when the initial negotiation is
1929 * over and we have selected an s_rdpkt function. Now pass
1930 * everything to s_rdpkt, and then pass the resulting packets
1931 * to the proper protocol handler.
1932 */
1933 if (datalen == 0)
1934 crReturnV;
1935 while (1) {
1936 while (datalen > 0) {
1937 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
1938 if (ssh->state == SSH_STATE_CLOSED) {
1939 return;
1940 }
1941 ssh->protocol(ssh, NULL, 0, 1);
1942 if (ssh->state == SSH_STATE_CLOSED) {
1943 return;
1944 }
1945 }
1946 }
1947 crReturnV;
1948 }
1949 crFinishV;
1950 }
1951
1952 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1953 int calling_back)
1954 {
1955 Ssh ssh = (Ssh) plug;
1956 ssh->state = SSH_STATE_CLOSED;
1957 if (ssh->s) {
1958 sk_close(ssh->s);
1959 ssh->s = NULL;
1960 }
1961 if (error_msg) {
1962 /* A socket error has occurred. */
1963 logevent(error_msg);
1964 connection_fatal(error_msg);
1965 } else {
1966 /* Otherwise, the remote side closed the connection normally. */
1967 }
1968 return 0;
1969 }
1970
1971 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1972 {
1973 Ssh ssh = (Ssh) plug;
1974 ssh_gotdata(ssh, data, len);
1975 if (ssh->state == SSH_STATE_CLOSED) {
1976 if (ssh->s) {
1977 sk_close(ssh->s);
1978 ssh->s = NULL;
1979 }
1980 return 0;
1981 }
1982 return 1;
1983 }
1984
1985 static void ssh_sent(Plug plug, int bufsize)
1986 {
1987 Ssh ssh = (Ssh) plug;
1988 /*
1989 * If the send backlog on the SSH socket itself clears, we
1990 * should unthrottle the whole world if it was throttled.
1991 */
1992 if (bufsize < SSH_MAX_BACKLOG)
1993 ssh_throttle_all(ssh, 0, bufsize);
1994 }
1995
1996 /*
1997 * Connect to specified host and port.
1998 * Returns an error message, or NULL on success.
1999 * Also places the canonical host name into `realhost'. It must be
2000 * freed by the caller.
2001 */
2002 static char *connect_to_host(Ssh ssh, char *host, int port,
2003 char **realhost, int nodelay)
2004 {
2005 static const struct plug_function_table fn_table = {
2006 ssh_closing,
2007 ssh_receive,
2008 ssh_sent,
2009 NULL
2010 };
2011
2012 SockAddr addr;
2013 char *err;
2014
2015 ssh->savedhost = smalloc(1 + strlen(host));
2016 if (!ssh->savedhost)
2017 fatalbox("Out of memory");
2018 strcpy(ssh->savedhost, host);
2019
2020 if (port < 0)
2021 port = 22; /* default ssh port */
2022 ssh->savedport = port;
2023
2024 /*
2025 * Try to find host.
2026 */
2027 {
2028 char buf[200];
2029 sprintf(buf, "Looking up host \"%.170s\"", host);
2030 logevent(buf);
2031 }
2032 addr = sk_namelookup(host, realhost);
2033 if ((err = sk_addr_error(addr)))
2034 return err;
2035
2036 /*
2037 * Open socket.
2038 */
2039 {
2040 char buf[200], addrbuf[100];
2041 sk_getaddr(addr, addrbuf, 100);
2042 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2043 logevent(buf);
2044 }
2045 ssh->fn = &fn_table;
2046 ssh->s = new_connection(addr, *realhost, port, 0, 1, nodelay, (Plug) ssh);
2047 if ((err = sk_socket_error(ssh->s))) {
2048 ssh->s = NULL;
2049 return err;
2050 }
2051
2052 return NULL;
2053 }
2054
2055 /*
2056 * Throttle or unthrottle the SSH connection.
2057 */
2058 static void ssh1_throttle(Ssh ssh, int adjust)
2059 {
2060 int old_count = ssh->v1_throttle_count;
2061 ssh->v1_throttle_count += adjust;
2062 assert(ssh->v1_throttle_count >= 0);
2063 if (ssh->v1_throttle_count && !old_count) {
2064 sk_set_frozen(ssh->s, 1);
2065 } else if (!ssh->v1_throttle_count && old_count) {
2066 sk_set_frozen(ssh->s, 0);
2067 }
2068 }
2069
2070 /*
2071 * Throttle or unthrottle _all_ local data streams (for when sends
2072 * on the SSH connection itself back up).
2073 */
2074 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2075 {
2076 int i;
2077 struct ssh_channel *c;
2078
2079 if (enable == ssh->throttled_all)
2080 return;
2081 ssh->throttled_all = enable;
2082 ssh->overall_bufsize = bufsize;
2083 if (!ssh->channels)
2084 return;
2085 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2086 switch (c->type) {
2087 case CHAN_MAINSESSION:
2088 /*
2089 * This is treated separately, outside the switch.
2090 */
2091 break;
2092 case CHAN_X11:
2093 x11_override_throttle(c->u.x11.s, enable);
2094 break;
2095 case CHAN_AGENT:
2096 /* Agent channels require no buffer management. */
2097 break;
2098 case CHAN_SOCKDATA:
2099 pfd_override_throttle(c->u.x11.s, enable);
2100 break;
2101 }
2102 }
2103 }
2104
2105 /*
2106 * Username and password input, abstracted off into routines
2107 * reusable in several places - even between SSH1 and SSH2.
2108 */
2109
2110 /* Set up a username or password input loop on a given buffer. */
2111 void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2112 {
2113 ssh->userpass_input_buffer = buffer;
2114 ssh->userpass_input_buflen = buflen;
2115 ssh->userpass_input_bufpos = 0;
2116 ssh->userpass_input_echo = echo;
2117 }
2118
2119 /*
2120 * Process some terminal data in the course of username/password
2121 * input. Returns >0 for success (line of input returned in
2122 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2123 * for inconclusive (keep waiting for more input please).
2124 */
2125 int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2126 {
2127 char c;
2128
2129 while (inlen--) {
2130 switch (c = *in++) {
2131 case 10:
2132 case 13:
2133 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2134 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2135 return +1;
2136 break;
2137 case 8:
2138 case 127:
2139 if (ssh->userpass_input_bufpos > 0) {
2140 if (ssh->userpass_input_echo)
2141 c_write_str(ssh, "\b \b");
2142 ssh->userpass_input_bufpos--;
2143 }
2144 break;
2145 case 21:
2146 case 27:
2147 while (ssh->userpass_input_bufpos > 0) {
2148 if (ssh->userpass_input_echo)
2149 c_write_str(ssh, "\b \b");
2150 ssh->userpass_input_bufpos--;
2151 }
2152 break;
2153 case 3:
2154 case 4:
2155 return -1;
2156 break;
2157 default:
2158 if (((c >= ' ' && c <= '~') ||
2159 ((unsigned char) c >= 160))
2160 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2161 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2162 if (ssh->userpass_input_echo)
2163 c_write(ssh, &c, 1);
2164 }
2165 break;
2166 }
2167 }
2168 return 0;
2169 }
2170
2171 /*
2172 * Handle the key exchange and user authentication phases.
2173 */
2174 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2175 {
2176 int i, j;
2177 unsigned char cookie[8];
2178 struct RSAKey servkey, hostkey;
2179 struct MD5Context md5c;
2180 struct do_ssh1_login_state {
2181 int len;
2182 unsigned char *rsabuf, *keystr1, *keystr2;
2183 unsigned long supported_ciphers_mask, supported_auths_mask;
2184 int tried_publickey, tried_agent;
2185 int tis_auth_refused, ccard_auth_refused;
2186 unsigned char session_id[16];
2187 int cipher_type;
2188 char username[100];
2189 void *publickey_blob;
2190 int publickey_bloblen;
2191 char password[100];
2192 char prompt[200];
2193 int pos;
2194 char c;
2195 int pwpkt_type;
2196 unsigned char request[5], *response, *p;
2197 int responselen;
2198 int keyi, nkeys;
2199 int authed;
2200 struct RSAKey key;
2201 Bignum challenge;
2202 char *commentp;
2203 int commentlen;
2204 };
2205 crState(do_ssh1_login_state);
2206
2207 crBegin(ssh->do_ssh1_login_crstate);
2208
2209 if (!ispkt)
2210 crWaitUntil(ispkt);
2211
2212 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2213 bombout(("Public key packet not received"));
2214 crReturn(0);
2215 }
2216
2217 logevent("Received public keys");
2218
2219 memcpy(cookie, ssh->pktin.body, 8);
2220
2221 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2222 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
2223
2224 /*
2225 * Log the host key fingerprint.
2226 */
2227 {
2228 char logmsg[80];
2229 logevent("Host key fingerprint is:");
2230 strcpy(logmsg, " ");
2231 hostkey.comment = NULL;
2232 rsa_fingerprint(logmsg + strlen(logmsg),
2233 sizeof(logmsg) - strlen(logmsg), &hostkey);
2234 logevent(logmsg);
2235 }
2236
2237 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2238 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2239 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
2240
2241 ssh->v1_local_protoflags =
2242 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2243 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2244
2245 MD5Init(&md5c);
2246 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2247 MD5Update(&md5c, s->keystr1, servkey.bytes);
2248 MD5Update(&md5c, ssh->pktin.body, 8);
2249 MD5Final(s->session_id, &md5c);
2250
2251 for (i = 0; i < 32; i++)
2252 ssh->session_key[i] = random_byte();
2253
2254 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2255
2256 s->rsabuf = smalloc(s->len);
2257 if (!s->rsabuf)
2258 fatalbox("Out of memory");
2259
2260 /*
2261 * Verify the host key.
2262 */
2263 {
2264 /*
2265 * First format the key into a string.
2266 */
2267 int len = rsastr_len(&hostkey);
2268 char fingerprint[100];
2269 char *keystr = smalloc(len);
2270 if (!keystr)
2271 fatalbox("Out of memory");
2272 rsastr_fmt(keystr, &hostkey);
2273 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2274 verify_ssh_host_key(ssh->savedhost, ssh->savedport, "rsa", keystr,
2275 fingerprint);
2276 sfree(keystr);
2277 }
2278
2279 for (i = 0; i < 32; i++) {
2280 s->rsabuf[i] = ssh->session_key[i];
2281 if (i < 16)
2282 s->rsabuf[i] ^= s->session_id[i];
2283 }
2284
2285 if (hostkey.bytes > servkey.bytes) {
2286 rsaencrypt(s->rsabuf, 32, &servkey);
2287 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2288 } else {
2289 rsaencrypt(s->rsabuf, 32, &hostkey);
2290 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2291 }
2292
2293 logevent("Encrypted session key");
2294
2295 {
2296 int cipher_chosen = 0, warn = 0;
2297 char *cipher_string = NULL;
2298 int i;
2299 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2300 int next_cipher = cfg.ssh_cipherlist[i];
2301 if (next_cipher == CIPHER_WARN) {
2302 /* If/when we choose a cipher, warn about it */
2303 warn = 1;
2304 } else if (next_cipher == CIPHER_AES) {
2305 /* XXX Probably don't need to mention this. */
2306 logevent("AES not supported in SSH1, skipping");
2307 } else {
2308 switch (next_cipher) {
2309 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2310 cipher_string = "3DES"; break;
2311 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2312 cipher_string = "Blowfish"; break;
2313 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2314 cipher_string = "single-DES"; break;
2315 }
2316 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2317 cipher_chosen = 1;
2318 }
2319 }
2320 if (!cipher_chosen) {
2321 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2322 bombout(("Server violates SSH 1 protocol by not "
2323 "supporting 3DES encryption"));
2324 else
2325 /* shouldn't happen */
2326 bombout(("No supported ciphers found"));
2327 crReturn(0);
2328 }
2329
2330 /* Warn about chosen cipher if necessary. */
2331 if (warn)
2332 askcipher(cipher_string, 0);
2333 }
2334
2335 switch (s->cipher_type) {
2336 case SSH_CIPHER_3DES:
2337 logevent("Using 3DES encryption");
2338 break;
2339 case SSH_CIPHER_DES:
2340 logevent("Using single-DES encryption");
2341 break;
2342 case SSH_CIPHER_BLOWFISH:
2343 logevent("Using Blowfish encryption");
2344 break;
2345 }
2346
2347 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2348 PKT_CHAR, s->cipher_type,
2349 PKT_DATA, cookie, 8,
2350 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2351 PKT_DATA, s->rsabuf, s->len,
2352 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2353
2354 logevent("Trying to enable encryption...");
2355
2356 sfree(s->rsabuf);
2357
2358 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2359 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2360 &ssh_3des);
2361 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2362 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2363 {
2364 char buf[256];
2365 sprintf(buf, "Initialised %.200s encryption", ssh->cipher->text_name);
2366 logevent(buf);
2367 }
2368
2369 crWaitUntil(ispkt);
2370
2371 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2372 bombout(("Encryption not successfully enabled"));
2373 crReturn(0);
2374 }
2375
2376 logevent("Successfully started encryption");
2377
2378 fflush(stdout);
2379 {
2380 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2381 if (ssh_get_line && !ssh_getline_pw_only) {
2382 if (!ssh_get_line("login as: ",
2383 s->username, sizeof(s->username), FALSE)) {
2384 /*
2385 * get_line failed to get a username.
2386 * Terminate.
2387 */
2388 logevent("No username provided. Abandoning session.");
2389 ssh->state = SSH_STATE_CLOSED;
2390 crReturn(1);
2391 }
2392 } else {
2393 int ret; /* need not be kept over crReturn */
2394 c_write_str(ssh, "login as: ");
2395 ssh->send_ok = 1;
2396
2397 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2398 do {
2399 crWaitUntil(!ispkt);
2400 ret = process_userpass_input(ssh, in, inlen);
2401 } while (ret == 0);
2402 if (ret < 0)
2403 cleanup_exit(0);
2404 c_write_str(ssh, "\r\n");
2405 }
2406 } else {
2407 strncpy(s->username, cfg.username, sizeof(s->username));
2408 s->username[sizeof(s->username)-1] = '\0';
2409 }
2410
2411 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2412 {
2413 char userlog[22 + sizeof(s->username)];
2414 sprintf(userlog, "Sent username \"%s\"", s->username);
2415 logevent(userlog);
2416 if (flags & FLAG_INTERACTIVE &&
2417 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2418 strcat(userlog, "\r\n");
2419 c_write_str(ssh, userlog);
2420 }
2421 }
2422 }
2423
2424 crWaitUntil(ispkt);
2425
2426 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2427 /* We must not attempt PK auth. Pretend we've already tried it. */
2428 s->tried_publickey = s->tried_agent = 1;
2429 } else {
2430 s->tried_publickey = s->tried_agent = 0;
2431 }
2432 s->tis_auth_refused = s->ccard_auth_refused = 0;
2433 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2434 if (*cfg.keyfile) {
2435 if (!rsakey_pubblob(cfg.keyfile,
2436 &s->publickey_blob, &s->publickey_bloblen))
2437 s->publickey_blob = NULL;
2438 } else
2439 s->publickey_blob = NULL;
2440
2441 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2442 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2443
2444 if (agent_exists() && !s->tried_agent) {
2445 /*
2446 * Attempt RSA authentication using Pageant.
2447 */
2448 void *r;
2449
2450 s->authed = FALSE;
2451 s->tried_agent = 1;
2452 logevent("Pageant is running. Requesting keys.");
2453
2454 /* Request the keys held by the agent. */
2455 PUT_32BIT(s->request, 1);
2456 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2457 agent_query(s->request, 5, &r, &s->responselen);
2458 s->response = (unsigned char *) r;
2459 if (s->response && s->responselen >= 5 &&
2460 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2461 s->p = s->response + 5;
2462 s->nkeys = GET_32BIT(s->p);
2463 s->p += 4;
2464 {
2465 char buf[64];
2466 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2467 logevent(buf);
2468 }
2469 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2470 {
2471 char buf[64];
2472 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2473 logevent(buf);
2474 }
2475 if (s->publickey_blob &&
2476 !memcmp(s->p, s->publickey_blob,
2477 s->publickey_bloblen)) {
2478 logevent("This key matches configured key file");
2479 s->tried_publickey = 1;
2480 }
2481 s->p += 4;
2482 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2483 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2484 s->commentlen = GET_32BIT(s->p);
2485 s->p += 4;
2486 s->commentp = s->p;
2487 s->p += s->commentlen;
2488 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2489 PKT_BIGNUM, s->key.modulus, PKT_END);
2490 crWaitUntil(ispkt);
2491 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2492 logevent("Key refused");
2493 continue;
2494 }
2495 logevent("Received RSA challenge");
2496 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
2497 {
2498 char *agentreq, *q, *ret;
2499 void *vret;
2500 int len, retlen;
2501 len = 1 + 4; /* message type, bit count */
2502 len += ssh1_bignum_length(s->key.exponent);
2503 len += ssh1_bignum_length(s->key.modulus);
2504 len += ssh1_bignum_length(s->challenge);
2505 len += 16; /* session id */
2506 len += 4; /* response format */
2507 agentreq = smalloc(4 + len);
2508 PUT_32BIT(agentreq, len);
2509 q = agentreq + 4;
2510 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2511 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2512 q += 4;
2513 q += ssh1_write_bignum(q, s->key.exponent);
2514 q += ssh1_write_bignum(q, s->key.modulus);
2515 q += ssh1_write_bignum(q, s->challenge);
2516 memcpy(q, s->session_id, 16);
2517 q += 16;
2518 PUT_32BIT(q, 1); /* response format */
2519 agent_query(agentreq, len + 4, &vret, &retlen);
2520 ret = vret;
2521 sfree(agentreq);
2522 if (ret) {
2523 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2524 logevent("Sending Pageant's response");
2525 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2526 PKT_DATA, ret + 5, 16,
2527 PKT_END);
2528 sfree(ret);
2529 crWaitUntil(ispkt);
2530 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
2531 logevent
2532 ("Pageant's response accepted");
2533 if (flags & FLAG_VERBOSE) {
2534 c_write_str(ssh, "Authenticated using"
2535 " RSA key \"");
2536 c_write(ssh, s->commentp,
2537 s->commentlen);
2538 c_write_str(ssh, "\" from agent\r\n");
2539 }
2540 s->authed = TRUE;
2541 } else
2542 logevent
2543 ("Pageant's response not accepted");
2544 } else {
2545 logevent
2546 ("Pageant failed to answer challenge");
2547 sfree(ret);
2548 }
2549 } else {
2550 logevent("No reply received from Pageant");
2551 }
2552 }
2553 freebn(s->key.exponent);
2554 freebn(s->key.modulus);
2555 freebn(s->challenge);
2556 if (s->authed)
2557 break;
2558 }
2559 }
2560 if (s->authed)
2561 break;
2562 }
2563 if (*cfg.keyfile && !s->tried_publickey)
2564 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
2565
2566 if (cfg.try_tis_auth &&
2567 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2568 !s->tis_auth_refused) {
2569 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2570 logevent("Requested TIS authentication");
2571 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
2572 crWaitUntil(ispkt);
2573 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2574 logevent("TIS authentication declined");
2575 if (flags & FLAG_INTERACTIVE)
2576 c_write_str(ssh, "TIS authentication refused.\r\n");
2577 s->tis_auth_refused = 1;
2578 continue;
2579 } else {
2580 int challengelen = GET_32BIT(ssh->pktin.body);
2581 logevent("Received TIS challenge");
2582 if (challengelen > sizeof(s->prompt) - 1)
2583 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2584 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2585 /* Prompt heuristic comes from OpenSSH */
2586 strncpy(s->prompt + challengelen,
2587 memchr(s->prompt, '\n', challengelen) ?
2588 "": "\r\nResponse: ",
2589 (sizeof s->prompt) - challengelen);
2590 s->prompt[(sizeof s->prompt) - 1] = '\0';
2591 }
2592 }
2593 if (cfg.try_tis_auth &&
2594 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2595 !s->ccard_auth_refused) {
2596 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2597 logevent("Requested CryptoCard authentication");
2598 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
2599 crWaitUntil(ispkt);
2600 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2601 logevent("CryptoCard authentication declined");
2602 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2603 s->ccard_auth_refused = 1;
2604 continue;
2605 } else {
2606 int challengelen = GET_32BIT(ssh->pktin.body);
2607 logevent("Received CryptoCard challenge");
2608 if (challengelen > sizeof(s->prompt) - 1)
2609 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2610 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2611 strncpy(s->prompt + challengelen,
2612 memchr(s->prompt, '\n', challengelen) ?
2613 "" : "\r\nResponse: ",
2614 sizeof(s->prompt) - challengelen);
2615 s->prompt[sizeof(s->prompt) - 1] = '\0';
2616 }
2617 }
2618 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2619 sprintf(s->prompt, "%.90s@%.90s's password: ",
2620 s->username, ssh->savedhost);
2621 }
2622 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2623 char *comment = NULL;
2624 int type;
2625 char msgbuf[256];
2626 if (flags & FLAG_VERBOSE)
2627 c_write_str(ssh, "Trying public key authentication.\r\n");
2628 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2629 logevent(msgbuf);
2630 type = key_type(cfg.keyfile);
2631 if (type != SSH_KEYTYPE_SSH1) {
2632 sprintf(msgbuf, "Key is of wrong type (%s)",
2633 key_type_to_str(type));
2634 logevent(msgbuf);
2635 c_write_str(ssh, msgbuf);
2636 c_write_str(ssh, "\r\n");
2637 s->tried_publickey = 1;
2638 continue;
2639 }
2640 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2641 if (flags & FLAG_VERBOSE)
2642 c_write_str(ssh, "No passphrase required.\r\n");
2643 goto tryauth;
2644 }
2645 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
2646 sfree(comment);
2647 }
2648
2649 /*
2650 * Show password prompt, having first obtained it via a TIS
2651 * or CryptoCard exchange if we're doing TIS or CryptoCard
2652 * authentication.
2653 */
2654 if (ssh_get_line) {
2655 if (!ssh_get_line(s->prompt, s->password,
2656 sizeof(s->password), TRUE)) {
2657 /*
2658 * get_line failed to get a password (for example
2659 * because one was supplied on the command line
2660 * which has already failed to work). Terminate.
2661 */
2662 send_packet(ssh, SSH1_MSG_DISCONNECT,
2663 PKT_STR, "No more passwords available to try",
2664 PKT_END);
2665 logevent("Unable to authenticate");
2666 connection_fatal("Unable to authenticate");
2667 ssh->state = SSH_STATE_CLOSED;
2668 crReturn(1);
2669 }
2670 } else {
2671 /* Prompt may have come from server. We've munged it a bit, so
2672 * we know it to be zero-terminated at least once. */
2673 int ret; /* need not be saved over crReturn */
2674 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2675 s->pos = 0;
2676
2677 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
2678 do {
2679 crWaitUntil(!ispkt);
2680 ret = process_userpass_input(ssh, in, inlen);
2681 } while (ret == 0);
2682 if (ret < 0)
2683 cleanup_exit(0);
2684 c_write_str(ssh, "\r\n");
2685 }
2686
2687 tryauth:
2688 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2689 /*
2690 * Try public key authentication with the specified
2691 * key file.
2692 */
2693 s->tried_publickey = 1;
2694
2695 {
2696 int ret = loadrsakey(cfg.keyfile, &s->key, s->password);
2697 if (ret == 0) {
2698 c_write_str(ssh, "Couldn't load private key from ");
2699 c_write_str(ssh, cfg.keyfile);
2700 c_write_str(ssh, ".\r\n");
2701 continue; /* go and try password */
2702 }
2703 if (ret == -1) {
2704 c_write_str(ssh, "Wrong passphrase.\r\n");
2705 s->tried_publickey = 0;
2706 continue; /* try again */
2707 }
2708 }
2709
2710 /*
2711 * Send a public key attempt.
2712 */
2713 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2714 PKT_BIGNUM, s->key.modulus, PKT_END);
2715
2716 crWaitUntil(ispkt);
2717 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2718 c_write_str(ssh, "Server refused our public key.\r\n");
2719 continue; /* go and try password */
2720 }
2721 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2722 bombout(("Bizarre response to offer of public key"));
2723 crReturn(0);
2724 }
2725
2726 {
2727 int i;
2728 unsigned char buffer[32];
2729 Bignum challenge, response;
2730
2731 ssh1_read_bignum(ssh->pktin.body, &challenge);
2732 response = rsadecrypt(challenge, &s->key);
2733 freebn(s->key.private_exponent);/* burn the evidence */
2734
2735 for (i = 0; i < 32; i++) {
2736 buffer[i] = bignum_byte(response, 31 - i);
2737 }
2738
2739 MD5Init(&md5c);
2740 MD5Update(&md5c, buffer, 32);
2741 MD5Update(&md5c, s->session_id, 16);
2742 MD5Final(buffer, &md5c);
2743
2744 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2745 PKT_DATA, buffer, 16, PKT_END);
2746
2747 freebn(challenge);
2748 freebn(response);
2749 }
2750
2751 crWaitUntil(ispkt);
2752 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2753 if (flags & FLAG_VERBOSE)
2754 c_write_str(ssh, "Failed to authenticate with"
2755 " our public key.\r\n");
2756 continue; /* go and try password */
2757 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2758 bombout(("Bizarre response to RSA authentication response"));
2759 crReturn(0);
2760 }
2761
2762 break; /* we're through! */
2763 } else {
2764 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2765 /*
2766 * Defence against traffic analysis: we send a
2767 * whole bunch of packets containing strings of
2768 * different lengths. One of these strings is the
2769 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2770 * The others are all random data in
2771 * SSH1_MSG_IGNORE packets. This way a passive
2772 * listener can't tell which is the password, and
2773 * hence can't deduce the password length.
2774 *
2775 * Anybody with a password length greater than 16
2776 * bytes is going to have enough entropy in their
2777 * password that a listener won't find it _that_
2778 * much help to know how long it is. So what we'll
2779 * do is:
2780 *
2781 * - if password length < 16, we send 15 packets
2782 * containing string lengths 1 through 15
2783 *
2784 * - otherwise, we let N be the nearest multiple
2785 * of 8 below the password length, and send 8
2786 * packets containing string lengths N through
2787 * N+7. This won't obscure the order of
2788 * magnitude of the password length, but it will
2789 * introduce a bit of extra uncertainty.
2790 *
2791 * A few servers (the old 1.2.18 through 1.2.22)
2792 * can't deal with SSH1_MSG_IGNORE. For these
2793 * servers, we need an alternative defence. We make
2794 * use of the fact that the password is interpreted
2795 * as a C string: so we can append a NUL, then some
2796 * random data.
2797 *
2798 * One server (a Cisco one) can deal with neither
2799 * SSH1_MSG_IGNORE _nor_ a padded password string.
2800 * For this server we are left with no defences
2801 * against password length sniffing.
2802 */
2803 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2804 /*
2805 * The server can deal with SSH1_MSG_IGNORE, so
2806 * we can use the primary defence.
2807 */
2808 int bottom, top, pwlen, i;
2809 char *randomstr;
2810
2811 pwlen = strlen(s->password);
2812 if (pwlen < 16) {
2813 bottom = 0; /* zero length passwords are OK! :-) */
2814 top = 15;
2815 } else {
2816 bottom = pwlen & ~7;
2817 top = bottom + 7;
2818 }
2819
2820 assert(pwlen >= bottom && pwlen <= top);
2821
2822 randomstr = smalloc(top + 1);
2823
2824 for (i = bottom; i <= top; i++) {
2825 if (i == pwlen)
2826 defer_packet(ssh, s->pwpkt_type,
2827 PKT_STR, s->password, PKT_END);
2828 else {
2829 for (j = 0; j < i; j++) {
2830 do {
2831 randomstr[j] = random_byte();
2832 } while (randomstr[j] == '\0');
2833 }
2834 randomstr[i] = '\0';
2835 defer_packet(ssh, SSH1_MSG_IGNORE,
2836 PKT_STR, randomstr, PKT_END);
2837 }
2838 }
2839 logevent("Sending password with camouflage packets");
2840 ssh_pkt_defersend(ssh);
2841 }
2842 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2843 /*
2844 * The server can't deal with SSH1_MSG_IGNORE
2845 * but can deal with padded passwords, so we
2846 * can use the secondary defence.
2847 */
2848 char string[64];
2849 char *ss;
2850 int len;
2851
2852 len = strlen(s->password);
2853 if (len < sizeof(string)) {
2854 ss = string;
2855 strcpy(string, s->password);
2856 len++; /* cover the zero byte */
2857 while (len < sizeof(string)) {
2858 string[len++] = (char) random_byte();
2859 }
2860 } else {
2861 ss = s->password;
2862 }
2863 logevent("Sending length-padded password");
2864 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2865 PKT_DATA, ss, len, PKT_END);
2866 } else {
2867 /*
2868 * The server has _both_
2869 * BUG_CHOKES_ON_SSH1_IGNORE and
2870 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2871 * therefore nothing we can do.
2872 */
2873 int len;
2874 len = strlen(s->password);
2875 logevent("Sending unpadded password");
2876 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2877 PKT_DATA, s->password, len, PKT_END);
2878 }
2879 } else {
2880 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
2881 }
2882 }
2883 logevent("Sent password");
2884 memset(s->password, 0, strlen(s->password));
2885 crWaitUntil(ispkt);
2886 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2887 if (flags & FLAG_VERBOSE)
2888 c_write_str(ssh, "Access denied\r\n");
2889 logevent("Authentication refused");
2890 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2891 bombout(("Strange packet received, type %d", ssh->pktin.type));
2892 crReturn(0);
2893 }
2894 }
2895
2896 logevent("Authentication successful");
2897
2898 crFinish(1);
2899 }
2900
2901 void sshfwd_close(struct ssh_channel *c)
2902 {
2903 Ssh ssh = c->ssh;
2904
2905 if (c && !c->closes) {
2906 /*
2907 * If the channel's remoteid is -1, we have sent
2908 * CHANNEL_OPEN for this channel, but it hasn't even been
2909 * acknowledged by the server. So we must set a close flag
2910 * on it now, and then when the server acks the channel
2911 * open, we can close it then.
2912 */
2913 if (((int)c->remoteid) != -1) {
2914 if (ssh->version == 1) {
2915 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2916 PKT_END);
2917 } else {
2918 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
2919 ssh2_pkt_adduint32(ssh, c->remoteid);
2920 ssh2_pkt_send(ssh);
2921 }
2922 }
2923 c->closes = 1; /* sent MSG_CLOSE */
2924 if (c->type == CHAN_X11) {
2925 c->u.x11.s = NULL;
2926 logevent("Forwarded X11 connection terminated");
2927 } else if (c->type == CHAN_SOCKDATA ||
2928 c->type == CHAN_SOCKDATA_DORMANT) {
2929 c->u.pfd.s = NULL;
2930 logevent("Forwarded port closed");
2931 }
2932 }
2933 }
2934
2935 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2936 {
2937 Ssh ssh = c->ssh;
2938
2939 if (ssh->version == 1) {
2940 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2941 PKT_INT, c->remoteid,
2942 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2943 /*
2944 * In SSH1 we can return 0 here - implying that forwarded
2945 * connections are never individually throttled - because
2946 * the only circumstance that can cause throttling will be
2947 * the whole SSH connection backing up, in which case
2948 * _everything_ will be throttled as a whole.
2949 */
2950 return 0;
2951 } else {
2952 ssh2_add_channel_data(c, buf, len);
2953 return ssh2_try_send(c);
2954 }
2955 }
2956
2957 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2958 {
2959 Ssh ssh = c->ssh;
2960
2961 if (ssh->version == 1) {
2962 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2963 c->v.v1.throttling = 0;
2964 ssh1_throttle(ssh, -1);
2965 }
2966 } else {
2967 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2968 }
2969 }
2970
2971 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2972 {
2973 crBegin(ssh->ssh1_protocol_crstate);
2974
2975 random_init();
2976
2977 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
2978 crReturnV;
2979 }
2980 if (ssh->state == SSH_STATE_CLOSED)
2981 crReturnV;
2982
2983 if (cfg.agentfwd && agent_exists()) {
2984 logevent("Requesting agent forwarding");
2985 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2986 do {
2987 crReturnV;
2988 } while (!ispkt);
2989 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
2990 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
2991 bombout(("Protocol confusion"));
2992 crReturnV;
2993 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2994 logevent("Agent forwarding refused");
2995 } else {
2996 logevent("Agent forwarding enabled");
2997 ssh->agentfwd_enabled = TRUE;
2998 }
2999 }
3000
3001 if (cfg.x11_forward) {
3002 char proto[20], data[64];
3003 logevent("Requesting X11 forwarding");
3004 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3005 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3006 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3007 PKT_STR, proto, PKT_STR, data,
3008 PKT_INT, 0, PKT_END);
3009 } else {
3010 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3011 PKT_STR, proto, PKT_STR, data, PKT_END);
3012 }
3013 do {
3014 crReturnV;
3015 } while (!ispkt);
3016 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3017 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3018 bombout(("Protocol confusion"));
3019 crReturnV;
3020 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3021 logevent("X11 forwarding refused");
3022 } else {
3023 logevent("X11 forwarding enabled");
3024 ssh->X11_fwd_enabled = TRUE;
3025 }
3026 }
3027
3028 {
3029 char type;
3030 int n;
3031 int sport,dport,sserv,dserv;
3032 char sports[256], dports[256], host[256];
3033 char buf[1024];
3034 struct servent *se;
3035
3036 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3037 /* Add port forwardings. */
3038 ssh->portfwd_strptr = cfg.portfwd;
3039 while (*ssh->portfwd_strptr) {
3040 type = *ssh->portfwd_strptr++;
3041 n = 0;
3042 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
3043 sports[n++] = *ssh->portfwd_strptr++;
3044 sports[n] = 0;
3045 if (*ssh->portfwd_strptr == '\t')
3046 ssh->portfwd_strptr++;
3047 n = 0;
3048 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
3049 host[n++] = *ssh->portfwd_strptr++;
3050 host[n] = 0;
3051 if (*ssh->portfwd_strptr == ':')
3052 ssh->portfwd_strptr++;
3053 n = 0;
3054 while (*ssh->portfwd_strptr)
3055 dports[n++] = *ssh->portfwd_strptr++;
3056 dports[n] = 0;
3057 ssh->portfwd_strptr++;
3058 dport = atoi(dports);
3059 dserv = 0;
3060 if (dport == 0) {
3061 dserv = 1;
3062 se = getservbyname(dports, NULL);
3063 if (se != NULL) {
3064 dport = ntohs(se->s_port);
3065 } else {
3066 sprintf(buf,
3067 "Service lookup failed for destination port \"%s\"",
3068 dports);
3069 logevent(buf);
3070 }
3071 }
3072 sport = atoi(sports);
3073 sserv = 0;
3074 if (sport == 0) {
3075 sserv = 1;
3076 se = getservbyname(sports, NULL);
3077 if (se != NULL) {
3078 sport = ntohs(se->s_port);
3079 } else {
3080 sprintf(buf,
3081 "Service lookup failed for source port \"%s\"",
3082 sports);
3083 logevent(buf);
3084 }
3085 }
3086 if (sport && dport) {
3087 if (type == 'L') {
3088 pfd_addforward(host, dport, sport);
3089 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3090 " %s:%.*s%.*s%d%.*s",
3091 sserv ? strlen(sports) : 0, sports,
3092 sserv, "(", sport, sserv, ")",
3093 host,
3094 dserv ? strlen(dports) : 0, dports,
3095 dserv, "(", dport, dserv, ")");
3096 logevent(buf);
3097 } else {
3098 struct ssh_rportfwd *pf;
3099 pf = smalloc(sizeof(*pf));
3100 strcpy(pf->dhost, host);
3101 pf->dport = dport;
3102 if (add234(ssh->rportfwds, pf) != pf) {
3103 sprintf(buf,
3104 "Duplicate remote port forwarding to %s:%d",
3105 host, dport);
3106 logevent(buf);
3107 sfree(pf);
3108 } else {
3109 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3110 " forward to %s:%.*s%.*s%d%.*s",
3111 sserv ? strlen(sports) : 0, sports,
3112 sserv, "(", sport, sserv, ")",
3113 host,
3114 dserv ? strlen(dports) : 0, dports,
3115 dserv, "(", dport, dserv, ")");
3116 logevent(buf);
3117 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3118 PKT_INT, sport,
3119 PKT_STR, host,
3120 PKT_INT, dport,
3121 PKT_END);
3122 do {
3123 crReturnV;
3124 } while (!ispkt);
3125 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3126 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3127 bombout(("Protocol confusion"));
3128 crReturnV;
3129 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3130 c_write_str(ssh, "Server refused port"
3131 " forwarding\r\n");
3132 }
3133 logevent("Remote port forwarding enabled");
3134 }
3135 }
3136 }
3137 }
3138 }
3139
3140 if (!cfg.nopty) {
3141 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
3142 PKT_STR, cfg.termtype,
3143 PKT_INT, ssh->term_height,
3144 PKT_INT, ssh->term_width,
3145 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3146 ssh->state = SSH_STATE_INTERMED;
3147 do {
3148 crReturnV;
3149 } while (!ispkt);
3150 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3151 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3152 bombout(("Protocol confusion"));
3153 crReturnV;
3154 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3155 c_write_str(ssh, "Server refused to allocate pty\r\n");
3156 ssh->editing = ssh->echoing = 1;
3157 }
3158 logevent("Allocated pty");
3159 } else {
3160 ssh->editing = ssh->echoing = 1;
3161 }
3162
3163 if (cfg.compression) {
3164 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3165 do {
3166 crReturnV;
3167 } while (!ispkt);
3168 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3169 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3170 bombout(("Protocol confusion"));
3171 crReturnV;
3172 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3173 c_write_str(ssh, "Server refused to compress\r\n");
3174 }
3175 logevent("Started compression");
3176 ssh->v1_compressing = TRUE;
3177 zlib_compress_init();
3178 zlib_decompress_init();
3179 }
3180
3181 /*
3182 * Start the shell or command.
3183 *
3184 * Special case: if the first-choice command is an SSH2
3185 * subsystem (hence not usable here) and the second choice
3186 * exists, we fall straight back to that.
3187 */
3188 {
3189 char *cmd = cfg.remote_cmd_ptr;
3190
3191 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3192 cmd = cfg.remote_cmd_ptr2;
3193 ssh->fallback_cmd = TRUE;
3194 }
3195 if (*cmd)
3196 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3197 else
3198 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
3199 logevent("Started session");
3200 }
3201
3202 ssh->state = SSH_STATE_SESSION;
3203 if (ssh->size_needed)
3204 ssh_size(ssh, ssh->term_width, ssh->term_height);
3205 if (ssh->eof_needed)
3206 ssh_special(ssh, TS_EOF);
3207
3208 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
3209 ssh->send_ok = 1;
3210 ssh->channels = newtree234(ssh_channelcmp);
3211 while (1) {
3212 crReturnV;
3213 if (ispkt) {
3214 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
3215 ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
3216 long len = GET_32BIT(ssh->pktin.body);
3217 int bufsize =
3218 from_backend(ssh->frontend,
3219 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
3220 ssh->pktin.body + 4, len);
3221 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3222 ssh->v1_stdout_throttling = 1;
3223 ssh1_throttle(ssh, +1);
3224 }
3225 } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
3226 ssh->state = SSH_STATE_CLOSED;
3227 logevent("Received disconnect request");
3228 crReturnV;
3229 } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
3230 /* Remote side is trying to open a channel to talk to our
3231 * X-Server. Give them back a local channel number. */
3232 struct ssh_channel *c;
3233
3234 logevent("Received X11 connect request");
3235 /* Refuse if X11 forwarding is disabled. */
3236 if (!ssh->X11_fwd_enabled) {
3237 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3238 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3239 logevent("Rejected X11 connect request");
3240 } else {
3241 c = smalloc(sizeof(struct ssh_channel));
3242 c->ssh = ssh;
3243
3244 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3245 logevent("opening X11 forward connection failed");
3246 sfree(c);
3247 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3248 PKT_INT, GET_32BIT(ssh->pktin.body),
3249 PKT_END);
3250 } else {
3251 logevent
3252 ("opening X11 forward connection succeeded");
3253 c->remoteid = GET_32BIT(ssh->pktin.body);
3254 c->localid = alloc_channel_id(ssh);
3255 c->closes = 0;
3256 c->v.v1.throttling = 0;
3257 c->type = CHAN_X11; /* identify channel type */
3258 add234(ssh->channels, c);
3259 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3260 PKT_INT, c->remoteid, PKT_INT,
3261 c->localid, PKT_END);
3262 logevent("Opened X11 forward channel");
3263 }
3264 }
3265 } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
3266 /* Remote side is trying to open a channel to talk to our
3267 * agent. Give them back a local channel number. */
3268 struct ssh_channel *c;
3269
3270 /* Refuse if agent forwarding is disabled. */
3271 if (!ssh->agentfwd_enabled) {
3272 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3273 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3274 } else {
3275 c = smalloc(sizeof(struct ssh_channel));
3276 c->ssh = ssh;
3277 c->remoteid = GET_32BIT(ssh->pktin.body);
3278 c->localid = alloc_channel_id(ssh);
3279 c->closes = 0;
3280 c->v.v1.throttling = 0;
3281 c->type = CHAN_AGENT; /* identify channel type */
3282 c->u.a.lensofar = 0;
3283 add234(ssh->channels, c);
3284 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3285 PKT_INT, c->remoteid, PKT_INT, c->localid,
3286 PKT_END);
3287 }
3288 } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
3289 /* Remote side is trying to open a channel to talk to a
3290 * forwarded port. Give them back a local channel number. */
3291 struct ssh_channel *c;
3292 struct ssh_rportfwd pf;
3293 int hostsize, port;
3294 char host[256], buf[1024];
3295 char *p, *h, *e;
3296 c = smalloc(sizeof(struct ssh_channel));
3297 c->ssh = ssh;
3298
3299 hostsize = GET_32BIT(ssh->pktin.body+4);
3300 for(h = host, p = ssh->pktin.body+8; hostsize != 0; hostsize--) {
3301 if (h+1 < host+sizeof(host))
3302 *h++ = *p;
3303 p++;
3304 }
3305 *h = 0;
3306 port = GET_32BIT(p);
3307
3308 strcpy(pf.dhost, host);
3309 pf.dport = port;
3310
3311 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3312 sprintf(buf, "Rejected remote port open request for %s:%d",
3313 host, port);
3314 logevent(buf);
3315 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3316 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3317 } else {
3318 sprintf(buf, "Received remote port open request for %s:%d",
3319 host, port);
3320 logevent(buf);
3321 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3322 if (e != NULL) {
3323 char buf[256];
3324 sprintf(buf, "Port open failed: %s", e);
3325 logevent(buf);
3326 sfree(c);
3327 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3328 PKT_INT, GET_32BIT(ssh->pktin.body),
3329 PKT_END);
3330 } else {
3331 c->remoteid = GET_32BIT(ssh->pktin.body);
3332 c->localid = alloc_channel_id(ssh);
3333 c->closes = 0;
3334 c->v.v1.throttling = 0;
3335 c->type = CHAN_SOCKDATA; /* identify channel type */
3336 add234(ssh->channels, c);
3337 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3338 PKT_INT, c->remoteid, PKT_INT,
3339 c->localid, PKT_END);
3340 logevent("Forwarded port opened successfully");
3341 }
3342 }
3343
3344 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3345 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3346 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3347 struct ssh_channel *c;
3348
3349 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3350 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3351 c->remoteid = localid;
3352 c->type = CHAN_SOCKDATA;
3353 c->v.v1.throttling = 0;
3354 pfd_confirm(c->u.pfd.s);
3355 }
3356
3357 if (c && c->closes) {
3358 /*
3359 * We have a pending close on this channel,
3360 * which we decided on before the server acked
3361 * the channel open. So now we know the
3362 * remoteid, we can close it again.
3363 */
3364 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3365 PKT_INT, c->remoteid, PKT_END);
3366 }
3367
3368 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3369 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3370 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3371 struct ssh_channel *c;
3372
3373 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3374 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3375 logevent("Forwarded connection refused by server");
3376 pfd_close(c->u.pfd.s);
3377 del234(ssh->channels, c);
3378 sfree(c);
3379 }
3380
3381 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3382 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3383 /* Remote side closes a channel. */
3384 unsigned i = GET_32BIT(ssh->pktin.body);
3385 struct ssh_channel *c;
3386 c = find234(ssh->channels, &i, ssh_channelfind);
3387 if (c && ((int)c->remoteid) != -1) {
3388 int closetype;
3389 closetype =
3390 (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3391
3392 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3393 logevent("Forwarded X11 connection terminated");
3394 assert(c->u.x11.s != NULL);
3395 x11_close(c->u.x11.s);
3396 c->u.x11.s = NULL;
3397 }
3398 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3399 logevent("Forwarded port closed");
3400 assert(c->u.pfd.s != NULL);
3401 pfd_close(c->u.pfd.s);
3402 c->u.pfd.s = NULL;
3403 }
3404
3405 c->closes |= (closetype << 2); /* seen this message */
3406 if (!(c->closes & closetype)) {
3407 send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
3408 PKT_END);
3409 c->closes |= closetype; /* sent it too */
3410 }
3411
3412 if (c->closes == 15) {
3413 del234(ssh->channels, c);
3414 sfree(c);
3415 }
3416 } else {
3417 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3418 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3419 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3420 i));
3421 }
3422 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
3423 /* Data sent down one of our channels. */
3424 int i = GET_32BIT(ssh->pktin.body);
3425 int len = GET_32BIT(ssh->pktin.body + 4);
3426 unsigned char *p = ssh->pktin.body + 8;
3427 struct ssh_channel *c;
3428 c = find234(ssh->channels, &i, ssh_channelfind);
3429 if (c) {
3430 int bufsize;
3431 switch (c->type) {
3432 case CHAN_X11:
3433 bufsize = x11_send(c->u.x11.s, p, len);
3434 break;
3435 case CHAN_SOCKDATA:
3436 bufsize = pfd_send(c->u.pfd.s, p, len);
3437 break;
3438 case CHAN_AGENT:
3439 /* Data for an agent message. Buffer it. */
3440 while (len > 0) {
3441 if (c->u.a.lensofar < 4) {
3442 int l = min(4 - c->u.a.lensofar, len);
3443 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3444 l);
3445 p += l;
3446 len -= l;
3447 c->u.a.lensofar += l;
3448 }
3449 if (c->u.a.lensofar == 4) {
3450 c->u.a.totallen =
3451 4 + GET_32BIT(c->u.a.msglen);
3452 c->u.a.message = smalloc(c->u.a.totallen);
3453 memcpy(c->u.a.message, c->u.a.msglen, 4);
3454 }
3455 if (c->u.a.lensofar >= 4 && len > 0) {
3456 int l =
3457 min(c->u.a.totallen - c->u.a.lensofar,
3458 len);
3459 memcpy(c->u.a.message + c->u.a.lensofar, p,
3460 l);
3461 p += l;
3462 len -= l;
3463 c->u.a.lensofar += l;
3464 }
3465 if (c->u.a.lensofar == c->u.a.totallen) {
3466 void *reply, *sentreply;
3467 int replylen;
3468 agent_query(c->u.a.message,
3469 c->u.a.totallen, &reply,
3470 &replylen);
3471 if (reply)
3472 sentreply = reply;
3473 else {
3474 /* Fake SSH_AGENT_FAILURE. */
3475 sentreply = "\0\0\0\1\5";
3476 replylen = 5;
3477 }
3478 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3479 PKT_INT, c->remoteid,
3480 PKT_INT, replylen,
3481 PKT_DATA, sentreply, replylen,
3482 PKT_END);
3483 if (reply)
3484 sfree(reply);
3485 sfree(c->u.a.message);
3486 c->u.a.lensofar = 0;
3487 }
3488 }
3489 bufsize = 0; /* agent channels never back up */
3490 break;
3491 }
3492 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3493 c->v.v1.throttling = 1;
3494 ssh1_throttle(ssh, +1);
3495 }
3496 }
3497 } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
3498 /* may be from EXEC_SHELL on some servers */
3499 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3500 /* may be from EXEC_SHELL on some servers
3501 * if no pty is available or in other odd cases. Ignore */
3502 } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
3503 char buf[100];
3504 ssh->exitcode = GET_32BIT(ssh->pktin.body);
3505 sprintf(buf, "Server sent command exit status %d",
3506 ssh->exitcode);
3507 logevent(buf);
3508 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3509 /*
3510 * In case `helpful' firewalls or proxies tack
3511 * extra human-readable text on the end of the
3512 * session which we might mistake for another
3513 * encrypted packet, we close the session once
3514 * we've sent EXIT_CONFIRMATION.
3515 */
3516 ssh->state = SSH_STATE_CLOSED;
3517 crReturnV;
3518 } else {
3519 bombout(("Strange packet received: type %d", ssh->pktin.type));
3520 crReturnV;
3521 }
3522 } else {
3523 while (inlen > 0) {
3524 int len = min(inlen, 512);
3525 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
3526 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3527 in += len;
3528 inlen -= len;
3529 }
3530 }
3531 }
3532
3533 crFinishV;
3534 }
3535
3536 /*
3537 * Utility routine for decoding comma-separated strings in KEXINIT.
3538 */
3539 static int in_commasep_string(char *needle, char *haystack, int haylen)
3540 {
3541 int needlen = strlen(needle);
3542 while (1) {
3543 /*
3544 * Is it at the start of the string?
3545 */
3546 if (haylen >= needlen && /* haystack is long enough */
3547 !memcmp(needle, haystack, needlen) && /* initial match */
3548 (haylen == needlen || haystack[needlen] == ',')
3549 /* either , or EOS follows */
3550 )
3551 return 1;
3552 /*
3553 * If not, search for the next comma and resume after that.
3554 * If no comma found, terminate.
3555 */
3556 while (haylen > 0 && *haystack != ',')
3557 haylen--, haystack++;
3558 if (haylen == 0)
3559 return 0;
3560 haylen--, haystack++; /* skip over comma itself */
3561 }
3562 }
3563
3564 /*
3565 * SSH2 key creation method.
3566 */
3567 static void ssh2_mkkey(Ssh ssh, Bignum K, char *H, char *sessid, char chr,
3568 char *keyspace)
3569 {
3570 SHA_State s;
3571 /* First 20 bytes. */
3572 SHA_Init(&s);
3573 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3574 sha_mpint(&s, K);
3575 SHA_Bytes(&s, H, 20);
3576 SHA_Bytes(&s, &chr, 1);
3577 SHA_Bytes(&s, sessid, 20);
3578 SHA_Final(&s, keyspace);
3579 /* Next 20 bytes. */
3580 SHA_Init(&s);
3581 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3582 sha_mpint(&s, K);
3583 SHA_Bytes(&s, H, 20);
3584 SHA_Bytes(&s, keyspace, 20);
3585 SHA_Final(&s, keyspace + 20);
3586 }
3587
3588 /*
3589 * Handle the SSH2 transport layer.
3590 */
3591 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3592 {
3593 struct do_ssh2_transport_state {
3594 int nbits, pbits, warn;
3595 Bignum p, g, e, f, K;
3596 int kex_init_value, kex_reply_value;
3597 const struct ssh_mac **maclist;
3598 int nmacs;
3599 const struct ssh2_cipher *cscipher_tobe;
3600 const struct ssh2_cipher *sccipher_tobe;
3601 const struct ssh_mac *csmac_tobe;
3602 const struct ssh_mac *scmac_tobe;
3603 const struct ssh_compress *cscomp_tobe;
3604 const struct ssh_compress *sccomp_tobe;
3605 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3606 int hostkeylen, siglen;
3607 void *hkey; /* actual host key */
3608 unsigned char exchange_hash[20];
3609 int n_preferred_ciphers;
3610 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3611 const struct ssh_compress *preferred_comp;
3612 int first_kex;
3613 };
3614 crState(do_ssh2_transport_state);
3615
3616 crBegin(ssh->do_ssh2_transport_crstate);
3617
3618 s->cscipher_tobe = s->sccipher_tobe = NULL;
3619 s->csmac_tobe = s->scmac_tobe = NULL;
3620 s->cscomp_tobe = s->sccomp_tobe = NULL;
3621
3622 random_init();
3623 s->first_kex = 1;
3624
3625 {
3626 int i;
3627 /*
3628 * Set up the preferred ciphers. (NULL => warn below here)
3629 */
3630 s->n_preferred_ciphers = 0;
3631 for (i = 0; i < CIPHER_MAX; i++) {
3632 switch (cfg.ssh_cipherlist[i]) {
3633 case CIPHER_BLOWFISH:
3634 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3635 break;
3636 case CIPHER_DES:
3637 if (cfg.ssh2_des_cbc) {
3638 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3639 }
3640 break;
3641 case CIPHER_3DES:
3642 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3643 break;
3644 case CIPHER_AES:
3645 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3646 break;
3647 case CIPHER_WARN:
3648 /* Flag for later. Don't bother if it's the last in
3649 * the list. */
3650 if (i < CIPHER_MAX - 1) {
3651 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3652 }
3653 break;
3654 }
3655 }
3656 }
3657
3658 /*
3659 * Set up preferred compression.
3660 */
3661 if (cfg.compression)
3662 s->preferred_comp = &ssh_zlib;
3663 else
3664 s->preferred_comp = &ssh_comp_none;
3665
3666 /*
3667 * Be prepared to work around the buggy MAC problem.
3668 */
3669 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3670 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
3671 else
3672 s->maclist = macs, s->nmacs = lenof(macs);
3673
3674 begin_key_exchange:
3675 {
3676 int i, j, cipherstr_started;
3677
3678 /*
3679 * Construct and send our key exchange packet.
3680 */
3681 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3682 for (i = 0; i < 16; i++)
3683 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3684 /* List key exchange algorithms. */
3685 ssh2_pkt_addstring_start(ssh);
3686 for (i = 0; i < lenof(kex_algs); i++) {
3687 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3688 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3689 continue;
3690 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3691 if (i < lenof(kex_algs) - 1)
3692 ssh2_pkt_addstring_str(ssh, ",");
3693 }
3694 /* List server host key algorithms. */
3695 ssh2_pkt_addstring_start(ssh);
3696 for (i = 0; i < lenof(hostkey_algs); i++) {
3697 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3698 if (i < lenof(hostkey_algs) - 1)
3699 ssh2_pkt_addstring_str(ssh, ",");
3700 }
3701 /* List client->server encryption algorithms. */
3702 ssh2_pkt_addstring_start(ssh);
3703 cipherstr_started = 0;
3704 for (i = 0; i < s->n_preferred_ciphers; i++) {
3705 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3706 if (!c) continue; /* warning flag */
3707 for (j = 0; j < c->nciphers; j++) {
3708 if (cipherstr_started)
3709 ssh2_pkt_addstring_str(ssh, ",");
3710 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3711 cipherstr_started = 1;
3712 }
3713 }
3714 /* List server->client encryption algorithms. */
3715 ssh2_pkt_addstring_start(ssh);
3716 cipherstr_started = 0;
3717 for (i = 0; i < s->n_preferred_ciphers; i++) {
3718 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3719 if (!c) continue; /* warning flag */
3720 for (j = 0; j < c->nciphers; j++) {
3721 if (cipherstr_started)
3722 ssh2_pkt_addstring_str(ssh, ",");
3723 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3724 cipherstr_started = 1;
3725 }
3726 }
3727 /* List client->server MAC algorithms. */
3728 ssh2_pkt_addstring_start(ssh);
3729 for (i = 0; i < s->nmacs; i++) {
3730 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3731 if (i < s->nmacs - 1)
3732 ssh2_pkt_addstring_str(ssh, ",");
3733 }
3734 /* List server->client MAC algorithms. */
3735 ssh2_pkt_addstring_start(ssh);
3736 for (i = 0; i < s->nmacs; i++) {
3737 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3738 if (i < s->nmacs - 1)
3739 ssh2_pkt_addstring_str(ssh, ",");
3740 }
3741 /* List client->server compression algorithms. */
3742 ssh2_pkt_addstring_start(ssh);
3743 for (i = 0; i < lenof(compressions) + 1; i++) {
3744 const struct ssh_compress *c =
3745 i == 0 ? s->preferred_comp : compressions[i - 1];
3746 ssh2_pkt_addstring_str(ssh, c->name);
3747 if (i < lenof(compressions))
3748 ssh2_pkt_addstring_str(ssh, ",");
3749 }
3750 /* List server->client compression algorithms. */
3751 ssh2_pkt_addstring_start(ssh);
3752 for (i = 0; i < lenof(compressions) + 1; i++) {
3753 const struct ssh_compress *c =
3754 i == 0 ? s->preferred_comp : compressions[i - 1];
3755 ssh2_pkt_addstring_str(ssh, c->name);
3756 if (i < lenof(compressions))
3757 ssh2_pkt_addstring_str(ssh, ",");
3758 }
3759 /* List client->server languages. Empty list. */
3760 ssh2_pkt_addstring_start(ssh);
3761 /* List server->client languages. Empty list. */
3762 ssh2_pkt_addstring_start(ssh);
3763 /* First KEX packet does _not_ follow, because we're not that brave. */
3764 ssh2_pkt_addbool(ssh, FALSE);
3765 /* Reserved. */
3766 ssh2_pkt_adduint32(ssh, 0);
3767 }
3768
3769 ssh->exhash = ssh->exhashbase;
3770 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
3771
3772 ssh2_pkt_send(ssh);
3773
3774 if (!ispkt)
3775 crWaitUntil(ispkt);
3776 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
3777
3778 /*
3779 * Now examine the other side's KEXINIT to see what we're up
3780 * to.
3781 */
3782 {
3783 char *str;
3784 int i, j, len;
3785
3786 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
3787 bombout(("expected key exchange packet from server"));
3788 crReturn(0);
3789 }
3790 ssh->kex = NULL;
3791 ssh->hostkey = NULL;
3792 s->cscipher_tobe = NULL;
3793 s->sccipher_tobe = NULL;
3794 s->csmac_tobe = NULL;
3795 s->scmac_tobe = NULL;
3796 s->cscomp_tobe = NULL;
3797 s->sccomp_tobe = NULL;
3798 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3799 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3800 for (i = 0; i < lenof(kex_algs); i++) {
3801 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3802 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3803 continue;
3804 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3805 ssh->kex = kex_algs[i];
3806 break;
3807 }
3808 }
3809 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3810 for (i = 0; i < lenof(hostkey_algs); i++) {
3811 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3812 ssh->hostkey = hostkey_algs[i];
3813 break;
3814 }
3815 }
3816 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3817 s->warn = 0;
3818 for (i = 0; i < s->n_preferred_ciphers; i++) {
3819 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3820 if (!c) {
3821 s->warn = 1;
3822 } else {
3823 for (j = 0; j < c->nciphers; j++) {
3824 if (in_commasep_string(c->list[j]->name, str, len)) {
3825 s->cscipher_tobe = c->list[j];
3826 break;
3827 }
3828 }
3829 }
3830 if (s->cscipher_tobe) {
3831 if (s->warn)
3832 askcipher(s->cscipher_tobe->name, 1);
3833 break;
3834 }
3835 }
3836 if (!s->cscipher_tobe) {
3837 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3838 crReturn(0);
3839 }
3840
3841 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3842 s->warn = 0;
3843 for (i = 0; i < s->n_preferred_ciphers; i++) {
3844 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3845 if (!c) {
3846 s->warn = 1;
3847 } else {
3848 for (j = 0; j < c->nciphers; j++) {
3849 if (in_commasep_string(c->list[j]->name, str, len)) {
3850 s->sccipher_tobe = c->list[j];
3851 break;
3852 }
3853 }
3854 }
3855 if (s->sccipher_tobe) {
3856 if (s->warn)
3857 askcipher(s->sccipher_tobe->name, 2);
3858 break;
3859 }
3860 }
3861 if (!s->sccipher_tobe) {
3862 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3863 crReturn(0);
3864 }
3865
3866 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3867 for (i = 0; i < s->nmacs; i++) {
3868 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3869 s->csmac_tobe = s->maclist[i];
3870 break;
3871 }
3872 }
3873 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3874 for (i = 0; i < s->nmacs; i++) {
3875 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3876 s->scmac_tobe = s->maclist[i];
3877 break;
3878 }
3879 }
3880 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3881 for (i = 0; i < lenof(compressions) + 1; i++) {
3882 const struct ssh_compress *c =
3883 i == 0 ? s->preferred_comp : compressions[i - 1];
3884 if (in_commasep_string(c->name, str, len)) {
3885 s->cscomp_tobe = c;
3886 break;
3887 }
3888 }
3889 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
3890 for (i = 0; i < lenof(compressions) + 1; i++) {
3891 const struct ssh_compress *c =
3892 i == 0 ? s->preferred_comp : compressions[i - 1];
3893 if (in_commasep_string(c->name, str, len)) {
3894 s->sccomp_tobe = c;
3895 break;
3896 }
3897 }
3898 }
3899
3900 /*
3901 * Work out the number of bits of key we will need from the key
3902 * exchange. We start with the maximum key length of either
3903 * cipher...
3904 */
3905 {
3906 int csbits, scbits;
3907
3908 csbits = s->cscipher_tobe->keylen;
3909 scbits = s->sccipher_tobe->keylen;
3910 s->nbits = (csbits > scbits ? csbits : scbits);
3911 }
3912 /* The keys only have 160-bit entropy, since they're based on
3913 * a SHA-1 hash. So cap the key size at 160 bits. */
3914 if (s->nbits > 160)
3915 s->nbits = 160;
3916
3917 /*
3918 * If we're doing Diffie-Hellman group exchange, start by
3919 * requesting a group.
3920 */
3921 if (ssh->kex == &ssh_diffiehellman_gex) {
3922 logevent("Doing Diffie-Hellman group exchange");
3923 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
3924 /*
3925 * Work out how big a DH group we will need to allow that
3926 * much data.
3927 */
3928 s->pbits = 512 << ((s->nbits - 1) / 64);
3929 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
3930 ssh2_pkt_adduint32(ssh, s->pbits);
3931 ssh2_pkt_send(ssh);
3932
3933 crWaitUntil(ispkt);
3934 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3935 bombout(("expected key exchange group packet from server"));
3936 crReturn(0);
3937 }
3938 s->p = ssh2_pkt_getmp(ssh);
3939 s->g = ssh2_pkt_getmp(ssh);
3940 dh_setup_group(s->p, s->g);
3941 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3942 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3943 } else {
3944 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3945 dh_setup_group1();
3946 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
3947 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3948 }
3949
3950 logevent("Doing Diffie-Hellman key exchange");
3951 /*
3952 * Now generate and send e for Diffie-Hellman.
3953 */
3954 s->e = dh_create_e(s->nbits * 2);
3955 ssh2_pkt_init(ssh, s->kex_init_value);
3956 ssh2_pkt_addmp(ssh, s->e);
3957 ssh2_pkt_send(ssh);
3958
3959 crWaitUntil(ispkt);
3960 if (ssh->pktin.type != s->kex_reply_value) {
3961 bombout(("expected key exchange reply packet from server"));
3962 crReturn(0);
3963 }
3964 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
3965 s->f = ssh2_pkt_getmp(ssh);
3966 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
3967
3968 s->K = dh_find_K(s->f);
3969
3970 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
3971 if (ssh->kex == &ssh_diffiehellman_gex) {
3972 sha_uint32(&ssh->exhash, s->pbits);
3973 sha_mpint(&ssh->exhash, s->p);
3974 sha_mpint(&ssh->exhash, s->g);
3975 }
3976 sha_mpint(&ssh->exhash, s->e);
3977 sha_mpint(&ssh->exhash, s->f);
3978 sha_mpint(&ssh->exhash, s->K);
3979 SHA_Final(&ssh->exhash, s->exchange_hash);
3980
3981 dh_cleanup();
3982
3983 #if 0
3984 debug(("Exchange hash is:\n"));
3985 dmemdump(s->exchange_hash, 20);
3986 #endif
3987
3988 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
3989 if (!s->hkey ||
3990 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
3991 s->exchange_hash, 20)) {
3992 bombout(("Server's host key did not match the signature supplied"));
3993 crReturn(0);
3994 }
3995
3996 /*
3997 * Authenticate remote host: verify host key. (We've already
3998 * checked the signature of the exchange hash.)
3999 */
4000 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4001 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4002 verify_ssh_host_key(ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4003 s->keystr, s->fingerprint);
4004 if (s->first_kex) { /* don't bother logging this in rekeys */
4005 logevent("Host key fingerprint is:");
4006 logevent(s->fingerprint);
4007 }
4008 sfree(s->fingerprint);
4009 sfree(s->keystr);
4010 ssh->hostkey->freekey(s->hkey);
4011
4012 /*
4013 * Send SSH2_MSG_NEWKEYS.
4014 */
4015 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4016 ssh2_pkt_send(ssh);
4017
4018 /*
4019 * Expect SSH2_MSG_NEWKEYS from server.
4020 */
4021 crWaitUntil(ispkt);
4022 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
4023 bombout(("expected new-keys packet from server"));
4024 crReturn(0);
4025 }
4026
4027 /*
4028 * Create and initialise session keys.
4029 */
4030 if (ssh->cs_cipher_ctx)
4031 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4032 ssh->cscipher = s->cscipher_tobe;
4033 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4034 if (ssh->sc_cipher_ctx)
4035 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4036 ssh->sccipher = s->sccipher_tobe;
4037 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4038 ssh->csmac = s->csmac_tobe;
4039 ssh->scmac = s->scmac_tobe;
4040 ssh->cscomp = s->cscomp_tobe;
4041 ssh->sccomp = s->sccomp_tobe;
4042 ssh->cscomp->compress_init();
4043 ssh->sccomp->decompress_init();
4044 /*
4045 * Set IVs after keys. Here we use the exchange hash from the
4046 * _first_ key exchange.
4047 */
4048 {
4049 unsigned char keyspace[40];
4050 if (s->first_kex)
4051 memcpy(ssh->v2_session_id, s->exchange_hash,
4052 sizeof(s->exchange_hash));
4053 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4054 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4055 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4056 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4057 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4058 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4059 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4060 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4061 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4062 ssh->csmac->setcskey(keyspace);
4063 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4064 ssh->scmac->setsckey(keyspace);
4065 }
4066 {
4067 char buf[256];
4068 sprintf(buf, "Initialised %.200s client->server encryption",
4069 ssh->cscipher->text_name);
4070 logevent(buf);
4071 sprintf(buf, "Initialised %.200s server->client encryption",
4072 ssh->sccipher->text_name);
4073 logevent(buf);
4074 }
4075
4076
4077 /*
4078 * If this is the first key exchange phase, we must pass the
4079 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4080 * wants to see it but because it will need time to initialise
4081 * itself before it sees an actual packet. In subsequent key
4082 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4083 * it would only confuse the layer above.
4084 */
4085 if (!s->first_kex) {
4086 crReturn(0);
4087 }
4088 s->first_kex = 0;
4089
4090 /*
4091 * Now we're encrypting. Begin returning 1 to the protocol main
4092 * function so that other things can run on top of the
4093 * transport. If we ever see a KEXINIT, we must go back to the
4094 * start.
4095 */
4096 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
4097 crReturn(1);
4098 }
4099 logevent("Server initiated key re-exchange");
4100 goto begin_key_exchange;
4101
4102 crFinish(1);
4103 }
4104
4105 /*
4106 * Add data to an SSH2 channel output buffer.
4107 */
4108 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4109 int len)
4110 {
4111 bufchain_add(&c->v.v2.outbuffer, buf, len);
4112 }
4113
4114 /*
4115 * Attempt to send data on an SSH2 channel.
4116 */
4117 static int ssh2_try_send(struct ssh_channel *c)
4118 {
4119 Ssh ssh = c->ssh;
4120
4121 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4122 int len;
4123 void *data;
4124 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4125 if ((unsigned)len > c->v.v2.remwindow)
4126 len = c->v.v2.remwindow;
4127 if ((unsigned)len > c->v.v2.remmaxpkt)
4128 len = c->v.v2.remmaxpkt;
4129 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4130 ssh2_pkt_adduint32(ssh, c->remoteid);
4131 ssh2_pkt_addstring_start(ssh);
4132 ssh2_pkt_addstring_data(ssh, data, len);
4133 ssh2_pkt_send(ssh);
4134 bufchain_consume(&c->v.v2.outbuffer, len);
4135 c->v.v2.remwindow -= len;
4136 }
4137
4138 /*
4139 * After having sent as much data as we can, return the amount
4140 * still buffered.
4141 */
4142 return bufchain_size(&c->v.v2.outbuffer);
4143 }
4144
4145 /*
4146 * Potentially enlarge the window on an SSH2 channel.
4147 */
4148 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4149 {
4150 Ssh ssh = c->ssh;
4151
4152 /*
4153 * Never send WINDOW_ADJUST for a channel that the remote side
4154 * already thinks it's closed; there's no point, since it won't
4155 * be sending any more data anyway.
4156 */
4157 if (c->closes != 0)
4158 return;
4159
4160 if (newwin > c->v.v2.locwindow) {
4161 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4162 ssh2_pkt_adduint32(ssh, c->remoteid);
4163 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4164 ssh2_pkt_send(ssh);
4165 c->v.v2.locwindow = newwin;
4166 }
4167 }
4168
4169 /*
4170 * Handle the SSH2 userauth and connection layers.
4171 */
4172 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
4173 {
4174 struct do_ssh2_authconn_state {
4175 enum {
4176 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4177 AUTH_PASSWORD,
4178 AUTH_KEYBOARD_INTERACTIVE
4179 } method;
4180 enum {
4181 AUTH_TYPE_NONE,
4182 AUTH_TYPE_PUBLICKEY,
4183 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4184 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4185 AUTH_TYPE_PASSWORD,
4186 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4187 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4188 } type;
4189 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4190 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4191 int kbd_inter_running;
4192 int we_are_in;
4193 int num_prompts, curr_prompt, echo;
4194 char username[100];
4195 int got_username;
4196 char pwprompt[200];
4197 char password[100];
4198 void *publickey_blob;
4199 int publickey_bloblen;
4200 unsigned char request[5], *response, *p;
4201 int responselen;
4202 int keyi, nkeys;
4203 int authed;
4204 char *pkblob, *alg, *commentp;
4205 int pklen, alglen, commentlen;
4206 int siglen, retlen, len;
4207 char *q, *agentreq, *ret;
4208 int try_send;
4209 };
4210 crState(do_ssh2_authconn_state);
4211
4212 crBegin(ssh->do_ssh2_authconn_crstate);
4213
4214 /*
4215 * Request userauth protocol, and await a response to it.
4216 */
4217 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4218 ssh2_pkt_addstring(ssh, "ssh-userauth");
4219 ssh2_pkt_send(ssh);
4220 crWaitUntilV(ispkt);
4221 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4222 bombout(("Server refused user authentication protocol"));
4223 crReturnV;
4224 }
4225
4226 /*
4227 * We repeat this whole loop, including the username prompt,
4228 * until we manage a successful authentication. If the user
4229 * types the wrong _password_, they can be sent back to the
4230 * beginning to try another username, if this is configured on.
4231 * (If they specify a username in the config, they are never
4232 * asked, even if they do give a wrong password.)
4233 *
4234 * I think this best serves the needs of
4235 *
4236 * - the people who have no configuration, no keys, and just
4237 * want to try repeated (username,password) pairs until they
4238 * type both correctly
4239 *
4240 * - people who have keys and configuration but occasionally
4241 * need to fall back to passwords
4242 *
4243 * - people with a key held in Pageant, who might not have
4244 * logged in to a particular machine before; so they want to
4245 * type a username, and then _either_ their key will be
4246 * accepted, _or_ they will type a password. If they mistype
4247 * the username they will want to be able to get back and
4248 * retype it!
4249 */
4250 s->username[0] = '\0';
4251 s->got_username = FALSE;
4252 do {
4253 /*
4254 * Get a username.
4255 */
4256 if (s->got_username && !cfg.change_username) {
4257 /*
4258 * We got a username last time round this loop, and
4259 * with change_username turned off we don't try to get
4260 * it again.
4261 */
4262 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4263 if (ssh_get_line && !ssh_getline_pw_only) {
4264 if (!ssh_get_line("login as: ",
4265 s->username, sizeof(s->username), FALSE)) {
4266 /*
4267 * get_line failed to get a username.
4268 * Terminate.
4269 */
4270 logevent("No username provided. Abandoning session.");
4271 ssh->state = SSH_STATE_CLOSED;
4272 crReturnV;
4273 }
4274 } else {
4275 int ret; /* need not be saved across crReturn */
4276 c_write_str(ssh, "login as: ");
4277 ssh->send_ok = 1;
4278 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
4279 do {
4280 crWaitUntilV(!ispkt);
4281 ret = process_userpass_input(ssh, in, inlen);
4282 } while (ret == 0);
4283 if (ret < 0)
4284 cleanup_exit(0);
4285 }
4286 c_write_str(ssh, "\r\n");
4287 s->username[strcspn(s->username, "\n\r")] = '\0';
4288 } else {
4289 char stuff[200];
4290 strncpy(s->username, cfg.username, sizeof(s->username));
4291 s->username[sizeof(s->username)-1] = '\0';
4292 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4293 sprintf(stuff, "Using username \"%s\".\r\n", s->username);
4294 c_write_str(ssh, stuff);
4295 }
4296 }
4297 s->got_username = TRUE;
4298
4299 /*
4300 * Send an authentication request using method "none": (a)
4301 * just in case it succeeds, and (b) so that we know what
4302 * authentication methods we can usefully try next.
4303 */
4304 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4305
4306 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4307 ssh2_pkt_addstring(ssh, s->username);
4308 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4309 ssh2_pkt_addstring(ssh, "none"); /* method */
4310 ssh2_pkt_send(ssh);
4311 s->type = AUTH_TYPE_NONE;
4312 s->gotit = FALSE;
4313 s->we_are_in = FALSE;
4314
4315 s->tried_pubkey_config = FALSE;
4316 s->tried_agent = FALSE;
4317 s->tried_keyb_inter = FALSE;
4318 s->kbd_inter_running = FALSE;
4319 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4320 if (*cfg.keyfile) {
4321 int keytype;
4322 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4323 keytype = key_type(cfg.keyfile);
4324 if (keytype == SSH_KEYTYPE_SSH2) {
4325 s->publickey_blob =
4326 ssh2_userkey_loadpub(cfg.keyfile, NULL,
4327 &s->publickey_bloblen);
4328 } else {
4329 char msgbuf[256];
4330 logeventf("Unable to use this key file (%s)",
4331 key_type_to_str(keytype));
4332 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4333 cfg.keyfile, key_type_to_str(keytype));
4334 c_write_str(ssh, msgbuf);
4335 s->publickey_blob = NULL;
4336 }
4337 } else
4338 s->publickey_blob = NULL;
4339
4340 while (1) {
4341 /*
4342 * Wait for the result of the last authentication request.
4343 */
4344 if (!s->gotit)
4345 crWaitUntilV(ispkt);
4346 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4347 char *banner;
4348 int size;
4349 /*
4350 * Don't show the banner if we're operating in
4351 * non-verbose non-interactive mode. (It's probably
4352 * a script, which means nobody will read the
4353 * banner _anyway_, and moreover the printing of
4354 * the banner will screw up processing on the
4355 * output of (say) plink.)
4356 */
4357 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4358 ssh2_pkt_getstring(ssh, &banner, &size);
4359 if (banner)
4360 c_write_untrusted(ssh, banner, size);
4361 }
4362 crWaitUntilV(ispkt);
4363 }
4364 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4365 logevent("Access granted");
4366 s->we_are_in = TRUE;
4367 break;
4368 }
4369
4370 if (s->kbd_inter_running &&
4371 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4372 /*
4373 * This is either a further set-of-prompts packet
4374 * in keyboard-interactive authentication, or it's
4375 * the same one and we came back here with `gotit'
4376 * set. In the former case, we must reset the
4377 * curr_prompt variable.
4378 */
4379 if (!s->gotit)
4380 s->curr_prompt = 0;
4381 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4382 bombout(("Strange packet received during authentication: type %d",
4383 ssh->pktin.type));
4384 crReturnV;
4385 }
4386
4387 s->gotit = FALSE;
4388
4389 /*
4390 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4391 * we can look at the string in it and know what we can
4392 * helpfully try next.
4393 */
4394 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4395 char *methods;
4396 int methlen;
4397 ssh2_pkt_getstring(ssh, &methods, &methlen);
4398 s->kbd_inter_running = FALSE;
4399 if (!ssh2_pkt_getbool(ssh)) {
4400 /*
4401 * We have received an unequivocal Access
4402 * Denied. This can translate to a variety of
4403 * messages:
4404 *
4405 * - if we'd just tried "none" authentication,
4406 * it's not worth printing anything at all
4407 *
4408 * - if we'd just tried a public key _offer_,
4409 * the message should be "Server refused our
4410 * key" (or no message at all if the key
4411 * came from Pageant)
4412 *
4413 * - if we'd just tried anything else, the
4414 * message really should be "Access denied".
4415 *
4416 * Additionally, if we'd just tried password
4417 * authentication, we should break out of this
4418 * whole loop so as to go back to the username
4419 * prompt.
4420 */
4421 if (s->type == AUTH_TYPE_NONE) {
4422 /* do nothing */
4423 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4424 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4425 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4426 c_write_str(ssh, "Server refused our key\r\n");
4427 logevent("Server refused public key");
4428 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4429 /* server declined keyboard-interactive; ignore */
4430 } else {
4431 c_write_str(ssh, "Access denied\r\n");
4432 logevent("Access denied");
4433 if (s->type == AUTH_TYPE_PASSWORD) {
4434 s->we_are_in = FALSE;
4435 break;
4436 }
4437 }
4438 } else {
4439 c_write_str(ssh, "Further authentication required\r\n");
4440 logevent("Further authentication required");
4441 }
4442
4443 s->can_pubkey =
4444 in_commasep_string("publickey", methods, methlen);
4445 s->can_passwd =
4446 in_commasep_string("password", methods, methlen);
4447 s->can_keyb_inter = cfg.try_ki_auth &&
4448 in_commasep_string("keyboard-interactive", methods, methlen);
4449 }
4450
4451 s->method = 0;
4452 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4453
4454 /*
4455 * Most password/passphrase prompts will be
4456 * non-echoing, so we set this to 0 by default.
4457 * Exception is that some keyboard-interactive prompts
4458 * can be echoing, in which case we'll set this to 1.
4459 */
4460 s->echo = 0;
4461
4462 if (!s->method && s->can_pubkey &&
4463 agent_exists() && !s->tried_agent) {
4464 /*
4465 * Attempt public-key authentication using Pageant.
4466 */
4467 void *r;
4468 s->authed = FALSE;
4469
4470 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4471 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4472
4473 s->tried_agent = TRUE;
4474
4475 logevent("Pageant is running. Requesting keys.");
4476
4477 /* Request the keys held by the agent. */
4478 PUT_32BIT(s->request, 1);
4479 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4480 agent_query(s->request, 5, &r, &s->responselen);
4481 s->response = (unsigned char *) r;
4482 if (s->response && s->responselen >= 5 &&
4483 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4484 s->p = s->response + 5;
4485 s->nkeys = GET_32BIT(s->p);
4486 s->p += 4;
4487 {
4488 char buf[64];
4489 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
4490 logevent(buf);
4491 }
4492 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4493 void *vret;
4494
4495 {
4496 char buf[64];
4497 sprintf(buf, "Trying Pageant key #%d", s->keyi);
4498 logevent(buf);
4499 }
4500 s->pklen = GET_32BIT(s->p);
4501 s->p += 4;
4502 if (s->publickey_blob &&
4503 s->pklen == s->publickey_bloblen &&
4504 !memcmp(s->p, s->publickey_blob,
4505 s->publickey_bloblen)) {
4506 logevent("This key matches configured key file");
4507 s->tried_pubkey_config = 1;
4508 }
4509 s->pkblob = s->p;
4510 s->p += s->pklen;
4511 s->alglen = GET_32BIT(s->pkblob);
4512 s->alg = s->pkblob + 4;
4513 s->commentlen = GET_32BIT(s->p);
4514 s->p += 4;
4515 s->commentp = s->p;
4516 s->p += s->commentlen;
4517 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4518 ssh2_pkt_addstring(ssh, s->username);
4519 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4520 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4521 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4522 ssh2_pkt_addstring_start(ssh);
4523 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4524 ssh2_pkt_addstring_start(ssh);
4525 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4526 ssh2_pkt_send(ssh);
4527
4528 crWaitUntilV(ispkt);
4529 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4530 logevent("Key refused");
4531 continue;
4532 }
4533
4534 if (flags & FLAG_VERBOSE) {
4535 c_write_str(ssh, "Authenticating with "
4536 "public key \"");
4537 c_write(ssh, s->commentp, s->commentlen);
4538 c_write_str(ssh, "\" from agent\r\n");
4539 }
4540
4541 /*
4542 * Server is willing to accept the key.
4543 * Construct a SIGN_REQUEST.
4544 */
4545 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4546 ssh2_pkt_addstring(ssh, s->username);
4547 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4548 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4549 ssh2_pkt_addbool(ssh, TRUE);
4550 ssh2_pkt_addstring_start(ssh);
4551 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4552 ssh2_pkt_addstring_start(ssh);
4553 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4554
4555 s->siglen = ssh->pktout.length - 5 + 4 + 20;
4556 s->len = 1; /* message type */
4557 s->len += 4 + s->pklen; /* key blob */
4558 s->len += 4 + s->siglen; /* data to sign */
4559 s->len += 4; /* flags */
4560 s->agentreq = smalloc(4 + s->len);
4561 PUT_32BIT(s->agentreq, s->len);
4562 s->q = s->agentreq + 4;
4563 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4564 PUT_32BIT(s->q, s->pklen);
4565 s->q += 4;
4566 memcpy(s->q, s->pkblob, s->pklen);
4567 s->q += s->pklen;
4568 PUT_32BIT(s->q, s->siglen);
4569 s->q += 4;
4570 /* Now the data to be signed... */
4571 PUT_32BIT(s->q, 20);
4572 s->q += 4;
4573 memcpy(s->q, ssh->v2_session_id, 20);
4574 s->q += 20;
4575 memcpy(s->q, ssh->pktout.data + 5,
4576 ssh->pktout.length - 5);
4577 s->q += ssh->pktout.length - 5;
4578 /* And finally the (zero) flags word. */
4579 PUT_32BIT(s->q, 0);
4580 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4581 s->ret = vret;
4582 sfree(s->agentreq);
4583 if (s->ret) {
4584 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4585 logevent("Sending Pageant's response");
4586 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4587 s->ret + 9,
4588 GET_32BIT(s->ret + 5));
4589 ssh2_pkt_send(ssh);
4590 s->authed = TRUE;
4591 break;
4592 } else {
4593 logevent
4594 ("Pageant failed to answer challenge");
4595 sfree(s->ret);
4596 }
4597 }
4598 }
4599 if (s->authed)
4600 continue;
4601 }
4602 }
4603
4604 if (!s->method && s->can_pubkey && s->publickey_blob
4605 && !s->tried_pubkey_config) {
4606 unsigned char *pub_blob;
4607 char *algorithm, *comment;
4608 int pub_blob_len;
4609
4610 s->tried_pubkey_config = TRUE;
4611
4612 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4613 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4614
4615 /*
4616 * Try the public key supplied in the configuration.
4617 *
4618 * First, offer the public blob to see if the server is
4619 * willing to accept it.
4620 */
4621 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4622 &pub_blob_len);
4623 if (pub_blob) {
4624 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4625 ssh2_pkt_addstring(ssh, s->username);
4626 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4627 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4628 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4629 ssh2_pkt_addstring(ssh, algorithm);
4630 ssh2_pkt_addstring_start(ssh);
4631 ssh2_pkt_addstring_data(ssh, pub_blob, pub_blob_len);
4632 ssh2_pkt_send(ssh);
4633 logevent("Offered public key"); /* FIXME */
4634
4635 crWaitUntilV(ispkt);
4636 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4637 s->gotit = TRUE;
4638 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4639 continue; /* key refused; give up on it */
4640 }
4641
4642 logevent("Offer of public key accepted");
4643 /*
4644 * Actually attempt a serious authentication using
4645 * the key.
4646 */
4647 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4648 sprintf(s->pwprompt,
4649 "Passphrase for key \"%.100s\": ",
4650 comment);
4651 s->need_pw = TRUE;
4652 } else {
4653 s->need_pw = FALSE;
4654 }
4655 c_write_str(ssh, "Authenticating with public key \"");
4656 c_write_str(ssh, comment);
4657 c_write_str(ssh, "\"\r\n");
4658 s->method = AUTH_PUBLICKEY_FILE;
4659 }
4660 }
4661
4662 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4663 s->method = AUTH_KEYBOARD_INTERACTIVE;
4664 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4665 s->tried_keyb_inter = TRUE;
4666
4667 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4668 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4669
4670 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4671 ssh2_pkt_addstring(ssh, s->username);
4672 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4673 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4674 ssh2_pkt_addstring(ssh, ""); /* lang */
4675 ssh2_pkt_addstring(ssh, "");
4676 ssh2_pkt_send(ssh);
4677
4678 crWaitUntilV(ispkt);
4679 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4680 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4681 s->gotit = TRUE;
4682 logevent("Keyboard-interactive authentication refused");
4683 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4684 continue;
4685 }
4686
4687 s->kbd_inter_running = TRUE;
4688 s->curr_prompt = 0;
4689 }
4690
4691 if (s->kbd_inter_running) {
4692 s->method = AUTH_KEYBOARD_INTERACTIVE;
4693 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4694 s->tried_keyb_inter = TRUE;
4695
4696 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4697 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4698
4699 if (s->curr_prompt == 0) {
4700 /*
4701 * We've got a fresh USERAUTH_INFO_REQUEST.
4702 * Display header data, and start going through
4703 * the prompts.
4704 */
4705 char *name, *inst, *lang;
4706 int name_len, inst_len, lang_len;
4707
4708 ssh2_pkt_getstring(ssh, &name, &name_len);
4709 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4710 ssh2_pkt_getstring(ssh, &lang, &lang_len);
4711 if (name_len > 0) {
4712 c_write_untrusted(ssh, name, name_len);
4713 c_write_str(ssh, "\r\n");
4714 }
4715 if (inst_len > 0) {
4716 c_write_untrusted(ssh, inst, inst_len);
4717 c_write_str(ssh, "\r\n");
4718 }
4719 s->num_prompts = ssh2_pkt_getuint32(ssh);
4720 }
4721
4722 /*
4723 * If there are prompts remaining in the packet,
4724 * display one and get a response.
4725 */
4726 if (s->curr_prompt < s->num_prompts) {
4727 char *prompt;
4728 int prompt_len;
4729
4730 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
4731 if (prompt_len > 0) {
4732 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4733 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4734 prompt_len : sizeof(s->pwprompt)-1] = '\0';
4735 } else {
4736 strcpy(s->pwprompt,
4737 "<server failed to send prompt>: ");
4738 }
4739 s->echo = ssh2_pkt_getbool(ssh);
4740 s->need_pw = TRUE;
4741 } else
4742 s->need_pw = FALSE;
4743 }
4744
4745 if (!s->method && s->can_passwd) {
4746 s->method = AUTH_PASSWORD;
4747 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4748 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4749 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4750 ssh->savedhost);
4751 s->need_pw = TRUE;
4752 }
4753
4754 if (s->need_pw) {
4755 if (ssh_get_line) {
4756 if (!ssh_get_line(s->pwprompt, s->password,
4757 sizeof(s->password), TRUE)) {
4758 /*
4759 * get_line failed to get a password (for
4760 * example because one was supplied on the
4761 * command line which has already failed to
4762 * work). Terminate.
4763 */
4764 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4765 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4766 ssh2_pkt_addstring(ssh, "No more passwords available"
4767 " to try");
4768 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4769 ssh2_pkt_send(ssh);
4770 logevent("Unable to authenticate");
4771 connection_fatal("Unable to authenticate");
4772 ssh->state = SSH_STATE_CLOSED;
4773 crReturnV;
4774 }
4775 } else {
4776 int ret; /* need not be saved across crReturn */
4777 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4778 ssh->send_ok = 1;
4779
4780 setup_userpass_input(ssh, s->password,
4781 sizeof(s->password), s->echo);
4782 do {
4783 crWaitUntilV(!ispkt);
4784 ret = process_userpass_input(ssh, in, inlen);
4785 } while (ret == 0);
4786 if (ret < 0)
4787 cleanup_exit(0);
4788 c_write_str(ssh, "\r\n");
4789 }
4790 }
4791
4792 if (s->method == AUTH_PUBLICKEY_FILE) {
4793 /*
4794 * We have our passphrase. Now try the actual authentication.
4795 */
4796 struct ssh2_userkey *key;
4797
4798 key = ssh2_load_userkey(cfg.keyfile, s->password);
4799 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4800 if (key == SSH2_WRONG_PASSPHRASE) {
4801 c_write_str(ssh, "Wrong passphrase\r\n");
4802 s->tried_pubkey_config = FALSE;
4803 } else {
4804 c_write_str(ssh, "Unable to load private key\r\n");
4805 s->tried_pubkey_config = TRUE;
4806 }
4807 /* Send a spurious AUTH_NONE to return to the top. */
4808 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4809 ssh2_pkt_addstring(ssh, s->username);
4810 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4811 ssh2_pkt_addstring(ssh, "none"); /* method */
4812 ssh2_pkt_send(ssh);
4813 s->type = AUTH_TYPE_NONE;
4814 } else {
4815 unsigned char *pkblob, *sigblob, *sigdata;
4816 int pkblob_len, sigblob_len, sigdata_len;
4817
4818 /*
4819 * We have loaded the private key and the server
4820 * has announced that it's willing to accept it.
4821 * Hallelujah. Generate a signature and send it.
4822 */
4823 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4824 ssh2_pkt_addstring(ssh, s->username);
4825 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4826 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4827 ssh2_pkt_addbool(ssh, TRUE);
4828 ssh2_pkt_addstring(ssh, key->alg->name);
4829 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4830 ssh2_pkt_addstring_start(ssh);
4831 ssh2_pkt_addstring_data(ssh, pkblob, pkblob_len);
4832
4833 /*
4834 * The data to be signed is:
4835 *
4836 * string session-id
4837 *
4838 * followed by everything so far placed in the
4839 * outgoing packet.
4840 */
4841 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
4842 sigdata = smalloc(sigdata_len);
4843 PUT_32BIT(sigdata, 20);
4844 memcpy(sigdata + 4, ssh->v2_session_id, 20);
4845 memcpy(sigdata + 24, ssh->pktout.data + 5,
4846 ssh->pktout.length - 5);
4847 sigblob = key->alg->sign(key->data, sigdata,
4848 sigdata_len, &sigblob_len);
4849 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
4850 sigblob, sigblob_len);
4851 sfree(pkblob);
4852 sfree(sigblob);
4853 sfree(sigdata);
4854
4855 ssh2_pkt_send(ssh);
4856 s->type = AUTH_TYPE_PUBLICKEY;
4857 }
4858 } else if (s->method == AUTH_PASSWORD) {
4859 /*
4860 * We send the password packet lumped tightly together with
4861 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4862 * string long enough to make the total length of the two
4863 * packets constant. This should ensure that a passive
4864 * listener doing traffic analyis can't work out the length
4865 * of the password.
4866 *
4867 * For this to work, we need an assumption about the
4868 * maximum length of the password packet. I think 256 is
4869 * pretty conservative. Anyone using a password longer than
4870 * that probably doesn't have much to worry about from
4871 * people who find out how long their password is!
4872 */
4873 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4874 ssh2_pkt_addstring(ssh, s->username);
4875 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4876 ssh2_pkt_addstring(ssh, "password");
4877 ssh2_pkt_addbool(ssh, FALSE);
4878 ssh2_pkt_addstring(ssh, s->password);
4879 ssh2_pkt_defer(ssh);
4880 /*
4881 * We'll include a string that's an exact multiple of the
4882 * cipher block size. If the cipher is NULL for some
4883 * reason, we don't do this trick at all because we gain
4884 * nothing by it.
4885 */
4886 if (ssh->cscipher) {
4887 int stringlen, i;
4888
4889 stringlen = (256 - ssh->deferred_len);
4890 stringlen += ssh->cscipher->blksize - 1;
4891 stringlen -= (stringlen % ssh->cscipher->blksize);
4892 if (ssh->cscomp) {
4893 /*
4894 * Temporarily disable actual compression,
4895 * so we can guarantee to get this string
4896 * exactly the length we want it. The
4897 * compression-disabling routine should
4898 * return an integer indicating how many
4899 * bytes we should adjust our string length
4900 * by.
4901 */
4902 stringlen -= ssh->cscomp->disable_compression();
4903 }
4904 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
4905 ssh2_pkt_addstring_start(ssh);
4906 for (i = 0; i < stringlen; i++) {
4907 char c = (char) random_byte();
4908 ssh2_pkt_addstring_data(ssh, &c, 1);
4909 }
4910 ssh2_pkt_defer(ssh);
4911 }
4912 ssh_pkt_defersend(ssh);
4913 logevent("Sent password");
4914 s->type = AUTH_TYPE_PASSWORD;
4915 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
4916 if (s->curr_prompt == 0) {
4917 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
4918 ssh2_pkt_adduint32(ssh, s->num_prompts);
4919 }
4920 if (s->need_pw) { /* only add pw if we just got one! */
4921 ssh2_pkt_addstring(ssh, s->password);
4922 memset(s->password, 0, sizeof(s->password));
4923 s->curr_prompt++;
4924 }
4925 if (s->curr_prompt >= s->num_prompts) {
4926 ssh2_pkt_send(ssh);
4927 } else {
4928 /*
4929 * If there are prompts remaining, we set
4930 * `gotit' so that we won't attempt to get
4931 * another packet. Then we go back round the
4932 * loop and will end up retrieving another
4933 * prompt out of the existing packet. Funky or
4934 * what?
4935 */
4936 s->gotit = TRUE;
4937 }
4938 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4939 } else {
4940 c_write_str(ssh, "No supported authentication methods"
4941 " left to try!\r\n");
4942 logevent("No supported authentications offered."
4943 " Disconnecting");
4944 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4945 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
4946 ssh2_pkt_addstring(ssh, "No supported authentication"
4947 " methods available");
4948 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4949 ssh2_pkt_send(ssh);
4950 ssh->state = SSH_STATE_CLOSED;
4951 crReturnV;
4952 }
4953 }
4954 } while (!s->we_are_in);
4955
4956 /*
4957 * Now we're authenticated for the connection protocol. The
4958 * connection protocol will automatically have started at this
4959 * point; there's no need to send SERVICE_REQUEST.
4960 */
4961
4962 /*
4963 * So now create a channel with a session in it.
4964 */
4965 ssh->channels = newtree234(ssh_channelcmp);
4966 ssh->mainchan = smalloc(sizeof(struct ssh_channel));
4967 ssh->mainchan->ssh = ssh;
4968 ssh->mainchan->localid = alloc_channel_id(ssh);
4969 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
4970 ssh2_pkt_addstring(ssh, "session");
4971 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
4972 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4973 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
4974 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
4975 ssh2_pkt_send(ssh);
4976 crWaitUntilV(ispkt);
4977 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4978 bombout(("Server refused to open a session"));
4979 crReturnV;
4980 /* FIXME: error data comes back in FAILURE packet */
4981 }
4982 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
4983 bombout(("Server's channel confirmation cited wrong channel"));
4984 crReturnV;
4985 }
4986 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
4987 ssh->mainchan->type = CHAN_MAINSESSION;
4988 ssh->mainchan->closes = 0;
4989 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
4990 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
4991 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
4992 add234(ssh->channels, ssh->mainchan);
4993 logevent("Opened channel for session");
4994
4995 /*
4996 * Potentially enable X11 forwarding.
4997 */
4998 if (cfg.x11_forward) {
4999 char proto[20], data[64];
5000 logevent("Requesting X11 forwarding");
5001 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
5002 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5003 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5004 ssh2_pkt_addstring(ssh, "x11-req");
5005 ssh2_pkt_addbool(ssh, 1); /* want reply */
5006 ssh2_pkt_addbool(ssh, 0); /* many connections */
5007 ssh2_pkt_addstring(ssh, proto);
5008 ssh2_pkt_addstring(ssh, data);
5009 ssh2_pkt_adduint32(ssh, 0); /* screen number */
5010 ssh2_pkt_send(ssh);
5011
5012 do {
5013 crWaitUntilV(ispkt);
5014 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5015 unsigned i = ssh2_pkt_getuint32(ssh);
5016 struct ssh_channel *c;
5017 c = find234(ssh->channels, &i, ssh_channelfind);
5018 if (!c)
5019 continue; /* nonexistent channel */
5020 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5021 }
5022 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5023
5024 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5025 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5026 bombout(("Unexpected response to X11 forwarding request:"
5027 " packet type %d", ssh->pktin.type));
5028 crReturnV;
5029 }
5030 logevent("X11 forwarding refused");
5031 } else {
5032 logevent("X11 forwarding enabled");
5033 ssh->X11_fwd_enabled = TRUE;
5034 }
5035 }
5036
5037 /*
5038 * Enable port forwardings.
5039 */
5040 {
5041 char type;
5042 int n;
5043 int sport,dport,sserv,dserv;
5044 char sports[256], dports[256], host[256];
5045 char buf[1024];
5046 struct servent *se;
5047
5048 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5049 /* Add port forwardings. */
5050 ssh->portfwd_strptr = cfg.portfwd;
5051 while (*ssh->portfwd_strptr) {
5052 type = *ssh->portfwd_strptr++;
5053 n = 0;
5054 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
5055 sports[n++] = *ssh->portfwd_strptr++;
5056 sports[n] = 0;
5057 if (*ssh->portfwd_strptr == '\t')
5058 ssh->portfwd_strptr++;
5059 n = 0;
5060 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
5061 host[n++] = *ssh->portfwd_strptr++;
5062 host[n] = 0;
5063 if (*ssh->portfwd_strptr == ':')
5064 ssh->portfwd_strptr++;
5065 n = 0;
5066 while (*ssh->portfwd_strptr)
5067 dports[n++] = *ssh->portfwd_strptr++;
5068 dports[n] = 0;
5069 ssh->portfwd_strptr++;
5070 dport = atoi(dports);
5071 dserv = 0;
5072 if (dport == 0) {
5073 dserv = 1;
5074 se = getservbyname(dports, NULL);
5075 if (se != NULL) {
5076 dport = ntohs(se->s_port);
5077 } else {
5078 sprintf(buf,
5079 "Service lookup failed for destination port \"%s\"",
5080 dports);
5081 logevent(buf);
5082 }
5083 }
5084 sport = atoi(sports);
5085 sserv = 0;
5086 if (sport == 0) {
5087 sserv = 1;
5088 se = getservbyname(sports, NULL);
5089 if (se != NULL) {
5090 sport = ntohs(se->s_port);
5091 } else {
5092 sprintf(buf,
5093 "Service lookup failed for source port \"%s\"",
5094 sports);
5095 logevent(buf);
5096 }
5097 }
5098 if (sport && dport) {
5099 if (type == 'L') {
5100 pfd_addforward(host, dport, sport);
5101 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
5102 " %s:%.*s%.*s%d%.*s",
5103 sserv ? strlen(sports) : 0, sports,
5104 sserv, "(", sport, sserv, ")",
5105 host,
5106 dserv ? strlen(dports) : 0, dports,
5107 dserv, "(", dport, dserv, ")");
5108 logevent(buf);
5109 } else {
5110 struct ssh_rportfwd *pf;
5111 pf = smalloc(sizeof(*pf));
5112 strcpy(pf->dhost, host);
5113 pf->dport = dport;
5114 pf->sport = sport;
5115 if (add234(ssh->rportfwds, pf) != pf) {
5116 sprintf(buf,
5117 "Duplicate remote port forwarding to %s:%d",
5118 host, dport);
5119 logevent(buf);
5120 sfree(pf);
5121 } else {
5122 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5123 " forward to %s:%.*s%.*s%d%.*s",
5124 sserv ? strlen(sports) : 0, sports,
5125 sserv, "(", sport, sserv, ")",
5126 host,
5127 dserv ? strlen(dports) : 0, dports,
5128 dserv, "(", dport, dserv, ")");
5129 logevent(buf);
5130 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5131 ssh2_pkt_addstring(ssh, "tcpip-forward");
5132 ssh2_pkt_addbool(ssh, 1);/* want reply */
5133 if (cfg.rport_acceptall)
5134 ssh2_pkt_addstring(ssh, "0.0.0.0");
5135 else
5136 ssh2_pkt_addstring(ssh, "127.0.0.1");
5137 ssh2_pkt_adduint32(ssh, sport);
5138 ssh2_pkt_send(ssh);
5139
5140 do {
5141 crWaitUntilV(ispkt);
5142 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5143 unsigned i = ssh2_pkt_getuint32(ssh);
5144 struct ssh_channel *c;
5145 c = find234(ssh->channels, &i, ssh_channelfind);
5146 if (!c)
5147 continue;/* nonexistent channel */
5148 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5149 }
5150 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5151
5152 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5153 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5154 bombout(("Unexpected response to port "
5155 "forwarding request: packet type %d",
5156 ssh->pktin.type));
5157 crReturnV;
5158 }
5159 logevent("Server refused this port forwarding");
5160 } else {
5161 logevent("Remote port forwarding enabled");
5162 }
5163 }
5164 }
5165 }
5166 }
5167 }
5168
5169 /*
5170 * Potentially enable agent forwarding.
5171 */
5172 if (cfg.agentfwd && agent_exists()) {
5173 logevent("Requesting OpenSSH-style agent forwarding");
5174 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5175 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5176 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5177 ssh2_pkt_addbool(ssh, 1); /* want reply */
5178 ssh2_pkt_send(ssh);
5179
5180 do {
5181 crWaitUntilV(ispkt);
5182 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5183 unsigned i = ssh2_pkt_getuint32(ssh);
5184 struct ssh_channel *c;
5185 c = find234(ssh->channels, &i, ssh_channelfind);
5186 if (!c)
5187 continue; /* nonexistent channel */
5188 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5189 }
5190 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5191
5192 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5193 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5194 bombout(("Unexpected response to agent forwarding request:"
5195 " packet type %d", ssh->pktin.type));
5196 crReturnV;
5197 }
5198 logevent("Agent forwarding refused");
5199 } else {
5200 logevent("Agent forwarding enabled");
5201 ssh->agentfwd_enabled = TRUE;
5202 }
5203 }
5204
5205 /*
5206 * Now allocate a pty for the session.
5207 */
5208 if (!cfg.nopty) {
5209 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5210 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5211 ssh2_pkt_addstring(ssh, "pty-req");
5212 ssh2_pkt_addbool(ssh, 1); /* want reply */
5213 ssh2_pkt_addstring(ssh, cfg.termtype);
5214 ssh2_pkt_adduint32(ssh, ssh->term_width);
5215 ssh2_pkt_adduint32(ssh, ssh->term_height);
5216 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5217 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5218 ssh2_pkt_addstring_start(ssh);
5219 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5220 ssh2_pkt_send(ssh);
5221 ssh->state = SSH_STATE_INTERMED;
5222
5223 do {
5224 crWaitUntilV(ispkt);
5225 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5226 unsigned i = ssh2_pkt_getuint32(ssh);
5227 struct ssh_channel *c;
5228 c = find234(ssh->channels, &i, ssh_channelfind);
5229 if (!c)
5230 continue; /* nonexistent channel */
5231 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5232 }
5233 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5234
5235 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5236 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5237 bombout(("Unexpected response to pty request:"
5238 " packet type %d", ssh->pktin.type));
5239 crReturnV;
5240 }
5241 c_write_str(ssh, "Server refused to allocate pty\r\n");
5242 ssh->editing = ssh->echoing = 1;
5243 } else {
5244 logevent("Allocated pty");
5245 }
5246 } else {
5247 ssh->editing = ssh->echoing = 1;
5248 }
5249
5250 /*
5251 * Start a shell or a remote command. We may have to attempt
5252 * this twice if the config data has provided a second choice
5253 * of command.
5254 */
5255 while (1) {
5256 int subsys;
5257 char *cmd;
5258
5259 if (ssh->fallback_cmd) {
5260 subsys = cfg.ssh_subsys2;
5261 cmd = cfg.remote_cmd_ptr2;
5262 } else {
5263 subsys = cfg.ssh_subsys;
5264 cmd = cfg.remote_cmd_ptr;
5265 }
5266
5267 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5268 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5269 if (subsys) {
5270 ssh2_pkt_addstring(ssh, "subsystem");
5271 ssh2_pkt_addbool(ssh, 1); /* want reply */
5272 ssh2_pkt_addstring(ssh, cmd);
5273 } else if (*cmd) {
5274 ssh2_pkt_addstring(ssh, "exec");
5275 ssh2_pkt_addbool(ssh, 1); /* want reply */
5276 ssh2_pkt_addstring(ssh, cmd);
5277 } else {
5278 ssh2_pkt_addstring(ssh, "shell");
5279 ssh2_pkt_addbool(ssh, 1); /* want reply */
5280 }
5281 ssh2_pkt_send(ssh);
5282 do {
5283 crWaitUntilV(ispkt);
5284 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5285 unsigned i = ssh2_pkt_getuint32(ssh);
5286 struct ssh_channel *c;
5287 c = find234(ssh->channels, &i, ssh_channelfind);
5288 if (!c)
5289 continue; /* nonexistent channel */
5290 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5291 }
5292 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5293 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5294 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5295 bombout(("Unexpected response to shell/command request:"
5296 " packet type %d", ssh->pktin.type));
5297 crReturnV;
5298 }
5299 /*
5300 * We failed to start the command. If this is the
5301 * fallback command, we really are finished; if it's
5302 * not, and if the fallback command exists, try falling
5303 * back to it before complaining.
5304 */
5305 if (!ssh->fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5306 logevent("Primary command failed; attempting fallback");
5307 ssh->fallback_cmd = TRUE;
5308 continue;
5309 }
5310 bombout(("Server refused to start a shell/command"));
5311 crReturnV;
5312 } else {
5313 logevent("Started a shell/command");
5314 }
5315 break;
5316 }
5317
5318 ssh->state = SSH_STATE_SESSION;
5319 if (ssh->size_needed)
5320 ssh_size(ssh, ssh->term_width, ssh->term_height);
5321 if (ssh->eof_needed)
5322 ssh_special(ssh, TS_EOF);
5323
5324 /*
5325 * Transfer data!
5326 */
5327 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
5328 ssh->send_ok = 1;
5329 while (1) {
5330 crReturnV;
5331 s->try_send = FALSE;
5332 if (ispkt) {
5333 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5334 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5335 char *data;
5336 int length;
5337 unsigned i = ssh2_pkt_getuint32(ssh);
5338 struct ssh_channel *c;
5339 c = find234(ssh->channels, &i, ssh_channelfind);
5340 if (!c)
5341 continue; /* nonexistent channel */
5342 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5343 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
5344 continue; /* extended but not stderr */
5345 ssh2_pkt_getstring(ssh, &data, &length);
5346 if (data) {
5347 int bufsize;
5348 c->v.v2.locwindow -= length;
5349 switch (c->type) {
5350 case CHAN_MAINSESSION:
5351 bufsize =
5352 from_backend(ssh->frontend, ssh->pktin.type ==
5353 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5354 data, length);
5355 break;
5356 case CHAN_X11:
5357 bufsize = x11_send(c->u.x11.s, data, length);
5358 break;
5359 case CHAN_SOCKDATA:
5360 bufsize = pfd_send(c->u.pfd.s, data, length);
5361 break;
5362 case CHAN_AGENT:
5363 while (length > 0) {
5364 if (c->u.a.lensofar < 4) {
5365 int l = min(4 - c->u.a.lensofar, length);
5366 memcpy(c->u.a.msglen + c->u.a.lensofar,
5367 data, l);
5368 data += l;
5369 length -= l;
5370 c->u.a.lensofar += l;
5371 }
5372 if (c->u.a.lensofar == 4) {
5373 c->u.a.totallen =
5374 4 + GET_32BIT(c->u.a.msglen);
5375 c->u.a.message = smalloc(c->u.a.totallen);
5376 memcpy(c->u.a.message, c->u.a.msglen, 4);
5377 }
5378 if (c->u.a.lensofar >= 4 && length > 0) {
5379 int l =
5380 min(c->u.a.totallen - c->u.a.lensofar,
5381 length);
5382 memcpy(c->u.a.message + c->u.a.lensofar,
5383 data, l);
5384 data += l;
5385 length -= l;
5386 c->u.a.lensofar += l;
5387 }
5388 if (c->u.a.lensofar == c->u.a.totallen) {
5389 void *reply, *sentreply;
5390 int replylen;
5391 agent_query(c->u.a.message,
5392 c->u.a.totallen, &reply,
5393 &replylen);
5394 if (reply)
5395 sentreply = reply;
5396 else {
5397 /* Fake SSH_AGENT_FAILURE. */
5398 sentreply = "\0\0\0\1\5";
5399 replylen = 5;
5400 }
5401 ssh2_add_channel_data(c, sentreply, replylen);
5402 s->try_send = TRUE;
5403 if (reply)
5404 sfree(reply);
5405 sfree(c->u.a.message);
5406 c->u.a.lensofar = 0;
5407 }
5408 }
5409 bufsize = 0;
5410 break;
5411 }
5412 /*
5413 * If we are not buffering too much data,
5414 * enlarge the window again at the remote side.
5415 */
5416 if (bufsize < OUR_V2_WINSIZE)
5417 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5418 }
5419 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5420 unsigned i = ssh2_pkt_getuint32(ssh);
5421 struct ssh_channel *c;
5422
5423 c = find234(ssh->channels, &i, ssh_channelfind);
5424 if (!c)
5425 continue; /* nonexistent channel */
5426
5427 if (c->type == CHAN_X11) {
5428 /*
5429 * Remote EOF on an X11 channel means we should
5430 * wrap up and close the channel ourselves.
5431 */
5432 x11_close(c->u.x11.s);
5433 sshfwd_close(c);
5434 } else if (c->type == CHAN_AGENT) {
5435 sshfwd_close(c);
5436 } else if (c->type == CHAN_SOCKDATA) {
5437 pfd_close(c->u.pfd.s);
5438 sshfwd_close(c);
5439 }
5440 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5441 unsigned i = ssh2_pkt_getuint32(ssh);
5442 struct ssh_channel *c;
5443
5444 c = find234(ssh->channels, &i, ssh_channelfind);
5445 if (!c || ((int)c->remoteid) == -1) {
5446 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5447 c ? "half-open" : "nonexistent", i));
5448 }
5449 /* Do pre-close processing on the channel. */
5450 switch (c->type) {
5451 case CHAN_MAINSESSION:
5452 break; /* nothing to see here, move along */
5453 case CHAN_X11:
5454 if (c->u.x11.s != NULL)
5455 x11_close(c->u.x11.s);
5456 sshfwd_close(c);
5457 break;
5458 case CHAN_AGENT:
5459 sshfwd_close(c);
5460 break;
5461 case CHAN_SOCKDATA:
5462 if (c->u.pfd.s != NULL)
5463 pfd_close(c->u.pfd.s);
5464 sshfwd_close(c);
5465 break;
5466 }
5467 if (c->closes == 0) {
5468 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5469 ssh2_pkt_adduint32(ssh, c->remoteid);
5470 ssh2_pkt_send(ssh);
5471 }
5472 del234(ssh->channels, c);
5473 bufchain_clear(&c->v.v2.outbuffer);
5474 sfree(c);
5475
5476 /*
5477 * See if that was the last channel left open.
5478 */
5479 if (count234(ssh->channels) == 0) {
5480 #if 0
5481 /*
5482 * We used to send SSH_MSG_DISCONNECT here,
5483 * because I'd believed that _every_ conforming
5484 * SSH2 connection had to end with a disconnect
5485 * being sent by at least one side; apparently
5486 * I was wrong and it's perfectly OK to
5487 * unceremoniously slam the connection shut
5488 * when you're done, and indeed OpenSSH feels
5489 * this is more polite than sending a
5490 * DISCONNECT. So now we don't.
5491 */
5492 logevent("All channels closed. Disconnecting");
5493 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5494 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5495 ssh2_pkt_addstring(ssh, "All open channels closed");
5496 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5497 ssh2_pkt_send(ssh);
5498 #endif
5499 ssh->state = SSH_STATE_CLOSED;
5500 crReturnV;
5501 }
5502 continue; /* remote sends close; ignore (FIXME) */
5503 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5504 unsigned i = ssh2_pkt_getuint32(ssh);
5505 struct ssh_channel *c;
5506 c = find234(ssh->channels, &i, ssh_channelfind);
5507 if (!c)
5508 continue; /* nonexistent channel */
5509 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5510 s->try_send = TRUE;
5511 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5512 unsigned i = ssh2_pkt_getuint32(ssh);
5513 struct ssh_channel *c;
5514 c = find234(ssh->channels, &i, ssh_channelfind);
5515 if (!c)
5516 continue; /* nonexistent channel */
5517 if (c->type != CHAN_SOCKDATA_DORMANT)
5518 continue; /* dunno why they're confirming this */
5519 c->remoteid = ssh2_pkt_getuint32(ssh);
5520 c->type = CHAN_SOCKDATA;
5521 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5522 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5523 if (c->u.pfd.s)
5524 pfd_confirm(c->u.pfd.s);
5525 if (c->closes) {
5526 /*
5527 * We have a pending close on this channel,
5528 * which we decided on before the server acked
5529 * the channel open. So now we know the
5530 * remoteid, we can close it again.
5531 */
5532 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5533 ssh2_pkt_adduint32(ssh, c->remoteid);
5534 ssh2_pkt_send(ssh);
5535 }
5536 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5537 unsigned i = ssh2_pkt_getuint32(ssh);
5538 struct ssh_channel *c;
5539 c = find234(ssh->channels, &i, ssh_channelfind);
5540 if (!c)
5541 continue; /* nonexistent channel */
5542 if (c->type != CHAN_SOCKDATA_DORMANT)
5543 continue; /* dunno why they're failing this */
5544
5545 logevent("Forwarded connection refused by server");
5546
5547 pfd_close(c->u.pfd.s);
5548
5549 del234(ssh->channels, c);
5550 sfree(c);
5551 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5552 unsigned localid;
5553 char *type;
5554 int typelen, want_reply;
5555 struct ssh_channel *c;
5556
5557 localid = ssh2_pkt_getuint32(ssh);
5558 ssh2_pkt_getstring(ssh, &type, &typelen);
5559 want_reply = ssh2_pkt_getbool(ssh);
5560
5561 /*
5562 * First, check that the channel exists. Otherwise,
5563 * we can instantly disconnect with a rude message.
5564 */
5565 c = find234(ssh->channels, &localid, ssh_channelfind);
5566 if (!c) {
5567 char buf[80];
5568 sprintf(buf, "Received channel request for nonexistent"
5569 " channel %d", localid);
5570 logevent(buf);
5571 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5572 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5573 ssh2_pkt_addstring(ssh, buf);
5574 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5575 ssh2_pkt_send(ssh);
5576 connection_fatal("%s", buf);
5577 ssh->state = SSH_STATE_CLOSED;
5578 crReturnV;
5579 }
5580
5581 /*
5582 * Having got the channel number, we now look at
5583 * the request type string to see if it's something
5584 * we recognise.
5585 */
5586 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5587 c == ssh->mainchan) {
5588 /* We recognise "exit-status" on the primary channel. */
5589 char buf[100];
5590 ssh->exitcode = ssh2_pkt_getuint32(ssh);
5591 sprintf(buf, "Server sent command exit status %d",
5592 ssh->exitcode);
5593 logevent(buf);
5594 if (want_reply) {
5595 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5596 ssh2_pkt_adduint32(ssh, c->remoteid);
5597 ssh2_pkt_send(ssh);
5598 }
5599 } else {
5600 /*
5601 * This is a channel request we don't know
5602 * about, so we now either ignore the request
5603 * or respond with CHANNEL_FAILURE, depending
5604 * on want_reply.
5605 */
5606 if (want_reply) {
5607 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5608 ssh2_pkt_adduint32(ssh, c->remoteid);
5609 ssh2_pkt_send(ssh);
5610 }
5611 }
5612 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5613 char *type;
5614 int typelen, want_reply;
5615
5616 ssh2_pkt_getstring(ssh, &type, &typelen);
5617 want_reply = ssh2_pkt_getbool(ssh);
5618
5619 /*
5620 * We currently don't support any global requests
5621 * at all, so we either ignore the request or
5622 * respond with REQUEST_FAILURE, depending on
5623 * want_reply.
5624 */
5625 if (want_reply) {
5626 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5627 ssh2_pkt_send(ssh);
5628 }
5629 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5630 char *type;
5631 int typelen;
5632 char *error = NULL;
5633 struct ssh_channel *c;
5634 unsigned remid, winsize, pktsize;
5635 ssh2_pkt_getstring(ssh, &type, &typelen);
5636 c = smalloc(sizeof(struct ssh_channel));
5637 c->ssh = ssh;
5638
5639 remid = ssh2_pkt_getuint32(ssh);
5640 winsize = ssh2_pkt_getuint32(ssh);
5641 pktsize = ssh2_pkt_getuint32(ssh);
5642
5643 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5644 if (!ssh->X11_fwd_enabled)
5645 error = "X11 forwarding is not enabled";
5646 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5647 NULL) {
5648 error = "Unable to open an X11 connection";
5649 } else {
5650 c->type = CHAN_X11;
5651 }
5652 } else if (typelen == 15 &&
5653 !memcmp(type, "forwarded-tcpip", 15)) {
5654 struct ssh_rportfwd pf, *realpf;
5655 char *dummy;
5656 int dummylen;
5657 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5658 pf.sport = ssh2_pkt_getuint32(ssh);
5659 realpf = find234(ssh->rportfwds, &pf, NULL);
5660 if (realpf == NULL) {
5661 error = "Remote port is not recognised";
5662 } else {
5663 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5664 realpf->dport, c);
5665 char buf[1024];
5666 sprintf(buf, "Received remote port open request for %s:%d",
5667 realpf->dhost, realpf->dport);
5668 logevent(buf);
5669 if (e != NULL) {
5670 sprintf(buf, "Port open failed: %s", e);
5671 logevent(buf);
5672 error = "Port open failed";
5673 } else {
5674 logevent("Forwarded port opened successfully");
5675 c->type = CHAN_SOCKDATA;
5676 }
5677 }
5678 } else if (typelen == 22 &&
5679 !memcmp(type, "auth-agent@openssh.com", 3)) {
5680 if (!ssh->agentfwd_enabled)
5681 error = "Agent forwarding is not enabled";
5682 else {
5683 c->type = CHAN_AGENT; /* identify channel type */
5684 c->u.a.lensofar = 0;
5685 }
5686 } else {
5687 error = "Unsupported channel type requested";
5688 }
5689
5690 c->remoteid = remid;
5691 if (error) {
5692 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5693 ssh2_pkt_adduint32(ssh, c->remoteid);
5694 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5695 ssh2_pkt_addstring(ssh, error);
5696 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5697 ssh2_pkt_send(ssh);
5698 sfree(c);
5699 } else {
5700 c->localid = alloc_channel_id(ssh);
5701 c->closes = 0;
5702 c->v.v2.locwindow = OUR_V2_WINSIZE;
5703 c->v.v2.remwindow = winsize;
5704 c->v.v2.remmaxpkt = pktsize;
5705 bufchain_init(&c->v.v2.outbuffer);
5706 add234(ssh->channels, c);
5707 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5708 ssh2_pkt_adduint32(ssh, c->remoteid);
5709 ssh2_pkt_adduint32(ssh, c->localid);
5710 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5711 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5712 ssh2_pkt_send(ssh);
5713 }
5714 } else {
5715 bombout(("Strange packet received: type %d", ssh->pktin.type));
5716 crReturnV;
5717 }
5718 } else {
5719 /*
5720 * We have spare data. Add it to the channel buffer.
5721 */
5722 ssh2_add_channel_data(ssh->mainchan, in, inlen);
5723 s->try_send = TRUE;
5724 }
5725 if (s->try_send) {
5726 int i;
5727 struct ssh_channel *c;
5728 /*
5729 * Try to send data on all channels if we can.
5730 */
5731 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5732 int bufsize = ssh2_try_send(c);
5733 if (bufsize == 0) {
5734 switch (c->type) {
5735 case CHAN_MAINSESSION:
5736 /* stdin need not receive an unthrottle
5737 * notification since it will be polled */
5738 break;
5739 case CHAN_X11:
5740 x11_unthrottle(c->u.x11.s);
5741 break;
5742 case CHAN_AGENT:
5743 /* agent sockets are request/response and need no
5744 * buffer management */
5745 break;
5746 case CHAN_SOCKDATA:
5747 pfd_unthrottle(c->u.pfd.s);
5748 break;
5749 }
5750 }
5751 }
5752 }
5753 }
5754
5755 crFinishV;
5756 }
5757
5758 /*
5759 * Handle the top-level SSH2 protocol.
5760 */
5761 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
5762 {
5763 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
5764 return;
5765 do_ssh2_authconn(ssh, in, inlen, ispkt);
5766 }
5767
5768 /*
5769 * Called to set up the connection.
5770 *
5771 * Returns an error message, or NULL on success.
5772 */
5773 static char *ssh_init(void *frontend_handle, void **backend_handle,
5774 char *host, int port, char **realhost, int nodelay)
5775 {
5776 char *p;
5777 Ssh ssh;
5778
5779 ssh = smalloc(sizeof(*ssh));
5780 ssh->s = NULL;
5781 ssh->cipher = NULL;
5782 ssh->v1_cipher_ctx = NULL;
5783 ssh->cscipher = NULL;
5784 ssh->cs_cipher_ctx = NULL;
5785 ssh->sccipher = NULL;
5786 ssh->sc_cipher_ctx = NULL;
5787 ssh->csmac = NULL;
5788 ssh->scmac = NULL;
5789 ssh->cscomp = NULL;
5790 ssh->sccomp = NULL;
5791 ssh->kex = NULL;
5792 ssh->hostkey = NULL;
5793 ssh->exitcode = -1;
5794 ssh->state = SSH_STATE_PREPACKET;
5795 ssh->size_needed = FALSE;
5796 ssh->eof_needed = FALSE;
5797 {
5798 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5799 ssh->pktin = ssh->pktout = empty;
5800 }
5801 ssh->deferred_send_data = NULL;
5802 ssh->deferred_len = 0;
5803 ssh->deferred_size = 0;
5804 ssh->fallback_cmd = 0;
5805 ssh->pkt_ctx = 0;
5806 ssh->v2_outgoing_sequence = 0;
5807 ssh->ssh1_rdpkt_crstate = 0;
5808 ssh->ssh2_rdpkt_crstate = 0;
5809 ssh->do_ssh_init_crstate = 0;
5810 ssh->ssh_gotdata_crstate = 0;
5811 ssh->ssh1_protocol_crstate = 0;
5812 ssh->do_ssh1_login_crstate = 0;
5813 ssh->do_ssh2_transport_crstate = 0;
5814 ssh->do_ssh2_authconn_crstate = 0;
5815 ssh->do_ssh_init_state = NULL;
5816 ssh->do_ssh1_login_state = NULL;
5817 ssh->do_ssh2_transport_state = NULL;
5818 ssh->do_ssh2_authconn_state = NULL;
5819
5820 *backend_handle = ssh;
5821
5822 #ifdef MSCRYPTOAPI
5823 if (crypto_startup() == 0)
5824 return "Microsoft high encryption pack not installed!";
5825 #endif
5826
5827 ssh->frontend = frontend_handle;
5828 ssh->term_width = cfg.width;
5829 ssh->term_height = cfg.height;
5830
5831 ssh->send_ok = 0;
5832 ssh->editing = 0;
5833 ssh->echoing = 0;
5834 ssh->v1_throttle_count = 0;
5835 ssh->overall_bufsize = 0;
5836 ssh->fallback_cmd = 0;
5837
5838 p = connect_to_host(ssh, host, port, realhost, nodelay);
5839 if (p != NULL)
5840 return p;
5841
5842 return NULL;
5843 }
5844
5845 /*
5846 * Called to send data down the Telnet connection.
5847 */
5848 static int ssh_send(void *handle, char *buf, int len)
5849 {
5850 Ssh ssh = (Ssh) handle;
5851
5852 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5853 return 0;
5854
5855 ssh->protocol(ssh, buf, len, 0);
5856
5857 return ssh_sendbuffer(ssh);
5858 }
5859
5860 /*
5861 * Called to query the current amount of buffered stdin data.
5862 */
5863 static int ssh_sendbuffer(void *handle)
5864 {
5865 Ssh ssh = (Ssh) handle;
5866 int override_value;
5867
5868 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5869 return 0;
5870
5871 /*
5872 * If the SSH socket itself has backed up, add the total backup
5873 * size on that to any individual buffer on the stdin channel.
5874 */
5875 override_value = 0;
5876 if (ssh->throttled_all)
5877 override_value = ssh->overall_bufsize;
5878
5879 if (ssh->version == 1) {
5880 return override_value;
5881 } else if (ssh->version == 2) {
5882 if (!ssh->mainchan || ssh->mainchan->closes > 0)
5883 return override_value;
5884 else
5885 return (override_value +
5886 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5887 }
5888
5889 return 0;
5890 }
5891
5892 /*
5893 * Called to set the size of the window from SSH's POV.
5894 */
5895 static void ssh_size(void *handle, int width, int height)
5896 {
5897 Ssh ssh = (Ssh) handle;
5898
5899 ssh->term_width = width;
5900 ssh->term_height = height;
5901
5902 switch (ssh->state) {
5903 case SSH_STATE_BEFORE_SIZE:
5904 case SSH_STATE_PREPACKET:
5905 case SSH_STATE_CLOSED:
5906 break; /* do nothing */
5907 case SSH_STATE_INTERMED:
5908 ssh->size_needed = TRUE; /* buffer for later */
5909 break;
5910 case SSH_STATE_SESSION:
5911 if (!cfg.nopty) {
5912 if (!term)
5913 return;
5914 if (ssh->version == 1) {
5915 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
5916 PKT_INT, ssh->term_height,
5917 PKT_INT, ssh->term_width,
5918 PKT_INT, 0, PKT_INT, 0, PKT_END);
5919 } else {
5920 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5921 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5922 ssh2_pkt_addstring(ssh, "window-change");
5923 ssh2_pkt_addbool(ssh, 0);
5924 ssh2_pkt_adduint32(ssh, ssh->term_width);
5925 ssh2_pkt_adduint32(ssh, ssh->term_height);
5926 ssh2_pkt_adduint32(ssh, 0);
5927 ssh2_pkt_adduint32(ssh, 0);
5928 ssh2_pkt_send(ssh);
5929 }
5930 }
5931 break;
5932 }
5933 }
5934
5935 /*
5936 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5937 * can send an EOF and collect resulting output (e.g. `plink
5938 * hostname sort').
5939 */
5940 static void ssh_special(void *handle, Telnet_Special code)
5941 {
5942 Ssh ssh = (Ssh) handle;
5943
5944 if (code == TS_EOF) {
5945 if (ssh->state != SSH_STATE_SESSION) {
5946 /*
5947 * Buffer the EOF in case we are pre-SESSION, so we can
5948 * send it as soon as we reach SESSION.
5949 */
5950 if (code == TS_EOF)
5951 ssh->eof_needed = TRUE;
5952 return;
5953 }
5954 if (ssh->version == 1) {
5955 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
5956 } else {
5957 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
5958 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5959 ssh2_pkt_send(ssh);
5960 }
5961 logevent("Sent EOF message");
5962 } else if (code == TS_PING) {
5963 if (ssh->state == SSH_STATE_CLOSED
5964 || ssh->state == SSH_STATE_PREPACKET) return;
5965 if (ssh->version == 1) {
5966 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
5967 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5968 } else {
5969 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
5970 ssh2_pkt_addstring_start(ssh);
5971 ssh2_pkt_send(ssh);
5972 }
5973 } else {
5974 /* do nothing */
5975 }
5976 }
5977
5978 void *new_sock_channel(void *handle, Socket s)
5979 {
5980 Ssh ssh = (Ssh) handle;
5981 struct ssh_channel *c;
5982 c = smalloc(sizeof(struct ssh_channel));
5983 c->ssh = ssh;
5984
5985 if (c) {
5986 c->remoteid = -1; /* to be set when open confirmed */
5987 c->localid = alloc_channel_id(ssh);
5988 c->closes = 0;
5989 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5990 c->u.pfd.s = s;
5991 bufchain_init(&c->v.v2.outbuffer);
5992 add234(ssh->channels, c);
5993 }
5994 return c;
5995 }
5996
5997 /*
5998 * This is called when stdout/stderr (the entity to which
5999 * from_backend sends data) manages to clear some backlog.
6000 */
6001 void ssh_unthrottle(void *handle, int bufsize)
6002 {
6003 Ssh ssh = (Ssh) handle;
6004 if (ssh->version == 1) {
6005 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6006 ssh->v1_stdout_throttling = 0;
6007 ssh1_throttle(ssh, -1);
6008 }
6009 } else {
6010 if (ssh->mainchan && ssh->mainchan->closes == 0)
6011 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
6012 }
6013 }
6014
6015 void ssh_send_port_open(void *handle, void *channel, char *hostname,
6016 int port, char *org)
6017 {
6018 Ssh ssh = (Ssh) handle;
6019 struct ssh_channel *c = (struct ssh_channel *)channel;
6020 char buf[1024];
6021
6022 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
6023 logevent(buf);
6024
6025 if (ssh->version == 1) {
6026 send_packet(ssh, SSH1_MSG_PORT_OPEN,
6027 PKT_INT, c->localid,
6028 PKT_STR, hostname,
6029 PKT_INT, port,
6030 //PKT_STR, <org:orgport>,
6031 PKT_END);
6032 } else {
6033 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6034 ssh2_pkt_addstring(ssh, "direct-tcpip");
6035 ssh2_pkt_adduint32(ssh, c->localid);
6036 c->v.v2.locwindow = OUR_V2_WINSIZE;
6037 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6038 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6039 ssh2_pkt_addstring(ssh, hostname);
6040 ssh2_pkt_adduint32(ssh, port);
6041 /*
6042 * We make up values for the originator data; partly it's
6043 * too much hassle to keep track, and partly I'm not
6044 * convinced the server should be told details like that
6045 * about my local network configuration.
6046 */
6047 ssh2_pkt_addstring(ssh, "client-side-connection");
6048 ssh2_pkt_adduint32(ssh, 0);
6049 ssh2_pkt_send(ssh);
6050 }
6051 }
6052
6053
6054 static Socket ssh_socket(void *handle)
6055 {
6056 Ssh ssh = (Ssh) handle;
6057 return ssh->s;
6058 }
6059
6060 static int ssh_sendok(void *handle)
6061 {
6062 Ssh ssh = (Ssh) handle;
6063 return ssh->send_ok;
6064 }
6065
6066 static int ssh_ldisc(void *handle, int option)
6067 {
6068 Ssh ssh = (Ssh) handle;
6069 if (option == LD_ECHO)
6070 return ssh->echoing;
6071 if (option == LD_EDIT)
6072 return ssh->editing;
6073 return FALSE;
6074 }
6075
6076 static int ssh_return_exitcode(void *handle)
6077 {
6078 Ssh ssh = (Ssh) handle;
6079 return ssh->exitcode;
6080 }
6081
6082 /*
6083 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6084 * that fails. This variable is the means by which scp.c can reach
6085 * into the SSH code and find out which one it got.
6086 */
6087 extern int ssh_fallback_cmd(void *handle)
6088 {
6089 Ssh ssh = (Ssh) handle;
6090 return ssh->fallback_cmd;
6091 }
6092
6093 Backend ssh_backend = {
6094 ssh_init,
6095 ssh_send,
6096 ssh_sendbuffer,
6097 ssh_size,
6098 ssh_special,
6099 ssh_socket,
6100 ssh_return_exitcode,
6101 ssh_sendok,
6102 ssh_ldisc,
6103 ssh_unthrottle,
6104 22
6105 };