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