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