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