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