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