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