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