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