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