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