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