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