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