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