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