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