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