27 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
28 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
29 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
30 #define SSH1_CMSG_USER 4 /* 0x4 */
31 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
32 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
33 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
34 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
35 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
36 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
37 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
38 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
39 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
40 #define SSH1_SMSG_FAILURE 15 /* 0xf */
41 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
42 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
43 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
44 #define SSH1_CMSG_EOF 19 /* 0x13 */
45 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
46 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
47 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
48 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
49 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
50 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
51 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
52 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
53 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
54 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
55 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
56 #define SSH1_MSG_IGNORE 32 /* 0x20 */
57 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
58 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
59 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
60 #define SSH1_MSG_DEBUG 36 /* 0x24 */
61 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
62 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
63 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
64 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
65 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
66 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
67 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
69 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
70 #define SSH1_AUTH_RSA 2 /* 0x2 */
71 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
72 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
73 #define SSH1_AUTH_TIS 5 /* 0x5 */
74 #define SSH1_AUTH_CCARD 16 /* 0x10 */
76 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
77 /* Mask for protoflags we will echo back to server if seen */
78 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
91 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
92 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
93 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
94 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
95 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
96 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
97 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
98 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
99 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
100 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
101 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
102 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
103 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
104 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
105 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
106 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
107 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
108 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
109 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
110 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
111 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
112 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
113 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
114 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
115 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
116 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
117 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
118 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
119 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
120 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
121 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
122 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
123 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
124 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
138 SSH2_PKTCTX_PUBLICKEY
,
139 SSH2_PKTCTX_PASSWORD
,
144 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
145 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
146 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
147 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
148 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
149 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
150 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
151 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
152 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
153 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
154 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
155 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
156 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
157 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
158 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
160 static const char *const ssh2_disconnect_reasons
[] = {
162 "host not allowed to connect",
164 "key exchange failed",
165 "host authentication failed",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
179 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
180 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
181 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
182 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
184 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
187 * Various remote-bug flags.
189 #define BUG_CHOKES_ON_SSH1_IGNORE 1
190 #define BUG_SSH2_HMAC 2
191 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
192 #define BUG_CHOKES_ON_RSA 8
193 #define BUG_SSH2_RSA_PADDING 16
194 #define BUG_SSH2_DERIVEKEY 32
195 #define BUG_SSH2_REKEY 64
196 #define BUG_SSH2_PK_SESSIONID 128
197 #define BUG_SSH2_MAXPKT 256
198 #define BUG_CHOKES_ON_SSH2_IGNORE 512
199 #define BUG_CHOKES_ON_WINADJ 1024
202 * Codes for terminal modes.
203 * Most of these are the same in SSH-1 and SSH-2.
204 * This list is derived from RFC 4254 and
207 static const struct {
208 const char* const mode
;
210 enum { TTY_OP_CHAR
, TTY_OP_BOOL
} type
;
212 /* "V" prefix discarded for special characters relative to SSH specs */
213 { "INTR", 1, TTY_OP_CHAR
},
214 { "QUIT", 2, TTY_OP_CHAR
},
215 { "ERASE", 3, TTY_OP_CHAR
},
216 { "KILL", 4, TTY_OP_CHAR
},
217 { "EOF", 5, TTY_OP_CHAR
},
218 { "EOL", 6, TTY_OP_CHAR
},
219 { "EOL2", 7, TTY_OP_CHAR
},
220 { "START", 8, TTY_OP_CHAR
},
221 { "STOP", 9, TTY_OP_CHAR
},
222 { "SUSP", 10, TTY_OP_CHAR
},
223 { "DSUSP", 11, TTY_OP_CHAR
},
224 { "REPRINT", 12, TTY_OP_CHAR
},
225 { "WERASE", 13, TTY_OP_CHAR
},
226 { "LNEXT", 14, TTY_OP_CHAR
},
227 { "FLUSH", 15, TTY_OP_CHAR
},
228 { "SWTCH", 16, TTY_OP_CHAR
},
229 { "STATUS", 17, TTY_OP_CHAR
},
230 { "DISCARD", 18, TTY_OP_CHAR
},
231 { "IGNPAR", 30, TTY_OP_BOOL
},
232 { "PARMRK", 31, TTY_OP_BOOL
},
233 { "INPCK", 32, TTY_OP_BOOL
},
234 { "ISTRIP", 33, TTY_OP_BOOL
},
235 { "INLCR", 34, TTY_OP_BOOL
},
236 { "IGNCR", 35, TTY_OP_BOOL
},
237 { "ICRNL", 36, TTY_OP_BOOL
},
238 { "IUCLC", 37, TTY_OP_BOOL
},
239 { "IXON", 38, TTY_OP_BOOL
},
240 { "IXANY", 39, TTY_OP_BOOL
},
241 { "IXOFF", 40, TTY_OP_BOOL
},
242 { "IMAXBEL", 41, TTY_OP_BOOL
},
243 { "ISIG", 50, TTY_OP_BOOL
},
244 { "ICANON", 51, TTY_OP_BOOL
},
245 { "XCASE", 52, TTY_OP_BOOL
},
246 { "ECHO", 53, TTY_OP_BOOL
},
247 { "ECHOE", 54, TTY_OP_BOOL
},
248 { "ECHOK", 55, TTY_OP_BOOL
},
249 { "ECHONL", 56, TTY_OP_BOOL
},
250 { "NOFLSH", 57, TTY_OP_BOOL
},
251 { "TOSTOP", 58, TTY_OP_BOOL
},
252 { "IEXTEN", 59, TTY_OP_BOOL
},
253 { "ECHOCTL", 60, TTY_OP_BOOL
},
254 { "ECHOKE", 61, TTY_OP_BOOL
},
255 { "PENDIN", 62, TTY_OP_BOOL
}, /* XXX is this a real mode? */
256 { "OPOST", 70, TTY_OP_BOOL
},
257 { "OLCUC", 71, TTY_OP_BOOL
},
258 { "ONLCR", 72, TTY_OP_BOOL
},
259 { "OCRNL", 73, TTY_OP_BOOL
},
260 { "ONOCR", 74, TTY_OP_BOOL
},
261 { "ONLRET", 75, TTY_OP_BOOL
},
262 { "CS7", 90, TTY_OP_BOOL
},
263 { "CS8", 91, TTY_OP_BOOL
},
264 { "PARENB", 92, TTY_OP_BOOL
},
265 { "PARODD", 93, TTY_OP_BOOL
}
268 /* Miscellaneous other tty-related constants. */
269 #define SSH_TTY_OP_END 0
270 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
271 #define SSH1_TTY_OP_ISPEED 192
272 #define SSH1_TTY_OP_OSPEED 193
273 #define SSH2_TTY_OP_ISPEED 128
274 #define SSH2_TTY_OP_OSPEED 129
276 /* Helper functions for parsing tty-related config. */
277 static unsigned int ssh_tty_parse_specchar(char *s
)
282 ret
= ctrlparse(s
, &next
);
283 if (!next
) ret
= s
[0];
285 ret
= 255; /* special value meaning "don't set" */
289 static unsigned int ssh_tty_parse_boolean(char *s
)
291 if (stricmp(s
, "yes") == 0 ||
292 stricmp(s
, "on") == 0 ||
293 stricmp(s
, "true") == 0 ||
294 stricmp(s
, "+") == 0)
296 else if (stricmp(s
, "no") == 0 ||
297 stricmp(s
, "off") == 0 ||
298 stricmp(s
, "false") == 0 ||
299 stricmp(s
, "-") == 0)
300 return 0; /* false */
302 return (atoi(s
) != 0);
305 #define translate(x) if (type == x) return #x
306 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
307 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
308 static char *ssh1_pkt_type(int type
)
310 translate(SSH1_MSG_DISCONNECT
);
311 translate(SSH1_SMSG_PUBLIC_KEY
);
312 translate(SSH1_CMSG_SESSION_KEY
);
313 translate(SSH1_CMSG_USER
);
314 translate(SSH1_CMSG_AUTH_RSA
);
315 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
316 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
317 translate(SSH1_CMSG_AUTH_PASSWORD
);
318 translate(SSH1_CMSG_REQUEST_PTY
);
319 translate(SSH1_CMSG_WINDOW_SIZE
);
320 translate(SSH1_CMSG_EXEC_SHELL
);
321 translate(SSH1_CMSG_EXEC_CMD
);
322 translate(SSH1_SMSG_SUCCESS
);
323 translate(SSH1_SMSG_FAILURE
);
324 translate(SSH1_CMSG_STDIN_DATA
);
325 translate(SSH1_SMSG_STDOUT_DATA
);
326 translate(SSH1_SMSG_STDERR_DATA
);
327 translate(SSH1_CMSG_EOF
);
328 translate(SSH1_SMSG_EXIT_STATUS
);
329 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
330 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
331 translate(SSH1_MSG_CHANNEL_DATA
);
332 translate(SSH1_MSG_CHANNEL_CLOSE
);
333 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
334 translate(SSH1_SMSG_X11_OPEN
);
335 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
336 translate(SSH1_MSG_PORT_OPEN
);
337 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
338 translate(SSH1_SMSG_AGENT_OPEN
);
339 translate(SSH1_MSG_IGNORE
);
340 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
341 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
342 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
343 translate(SSH1_MSG_DEBUG
);
344 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
345 translate(SSH1_CMSG_AUTH_TIS
);
346 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
347 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
348 translate(SSH1_CMSG_AUTH_CCARD
);
349 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
350 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
353 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx
, Pkt_ACtx pkt_actx
, int type
)
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE
,SSH2_PKTCTX_GSSAPI
);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN
,SSH2_PKTCTX_GSSAPI
);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE
,SSH2_PKTCTX_GSSAPI
);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR
,SSH2_PKTCTX_GSSAPI
);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK
,SSH2_PKTCTX_GSSAPI
);
360 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC
, SSH2_PKTCTX_GSSAPI
);
361 translate(SSH2_MSG_DISCONNECT
);
362 translate(SSH2_MSG_IGNORE
);
363 translate(SSH2_MSG_UNIMPLEMENTED
);
364 translate(SSH2_MSG_DEBUG
);
365 translate(SSH2_MSG_SERVICE_REQUEST
);
366 translate(SSH2_MSG_SERVICE_ACCEPT
);
367 translate(SSH2_MSG_KEXINIT
);
368 translate(SSH2_MSG_NEWKEYS
);
369 translatek(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP
);
370 translatek(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP
);
371 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
372 translatek(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
373 translatek(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
374 translatek(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
375 translatek(SSH2_MSG_KEXRSA_PUBKEY
, SSH2_PKTCTX_RSAKEX
);
376 translatek(SSH2_MSG_KEXRSA_SECRET
, SSH2_PKTCTX_RSAKEX
);
377 translatek(SSH2_MSG_KEXRSA_DONE
, SSH2_PKTCTX_RSAKEX
);
378 translate(SSH2_MSG_USERAUTH_REQUEST
);
379 translate(SSH2_MSG_USERAUTH_FAILURE
);
380 translate(SSH2_MSG_USERAUTH_SUCCESS
);
381 translate(SSH2_MSG_USERAUTH_BANNER
);
382 translatea(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
383 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
384 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
385 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
386 translate(SSH2_MSG_GLOBAL_REQUEST
);
387 translate(SSH2_MSG_REQUEST_SUCCESS
);
388 translate(SSH2_MSG_REQUEST_FAILURE
);
389 translate(SSH2_MSG_CHANNEL_OPEN
);
390 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
391 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
392 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
393 translate(SSH2_MSG_CHANNEL_DATA
);
394 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
395 translate(SSH2_MSG_CHANNEL_EOF
);
396 translate(SSH2_MSG_CHANNEL_CLOSE
);
397 translate(SSH2_MSG_CHANNEL_REQUEST
);
398 translate(SSH2_MSG_CHANNEL_SUCCESS
);
399 translate(SSH2_MSG_CHANNEL_FAILURE
);
405 /* Enumeration values for fields in SSH-1 packets */
407 PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
,
408 /* These values are for communicating relevant semantics of
409 * fields to the packet logging code. */
410 PKTT_OTHER
, PKTT_PASSWORD
, PKTT_DATA
414 * Coroutine mechanics for the sillier bits of the code. If these
415 * macros look impenetrable to you, you might find it helpful to
418 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
420 * which explains the theory behind these macros.
422 * In particular, if you are getting `case expression not constant'
423 * errors when building with MS Visual Studio, this is because MS's
424 * Edit and Continue debugging feature causes their compiler to
425 * violate ANSI C. To disable Edit and Continue debugging:
427 * - right-click ssh.c in the FileView
429 * - select the C/C++ tab and the General category
430 * - under `Debug info:', select anything _other_ than `Program
431 * Database for Edit and Continue'.
433 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
434 #define crBeginState crBegin(s->crLine)
435 #define crStateP(t, v) \
437 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
439 #define crState(t) crStateP(t, ssh->t)
440 #define crFinish(z) } *crLine = 0; return (z); }
441 #define crFinishV } *crLine = 0; return; }
442 #define crFinishFree(z) } sfree(s); return (z); }
443 #define crFinishFreeV } sfree(s); return; }
444 #define crReturn(z) \
446 *crLine =__LINE__; return (z); case __LINE__:;\
450 *crLine=__LINE__; return; case __LINE__:;\
452 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
453 #define crStopV do{ *crLine = 0; return; }while(0)
454 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
455 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
457 typedef struct ssh_tag
*Ssh
;
460 static struct Packet
*ssh1_pkt_init(int pkt_type
);
461 static struct Packet
*ssh2_pkt_init(int pkt_type
);
462 static void ssh_pkt_ensure(struct Packet
*, int length
);
463 static void ssh_pkt_adddata(struct Packet
*, void *data
, int len
);
464 static void ssh_pkt_addbyte(struct Packet
*, unsigned char value
);
465 static void ssh2_pkt_addbool(struct Packet
*, unsigned char value
);
466 static void ssh_pkt_adduint32(struct Packet
*, unsigned long value
);
467 static void ssh_pkt_addstring_start(struct Packet
*);
468 static void ssh_pkt_addstring_str(struct Packet
*, char *data
);
469 static void ssh_pkt_addstring_data(struct Packet
*, char *data
, int len
);
470 static void ssh_pkt_addstring(struct Packet
*, char *data
);
471 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
472 static void ssh1_pkt_addmp(struct Packet
*, Bignum b
);
473 static void ssh2_pkt_addmp(struct Packet
*, Bignum b
);
474 static int ssh2_pkt_construct(Ssh
, struct Packet
*);
475 static void ssh2_pkt_send(Ssh
, struct Packet
*);
476 static void ssh2_pkt_send_noqueue(Ssh
, struct Packet
*);
477 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
478 struct Packet
*pktin
);
479 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
480 struct Packet
*pktin
);
481 static void ssh2_channel_check_close(struct ssh_channel
*c
);
482 static void ssh_channel_destroy(struct ssh_channel
*c
);
485 * Buffer management constants. There are several of these for
486 * various different purposes:
488 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
489 * on a local data stream before we throttle the whole SSH
490 * connection (in SSH-1 only). Throttling the whole connection is
491 * pretty drastic so we set this high in the hope it won't
494 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
495 * on the SSH connection itself before we defensively throttle
496 * _all_ local data streams. This is pretty drastic too (though
497 * thankfully unlikely in SSH-2 since the window mechanism should
498 * ensure that the server never has any need to throttle its end
499 * of the connection), so we set this high as well.
501 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
504 * - OUR_V2_BIGWIN is the window size we advertise for the only
505 * channel in a simple connection. It must be <= INT_MAX.
507 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
508 * to the remote side. This actually has nothing to do with the
509 * size of the _packet_, but is instead a limit on the amount
510 * of data we're willing to receive in a single SSH2 channel
513 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
514 * _packet_ we're prepared to cope with. It must be a multiple
515 * of the cipher block size, and must be at least 35000.
518 #define SSH1_BUFFER_LIMIT 32768
519 #define SSH_MAX_BACKLOG 32768
520 #define OUR_V2_WINSIZE 16384
521 #define OUR_V2_BIGWIN 0x7fffffff
522 #define OUR_V2_MAXPKT 0x4000UL
523 #define OUR_V2_PACKETLIMIT 0x9000UL
525 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
527 const static struct ssh_mac
*macs
[] = {
528 &ssh_hmac_sha1
, &ssh_hmac_sha1_96
, &ssh_hmac_md5
530 const static struct ssh_mac
*buggymacs
[] = {
531 &ssh_hmac_sha1_buggy
, &ssh_hmac_sha1_96_buggy
, &ssh_hmac_md5
534 static void *ssh_comp_none_init(void)
538 static void ssh_comp_none_cleanup(void *handle
)
541 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
542 unsigned char **outblock
, int *outlen
)
546 static int ssh_comp_none_disable(void *handle
)
550 const static struct ssh_compress ssh_comp_none
= {
552 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
553 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
554 ssh_comp_none_disable
, NULL
556 extern const struct ssh_compress ssh_zlib
;
557 const static struct ssh_compress
*compressions
[] = {
558 &ssh_zlib
, &ssh_comp_none
561 enum { /* channel types */
566 CHAN_SOCKDATA_DORMANT
, /* one the remote hasn't confirmed */
568 * CHAN_ZOMBIE is used to indicate a channel for which we've
569 * already destroyed the local data source: for instance, if a
570 * forwarded port experiences a socket error on the local side, we
571 * immediately destroy its local socket and turn the SSH channel
577 typedef void (*handler_fn_t
)(Ssh ssh
, struct Packet
*pktin
);
578 typedef void (*chandler_fn_t
)(Ssh ssh
, struct Packet
*pktin
, void *ctx
);
579 typedef void (*cchandler_fn_t
)(struct ssh_channel
*, struct Packet
*, void *);
582 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
585 struct outstanding_channel_request
{
586 cchandler_fn_t handler
;
588 struct outstanding_channel_request
*next
;
592 * little structure to keep track of outstanding WINDOW_ADJUSTs
600 * 2-3-4 tree storing channels.
603 Ssh ssh
; /* pointer back to main context */
604 unsigned remoteid
, localid
;
606 /* True if we opened this channel but server hasn't confirmed. */
609 * In SSH-1, this value contains four bits:
611 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
612 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
613 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
614 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
616 * A channel is completely finished with when all four bits are set.
618 * In SSH-2, the four bits mean:
620 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
621 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
622 * 4 We have received SSH2_MSG_CHANNEL_EOF.
623 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
625 * A channel is completely finished with when we have both sent
626 * and received CLOSE.
628 * The symbolic constants below use the SSH-2 terminology, which
629 * is a bit confusing in SSH-1, but we have to use _something_.
631 #define CLOSES_SENT_EOF 1
632 #define CLOSES_SENT_CLOSE 2
633 #define CLOSES_RCVD_EOF 4
634 #define CLOSES_RCVD_CLOSE 8
638 * This flag indicates that an EOF is pending on the outgoing side
639 * of the channel: that is, wherever we're getting the data for
640 * this channel has sent us some data followed by EOF. We can't
641 * actually send the EOF until we've finished sending the data, so
642 * we set this flag instead to remind us to do so once our buffer
648 * True if this channel is causing the underlying connection to be
653 struct ssh2_data_channel
{
655 unsigned remwindow
, remmaxpkt
;
656 /* locwindow is signed so we can cope with excess data. */
657 int locwindow
, locmaxwin
;
659 * remlocwin is the amount of local window that we think
660 * the remote end had available to it after it sent the
661 * last data packet or window adjust ack.
665 * These store the list of channel requests that haven't
668 struct outstanding_channel_request
*chanreq_head
, *chanreq_tail
;
669 enum { THROTTLED
, UNTHROTTLING
, UNTHROTTLED
} throttle_state
;
673 struct ssh_agent_channel
{
674 unsigned char *message
;
675 unsigned char msglen
[4];
676 unsigned lensofar
, totallen
;
678 struct ssh_x11_channel
{
681 struct ssh_pfd_channel
{
688 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
689 * use this structure in different ways, reflecting SSH-2's
690 * altogether saner approach to port forwarding.
692 * In SSH-1, you arrange a remote forwarding by sending the server
693 * the remote port number, and the local destination host:port.
694 * When a connection comes in, the server sends you back that
695 * host:port pair, and you connect to it. This is a ready-made
696 * security hole if you're not on the ball: a malicious server
697 * could send you back _any_ host:port pair, so if you trustingly
698 * connect to the address it gives you then you've just opened the
699 * entire inside of your corporate network just by connecting
700 * through it to a dodgy SSH server. Hence, we must store a list of
701 * host:port pairs we _are_ trying to forward to, and reject a
702 * connection request from the server if it's not in the list.
704 * In SSH-2, each side of the connection minds its own business and
705 * doesn't send unnecessary information to the other. You arrange a
706 * remote forwarding by sending the server just the remote port
707 * number. When a connection comes in, the server tells you which
708 * of its ports was connected to; and _you_ have to remember what
709 * local host:port pair went with that port number.
711 * Hence, in SSH-1 this structure is indexed by destination
712 * host:port pair, whereas in SSH-2 it is indexed by source port.
714 struct ssh_portfwd
; /* forward declaration */
716 struct ssh_rportfwd
{
717 unsigned sport
, dport
;
720 struct ssh_portfwd
*pfrec
;
722 #define free_rportfwd(pf) ( \
723 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
726 * Separately to the rportfwd tree (which is for looking up port
727 * open requests from the server), a tree of _these_ structures is
728 * used to keep track of all the currently open port forwardings,
729 * so that we can reconfigure in mid-session if the user requests
733 enum { DESTROY
, KEEP
, CREATE
} status
;
735 unsigned sport
, dport
;
738 struct ssh_rportfwd
*remote
;
742 #define free_portfwd(pf) ( \
743 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
744 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
747 long length
; /* length of `data' actually used */
748 long forcepad
; /* SSH-2: force padding to at least this length */
749 int type
; /* only used for incoming packets */
750 unsigned long sequence
; /* SSH-2 incoming sequence number */
751 unsigned char *data
; /* allocated storage */
752 unsigned char *body
; /* offset of payload within `data' */
753 long savedpos
; /* temporary index into `data' (for strings) */
754 long maxlen
; /* amount of storage allocated for `data' */
755 long encrypted_len
; /* for SSH-2 total-size counting */
758 * State associated with packet logging
762 struct logblank_t
*blanks
;
765 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
766 struct Packet
*pktin
);
767 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
768 struct Packet
*pktin
);
769 static void ssh1_protocol_setup(Ssh ssh
);
770 static void ssh2_protocol_setup(Ssh ssh
);
771 static void ssh_size(void *handle
, int width
, int height
);
772 static void ssh_special(void *handle
, Telnet_Special
);
773 static int ssh2_try_send(struct ssh_channel
*c
);
774 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
775 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
776 static void ssh2_set_window(struct ssh_channel
*c
, int newwin
);
777 static int ssh_sendbuffer(void *handle
);
778 static int ssh_do_close(Ssh ssh
, int notify_exit
);
779 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
);
780 static int ssh2_pkt_getbool(struct Packet
*pkt
);
781 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
);
782 static void ssh2_timer(void *ctx
, long now
);
783 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
784 struct Packet
*pktin
);
785 static void ssh2_msg_unexpected(Ssh ssh
, struct Packet
*pktin
);
787 struct rdpkt1_state_tag
{
788 long len
, pad
, biglen
, to_read
;
789 unsigned long realcrc
, gotcrc
;
793 struct Packet
*pktin
;
796 struct rdpkt2_state_tag
{
797 long len
, pad
, payload
, packetlen
, maclen
;
800 unsigned long incoming_sequence
;
801 struct Packet
*pktin
;
804 struct queued_handler
;
805 struct queued_handler
{
807 chandler_fn_t handler
;
809 struct queued_handler
*next
;
813 const struct plug_function_table
*fn
;
814 /* the above field _must_ be first in the structure */
824 unsigned char session_key
[32];
826 int v1_remote_protoflags
;
827 int v1_local_protoflags
;
828 int agentfwd_enabled
;
831 const struct ssh_cipher
*cipher
;
834 const struct ssh2_cipher
*cscipher
, *sccipher
;
835 void *cs_cipher_ctx
, *sc_cipher_ctx
;
836 const struct ssh_mac
*csmac
, *scmac
;
837 void *cs_mac_ctx
, *sc_mac_ctx
;
838 const struct ssh_compress
*cscomp
, *sccomp
;
839 void *cs_comp_ctx
, *sc_comp_ctx
;
840 const struct ssh_kex
*kex
;
841 const struct ssh_signkey
*hostkey
;
842 unsigned char v2_session_id
[SSH2_KEX_MAX_HASH_LEN
];
843 int v2_session_id_len
;
849 int echoing
, editing
;
853 int ospeed
, ispeed
; /* temporaries */
854 int term_width
, term_height
;
856 tree234
*channels
; /* indexed by local id */
857 struct ssh_channel
*mainchan
; /* primary session channel */
858 int ncmode
; /* is primary channel direct-tcpip? */
863 tree234
*rportfwds
, *portfwds
;
867 SSH_STATE_BEFORE_SIZE
,
873 int size_needed
, eof_needed
;
874 int sent_console_eof
;
875 int got_pty
; /* affects EOF behaviour on main channel */
877 struct Packet
**queue
;
878 int queuelen
, queuesize
;
880 unsigned char *deferred_send_data
;
881 int deferred_len
, deferred_size
;
884 * Gross hack: pscp will try to start SFTP but fall back to
885 * scp1 if that fails. This variable is the means by which
886 * scp.c can reach into the SSH code and find out which one it
891 bufchain banner
; /* accumulates banners during do_ssh2_authconn */
896 struct X11Display
*x11disp
;
899 int conn_throttle_count
;
902 int v1_stdout_throttling
;
903 unsigned long v2_outgoing_sequence
;
905 int ssh1_rdpkt_crstate
;
906 int ssh2_rdpkt_crstate
;
907 int ssh_gotdata_crstate
;
908 int do_ssh1_connection_crstate
;
910 void *do_ssh_init_state
;
911 void *do_ssh1_login_state
;
912 void *do_ssh2_transport_state
;
913 void *do_ssh2_authconn_state
;
915 struct rdpkt1_state_tag rdpkt1_state
;
916 struct rdpkt2_state_tag rdpkt2_state
;
918 /* SSH-1 and SSH-2 use this for different things, but both use it */
919 int protocol_initial_phase_done
;
921 void (*protocol
) (Ssh ssh
, void *vin
, int inlen
,
923 struct Packet
*(*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
926 * We maintain our own copy of a Conf structure here. That way,
927 * when we're passed a new one for reconfiguration, we can check
928 * the differences and potentially reconfigure port forwardings
929 * etc in mid-session.
934 * Values cached out of conf so as to avoid the tree234 lookup
935 * cost every time they're used.
940 * Dynamically allocated username string created during SSH
941 * login. Stored in here rather than in the coroutine state so
942 * that it'll be reliably freed if we shut down the SSH session
943 * at some unexpected moment.
948 * Used to transfer data back from async callbacks.
950 void *agent_response
;
951 int agent_response_len
;
955 * The SSH connection can be set as `frozen', meaning we are
956 * not currently accepting incoming data from the network. This
957 * is slightly more serious than setting the _socket_ as
958 * frozen, because we may already have had data passed to us
959 * from the network which we need to delay processing until
960 * after the freeze is lifted, so we also need a bufchain to
964 bufchain queued_incoming_data
;
967 * Dispatch table for packet types that we may have to deal
970 handler_fn_t packet_dispatch
[256];
973 * Queues of one-off handler functions for success/failure
974 * indications from a request.
976 struct queued_handler
*qhead
, *qtail
;
977 handler_fn_t q_saved_handler1
, q_saved_handler2
;
980 * This module deals with sending keepalives.
985 * Track incoming and outgoing data sizes and time, for
988 unsigned long incoming_data_size
, outgoing_data_size
, deferred_data_size
;
989 unsigned long max_data_size
;
991 long next_rekey
, last_rekey
;
992 char *deferred_rekey_reason
; /* points to STATIC string; don't free */
995 * Fully qualified host name, which we need if doing GSSAPI.
1001 * GSSAPI libraries for this session.
1003 struct ssh_gss_liblist
*gsslibs
;
1007 #define logevent(s) logevent(ssh->frontend, s)
1009 /* logevent, only printf-formatted. */
1010 static void logeventf(Ssh ssh
, const char *fmt
, ...)
1016 buf
= dupvprintf(fmt
, ap
);
1022 #define bombout(msg) \
1024 char *text = dupprintf msg; \
1025 ssh_do_close(ssh, FALSE); \
1027 connection_fatal(ssh->frontend, "%s", text); \
1031 /* Functions to leave bits out of the SSH packet log file. */
1033 static void dont_log_password(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
1035 if (conf_get_int(ssh
->conf
, CONF_logomitpass
))
1036 pkt
->logmode
= blanktype
;
1039 static void dont_log_data(Ssh ssh
, struct Packet
*pkt
, int blanktype
)
1041 if (ssh
->logomitdata
)
1042 pkt
->logmode
= blanktype
;
1045 static void end_log_omission(Ssh ssh
, struct Packet
*pkt
)
1047 pkt
->logmode
= PKTLOG_EMIT
;
1050 /* Helper function for common bits of parsing ttymodes. */
1051 static void parse_ttymodes(Ssh ssh
,
1052 void (*do_mode
)(void *data
, char *mode
, char *val
),
1057 for (val
= conf_get_str_strs(ssh
->conf
, CONF_ttymodes
, NULL
, &key
);
1059 val
= conf_get_str_strs(ssh
->conf
, CONF_ttymodes
, key
, &key
)) {
1061 * val[0] is either 'V', indicating that an explicit value
1062 * follows it, or 'A' indicating that we should pass the
1063 * value through from the local environment via get_ttymode.
1065 if (val
[0] == 'A') {
1066 val
= get_ttymode(ssh
->frontend
, key
);
1068 do_mode(data
, key
, val
);
1072 do_mode(data
, key
, val
+ 1); /* skip the 'V' */
1076 static int ssh_channelcmp(void *av
, void *bv
)
1078 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
1079 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
1080 if (a
->localid
< b
->localid
)
1082 if (a
->localid
> b
->localid
)
1086 static int ssh_channelfind(void *av
, void *bv
)
1088 unsigned *a
= (unsigned *) av
;
1089 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
1090 if (*a
< b
->localid
)
1092 if (*a
> b
->localid
)
1097 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
1099 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
1100 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
1102 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
1103 return i
< 0 ?
-1 : +1;
1104 if (a
->dport
> b
->dport
)
1106 if (a
->dport
< b
->dport
)
1111 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
1113 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
1114 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
1116 if (a
->sport
> b
->sport
)
1118 if (a
->sport
< b
->sport
)
1124 * Special form of strcmp which can cope with NULL inputs. NULL is
1125 * defined to sort before even the empty string.
1127 static int nullstrcmp(const char *a
, const char *b
)
1129 if (a
== NULL
&& b
== NULL
)
1135 return strcmp(a
, b
);
1138 static int ssh_portcmp(void *av
, void *bv
)
1140 struct ssh_portfwd
*a
= (struct ssh_portfwd
*) av
;
1141 struct ssh_portfwd
*b
= (struct ssh_portfwd
*) bv
;
1143 if (a
->type
> b
->type
)
1145 if (a
->type
< b
->type
)
1147 if (a
->addressfamily
> b
->addressfamily
)
1149 if (a
->addressfamily
< b
->addressfamily
)
1151 if ( (i
= nullstrcmp(a
->saddr
, b
->saddr
)) != 0)
1152 return i
< 0 ?
-1 : +1;
1153 if (a
->sport
> b
->sport
)
1155 if (a
->sport
< b
->sport
)
1157 if (a
->type
!= 'D') {
1158 if ( (i
= nullstrcmp(a
->daddr
, b
->daddr
)) != 0)
1159 return i
< 0 ?
-1 : +1;
1160 if (a
->dport
> b
->dport
)
1162 if (a
->dport
< b
->dport
)
1168 static int alloc_channel_id(Ssh ssh
)
1170 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
1171 unsigned low
, high
, mid
;
1173 struct ssh_channel
*c
;
1176 * First-fit allocation of channel numbers: always pick the
1177 * lowest unused one. To do this, binary-search using the
1178 * counted B-tree to find the largest channel ID which is in a
1179 * contiguous sequence from the beginning. (Precisely
1180 * everything in that sequence must have ID equal to its tree
1181 * index plus CHANNEL_NUMBER_OFFSET.)
1183 tsize
= count234(ssh
->channels
);
1187 while (high
- low
> 1) {
1188 mid
= (high
+ low
) / 2;
1189 c
= index234(ssh
->channels
, mid
);
1190 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
1191 low
= mid
; /* this one is fine */
1193 high
= mid
; /* this one is past it */
1196 * Now low points to either -1, or the tree index of the
1197 * largest ID in the initial sequence.
1200 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1201 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
1203 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
1206 static void c_write_stderr(int trusted
, const char *buf
, int len
)
1209 for (i
= 0; i
< len
; i
++)
1210 if (buf
[i
] != '\r' && (trusted
|| buf
[i
] == '\n' || (buf
[i
] & 0x60)))
1211 fputc(buf
[i
], stderr
);
1214 static void c_write(Ssh ssh
, const char *buf
, int len
)
1216 if (flags
& FLAG_STDERR
)
1217 c_write_stderr(1, buf
, len
);
1219 from_backend(ssh
->frontend
, 1, buf
, len
);
1222 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
1224 if (flags
& FLAG_STDERR
)
1225 c_write_stderr(0, buf
, len
);
1227 from_backend_untrusted(ssh
->frontend
, buf
, len
);
1230 static void c_write_str(Ssh ssh
, const char *buf
)
1232 c_write(ssh
, buf
, strlen(buf
));
1235 static void ssh_free_packet(struct Packet
*pkt
)
1240 static struct Packet
*ssh_new_packet(void)
1242 struct Packet
*pkt
= snew(struct Packet
);
1244 pkt
->body
= pkt
->data
= NULL
;
1246 pkt
->logmode
= PKTLOG_EMIT
;
1254 * Collect incoming data in the incoming packet buffer.
1255 * Decipher and verify the packet when it is completely read.
1256 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1257 * Update the *data and *datalen variables.
1258 * Return a Packet structure when a packet is completed.
1260 static struct Packet
*ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1262 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
1264 crBegin(ssh
->ssh1_rdpkt_crstate
);
1266 st
->pktin
= ssh_new_packet();
1268 st
->pktin
->type
= 0;
1269 st
->pktin
->length
= 0;
1271 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
1272 while ((*datalen
) == 0)
1274 st
->len
= (st
->len
<< 8) + **data
;
1275 (*data
)++, (*datalen
)--;
1278 st
->pad
= 8 - (st
->len
% 8);
1279 st
->biglen
= st
->len
+ st
->pad
;
1280 st
->pktin
->length
= st
->len
- 5;
1282 if (st
->biglen
< 0) {
1283 bombout(("Extremely large packet length from server suggests"
1284 " data stream corruption"));
1285 ssh_free_packet(st
->pktin
);
1289 st
->pktin
->maxlen
= st
->biglen
;
1290 st
->pktin
->data
= snewn(st
->biglen
+ APIEXTRA
, unsigned char);
1292 st
->to_read
= st
->biglen
;
1293 st
->p
= st
->pktin
->data
;
1294 while (st
->to_read
> 0) {
1295 st
->chunk
= st
->to_read
;
1296 while ((*datalen
) == 0)
1298 if (st
->chunk
> (*datalen
))
1299 st
->chunk
= (*datalen
);
1300 memcpy(st
->p
, *data
, st
->chunk
);
1302 *datalen
-= st
->chunk
;
1304 st
->to_read
-= st
->chunk
;
1307 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, st
->pktin
->data
,
1308 st
->biglen
, NULL
)) {
1309 bombout(("Network attack (CRC compensation) detected!"));
1310 ssh_free_packet(st
->pktin
);
1315 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, st
->pktin
->data
, st
->biglen
);
1317 st
->realcrc
= crc32_compute(st
->pktin
->data
, st
->biglen
- 4);
1318 st
->gotcrc
= GET_32BIT(st
->pktin
->data
+ st
->biglen
- 4);
1319 if (st
->gotcrc
!= st
->realcrc
) {
1320 bombout(("Incorrect CRC received on packet"));
1321 ssh_free_packet(st
->pktin
);
1325 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1326 st
->pktin
->savedpos
= 0;
1328 if (ssh
->v1_compressing
) {
1329 unsigned char *decompblk
;
1331 if (!zlib_decompress_block(ssh
->sc_comp_ctx
,
1332 st
->pktin
->body
- 1, st
->pktin
->length
+ 1,
1333 &decompblk
, &decomplen
)) {
1334 bombout(("Zlib decompression encountered invalid data"));
1335 ssh_free_packet(st
->pktin
);
1339 if (st
->pktin
->maxlen
< st
->pad
+ decomplen
) {
1340 st
->pktin
->maxlen
= st
->pad
+ decomplen
;
1341 st
->pktin
->data
= sresize(st
->pktin
->data
,
1342 st
->pktin
->maxlen
+ APIEXTRA
,
1344 st
->pktin
->body
= st
->pktin
->data
+ st
->pad
+ 1;
1347 memcpy(st
->pktin
->body
- 1, decompblk
, decomplen
);
1349 st
->pktin
->length
= decomplen
- 1;
1352 st
->pktin
->type
= st
->pktin
->body
[-1];
1355 * Log incoming packet, possibly omitting sensitive fields.
1359 struct logblank_t blank
;
1360 if (ssh
->logomitdata
) {
1361 int do_blank
= FALSE
, blank_prefix
= 0;
1362 /* "Session data" packets - omit the data field */
1363 if ((st
->pktin
->type
== SSH1_SMSG_STDOUT_DATA
) ||
1364 (st
->pktin
->type
== SSH1_SMSG_STDERR_DATA
)) {
1365 do_blank
= TRUE
; blank_prefix
= 4;
1366 } else if (st
->pktin
->type
== SSH1_MSG_CHANNEL_DATA
) {
1367 do_blank
= TRUE
; blank_prefix
= 8;
1370 blank
.offset
= blank_prefix
;
1371 blank
.len
= st
->pktin
->length
;
1372 blank
.type
= PKTLOG_OMIT
;
1376 log_packet(ssh
->logctx
,
1377 PKT_INCOMING
, st
->pktin
->type
,
1378 ssh1_pkt_type(st
->pktin
->type
),
1379 st
->pktin
->body
, st
->pktin
->length
,
1380 nblanks
, &blank
, NULL
);
1383 crFinish(st
->pktin
);
1386 static struct Packet
*ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
1388 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
1390 crBegin(ssh
->ssh2_rdpkt_crstate
);
1392 st
->pktin
= ssh_new_packet();
1394 st
->pktin
->type
= 0;
1395 st
->pktin
->length
= 0;
1397 st
->cipherblk
= ssh
->sccipher
->blksize
;
1400 if (st
->cipherblk
< 8)
1402 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
1404 if (ssh
->sccipher
&& (ssh
->sccipher
->flags
& SSH_CIPHER_IS_CBC
) &&
1407 * When dealing with a CBC-mode cipher, we want to avoid the
1408 * possibility of an attacker's tweaking the ciphertext stream
1409 * so as to cause us to feed the same block to the block
1410 * cipher more than once and thus leak information
1411 * (VU#958563). The way we do this is not to take any
1412 * decisions on the basis of anything we've decrypted until
1413 * we've verified it with a MAC. That includes the packet
1414 * length, so we just read data and check the MAC repeatedly,
1415 * and when the MAC passes, see if the length we've got is
1419 /* May as well allocate the whole lot now. */
1420 st
->pktin
->data
= snewn(OUR_V2_PACKETLIMIT
+ st
->maclen
+ APIEXTRA
,
1423 /* Read an amount corresponding to the MAC. */
1424 for (st
->i
= 0; st
->i
< st
->maclen
; st
->i
++) {
1425 while ((*datalen
) == 0)
1427 st
->pktin
->data
[st
->i
] = *(*data
)++;
1433 unsigned char seq
[4];
1434 ssh
->scmac
->start(ssh
->sc_mac_ctx
);
1435 PUT_32BIT(seq
, st
->incoming_sequence
);
1436 ssh
->scmac
->bytes(ssh
->sc_mac_ctx
, seq
, 4);
1439 for (;;) { /* Once around this loop per cipher block. */
1440 /* Read another cipher-block's worth, and tack it onto the end. */
1441 for (st
->i
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1442 while ((*datalen
) == 0)
1444 st
->pktin
->data
[st
->packetlen
+st
->maclen
+st
->i
] = *(*data
)++;
1447 /* Decrypt one more block (a little further back in the stream). */
1448 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1449 st
->pktin
->data
+ st
->packetlen
,
1451 /* Feed that block to the MAC. */
1452 ssh
->scmac
->bytes(ssh
->sc_mac_ctx
,
1453 st
->pktin
->data
+ st
->packetlen
, st
->cipherblk
);
1454 st
->packetlen
+= st
->cipherblk
;
1455 /* See if that gives us a valid packet. */
1456 if (ssh
->scmac
->verresult(ssh
->sc_mac_ctx
,
1457 st
->pktin
->data
+ st
->packetlen
) &&
1458 (st
->len
= GET_32BIT(st
->pktin
->data
)) + 4 == st
->packetlen
)
1460 if (st
->packetlen
>= OUR_V2_PACKETLIMIT
) {
1461 bombout(("No valid incoming packet found"));
1462 ssh_free_packet(st
->pktin
);
1466 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1467 st
->pktin
->data
= sresize(st
->pktin
->data
,
1468 st
->pktin
->maxlen
+ APIEXTRA
,
1471 st
->pktin
->data
= snewn(st
->cipherblk
+ APIEXTRA
, unsigned char);
1474 * Acquire and decrypt the first block of the packet. This will
1475 * contain the length and padding details.
1477 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
1478 while ((*datalen
) == 0)
1480 st
->pktin
->data
[st
->i
] = *(*data
)++;
1485 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1486 st
->pktin
->data
, st
->cipherblk
);
1489 * Now get the length figure.
1491 st
->len
= GET_32BIT(st
->pktin
->data
);
1494 * _Completely_ silly lengths should be stomped on before they
1495 * do us any more damage.
1497 if (st
->len
< 0 || st
->len
> OUR_V2_PACKETLIMIT
||
1498 (st
->len
+ 4) % st
->cipherblk
!= 0) {
1499 bombout(("Incoming packet was garbled on decryption"));
1500 ssh_free_packet(st
->pktin
);
1505 * So now we can work out the total packet length.
1507 st
->packetlen
= st
->len
+ 4;
1510 * Allocate memory for the rest of the packet.
1512 st
->pktin
->maxlen
= st
->packetlen
+ st
->maclen
;
1513 st
->pktin
->data
= sresize(st
->pktin
->data
,
1514 st
->pktin
->maxlen
+ APIEXTRA
,
1518 * Read and decrypt the remainder of the packet.
1520 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1522 while ((*datalen
) == 0)
1524 st
->pktin
->data
[st
->i
] = *(*data
)++;
1527 /* Decrypt everything _except_ the MAC. */
1529 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1530 st
->pktin
->data
+ st
->cipherblk
,
1531 st
->packetlen
- st
->cipherblk
);
1537 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, st
->pktin
->data
,
1538 st
->len
+ 4, st
->incoming_sequence
)) {
1539 bombout(("Incorrect MAC received on packet"));
1540 ssh_free_packet(st
->pktin
);
1544 /* Get and sanity-check the amount of random padding. */
1545 st
->pad
= st
->pktin
->data
[4];
1546 if (st
->pad
< 4 || st
->len
- st
->pad
< 1) {
1547 bombout(("Invalid padding length on received packet"));
1548 ssh_free_packet(st
->pktin
);
1552 * This enables us to deduce the payload length.
1554 st
->payload
= st
->len
- st
->pad
- 1;
1556 st
->pktin
->length
= st
->payload
+ 5;
1557 st
->pktin
->encrypted_len
= st
->packetlen
;
1559 st
->pktin
->sequence
= st
->incoming_sequence
++;
1562 * Decompress packet payload.
1565 unsigned char *newpayload
;
1568 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1569 st
->pktin
->data
+ 5, st
->pktin
->length
- 5,
1570 &newpayload
, &newlen
)) {
1571 if (st
->pktin
->maxlen
< newlen
+ 5) {
1572 st
->pktin
->maxlen
= newlen
+ 5;
1573 st
->pktin
->data
= sresize(st
->pktin
->data
,
1574 st
->pktin
->maxlen
+ APIEXTRA
,
1577 st
->pktin
->length
= 5 + newlen
;
1578 memcpy(st
->pktin
->data
+ 5, newpayload
, newlen
);
1583 st
->pktin
->savedpos
= 6;
1584 st
->pktin
->body
= st
->pktin
->data
;
1585 st
->pktin
->type
= st
->pktin
->data
[5];
1588 * Log incoming packet, possibly omitting sensitive fields.
1592 struct logblank_t blank
;
1593 if (ssh
->logomitdata
) {
1594 int do_blank
= FALSE
, blank_prefix
= 0;
1595 /* "Session data" packets - omit the data field */
1596 if (st
->pktin
->type
== SSH2_MSG_CHANNEL_DATA
) {
1597 do_blank
= TRUE
; blank_prefix
= 8;
1598 } else if (st
->pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
1599 do_blank
= TRUE
; blank_prefix
= 12;
1602 blank
.offset
= blank_prefix
;
1603 blank
.len
= (st
->pktin
->length
-6) - blank_prefix
;
1604 blank
.type
= PKTLOG_OMIT
;
1608 log_packet(ssh
->logctx
, PKT_INCOMING
, st
->pktin
->type
,
1609 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
,
1611 st
->pktin
->data
+6, st
->pktin
->length
-6,
1612 nblanks
, &blank
, &st
->pktin
->sequence
);
1615 crFinish(st
->pktin
);
1618 static int s_wrpkt_prepare(Ssh ssh
, struct Packet
*pkt
, int *offset_p
)
1620 int pad
, biglen
, i
, pktoffs
;
1624 * XXX various versions of SC (including 8.8.4) screw up the
1625 * register allocation in this function and use the same register
1626 * (D6) for len and as a temporary, with predictable results. The
1627 * following sledgehammer prevents this.
1634 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[12],
1635 ssh1_pkt_type(pkt
->data
[12]),
1636 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1637 pkt
->nblanks
, pkt
->blanks
, NULL
);
1638 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1641 if (ssh
->v1_compressing
) {
1642 unsigned char *compblk
;
1644 zlib_compress_block(ssh
->cs_comp_ctx
,
1645 pkt
->data
+ 12, pkt
->length
- 12,
1646 &compblk
, &complen
);
1647 ssh_pkt_ensure(pkt
, complen
+ 2); /* just in case it's got bigger */
1648 memcpy(pkt
->data
+ 12, compblk
, complen
);
1650 pkt
->length
= complen
+ 12;
1653 ssh_pkt_ensure(pkt
, pkt
->length
+ 4); /* space for CRC */
1655 len
= pkt
->length
- 4 - 8; /* len(type+data+CRC) */
1656 pad
= 8 - (len
% 8);
1658 biglen
= len
+ pad
; /* len(padding+type+data+CRC) */
1660 for (i
= pktoffs
; i
< 4+8; i
++)
1661 pkt
->data
[i
] = random_byte();
1662 crc
= crc32_compute(pkt
->data
+ pktoffs
+ 4, biglen
- 4); /* all ex len */
1663 PUT_32BIT(pkt
->data
+ pktoffs
+ 4 + biglen
- 4, crc
);
1664 PUT_32BIT(pkt
->data
+ pktoffs
, len
);
1667 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
,
1668 pkt
->data
+ pktoffs
+ 4, biglen
);
1670 if (offset_p
) *offset_p
= pktoffs
;
1671 return biglen
+ 4; /* len(length+padding+type+data+CRC) */
1674 static int s_write(Ssh ssh
, void *data
, int len
)
1677 log_packet(ssh
->logctx
, PKT_OUTGOING
, -1, NULL
, data
, len
,
1679 return sk_write(ssh
->s
, (char *)data
, len
);
1682 static void s_wrpkt(Ssh ssh
, struct Packet
*pkt
)
1684 int len
, backlog
, offset
;
1685 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1686 backlog
= s_write(ssh
, pkt
->data
+ offset
, len
);
1687 if (backlog
> SSH_MAX_BACKLOG
)
1688 ssh_throttle_all(ssh
, 1, backlog
);
1689 ssh_free_packet(pkt
);
1692 static void s_wrpkt_defer(Ssh ssh
, struct Packet
*pkt
)
1695 len
= s_wrpkt_prepare(ssh
, pkt
, &offset
);
1696 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1697 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1698 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
1702 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
,
1703 pkt
->data
+ offset
, len
);
1704 ssh
->deferred_len
+= len
;
1705 ssh_free_packet(pkt
);
1709 * Construct a SSH-1 packet with the specified contents.
1710 * (This all-at-once interface used to be the only one, but now SSH-1
1711 * packets can also be constructed incrementally.)
1713 static struct Packet
*construct_packet(Ssh ssh
, int pkttype
, va_list ap
)
1719 pkt
= ssh1_pkt_init(pkttype
);
1721 while ((argtype
= va_arg(ap
, int)) != PKT_END
) {
1722 unsigned char *argp
, argchar
;
1724 unsigned long argint
;
1727 /* Actual fields in the packet */
1729 argint
= va_arg(ap
, int);
1730 ssh_pkt_adduint32(pkt
, argint
);
1733 argchar
= (unsigned char) va_arg(ap
, int);
1734 ssh_pkt_addbyte(pkt
, argchar
);
1737 argp
= va_arg(ap
, unsigned char *);
1738 arglen
= va_arg(ap
, int);
1739 ssh_pkt_adddata(pkt
, argp
, arglen
);
1742 sargp
= va_arg(ap
, char *);
1743 ssh_pkt_addstring(pkt
, sargp
);
1746 bn
= va_arg(ap
, Bignum
);
1747 ssh1_pkt_addmp(pkt
, bn
);
1749 /* Tokens for modifications to packet logging */
1751 dont_log_password(ssh
, pkt
, PKTLOG_BLANK
);
1754 dont_log_data(ssh
, pkt
, PKTLOG_OMIT
);
1757 end_log_omission(ssh
, pkt
);
1765 static void send_packet(Ssh ssh
, int pkttype
, ...)
1769 va_start(ap
, pkttype
);
1770 pkt
= construct_packet(ssh
, pkttype
, ap
);
1775 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1779 va_start(ap
, pkttype
);
1780 pkt
= construct_packet(ssh
, pkttype
, ap
);
1782 s_wrpkt_defer(ssh
, pkt
);
1785 static int ssh_versioncmp(char *a
, char *b
)
1788 unsigned long av
, bv
;
1790 av
= strtoul(a
, &ae
, 10);
1791 bv
= strtoul(b
, &be
, 10);
1793 return (av
< bv ?
-1 : +1);
1798 av
= strtoul(ae
, &ae
, 10);
1799 bv
= strtoul(be
, &be
, 10);
1801 return (av
< bv ?
-1 : +1);
1806 * Utility routines for putting an SSH-protocol `string' and
1807 * `uint32' into a hash state.
1809 static void hash_string(const struct ssh_hash
*h
, void *s
, void *str
, int len
)
1811 unsigned char lenblk
[4];
1812 PUT_32BIT(lenblk
, len
);
1813 h
->bytes(s
, lenblk
, 4);
1814 h
->bytes(s
, str
, len
);
1817 static void hash_uint32(const struct ssh_hash
*h
, void *s
, unsigned i
)
1819 unsigned char intblk
[4];
1820 PUT_32BIT(intblk
, i
);
1821 h
->bytes(s
, intblk
, 4);
1825 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1827 static void ssh_pkt_ensure(struct Packet
*pkt
, int length
)
1829 if (pkt
->maxlen
< length
) {
1830 unsigned char *body
= pkt
->body
;
1831 int offset
= body ? body
- pkt
->data
: 0;
1832 pkt
->maxlen
= length
+ 256;
1833 pkt
->data
= sresize(pkt
->data
, pkt
->maxlen
+ APIEXTRA
, unsigned char);
1834 if (body
) pkt
->body
= pkt
->data
+ offset
;
1837 static void ssh_pkt_adddata(struct Packet
*pkt
, void *data
, int len
)
1839 if (pkt
->logmode
!= PKTLOG_EMIT
) {
1841 pkt
->blanks
= sresize(pkt
->blanks
, pkt
->nblanks
, struct logblank_t
);
1843 pkt
->blanks
[pkt
->nblanks
-1].offset
= pkt
->length
-
1844 (pkt
->body
- pkt
->data
);
1845 pkt
->blanks
[pkt
->nblanks
-1].len
= len
;
1846 pkt
->blanks
[pkt
->nblanks
-1].type
= pkt
->logmode
;
1849 ssh_pkt_ensure(pkt
, pkt
->length
);
1850 memcpy(pkt
->data
+ pkt
->length
- len
, data
, len
);
1852 static void ssh_pkt_addbyte(struct Packet
*pkt
, unsigned char byte
)
1854 ssh_pkt_adddata(pkt
, &byte
, 1);
1856 static void ssh2_pkt_addbool(struct Packet
*pkt
, unsigned char value
)
1858 ssh_pkt_adddata(pkt
, &value
, 1);
1860 static void ssh_pkt_adduint32(struct Packet
*pkt
, unsigned long value
)
1863 PUT_32BIT(x
, value
);
1864 ssh_pkt_adddata(pkt
, x
, 4);
1866 static void ssh_pkt_addstring_start(struct Packet
*pkt
)
1868 ssh_pkt_adduint32(pkt
, 0);
1869 pkt
->savedpos
= pkt
->length
;
1871 static void ssh_pkt_addstring_str(struct Packet
*pkt
, char *data
)
1873 ssh_pkt_adddata(pkt
, data
, strlen(data
));
1874 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1876 static void ssh_pkt_addstring_data(struct Packet
*pkt
, char *data
, int len
)
1878 ssh_pkt_adddata(pkt
, data
, len
);
1879 PUT_32BIT(pkt
->data
+ pkt
->savedpos
- 4, pkt
->length
- pkt
->savedpos
);
1881 static void ssh_pkt_addstring(struct Packet
*pkt
, char *data
)
1883 ssh_pkt_addstring_start(pkt
);
1884 ssh_pkt_addstring_str(pkt
, data
);
1886 static void ssh1_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1888 int len
= ssh1_bignum_length(b
);
1889 unsigned char *data
= snewn(len
, unsigned char);
1890 (void) ssh1_write_bignum(data
, b
);
1891 ssh_pkt_adddata(pkt
, data
, len
);
1894 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1897 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1898 p
= snewn(n
+ 1, unsigned char);
1900 for (i
= 1; i
<= n
; i
++)
1901 p
[i
] = bignum_byte(b
, n
- i
);
1903 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1905 memmove(p
, p
+ i
, n
+ 1 - i
);
1909 static void ssh2_pkt_addmp(struct Packet
*pkt
, Bignum b
)
1913 p
= ssh2_mpint_fmt(b
, &len
);
1914 ssh_pkt_addstring_start(pkt
);
1915 ssh_pkt_addstring_data(pkt
, (char *)p
, len
);
1919 static struct Packet
*ssh1_pkt_init(int pkt_type
)
1921 struct Packet
*pkt
= ssh_new_packet();
1922 pkt
->length
= 4 + 8; /* space for length + max padding */
1923 ssh_pkt_addbyte(pkt
, pkt_type
);
1924 pkt
->body
= pkt
->data
+ pkt
->length
;
1928 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1929 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1930 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1931 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1932 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1933 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1934 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1935 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1936 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1938 static struct Packet
*ssh2_pkt_init(int pkt_type
)
1940 struct Packet
*pkt
= ssh_new_packet();
1941 pkt
->length
= 5; /* space for packet length + padding length */
1943 ssh_pkt_addbyte(pkt
, (unsigned char) pkt_type
);
1944 pkt
->body
= pkt
->data
+ pkt
->length
; /* after packet type */
1949 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1950 * put the MAC on it. Final packet, ready to be sent, is stored in
1951 * pkt->data. Total length is returned.
1953 static int ssh2_pkt_construct(Ssh ssh
, struct Packet
*pkt
)
1955 int cipherblk
, maclen
, padding
, i
;
1958 log_packet(ssh
->logctx
, PKT_OUTGOING
, pkt
->data
[5],
1959 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
, pkt
->data
[5]),
1960 pkt
->body
, pkt
->length
- (pkt
->body
- pkt
->data
),
1961 pkt
->nblanks
, pkt
->blanks
, &ssh
->v2_outgoing_sequence
);
1962 sfree(pkt
->blanks
); pkt
->blanks
= NULL
;
1966 * Compress packet payload.
1969 unsigned char *newpayload
;
1972 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, pkt
->data
+ 5,
1974 &newpayload
, &newlen
)) {
1976 ssh2_pkt_adddata(pkt
, newpayload
, newlen
);
1982 * Add padding. At least four bytes, and must also bring total
1983 * length (minus MAC) up to a multiple of the block size.
1984 * If pkt->forcepad is set, make sure the packet is at least that size
1987 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1988 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1990 if (pkt
->length
+ padding
< pkt
->forcepad
)
1991 padding
= pkt
->forcepad
- pkt
->length
;
1993 (cipherblk
- (pkt
->length
+ padding
) % cipherblk
) % cipherblk
;
1994 assert(padding
<= 255);
1995 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1996 ssh2_pkt_ensure(pkt
, pkt
->length
+ padding
+ maclen
);
1997 pkt
->data
[4] = padding
;
1998 for (i
= 0; i
< padding
; i
++)
1999 pkt
->data
[pkt
->length
+ i
] = random_byte();
2000 PUT_32BIT(pkt
->data
, pkt
->length
+ padding
- 4);
2002 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, pkt
->data
,
2003 pkt
->length
+ padding
,
2004 ssh
->v2_outgoing_sequence
);
2005 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
2008 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
2009 pkt
->data
, pkt
->length
+ padding
);
2011 pkt
->encrypted_len
= pkt
->length
+ padding
;
2013 /* Ready-to-send packet starts at pkt->data. We return length. */
2014 return pkt
->length
+ padding
+ maclen
;
2018 * Routines called from the main SSH code to send packets. There
2019 * are quite a few of these, because we have two separate
2020 * mechanisms for delaying the sending of packets:
2022 * - In order to send an IGNORE message and a password message in
2023 * a single fixed-length blob, we require the ability to
2024 * concatenate the encrypted forms of those two packets _into_ a
2025 * single blob and then pass it to our <network.h> transport
2026 * layer in one go. Hence, there's a deferment mechanism which
2027 * works after packet encryption.
2029 * - In order to avoid sending any connection-layer messages
2030 * during repeat key exchange, we have to queue up any such
2031 * outgoing messages _before_ they are encrypted (and in
2032 * particular before they're allocated sequence numbers), and
2033 * then send them once we've finished.
2035 * I call these mechanisms `defer' and `queue' respectively, so as
2036 * to distinguish them reasonably easily.
2038 * The functions send_noqueue() and defer_noqueue() free the packet
2039 * structure they are passed. Every outgoing packet goes through
2040 * precisely one of these functions in its life; packets passed to
2041 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2042 * these or get queued, and then when the queue is later emptied
2043 * the packets are all passed to defer_noqueue().
2045 * When using a CBC-mode cipher, it's necessary to ensure that an
2046 * attacker can't provide data to be encrypted using an IV that they
2047 * know. We ensure this by prefixing each packet that might contain
2048 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2049 * mechanism, so in this case send_noqueue() ends up redirecting to
2050 * defer_noqueue(). If you don't like this inefficiency, don't use
2054 static void ssh2_pkt_defer_noqueue(Ssh
, struct Packet
*, int);
2055 static void ssh_pkt_defersend(Ssh
);
2058 * Send an SSH-2 packet immediately, without queuing or deferring.
2060 static void ssh2_pkt_send_noqueue(Ssh ssh
, struct Packet
*pkt
)
2064 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
)) {
2065 /* We need to send two packets, so use the deferral mechanism. */
2066 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
2067 ssh_pkt_defersend(ssh
);
2070 len
= ssh2_pkt_construct(ssh
, pkt
);
2071 backlog
= s_write(ssh
, pkt
->data
, len
);
2072 if (backlog
> SSH_MAX_BACKLOG
)
2073 ssh_throttle_all(ssh
, 1, backlog
);
2075 ssh
->outgoing_data_size
+= pkt
->encrypted_len
;
2076 if (!ssh
->kex_in_progress
&&
2077 ssh
->max_data_size
!= 0 &&
2078 ssh
->outgoing_data_size
> ssh
->max_data_size
)
2079 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
2081 ssh_free_packet(pkt
);
2085 * Defer an SSH-2 packet.
2087 static void ssh2_pkt_defer_noqueue(Ssh ssh
, struct Packet
*pkt
, int noignore
)
2090 if (ssh
->cscipher
!= NULL
&& (ssh
->cscipher
->flags
& SSH_CIPHER_IS_CBC
) &&
2091 ssh
->deferred_len
== 0 && !noignore
&&
2092 !(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
)) {
2094 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2095 * get encrypted with a known IV.
2097 struct Packet
*ipkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
2098 ssh2_pkt_addstring_start(ipkt
);
2099 ssh2_pkt_defer_noqueue(ssh
, ipkt
, TRUE
);
2101 len
= ssh2_pkt_construct(ssh
, pkt
);
2102 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
2103 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
2104 ssh
->deferred_send_data
= sresize(ssh
->deferred_send_data
,
2108 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, pkt
->data
, len
);
2109 ssh
->deferred_len
+= len
;
2110 ssh
->deferred_data_size
+= pkt
->encrypted_len
;
2111 ssh_free_packet(pkt
);
2115 * Queue an SSH-2 packet.
2117 static void ssh2_pkt_queue(Ssh ssh
, struct Packet
*pkt
)
2119 assert(ssh
->queueing
);
2121 if (ssh
->queuelen
>= ssh
->queuesize
) {
2122 ssh
->queuesize
= ssh
->queuelen
+ 32;
2123 ssh
->queue
= sresize(ssh
->queue
, ssh
->queuesize
, struct Packet
*);
2126 ssh
->queue
[ssh
->queuelen
++] = pkt
;
2130 * Either queue or send a packet, depending on whether queueing is
2133 static void ssh2_pkt_send(Ssh ssh
, struct Packet
*pkt
)
2136 ssh2_pkt_queue(ssh
, pkt
);
2138 ssh2_pkt_send_noqueue(ssh
, pkt
);
2142 * Either queue or defer a packet, depending on whether queueing is
2145 static void ssh2_pkt_defer(Ssh ssh
, struct Packet
*pkt
)
2148 ssh2_pkt_queue(ssh
, pkt
);
2150 ssh2_pkt_defer_noqueue(ssh
, pkt
, FALSE
);
2154 * Send the whole deferred data block constructed by
2155 * ssh2_pkt_defer() or SSH-1's defer_packet().
2157 * The expected use of the defer mechanism is that you call
2158 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2159 * not currently queueing, this simply sets up deferred_send_data
2160 * and then sends it. If we _are_ currently queueing, the calls to
2161 * ssh2_pkt_defer() put the deferred packets on to the queue
2162 * instead, and therefore ssh_pkt_defersend() has no deferred data
2163 * to send. Hence, there's no need to make it conditional on
2166 static void ssh_pkt_defersend(Ssh ssh
)
2169 backlog
= s_write(ssh
, ssh
->deferred_send_data
, ssh
->deferred_len
);
2170 ssh
->deferred_len
= ssh
->deferred_size
= 0;
2171 sfree(ssh
->deferred_send_data
);
2172 ssh
->deferred_send_data
= NULL
;
2173 if (backlog
> SSH_MAX_BACKLOG
)
2174 ssh_throttle_all(ssh
, 1, backlog
);
2176 ssh
->outgoing_data_size
+= ssh
->deferred_data_size
;
2177 if (!ssh
->kex_in_progress
&&
2178 ssh
->max_data_size
!= 0 &&
2179 ssh
->outgoing_data_size
> ssh
->max_data_size
)
2180 do_ssh2_transport(ssh
, "too much data sent", -1, NULL
);
2181 ssh
->deferred_data_size
= 0;
2185 * Send a packet whose length needs to be disguised (typically
2186 * passwords or keyboard-interactive responses).
2188 static void ssh2_pkt_send_with_padding(Ssh ssh
, struct Packet
*pkt
,
2194 * The simplest way to do this is to adjust the
2195 * variable-length padding field in the outgoing packet.
2197 * Currently compiled out, because some Cisco SSH servers
2198 * don't like excessively padded packets (bah, why's it
2201 pkt
->forcepad
= padsize
;
2202 ssh2_pkt_send(ssh
, pkt
);
2207 * If we can't do that, however, an alternative approach is
2208 * to use the pkt_defer mechanism to bundle the packet
2209 * tightly together with an SSH_MSG_IGNORE such that their
2210 * combined length is a constant. So first we construct the
2211 * final form of this packet and defer its sending.
2213 ssh2_pkt_defer(ssh
, pkt
);
2216 * Now construct an SSH_MSG_IGNORE which includes a string
2217 * that's an exact multiple of the cipher block size. (If
2218 * the cipher is NULL so that the block size is
2219 * unavailable, we don't do this trick at all, because we
2220 * gain nothing by it.)
2222 if (ssh
->cscipher
&&
2223 !(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
)) {
2226 stringlen
= (256 - ssh
->deferred_len
);
2227 stringlen
+= ssh
->cscipher
->blksize
- 1;
2228 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
2231 * Temporarily disable actual compression, so we
2232 * can guarantee to get this string exactly the
2233 * length we want it. The compression-disabling
2234 * routine should return an integer indicating how
2235 * many bytes we should adjust our string length
2239 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
2241 pkt
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
2242 ssh2_pkt_addstring_start(pkt
);
2243 for (i
= 0; i
< stringlen
; i
++) {
2244 char c
= (char) random_byte();
2245 ssh2_pkt_addstring_data(pkt
, &c
, 1);
2247 ssh2_pkt_defer(ssh
, pkt
);
2249 ssh_pkt_defersend(ssh
);
2254 * Send all queued SSH-2 packets. We send them by means of
2255 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2256 * packets that needed to be lumped together.
2258 static void ssh2_pkt_queuesend(Ssh ssh
)
2262 assert(!ssh
->queueing
);
2264 for (i
= 0; i
< ssh
->queuelen
; i
++)
2265 ssh2_pkt_defer_noqueue(ssh
, ssh
->queue
[i
], FALSE
);
2268 ssh_pkt_defersend(ssh
);
2272 void bndebug(char *string
, Bignum b
)
2276 p
= ssh2_mpint_fmt(b
, &len
);
2277 debug(("%s", string
));
2278 for (i
= 0; i
< len
; i
++)
2279 debug((" %02x", p
[i
]));
2285 static void hash_mpint(const struct ssh_hash
*h
, void *s
, Bignum b
)
2289 p
= ssh2_mpint_fmt(b
, &len
);
2290 hash_string(h
, s
, p
, len
);
2295 * Packet decode functions for both SSH-1 and SSH-2.
2297 static unsigned long ssh_pkt_getuint32(struct Packet
*pkt
)
2299 unsigned long value
;
2300 if (pkt
->length
- pkt
->savedpos
< 4)
2301 return 0; /* arrgh, no way to decline (FIXME?) */
2302 value
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2306 static int ssh2_pkt_getbool(struct Packet
*pkt
)
2308 unsigned long value
;
2309 if (pkt
->length
- pkt
->savedpos
< 1)
2310 return 0; /* arrgh, no way to decline (FIXME?) */
2311 value
= pkt
->body
[pkt
->savedpos
] != 0;
2315 static void ssh_pkt_getstring(struct Packet
*pkt
, char **p
, int *length
)
2320 if (pkt
->length
- pkt
->savedpos
< 4)
2322 len
= GET_32BIT(pkt
->body
+ pkt
->savedpos
);
2327 if (pkt
->length
- pkt
->savedpos
< *length
)
2329 *p
= (char *)(pkt
->body
+ pkt
->savedpos
);
2330 pkt
->savedpos
+= *length
;
2332 static void *ssh_pkt_getdata(struct Packet
*pkt
, int length
)
2334 if (pkt
->length
- pkt
->savedpos
< length
)
2336 pkt
->savedpos
+= length
;
2337 return pkt
->body
+ (pkt
->savedpos
- length
);
2339 static int ssh1_pkt_getrsakey(struct Packet
*pkt
, struct RSAKey
*key
,
2340 unsigned char **keystr
)
2344 j
= makekey(pkt
->body
+ pkt
->savedpos
,
2345 pkt
->length
- pkt
->savedpos
,
2352 assert(pkt
->savedpos
< pkt
->length
);
2356 static Bignum
ssh1_pkt_getmp(struct Packet
*pkt
)
2361 j
= ssh1_read_bignum(pkt
->body
+ pkt
->savedpos
,
2362 pkt
->length
- pkt
->savedpos
, &b
);
2370 static Bignum
ssh2_pkt_getmp(struct Packet
*pkt
)
2376 ssh_pkt_getstring(pkt
, &p
, &length
);
2381 b
= bignum_from_bytes((unsigned char *)p
, length
);
2386 * Helper function to add an SSH-2 signature blob to a packet.
2387 * Expects to be shown the public key blob as well as the signature
2388 * blob. Normally works just like ssh2_pkt_addstring, but will
2389 * fiddle with the signature packet if necessary for
2390 * BUG_SSH2_RSA_PADDING.
2392 static void ssh2_add_sigblob(Ssh ssh
, struct Packet
*pkt
,
2393 void *pkblob_v
, int pkblob_len
,
2394 void *sigblob_v
, int sigblob_len
)
2396 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
2397 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
2399 /* dmemdump(pkblob, pkblob_len); */
2400 /* dmemdump(sigblob, sigblob_len); */
2403 * See if this is in fact an ssh-rsa signature and a buggy
2404 * server; otherwise we can just do this the easy way.
2406 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
2407 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
2408 int pos
, len
, siglen
;
2411 * Find the byte length of the modulus.
2414 pos
= 4+7; /* skip over "ssh-rsa" */
2415 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
2416 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
2417 pos
+= 4; /* find modulus itself */
2418 while (len
> 0 && pkblob
[pos
] == 0)
2420 /* debug(("modulus length is %d\n", len)); */
2423 * Now find the signature integer.
2425 pos
= 4+7; /* skip over "ssh-rsa" */
2426 siglen
= GET_32BIT(sigblob
+pos
);
2427 /* debug(("signature length is %d\n", siglen)); */
2429 if (len
!= siglen
) {
2430 unsigned char newlen
[4];
2431 ssh2_pkt_addstring_start(pkt
);
2432 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, pos
);
2433 /* dmemdump(sigblob, pos); */
2434 pos
+= 4; /* point to start of actual sig */
2435 PUT_32BIT(newlen
, len
);
2436 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 4);
2437 /* dmemdump(newlen, 4); */
2439 while (len
-- > siglen
) {
2440 ssh2_pkt_addstring_data(pkt
, (char *)newlen
, 1);
2441 /* dmemdump(newlen, 1); */
2443 ssh2_pkt_addstring_data(pkt
, (char *)(sigblob
+pos
), siglen
);
2444 /* dmemdump(sigblob+pos, siglen); */
2448 /* Otherwise fall through and do it the easy way. */
2451 ssh2_pkt_addstring_start(pkt
);
2452 ssh2_pkt_addstring_data(pkt
, (char *)sigblob
, sigblob_len
);
2456 * Examine the remote side's version string and compare it against
2457 * a list of known buggy implementations.
2459 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
2461 char *imp
; /* pointer to implementation part */
2463 imp
+= strcspn(imp
, "-");
2465 imp
+= strcspn(imp
, "-");
2468 ssh
->remote_bugs
= 0;
2471 * General notes on server version strings:
2472 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2473 * here -- in particular, we've heard of one that's perfectly happy
2474 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2475 * so we can't distinguish them.
2477 if (conf_get_int(ssh
->conf
, CONF_sshbug_ignore1
) == FORCE_ON
||
2478 (conf_get_int(ssh
->conf
, CONF_sshbug_ignore1
) == AUTO
&&
2479 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
2480 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
2481 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25") ||
2482 !strcmp(imp
, "OSU_1.4alpha3") || !strcmp(imp
, "OSU_1.5alpha4")))) {
2484 * These versions don't support SSH1_MSG_IGNORE, so we have
2485 * to use a different defence against password length
2488 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
2489 logevent("We believe remote version has SSH-1 ignore bug");
2492 if (conf_get_int(ssh
->conf
, CONF_sshbug_plainpw1
) == FORCE_ON
||
2493 (conf_get_int(ssh
->conf
, CONF_sshbug_plainpw1
) == AUTO
&&
2494 (!strcmp(imp
, "Cisco-1.25") || !strcmp(imp
, "OSU_1.4alpha3")))) {
2496 * These versions need a plain password sent; they can't
2497 * handle having a null and a random length of data after
2500 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
2501 logevent("We believe remote version needs a plain SSH-1 password");
2504 if (conf_get_int(ssh
->conf
, CONF_sshbug_rsa1
) == FORCE_ON
||
2505 (conf_get_int(ssh
->conf
, CONF_sshbug_rsa1
) == AUTO
&&
2506 (!strcmp(imp
, "Cisco-1.25")))) {
2508 * These versions apparently have no clue whatever about
2509 * RSA authentication and will panic and die if they see
2510 * an AUTH_RSA message.
2512 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
2513 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2516 if (conf_get_int(ssh
->conf
, CONF_sshbug_hmac2
) == FORCE_ON
||
2517 (conf_get_int(ssh
->conf
, CONF_sshbug_hmac2
) == AUTO
&&
2518 !wc_match("* VShell", imp
) &&
2519 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
2520 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
2521 wc_match("2.1 *", imp
)))) {
2523 * These versions have the HMAC bug.
2525 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
2526 logevent("We believe remote version has SSH-2 HMAC bug");
2529 if (conf_get_int(ssh
->conf
, CONF_sshbug_derivekey2
) == FORCE_ON
||
2530 (conf_get_int(ssh
->conf
, CONF_sshbug_derivekey2
) == AUTO
&&
2531 !wc_match("* VShell", imp
) &&
2532 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
2534 * These versions have the key-derivation bug (failing to
2535 * include the literal shared secret in the hashes that
2536 * generate the keys).
2538 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
2539 logevent("We believe remote version has SSH-2 key-derivation bug");
2542 if (conf_get_int(ssh
->conf
, CONF_sshbug_rsapad2
) == FORCE_ON
||
2543 (conf_get_int(ssh
->conf
, CONF_sshbug_rsapad2
) == AUTO
&&
2544 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
2545 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
2547 * These versions have the SSH-2 RSA padding bug.
2549 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
2550 logevent("We believe remote version has SSH-2 RSA padding bug");
2553 if (conf_get_int(ssh
->conf
, CONF_sshbug_pksessid2
) == FORCE_ON
||
2554 (conf_get_int(ssh
->conf
, CONF_sshbug_pksessid2
) == AUTO
&&
2555 wc_match("OpenSSH_2.[0-2]*", imp
))) {
2557 * These versions have the SSH-2 session-ID bug in
2558 * public-key authentication.
2560 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
2561 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2564 if (conf_get_int(ssh
->conf
, CONF_sshbug_rekey2
) == FORCE_ON
||
2565 (conf_get_int(ssh
->conf
, CONF_sshbug_rekey2
) == AUTO
&&
2566 (wc_match("DigiSSH_2.0", imp
) ||
2567 wc_match("OpenSSH_2.[0-4]*", imp
) ||
2568 wc_match("OpenSSH_2.5.[0-3]*", imp
) ||
2569 wc_match("Sun_SSH_1.0", imp
) ||
2570 wc_match("Sun_SSH_1.0.1", imp
) ||
2571 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2572 wc_match("WeOnlyDo-*", imp
)))) {
2574 * These versions have the SSH-2 rekey bug.
2576 ssh
->remote_bugs
|= BUG_SSH2_REKEY
;
2577 logevent("We believe remote version has SSH-2 rekey bug");
2580 if (conf_get_int(ssh
->conf
, CONF_sshbug_maxpkt2
) == FORCE_ON
||
2581 (conf_get_int(ssh
->conf
, CONF_sshbug_maxpkt2
) == AUTO
&&
2582 (wc_match("1.36_sshlib GlobalSCAPE", imp
) ||
2583 wc_match("1.36 sshlib: GlobalScape", imp
)))) {
2585 * This version ignores our makpkt and needs to be throttled.
2587 ssh
->remote_bugs
|= BUG_SSH2_MAXPKT
;
2588 logevent("We believe remote version ignores SSH-2 maximum packet size");
2591 if (conf_get_int(ssh
->conf
, CONF_sshbug_ignore2
) == FORCE_ON
) {
2593 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2594 * none detected automatically.
2596 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH2_IGNORE
;
2597 logevent("We believe remote version has SSH-2 ignore bug");
2600 if (conf_get_int(ssh
->conf
, CONF_sshbug_winadj
) == FORCE_ON
) {
2602 * Servers that don't support our winadj request for one
2603 * reason or another. Currently, none detected automatically.
2605 ssh
->remote_bugs
|= BUG_CHOKES_ON_WINADJ
;
2606 logevent("We believe remote version has winadj bug");
2611 * The `software version' part of an SSH version string is required
2612 * to contain no spaces or minus signs.
2614 static void ssh_fix_verstring(char *str
)
2616 /* Eat "SSH-<protoversion>-". */
2617 assert(*str
== 'S'); str
++;
2618 assert(*str
== 'S'); str
++;
2619 assert(*str
== 'H'); str
++;
2620 assert(*str
== '-'); str
++;
2621 while (*str
&& *str
!= '-') str
++;
2622 assert(*str
== '-'); str
++;
2624 /* Convert minus signs and spaces in the remaining string into
2627 if (*str
== '-' || *str
== ' ')
2634 * Send an appropriate SSH version string.
2636 static void ssh_send_verstring(Ssh ssh
, char *svers
)
2640 if (ssh
->version
== 2) {
2642 * Construct a v2 version string.
2644 verstring
= dupprintf("SSH-2.0-%s\015\012", sshver
);
2647 * Construct a v1 version string.
2649 verstring
= dupprintf("SSH-%s-%s\012",
2650 (ssh_versioncmp(svers
, "1.5") <= 0 ?
2655 ssh_fix_verstring(verstring
);
2657 if (ssh
->version
== 2) {
2660 * Record our version string.
2662 len
= strcspn(verstring
, "\015\012");
2663 ssh
->v_c
= snewn(len
+ 1, char);
2664 memcpy(ssh
->v_c
, verstring
, len
);
2668 logeventf(ssh
, "We claim version: %.*s",
2669 strcspn(verstring
, "\015\012"), verstring
);
2670 s_write(ssh
, verstring
, strlen(verstring
));
2674 static int do_ssh_init(Ssh ssh
, unsigned char c
)
2676 struct do_ssh_init_state
{
2685 crState(do_ssh_init_state
);
2689 /* Search for a line beginning with the string "SSH-" in the input. */
2691 if (c
!= 'S') goto no
;
2693 if (c
!= 'S') goto no
;
2695 if (c
!= 'H') goto no
;
2697 if (c
!= '-') goto no
;
2706 s
->vstring
= snewn(s
->vstrsize
, char);
2707 strcpy(s
->vstring
, "SSH-");
2711 crReturn(1); /* get another char */
2712 if (s
->vslen
>= s
->vstrsize
- 1) {
2714 s
->vstring
= sresize(s
->vstring
, s
->vstrsize
, char);
2716 s
->vstring
[s
->vslen
++] = c
;
2719 s
->version
[s
->i
] = '\0';
2721 } else if (s
->i
< sizeof(s
->version
) - 1)
2722 s
->version
[s
->i
++] = c
;
2723 } else if (c
== '\012')
2727 ssh
->agentfwd_enabled
= FALSE
;
2728 ssh
->rdpkt2_state
.incoming_sequence
= 0;
2730 s
->vstring
[s
->vslen
] = 0;
2731 s
->vstring
[strcspn(s
->vstring
, "\015\012")] = '\0';/* remove EOL chars */
2732 logeventf(ssh
, "Server version: %s", s
->vstring
);
2733 ssh_detect_bugs(ssh
, s
->vstring
);
2736 * Decide which SSH protocol version to support.
2739 /* Anything strictly below "2.0" means protocol 1 is supported. */
2740 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
2741 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2742 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
2744 if (conf_get_int(ssh
->conf
, CONF_sshprot
) == 0 && !s
->proto1
) {
2745 bombout(("SSH protocol version 1 required by user but not provided by server"));
2748 if (conf_get_int(ssh
->conf
, CONF_sshprot
) == 3 && !s
->proto2
) {
2749 bombout(("SSH protocol version 2 required by user but not provided by server"));
2753 if (s
->proto2
&& (conf_get_int(ssh
->conf
, CONF_sshprot
) >= 2 || !s
->proto1
))
2758 logeventf(ssh
, "Using SSH protocol version %d", ssh
->version
);
2760 /* Send the version string, if we haven't already */
2761 if (conf_get_int(ssh
->conf
, CONF_sshprot
) != 3)
2762 ssh_send_verstring(ssh
, s
->version
);
2764 if (ssh
->version
== 2) {
2767 * Record their version string.
2769 len
= strcspn(s
->vstring
, "\015\012");
2770 ssh
->v_s
= snewn(len
+ 1, char);
2771 memcpy(ssh
->v_s
, s
->vstring
, len
);
2775 * Initialise SSH-2 protocol.
2777 ssh
->protocol
= ssh2_protocol
;
2778 ssh2_protocol_setup(ssh
);
2779 ssh
->s_rdpkt
= ssh2_rdpkt
;
2782 * Initialise SSH-1 protocol.
2784 ssh
->protocol
= ssh1_protocol
;
2785 ssh1_protocol_setup(ssh
);
2786 ssh
->s_rdpkt
= ssh1_rdpkt
;
2788 if (ssh
->version
== 2)
2789 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
2791 update_specials_menu(ssh
->frontend
);
2792 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
2793 ssh
->pinger
= pinger_new(ssh
->conf
, &ssh_backend
, ssh
);
2800 static void ssh_process_incoming_data(Ssh ssh
,
2801 unsigned char **data
, int *datalen
)
2803 struct Packet
*pktin
;
2805 pktin
= ssh
->s_rdpkt(ssh
, data
, datalen
);
2807 ssh
->protocol(ssh
, NULL
, 0, pktin
);
2808 ssh_free_packet(pktin
);
2812 static void ssh_queue_incoming_data(Ssh ssh
,
2813 unsigned char **data
, int *datalen
)
2815 bufchain_add(&ssh
->queued_incoming_data
, *data
, *datalen
);
2820 static void ssh_process_queued_incoming_data(Ssh ssh
)
2823 unsigned char *data
;
2826 while (!ssh
->frozen
&& bufchain_size(&ssh
->queued_incoming_data
)) {
2827 bufchain_prefix(&ssh
->queued_incoming_data
, &vdata
, &len
);
2831 while (!ssh
->frozen
&& len
> 0)
2832 ssh_process_incoming_data(ssh
, &data
, &len
);
2835 bufchain_consume(&ssh
->queued_incoming_data
, origlen
- len
);
2839 static void ssh_set_frozen(Ssh ssh
, int frozen
)
2842 sk_set_frozen(ssh
->s
, frozen
);
2843 ssh
->frozen
= frozen
;
2846 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
2848 /* Log raw data, if we're in that mode. */
2850 log_packet(ssh
->logctx
, PKT_INCOMING
, -1, NULL
, data
, datalen
,
2853 crBegin(ssh
->ssh_gotdata_crstate
);
2856 * To begin with, feed the characters one by one to the
2857 * protocol initialisation / selection function do_ssh_init().
2858 * When that returns 0, we're done with the initial greeting
2859 * exchange and can move on to packet discipline.
2862 int ret
; /* need not be kept across crReturn */
2864 crReturnV
; /* more data please */
2865 ret
= do_ssh_init(ssh
, *data
);
2873 * We emerge from that loop when the initial negotiation is
2874 * over and we have selected an s_rdpkt function. Now pass
2875 * everything to s_rdpkt, and then pass the resulting packets
2876 * to the proper protocol handler.
2880 while (bufchain_size(&ssh
->queued_incoming_data
) > 0 || datalen
> 0) {
2882 ssh_queue_incoming_data(ssh
, &data
, &datalen
);
2883 /* This uses up all data and cannot cause anything interesting
2884 * to happen; indeed, for anything to happen at all, we must
2885 * return, so break out. */
2887 } else if (bufchain_size(&ssh
->queued_incoming_data
) > 0) {
2888 /* This uses up some or all data, and may freeze the
2890 ssh_process_queued_incoming_data(ssh
);
2892 /* This uses up some or all data, and may freeze the
2894 ssh_process_incoming_data(ssh
, &data
, &datalen
);
2896 /* FIXME this is probably EBW. */
2897 if (ssh
->state
== SSH_STATE_CLOSED
)
2900 /* We're out of data. Go and get some more. */
2906 static int ssh_do_close(Ssh ssh
, int notify_exit
)
2909 struct ssh_channel
*c
;
2911 ssh
->state
= SSH_STATE_CLOSED
;
2912 expire_timer_context(ssh
);
2917 notify_remote_exit(ssh
->frontend
);
2922 * Now we must shut down any port- and X-forwarded channels going
2923 * through this connection.
2925 if (ssh
->channels
) {
2926 while (NULL
!= (c
= index234(ssh
->channels
, 0))) {
2929 x11_close(c
->u
.x11
.s
);
2932 case CHAN_SOCKDATA_DORMANT
:
2933 pfd_close(c
->u
.pfd
.s
);
2936 del234(ssh
->channels
, c
); /* moving next one to index 0 */
2937 if (ssh
->version
== 2)
2938 bufchain_clear(&c
->v
.v2
.outbuffer
);
2943 * Go through port-forwardings, and close any associated
2944 * listening sockets.
2946 if (ssh
->portfwds
) {
2947 struct ssh_portfwd
*pf
;
2948 while (NULL
!= (pf
= index234(ssh
->portfwds
, 0))) {
2949 /* Dispose of any listening socket. */
2951 pfd_terminate(pf
->local
);
2952 del234(ssh
->portfwds
, pf
); /* moving next one to index 0 */
2955 freetree234(ssh
->portfwds
);
2956 ssh
->portfwds
= NULL
;
2962 static void ssh_log(Plug plug
, int type
, SockAddr addr
, int port
,
2963 const char *error_msg
, int error_code
)
2965 Ssh ssh
= (Ssh
) plug
;
2966 char addrbuf
[256], *msg
;
2968 sk_getaddr(addr
, addrbuf
, lenof(addrbuf
));
2971 msg
= dupprintf("Connecting to %s port %d", addrbuf
, port
);
2973 msg
= dupprintf("Failed to connect to %s: %s", addrbuf
, error_msg
);
2979 static int ssh_closing(Plug plug
, const char *error_msg
, int error_code
,
2982 Ssh ssh
= (Ssh
) plug
;
2983 int need_notify
= ssh_do_close(ssh
, FALSE
);
2986 if (!ssh
->close_expected
)
2987 error_msg
= "Server unexpectedly closed network connection";
2989 error_msg
= "Server closed network connection";
2992 if (ssh
->close_expected
&& ssh
->clean_exit
&& ssh
->exitcode
< 0)
2996 notify_remote_exit(ssh
->frontend
);
2999 logevent(error_msg
);
3000 if (!ssh
->close_expected
|| !ssh
->clean_exit
)
3001 connection_fatal(ssh
->frontend
, "%s", error_msg
);
3005 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
3007 Ssh ssh
= (Ssh
) plug
;
3008 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
3009 if (ssh
->state
== SSH_STATE_CLOSED
) {
3010 ssh_do_close(ssh
, TRUE
);
3016 static void ssh_sent(Plug plug
, int bufsize
)
3018 Ssh ssh
= (Ssh
) plug
;
3020 * If the send backlog on the SSH socket itself clears, we
3021 * should unthrottle the whole world if it was throttled.
3023 if (bufsize
< SSH_MAX_BACKLOG
)
3024 ssh_throttle_all(ssh
, 0, bufsize
);
3028 * Connect to specified host and port.
3029 * Returns an error message, or NULL on success.
3030 * Also places the canonical host name into `realhost'. It must be
3031 * freed by the caller.
3033 static const char *connect_to_host(Ssh ssh
, char *host
, int port
,
3034 char **realhost
, int nodelay
, int keepalive
)
3036 static const struct plug_function_table fn_table
= {
3047 int addressfamily
, sshprot
;
3049 loghost
= conf_get_str(ssh
->conf
, CONF_loghost
);
3053 ssh
->savedhost
= dupstr(loghost
);
3054 ssh
->savedport
= 22; /* default ssh port */
3057 * A colon suffix on savedhost also lets us affect
3060 * (FIXME: do something about IPv6 address literals here.)
3062 colon
= strrchr(ssh
->savedhost
, ':');
3066 ssh
->savedport
= atoi(colon
);
3069 ssh
->savedhost
= dupstr(host
);
3071 port
= 22; /* default ssh port */
3072 ssh
->savedport
= port
;
3078 addressfamily
= conf_get_int(ssh
->conf
, CONF_addressfamily
);
3079 logeventf(ssh
, "Looking up host \"%s\"%s", host
,
3080 (addressfamily
== ADDRTYPE_IPV4 ?
" (IPv4)" :
3081 (addressfamily
== ADDRTYPE_IPV6 ?
" (IPv6)" : "")));
3082 addr
= name_lookup(host
, port
, realhost
, ssh
->conf
, addressfamily
);
3083 if ((err
= sk_addr_error(addr
)) != NULL
) {
3087 ssh
->fullhostname
= dupstr(*realhost
); /* save in case of GSSAPI */
3092 ssh
->fn
= &fn_table
;
3093 ssh
->s
= new_connection(addr
, *realhost
, port
,
3094 0, 1, nodelay
, keepalive
, (Plug
) ssh
, ssh
->conf
);
3095 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
3097 notify_remote_exit(ssh
->frontend
);
3102 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3103 * send the version string too.
3105 sshprot
= conf_get_int(ssh
->conf
, CONF_sshprot
);
3110 ssh_send_verstring(ssh
, NULL
);
3114 * loghost, if configured, overrides realhost.
3118 *realhost
= dupstr(loghost
);
3125 * Throttle or unthrottle the SSH connection.
3127 static void ssh_throttle_conn(Ssh ssh
, int adjust
)
3129 int old_count
= ssh
->conn_throttle_count
;
3130 ssh
->conn_throttle_count
+= adjust
;
3131 assert(ssh
->conn_throttle_count
>= 0);
3132 if (ssh
->conn_throttle_count
&& !old_count
) {
3133 ssh_set_frozen(ssh
, 1);
3134 } else if (!ssh
->conn_throttle_count
&& old_count
) {
3135 ssh_set_frozen(ssh
, 0);
3140 * Throttle or unthrottle _all_ local data streams (for when sends
3141 * on the SSH connection itself back up).
3143 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
3146 struct ssh_channel
*c
;
3148 if (enable
== ssh
->throttled_all
)
3150 ssh
->throttled_all
= enable
;
3151 ssh
->overall_bufsize
= bufsize
;
3154 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
3156 case CHAN_MAINSESSION
:
3158 * This is treated separately, outside the switch.
3162 x11_override_throttle(c
->u
.x11
.s
, enable
);
3165 /* Agent channels require no buffer management. */
3168 pfd_override_throttle(c
->u
.pfd
.s
, enable
);
3174 static void ssh_agent_callback(void *sshv
, void *reply
, int replylen
)
3176 Ssh ssh
= (Ssh
) sshv
;
3178 ssh
->agent_response
= reply
;
3179 ssh
->agent_response_len
= replylen
;
3181 if (ssh
->version
== 1)
3182 do_ssh1_login(ssh
, NULL
, -1, NULL
);
3184 do_ssh2_authconn(ssh
, NULL
, -1, NULL
);
3187 static void ssh_dialog_callback(void *sshv
, int ret
)
3189 Ssh ssh
= (Ssh
) sshv
;
3191 ssh
->user_response
= ret
;
3193 if (ssh
->version
== 1)
3194 do_ssh1_login(ssh
, NULL
, -1, NULL
);
3196 do_ssh2_transport(ssh
, NULL
, -1, NULL
);
3199 * This may have unfrozen the SSH connection, so do a
3202 ssh_process_queued_incoming_data(ssh
);
3205 static void ssh_agentf_callback(void *cv
, void *reply
, int replylen
)
3207 struct ssh_channel
*c
= (struct ssh_channel
*)cv
;
3209 void *sentreply
= reply
;
3212 /* Fake SSH_AGENT_FAILURE. */
3213 sentreply
= "\0\0\0\1\5";
3216 if (ssh
->version
== 2) {
3217 ssh2_add_channel_data(c
, sentreply
, replylen
);
3220 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3221 PKT_INT
, c
->remoteid
,
3224 PKT_DATA
, sentreply
, replylen
,
3233 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3234 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3235 * => log `wire_reason'.
3237 static void ssh_disconnect(Ssh ssh
, char *client_reason
, char *wire_reason
,
3238 int code
, int clean_exit
)
3242 client_reason
= wire_reason
;
3244 error
= dupprintf("Disconnected: %s", client_reason
);
3246 error
= dupstr("Disconnected");
3248 if (ssh
->version
== 1) {
3249 send_packet(ssh
, SSH1_MSG_DISCONNECT
, PKT_STR
, wire_reason
,
3251 } else if (ssh
->version
== 2) {
3252 struct Packet
*pktout
= ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3253 ssh2_pkt_adduint32(pktout
, code
);
3254 ssh2_pkt_addstring(pktout
, wire_reason
);
3255 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
3256 ssh2_pkt_send_noqueue(ssh
, pktout
);
3259 ssh
->close_expected
= TRUE
;
3260 ssh
->clean_exit
= clean_exit
;
3261 ssh_closing((Plug
)ssh
, error
, 0, 0);
3266 * Handle the key exchange and user authentication phases.
3268 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
,
3269 struct Packet
*pktin
)
3272 unsigned char cookie
[8], *ptr
;
3273 struct RSAKey servkey
, hostkey
;
3274 struct MD5Context md5c
;
3275 struct do_ssh1_login_state
{
3278 unsigned char *rsabuf
, *keystr1
, *keystr2
;
3279 unsigned long supported_ciphers_mask
, supported_auths_mask
;
3280 int tried_publickey
, tried_agent
;
3281 int tis_auth_refused
, ccard_auth_refused
;
3282 unsigned char session_id
[16];
3284 void *publickey_blob
;
3285 int publickey_bloblen
;
3286 char *publickey_comment
;
3287 int publickey_encrypted
;
3288 prompts_t
*cur_prompt
;
3291 unsigned char request
[5], *response
, *p
;
3302 crState(do_ssh1_login_state
);
3309 if (pktin
->type
!= SSH1_SMSG_PUBLIC_KEY
) {
3310 bombout(("Public key packet not received"));
3314 logevent("Received public keys");
3316 ptr
= ssh_pkt_getdata(pktin
, 8);
3318 bombout(("SSH-1 public key packet stopped before random cookie"));
3321 memcpy(cookie
, ptr
, 8);
3323 if (!ssh1_pkt_getrsakey(pktin
, &servkey
, &s
->keystr1
) ||
3324 !ssh1_pkt_getrsakey(pktin
, &hostkey
, &s
->keystr2
)) {
3325 bombout(("Failed to read SSH-1 public keys from public key packet"));
3330 * Log the host key fingerprint.
3334 logevent("Host key fingerprint is:");
3335 strcpy(logmsg
, " ");
3336 hostkey
.comment
= NULL
;
3337 rsa_fingerprint(logmsg
+ strlen(logmsg
),
3338 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
3342 ssh
->v1_remote_protoflags
= ssh_pkt_getuint32(pktin
);
3343 s
->supported_ciphers_mask
= ssh_pkt_getuint32(pktin
);
3344 s
->supported_auths_mask
= ssh_pkt_getuint32(pktin
);
3345 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
))
3346 s
->supported_auths_mask
&= ~(1 << SSH1_AUTH_RSA
);
3348 ssh
->v1_local_protoflags
=
3349 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
3350 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
3353 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
3354 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
3355 MD5Update(&md5c
, cookie
, 8);
3356 MD5Final(s
->session_id
, &md5c
);
3358 for (i
= 0; i
< 32; i
++)
3359 ssh
->session_key
[i
] = random_byte();
3362 * Verify that the `bits' and `bytes' parameters match.
3364 if (hostkey
.bits
> hostkey
.bytes
* 8 ||
3365 servkey
.bits
> servkey
.bytes
* 8) {
3366 bombout(("SSH-1 public keys were badly formatted"));
3370 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
3372 s
->rsabuf
= snewn(s
->len
, unsigned char);
3375 * Verify the host key.
3379 * First format the key into a string.
3381 int len
= rsastr_len(&hostkey
);
3382 char fingerprint
[100];
3383 char *keystr
= snewn(len
, char);
3384 rsastr_fmt(keystr
, &hostkey
);
3385 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
3387 ssh_set_frozen(ssh
, 1);
3388 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
3389 ssh
->savedhost
, ssh
->savedport
,
3390 "rsa", keystr
, fingerprint
,
3391 ssh_dialog_callback
, ssh
);
3393 if (s
->dlgret
< 0) {
3397 bombout(("Unexpected data from server while waiting"
3398 " for user host key response"));
3401 } while (pktin
|| inlen
> 0);
3402 s
->dlgret
= ssh
->user_response
;
3404 ssh_set_frozen(ssh
, 0);
3406 if (s
->dlgret
== 0) {
3407 ssh_disconnect(ssh
, "User aborted at host key verification",
3413 for (i
= 0; i
< 32; i
++) {
3414 s
->rsabuf
[i
] = ssh
->session_key
[i
];
3416 s
->rsabuf
[i
] ^= s
->session_id
[i
];
3419 if (hostkey
.bytes
> servkey
.bytes
) {
3420 ret
= rsaencrypt(s
->rsabuf
, 32, &servkey
);
3422 ret
= rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
3424 ret
= rsaencrypt(s
->rsabuf
, 32, &hostkey
);
3426 ret
= rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
3429 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3433 logevent("Encrypted session key");
3436 int cipher_chosen
= 0, warn
= 0;
3437 char *cipher_string
= NULL
;
3439 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
3440 int next_cipher
= conf_get_int_int(ssh
->conf
,
3441 CONF_ssh_cipherlist
, i
);
3442 if (next_cipher
== CIPHER_WARN
) {
3443 /* If/when we choose a cipher, warn about it */
3445 } else if (next_cipher
== CIPHER_AES
) {
3446 /* XXX Probably don't need to mention this. */
3447 logevent("AES not supported in SSH-1, skipping");
3449 switch (next_cipher
) {
3450 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
3451 cipher_string
= "3DES"; break;
3452 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
3453 cipher_string
= "Blowfish"; break;
3454 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
3455 cipher_string
= "single-DES"; break;
3457 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
3461 if (!cipher_chosen
) {
3462 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
3463 bombout(("Server violates SSH-1 protocol by not "
3464 "supporting 3DES encryption"));
3466 /* shouldn't happen */
3467 bombout(("No supported ciphers found"));
3471 /* Warn about chosen cipher if necessary. */
3473 ssh_set_frozen(ssh
, 1);
3474 s
->dlgret
= askalg(ssh
->frontend
, "cipher", cipher_string
,
3475 ssh_dialog_callback
, ssh
);
3476 if (s
->dlgret
< 0) {
3480 bombout(("Unexpected data from server while waiting"
3481 " for user response"));
3484 } while (pktin
|| inlen
> 0);
3485 s
->dlgret
= ssh
->user_response
;
3487 ssh_set_frozen(ssh
, 0);
3488 if (s
->dlgret
== 0) {
3489 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
3496 switch (s
->cipher_type
) {
3497 case SSH_CIPHER_3DES
:
3498 logevent("Using 3DES encryption");
3500 case SSH_CIPHER_DES
:
3501 logevent("Using single-DES encryption");
3503 case SSH_CIPHER_BLOWFISH
:
3504 logevent("Using Blowfish encryption");
3508 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
3509 PKT_CHAR
, s
->cipher_type
,
3510 PKT_DATA
, cookie
, 8,
3511 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
3512 PKT_DATA
, s
->rsabuf
, s
->len
,
3513 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
3515 logevent("Trying to enable encryption...");
3519 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
3520 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
3522 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
3523 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
3524 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
3526 ssh
->crcda_ctx
= crcda_make_context();
3527 logevent("Installing CRC compensation attack detector");
3529 if (servkey
.modulus
) {
3530 sfree(servkey
.modulus
);
3531 servkey
.modulus
= NULL
;
3533 if (servkey
.exponent
) {
3534 sfree(servkey
.exponent
);
3535 servkey
.exponent
= NULL
;
3537 if (hostkey
.modulus
) {
3538 sfree(hostkey
.modulus
);
3539 hostkey
.modulus
= NULL
;
3541 if (hostkey
.exponent
) {
3542 sfree(hostkey
.exponent
);
3543 hostkey
.exponent
= NULL
;
3547 if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3548 bombout(("Encryption not successfully enabled"));
3552 logevent("Successfully started encryption");
3554 fflush(stdout
); /* FIXME eh? */
3556 if ((ssh
->username
= get_remote_username(ssh
->conf
)) == NULL
) {
3557 int ret
; /* need not be kept over crReturn */
3558 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3559 s
->cur_prompt
->to_server
= TRUE
;
3560 s
->cur_prompt
->name
= dupstr("SSH login name");
3561 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
);
3562 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3565 crWaitUntil(!pktin
);
3566 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3571 * Failed to get a username. Terminate.
3573 free_prompts(s
->cur_prompt
);
3574 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
3577 ssh
->username
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
3578 free_prompts(s
->cur_prompt
);
3581 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, ssh
->username
, PKT_END
);
3583 char *userlog
= dupprintf("Sent username \"%s\"", ssh
->username
);
3585 if (flags
& FLAG_INTERACTIVE
&&
3586 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
3587 c_write_str(ssh
, userlog
);
3588 c_write_str(ssh
, "\r\n");
3596 if ((s
->supported_auths_mask
& (1 << SSH1_AUTH_RSA
)) == 0) {
3597 /* We must not attempt PK auth. Pretend we've already tried it. */
3598 s
->tried_publickey
= s
->tried_agent
= 1;
3600 s
->tried_publickey
= s
->tried_agent
= 0;
3602 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
3604 * Load the public half of any configured keyfile for later use.
3606 s
->keyfile
= conf_get_filename(ssh
->conf
, CONF_keyfile
);
3607 if (!filename_is_null(s
->keyfile
)) {
3609 logeventf(ssh
, "Reading private key file \"%.150s\"",
3610 filename_to_str(s
->keyfile
));
3611 keytype
= key_type(s
->keyfile
);
3612 if (keytype
== SSH_KEYTYPE_SSH1
) {
3614 if (rsakey_pubblob(s
->keyfile
,
3615 &s
->publickey_blob
, &s
->publickey_bloblen
,
3616 &s
->publickey_comment
, &error
)) {
3617 s
->publickey_encrypted
= rsakey_encrypted(s
->keyfile
,
3621 logeventf(ssh
, "Unable to load private key (%s)", error
);
3622 msgbuf
= dupprintf("Unable to load private key file "
3623 "\"%.150s\" (%s)\r\n",
3624 filename_to_str(s
->keyfile
),
3626 c_write_str(ssh
, msgbuf
);
3628 s
->publickey_blob
= NULL
;
3632 logeventf(ssh
, "Unable to use this key file (%s)",
3633 key_type_to_str(keytype
));
3634 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
3636 filename_to_str(s
->keyfile
),
3637 key_type_to_str(keytype
));
3638 c_write_str(ssh
, msgbuf
);
3640 s
->publickey_blob
= NULL
;
3643 s
->publickey_blob
= NULL
;
3645 while (pktin
->type
== SSH1_SMSG_FAILURE
) {
3646 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
3648 if (conf_get_int(ssh
->conf
, CONF_tryagent
) && agent_exists() && !s
->tried_agent
) {
3650 * Attempt RSA authentication using Pageant.
3656 logevent("Pageant is running. Requesting keys.");
3658 /* Request the keys held by the agent. */
3659 PUT_32BIT(s
->request
, 1);
3660 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
3661 if (!agent_query(s
->request
, 5, &r
, &s
->responselen
,
3662 ssh_agent_callback
, ssh
)) {
3666 bombout(("Unexpected data from server while waiting"
3667 " for agent response"));
3670 } while (pktin
|| inlen
> 0);
3671 r
= ssh
->agent_response
;
3672 s
->responselen
= ssh
->agent_response_len
;
3674 s
->response
= (unsigned char *) r
;
3675 if (s
->response
&& s
->responselen
>= 5 &&
3676 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
3677 s
->p
= s
->response
+ 5;
3678 s
->nkeys
= GET_32BIT(s
->p
);
3680 logeventf(ssh
, "Pageant has %d SSH-1 keys", s
->nkeys
);
3681 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
3682 unsigned char *pkblob
= s
->p
;
3686 do { /* do while (0) to make breaking easy */
3687 n
= ssh1_read_bignum
3688 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3693 n
= ssh1_read_bignum
3694 (s
->p
, s
->responselen
-(s
->p
-s
->response
),
3699 if (s
->responselen
- (s
->p
-s
->response
) < 4)
3701 s
->commentlen
= GET_32BIT(s
->p
);
3703 if (s
->responselen
- (s
->p
-s
->response
) <
3706 s
->commentp
= (char *)s
->p
;
3707 s
->p
+= s
->commentlen
;
3711 logevent("Pageant key list packet was truncated");
3715 if (s
->publickey_blob
) {
3716 if (!memcmp(pkblob
, s
->publickey_blob
,
3717 s
->publickey_bloblen
)) {
3718 logeventf(ssh
, "Pageant key #%d matches "
3719 "configured key file", s
->keyi
);
3720 s
->tried_publickey
= 1;
3722 /* Skip non-configured key */
3725 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
3726 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3727 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3729 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3730 logevent("Key refused");
3733 logevent("Received RSA challenge");
3734 if ((s
->challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3735 bombout(("Server's RSA challenge was badly formatted"));
3740 char *agentreq
, *q
, *ret
;
3743 len
= 1 + 4; /* message type, bit count */
3744 len
+= ssh1_bignum_length(s
->key
.exponent
);
3745 len
+= ssh1_bignum_length(s
->key
.modulus
);
3746 len
+= ssh1_bignum_length(s
->challenge
);
3747 len
+= 16; /* session id */
3748 len
+= 4; /* response format */
3749 agentreq
= snewn(4 + len
, char);
3750 PUT_32BIT(agentreq
, len
);
3752 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
3753 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
3755 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
3756 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
3757 q
+= ssh1_write_bignum(q
, s
->challenge
);
3758 memcpy(q
, s
->session_id
, 16);
3760 PUT_32BIT(q
, 1); /* response format */
3761 if (!agent_query(agentreq
, len
+ 4, &vret
, &retlen
,
3762 ssh_agent_callback
, ssh
)) {
3767 bombout(("Unexpected data from server"
3768 " while waiting for agent"
3772 } while (pktin
|| inlen
> 0);
3773 vret
= ssh
->agent_response
;
3774 retlen
= ssh
->agent_response_len
;
3779 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
3780 logevent("Sending Pageant's response");
3781 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3782 PKT_DATA
, ret
+ 5, 16,
3786 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
3788 ("Pageant's response accepted");
3789 if (flags
& FLAG_VERBOSE
) {
3790 c_write_str(ssh
, "Authenticated using"
3792 c_write(ssh
, s
->commentp
,
3794 c_write_str(ssh
, "\" from agent\r\n");
3799 ("Pageant's response not accepted");
3802 ("Pageant failed to answer challenge");
3806 logevent("No reply received from Pageant");
3809 freebn(s
->key
.exponent
);
3810 freebn(s
->key
.modulus
);
3811 freebn(s
->challenge
);
3816 if (s
->publickey_blob
&& !s
->tried_publickey
)
3817 logevent("Configured key file not in Pageant");
3819 logevent("Failed to get reply from Pageant");
3824 if (s
->publickey_blob
&& !s
->tried_publickey
) {
3826 * Try public key authentication with the specified
3829 int got_passphrase
; /* need not be kept over crReturn */
3830 if (flags
& FLAG_VERBOSE
)
3831 c_write_str(ssh
, "Trying public key authentication.\r\n");
3832 s
->keyfile
= conf_get_filename(ssh
->conf
, CONF_keyfile
);
3833 logeventf(ssh
, "Trying public key \"%s\"",
3834 filename_to_str(s
->keyfile
));
3835 s
->tried_publickey
= 1;
3836 got_passphrase
= FALSE
;
3837 while (!got_passphrase
) {
3839 * Get a passphrase, if necessary.
3841 char *passphrase
= NULL
; /* only written after crReturn */
3843 if (!s
->publickey_encrypted
) {
3844 if (flags
& FLAG_VERBOSE
)
3845 c_write_str(ssh
, "No passphrase required.\r\n");
3848 int ret
; /* need not be kept over crReturn */
3849 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3850 s
->cur_prompt
->to_server
= FALSE
;
3851 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
3852 add_prompt(s
->cur_prompt
,
3853 dupprintf("Passphrase for key \"%.100s\": ",
3854 s
->publickey_comment
), FALSE
);
3855 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
3858 crWaitUntil(!pktin
);
3859 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
3863 /* Failed to get a passphrase. Terminate. */
3864 free_prompts(s
->cur_prompt
);
3865 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
3869 passphrase
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
3870 free_prompts(s
->cur_prompt
);
3873 * Try decrypting key with passphrase.
3875 s
->keyfile
= conf_get_filename(ssh
->conf
, CONF_keyfile
);
3876 ret
= loadrsakey(s
->keyfile
, &s
->key
, passphrase
,
3879 smemclr(passphrase
, strlen(passphrase
));
3883 /* Correct passphrase. */
3884 got_passphrase
= TRUE
;
3885 } else if (ret
== 0) {
3886 c_write_str(ssh
, "Couldn't load private key from ");
3887 c_write_str(ssh
, filename_to_str(s
->keyfile
));
3888 c_write_str(ssh
, " (");
3889 c_write_str(ssh
, error
);
3890 c_write_str(ssh
, ").\r\n");
3891 got_passphrase
= FALSE
;
3892 break; /* go and try something else */
3893 } else if (ret
== -1) {
3894 c_write_str(ssh
, "Wrong passphrase.\r\n"); /* FIXME */
3895 got_passphrase
= FALSE
;
3898 assert(0 && "unexpected return from loadrsakey()");
3899 got_passphrase
= FALSE
; /* placate optimisers */
3903 if (got_passphrase
) {
3906 * Send a public key attempt.
3908 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
3909 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
3912 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3913 c_write_str(ssh
, "Server refused our public key.\r\n");
3914 continue; /* go and try something else */
3916 if (pktin
->type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
3917 bombout(("Bizarre response to offer of public key"));
3923 unsigned char buffer
[32];
3924 Bignum challenge
, response
;
3926 if ((challenge
= ssh1_pkt_getmp(pktin
)) == NULL
) {
3927 bombout(("Server's RSA challenge was badly formatted"));
3930 response
= rsadecrypt(challenge
, &s
->key
);
3931 freebn(s
->key
.private_exponent
);/* burn the evidence */
3933 for (i
= 0; i
< 32; i
++) {
3934 buffer
[i
] = bignum_byte(response
, 31 - i
);
3938 MD5Update(&md5c
, buffer
, 32);
3939 MD5Update(&md5c
, s
->session_id
, 16);
3940 MD5Final(buffer
, &md5c
);
3942 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
3943 PKT_DATA
, buffer
, 16, PKT_END
);
3950 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
3951 if (flags
& FLAG_VERBOSE
)
3952 c_write_str(ssh
, "Failed to authenticate with"
3953 " our public key.\r\n");
3954 continue; /* go and try something else */
3955 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
3956 bombout(("Bizarre response to RSA authentication response"));
3960 break; /* we're through! */
3966 * Otherwise, try various forms of password-like authentication.
3968 s
->cur_prompt
= new_prompts(ssh
->frontend
);
3970 if (conf_get_int(ssh
->conf
, CONF_try_tis_auth
) &&
3971 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
3972 !s
->tis_auth_refused
) {
3973 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
3974 logevent("Requested TIS authentication");
3975 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
3977 if (pktin
->type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
3978 logevent("TIS authentication declined");
3979 if (flags
& FLAG_INTERACTIVE
)
3980 c_write_str(ssh
, "TIS authentication refused.\r\n");
3981 s
->tis_auth_refused
= 1;
3986 char *instr_suf
, *prompt
;
3988 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
3990 bombout(("TIS challenge packet was badly formed"));
3993 logevent("Received TIS challenge");
3994 s
->cur_prompt
->to_server
= TRUE
;
3995 s
->cur_prompt
->name
= dupstr("SSH TIS authentication");
3996 /* Prompt heuristic comes from OpenSSH */
3997 if (memchr(challenge
, '\n', challengelen
)) {
3998 instr_suf
= dupstr("");
3999 prompt
= dupprintf("%.*s", challengelen
, challenge
);
4001 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
4002 prompt
= dupstr("Response: ");
4004 s
->cur_prompt
->instruction
=
4005 dupprintf("Using TIS authentication.%s%s",
4006 (*instr_suf
) ?
"\n" : "",
4008 s
->cur_prompt
->instr_reqd
= TRUE
;
4009 add_prompt(s
->cur_prompt
, prompt
, FALSE
);
4013 if (conf_get_int(ssh
->conf
, CONF_try_tis_auth
) &&
4014 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
4015 !s
->ccard_auth_refused
) {
4016 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
4017 logevent("Requested CryptoCard authentication");
4018 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
4020 if (pktin
->type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
4021 logevent("CryptoCard authentication declined");
4022 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
4023 s
->ccard_auth_refused
= 1;
4028 char *instr_suf
, *prompt
;
4030 ssh_pkt_getstring(pktin
, &challenge
, &challengelen
);
4032 bombout(("CryptoCard challenge packet was badly formed"));
4035 logevent("Received CryptoCard challenge");
4036 s
->cur_prompt
->to_server
= TRUE
;
4037 s
->cur_prompt
->name
= dupstr("SSH CryptoCard authentication");
4038 s
->cur_prompt
->name_reqd
= FALSE
;
4039 /* Prompt heuristic comes from OpenSSH */
4040 if (memchr(challenge
, '\n', challengelen
)) {
4041 instr_suf
= dupstr("");
4042 prompt
= dupprintf("%.*s", challengelen
, challenge
);
4044 instr_suf
= dupprintf("%.*s", challengelen
, challenge
);
4045 prompt
= dupstr("Response: ");
4047 s
->cur_prompt
->instruction
=
4048 dupprintf("Using CryptoCard authentication.%s%s",
4049 (*instr_suf
) ?
"\n" : "",
4051 s
->cur_prompt
->instr_reqd
= TRUE
;
4052 add_prompt(s
->cur_prompt
, prompt
, FALSE
);
4056 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
4057 if ((s
->supported_auths_mask
& (1 << SSH1_AUTH_PASSWORD
)) == 0) {
4058 bombout(("No supported authentication methods available"));
4061 s
->cur_prompt
->to_server
= TRUE
;
4062 s
->cur_prompt
->name
= dupstr("SSH password");
4063 add_prompt(s
->cur_prompt
, dupprintf("%s@%s's password: ",
4064 ssh
->username
, ssh
->savedhost
),
4069 * Show password prompt, having first obtained it via a TIS
4070 * or CryptoCard exchange if we're doing TIS or CryptoCard
4074 int ret
; /* need not be kept over crReturn */
4075 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
4078 crWaitUntil(!pktin
);
4079 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
4084 * Failed to get a password (for example
4085 * because one was supplied on the command line
4086 * which has already failed to work). Terminate.
4088 free_prompts(s
->cur_prompt
);
4089 ssh_disconnect(ssh
, NULL
, "Unable to authenticate", 0, TRUE
);
4094 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
4096 * Defence against traffic analysis: we send a
4097 * whole bunch of packets containing strings of
4098 * different lengths. One of these strings is the
4099 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4100 * The others are all random data in
4101 * SSH1_MSG_IGNORE packets. This way a passive
4102 * listener can't tell which is the password, and
4103 * hence can't deduce the password length.
4105 * Anybody with a password length greater than 16
4106 * bytes is going to have enough entropy in their
4107 * password that a listener won't find it _that_
4108 * much help to know how long it is. So what we'll
4111 * - if password length < 16, we send 15 packets
4112 * containing string lengths 1 through 15
4114 * - otherwise, we let N be the nearest multiple
4115 * of 8 below the password length, and send 8
4116 * packets containing string lengths N through
4117 * N+7. This won't obscure the order of
4118 * magnitude of the password length, but it will
4119 * introduce a bit of extra uncertainty.
4121 * A few servers can't deal with SSH1_MSG_IGNORE, at
4122 * least in this context. For these servers, we need
4123 * an alternative defence. We make use of the fact
4124 * that the password is interpreted as a C string:
4125 * so we can append a NUL, then some random data.
4127 * A few servers can deal with neither SSH1_MSG_IGNORE
4128 * here _nor_ a padded password string.
4129 * For these servers we are left with no defences
4130 * against password length sniffing.
4132 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) &&
4133 !(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
4135 * The server can deal with SSH1_MSG_IGNORE, so
4136 * we can use the primary defence.
4138 int bottom
, top
, pwlen
, i
;
4141 pwlen
= strlen(s
->cur_prompt
->prompts
[0]->result
);
4143 bottom
= 0; /* zero length passwords are OK! :-) */
4146 bottom
= pwlen
& ~7;
4150 assert(pwlen
>= bottom
&& pwlen
<= top
);
4152 randomstr
= snewn(top
+ 1, char);
4154 for (i
= bottom
; i
<= top
; i
++) {
4156 defer_packet(ssh
, s
->pwpkt_type
,
4157 PKTT_PASSWORD
, PKT_STR
,
4158 s
->cur_prompt
->prompts
[0]->result
,
4159 PKTT_OTHER
, PKT_END
);
4161 for (j
= 0; j
< i
; j
++) {
4163 randomstr
[j
] = random_byte();
4164 } while (randomstr
[j
] == '\0');
4166 randomstr
[i
] = '\0';
4167 defer_packet(ssh
, SSH1_MSG_IGNORE
,
4168 PKT_STR
, randomstr
, PKT_END
);
4171 logevent("Sending password with camouflage packets");
4172 ssh_pkt_defersend(ssh
);
4175 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
4177 * The server can't deal with SSH1_MSG_IGNORE
4178 * but can deal with padded passwords, so we
4179 * can use the secondary defence.
4185 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
4186 if (len
< sizeof(string
)) {
4188 strcpy(string
, s
->cur_prompt
->prompts
[0]->result
);
4189 len
++; /* cover the zero byte */
4190 while (len
< sizeof(string
)) {
4191 string
[len
++] = (char) random_byte();
4194 ss
= s
->cur_prompt
->prompts
[0]->result
;
4196 logevent("Sending length-padded password");
4197 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
4198 PKT_INT
, len
, PKT_DATA
, ss
, len
,
4199 PKTT_OTHER
, PKT_END
);
4202 * The server is believed unable to cope with
4203 * any of our password camouflage methods.
4206 len
= strlen(s
->cur_prompt
->prompts
[0]->result
);
4207 logevent("Sending unpadded password");
4208 send_packet(ssh
, s
->pwpkt_type
,
4209 PKTT_PASSWORD
, PKT_INT
, len
,
4210 PKT_DATA
, s
->cur_prompt
->prompts
[0]->result
, len
,
4211 PKTT_OTHER
, PKT_END
);
4214 send_packet(ssh
, s
->pwpkt_type
, PKTT_PASSWORD
,
4215 PKT_STR
, s
->cur_prompt
->prompts
[0]->result
,
4216 PKTT_OTHER
, PKT_END
);
4218 logevent("Sent password");
4219 free_prompts(s
->cur_prompt
);
4221 if (pktin
->type
== SSH1_SMSG_FAILURE
) {
4222 if (flags
& FLAG_VERBOSE
)
4223 c_write_str(ssh
, "Access denied\r\n");
4224 logevent("Authentication refused");
4225 } else if (pktin
->type
!= SSH1_SMSG_SUCCESS
) {
4226 bombout(("Strange packet received, type %d", pktin
->type
));
4232 if (s
->publickey_blob
) {
4233 sfree(s
->publickey_blob
);
4234 sfree(s
->publickey_comment
);
4237 logevent("Authentication successful");
4242 static void ssh_channel_try_eof(struct ssh_channel
*c
)
4245 assert(c
->pending_eof
); /* precondition for calling us */
4247 return; /* can't close: not even opened yet */
4248 if (ssh
->version
== 2 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0)
4249 return; /* can't send EOF: pending outgoing data */
4251 c
->pending_eof
= FALSE
; /* we're about to send it */
4252 if (ssh
->version
== 1) {
4253 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
4255 c
->closes
|= CLOSES_SENT_EOF
;
4257 struct Packet
*pktout
;
4258 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4259 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
4260 ssh2_pkt_send(ssh
, pktout
);
4261 c
->closes
|= CLOSES_SENT_EOF
;
4262 ssh2_channel_check_close(c
);
4266 void sshfwd_write_eof(struct ssh_channel
*c
)
4270 if (ssh
->state
== SSH_STATE_CLOSED
)
4273 if (c
->closes
& CLOSES_SENT_EOF
)
4276 c
->pending_eof
= TRUE
;
4277 ssh_channel_try_eof(c
);
4280 void sshfwd_unclean_close(struct ssh_channel
*c
)
4284 if (ssh
->state
== SSH_STATE_CLOSED
)
4289 x11_close(c
->u
.x11
.s
);
4290 logevent("Forwarded X11 connection terminated due to local error");
4293 case CHAN_SOCKDATA_DORMANT
:
4294 pfd_close(c
->u
.pfd
.s
);
4295 logevent("Forwarded port closed due to local error");
4298 c
->type
= CHAN_ZOMBIE
;
4300 ssh2_channel_check_close(c
);
4303 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
4307 if (ssh
->state
== SSH_STATE_CLOSED
)
4310 if (ssh
->version
== 1) {
4311 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
4312 PKT_INT
, c
->remoteid
,
4313 PKT_INT
, len
, PKTT_DATA
, PKT_DATA
, buf
, len
,
4314 PKTT_OTHER
, PKT_END
);
4316 * In SSH-1 we can return 0 here - implying that forwarded
4317 * connections are never individually throttled - because
4318 * the only circumstance that can cause throttling will be
4319 * the whole SSH connection backing up, in which case
4320 * _everything_ will be throttled as a whole.
4324 ssh2_add_channel_data(c
, buf
, len
);
4325 return ssh2_try_send(c
);
4329 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
4334 if (ssh
->state
== SSH_STATE_CLOSED
)
4337 if (ssh
->version
== 1) {
4338 buflimit
= SSH1_BUFFER_LIMIT
;
4340 buflimit
= c
->v
.v2
.locmaxwin
;
4341 ssh2_set_window(c
, bufsize
< buflimit ? buflimit
- bufsize
: 0);
4343 if (c
->throttling_conn
&& bufsize
<= buflimit
) {
4344 c
->throttling_conn
= 0;
4345 ssh_throttle_conn(ssh
, -1);
4349 static void ssh_queueing_handler(Ssh ssh
, struct Packet
*pktin
)
4351 struct queued_handler
*qh
= ssh
->qhead
;
4355 assert(pktin
->type
== qh
->msg1
|| pktin
->type
== qh
->msg2
);
4358 assert(ssh
->packet_dispatch
[qh
->msg1
] == ssh_queueing_handler
);
4359 ssh
->packet_dispatch
[qh
->msg1
] = ssh
->q_saved_handler1
;
4362 assert(ssh
->packet_dispatch
[qh
->msg2
] == ssh_queueing_handler
);
4363 ssh
->packet_dispatch
[qh
->msg2
] = ssh
->q_saved_handler2
;
4367 ssh
->qhead
= qh
->next
;
4369 if (ssh
->qhead
->msg1
> 0) {
4370 ssh
->q_saved_handler1
= ssh
->packet_dispatch
[ssh
->qhead
->msg1
];
4371 ssh
->packet_dispatch
[ssh
->qhead
->msg1
] = ssh_queueing_handler
;
4373 if (ssh
->qhead
->msg2
> 0) {
4374 ssh
->q_saved_handler2
= ssh
->packet_dispatch
[ssh
->qhead
->msg2
];
4375 ssh
->packet_dispatch
[ssh
->qhead
->msg2
] = ssh_queueing_handler
;
4378 ssh
->qhead
= ssh
->qtail
= NULL
;
4381 qh
->handler(ssh
, pktin
, qh
->ctx
);
4386 static void ssh_queue_handler(Ssh ssh
, int msg1
, int msg2
,
4387 chandler_fn_t handler
, void *ctx
)
4389 struct queued_handler
*qh
;
4391 qh
= snew(struct queued_handler
);
4394 qh
->handler
= handler
;
4398 if (ssh
->qtail
== NULL
) {
4402 ssh
->q_saved_handler1
= ssh
->packet_dispatch
[ssh
->qhead
->msg1
];
4403 ssh
->packet_dispatch
[qh
->msg1
] = ssh_queueing_handler
;
4406 ssh
->q_saved_handler2
= ssh
->packet_dispatch
[ssh
->qhead
->msg2
];
4407 ssh
->packet_dispatch
[qh
->msg2
] = ssh_queueing_handler
;
4410 ssh
->qtail
->next
= qh
;
4415 static void ssh_rportfwd_succfail(Ssh ssh
, struct Packet
*pktin
, void *ctx
)
4417 struct ssh_rportfwd
*rpf
, *pf
= (struct ssh_rportfwd
*)ctx
;
4419 if (pktin
->type
== (ssh
->version
== 1 ? SSH1_SMSG_SUCCESS
:
4420 SSH2_MSG_REQUEST_SUCCESS
)) {
4421 logeventf(ssh
, "Remote port forwarding from %s enabled",
4424 logeventf(ssh
, "Remote port forwarding from %s refused",
4427 rpf
= del234(ssh
->rportfwds
, pf
);
4429 pf
->pfrec
->remote
= NULL
;
4434 static void ssh_setup_portfwd(Ssh ssh
, Conf
*conf
)
4436 struct ssh_portfwd
*epf
;
4440 if (!ssh
->portfwds
) {
4441 ssh
->portfwds
= newtree234(ssh_portcmp
);
4444 * Go through the existing port forwardings and tag them
4445 * with status==DESTROY. Any that we want to keep will be
4446 * re-enabled (status==KEEP) as we go through the
4447 * configuration and find out which bits are the same as
4450 struct ssh_portfwd
*epf
;
4452 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4453 epf
->status
= DESTROY
;
4456 for (val
= conf_get_str_strs(conf
, CONF_portfwd
, NULL
, &key
);
4458 val
= conf_get_str_strs(conf
, CONF_portfwd
, key
, &key
)) {
4459 char *kp
, *kp2
, *vp
, *vp2
;
4460 char address_family
, type
;
4461 int sport
,dport
,sserv
,dserv
;
4462 char *sports
, *dports
, *saddr
, *host
;
4466 address_family
= 'A';
4468 if (*kp
== 'A' || *kp
== '4' || *kp
== '6')
4469 address_family
= *kp
++;
4470 if (*kp
== 'L' || *kp
== 'R')
4473 if ((kp2
= strchr(kp
, ':')) != NULL
) {
4475 * There's a colon in the middle of the source port
4476 * string, which means that the part before it is
4477 * actually a source address.
4479 saddr
= dupprintf("%.*s", (int)(kp2
- kp
), kp
);
4485 sport
= atoi(sports
);
4489 sport
= net_service_lookup(sports
);
4491 logeventf(ssh
, "Service lookup failed for source"
4492 " port \"%s\"", sports
);
4496 if (type
== 'L' && !strcmp(val
, "D")) {
4497 /* dynamic forwarding */
4504 /* ordinary forwarding */
4506 vp2
= vp
+ strcspn(vp
, ":");
4507 host
= dupprintf("%.*s", (int)(vp2
- vp
), vp
);
4511 dport
= atoi(dports
);
4515 dport
= net_service_lookup(dports
);
4517 logeventf(ssh
, "Service lookup failed for destination"
4518 " port \"%s\"", dports
);
4523 if (sport
&& dport
) {
4524 /* Set up a description of the source port. */
4525 struct ssh_portfwd
*pfrec
, *epfrec
;
4527 pfrec
= snew(struct ssh_portfwd
);
4529 pfrec
->saddr
= saddr
;
4530 pfrec
->sserv
= sserv ?
dupstr(sports
) : NULL
;
4531 pfrec
->sport
= sport
;
4532 pfrec
->daddr
= host
;
4533 pfrec
->dserv
= dserv ?
dupstr(dports
) : NULL
;
4534 pfrec
->dport
= dport
;
4535 pfrec
->local
= NULL
;
4536 pfrec
->remote
= NULL
;
4537 pfrec
->addressfamily
= (address_family
== '4' ? ADDRTYPE_IPV4
:
4538 address_family
== '6' ? ADDRTYPE_IPV6
:
4541 epfrec
= add234(ssh
->portfwds
, pfrec
);
4542 if (epfrec
!= pfrec
) {
4543 if (epfrec
->status
== DESTROY
) {
4545 * We already have a port forwarding up and running
4546 * with precisely these parameters. Hence, no need
4547 * to do anything; simply re-tag the existing one
4550 epfrec
->status
= KEEP
;
4553 * Anything else indicates that there was a duplicate
4554 * in our input, which we'll silently ignore.
4556 free_portfwd(pfrec
);
4558 pfrec
->status
= CREATE
;
4567 * Now go through and destroy any port forwardings which were
4570 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4571 if (epf
->status
== DESTROY
) {
4574 message
= dupprintf("%s port forwarding from %s%s%d",
4575 epf
->type
== 'L' ?
"local" :
4576 epf
->type
== 'R' ?
"remote" : "dynamic",
4577 epf
->saddr ? epf
->saddr
: "",
4578 epf
->saddr ?
":" : "",
4581 if (epf
->type
!= 'D') {
4582 char *msg2
= dupprintf("%s to %s:%d", message
,
4583 epf
->daddr
, epf
->dport
);
4588 logeventf(ssh
, "Cancelling %s", message
);
4591 /* epf->remote or epf->local may be NULL if setting up a
4592 * forwarding failed. */
4594 struct ssh_rportfwd
*rpf
= epf
->remote
;
4595 struct Packet
*pktout
;
4598 * Cancel the port forwarding at the server
4601 if (ssh
->version
== 1) {
4603 * We cannot cancel listening ports on the
4604 * server side in SSH-1! There's no message
4605 * to support it. Instead, we simply remove
4606 * the rportfwd record from the local end
4607 * so that any connections the server tries
4608 * to make on it are rejected.
4611 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4612 ssh2_pkt_addstring(pktout
, "cancel-tcpip-forward");
4613 ssh2_pkt_addbool(pktout
, 0);/* _don't_ want reply */
4615 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4616 } else if (conf_get_int(conf
, CONF_rport_acceptall
)) {
4617 /* XXX: rport_acceptall may not represent
4618 * what was used to open the original connection,
4619 * since it's reconfigurable. */
4620 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4622 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4624 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4625 ssh2_pkt_send(ssh
, pktout
);
4628 del234(ssh
->rportfwds
, rpf
);
4630 } else if (epf
->local
) {
4631 pfd_terminate(epf
->local
);
4634 delpos234(ssh
->portfwds
, i
);
4636 i
--; /* so we don't skip one in the list */
4640 * And finally, set up any new port forwardings (status==CREATE).
4642 for (i
= 0; (epf
= index234(ssh
->portfwds
, i
)) != NULL
; i
++)
4643 if (epf
->status
== CREATE
) {
4644 char *sportdesc
, *dportdesc
;
4645 sportdesc
= dupprintf("%s%s%s%s%d%s",
4646 epf
->saddr ? epf
->saddr
: "",
4647 epf
->saddr ?
":" : "",
4648 epf
->sserv ? epf
->sserv
: "",
4649 epf
->sserv ?
"(" : "",
4651 epf
->sserv ?
")" : "");
4652 if (epf
->type
== 'D') {
4655 dportdesc
= dupprintf("%s:%s%s%d%s",
4657 epf
->dserv ? epf
->dserv
: "",
4658 epf
->dserv ?
"(" : "",
4660 epf
->dserv ?
")" : "");
4663 if (epf
->type
== 'L') {
4664 const char *err
= pfd_addforward(epf
->daddr
, epf
->dport
,
4665 epf
->saddr
, epf
->sport
,
4668 epf
->addressfamily
);
4670 logeventf(ssh
, "Local %sport %s forwarding to %s%s%s",
4671 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4672 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4673 sportdesc
, dportdesc
,
4674 err ?
" failed: " : "", err ? err
: "");
4675 } else if (epf
->type
== 'D') {
4676 const char *err
= pfd_addforward(NULL
, -1,
4677 epf
->saddr
, epf
->sport
,
4680 epf
->addressfamily
);
4682 logeventf(ssh
, "Local %sport %s SOCKS dynamic forwarding%s%s",
4683 epf
->addressfamily
== ADDRTYPE_IPV4 ?
"IPv4 " :
4684 epf
->addressfamily
== ADDRTYPE_IPV6 ?
"IPv6 " : "",
4686 err ?
" failed: " : "", err ? err
: "");
4688 struct ssh_rportfwd
*pf
;
4691 * Ensure the remote port forwardings tree exists.
4693 if (!ssh
->rportfwds
) {
4694 if (ssh
->version
== 1)
4695 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
4697 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4700 pf
= snew(struct ssh_rportfwd
);
4701 strncpy(pf
->dhost
, epf
->daddr
, lenof(pf
->dhost
)-1);
4702 pf
->dhost
[lenof(pf
->dhost
)-1] = '\0';
4703 pf
->dport
= epf
->dport
;
4704 pf
->sport
= epf
->sport
;
4705 if (add234(ssh
->rportfwds
, pf
) != pf
) {
4706 logeventf(ssh
, "Duplicate remote port forwarding to %s:%d",
4707 epf
->daddr
, epf
->dport
);
4710 logeventf(ssh
, "Requesting remote port %s"
4711 " forward to %s", sportdesc
, dportdesc
);
4713 pf
->sportdesc
= sportdesc
;
4718 if (ssh
->version
== 1) {
4719 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
4720 PKT_INT
, epf
->sport
,
4721 PKT_STR
, epf
->daddr
,
4722 PKT_INT
, epf
->dport
,
4724 ssh_queue_handler(ssh
, SSH1_SMSG_SUCCESS
,
4726 ssh_rportfwd_succfail
, pf
);
4728 struct Packet
*pktout
;
4729 pktout
= ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4730 ssh2_pkt_addstring(pktout
, "tcpip-forward");
4731 ssh2_pkt_addbool(pktout
, 1);/* want reply */
4733 ssh2_pkt_addstring(pktout
, epf
->saddr
);
4734 } else if (conf_get_int(conf
, CONF_rport_acceptall
)) {
4735 ssh2_pkt_addstring(pktout
, "0.0.0.0");
4737 ssh2_pkt_addstring(pktout
, "127.0.0.1");
4739 ssh2_pkt_adduint32(pktout
, epf
->sport
);
4740 ssh2_pkt_send(ssh
, pktout
);
4742 ssh_queue_handler(ssh
, SSH2_MSG_REQUEST_SUCCESS
,
4743 SSH2_MSG_REQUEST_FAILURE
,
4744 ssh_rportfwd_succfail
, pf
);
4753 static void ssh1_smsg_stdout_stderr_data(Ssh ssh
, struct Packet
*pktin
)
4756 int stringlen
, bufsize
;
4758 ssh_pkt_getstring(pktin
, &string
, &stringlen
);
4759 if (string
== NULL
) {
4760 bombout(("Incoming terminal data packet was badly formed"));
4764 bufsize
= from_backend(ssh
->frontend
, pktin
->type
== SSH1_SMSG_STDERR_DATA
,
4766 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
4767 ssh
->v1_stdout_throttling
= 1;
4768 ssh_throttle_conn(ssh
, +1);
4772 static void ssh1_smsg_x11_open(Ssh ssh
, struct Packet
*pktin
)
4774 /* Remote side is trying to open a channel to talk to our
4775 * X-Server. Give them back a local channel number. */
4776 struct ssh_channel
*c
;
4777 int remoteid
= ssh_pkt_getuint32(pktin
);
4779 logevent("Received X11 connect request");
4780 /* Refuse if X11 forwarding is disabled. */
4781 if (!ssh
->X11_fwd_enabled
) {
4782 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4783 PKT_INT
, remoteid
, PKT_END
);
4784 logevent("Rejected X11 connect request");
4786 c
= snew(struct ssh_channel
);
4789 if (x11_init(&c
->u
.x11
.s
, ssh
->x11disp
, c
,
4790 NULL
, -1, ssh
->conf
) != NULL
) {
4791 logevent("Opening X11 forward connection failed");
4793 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4794 PKT_INT
, remoteid
, PKT_END
);
4797 ("Opening X11 forward connection succeeded");
4798 c
->remoteid
= remoteid
;
4799 c
->halfopen
= FALSE
;
4800 c
->localid
= alloc_channel_id(ssh
);
4802 c
->pending_eof
= FALSE
;
4803 c
->throttling_conn
= 0;
4804 c
->type
= CHAN_X11
; /* identify channel type */
4805 add234(ssh
->channels
, c
);
4806 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4807 PKT_INT
, c
->remoteid
, PKT_INT
,
4808 c
->localid
, PKT_END
);
4809 logevent("Opened X11 forward channel");
4814 static void ssh1_smsg_agent_open(Ssh ssh
, struct Packet
*pktin
)
4816 /* Remote side is trying to open a channel to talk to our
4817 * agent. Give them back a local channel number. */
4818 struct ssh_channel
*c
;
4819 int remoteid
= ssh_pkt_getuint32(pktin
);
4821 /* Refuse if agent forwarding is disabled. */
4822 if (!ssh
->agentfwd_enabled
) {
4823 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4824 PKT_INT
, remoteid
, PKT_END
);
4826 c
= snew(struct ssh_channel
);
4828 c
->remoteid
= remoteid
;
4829 c
->halfopen
= FALSE
;
4830 c
->localid
= alloc_channel_id(ssh
);
4832 c
->pending_eof
= FALSE
;
4833 c
->throttling_conn
= 0;
4834 c
->type
= CHAN_AGENT
; /* identify channel type */
4835 c
->u
.a
.lensofar
= 0;
4836 c
->u
.a
.message
= NULL
;
4837 add234(ssh
->channels
, c
);
4838 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4839 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
4844 static void ssh1_msg_port_open(Ssh ssh
, struct Packet
*pktin
)
4846 /* Remote side is trying to open a channel to talk to a
4847 * forwarded port. Give them back a local channel number. */
4848 struct ssh_channel
*c
;
4849 struct ssh_rportfwd pf
, *pfp
;
4854 c
= snew(struct ssh_channel
);
4857 remoteid
= ssh_pkt_getuint32(pktin
);
4858 ssh_pkt_getstring(pktin
, &host
, &hostsize
);
4859 port
= ssh_pkt_getuint32(pktin
);
4861 if (hostsize
>= lenof(pf
.dhost
))
4862 hostsize
= lenof(pf
.dhost
)-1;
4863 memcpy(pf
.dhost
, host
, hostsize
);
4864 pf
.dhost
[hostsize
] = '\0';
4866 pfp
= find234(ssh
->rportfwds
, &pf
, NULL
);
4869 logeventf(ssh
, "Rejected remote port open request for %s:%d",
4871 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4872 PKT_INT
, remoteid
, PKT_END
);
4874 logeventf(ssh
, "Received remote port open request for %s:%d",
4876 e
= pfd_newconnect(&c
->u
.pfd
.s
, pf
.dhost
, port
,
4877 c
, ssh
->conf
, pfp
->pfrec
->addressfamily
);
4879 logeventf(ssh
, "Port open failed: %s", e
);
4881 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
4882 PKT_INT
, remoteid
, PKT_END
);
4884 c
->remoteid
= remoteid
;
4885 c
->halfopen
= FALSE
;
4886 c
->localid
= alloc_channel_id(ssh
);
4888 c
->pending_eof
= FALSE
;
4889 c
->throttling_conn
= 0;
4890 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4891 add234(ssh
->channels
, c
);
4892 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
4893 PKT_INT
, c
->remoteid
, PKT_INT
,
4894 c
->localid
, PKT_END
);
4895 logevent("Forwarded port opened successfully");
4900 static void ssh1_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
4902 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4903 unsigned int localid
= ssh_pkt_getuint32(pktin
);
4904 struct ssh_channel
*c
;
4906 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4907 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4908 c
->remoteid
= localid
;
4909 c
->halfopen
= FALSE
;
4910 c
->type
= CHAN_SOCKDATA
;
4911 c
->throttling_conn
= 0;
4912 pfd_confirm(c
->u
.pfd
.s
);
4915 if (c
&& c
->pending_eof
) {
4917 * We have a pending close on this channel,
4918 * which we decided on before the server acked
4919 * the channel open. So now we know the
4920 * remoteid, we can close it again.
4922 ssh_channel_try_eof(c
);
4926 static void ssh1_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
4928 unsigned int remoteid
= ssh_pkt_getuint32(pktin
);
4929 struct ssh_channel
*c
;
4931 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
4932 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
4933 logevent("Forwarded connection refused by server");
4934 pfd_close(c
->u
.pfd
.s
);
4935 del234(ssh
->channels
, c
);
4940 static void ssh1_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
4942 /* Remote side closes a channel. */
4943 unsigned i
= ssh_pkt_getuint32(pktin
);
4944 struct ssh_channel
*c
;
4945 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
4946 if (c
&& !c
->halfopen
) {
4948 if (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE
&&
4949 !(c
->closes
& CLOSES_RCVD_EOF
)) {
4951 * Received CHANNEL_CLOSE, which we translate into
4954 int send_close
= FALSE
;
4956 c
->closes
|= CLOSES_RCVD_EOF
;
4961 x11_send_eof(c
->u
.x11
.s
);
4967 pfd_send_eof(c
->u
.pfd
.s
);
4976 if (send_close
&& !(c
->closes
& CLOSES_SENT_EOF
)) {
4977 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
4979 c
->closes
|= CLOSES_SENT_EOF
;
4983 if (pktin
->type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
&&
4984 !(c
->closes
& CLOSES_RCVD_CLOSE
)) {
4986 if (!(c
->closes
& CLOSES_SENT_EOF
)) {
4987 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4988 " for which we never sent CHANNEL_CLOSE\n", i
));
4991 c
->closes
|= CLOSES_RCVD_CLOSE
;
4994 if (!((CLOSES_SENT_EOF
| CLOSES_RCVD_EOF
) & ~c
->closes
) &&
4995 !(c
->closes
& CLOSES_SENT_CLOSE
)) {
4996 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
,
4997 PKT_INT
, c
->remoteid
, PKT_END
);
4998 c
->closes
|= CLOSES_SENT_CLOSE
;
5001 if (!((CLOSES_SENT_CLOSE
| CLOSES_RCVD_CLOSE
) & ~c
->closes
))
5002 ssh_channel_destroy(c
);
5004 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5005 pktin
->type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
5006 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
5011 static void ssh1_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
5013 /* Data sent down one of our channels. */
5014 int i
= ssh_pkt_getuint32(pktin
);
5017 struct ssh_channel
*c
;
5019 ssh_pkt_getstring(pktin
, &p
, &len
);
5021 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5026 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
5029 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
5032 /* Data for an agent message. Buffer it. */
5034 if (c
->u
.a
.lensofar
< 4) {
5035 unsigned int l
= min(4 - c
->u
.a
.lensofar
, (unsigned)len
);
5036 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
5040 c
->u
.a
.lensofar
+= l
;
5042 if (c
->u
.a
.lensofar
== 4) {
5044 4 + GET_32BIT(c
->u
.a
.msglen
);
5045 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
5047 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5049 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
5051 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5053 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
5057 c
->u
.a
.lensofar
+= l
;
5059 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5062 if (agent_query(c
->u
.a
.message
,
5065 ssh_agentf_callback
, c
))
5066 ssh_agentf_callback(c
, reply
, replylen
);
5067 sfree(c
->u
.a
.message
);
5068 c
->u
.a
.lensofar
= 0;
5071 bufsize
= 0; /* agent channels never back up */
5074 if (!c
->throttling_conn
&& bufsize
> SSH1_BUFFER_LIMIT
) {
5075 c
->throttling_conn
= 1;
5076 ssh_throttle_conn(ssh
, +1);
5081 static void ssh1_smsg_exit_status(Ssh ssh
, struct Packet
*pktin
)
5083 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
5084 logeventf(ssh
, "Server sent command exit status %d", ssh
->exitcode
);
5085 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
5087 * In case `helpful' firewalls or proxies tack
5088 * extra human-readable text on the end of the
5089 * session which we might mistake for another
5090 * encrypted packet, we close the session once
5091 * we've sent EXIT_CONFIRMATION.
5093 ssh_disconnect(ssh
, NULL
, NULL
, 0, TRUE
);
5096 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5097 static void ssh1_send_ttymode(void *data
, char *mode
, char *val
)
5099 struct Packet
*pktout
= (struct Packet
*)data
;
5101 unsigned int arg
= 0;
5102 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
5103 if (i
== lenof(ssh_ttymodes
)) return;
5104 switch (ssh_ttymodes
[i
].type
) {
5106 arg
= ssh_tty_parse_specchar(val
);
5109 arg
= ssh_tty_parse_boolean(val
);
5112 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
5113 ssh2_pkt_addbyte(pktout
, arg
);
5117 static void do_ssh1_connection(Ssh ssh
, unsigned char *in
, int inlen
,
5118 struct Packet
*pktin
)
5120 crBegin(ssh
->do_ssh1_connection_crstate
);
5122 ssh
->packet_dispatch
[SSH1_SMSG_STDOUT_DATA
] =
5123 ssh
->packet_dispatch
[SSH1_SMSG_STDERR_DATA
] =
5124 ssh1_smsg_stdout_stderr_data
;
5126 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
] =
5127 ssh1_msg_channel_open_confirmation
;
5128 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_OPEN_FAILURE
] =
5129 ssh1_msg_channel_open_failure
;
5130 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE
] =
5131 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
] =
5132 ssh1_msg_channel_close
;
5133 ssh
->packet_dispatch
[SSH1_MSG_CHANNEL_DATA
] = ssh1_msg_channel_data
;
5134 ssh
->packet_dispatch
[SSH1_SMSG_EXIT_STATUS
] = ssh1_smsg_exit_status
;
5136 if (conf_get_int(ssh
->conf
, CONF_agentfwd
) && agent_exists()) {
5137 logevent("Requesting agent forwarding");
5138 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
5142 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5143 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5144 bombout(("Protocol confusion"));
5146 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5147 logevent("Agent forwarding refused");
5149 logevent("Agent forwarding enabled");
5150 ssh
->agentfwd_enabled
= TRUE
;
5151 ssh
->packet_dispatch
[SSH1_SMSG_AGENT_OPEN
] = ssh1_smsg_agent_open
;
5155 if (conf_get_int(ssh
->conf
, CONF_x11_forward
) &&
5156 (ssh
->x11disp
= x11_setup_display(conf_get_str(ssh
->conf
, CONF_x11_display
),
5157 conf_get_int(ssh
->conf
, CONF_x11_auth
), ssh
->conf
))) {
5158 logevent("Requesting X11 forwarding");
5160 * Note that while we blank the X authentication data here, we don't
5161 * take any special action to blank the start of an X11 channel,
5162 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5163 * without having session blanking enabled is likely to leak your
5164 * cookie into the log.
5166 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
5167 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
5168 PKT_STR
, ssh
->x11disp
->remoteauthprotoname
,
5170 PKT_STR
, ssh
->x11disp
->remoteauthdatastring
,
5172 PKT_INT
, ssh
->x11disp
->screennum
,
5175 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
5176 PKT_STR
, ssh
->x11disp
->remoteauthprotoname
,
5178 PKT_STR
, ssh
->x11disp
->remoteauthdatastring
,
5185 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5186 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5187 bombout(("Protocol confusion"));
5189 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5190 logevent("X11 forwarding refused");
5192 logevent("X11 forwarding enabled");
5193 ssh
->X11_fwd_enabled
= TRUE
;
5194 ssh
->packet_dispatch
[SSH1_SMSG_X11_OPEN
] = ssh1_smsg_x11_open
;
5198 ssh_setup_portfwd(ssh
, ssh
->conf
);
5199 ssh
->packet_dispatch
[SSH1_MSG_PORT_OPEN
] = ssh1_msg_port_open
;
5201 if (!conf_get_int(ssh
->conf
, CONF_nopty
)) {
5203 /* Unpick the terminal-speed string. */
5204 /* XXX perhaps we should allow no speeds to be sent. */
5205 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
5206 sscanf(conf_get_str(ssh
->conf
, CONF_termspeed
), "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
5207 /* Send the pty request. */
5208 pkt
= ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY
);
5209 ssh_pkt_addstring(pkt
, conf_get_str(ssh
->conf
, CONF_termtype
));
5210 ssh_pkt_adduint32(pkt
, ssh
->term_height
);
5211 ssh_pkt_adduint32(pkt
, ssh
->term_width
);
5212 ssh_pkt_adduint32(pkt
, 0); /* width in pixels */
5213 ssh_pkt_adduint32(pkt
, 0); /* height in pixels */
5214 parse_ttymodes(ssh
, ssh1_send_ttymode
, (void *)pkt
);
5215 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_ISPEED
);
5216 ssh_pkt_adduint32(pkt
, ssh
->ispeed
);
5217 ssh_pkt_addbyte(pkt
, SSH1_TTY_OP_OSPEED
);
5218 ssh_pkt_adduint32(pkt
, ssh
->ospeed
);
5219 ssh_pkt_addbyte(pkt
, SSH_TTY_OP_END
);
5221 ssh
->state
= SSH_STATE_INTERMED
;
5225 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5226 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5227 bombout(("Protocol confusion"));
5229 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5230 c_write_str(ssh
, "Server refused to allocate pty\r\n");
5231 ssh
->editing
= ssh
->echoing
= 1;
5233 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5234 ssh
->ospeed
, ssh
->ispeed
);
5235 ssh
->got_pty
= TRUE
;
5238 ssh
->editing
= ssh
->echoing
= 1;
5241 if (conf_get_int(ssh
->conf
, CONF_compression
)) {
5242 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
5246 if (pktin
->type
!= SSH1_SMSG_SUCCESS
5247 && pktin
->type
!= SSH1_SMSG_FAILURE
) {
5248 bombout(("Protocol confusion"));
5250 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5251 c_write_str(ssh
, "Server refused to compress\r\n");
5253 logevent("Started compression");
5254 ssh
->v1_compressing
= TRUE
;
5255 ssh
->cs_comp_ctx
= zlib_compress_init();
5256 logevent("Initialised zlib (RFC1950) compression");
5257 ssh
->sc_comp_ctx
= zlib_decompress_init();
5258 logevent("Initialised zlib (RFC1950) decompression");
5262 * Start the shell or command.
5264 * Special case: if the first-choice command is an SSH-2
5265 * subsystem (hence not usable here) and the second choice
5266 * exists, we fall straight back to that.
5269 char *cmd
= conf_get_str(ssh
->conf
, CONF_remote_cmd
);
5271 if (conf_get_int(ssh
->conf
, CONF_ssh_subsys
) &&
5272 conf_get_str(ssh
->conf
, CONF_remote_cmd2
)) {
5273 cmd
= conf_get_str(ssh
->conf
, CONF_remote_cmd2
);
5274 ssh
->fallback_cmd
= TRUE
;
5277 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
5279 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
5280 logevent("Started session");
5283 ssh
->state
= SSH_STATE_SESSION
;
5284 if (ssh
->size_needed
)
5285 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
5286 if (ssh
->eof_needed
)
5287 ssh_special(ssh
, TS_EOF
);
5290 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
5292 ssh
->channels
= newtree234(ssh_channelcmp
);
5296 * By this point, most incoming packets are already being
5297 * handled by the dispatch table, and we need only pay
5298 * attention to the unusual ones.
5303 if (pktin
->type
== SSH1_SMSG_SUCCESS
) {
5304 /* may be from EXEC_SHELL on some servers */
5305 } else if (pktin
->type
== SSH1_SMSG_FAILURE
) {
5306 /* may be from EXEC_SHELL on some servers
5307 * if no pty is available or in other odd cases. Ignore */
5309 bombout(("Strange packet received: type %d", pktin
->type
));
5314 int len
= min(inlen
, 512);
5315 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
,
5316 PKT_INT
, len
, PKTT_DATA
, PKT_DATA
, in
, len
,
5317 PKTT_OTHER
, PKT_END
);
5328 * Handle the top-level SSH-2 protocol.
5330 static void ssh1_msg_debug(Ssh ssh
, struct Packet
*pktin
)
5335 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5336 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
5339 static void ssh1_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
5341 /* log reason code in disconnect message */
5345 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
5346 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen
, msg
));
5349 static void ssh_msg_ignore(Ssh ssh
, struct Packet
*pktin
)
5351 /* Do nothing, because we're ignoring it! Duhh. */
5354 static void ssh1_protocol_setup(Ssh ssh
)
5359 * Most messages are handled by the coroutines.
5361 for (i
= 0; i
< 256; i
++)
5362 ssh
->packet_dispatch
[i
] = NULL
;
5365 * These special message types we install handlers for.
5367 ssh
->packet_dispatch
[SSH1_MSG_DISCONNECT
] = ssh1_msg_disconnect
;
5368 ssh
->packet_dispatch
[SSH1_MSG_IGNORE
] = ssh_msg_ignore
;
5369 ssh
->packet_dispatch
[SSH1_MSG_DEBUG
] = ssh1_msg_debug
;
5372 static void ssh1_protocol(Ssh ssh
, void *vin
, int inlen
,
5373 struct Packet
*pktin
)
5375 unsigned char *in
=(unsigned char*)vin
;
5376 if (ssh
->state
== SSH_STATE_CLOSED
)
5379 if (pktin
&& ssh
->packet_dispatch
[pktin
->type
]) {
5380 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
5384 if (!ssh
->protocol_initial_phase_done
) {
5385 if (do_ssh1_login(ssh
, in
, inlen
, pktin
))
5386 ssh
->protocol_initial_phase_done
= TRUE
;
5391 do_ssh1_connection(ssh
, in
, inlen
, pktin
);
5395 * Utility routine for decoding comma-separated strings in KEXINIT.
5397 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
5400 if (!needle
|| !haystack
) /* protect against null pointers */
5402 needlen
= strlen(needle
);
5405 * Is it at the start of the string?
5407 if (haylen
>= needlen
&& /* haystack is long enough */
5408 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5409 (haylen
== needlen
|| haystack
[needlen
] == ',')
5410 /* either , or EOS follows */
5414 * If not, search for the next comma and resume after that.
5415 * If no comma found, terminate.
5417 while (haylen
> 0 && *haystack
!= ',')
5418 haylen
--, haystack
++;
5421 haylen
--, haystack
++; /* skip over comma itself */
5426 * Similar routine for checking whether we have the first string in a list.
5428 static int first_in_commasep_string(char *needle
, char *haystack
, int haylen
)
5431 if (!needle
|| !haystack
) /* protect against null pointers */
5433 needlen
= strlen(needle
);
5435 * Is it at the start of the string?
5437 if (haylen
>= needlen
&& /* haystack is long enough */
5438 !memcmp(needle
, haystack
, needlen
) && /* initial match */
5439 (haylen
== needlen
|| haystack
[needlen
] == ',')
5440 /* either , or EOS follows */
5448 * SSH-2 key creation method.
5449 * (Currently assumes 2 lots of any hash are sufficient to generate
5450 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5452 #define SSH2_MKKEY_ITERS (2)
5453 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
, char chr
,
5454 unsigned char *keyspace
)
5456 const struct ssh_hash
*h
= ssh
->kex
->hash
;
5458 /* First hlen bytes. */
5460 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5461 hash_mpint(h
, s
, K
);
5462 h
->bytes(s
, H
, h
->hlen
);
5463 h
->bytes(s
, &chr
, 1);
5464 h
->bytes(s
, ssh
->v2_session_id
, ssh
->v2_session_id_len
);
5465 h
->final(s
, keyspace
);
5466 /* Next hlen bytes. */
5468 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
5469 hash_mpint(h
, s
, K
);
5470 h
->bytes(s
, H
, h
->hlen
);
5471 h
->bytes(s
, keyspace
, h
->hlen
);
5472 h
->final(s
, keyspace
+ h
->hlen
);
5476 * Handle the SSH-2 transport layer.
5478 static int do_ssh2_transport(Ssh ssh
, void *vin
, int inlen
,
5479 struct Packet
*pktin
)
5481 unsigned char *in
= (unsigned char *)vin
;
5482 struct do_ssh2_transport_state
{
5484 int nbits
, pbits
, warn_kex
, warn_cscipher
, warn_sccipher
;
5485 Bignum p
, g
, e
, f
, K
;
5488 int kex_init_value
, kex_reply_value
;
5489 const struct ssh_mac
**maclist
;
5491 const struct ssh2_cipher
*cscipher_tobe
;
5492 const struct ssh2_cipher
*sccipher_tobe
;
5493 const struct ssh_mac
*csmac_tobe
;
5494 const struct ssh_mac
*scmac_tobe
;
5495 const struct ssh_compress
*cscomp_tobe
;
5496 const struct ssh_compress
*sccomp_tobe
;
5497 char *hostkeydata
, *sigdata
, *rsakeydata
, *keystr
, *fingerprint
;
5498 int hostkeylen
, siglen
, rsakeylen
;
5499 void *hkey
; /* actual host key */
5500 void *rsakey
; /* for RSA kex */
5501 unsigned char exchange_hash
[SSH2_KEX_MAX_HASH_LEN
];
5502 int n_preferred_kex
;
5503 const struct ssh_kexes
*preferred_kex
[KEX_MAX
];
5504 int n_preferred_ciphers
;
5505 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
5506 const struct ssh_compress
*preferred_comp
;
5507 int userauth_succeeded
; /* for delayed compression */
5508 int pending_compression
;
5509 int got_session_id
, activated_authconn
;
5510 struct Packet
*pktout
;
5515 crState(do_ssh2_transport_state
);
5519 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
5520 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
5521 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
5523 s
->got_session_id
= s
->activated_authconn
= FALSE
;
5524 s
->userauth_succeeded
= FALSE
;
5525 s
->pending_compression
= FALSE
;
5528 * Be prepared to work around the buggy MAC problem.
5530 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
5531 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
5533 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
5536 ssh
->pkt_kctx
= SSH2_PKTCTX_NOKEX
;
5538 int i
, j
, k
, commalist_started
;
5541 * Set up the preferred key exchange. (NULL => warn below here)
5543 s
->n_preferred_kex
= 0;
5544 for (i
= 0; i
< KEX_MAX
; i
++) {
5545 switch (conf_get_int_int(ssh
->conf
, CONF_ssh_kexlist
, i
)) {
5547 s
->preferred_kex
[s
->n_preferred_kex
++] =
5548 &ssh_diffiehellman_gex
;
5551 s
->preferred_kex
[s
->n_preferred_kex
++] =
5552 &ssh_diffiehellman_group14
;
5555 s
->preferred_kex
[s
->n_preferred_kex
++] =
5556 &ssh_diffiehellman_group1
;
5559 s
->preferred_kex
[s
->n_preferred_kex
++] =
5563 /* Flag for later. Don't bother if it's the last in
5565 if (i
< KEX_MAX
- 1) {
5566 s
->preferred_kex
[s
->n_preferred_kex
++] = NULL
;
5573 * Set up the preferred ciphers. (NULL => warn below here)
5575 s
->n_preferred_ciphers
= 0;
5576 for (i
= 0; i
< CIPHER_MAX
; i
++) {
5577 switch (conf_get_int_int(ssh
->conf
, CONF_ssh_cipherlist
, i
)) {
5578 case CIPHER_BLOWFISH
:
5579 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
5582 if (conf_get_int(ssh
->conf
, CONF_ssh2_des_cbc
)) {
5583 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
5587 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
5590 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
5592 case CIPHER_ARCFOUR
:
5593 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_arcfour
;
5596 /* Flag for later. Don't bother if it's the last in
5598 if (i
< CIPHER_MAX
- 1) {
5599 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
5606 * Set up preferred compression.
5608 if (conf_get_int(ssh
->conf
, CONF_compression
))
5609 s
->preferred_comp
= &ssh_zlib
;
5611 s
->preferred_comp
= &ssh_comp_none
;
5614 * Enable queueing of outgoing auth- or connection-layer
5615 * packets while we are in the middle of a key exchange.
5617 ssh
->queueing
= TRUE
;
5620 * Flag that KEX is in progress.
5622 ssh
->kex_in_progress
= TRUE
;
5625 * Construct and send our key exchange packet.
5627 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXINIT
);
5628 for (i
= 0; i
< 16; i
++)
5629 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) random_byte());
5630 /* List key exchange algorithms. */
5631 ssh2_pkt_addstring_start(s
->pktout
);
5632 commalist_started
= 0;
5633 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5634 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5635 if (!k
) continue; /* warning flag */
5636 for (j
= 0; j
< k
->nkexes
; j
++) {
5637 if (commalist_started
)
5638 ssh2_pkt_addstring_str(s
->pktout
, ",");
5639 ssh2_pkt_addstring_str(s
->pktout
, k
->list
[j
]->name
);
5640 commalist_started
= 1;
5643 /* List server host key algorithms. */
5644 ssh2_pkt_addstring_start(s
->pktout
);
5645 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5646 ssh2_pkt_addstring_str(s
->pktout
, hostkey_algs
[i
]->name
);
5647 if (i
< lenof(hostkey_algs
) - 1)
5648 ssh2_pkt_addstring_str(s
->pktout
, ",");
5650 /* List encryption algorithms (client->server then server->client). */
5651 for (k
= 0; k
< 2; k
++) {
5652 ssh2_pkt_addstring_start(s
->pktout
);
5653 commalist_started
= 0;
5654 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5655 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5656 if (!c
) continue; /* warning flag */
5657 for (j
= 0; j
< c
->nciphers
; j
++) {
5658 if (commalist_started
)
5659 ssh2_pkt_addstring_str(s
->pktout
, ",");
5660 ssh2_pkt_addstring_str(s
->pktout
, c
->list
[j
]->name
);
5661 commalist_started
= 1;
5665 /* List MAC algorithms (client->server then server->client). */
5666 for (j
= 0; j
< 2; j
++) {
5667 ssh2_pkt_addstring_start(s
->pktout
);
5668 for (i
= 0; i
< s
->nmacs
; i
++) {
5669 ssh2_pkt_addstring_str(s
->pktout
, s
->maclist
[i
]->name
);
5670 if (i
< s
->nmacs
- 1)
5671 ssh2_pkt_addstring_str(s
->pktout
, ",");
5674 /* List client->server compression algorithms,
5675 * then server->client compression algorithms. (We use the
5676 * same set twice.) */
5677 for (j
= 0; j
< 2; j
++) {
5678 ssh2_pkt_addstring_start(s
->pktout
);
5679 assert(lenof(compressions
) > 1);
5680 /* Prefer non-delayed versions */
5681 ssh2_pkt_addstring_str(s
->pktout
, s
->preferred_comp
->name
);
5682 /* We don't even list delayed versions of algorithms until
5683 * they're allowed to be used, to avoid a race. See the end of
5685 if (s
->userauth_succeeded
&& s
->preferred_comp
->delayed_name
) {
5686 ssh2_pkt_addstring_str(s
->pktout
, ",");
5687 ssh2_pkt_addstring_str(s
->pktout
,
5688 s
->preferred_comp
->delayed_name
);
5690 for (i
= 0; i
< lenof(compressions
); i
++) {
5691 const struct ssh_compress
*c
= compressions
[i
];
5692 if (c
!= s
->preferred_comp
) {
5693 ssh2_pkt_addstring_str(s
->pktout
, ",");
5694 ssh2_pkt_addstring_str(s
->pktout
, c
->name
);
5695 if (s
->userauth_succeeded
&& c
->delayed_name
) {
5696 ssh2_pkt_addstring_str(s
->pktout
, ",");
5697 ssh2_pkt_addstring_str(s
->pktout
, c
->delayed_name
);
5702 /* List client->server languages. Empty list. */
5703 ssh2_pkt_addstring_start(s
->pktout
);
5704 /* List server->client languages. Empty list. */
5705 ssh2_pkt_addstring_start(s
->pktout
);
5706 /* First KEX packet does _not_ follow, because we're not that brave. */
5707 ssh2_pkt_addbool(s
->pktout
, FALSE
);
5709 ssh2_pkt_adduint32(s
->pktout
, 0);
5712 s
->our_kexinitlen
= s
->pktout
->length
- 5;
5713 s
->our_kexinit
= snewn(s
->our_kexinitlen
, unsigned char);
5714 memcpy(s
->our_kexinit
, s
->pktout
->data
+ 5, s
->our_kexinitlen
);
5716 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
5722 * Now examine the other side's KEXINIT to see what we're up
5726 char *str
, *preferred
;
5729 if (pktin
->type
!= SSH2_MSG_KEXINIT
) {
5730 bombout(("expected key exchange packet from server"));
5734 ssh
->hostkey
= NULL
;
5735 s
->cscipher_tobe
= NULL
;
5736 s
->sccipher_tobe
= NULL
;
5737 s
->csmac_tobe
= NULL
;
5738 s
->scmac_tobe
= NULL
;
5739 s
->cscomp_tobe
= NULL
;
5740 s
->sccomp_tobe
= NULL
;
5741 s
->warn_kex
= s
->warn_cscipher
= s
->warn_sccipher
= FALSE
;
5743 pktin
->savedpos
+= 16; /* skip garbage cookie */
5744 ssh_pkt_getstring(pktin
, &str
, &len
); /* key exchange algorithms */
5747 for (i
= 0; i
< s
->n_preferred_kex
; i
++) {
5748 const struct ssh_kexes
*k
= s
->preferred_kex
[i
];
5752 for (j
= 0; j
< k
->nkexes
; j
++) {
5753 if (!preferred
) preferred
= k
->list
[j
]->name
;
5754 if (in_commasep_string(k
->list
[j
]->name
, str
, len
)) {
5755 ssh
->kex
= k
->list
[j
];
5764 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5765 str ? str
: "(null)"));
5769 * Note that the server's guess is considered wrong if it doesn't match
5770 * the first algorithm in our list, even if it's still the algorithm
5773 s
->guessok
= first_in_commasep_string(preferred
, str
, len
);
5774 ssh_pkt_getstring(pktin
, &str
, &len
); /* host key algorithms */
5775 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
5776 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
5777 ssh
->hostkey
= hostkey_algs
[i
];
5781 if (!ssh
->hostkey
) {
5782 bombout(("Couldn't agree a host key algorithm (available: %s)",
5783 str ? str
: "(null)"));
5787 s
->guessok
= s
->guessok
&&
5788 first_in_commasep_string(hostkey_algs
[0]->name
, str
, len
);
5789 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server cipher */
5790 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5791 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5793 s
->warn_cscipher
= TRUE
;
5795 for (j
= 0; j
< c
->nciphers
; j
++) {
5796 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5797 s
->cscipher_tobe
= c
->list
[j
];
5802 if (s
->cscipher_tobe
)
5805 if (!s
->cscipher_tobe
) {
5806 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5807 str ? str
: "(null)"));
5811 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client cipher */
5812 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
5813 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
5815 s
->warn_sccipher
= TRUE
;
5817 for (j
= 0; j
< c
->nciphers
; j
++) {
5818 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
5819 s
->sccipher_tobe
= c
->list
[j
];
5824 if (s
->sccipher_tobe
)
5827 if (!s
->sccipher_tobe
) {
5828 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5829 str ? str
: "(null)"));
5833 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server mac */
5834 for (i
= 0; i
< s
->nmacs
; i
++) {
5835 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5836 s
->csmac_tobe
= s
->maclist
[i
];
5840 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client mac */
5841 for (i
= 0; i
< s
->nmacs
; i
++) {
5842 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
5843 s
->scmac_tobe
= s
->maclist
[i
];
5847 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server compression */
5848 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5849 const struct ssh_compress
*c
=
5850 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5851 if (in_commasep_string(c
->name
, str
, len
)) {
5854 } else if (in_commasep_string(c
->delayed_name
, str
, len
)) {
5855 if (s
->userauth_succeeded
) {
5859 s
->pending_compression
= TRUE
; /* try this later */
5863 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client compression */
5864 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
5865 const struct ssh_compress
*c
=
5866 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
5867 if (in_commasep_string(c
->name
, str
, len
)) {
5870 } else if (in_commasep_string(c
->delayed_name
, str
, len
)) {
5871 if (s
->userauth_succeeded
) {
5875 s
->pending_compression
= TRUE
; /* try this later */
5879 if (s
->pending_compression
) {
5880 logevent("Server supports delayed compression; "
5881 "will try this later");
5883 ssh_pkt_getstring(pktin
, &str
, &len
); /* client->server language */
5884 ssh_pkt_getstring(pktin
, &str
, &len
); /* server->client language */
5885 s
->ignorepkt
= ssh2_pkt_getbool(pktin
) && !s
->guessok
;
5888 ssh_set_frozen(ssh
, 1);
5889 s
->dlgret
= askalg(ssh
->frontend
, "key-exchange algorithm",
5891 ssh_dialog_callback
, ssh
);
5892 if (s
->dlgret
< 0) {
5896 bombout(("Unexpected data from server while"
5897 " waiting for user response"));
5900 } while (pktin
|| inlen
> 0);
5901 s
->dlgret
= ssh
->user_response
;
5903 ssh_set_frozen(ssh
, 0);
5904 if (s
->dlgret
== 0) {
5905 ssh_disconnect(ssh
, "User aborted at kex warning", NULL
,
5911 if (s
->warn_cscipher
) {
5912 ssh_set_frozen(ssh
, 1);
5913 s
->dlgret
= askalg(ssh
->frontend
,
5914 "client-to-server cipher",
5915 s
->cscipher_tobe
->name
,
5916 ssh_dialog_callback
, ssh
);
5917 if (s
->dlgret
< 0) {
5921 bombout(("Unexpected data from server while"
5922 " waiting for user response"));
5925 } while (pktin
|| inlen
> 0);
5926 s
->dlgret
= ssh
->user_response
;
5928 ssh_set_frozen(ssh
, 0);
5929 if (s
->dlgret
== 0) {
5930 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5936 if (s
->warn_sccipher
) {
5937 ssh_set_frozen(ssh
, 1);
5938 s
->dlgret
= askalg(ssh
->frontend
,
5939 "server-to-client cipher",
5940 s
->sccipher_tobe
->name
,
5941 ssh_dialog_callback
, ssh
);
5942 if (s
->dlgret
< 0) {
5946 bombout(("Unexpected data from server while"
5947 " waiting for user response"));
5950 } while (pktin
|| inlen
> 0);
5951 s
->dlgret
= ssh
->user_response
;
5953 ssh_set_frozen(ssh
, 0);
5954 if (s
->dlgret
== 0) {
5955 ssh_disconnect(ssh
, "User aborted at cipher warning", NULL
,
5961 ssh
->exhash
= ssh
->kex
->hash
->init();
5962 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_c
, strlen(ssh
->v_c
));
5963 hash_string(ssh
->kex
->hash
, ssh
->exhash
, ssh
->v_s
, strlen(ssh
->v_s
));
5964 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5965 s
->our_kexinit
, s
->our_kexinitlen
);
5966 sfree(s
->our_kexinit
);
5967 if (pktin
->length
> 5)
5968 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
5969 pktin
->data
+ 5, pktin
->length
- 5);
5971 if (s
->ignorepkt
) /* first_kex_packet_follows */
5972 crWaitUntil(pktin
); /* Ignore packet */
5975 if (ssh
->kex
->main_type
== KEXTYPE_DH
) {
5977 * Work out the number of bits of key we will need from the
5978 * key exchange. We start with the maximum key length of
5984 csbits
= s
->cscipher_tobe
->keylen
;
5985 scbits
= s
->sccipher_tobe
->keylen
;
5986 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
5988 /* The keys only have hlen-bit entropy, since they're based on
5989 * a hash. So cap the key size at hlen bits. */
5990 if (s
->nbits
> ssh
->kex
->hash
->hlen
* 8)
5991 s
->nbits
= ssh
->kex
->hash
->hlen
* 8;
5994 * If we're doing Diffie-Hellman group exchange, start by
5995 * requesting a group.
5997 if (!ssh
->kex
->pdata
) {
5998 logevent("Doing Diffie-Hellman group exchange");
5999 ssh
->pkt_kctx
= SSH2_PKTCTX_DHGEX
;
6001 * Work out how big a DH group we will need to allow that
6004 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
6005 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
6006 ssh2_pkt_adduint32(s
->pktout
, s
->pbits
);
6007 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6010 if (pktin
->type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
6011 bombout(("expected key exchange group packet from server"));
6014 s
->p
= ssh2_pkt_getmp(pktin
);
6015 s
->g
= ssh2_pkt_getmp(pktin
);
6016 if (!s
->p
|| !s
->g
) {
6017 bombout(("unable to read mp-ints from incoming group packet"));
6020 ssh
->kex_ctx
= dh_setup_gex(s
->p
, s
->g
);
6021 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
6022 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
6024 ssh
->pkt_kctx
= SSH2_PKTCTX_DHGROUP
;
6025 ssh
->kex_ctx
= dh_setup_group(ssh
->kex
);
6026 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
6027 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
6028 logeventf(ssh
, "Using Diffie-Hellman with standard group \"%s\"",
6029 ssh
->kex
->groupname
);
6032 logeventf(ssh
, "Doing Diffie-Hellman key exchange with hash %s",
6033 ssh
->kex
->hash
->text_name
);
6035 * Now generate and send e for Diffie-Hellman.
6037 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* this can take a while */
6038 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
6039 s
->pktout
= ssh2_pkt_init(s
->kex_init_value
);
6040 ssh2_pkt_addmp(s
->pktout
, s
->e
);
6041 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6043 set_busy_status(ssh
->frontend
, BUSY_WAITING
); /* wait for server */
6045 if (pktin
->type
!= s
->kex_reply_value
) {
6046 bombout(("expected key exchange reply packet from server"));
6049 set_busy_status(ssh
->frontend
, BUSY_CPU
); /* cogitate */
6050 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
6051 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
6052 s
->f
= ssh2_pkt_getmp(pktin
);
6054 bombout(("unable to parse key exchange reply packet"));
6057 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
6059 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
6061 /* We assume everything from now on will be quick, and it might
6062 * involve user interaction. */
6063 set_busy_status(ssh
->frontend
, BUSY_NOT
);
6065 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
6066 if (!ssh
->kex
->pdata
) {
6067 hash_uint32(ssh
->kex
->hash
, ssh
->exhash
, s
->pbits
);
6068 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->p
);
6069 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->g
);
6071 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->e
);
6072 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->f
);
6074 dh_cleanup(ssh
->kex_ctx
);
6076 if (!ssh
->kex
->pdata
) {
6081 logeventf(ssh
, "Doing RSA key exchange with hash %s",
6082 ssh
->kex
->hash
->text_name
);
6083 ssh
->pkt_kctx
= SSH2_PKTCTX_RSAKEX
;
6085 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6089 if (pktin
->type
!= SSH2_MSG_KEXRSA_PUBKEY
) {
6090 bombout(("expected RSA public key packet from server"));
6094 ssh_pkt_getstring(pktin
, &s
->hostkeydata
, &s
->hostkeylen
);
6095 hash_string(ssh
->kex
->hash
, ssh
->exhash
,
6096 s
->hostkeydata
, s
->hostkeylen
);
6097 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
6101 ssh_pkt_getstring(pktin
, &keydata
, &s
->rsakeylen
);
6102 s
->rsakeydata
= snewn(s
->rsakeylen
, char);
6103 memcpy(s
->rsakeydata
, keydata
, s
->rsakeylen
);
6106 s
->rsakey
= ssh_rsakex_newkey(s
->rsakeydata
, s
->rsakeylen
);
6108 sfree(s
->rsakeydata
);
6109 bombout(("unable to parse RSA public key from server"));
6113 hash_string(ssh
->kex
->hash
, ssh
->exhash
, s
->rsakeydata
, s
->rsakeylen
);
6116 * Next, set up a shared secret K, of precisely KLEN -
6117 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6118 * RSA key modulus and HLEN is the bit length of the hash
6122 int klen
= ssh_rsakex_klen(s
->rsakey
);
6123 int nbits
= klen
- (2*ssh
->kex
->hash
->hlen
*8 + 49);
6125 unsigned char *kstr1
, *kstr2
, *outstr
;
6126 int kstr1len
, kstr2len
, outstrlen
;
6128 s
->K
= bn_power_2(nbits
- 1);
6130 for (i
= 0; i
< nbits
; i
++) {
6132 byte
= random_byte();
6134 bignum_set_bit(s
->K
, i
, (byte
>> (i
& 7)) & 1);
6138 * Encode this as an mpint.
6140 kstr1
= ssh2_mpint_fmt(s
->K
, &kstr1len
);
6141 kstr2
= snewn(kstr2len
= 4 + kstr1len
, unsigned char);
6142 PUT_32BIT(kstr2
, kstr1len
);
6143 memcpy(kstr2
+ 4, kstr1
, kstr1len
);
6146 * Encrypt it with the given RSA key.
6148 outstrlen
= (klen
+ 7) / 8;
6149 outstr
= snewn(outstrlen
, unsigned char);
6150 ssh_rsakex_encrypt(ssh
->kex
->hash
, kstr2
, kstr2len
,
6151 outstr
, outstrlen
, s
->rsakey
);
6154 * And send it off in a return packet.
6156 s
->pktout
= ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET
);
6157 ssh2_pkt_addstring_start(s
->pktout
);
6158 ssh2_pkt_addstring_data(s
->pktout
, (char *)outstr
, outstrlen
);
6159 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6161 hash_string(ssh
->kex
->hash
, ssh
->exhash
, outstr
, outstrlen
);
6168 ssh_rsakex_freekey(s
->rsakey
);
6171 if (pktin
->type
!= SSH2_MSG_KEXRSA_DONE
) {
6172 sfree(s
->rsakeydata
);
6173 bombout(("expected signature packet from server"));
6177 ssh_pkt_getstring(pktin
, &s
->sigdata
, &s
->siglen
);
6179 sfree(s
->rsakeydata
);
6182 hash_mpint(ssh
->kex
->hash
, ssh
->exhash
, s
->K
);
6183 assert(ssh
->kex
->hash
->hlen
<= sizeof(s
->exchange_hash
));
6184 ssh
->kex
->hash
->final(ssh
->exhash
, s
->exchange_hash
);
6186 ssh
->kex_ctx
= NULL
;
6189 debug(("Exchange hash is:\n"));
6190 dmemdump(s
->exchange_hash
, ssh
->kex
->hash
->hlen
);
6194 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
6195 (char *)s
->exchange_hash
,
6196 ssh
->kex
->hash
->hlen
)) {
6197 bombout(("Server's host key did not match the signature supplied"));
6202 * Authenticate remote host: verify host key. (We've already
6203 * checked the signature of the exchange hash.)
6205 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
6206 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
6207 ssh_set_frozen(ssh
, 1);
6208 s
->dlgret
= verify_ssh_host_key(ssh
->frontend
,
6209 ssh
->savedhost
, ssh
->savedport
,
6210 ssh
->hostkey
->keytype
, s
->keystr
,
6212 ssh_dialog_callback
, ssh
);
6213 if (s
->dlgret
< 0) {
6217 bombout(("Unexpected data from server while waiting"
6218 " for user host key response"));
6221 } while (pktin
|| inlen
> 0);
6222 s
->dlgret
= ssh
->user_response
;
6224 ssh_set_frozen(ssh
, 0);
6225 if (s
->dlgret
== 0) {
6226 ssh_disconnect(ssh
, "User aborted at host key verification", NULL
,
6230 if (!s
->got_session_id
) { /* don't bother logging this in rekeys */
6231 logevent("Host key fingerprint is:");
6232 logevent(s
->fingerprint
);
6234 sfree(s
->fingerprint
);
6236 ssh
->hostkey
->freekey(s
->hkey
);
6239 * The exchange hash from the very first key exchange is also
6240 * the session id, used in session key construction and
6243 if (!s
->got_session_id
) {
6244 assert(sizeof(s
->exchange_hash
) <= sizeof(ssh
->v2_session_id
));
6245 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
6246 sizeof(s
->exchange_hash
));
6247 ssh
->v2_session_id_len
= ssh
->kex
->hash
->hlen
;
6248 assert(ssh
->v2_session_id_len
<= sizeof(ssh
->v2_session_id
));
6249 s
->got_session_id
= TRUE
;
6253 * Send SSH2_MSG_NEWKEYS.
6255 s
->pktout
= ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
6256 ssh2_pkt_send_noqueue(ssh
, s
->pktout
);
6257 ssh
->outgoing_data_size
= 0; /* start counting from here */
6260 * We've sent client NEWKEYS, so create and initialise
6261 * client-to-server session keys.
6263 if (ssh
->cs_cipher_ctx
)
6264 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
6265 ssh
->cscipher
= s
->cscipher_tobe
;
6266 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
6268 if (ssh
->cs_mac_ctx
)
6269 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
6270 ssh
->csmac
= s
->csmac_tobe
;
6271 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
6273 if (ssh
->cs_comp_ctx
)
6274 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
6275 ssh
->cscomp
= s
->cscomp_tobe
;
6276 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
6279 * Set IVs on client-to-server keys. Here we use the exchange
6280 * hash from the _first_ key exchange.
6283 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
6284 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6285 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'C',keyspace
);
6286 assert((ssh
->cscipher
->keylen
+7) / 8 <=
6287 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6288 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
6289 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'A',keyspace
);
6290 assert(ssh
->cscipher
->blksize
<=
6291 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6292 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
6293 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'E',keyspace
);
6294 assert(ssh
->csmac
->len
<=
6295 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6296 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
6297 smemclr(keyspace
, sizeof(keyspace
));
6300 logeventf(ssh
, "Initialised %.200s client->server encryption",
6301 ssh
->cscipher
->text_name
);
6302 logeventf(ssh
, "Initialised %.200s client->server MAC algorithm",
6303 ssh
->csmac
->text_name
);
6304 if (ssh
->cscomp
->text_name
)
6305 logeventf(ssh
, "Initialised %s compression",
6306 ssh
->cscomp
->text_name
);
6309 * Now our end of the key exchange is complete, we can send all
6310 * our queued higher-layer packets.
6312 ssh
->queueing
= FALSE
;
6313 ssh2_pkt_queuesend(ssh
);
6316 * Expect SSH2_MSG_NEWKEYS from server.
6319 if (pktin
->type
!= SSH2_MSG_NEWKEYS
) {
6320 bombout(("expected new-keys packet from server"));
6323 ssh
->incoming_data_size
= 0; /* start counting from here */
6326 * We've seen server NEWKEYS, so create and initialise
6327 * server-to-client session keys.
6329 if (ssh
->sc_cipher_ctx
)
6330 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
6331 ssh
->sccipher
= s
->sccipher_tobe
;
6332 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
6334 if (ssh
->sc_mac_ctx
)
6335 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
6336 ssh
->scmac
= s
->scmac_tobe
;
6337 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
6339 if (ssh
->sc_comp_ctx
)
6340 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
6341 ssh
->sccomp
= s
->sccomp_tobe
;
6342 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
6345 * Set IVs on server-to-client keys. Here we use the exchange
6346 * hash from the _first_ key exchange.
6349 unsigned char keyspace
[SSH2_KEX_MAX_HASH_LEN
* SSH2_MKKEY_ITERS
];
6350 assert(sizeof(keyspace
) >= ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6351 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'D',keyspace
);
6352 assert((ssh
->sccipher
->keylen
+7) / 8 <=
6353 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6354 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
6355 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'B',keyspace
);
6356 assert(ssh
->sccipher
->blksize
<=
6357 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6358 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
6359 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,'F',keyspace
);
6360 assert(ssh
->scmac
->len
<=
6361 ssh
->kex
->hash
->hlen
* SSH2_MKKEY_ITERS
);
6362 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
6363 smemclr(keyspace
, sizeof(keyspace
));
6365 logeventf(ssh
, "Initialised %.200s server->client encryption",
6366 ssh
->sccipher
->text_name
);
6367 logeventf(ssh
, "Initialised %.200s server->client MAC algorithm",
6368 ssh
->scmac
->text_name
);
6369 if (ssh
->sccomp
->text_name
)
6370 logeventf(ssh
, "Initialised %s decompression",
6371 ssh
->sccomp
->text_name
);
6374 * Free shared secret.
6379 * Key exchange is over. Loop straight back round if we have a
6380 * deferred rekey reason.
6382 if (ssh
->deferred_rekey_reason
) {
6383 logevent(ssh
->deferred_rekey_reason
);
6385 ssh
->deferred_rekey_reason
= NULL
;
6386 goto begin_key_exchange
;
6390 * Otherwise, schedule a timer for our next rekey.
6392 ssh
->kex_in_progress
= FALSE
;
6393 ssh
->last_rekey
= GETTICKCOUNT();
6394 if (conf_get_int(ssh
->conf
, CONF_ssh_rekey_time
) != 0)
6395 ssh
->next_rekey
= schedule_timer(conf_get_int(ssh
->conf
, CONF_ssh_rekey_time
)*60*TICKSPERSEC
,
6399 * Now we're encrypting. Begin returning 1 to the protocol main
6400 * function so that other things can run on top of the
6401 * transport. If we ever see a KEXINIT, we must go back to the
6404 * We _also_ go back to the start if we see pktin==NULL and
6405 * inlen negative, because this is a special signal meaning
6406 * `initiate client-driven rekey', and `in' contains a message
6407 * giving the reason for the rekey.
6409 * inlen==-1 means always initiate a rekey;
6410 * inlen==-2 means that userauth has completed successfully and
6411 * we should consider rekeying (for delayed compression).
6413 while (!((pktin
&& pktin
->type
== SSH2_MSG_KEXINIT
) ||
6414 (!pktin
&& inlen
< 0))) {
6416 if (!ssh
->protocol_initial_phase_done
) {
6417 ssh
->protocol_initial_phase_done
= TRUE
;
6419 * Allow authconn to initialise itself.
6421 do_ssh2_authconn(ssh
, NULL
, 0, NULL
);
6426 logevent("Server initiated key re-exchange");
6430 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6431 * delayed compression, if it's available.
6433 * draft-miller-secsh-compression-delayed-00 says that you
6434 * negotiate delayed compression in the first key exchange, and
6435 * both sides start compressing when the server has sent
6436 * USERAUTH_SUCCESS. This has a race condition -- the server
6437 * can't know when the client has seen it, and thus which incoming
6438 * packets it should treat as compressed.
6440 * Instead, we do the initial key exchange without offering the
6441 * delayed methods, but note if the server offers them; when we
6442 * get here, if a delayed method was available that was higher
6443 * on our list than what we got, we initiate a rekey in which we
6444 * _do_ list the delayed methods (and hopefully get it as a
6445 * result). Subsequent rekeys will do the same.
6447 assert(!s
->userauth_succeeded
); /* should only happen once */
6448 s
->userauth_succeeded
= TRUE
;
6449 if (!s
->pending_compression
)
6450 /* Can't see any point rekeying. */
6451 goto wait_for_rekey
; /* this is utterly horrid */
6452 /* else fall through to rekey... */
6453 s
->pending_compression
= FALSE
;
6456 * Now we've decided to rekey.
6458 * Special case: if the server bug is set that doesn't
6459 * allow rekeying, we give a different log message and
6460 * continue waiting. (If such a server _initiates_ a rekey,
6461 * we process it anyway!)
6463 if ((ssh
->remote_bugs
& BUG_SSH2_REKEY
)) {
6464 logeventf(ssh
, "Server bug prevents key re-exchange (%s)",
6466 /* Reset the counters, so that at least this message doesn't
6467 * hit the event log _too_ often. */
6468 ssh
->outgoing_data_size
= 0;
6469 ssh
->incoming_data_size
= 0;
6470 if (conf_get_int(ssh
->conf
, CONF_ssh_rekey_time
) != 0) {
6472 schedule_timer(conf_get_int(ssh
->conf
, CONF_ssh_rekey_time
)*60*TICKSPERSEC
,
6475 goto wait_for_rekey
; /* this is still utterly horrid */
6477 logeventf(ssh
, "Initiating key re-exchange (%s)", (char *)in
);
6480 goto begin_key_exchange
;
6486 * Add data to an SSH-2 channel output buffer.
6488 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
6491 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
6495 * Attempt to send data on an SSH-2 channel.
6497 static int ssh2_try_send(struct ssh_channel
*c
)
6500 struct Packet
*pktout
;
6503 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
6506 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
6507 if ((unsigned)len
> c
->v
.v2
.remwindow
)
6508 len
= c
->v
.v2
.remwindow
;
6509 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
6510 len
= c
->v
.v2
.remmaxpkt
;
6511 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
6512 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6513 ssh2_pkt_addstring_start(pktout
);
6514 dont_log_data(ssh
, pktout
, PKTLOG_OMIT
);
6515 ssh2_pkt_addstring_data(pktout
, data
, len
);
6516 end_log_omission(ssh
, pktout
);
6517 ssh2_pkt_send(ssh
, pktout
);
6518 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
6519 c
->v
.v2
.remwindow
-= len
;
6523 * After having sent as much data as we can, return the amount
6526 ret
= bufchain_size(&c
->v
.v2
.outbuffer
);
6529 * And if there's no data pending but we need to send an EOF, send
6532 if (!ret
&& c
->pending_eof
)
6533 ssh_channel_try_eof(c
);
6538 static void ssh2_try_send_and_unthrottle(Ssh ssh
, struct ssh_channel
*c
)
6541 if (c
->closes
& CLOSES_SENT_EOF
)
6542 return; /* don't send on channels we've EOFed */
6543 bufsize
= ssh2_try_send(c
);
6546 case CHAN_MAINSESSION
:
6547 /* stdin need not receive an unthrottle
6548 * notification since it will be polled */
6551 x11_unthrottle(c
->u
.x11
.s
);
6554 /* agent sockets are request/response and need no
6555 * buffer management */
6558 pfd_unthrottle(c
->u
.pfd
.s
);
6565 * Set up most of a new ssh_channel for SSH-2.
6567 static void ssh2_channel_init(struct ssh_channel
*c
)
6570 c
->localid
= alloc_channel_id(ssh
);
6572 c
->pending_eof
= FALSE
;
6573 c
->throttling_conn
= FALSE
;
6574 c
->v
.v2
.locwindow
= c
->v
.v2
.locmaxwin
= c
->v
.v2
.remlocwin
=
6575 conf_get_int(ssh
->conf
, CONF_ssh_simple
) ? OUR_V2_BIGWIN
: OUR_V2_WINSIZE
;
6576 c
->v
.v2
.chanreq_head
= NULL
;
6577 c
->v
.v2
.throttle_state
= UNTHROTTLED
;
6578 bufchain_init(&c
->v
.v2
.outbuffer
);
6582 * CHANNEL_FAILURE doesn't come with any indication of what message
6583 * caused it, so we have to keep track of the outstanding
6584 * CHANNEL_REQUESTs ourselves.
6586 static void ssh2_queue_chanreq_handler(struct ssh_channel
*c
,
6587 cchandler_fn_t handler
, void *ctx
)
6589 struct outstanding_channel_request
*ocr
=
6590 snew(struct outstanding_channel_request
);
6592 assert(!(c
->closes
& (CLOSES_SENT_CLOSE
| CLOSES_RCVD_CLOSE
)));
6593 ocr
->handler
= handler
;
6596 if (!c
->v
.v2
.chanreq_head
)
6597 c
->v
.v2
.chanreq_head
= ocr
;
6599 c
->v
.v2
.chanreq_tail
->next
= ocr
;
6600 c
->v
.v2
.chanreq_tail
= ocr
;
6604 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6605 * NULL then a reply will be requested and the handler will be called
6606 * when it arrives. The returned packet is ready to have any
6607 * request-specific data added and be sent. Note that if a handler is
6608 * provided, it's essential that the request actually be sent.
6610 * The handler will usually be passed the response packet in pktin.
6611 * If pktin is NULL, this means that no reply will ever be forthcoming
6612 * (e.g. because the entire connection is being destroyed) and the
6613 * handler should free any storage it's holding.
6615 static struct Packet
*ssh2_chanreq_init(struct ssh_channel
*c
, char *type
,
6616 cchandler_fn_t handler
, void *ctx
)
6618 struct Packet
*pktout
;
6620 assert(!(c
->closes
& (CLOSES_SENT_CLOSE
| CLOSES_RCVD_CLOSE
)));
6621 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
6622 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6623 ssh2_pkt_addstring(pktout
, type
);
6624 ssh2_pkt_addbool(pktout
, handler
!= NULL
);
6625 if (handler
!= NULL
)
6626 ssh2_queue_chanreq_handler(c
, handler
, ctx
);
6631 * Potentially enlarge the window on an SSH-2 channel.
6633 static void ssh2_handle_winadj_response(struct ssh_channel
*, struct Packet
*,
6635 static void ssh2_set_window(struct ssh_channel
*c
, int newwin
)
6640 * Never send WINDOW_ADJUST for a channel that the remote side has
6641 * already sent EOF on; there's no point, since it won't be
6642 * sending any more data anyway. Ditto if _we've_ already sent
6645 if (c
->closes
& (CLOSES_RCVD_EOF
| CLOSES_SENT_CLOSE
))
6649 * If the remote end has a habit of ignoring maxpkt, limit the
6650 * window so that it has no choice (assuming it doesn't ignore the
6653 if ((ssh
->remote_bugs
& BUG_SSH2_MAXPKT
) && newwin
> OUR_V2_MAXPKT
)
6654 newwin
= OUR_V2_MAXPKT
;
6657 * Only send a WINDOW_ADJUST if there's significantly more window
6658 * available than the other end thinks there is. This saves us
6659 * sending a WINDOW_ADJUST for every character in a shell session.
6661 * "Significant" is arbitrarily defined as half the window size.
6663 if (newwin
/ 2 >= c
->v
.v2
.locwindow
) {
6664 struct Packet
*pktout
;
6668 * In order to keep track of how much window the client
6669 * actually has available, we'd like it to acknowledge each
6670 * WINDOW_ADJUST. We can't do that directly, so we accompany
6671 * it with a CHANNEL_REQUEST that has to be acknowledged.
6673 * This is only necessary if we're opening the window wide.
6674 * If we're not, then throughput is being constrained by
6675 * something other than the maximum window size anyway.
6677 if (newwin
== c
->v
.v2
.locmaxwin
&&
6678 !(ssh
->remote_bugs
& BUG_CHOKES_ON_WINADJ
)) {
6679 up
= snew(unsigned);
6680 *up
= newwin
- c
->v
.v2
.locwindow
;
6681 pktout
= ssh2_chanreq_init(c
, "winadj@putty.projects.tartarus.org",
6682 ssh2_handle_winadj_response
, up
);
6683 ssh2_pkt_send(ssh
, pktout
);
6685 if (c
->v
.v2
.throttle_state
!= UNTHROTTLED
)
6686 c
->v
.v2
.throttle_state
= UNTHROTTLING
;
6688 /* Pretend the WINDOW_ADJUST was acked immediately. */
6689 c
->v
.v2
.remlocwin
= newwin
;
6690 c
->v
.v2
.throttle_state
= THROTTLED
;
6692 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
6693 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6694 ssh2_pkt_adduint32(pktout
, newwin
- c
->v
.v2
.locwindow
);
6695 ssh2_pkt_send(ssh
, pktout
);
6696 c
->v
.v2
.locwindow
= newwin
;
6701 * Find the channel associated with a message. If there's no channel,
6702 * or it's not properly open, make a noise about it and return NULL.
6704 static struct ssh_channel
*ssh2_channel_msg(Ssh ssh
, struct Packet
*pktin
)
6706 unsigned localid
= ssh_pkt_getuint32(pktin
);
6707 struct ssh_channel
*c
;
6709 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
6711 (c
->halfopen
&& pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
&&
6712 pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_FAILURE
)) {
6713 char *buf
= dupprintf("Received %s for %s channel %u",
6714 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
,
6716 c ?
"half-open" : "nonexistent", localid
);
6717 ssh_disconnect(ssh
, NULL
, buf
, SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
6724 static void ssh2_handle_winadj_response(struct ssh_channel
*c
,
6725 struct Packet
*pktin
, void *ctx
)
6727 unsigned *sizep
= ctx
;
6730 * Winadj responses should always be failures. However, at least
6731 * one server ("boks_sshd") is known to return SUCCESS for channel
6732 * requests it's never heard of, such as "winadj@putty". Raised
6733 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6734 * life, we don't worry about what kind of response we got.
6737 c
->v
.v2
.remlocwin
+= *sizep
;
6740 * winadj messages are only sent when the window is fully open, so
6741 * if we get an ack of one, we know any pending unthrottle is
6744 if (c
->v
.v2
.throttle_state
== UNTHROTTLING
)
6745 c
->v
.v2
.throttle_state
= UNTHROTTLED
;
6748 static void ssh2_msg_channel_response(Ssh ssh
, struct Packet
*pktin
)
6750 struct ssh_channel
*c
= ssh2_channel_msg(ssh
, pktin
);
6751 struct outstanding_channel_request
*ocr
;
6754 ocr
= c
->v
.v2
.chanreq_head
;
6756 ssh2_msg_unexpected(ssh
, pktin
);
6759 ocr
->handler(c
, pktin
, ocr
->ctx
);
6760 c
->v
.v2
.chanreq_head
= ocr
->next
;
6763 * We may now initiate channel-closing procedures, if that
6764 * CHANNEL_REQUEST was the last thing outstanding before we send
6767 ssh2_channel_check_close(c
);
6770 static void ssh2_msg_channel_window_adjust(Ssh ssh
, struct Packet
*pktin
)
6772 struct ssh_channel
*c
;
6773 c
= ssh2_channel_msg(ssh
, pktin
);
6776 if (!(c
->closes
& CLOSES_SENT_EOF
)) {
6777 c
->v
.v2
.remwindow
+= ssh_pkt_getuint32(pktin
);
6778 ssh2_try_send_and_unthrottle(ssh
, c
);
6782 static void ssh2_msg_channel_data(Ssh ssh
, struct Packet
*pktin
)
6786 struct ssh_channel
*c
;
6787 c
= ssh2_channel_msg(ssh
, pktin
);
6790 if (pktin
->type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
6791 ssh_pkt_getuint32(pktin
) != SSH2_EXTENDED_DATA_STDERR
)
6792 return; /* extended but not stderr */
6793 ssh_pkt_getstring(pktin
, &data
, &length
);
6796 c
->v
.v2
.locwindow
-= length
;
6797 c
->v
.v2
.remlocwin
-= length
;
6799 case CHAN_MAINSESSION
:
6801 from_backend(ssh
->frontend
, pktin
->type
==
6802 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
6806 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
6809 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
6812 while (length
> 0) {
6813 if (c
->u
.a
.lensofar
< 4) {
6814 unsigned int l
= min(4 - c
->u
.a
.lensofar
,
6816 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
6820 c
->u
.a
.lensofar
+= l
;
6822 if (c
->u
.a
.lensofar
== 4) {
6824 4 + GET_32BIT(c
->u
.a
.msglen
);
6825 c
->u
.a
.message
= snewn(c
->u
.a
.totallen
,
6827 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
6829 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
6831 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
6833 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
6837 c
->u
.a
.lensofar
+= l
;
6839 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
6842 if (agent_query(c
->u
.a
.message
,
6845 ssh_agentf_callback
, c
))
6846 ssh_agentf_callback(c
, reply
, replylen
);
6847 sfree(c
->u
.a
.message
);
6848 c
->u
.a
.message
= NULL
;
6849 c
->u
.a
.lensofar
= 0;
6856 * If it looks like the remote end hit the end of its window,
6857 * and we didn't want it to do that, think about using a
6860 if (c
->v
.v2
.remlocwin
<= 0 && c
->v
.v2
.throttle_state
== UNTHROTTLED
&&
6861 c
->v
.v2
.locmaxwin
< 0x40000000)
6862 c
->v
.v2
.locmaxwin
+= OUR_V2_WINSIZE
;
6864 * If we are not buffering too much data,
6865 * enlarge the window again at the remote side.
6866 * If we are buffering too much, we may still
6867 * need to adjust the window if the server's
6870 ssh2_set_window(c
, bufsize
< c
->v
.v2
.locmaxwin ?
6871 c
->v
.v2
.locmaxwin
- bufsize
: 0);
6873 * If we're either buffering way too much data, or if we're
6874 * buffering anything at all and we're in "simple" mode,
6875 * throttle the whole channel.
6877 if ((bufsize
> c
->v
.v2
.locmaxwin
||
6878 (conf_get_int(ssh
->conf
, CONF_ssh_simple
) && bufsize
> 0)) &&
6879 !c
->throttling_conn
) {
6880 c
->throttling_conn
= 1;
6881 ssh_throttle_conn(ssh
, +1);
6886 static void ssh_channel_destroy(struct ssh_channel
*c
)
6891 case CHAN_MAINSESSION
:
6892 ssh
->mainchan
= NULL
;
6893 update_specials_menu(ssh
->frontend
);
6896 if (c
->u
.x11
.s
!= NULL
)
6897 x11_close(c
->u
.x11
.s
);
6898 logevent("Forwarded X11 connection terminated");
6901 sfree(c
->u
.a
.message
);
6904 if (c
->u
.pfd
.s
!= NULL
)
6905 pfd_close(c
->u
.pfd
.s
);
6906 logevent("Forwarded port closed");
6910 del234(ssh
->channels
, c
);
6911 if (ssh
->version
== 2) {
6912 bufchain_clear(&c
->v
.v2
.outbuffer
);
6913 assert(c
->v
.v2
.chanreq_head
== NULL
);
6918 * See if that was the last channel left open.
6919 * (This is only our termination condition if we're
6920 * not running in -N mode.)
6922 if (ssh
->version
== 2 &&
6923 !conf_get_int(ssh
->conf
, CONF_ssh_no_shell
) &&
6924 count234(ssh
->channels
) == 0) {
6926 * We used to send SSH_MSG_DISCONNECT here,
6927 * because I'd believed that _every_ conforming
6928 * SSH-2 connection had to end with a disconnect
6929 * being sent by at least one side; apparently
6930 * I was wrong and it's perfectly OK to
6931 * unceremoniously slam the connection shut
6932 * when you're done, and indeed OpenSSH feels
6933 * this is more polite than sending a
6934 * DISCONNECT. So now we don't.
6936 ssh_disconnect(ssh
, "All channels closed", NULL
, 0, TRUE
);
6940 static void ssh2_channel_check_close(struct ssh_channel
*c
)
6943 struct Packet
*pktout
;
6945 if ((!((CLOSES_SENT_EOF
| CLOSES_RCVD_EOF
) & ~c
->closes
) ||
6946 c
->type
== CHAN_ZOMBIE
) &&
6947 !c
->v
.v2
.chanreq_head
&&
6948 !(c
->closes
& CLOSES_SENT_CLOSE
)) {
6950 * We have both sent and received EOF (or the channel is a
6951 * zombie), and we have no outstanding channel requests, which
6952 * means the channel is in final wind-up. But we haven't sent
6953 * CLOSE, so let's do so now.
6955 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
6956 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
6957 ssh2_pkt_send(ssh
, pktout
);
6958 c
->closes
|= CLOSES_SENT_EOF
| CLOSES_SENT_CLOSE
;
6961 if (!((CLOSES_SENT_CLOSE
| CLOSES_RCVD_CLOSE
) & ~c
->closes
)) {
6962 assert(c
->v
.v2
.chanreq_head
== NULL
);
6964 * We have both sent and received CLOSE, which means we're
6965 * completely done with the channel.
6967 ssh_channel_destroy(c
);
6971 static void ssh2_channel_got_eof(struct ssh_channel
*c
)
6973 if (c
->closes
& CLOSES_RCVD_EOF
)
6974 return; /* already seen EOF */
6975 c
->closes
|= CLOSES_RCVD_EOF
;
6977 if (c
->type
== CHAN_X11
) {
6978 x11_send_eof(c
->u
.x11
.s
);
6979 } else if (c
->type
== CHAN_AGENT
) {
6980 /* Manufacture an outgoing EOF in response to the incoming one. */
6981 sshfwd_write_eof(c
);
6982 } else if (c
->type
== CHAN_SOCKDATA
) {
6983 pfd_send_eof(c
->u
.pfd
.s
);
6984 } else if (c
->type
== CHAN_MAINSESSION
) {
6987 if (!ssh
->sent_console_eof
&&
6988 (from_backend_eof(ssh
->frontend
) || ssh
->got_pty
)) {
6990 * Either from_backend_eof told us that the front end
6991 * wants us to close the outgoing side of the connection
6992 * as soon as we see EOF from the far end, or else we've
6993 * unilaterally decided to do that because we've allocated
6994 * a remote pty and hence EOF isn't a particularly
6995 * meaningful concept.
6997 sshfwd_write_eof(c
);
6999 ssh
->sent_console_eof
= TRUE
;
7002 ssh2_channel_check_close(c
);
7005 static void ssh2_msg_channel_eof(Ssh ssh
, struct Packet
*pktin
)
7007 struct ssh_channel
*c
;
7009 c
= ssh2_channel_msg(ssh
, pktin
);
7012 ssh2_channel_got_eof(c
);
7015 static void ssh2_msg_channel_close(Ssh ssh
, struct Packet
*pktin
)
7017 struct ssh_channel
*c
;
7019 c
= ssh2_channel_msg(ssh
, pktin
);
7024 * When we receive CLOSE on a channel, we assume it comes with an
7025 * implied EOF if we haven't seen EOF yet.
7027 ssh2_channel_got_eof(c
);
7030 * And we also send an outgoing EOF, if we haven't already, on the
7031 * assumption that CLOSE is a pretty forceful announcement that
7032 * the remote side is doing away with the entire channel. (If it
7033 * had wanted to send us EOF and continue receiving data from us,
7034 * it would have just sent CHANNEL_EOF.)
7036 if (!(c
->closes
& CLOSES_SENT_EOF
)) {
7038 * Make sure we don't read any more from whatever our local
7039 * data source is for this channel.
7042 case CHAN_MAINSESSION
:
7043 ssh
->send_ok
= 0; /* stop trying to read from stdin */
7046 x11_override_throttle(c
->u
.x11
.s
, 1);
7049 pfd_override_throttle(c
->u
.pfd
.s
, 1);
7054 * Send outgoing EOF.
7056 sshfwd_write_eof(c
);
7060 * Now process the actual close.
7062 if (!(c
->closes
& CLOSES_RCVD_CLOSE
)) {
7063 c
->closes
|= CLOSES_RCVD_CLOSE
;
7064 ssh2_channel_check_close(c
);
7068 static void ssh2_msg_channel_open_confirmation(Ssh ssh
, struct Packet
*pktin
)
7070 struct ssh_channel
*c
;
7072 c
= ssh2_channel_msg(ssh
, pktin
);
7075 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
7076 return; /* dunno why they're confirming this */
7077 c
->remoteid
= ssh_pkt_getuint32(pktin
);
7078 c
->halfopen
= FALSE
;
7079 c
->type
= CHAN_SOCKDATA
;
7080 c
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
7081 c
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
7083 pfd_confirm(c
->u
.pfd
.s
);
7085 ssh_channel_try_eof(c
);
7088 static void ssh2_msg_channel_open_failure(Ssh ssh
, struct Packet
*pktin
)
7090 static const char *const reasons
[] = {
7091 "<unknown reason code>",
7092 "Administratively prohibited",
7094 "Unknown channel type",
7095 "Resource shortage",
7097 unsigned reason_code
;
7098 char *reason_string
;
7100 struct ssh_channel
*c
;
7101 c
= ssh2_channel_msg(ssh
, pktin
);
7104 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
7105 return; /* dunno why they're failing this */
7107 reason_code
= ssh_pkt_getuint32(pktin
);
7108 if (reason_code
>= lenof(reasons
))
7109 reason_code
= 0; /* ensure reasons[reason_code] in range */
7110 ssh_pkt_getstring(pktin
, &reason_string
, &reason_length
);
7111 logeventf(ssh
, "Forwarded connection refused by server: %s [%.*s]",
7112 reasons
[reason_code
], reason_length
, reason_string
);
7114 pfd_close(c
->u
.pfd
.s
);
7116 del234(ssh
->channels
, c
);
7120 static void ssh2_msg_channel_request(Ssh ssh
, struct Packet
*pktin
)
7123 int typelen
, want_reply
;
7124 int reply
= SSH2_MSG_CHANNEL_FAILURE
; /* default */
7125 struct ssh_channel
*c
;
7126 struct Packet
*pktout
;
7128 c
= ssh2_channel_msg(ssh
, pktin
);
7131 ssh_pkt_getstring(pktin
, &type
, &typelen
);
7132 want_reply
= ssh2_pkt_getbool(pktin
);
7135 * Having got the channel number, we now look at
7136 * the request type string to see if it's something
7139 if (c
== ssh
->mainchan
) {
7141 * We recognise "exit-status" and "exit-signal" on
7142 * the primary channel.
7144 if (typelen
== 11 &&
7145 !memcmp(type
, "exit-status", 11)) {
7147 ssh
->exitcode
= ssh_pkt_getuint32(pktin
);
7148 logeventf(ssh
, "Server sent command exit status %d",
7150 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
7152 } else if (typelen
== 11 &&
7153 !memcmp(type
, "exit-signal", 11)) {
7155 int is_plausible
= TRUE
, is_int
= FALSE
;
7156 char *fmt_sig
= "", *fmt_msg
= "";
7158 int msglen
= 0, core
= FALSE
;
7159 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7160 * provide an `int' for the signal, despite its
7161 * having been a `string' in the drafts of RFC 4254 since at
7162 * least 2001. (Fixed in session.c 1.147.) Try to
7163 * infer which we can safely parse it as. */
7165 unsigned char *p
= pktin
->body
+
7167 long len
= pktin
->length
- pktin
->savedpos
;
7168 unsigned long num
= GET_32BIT(p
); /* what is it? */
7169 /* If it's 0, it hardly matters; assume string */
7173 int maybe_int
= FALSE
, maybe_str
= FALSE
;
7174 #define CHECK_HYPOTHESIS(offset, result) \
7177 if (q >= 0 && q+4 <= len) { \
7178 q = q + 4 + GET_32BIT(p+q); \
7179 if (q >= 0 && q+4 <= len && \
7180 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
7184 CHECK_HYPOTHESIS(4+1, maybe_int
);
7185 CHECK_HYPOTHESIS(4+num
+1, maybe_str
);
7186 #undef CHECK_HYPOTHESIS
7187 if (maybe_int
&& !maybe_str
)
7189 else if (!maybe_int
&& maybe_str
)
7192 /* Crikey. Either or neither. Panic. */
7193 is_plausible
= FALSE
;
7196 ssh
->exitcode
= 128; /* means `unknown signal' */
7199 /* Old non-standard OpenSSH. */
7200 int signum
= ssh_pkt_getuint32(pktin
);
7201 fmt_sig
= dupprintf(" %d", signum
);
7202 ssh
->exitcode
= 128 + signum
;
7204 /* As per RFC 4254. */
7207 ssh_pkt_getstring(pktin
, &sig
, &siglen
);
7208 /* Signal name isn't supposed to be blank, but
7209 * let's cope gracefully if it is. */
7211 fmt_sig
= dupprintf(" \"%.*s\"",
7216 * Really hideous method of translating the
7217 * signal description back into a locally
7218 * meaningful number.
7223 #define TRANSLATE_SIGNAL(s) \
7224 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7225 ssh->exitcode = 128 + SIG ## s
7227 TRANSLATE_SIGNAL(ABRT
);
7230 TRANSLATE_SIGNAL(ALRM
);
7233 TRANSLATE_SIGNAL(FPE
);
7236 TRANSLATE_SIGNAL(HUP
);
7239 TRANSLATE_SIGNAL(ILL
);
7242 TRANSLATE_SIGNAL(INT
);
7245 TRANSLATE_SIGNAL(KILL
);
7248 TRANSLATE_SIGNAL(PIPE
);
7251 TRANSLATE_SIGNAL(QUIT
);
7254 TRANSLATE_SIGNAL(SEGV
);
7257 TRANSLATE_SIGNAL(TERM
);
7260 TRANSLATE_SIGNAL(USR1
);
7263 TRANSLATE_SIGNAL(USR2
);
7265 #undef TRANSLATE_SIGNAL
7267 ssh
->exitcode
= 128;
7269 core
= ssh2_pkt_getbool(pktin
);
7270 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
7272 fmt_msg
= dupprintf(" (\"%.*s\")", msglen
, msg
);
7274 /* ignore lang tag */
7275 } /* else don't attempt to parse */
7276 logeventf(ssh
, "Server exited on signal%s%s%s",
7277 fmt_sig
, core ?
" (core dumped)" : "",
7279 if (*fmt_sig
) sfree(fmt_sig
);
7280 if (*fmt_msg
) sfree(fmt_msg
);
7281 reply
= SSH2_MSG_CHANNEL_SUCCESS
;
7286 * This is a channel request we don't know
7287 * about, so we now either ignore the request
7288 * or respond with CHANNEL_FAILURE, depending
7291 reply
= SSH2_MSG_CHANNEL_FAILURE
;
7294 pktout
= ssh2_pkt_init(reply
);
7295 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
7296 ssh2_pkt_send(ssh
, pktout
);
7300 static void ssh2_msg_global_request(Ssh ssh
, struct Packet
*pktin
)
7303 int typelen
, want_reply
;
7304 struct Packet
*pktout
;
7306 ssh_pkt_getstring(pktin
, &type
, &typelen
);
7307 want_reply
= ssh2_pkt_getbool(pktin
);
7310 * We currently don't support any global requests
7311 * at all, so we either ignore the request or
7312 * respond with REQUEST_FAILURE, depending on
7316 pktout
= ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
7317 ssh2_pkt_send(ssh
, pktout
);
7321 static void ssh2_msg_channel_open(Ssh ssh
, struct Packet
*pktin
)
7329 struct ssh_channel
*c
;
7330 unsigned remid
, winsize
, pktsize
;
7331 struct Packet
*pktout
;
7333 ssh_pkt_getstring(pktin
, &type
, &typelen
);
7334 c
= snew(struct ssh_channel
);
7337 remid
= ssh_pkt_getuint32(pktin
);
7338 winsize
= ssh_pkt_getuint32(pktin
);
7339 pktsize
= ssh_pkt_getuint32(pktin
);
7341 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
7345 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
7346 addrstr
= snewn(peeraddrlen
+1, char);
7347 memcpy(addrstr
, peeraddr
, peeraddrlen
);
7348 addrstr
[peeraddrlen
] = '\0';
7349 peerport
= ssh_pkt_getuint32(pktin
);
7351 logeventf(ssh
, "Received X11 connect request from %s:%d",
7354 if (!ssh
->X11_fwd_enabled
)
7355 error
= "X11 forwarding is not enabled";
7356 else if ((x11err
= x11_init(&c
->u
.x11
.s
, ssh
->x11disp
, c
,
7357 addrstr
, peerport
, ssh
->conf
)) != NULL
) {
7358 logeventf(ssh
, "Local X11 connection failed: %s", x11err
);
7359 error
= "Unable to open an X11 connection";
7361 logevent("Opening X11 forward connection succeeded");
7366 } else if (typelen
== 15 &&
7367 !memcmp(type
, "forwarded-tcpip", 15)) {
7368 struct ssh_rportfwd pf
, *realpf
;
7371 ssh_pkt_getstring(pktin
, &dummy
, &dummylen
);/* skip address */
7372 pf
.sport
= ssh_pkt_getuint32(pktin
);
7373 ssh_pkt_getstring(pktin
, &peeraddr
, &peeraddrlen
);
7374 peerport
= ssh_pkt_getuint32(pktin
);
7375 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
7376 logeventf(ssh
, "Received remote port %d open request "
7377 "from %s:%d", pf
.sport
, peeraddr
, peerport
);
7378 if (realpf
== NULL
) {
7379 error
= "Remote port is not recognised";
7381 const char *e
= pfd_newconnect(&c
->u
.pfd
.s
,
7385 realpf
->pfrec
->addressfamily
);
7386 logeventf(ssh
, "Attempting to forward remote port to "
7387 "%s:%d", realpf
->dhost
, realpf
->dport
);
7389 logeventf(ssh
, "Port open failed: %s", e
);
7390 error
= "Port open failed";
7392 logevent("Forwarded port opened successfully");
7393 c
->type
= CHAN_SOCKDATA
;
7396 } else if (typelen
== 22 &&
7397 !memcmp(type
, "auth-agent@openssh.com", 22)) {
7398 if (!ssh
->agentfwd_enabled
)
7399 error
= "Agent forwarding is not enabled";
7401 c
->type
= CHAN_AGENT
; /* identify channel type */
7402 c
->u
.a
.lensofar
= 0;
7405 error
= "Unsupported channel type requested";
7408 c
->remoteid
= remid
;
7409 c
->halfopen
= FALSE
;
7411 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
7412 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
7413 ssh2_pkt_adduint32(pktout
, SSH2_OPEN_CONNECT_FAILED
);
7414 ssh2_pkt_addstring(pktout
, error
);
7415 ssh2_pkt_addstring(pktout
, "en"); /* language tag */
7416 ssh2_pkt_send(ssh
, pktout
);
7417 logeventf(ssh
, "Rejected channel open: %s", error
);
7420 ssh2_channel_init(c
);
7421 c
->v
.v2
.remwindow
= winsize
;
7422 c
->v
.v2
.remmaxpkt
= pktsize
;
7423 add234(ssh
->channels
, c
);
7424 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
7425 ssh2_pkt_adduint32(pktout
, c
->remoteid
);
7426 ssh2_pkt_adduint32(pktout
, c
->localid
);
7427 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);
7428 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
7429 ssh2_pkt_send(ssh
, pktout
);
7434 * Buffer banner messages for later display at some convenient point,
7435 * if we're going to display them.
7437 static void ssh2_msg_userauth_banner(Ssh ssh
, struct Packet
*pktin
)
7439 /* Arbitrary limit to prevent unbounded inflation of buffer */
7440 if (conf_get_int(ssh
->conf
, CONF_ssh_show_banner
) &&
7441 bufchain_size(&ssh
->banner
) <= 131072) {
7442 char *banner
= NULL
;
7444 ssh_pkt_getstring(pktin
, &banner
, &size
);
7446 bufchain_add(&ssh
->banner
, banner
, size
);
7450 /* Helper function to deal with sending tty modes for "pty-req" */
7451 static void ssh2_send_ttymode(void *data
, char *mode
, char *val
)
7453 struct Packet
*pktout
= (struct Packet
*)data
;
7455 unsigned int arg
= 0;
7456 while (strcmp(mode
, ssh_ttymodes
[i
].mode
) != 0) i
++;
7457 if (i
== lenof(ssh_ttymodes
)) return;
7458 switch (ssh_ttymodes
[i
].type
) {
7460 arg
= ssh_tty_parse_specchar(val
);
7463 arg
= ssh_tty_parse_boolean(val
);
7466 ssh2_pkt_addbyte(pktout
, ssh_ttymodes
[i
].opcode
);
7467 ssh2_pkt_adduint32(pktout
, arg
);
7470 static void ssh2_maybe_setup_x11(struct ssh_channel
*c
, struct Packet
*pktin
,
7473 struct ssh2_maybe_setup_x11_state
{
7477 struct Packet
*pktout
;
7478 crStateP(ssh2_maybe_setup_x11_state
, ctx
);
7483 * Potentially enable X11 forwarding.
7485 if (ssh
->mainchan
&& !ssh
->ncmode
&& conf_get_int(ssh
->conf
, CONF_x11_forward
) &&
7486 (ssh
->x11disp
= x11_setup_display(conf_get_str(ssh
->conf
, CONF_x11_display
),
7487 conf_get_int(ssh
->conf
, CONF_x11_auth
), ssh
->conf
))) {
7488 logevent("Requesting X11 forwarding");
7489 pktout
= ssh2_chanreq_init(ssh
->mainchan
, "x11-req",
7490 ssh2_maybe_setup_x11
, s
);
7491 ssh2_pkt_addbool(pktout
, 0); /* many connections */
7492 ssh2_pkt_addstring(pktout
, ssh
->x11disp
->remoteauthprotoname
);
7494 * Note that while we blank the X authentication data here, we don't
7495 * take any special action to blank the start of an X11 channel,
7496 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
7497 * without having session blanking enabled is likely to leak your
7498 * cookie into the log.
7500 dont_log_password(ssh
, pktout
, PKTLOG_BLANK
);
7501 ssh2_pkt_addstring(pktout
, ssh
->x11disp
->remoteauthdatastring
);
7502 end_log_omission(ssh
, pktout
);
7503 ssh2_pkt_adduint32(pktout
, ssh
->x11disp
->screennum
);
7504 ssh2_pkt_send(ssh
, pktout
);
7506 crWaitUntilV(pktin
);
7509 if (pktin
->type
== SSH2_MSG_CHANNEL_SUCCESS
) {
7510 logevent("X11 forwarding enabled");
7511 ssh
->X11_fwd_enabled
= TRUE
;
7513 logevent("X11 forwarding refused");
7519 static void ssh2_maybe_setup_agent(struct ssh_channel
*c
, struct Packet
*pktin
,
7522 struct ssh2_maybe_setup_agent_state
{
7526 struct Packet
*pktout
;
7527 crStateP(ssh2_maybe_setup_agent_state
, ctx
);
7531 if (ssh
->mainchan
&& !ssh
->ncmode
&& conf_get_int(ssh
->conf
, CONF_agentfwd
) && agent_exists()) {
7532 logevent("Requesting OpenSSH-style agent forwarding");
7533 pktout
= ssh2_chanreq_init(ssh
->mainchan
, "auth-agent-req@openssh.com",
7534 ssh2_maybe_setup_agent
, s
);
7535 ssh2_pkt_send(ssh
, pktout
);
7537 crWaitUntilV(pktin
);
7540 if (pktin
->type
== SSH2_MSG_CHANNEL_SUCCESS
) {
7541 logevent("Agent forwarding enabled");
7542 ssh
->agentfwd_enabled
= TRUE
;
7544 logevent("Agent forwarding refused");
7550 static void ssh2_maybe_setup_pty(struct ssh_channel
*c
, struct Packet
*pktin
,
7553 struct ssh2_maybe_setup_pty_state
{
7557 struct Packet
*pktout
;
7558 crStateP(ssh2_maybe_setup_pty_state
, ctx
);
7562 if (ssh
->mainchan
&& !ssh
->ncmode
&& !conf_get_int(ssh
->conf
, CONF_nopty
)) {
7563 /* Unpick the terminal-speed string. */
7564 /* XXX perhaps we should allow no speeds to be sent. */
7565 ssh
->ospeed
= 38400; ssh
->ispeed
= 38400; /* last-resort defaults */
7566 sscanf(conf_get_str(ssh
->conf
, CONF_termspeed
), "%d,%d", &ssh
->ospeed
, &ssh
->ispeed
);
7567 /* Build the pty request. */
7568 pktout
= ssh2_chanreq_init(ssh
->mainchan
, "pty-req",
7569 ssh2_maybe_setup_pty
, s
);
7570 ssh2_pkt_addstring(pktout
, conf_get_str(ssh
->conf
, CONF_termtype
));
7571 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
7572 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
7573 ssh2_pkt_adduint32(pktout
, 0); /* pixel width */
7574 ssh2_pkt_adduint32(pktout
, 0); /* pixel height */
7575 ssh2_pkt_addstring_start(pktout
);
7576 parse_ttymodes(ssh
, ssh2_send_ttymode
, (void *)pktout
);
7577 ssh2_pkt_addbyte(pktout
, SSH2_TTY_OP_ISPEED
);
7578 ssh2_pkt_adduint32(pktout
, ssh
->ispeed
);
7579 ssh2_pkt_addbyte(pktout
, SSH2_TTY_OP_OSPEED
);
7580 ssh2_pkt_adduint32(pktout
, ssh
->ospeed
);
7581 ssh2_pkt_addstring_data(pktout
, "\0", 1); /* TTY_OP_END */
7582 ssh2_pkt_send(ssh
, pktout
);
7583 ssh
->state
= SSH_STATE_INTERMED
;
7585 crWaitUntilV(pktin
);
7588 if (pktin
->type
== SSH2_MSG_CHANNEL_SUCCESS
) {
7589 logeventf(ssh
, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7590 ssh
->ospeed
, ssh
->ispeed
);
7591 ssh
->got_pty
= TRUE
;
7593 c_write_str(ssh
, "Server refused to allocate pty\r\n");
7594 ssh
->editing
= ssh
->echoing
= 1;
7598 ssh
->editing
= ssh
->echoing
= 1;
7603 static void ssh2_setup_env(struct ssh_channel
*c
, struct Packet
*pktin
,
7606 struct ssh2_setup_env_state
{
7608 int num_env
, env_left
, env_ok
;
7611 struct Packet
*pktout
;
7612 crStateP(ssh2_setup_env_state
, ctx
);
7617 * Send environment variables.
7619 * Simplest thing here is to send all the requests at once, and
7620 * then wait for a whole bunch of successes or failures.
7623 if (ssh
->mainchan
&& !ssh
->ncmode
) {
7626 for (val
= conf_get_str_strs(ssh
->conf
, CONF_environmt
, NULL
, &key
);
7628 val
= conf_get_str_strs(ssh
->conf
, CONF_environmt
, key
, &key
)) {
7629 pktout
= ssh2_chanreq_init(ssh
->mainchan
, "env", ssh2_setup_env
, s
);
7630 ssh2_pkt_addstring(pktout
, key
);
7631 ssh2_pkt_addstring(pktout
, val
);
7632 ssh2_pkt_send(ssh
, pktout
);
7637 logeventf(ssh
, "Sent %d environment variables", s
->num_env
);
7642 s
->env_left
= s
->num_env
;
7644 while (s
->env_left
> 0) {
7645 crWaitUntilV(pktin
);
7646 if (!pktin
) goto out
;
7647 if (pktin
->type
== SSH2_MSG_CHANNEL_SUCCESS
)
7652 if (s
->env_ok
== s
->num_env
) {
7653 logevent("All environment variables successfully set");
7654 } else if (s
->env_ok
== 0) {
7655 logevent("All environment variables refused");
7656 c_write_str(ssh
, "Server refused to set environment variables\r\n");
7658 logeventf(ssh
, "%d environment variables refused",
7659 s
->num_env
- s
->env_ok
);
7660 c_write_str(ssh
, "Server refused to set all environment variables\r\n");
7668 * Handle the SSH-2 userauth and connection layers.
7670 static void ssh2_msg_authconn(Ssh ssh
, struct Packet
*pktin
)
7672 do_ssh2_authconn(ssh
, NULL
, 0, pktin
);
7675 static void ssh2_response_authconn(struct ssh_channel
*c
, struct Packet
*pktin
,
7678 do_ssh2_authconn(c
->ssh
, NULL
, 0, pktin
);
7681 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
,
7682 struct Packet
*pktin
)
7684 struct do_ssh2_authconn_state
{
7688 AUTH_TYPE_PUBLICKEY
,
7689 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
7690 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
7692 AUTH_TYPE_GSSAPI
, /* always QUIET */
7693 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
7694 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7696 int done_service_req
;
7697 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
7698 int tried_pubkey_config
, done_agent
;
7703 int kbd_inter_refused
;
7704 int we_are_in
, userauth_success
;
7705 prompts_t
*cur_prompt
;
7710 void *publickey_blob
;
7711 int publickey_bloblen
;
7712 int publickey_encrypted
;
7713 char *publickey_algorithm
;
7714 char *publickey_comment
;
7715 unsigned char agent_request
[5], *agent_response
, *agentp
;
7716 int agent_responselen
;
7717 unsigned char *pkblob_in_agent
;
7719 char *pkblob
, *alg
, *commentp
;
7720 int pklen
, alglen
, commentlen
;
7721 int siglen
, retlen
, len
;
7722 char *q
, *agentreq
, *ret
;
7724 struct Packet
*pktout
;
7727 struct ssh_gss_library
*gsslib
;
7728 Ssh_gss_ctx gss_ctx
;
7729 Ssh_gss_buf gss_buf
;
7730 Ssh_gss_buf gss_rcvtok
, gss_sndtok
;
7731 Ssh_gss_name gss_srv_name
;
7732 Ssh_gss_stat gss_stat
;
7735 crState(do_ssh2_authconn_state
);
7739 /* Register as a handler for all the messages this coroutine handles. */
7740 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = ssh2_msg_authconn
;
7741 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = ssh2_msg_authconn
;
7742 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = ssh2_msg_authconn
;
7743 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = ssh2_msg_authconn
;
7744 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = ssh2_msg_authconn
;
7745 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = ssh2_msg_authconn
;
7746 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7747 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7748 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = ssh2_msg_authconn
;
7749 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = ssh2_msg_authconn
;
7750 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = ssh2_msg_authconn
;
7751 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = ssh2_msg_authconn
;
7752 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = ssh2_msg_authconn
;
7753 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = ssh2_msg_authconn
;
7754 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = ssh2_msg_authconn
;
7755 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = ssh2_msg_authconn
;
7756 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = ssh2_msg_authconn
;
7757 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = ssh2_msg_authconn
;
7758 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_authconn
;
7759 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_authconn
;
7761 s
->done_service_req
= FALSE
;
7762 s
->we_are_in
= s
->userauth_success
= FALSE
;
7764 s
->tried_gssapi
= FALSE
;
7767 if (!conf_get_int(ssh
->conf
, CONF_ssh_no_userauth
)) {
7769 * Request userauth protocol, and await a response to it.
7771 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
7772 ssh2_pkt_addstring(s
->pktout
, "ssh-userauth");
7773 ssh2_pkt_send(ssh
, s
->pktout
);
7774 crWaitUntilV(pktin
);
7775 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
)
7776 s
->done_service_req
= TRUE
;
7778 if (!s
->done_service_req
) {
7780 * Request connection protocol directly, without authentication.
7782 s
->pktout
= ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
7783 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
7784 ssh2_pkt_send(ssh
, s
->pktout
);
7785 crWaitUntilV(pktin
);
7786 if (pktin
->type
== SSH2_MSG_SERVICE_ACCEPT
) {
7787 s
->we_are_in
= TRUE
; /* no auth required */
7789 bombout(("Server refused service request"));
7794 /* Arrange to be able to deal with any BANNERs that come in.
7795 * (We do this now as packets may come in during the next bit.) */
7796 bufchain_init(&ssh
->banner
);
7797 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] =
7798 ssh2_msg_userauth_banner
;
7801 * Misc one-time setup for authentication.
7803 s
->publickey_blob
= NULL
;
7804 if (!s
->we_are_in
) {
7807 * Load the public half of any configured public key file
7810 s
->keyfile
= conf_get_filename(ssh
->conf
, CONF_keyfile
);
7811 if (!filename_is_null(s
->keyfile
)) {
7813 logeventf(ssh
, "Reading private key file \"%.150s\"",
7814 filename_to_str(s
->keyfile
));
7815 keytype
= key_type(s
->keyfile
);
7816 if (keytype
== SSH_KEYTYPE_SSH2
) {
7819 ssh2_userkey_loadpub(s
->keyfile
,
7820 &s
->publickey_algorithm
,
7821 &s
->publickey_bloblen
,
7822 &s
->publickey_comment
, &error
);
7823 if (s
->publickey_blob
) {
7824 s
->publickey_encrypted
=
7825 ssh2_userkey_encrypted(s
->keyfile
, NULL
);
7828 logeventf(ssh
, "Unable to load private key (%s)",
7830 msgbuf
= dupprintf("Unable to load private key file "
7831 "\"%.150s\" (%s)\r\n",
7832 filename_to_str(s
->keyfile
),
7834 c_write_str(ssh
, msgbuf
);
7839 logeventf(ssh
, "Unable to use this key file (%s)",
7840 key_type_to_str(keytype
));
7841 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
7843 filename_to_str(s
->keyfile
),
7844 key_type_to_str(keytype
));
7845 c_write_str(ssh
, msgbuf
);
7847 s
->publickey_blob
= NULL
;
7852 * Find out about any keys Pageant has (but if there's a
7853 * public key configured, filter out all others).
7856 s
->agent_response
= NULL
;
7857 s
->pkblob_in_agent
= NULL
;
7858 if (conf_get_int(ssh
->conf
, CONF_tryagent
) && agent_exists()) {
7862 logevent("Pageant is running. Requesting keys.");
7864 /* Request the keys held by the agent. */
7865 PUT_32BIT(s
->agent_request
, 1);
7866 s
->agent_request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
7867 if (!agent_query(s
->agent_request
, 5, &r
, &s
->agent_responselen
,
7868 ssh_agent_callback
, ssh
)) {
7872 bombout(("Unexpected data from server while"
7873 " waiting for agent response"));
7876 } while (pktin
|| inlen
> 0);
7877 r
= ssh
->agent_response
;
7878 s
->agent_responselen
= ssh
->agent_response_len
;
7880 s
->agent_response
= (unsigned char *) r
;
7881 if (s
->agent_response
&& s
->agent_responselen
>= 5 &&
7882 s
->agent_response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
7885 p
= s
->agent_response
+ 5;
7886 s
->nkeys
= GET_32BIT(p
);
7888 logeventf(ssh
, "Pageant has %d SSH-2 keys", s
->nkeys
);
7889 if (s
->publickey_blob
) {
7890 /* See if configured key is in agent. */
7891 for (keyi
= 0; keyi
< s
->nkeys
; keyi
++) {
7892 s
->pklen
= GET_32BIT(p
);
7893 if (s
->pklen
== s
->publickey_bloblen
&&
7894 !memcmp(p
+4, s
->publickey_blob
,
7895 s
->publickey_bloblen
)) {
7896 logeventf(ssh
, "Pageant key #%d matches "
7897 "configured key file", keyi
);
7899 s
->pkblob_in_agent
= p
;
7903 p
+= GET_32BIT(p
) + 4; /* comment */
7905 if (!s
->pkblob_in_agent
) {
7906 logevent("Configured key file not in Pageant");
7911 logevent("Failed to get reply from Pageant");
7918 * We repeat this whole loop, including the username prompt,
7919 * until we manage a successful authentication. If the user
7920 * types the wrong _password_, they can be sent back to the
7921 * beginning to try another username, if this is configured on.
7922 * (If they specify a username in the config, they are never
7923 * asked, even if they do give a wrong password.)
7925 * I think this best serves the needs of
7927 * - the people who have no configuration, no keys, and just
7928 * want to try repeated (username,password) pairs until they
7929 * type both correctly
7931 * - people who have keys and configuration but occasionally
7932 * need to fall back to passwords
7934 * - people with a key held in Pageant, who might not have
7935 * logged in to a particular machine before; so they want to
7936 * type a username, and then _either_ their key will be
7937 * accepted, _or_ they will type a password. If they mistype
7938 * the username they will want to be able to get back and
7941 s
->got_username
= FALSE
;
7942 while (!s
->we_are_in
) {
7946 if (s
->got_username
&& !conf_get_int(ssh
->conf
, CONF_change_username
)) {
7948 * We got a username last time round this loop, and
7949 * with change_username turned off we don't try to get
7952 } else if ((ssh
->username
= get_remote_username(ssh
->conf
)) == NULL
) {
7953 int ret
; /* need not be kept over crReturn */
7954 s
->cur_prompt
= new_prompts(ssh
->frontend
);
7955 s
->cur_prompt
->to_server
= TRUE
;
7956 s
->cur_prompt
->name
= dupstr("SSH login name");
7957 add_prompt(s
->cur_prompt
, dupstr("login as: "), TRUE
);
7958 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
7961 crWaitUntilV(!pktin
);
7962 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
7967 * get_userpass_input() failed to get a username.
7970 free_prompts(s
->cur_prompt
);
7971 ssh_disconnect(ssh
, "No username provided", NULL
, 0, TRUE
);
7974 ssh
->username
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
7975 free_prompts(s
->cur_prompt
);
7978 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
7979 stuff
= dupprintf("Using username \"%s\".\r\n", ssh
->username
);
7980 c_write_str(ssh
, stuff
);
7984 s
->got_username
= TRUE
;
7987 * Send an authentication request using method "none": (a)
7988 * just in case it succeeds, and (b) so that we know what
7989 * authentication methods we can usefully try next.
7991 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
7993 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
7994 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
7995 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");/* service requested */
7996 ssh2_pkt_addstring(s
->pktout
, "none"); /* method */
7997 ssh2_pkt_send(ssh
, s
->pktout
);
7998 s
->type
= AUTH_TYPE_NONE
;
8000 s
->we_are_in
= FALSE
;
8002 s
->tried_pubkey_config
= FALSE
;
8003 s
->kbd_inter_refused
= FALSE
;
8005 /* Reset agent request state. */
8006 s
->done_agent
= FALSE
;
8007 if (s
->agent_response
) {
8008 if (s
->pkblob_in_agent
) {
8009 s
->agentp
= s
->pkblob_in_agent
;
8011 s
->agentp
= s
->agent_response
+ 5 + 4;
8017 char *methods
= NULL
;
8021 * Wait for the result of the last authentication request.
8024 crWaitUntilV(pktin
);
8026 * Now is a convenient point to spew any banner material
8027 * that we've accumulated. (This should ensure that when
8028 * we exit the auth loop, we haven't any left to deal
8032 int size
= bufchain_size(&ssh
->banner
);
8034 * Don't show the banner if we're operating in
8035 * non-verbose non-interactive mode. (It's probably
8036 * a script, which means nobody will read the
8037 * banner _anyway_, and moreover the printing of
8038 * the banner will screw up processing on the
8039 * output of (say) plink.)
8041 if (size
&& (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
))) {
8042 char *banner
= snewn(size
, char);
8043 bufchain_fetch(&ssh
->banner
, banner
, size
);
8044 c_write_untrusted(ssh
, banner
, size
);
8047 bufchain_clear(&ssh
->banner
);
8049 if (pktin
->type
== SSH2_MSG_USERAUTH_SUCCESS
) {
8050 logevent("Access granted");
8051 s
->we_are_in
= s
->userauth_success
= TRUE
;
8055 if (pktin
->type
!= SSH2_MSG_USERAUTH_FAILURE
&& s
->type
!= AUTH_TYPE_GSSAPI
) {
8056 bombout(("Strange packet received during authentication: "
8057 "type %d", pktin
->type
));
8064 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8065 * we can look at the string in it and know what we can
8066 * helpfully try next.
8068 if (pktin
->type
== SSH2_MSG_USERAUTH_FAILURE
) {
8069 ssh_pkt_getstring(pktin
, &methods
, &methlen
);
8070 if (!ssh2_pkt_getbool(pktin
)) {
8072 * We have received an unequivocal Access
8073 * Denied. This can translate to a variety of
8074 * messages, or no message at all.
8076 * For forms of authentication which are attempted
8077 * implicitly, by which I mean without printing
8078 * anything in the window indicating that we're
8079 * trying them, we should never print 'Access
8082 * If we do print a message saying that we're
8083 * attempting some kind of authentication, it's OK
8084 * to print a followup message saying it failed -
8085 * but the message may sometimes be more specific
8086 * than simply 'Access denied'.
8088 * Additionally, if we'd just tried password
8089 * authentication, we should break out of this
8090 * whole loop so as to go back to the username
8091 * prompt (iff we're configured to allow
8092 * username change attempts).
8094 if (s
->type
== AUTH_TYPE_NONE
) {
8096 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
8097 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
8098 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
8099 c_write_str(ssh
, "Server refused our key\r\n");
8100 logevent("Server refused our key");
8101 } else if (s
->type
== AUTH_TYPE_PUBLICKEY
) {
8102 /* This _shouldn't_ happen except by a
8103 * protocol bug causing client and server to
8104 * disagree on what is a correct signature. */
8105 c_write_str(ssh
, "Server refused public-key signature"
8106 " despite accepting key!\r\n");
8107 logevent("Server refused public-key signature"
8108 " despite accepting key!");
8109 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
8110 /* quiet, so no c_write */
8111 logevent("Server refused keyboard-interactive authentication");
8112 } else if (s
->type
==AUTH_TYPE_GSSAPI
) {
8113 /* always quiet, so no c_write */
8114 /* also, the code down in the GSSAPI block has
8115 * already logged this in the Event Log */
8116 } else if (s
->type
== AUTH_TYPE_KEYBOARD_INTERACTIVE
) {
8117 logevent("Keyboard-interactive authentication failed");
8118 c_write_str(ssh
, "Access denied\r\n");
8120 assert(s
->type
== AUTH_TYPE_PASSWORD
);
8121 logevent("Password authentication failed");
8122 c_write_str(ssh
, "Access denied\r\n");
8124 if (conf_get_int(ssh
->conf
, CONF_change_username
)) {
8125 /* XXX perhaps we should allow
8126 * keyboard-interactive to do this too? */
8127 s
->we_are_in
= FALSE
;
8132 c_write_str(ssh
, "Further authentication required\r\n");
8133 logevent("Further authentication required");
8137 in_commasep_string("publickey", methods
, methlen
);
8139 in_commasep_string("password", methods
, methlen
);
8140 s
->can_keyb_inter
= conf_get_int(ssh
->conf
, CONF_try_ki_auth
) &&
8141 in_commasep_string("keyboard-interactive", methods
, methlen
);
8144 ssh
->gsslibs
= ssh_gss_setup(ssh
->conf
);
8145 s
->can_gssapi
= conf_get_int(ssh
->conf
, CONF_try_gssapi_auth
) &&
8146 in_commasep_string("gssapi-with-mic", methods
, methlen
) &&
8147 ssh
->gsslibs
->nlibraries
> 0;
8151 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
8153 if (s
->can_pubkey
&& !s
->done_agent
&& s
->nkeys
) {
8156 * Attempt public-key authentication using a key from Pageant.
8159 ssh
->pkt_actx
= SSH2_PKTCTX_PUBLICKEY
;
8161 logeventf(ssh
, "Trying Pageant key #%d", s
->keyi
);
8163 /* Unpack key from agent response */
8164 s
->pklen
= GET_32BIT(s
->agentp
);
8166 s
->pkblob
= (char *)s
->agentp
;
8167 s
->agentp
+= s
->pklen
;
8168 s
->alglen
= GET_32BIT(s
->pkblob
);
8169 s
->alg
= s
->pkblob
+ 4;
8170 s
->commentlen
= GET_32BIT(s
->agentp
);
8172 s
->commentp
= (char *)s
->agentp
;
8173 s
->agentp
+= s
->commentlen
;
8174 /* s->agentp now points at next key, if any */
8176 /* See if server will accept it */
8177 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8178 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
8179 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8180 /* service requested */
8181 ssh2_pkt_addstring(s
->pktout
, "publickey");
8183 ssh2_pkt_addbool(s
->pktout
, FALSE
); /* no signature included */
8184 ssh2_pkt_addstring_start(s
->pktout
);
8185 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
8186 ssh2_pkt_addstring_start(s
->pktout
);
8187 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
8188 ssh2_pkt_send(ssh
, s
->pktout
);
8189 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_QUIET
;
8191 crWaitUntilV(pktin
);
8192 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
8194 /* Offer of key refused. */
8201 if (flags
& FLAG_VERBOSE
) {
8202 c_write_str(ssh
, "Authenticating with "
8204 c_write(ssh
, s
->commentp
, s
->commentlen
);
8205 c_write_str(ssh
, "\" from agent\r\n");
8209 * Server is willing to accept the key.
8210 * Construct a SIGN_REQUEST.
8212 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8213 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
8214 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8215 /* service requested */
8216 ssh2_pkt_addstring(s
->pktout
, "publickey");
8218 ssh2_pkt_addbool(s
->pktout
, TRUE
); /* signature included */
8219 ssh2_pkt_addstring_start(s
->pktout
);
8220 ssh2_pkt_addstring_data(s
->pktout
, s
->alg
, s
->alglen
);
8221 ssh2_pkt_addstring_start(s
->pktout
);
8222 ssh2_pkt_addstring_data(s
->pktout
, s
->pkblob
, s
->pklen
);
8224 /* Ask agent for signature. */
8225 s
->siglen
= s
->pktout
->length
- 5 + 4 +
8226 ssh
->v2_session_id_len
;
8227 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
8229 s
->len
= 1; /* message type */
8230 s
->len
+= 4 + s
->pklen
; /* key blob */
8231 s
->len
+= 4 + s
->siglen
; /* data to sign */
8232 s
->len
+= 4; /* flags */
8233 s
->agentreq
= snewn(4 + s
->len
, char);
8234 PUT_32BIT(s
->agentreq
, s
->len
);
8235 s
->q
= s
->agentreq
+ 4;
8236 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
8237 PUT_32BIT(s
->q
, s
->pklen
);
8239 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
8241 PUT_32BIT(s
->q
, s
->siglen
);
8243 /* Now the data to be signed... */
8244 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
8245 PUT_32BIT(s
->q
, ssh
->v2_session_id_len
);
8248 memcpy(s
->q
, ssh
->v2_session_id
,
8249 ssh
->v2_session_id_len
);
8250 s
->q
+= ssh
->v2_session_id_len
;
8251 memcpy(s
->q
, s
->pktout
->data
+ 5,
8252 s
->pktout
->length
- 5);
8253 s
->q
+= s
->pktout
->length
- 5;
8254 /* And finally the (zero) flags word. */
8256 if (!agent_query(s
->agentreq
, s
->len
+ 4,
8258 ssh_agent_callback
, ssh
)) {
8262 bombout(("Unexpected data from server"
8263 " while waiting for agent"
8267 } while (pktin
|| inlen
> 0);
8268 vret
= ssh
->agent_response
;
8269 s
->retlen
= ssh
->agent_response_len
;
8274 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
8275 logevent("Sending Pageant's response");
8276 ssh2_add_sigblob(ssh
, s
->pktout
,
8277 s
->pkblob
, s
->pklen
,
8279 GET_32BIT(s
->ret
+ 5));
8280 ssh2_pkt_send(ssh
, s
->pktout
);
8281 s
->type
= AUTH_TYPE_PUBLICKEY
;
8283 /* FIXME: less drastic response */
8284 bombout(("Pageant failed to answer challenge"));
8290 /* Do we have any keys left to try? */
8291 if (s
->pkblob_in_agent
) {
8292 s
->done_agent
= TRUE
;
8293 s
->tried_pubkey_config
= TRUE
;
8296 if (s
->keyi
>= s
->nkeys
)
8297 s
->done_agent
= TRUE
;
8300 } else if (s
->can_pubkey
&& s
->publickey_blob
&&
8301 !s
->tried_pubkey_config
) {
8303 struct ssh2_userkey
*key
; /* not live over crReturn */
8304 char *passphrase
; /* not live over crReturn */
8306 ssh
->pkt_actx
= SSH2_PKTCTX_PUBLICKEY
;
8308 s
->tried_pubkey_config
= TRUE
;
8311 * Try the public key supplied in the configuration.
8313 * First, offer the public blob to see if the server is
8314 * willing to accept it.
8316 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8317 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
8318 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8319 /* service requested */
8320 ssh2_pkt_addstring(s
->pktout
, "publickey"); /* method */
8321 ssh2_pkt_addbool(s
->pktout
, FALSE
);
8322 /* no signature included */
8323 ssh2_pkt_addstring(s
->pktout
, s
->publickey_algorithm
);
8324 ssh2_pkt_addstring_start(s
->pktout
);
8325 ssh2_pkt_addstring_data(s
->pktout
,
8326 (char *)s
->publickey_blob
,
8327 s
->publickey_bloblen
);
8328 ssh2_pkt_send(ssh
, s
->pktout
);
8329 logevent("Offered public key");
8331 crWaitUntilV(pktin
);
8332 if (pktin
->type
!= SSH2_MSG_USERAUTH_PK_OK
) {
8333 /* Key refused. Give up. */
8334 s
->gotit
= TRUE
; /* reconsider message next loop */
8335 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
8336 continue; /* process this new message */
8338 logevent("Offer of public key accepted");
8341 * Actually attempt a serious authentication using
8344 if (flags
& FLAG_VERBOSE
) {
8345 c_write_str(ssh
, "Authenticating with public key \"");
8346 c_write_str(ssh
, s
->publickey_comment
);
8347 c_write_str(ssh
, "\"\r\n");
8351 const char *error
; /* not live over crReturn */
8352 if (s
->publickey_encrypted
) {
8354 * Get a passphrase from the user.
8356 int ret
; /* need not be kept over crReturn */
8357 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8358 s
->cur_prompt
->to_server
= FALSE
;
8359 s
->cur_prompt
->name
= dupstr("SSH key passphrase");
8360 add_prompt(s
->cur_prompt
,
8361 dupprintf("Passphrase for key \"%.100s\": ",
8362 s
->publickey_comment
),
8364 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8367 crWaitUntilV(!pktin
);
8368 ret
= get_userpass_input(s
->cur_prompt
,
8373 /* Failed to get a passphrase. Terminate. */
8374 free_prompts(s
->cur_prompt
);
8375 ssh_disconnect(ssh
, NULL
,
8376 "Unable to authenticate",
8377 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8382 dupstr(s
->cur_prompt
->prompts
[0]->result
);
8383 free_prompts(s
->cur_prompt
);
8385 passphrase
= NULL
; /* no passphrase needed */
8389 * Try decrypting the key.
8391 s
->keyfile
= conf_get_filename(ssh
->conf
, CONF_keyfile
);
8392 key
= ssh2_load_userkey(s
->keyfile
, passphrase
, &error
);
8394 /* burn the evidence */
8395 smemclr(passphrase
, strlen(passphrase
));
8398 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
8400 (key
== SSH2_WRONG_PASSPHRASE
)) {
8401 c_write_str(ssh
, "Wrong passphrase\r\n");
8403 /* and loop again */
8405 c_write_str(ssh
, "Unable to load private key (");
8406 c_write_str(ssh
, error
);
8407 c_write_str(ssh
, ")\r\n");
8409 break; /* try something else */
8415 unsigned char *pkblob
, *sigblob
, *sigdata
;
8416 int pkblob_len
, sigblob_len
, sigdata_len
;
8420 * We have loaded the private key and the server
8421 * has announced that it's willing to accept it.
8422 * Hallelujah. Generate a signature and send it.
8424 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8425 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
8426 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8427 /* service requested */
8428 ssh2_pkt_addstring(s
->pktout
, "publickey");
8430 ssh2_pkt_addbool(s
->pktout
, TRUE
);
8431 /* signature follows */
8432 ssh2_pkt_addstring(s
->pktout
, key
->alg
->name
);
8433 pkblob
= key
->alg
->public_blob(key
->data
,
8435 ssh2_pkt_addstring_start(s
->pktout
);
8436 ssh2_pkt_addstring_data(s
->pktout
, (char *)pkblob
,
8440 * The data to be signed is:
8444 * followed by everything so far placed in the
8447 sigdata_len
= s
->pktout
->length
- 5 + 4 +
8448 ssh
->v2_session_id_len
;
8449 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
8451 sigdata
= snewn(sigdata_len
, unsigned char);
8453 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
8454 PUT_32BIT(sigdata
+p
, ssh
->v2_session_id_len
);
8457 memcpy(sigdata
+p
, ssh
->v2_session_id
,
8458 ssh
->v2_session_id_len
);
8459 p
+= ssh
->v2_session_id_len
;
8460 memcpy(sigdata
+p
, s
->pktout
->data
+ 5,
8461 s
->pktout
->length
- 5);
8462 p
+= s
->pktout
->length
- 5;
8463 assert(p
== sigdata_len
);
8464 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
8465 sigdata_len
, &sigblob_len
);
8466 ssh2_add_sigblob(ssh
, s
->pktout
, pkblob
, pkblob_len
,
8467 sigblob
, sigblob_len
);
8472 ssh2_pkt_send(ssh
, s
->pktout
);
8473 logevent("Sent public key signature");
8474 s
->type
= AUTH_TYPE_PUBLICKEY
;
8475 key
->alg
->freekey(key
->data
);
8479 } else if (s
->can_gssapi
&& !s
->tried_gssapi
) {
8481 /* GSSAPI Authentication */
8486 s
->type
= AUTH_TYPE_GSSAPI
;
8487 s
->tried_gssapi
= TRUE
;
8489 ssh
->pkt_actx
= SSH2_PKTCTX_GSSAPI
;
8492 * Pick the highest GSS library on the preference
8498 for (i
= 0; i
< ngsslibs
; i
++) {
8499 int want_id
= conf_get_int_int(ssh
->conf
,
8500 CONF_ssh_gsslist
, i
);
8501 for (j
= 0; j
< ssh
->gsslibs
->nlibraries
; j
++)
8502 if (ssh
->gsslibs
->libraries
[j
].id
== want_id
) {
8503 s
->gsslib
= &ssh
->gsslibs
->libraries
[j
];
8504 goto got_gsslib
; /* double break */
8509 * We always expect to have found something in
8510 * the above loop: we only came here if there
8511 * was at least one viable GSS library, and the
8512 * preference list should always mention
8513 * everything and only change the order.
8518 if (s
->gsslib
->gsslogmsg
)
8519 logevent(s
->gsslib
->gsslogmsg
);
8521 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8522 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8523 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
8524 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8525 ssh2_pkt_addstring(s
->pktout
, "gssapi-with-mic");
8526 logevent("Attempting GSSAPI authentication");
8528 /* add mechanism info */
8529 s
->gsslib
->indicate_mech(s
->gsslib
, &s
->gss_buf
);
8531 /* number of GSSAPI mechanisms */
8532 ssh2_pkt_adduint32(s
->pktout
,1);
8534 /* length of OID + 2 */
8535 ssh2_pkt_adduint32(s
->pktout
, s
->gss_buf
.length
+ 2);
8536 ssh2_pkt_addbyte(s
->pktout
, SSH2_GSS_OIDTYPE
);
8539 ssh2_pkt_addbyte(s
->pktout
, (unsigned char) s
->gss_buf
.length
);
8541 ssh_pkt_adddata(s
->pktout
, s
->gss_buf
.value
,
8543 ssh2_pkt_send(ssh
, s
->pktout
);
8544 crWaitUntilV(pktin
);
8545 if (pktin
->type
!= SSH2_MSG_USERAUTH_GSSAPI_RESPONSE
) {
8546 logevent("GSSAPI authentication request refused");
8550 /* check returned packet ... */
8552 ssh_pkt_getstring(pktin
, &data
, &len
);
8553 s
->gss_rcvtok
.value
= data
;
8554 s
->gss_rcvtok
.length
= len
;
8555 if (s
->gss_rcvtok
.length
!= s
->gss_buf
.length
+ 2 ||
8556 ((char *)s
->gss_rcvtok
.value
)[0] != SSH2_GSS_OIDTYPE
||
8557 ((char *)s
->gss_rcvtok
.value
)[1] != s
->gss_buf
.length
||
8558 memcmp((char *)s
->gss_rcvtok
.value
+ 2,
8559 s
->gss_buf
.value
,s
->gss_buf
.length
) ) {
8560 logevent("GSSAPI authentication - wrong response from server");
8564 /* now start running */
8565 s
->gss_stat
= s
->gsslib
->import_name(s
->gsslib
,
8568 if (s
->gss_stat
!= SSH_GSS_OK
) {
8569 if (s
->gss_stat
== SSH_GSS_BAD_HOST_NAME
)
8570 logevent("GSSAPI import name failed - Bad service name");
8572 logevent("GSSAPI import name failed");
8576 /* fetch TGT into GSS engine */
8577 s
->gss_stat
= s
->gsslib
->acquire_cred(s
->gsslib
, &s
->gss_ctx
);
8579 if (s
->gss_stat
!= SSH_GSS_OK
) {
8580 logevent("GSSAPI authentication failed to get credentials");
8581 s
->gsslib
->release_name(s
->gsslib
, &s
->gss_srv_name
);
8585 /* initial tokens are empty */
8586 SSH_GSS_CLEAR_BUF(&s
->gss_rcvtok
);
8587 SSH_GSS_CLEAR_BUF(&s
->gss_sndtok
);
8589 /* now enter the loop */
8591 s
->gss_stat
= s
->gsslib
->init_sec_context
8595 conf_get_int(ssh
->conf
, CONF_gssapifwd
),
8599 if (s
->gss_stat
!=SSH_GSS_S_COMPLETE
&&
8600 s
->gss_stat
!=SSH_GSS_S_CONTINUE_NEEDED
) {
8601 logevent("GSSAPI authentication initialisation failed");
8603 if (s
->gsslib
->display_status(s
->gsslib
, s
->gss_ctx
,
8604 &s
->gss_buf
) == SSH_GSS_OK
) {
8605 logevent(s
->gss_buf
.value
);
8606 sfree(s
->gss_buf
.value
);
8611 logevent("GSSAPI authentication initialised");
8613 /* Client and server now exchange tokens until GSSAPI
8614 * no longer says CONTINUE_NEEDED */
8616 if (s
->gss_sndtok
.length
!= 0) {
8617 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN
);
8618 ssh_pkt_addstring_start(s
->pktout
);
8619 ssh_pkt_addstring_data(s
->pktout
,s
->gss_sndtok
.value
,s
->gss_sndtok
.length
);
8620 ssh2_pkt_send(ssh
, s
->pktout
);
8621 s
->gsslib
->free_tok(s
->gsslib
, &s
->gss_sndtok
);
8624 if (s
->gss_stat
== SSH_GSS_S_CONTINUE_NEEDED
) {
8625 crWaitUntilV(pktin
);
8626 if (pktin
->type
!= SSH2_MSG_USERAUTH_GSSAPI_TOKEN
) {
8627 logevent("GSSAPI authentication - bad server response");
8628 s
->gss_stat
= SSH_GSS_FAILURE
;
8631 ssh_pkt_getstring(pktin
, &data
, &len
);
8632 s
->gss_rcvtok
.value
= data
;
8633 s
->gss_rcvtok
.length
= len
;
8635 } while (s
-> gss_stat
== SSH_GSS_S_CONTINUE_NEEDED
);
8637 if (s
->gss_stat
!= SSH_GSS_OK
) {
8638 s
->gsslib
->release_name(s
->gsslib
, &s
->gss_srv_name
);
8639 s
->gsslib
->release_cred(s
->gsslib
, &s
->gss_ctx
);
8642 logevent("GSSAPI authentication loop finished OK");
8644 /* Now send the MIC */
8646 s
->pktout
= ssh2_pkt_init(0);
8647 micoffset
= s
->pktout
->length
;
8648 ssh_pkt_addstring_start(s
->pktout
);
8649 ssh_pkt_addstring_data(s
->pktout
, (char *)ssh
->v2_session_id
, ssh
->v2_session_id_len
);
8650 ssh_pkt_addbyte(s
->pktout
, SSH2_MSG_USERAUTH_REQUEST
);
8651 ssh_pkt_addstring(s
->pktout
, ssh
->username
);
8652 ssh_pkt_addstring(s
->pktout
, "ssh-connection");
8653 ssh_pkt_addstring(s
->pktout
, "gssapi-with-mic");
8655 s
->gss_buf
.value
= (char *)s
->pktout
->data
+ micoffset
;
8656 s
->gss_buf
.length
= s
->pktout
->length
- micoffset
;
8658 s
->gsslib
->get_mic(s
->gsslib
, s
->gss_ctx
, &s
->gss_buf
, &mic
);
8659 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC
);
8660 ssh_pkt_addstring_start(s
->pktout
);
8661 ssh_pkt_addstring_data(s
->pktout
, mic
.value
, mic
.length
);
8662 ssh2_pkt_send(ssh
, s
->pktout
);
8663 s
->gsslib
->free_mic(s
->gsslib
, &mic
);
8667 s
->gsslib
->release_name(s
->gsslib
, &s
->gss_srv_name
);
8668 s
->gsslib
->release_cred(s
->gsslib
, &s
->gss_ctx
);
8671 } else if (s
->can_keyb_inter
&& !s
->kbd_inter_refused
) {
8674 * Keyboard-interactive authentication.
8677 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
8679 ssh
->pkt_actx
= SSH2_PKTCTX_KBDINTER
;
8681 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8682 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
8683 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8684 /* service requested */
8685 ssh2_pkt_addstring(s
->pktout
, "keyboard-interactive");
8687 ssh2_pkt_addstring(s
->pktout
, ""); /* lang */
8688 ssh2_pkt_addstring(s
->pktout
, ""); /* submethods */
8689 ssh2_pkt_send(ssh
, s
->pktout
);
8691 logevent("Attempting keyboard-interactive authentication");
8693 crWaitUntilV(pktin
);
8694 if (pktin
->type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
8695 /* Server is not willing to do keyboard-interactive
8696 * at all (or, bizarrely but legally, accepts the
8697 * user without actually issuing any prompts).
8698 * Give up on it entirely. */
8700 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
8701 s
->kbd_inter_refused
= TRUE
; /* don't try it again */
8706 * Loop while the server continues to send INFO_REQUESTs.
8708 while (pktin
->type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
8710 char *name
, *inst
, *lang
;
8711 int name_len
, inst_len
, lang_len
;
8715 * We've got a fresh USERAUTH_INFO_REQUEST.
8716 * Get the preamble and start building a prompt.
8718 ssh_pkt_getstring(pktin
, &name
, &name_len
);
8719 ssh_pkt_getstring(pktin
, &inst
, &inst_len
);
8720 ssh_pkt_getstring(pktin
, &lang
, &lang_len
);
8721 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8722 s
->cur_prompt
->to_server
= TRUE
;
8725 * Get any prompt(s) from the packet.
8727 s
->num_prompts
= ssh_pkt_getuint32(pktin
);
8728 for (i
= 0; i
< s
->num_prompts
; i
++) {
8732 static char noprompt
[] =
8733 "<server failed to send prompt>: ";
8735 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
8736 echo
= ssh2_pkt_getbool(pktin
);
8739 prompt_len
= lenof(noprompt
)-1;
8741 add_prompt(s
->cur_prompt
,
8742 dupprintf("%.*s", prompt_len
, prompt
),
8747 /* FIXME: better prefix to distinguish from
8749 s
->cur_prompt
->name
=
8750 dupprintf("SSH server: %.*s", name_len
, name
);
8751 s
->cur_prompt
->name_reqd
= TRUE
;
8753 s
->cur_prompt
->name
=
8754 dupstr("SSH server authentication");
8755 s
->cur_prompt
->name_reqd
= FALSE
;
8757 /* We add a prefix to try to make it clear that a prompt
8758 * has come from the server.
8759 * FIXME: ugly to print "Using..." in prompt _every_
8760 * time round. Can this be done more subtly? */
8761 /* Special case: for reasons best known to themselves,
8762 * some servers send k-i requests with no prompts and
8763 * nothing to display. Keep quiet in this case. */
8764 if (s
->num_prompts
|| name_len
|| inst_len
) {
8765 s
->cur_prompt
->instruction
=
8766 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8767 inst_len ?
"\n" : "", inst_len
, inst
);
8768 s
->cur_prompt
->instr_reqd
= TRUE
;
8770 s
->cur_prompt
->instr_reqd
= FALSE
;
8774 * Display any instructions, and get the user's
8778 int ret
; /* not live over crReturn */
8779 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8782 crWaitUntilV(!pktin
);
8783 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8788 * Failed to get responses. Terminate.
8790 free_prompts(s
->cur_prompt
);
8791 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8792 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8799 * Send the response(s) to the server.
8801 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
8802 ssh2_pkt_adduint32(s
->pktout
, s
->num_prompts
);
8803 for (i
=0; i
< s
->num_prompts
; i
++) {
8804 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8805 ssh2_pkt_addstring(s
->pktout
,
8806 s
->cur_prompt
->prompts
[i
]->result
);
8807 end_log_omission(ssh
, s
->pktout
);
8809 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8812 * Free the prompts structure from this iteration.
8813 * If there's another, a new one will be allocated
8814 * when we return to the top of this while loop.
8816 free_prompts(s
->cur_prompt
);
8819 * Get the next packet in case it's another
8822 crWaitUntilV(pktin
);
8827 * We should have SUCCESS or FAILURE now.
8831 } else if (s
->can_passwd
) {
8834 * Plain old password authentication.
8836 int ret
; /* not live over crReturn */
8837 int changereq_first_time
; /* not live over crReturn */
8839 ssh
->pkt_actx
= SSH2_PKTCTX_PASSWORD
;
8841 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8842 s
->cur_prompt
->to_server
= TRUE
;
8843 s
->cur_prompt
->name
= dupstr("SSH password");
8844 add_prompt(s
->cur_prompt
, dupprintf("%s@%s's password: ",
8849 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8852 crWaitUntilV(!pktin
);
8853 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8858 * Failed to get responses. Terminate.
8860 free_prompts(s
->cur_prompt
);
8861 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8862 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8867 * Squirrel away the password. (We may need it later if
8868 * asked to change it.)
8870 s
->password
= dupstr(s
->cur_prompt
->prompts
[0]->result
);
8871 free_prompts(s
->cur_prompt
);
8874 * Send the password packet.
8876 * We pad out the password packet to 256 bytes to make
8877 * it harder for an attacker to find the length of the
8880 * Anyone using a password longer than 256 bytes
8881 * probably doesn't have much to worry about from
8882 * people who find out how long their password is!
8884 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
8885 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
8886 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
8887 /* service requested */
8888 ssh2_pkt_addstring(s
->pktout
, "password");
8889 ssh2_pkt_addbool(s
->pktout
, FALSE
);
8890 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
8891 ssh2_pkt_addstring(s
->pktout
, s
->password
);
8892 end_log_omission(ssh
, s
->pktout
);
8893 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
8894 logevent("Sent password");
8895 s
->type
= AUTH_TYPE_PASSWORD
;
8898 * Wait for next packet, in case it's a password change
8901 crWaitUntilV(pktin
);
8902 changereq_first_time
= TRUE
;
8904 while (pktin
->type
== SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
) {
8907 * We're being asked for a new password
8908 * (perhaps not for the first time).
8909 * Loop until the server accepts it.
8912 int got_new
= FALSE
; /* not live over crReturn */
8913 char *prompt
; /* not live over crReturn */
8914 int prompt_len
; /* not live over crReturn */
8918 if (changereq_first_time
)
8919 msg
= "Server requested password change";
8921 msg
= "Server rejected new password";
8923 c_write_str(ssh
, msg
);
8924 c_write_str(ssh
, "\r\n");
8927 ssh_pkt_getstring(pktin
, &prompt
, &prompt_len
);
8929 s
->cur_prompt
= new_prompts(ssh
->frontend
);
8930 s
->cur_prompt
->to_server
= TRUE
;
8931 s
->cur_prompt
->name
= dupstr("New SSH password");
8932 s
->cur_prompt
->instruction
=
8933 dupprintf("%.*s", prompt_len
, prompt
);
8934 s
->cur_prompt
->instr_reqd
= TRUE
;
8936 * There's no explicit requirement in the protocol
8937 * for the "old" passwords in the original and
8938 * password-change messages to be the same, and
8939 * apparently some Cisco kit supports password change
8940 * by the user entering a blank password originally
8941 * and the real password subsequently, so,
8942 * reluctantly, we prompt for the old password again.
8944 * (On the other hand, some servers don't even bother
8945 * to check this field.)
8947 add_prompt(s
->cur_prompt
,
8948 dupstr("Current password (blank for previously entered password): "),
8950 add_prompt(s
->cur_prompt
, dupstr("Enter new password: "),
8952 add_prompt(s
->cur_prompt
, dupstr("Confirm new password: "),
8956 * Loop until the user manages to enter the same
8961 ret
= get_userpass_input(s
->cur_prompt
, NULL
, 0);
8964 crWaitUntilV(!pktin
);
8965 ret
= get_userpass_input(s
->cur_prompt
, in
, inlen
);
8970 * Failed to get responses. Terminate.
8972 /* burn the evidence */
8973 free_prompts(s
->cur_prompt
);
8974 smemclr(s
->password
, strlen(s
->password
));
8976 ssh_disconnect(ssh
, NULL
, "Unable to authenticate",
8977 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER
,
8983 * If the user specified a new original password
8984 * (IYSWIM), overwrite any previously specified
8986 * (A side effect is that the user doesn't have to
8987 * re-enter it if they louse up the new password.)
8989 if (s
->cur_prompt
->prompts
[0]->result
[0]) {
8990 smemclr(s
->password
, strlen(s
->password
));
8991 /* burn the evidence */
8994 dupstr(s
->cur_prompt
->prompts
[0]->result
);
8998 * Check the two new passwords match.
9000 got_new
= (strcmp(s
->cur_prompt
->prompts
[1]->result
,
9001 s
->cur_prompt
->prompts
[2]->result
)
9004 /* They don't. Silly user. */
9005 c_write_str(ssh
, "Passwords do not match\r\n");
9010 * Send the new password (along with the old one).
9011 * (see above for padding rationale)
9013 s
->pktout
= ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
9014 ssh2_pkt_addstring(s
->pktout
, ssh
->username
);
9015 ssh2_pkt_addstring(s
->pktout
, "ssh-connection");
9016 /* service requested */
9017 ssh2_pkt_addstring(s
->pktout
, "password");
9018 ssh2_pkt_addbool(s
->pktout
, TRUE
);
9019 dont_log_password(ssh
, s
->pktout
, PKTLOG_BLANK
);
9020 ssh2_pkt_addstring(s
->pktout
, s
->password
);
9021 ssh2_pkt_addstring(s
->pktout
,
9022 s
->cur_prompt
->prompts
[1]->result
);
9023 free_prompts(s
->cur_prompt
);
9024 end_log_omission(ssh
, s
->pktout
);
9025 ssh2_pkt_send_with_padding(ssh
, s
->pktout
, 256);
9026 logevent("Sent new password");
9029 * Now see what the server has to say about it.
9030 * (If it's CHANGEREQ again, it's not happy with the
9033 crWaitUntilV(pktin
);
9034 changereq_first_time
= FALSE
;
9039 * We need to reexamine the current pktin at the top
9040 * of the loop. Either:
9041 * - we weren't asked to change password at all, in
9042 * which case it's a SUCCESS or FAILURE with the
9044 * - we sent a new password, and the server was
9045 * either OK with it (SUCCESS or FAILURE w/partial
9046 * success) or unhappy with the _old_ password
9047 * (FAILURE w/o partial success)
9048 * In any of these cases, we go back to the top of
9049 * the loop and start again.
9054 * We don't need the old password any more, in any
9055 * case. Burn the evidence.
9057 smemclr(s
->password
, strlen(s
->password
));
9061 char *str
= dupprintf("No supported authentication methods available"
9062 " (server sent: %.*s)",
9065 ssh_disconnect(ssh
, str
,
9066 "No supported authentication methods available",
9067 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE
,
9077 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = NULL
;
9079 /* Clear up various bits and pieces from authentication. */
9080 if (s
->publickey_blob
) {
9081 sfree(s
->publickey_blob
);
9082 sfree(s
->publickey_comment
);
9084 if (s
->agent_response
)
9085 sfree(s
->agent_response
);
9087 if (s
->userauth_success
) {
9089 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9090 * packets since. Signal the transport layer to consider enacting
9091 * delayed compression.
9093 * (Relying on we_are_in is not sufficient, as
9094 * draft-miller-secsh-compression-delayed is quite clear that it
9095 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9096 * become set for other reasons.)
9098 do_ssh2_transport(ssh
, "enabling delayed compression", -2, NULL
);
9102 * Now the connection protocol has started, one way or another.
9105 ssh
->channels
= newtree234(ssh_channelcmp
);
9108 * Set up handlers for some connection protocol messages, so we
9109 * don't have to handle them repeatedly in this coroutine.
9111 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] =
9112 ssh2_msg_channel_window_adjust
;
9113 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] =
9114 ssh2_msg_global_request
;
9117 * Create the main session channel.
9119 if (conf_get_int(ssh
->conf
, CONF_ssh_no_shell
)) {
9120 ssh
->mainchan
= NULL
;
9121 } else if (*conf_get_str(ssh
->conf
, CONF_ssh_nc_host
)) {
9123 * Just start a direct-tcpip channel and use it as the main
9126 ssh
->mainchan
= snew(struct ssh_channel
);
9127 ssh
->mainchan
->ssh
= ssh
;
9128 ssh2_channel_init(ssh
->mainchan
);
9130 "Opening direct-tcpip channel to %s:%d in place of session",
9131 conf_get_str(ssh
->conf
, CONF_ssh_nc_host
),
9132 conf_get_int(ssh
->conf
, CONF_ssh_nc_port
));
9133 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
9134 ssh2_pkt_addstring(s
->pktout
, "direct-tcpip");
9135 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
9136 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
9137 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
9138 ssh2_pkt_addstring(s
->pktout
, conf_get_str(ssh
->conf
, CONF_ssh_nc_host
));
9139 ssh2_pkt_adduint32(s
->pktout
, conf_get_int(ssh
->conf
, CONF_ssh_nc_port
));
9141 * There's nothing meaningful to put in the originator
9142 * fields, but some servers insist on syntactically correct
9145 ssh2_pkt_addstring(s
->pktout
, "0.0.0.0");
9146 ssh2_pkt_adduint32(s
->pktout
, 0);
9147 ssh2_pkt_send(ssh
, s
->pktout
);
9149 crWaitUntilV(pktin
);
9150 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
9151 bombout(("Server refused to open a direct-tcpip channel"));
9153 /* FIXME: error data comes back in FAILURE packet */
9155 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
9156 bombout(("Server's channel confirmation cited wrong channel"));
9159 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
9160 ssh
->mainchan
->halfopen
= FALSE
;
9161 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
9162 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
9163 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
9164 add234(ssh
->channels
, ssh
->mainchan
);
9165 update_specials_menu(ssh
->frontend
);
9166 logevent("Opened direct-tcpip channel");
9169 ssh
->mainchan
= snew(struct ssh_channel
);
9170 ssh
->mainchan
->ssh
= ssh
;
9171 ssh2_channel_init(ssh
->mainchan
);
9172 s
->pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
9173 ssh2_pkt_addstring(s
->pktout
, "session");
9174 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->localid
);
9175 ssh2_pkt_adduint32(s
->pktout
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
9176 ssh2_pkt_adduint32(s
->pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
9177 ssh2_pkt_send(ssh
, s
->pktout
);
9178 crWaitUntilV(pktin
);
9179 if (pktin
->type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
9180 bombout(("Server refused to open a session"));
9182 /* FIXME: error data comes back in FAILURE packet */
9184 if (ssh_pkt_getuint32(pktin
) != ssh
->mainchan
->localid
) {
9185 bombout(("Server's channel confirmation cited wrong channel"));
9188 ssh
->mainchan
->remoteid
= ssh_pkt_getuint32(pktin
);
9189 ssh
->mainchan
->halfopen
= FALSE
;
9190 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
9191 ssh
->mainchan
->v
.v2
.remwindow
= ssh_pkt_getuint32(pktin
);
9192 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh_pkt_getuint32(pktin
);
9193 add234(ssh
->channels
, ssh
->mainchan
);
9194 update_specials_menu(ssh
->frontend
);
9195 logevent("Opened channel for session");
9196 ssh
->ncmode
= FALSE
;
9200 * Now we have a channel, make dispatch table entries for
9201 * general channel-based messages.
9203 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] =
9204 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] =
9205 ssh2_msg_channel_data
;
9206 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_channel_eof
;
9207 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_channel_close
;
9208 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] =
9209 ssh2_msg_channel_open_confirmation
;
9210 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] =
9211 ssh2_msg_channel_open_failure
;
9212 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] =
9213 ssh2_msg_channel_request
;
9214 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] =
9215 ssh2_msg_channel_open
;
9216 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = ssh2_msg_channel_response
;
9217 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = ssh2_msg_channel_response
;
9220 if (ssh
->mainchan
&& conf_get_int(ssh
->conf
, CONF_ssh_simple
)) {
9222 * This message indicates to the server that we promise
9223 * not to try to run any other channel in parallel with
9224 * this one, so it's safe for it to advertise a very large
9225 * window and leave the flow control to TCP.
9227 s
->pktout
= ssh2_chanreq_init(ssh
->mainchan
,
9228 "simple@putty.projects.tartarus.org",
9230 ssh2_pkt_send(ssh
, s
->pktout
);
9234 * Enable port forwardings.
9236 ssh_setup_portfwd(ssh
, ssh
->conf
);
9239 * Send the CHANNEL_REQUESTS for the main channel. Each one is
9240 * handled by its own little asynchronous co-routine.
9244 * Potentially enable X11 forwarding.
9246 ssh2_maybe_setup_x11(ssh
->mainchan
, NULL
, NULL
);
9249 * Potentially enable agent forwarding.
9251 ssh2_maybe_setup_agent(ssh
->mainchan
, NULL
, NULL
);
9254 * Now allocate a pty for the session.
9256 ssh2_maybe_setup_pty(ssh
->mainchan
, NULL
, NULL
);
9259 * Send environment variables.
9261 ssh2_setup_env(ssh
->mainchan
, NULL
, NULL
);
9264 * Start a shell or a remote command. We may have to attempt
9265 * this twice if the config data has provided a second choice
9268 if (ssh
->mainchan
&& !ssh
->ncmode
) while (1) {
9272 if (ssh
->fallback_cmd
) {
9273 subsys
= conf_get_int(ssh
->conf
, CONF_ssh_subsys2
);
9274 cmd
= conf_get_str(ssh
->conf
, CONF_remote_cmd2
);
9276 subsys
= conf_get_int(ssh
->conf
, CONF_ssh_subsys
);
9277 cmd
= conf_get_str(ssh
->conf
, CONF_remote_cmd
);
9281 s
->pktout
= ssh2_chanreq_init(ssh
->mainchan
, "subsystem",
9282 ssh2_response_authconn
, NULL
);
9283 ssh2_pkt_addstring(s
->pktout
, cmd
);
9285 s
->pktout
= ssh2_chanreq_init(ssh
->mainchan
, "exec",
9286 ssh2_response_authconn
, NULL
);
9287 ssh2_pkt_addstring(s
->pktout
, cmd
);
9289 s
->pktout
= ssh2_chanreq_init(ssh
->mainchan
, "shell",
9290 ssh2_response_authconn
, NULL
);
9292 ssh2_pkt_send(ssh
, s
->pktout
);
9294 crWaitUntilV(pktin
);
9296 if (pktin
->type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
9297 if (pktin
->type
!= SSH2_MSG_CHANNEL_FAILURE
) {
9298 bombout(("Unexpected response to shell/command request:"
9299 " packet type %d", pktin
->type
));
9303 * We failed to start the command. If this is the
9304 * fallback command, we really are finished; if it's
9305 * not, and if the fallback command exists, try falling
9306 * back to it before complaining.
9308 if (!ssh
->fallback_cmd
&&
9309 *conf_get_str(ssh
->conf
, CONF_remote_cmd2
)) {
9310 logevent("Primary command failed; attempting fallback");
9311 ssh
->fallback_cmd
= TRUE
;
9314 bombout(("Server refused to start a shell/command"));
9317 logevent("Started a shell/command");
9322 ssh
->state
= SSH_STATE_SESSION
;
9323 if (ssh
->size_needed
)
9324 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
9325 if (ssh
->eof_needed
)
9326 ssh_special(ssh
, TS_EOF
);
9329 * All the initial channel requests are done, so install the default
9332 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = ssh2_msg_channel_response
;
9333 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = ssh2_msg_channel_response
;
9339 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
9344 s
->try_send
= FALSE
;
9348 * _All_ the connection-layer packets we expect to
9349 * receive are now handled by the dispatch table.
9350 * Anything that reaches here must be bogus.
9353 bombout(("Strange packet received: type %d", pktin
->type
));
9355 } else if (ssh
->mainchan
) {
9357 * We have spare data. Add it to the channel buffer.
9359 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
9364 struct ssh_channel
*c
;
9366 * Try to send data on all channels if we can.
9368 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++)
9369 ssh2_try_send_and_unthrottle(ssh
, c
);
9377 * Handlers for SSH-2 messages that might arrive at any moment.
9379 static void ssh2_msg_disconnect(Ssh ssh
, struct Packet
*pktin
)
9381 /* log reason code in disconnect message */
9385 reason
= ssh_pkt_getuint32(pktin
);
9386 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
9388 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
9389 buf
= dupprintf("Received disconnect message (%s)",
9390 ssh2_disconnect_reasons
[reason
]);
9392 buf
= dupprintf("Received disconnect message (unknown"
9393 " type %d)", reason
);
9397 buf
= dupprintf("Disconnection message text: %.*s",
9400 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9402 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
9403 ssh2_disconnect_reasons
[reason
] : "unknown",
9408 static void ssh2_msg_debug(Ssh ssh
, struct Packet
*pktin
)
9410 /* log the debug message */
9414 /* XXX maybe we should actually take notice of the return value */
9415 ssh2_pkt_getbool(pktin
);
9416 ssh_pkt_getstring(pktin
, &msg
, &msglen
);
9418 logeventf(ssh
, "Remote debug message: %.*s", msglen
, msg
);
9421 static void ssh2_msg_transport(Ssh ssh
, struct Packet
*pktin
)
9423 do_ssh2_transport(ssh
, NULL
, 0, pktin
);
9427 * Called if we receive a packet that isn't allowed by the protocol.
9428 * This only applies to packets whose meaning PuTTY understands.
9429 * Entirely unknown packets are handled below.
9431 static void ssh2_msg_unexpected(Ssh ssh
, struct Packet
*pktin
)
9433 char *buf
= dupprintf("Server protocol violation: unexpected %s packet",
9434 ssh2_pkt_type(ssh
->pkt_kctx
, ssh
->pkt_actx
,
9436 ssh_disconnect(ssh
, NULL
, buf
, SSH2_DISCONNECT_PROTOCOL_ERROR
, FALSE
);
9440 static void ssh2_msg_something_unimplemented(Ssh ssh
, struct Packet
*pktin
)
9442 struct Packet
*pktout
;
9443 pktout
= ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
9444 ssh2_pkt_adduint32(pktout
, pktin
->sequence
);
9446 * UNIMPLEMENTED messages MUST appear in the same order as the
9447 * messages they respond to. Hence, never queue them.
9449 ssh2_pkt_send_noqueue(ssh
, pktout
);
9453 * Handle the top-level SSH-2 protocol.
9455 static void ssh2_protocol_setup(Ssh ssh
)
9460 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9462 for (i
= 0; i
< 256; i
++)
9463 ssh
->packet_dispatch
[i
] = ssh2_msg_something_unimplemented
;
9466 * Initially, we only accept transport messages (and a few generic
9467 * ones). do_ssh2_authconn will add more when it starts.
9468 * Messages that are understood but not currently acceptable go to
9469 * ssh2_msg_unexpected.
9471 ssh
->packet_dispatch
[SSH2_MSG_UNIMPLEMENTED
] = ssh2_msg_unexpected
;
9472 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_REQUEST
] = ssh2_msg_unexpected
;
9473 ssh
->packet_dispatch
[SSH2_MSG_SERVICE_ACCEPT
] = ssh2_msg_unexpected
;
9474 ssh
->packet_dispatch
[SSH2_MSG_KEXINIT
] = ssh2_msg_transport
;
9475 ssh
->packet_dispatch
[SSH2_MSG_NEWKEYS
] = ssh2_msg_transport
;
9476 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_INIT
] = ssh2_msg_transport
;
9477 ssh
->packet_dispatch
[SSH2_MSG_KEXDH_REPLY
] = ssh2_msg_transport
;
9478 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9479 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9480 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_INIT
] = ssh2_msg_transport
;
9481 ssh
->packet_dispatch
[SSH2_MSG_KEX_DH_GEX_REPLY
] = ssh2_msg_transport
;
9482 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_REQUEST
] = ssh2_msg_unexpected
;
9483 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_FAILURE
] = ssh2_msg_unexpected
;
9484 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_SUCCESS
] = ssh2_msg_unexpected
;
9485 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_BANNER
] = ssh2_msg_unexpected
;
9486 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_PK_OK
] = ssh2_msg_unexpected
;
9487 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9488 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9489 ssh
->packet_dispatch
[SSH2_MSG_USERAUTH_INFO_RESPONSE
] = ssh2_msg_unexpected
;
9490 ssh
->packet_dispatch
[SSH2_MSG_GLOBAL_REQUEST
] = ssh2_msg_unexpected
;
9491 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_SUCCESS
] = ssh2_msg_unexpected
;
9492 ssh
->packet_dispatch
[SSH2_MSG_REQUEST_FAILURE
] = ssh2_msg_unexpected
;
9493 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN
] = ssh2_msg_unexpected
;
9494 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
] = ssh2_msg_unexpected
;
9495 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_OPEN_FAILURE
] = ssh2_msg_unexpected
;
9496 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_WINDOW_ADJUST
] = ssh2_msg_unexpected
;
9497 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_DATA
] = ssh2_msg_unexpected
;
9498 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EXTENDED_DATA
] = ssh2_msg_unexpected
;
9499 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_EOF
] = ssh2_msg_unexpected
;
9500 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_CLOSE
] = ssh2_msg_unexpected
;
9501 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_REQUEST
] = ssh2_msg_unexpected
;
9502 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_SUCCESS
] = ssh2_msg_unexpected
;
9503 ssh
->packet_dispatch
[SSH2_MSG_CHANNEL_FAILURE
] = ssh2_msg_unexpected
;
9506 * These messages have a special handler from the start.
9508 ssh
->packet_dispatch
[SSH2_MSG_DISCONNECT
] = ssh2_msg_disconnect
;
9509 ssh
->packet_dispatch
[SSH2_MSG_IGNORE
] = ssh_msg_ignore
; /* shared with SSH-1 */
9510 ssh
->packet_dispatch
[SSH2_MSG_DEBUG
] = ssh2_msg_debug
;
9513 static void ssh2_timer(void *ctx
, long now
)
9517 if (ssh
->state
== SSH_STATE_CLOSED
)
9520 if (!ssh
->kex_in_progress
&& conf_get_int(ssh
->conf
, CONF_ssh_rekey_time
) != 0 &&
9521 now
- ssh
->next_rekey
>= 0) {
9522 do_ssh2_transport(ssh
, "timeout", -1, NULL
);
9526 static void ssh2_protocol(Ssh ssh
, void *vin
, int inlen
,
9527 struct Packet
*pktin
)
9529 unsigned char *in
= (unsigned char *)vin
;
9530 if (ssh
->state
== SSH_STATE_CLOSED
)
9534 ssh
->incoming_data_size
+= pktin
->encrypted_len
;
9535 if (!ssh
->kex_in_progress
&&
9536 ssh
->max_data_size
!= 0 &&
9537 ssh
->incoming_data_size
> ssh
->max_data_size
)
9538 do_ssh2_transport(ssh
, "too much data received", -1, NULL
);
9542 ssh
->packet_dispatch
[pktin
->type
](ssh
, pktin
);
9543 else if (!ssh
->protocol_initial_phase_done
)
9544 do_ssh2_transport(ssh
, in
, inlen
, pktin
);
9546 do_ssh2_authconn(ssh
, in
, inlen
, pktin
);
9549 static void ssh_cache_conf_values(Ssh ssh
)
9551 ssh
->logomitdata
= conf_get_int(ssh
->conf
, CONF_logomitdata
);
9555 * Called to set up the connection.
9557 * Returns an error message, or NULL on success.
9559 static const char *ssh_init(void *frontend_handle
, void **backend_handle
,
9560 Conf
*conf
, char *host
, int port
, char **realhost
,
9561 int nodelay
, int keepalive
)
9566 ssh
= snew(struct ssh_tag
);
9567 ssh
->conf
= conf_copy(conf
);
9568 ssh_cache_conf_values(ssh
);
9569 ssh
->version
= 0; /* when not ready yet */
9572 ssh
->v1_cipher_ctx
= NULL
;
9573 ssh
->crcda_ctx
= NULL
;
9574 ssh
->cscipher
= NULL
;
9575 ssh
->cs_cipher_ctx
= NULL
;
9576 ssh
->sccipher
= NULL
;
9577 ssh
->sc_cipher_ctx
= NULL
;
9579 ssh
->cs_mac_ctx
= NULL
;
9581 ssh
->sc_mac_ctx
= NULL
;
9583 ssh
->cs_comp_ctx
= NULL
;
9585 ssh
->sc_comp_ctx
= NULL
;
9587 ssh
->kex_ctx
= NULL
;
9588 ssh
->hostkey
= NULL
;
9590 ssh
->close_expected
= FALSE
;
9591 ssh
->clean_exit
= FALSE
;
9592 ssh
->state
= SSH_STATE_PREPACKET
;
9593 ssh
->size_needed
= FALSE
;
9594 ssh
->eof_needed
= FALSE
;
9597 ssh
->deferred_send_data
= NULL
;
9598 ssh
->deferred_len
= 0;
9599 ssh
->deferred_size
= 0;
9600 ssh
->fallback_cmd
= 0;
9601 ssh
->pkt_kctx
= SSH2_PKTCTX_NOKEX
;
9602 ssh
->pkt_actx
= SSH2_PKTCTX_NOAUTH
;
9603 ssh
->x11disp
= NULL
;
9604 ssh
->v1_compressing
= FALSE
;
9605 ssh
->v2_outgoing_sequence
= 0;
9606 ssh
->ssh1_rdpkt_crstate
= 0;
9607 ssh
->ssh2_rdpkt_crstate
= 0;
9608 ssh
->ssh_gotdata_crstate
= 0;
9609 ssh
->do_ssh1_connection_crstate
= 0;
9610 ssh
->do_ssh_init_state
= NULL
;
9611 ssh
->do_ssh1_login_state
= NULL
;
9612 ssh
->do_ssh2_transport_state
= NULL
;
9613 ssh
->do_ssh2_authconn_state
= NULL
;
9616 ssh
->mainchan
= NULL
;
9617 ssh
->throttled_all
= 0;
9618 ssh
->v1_stdout_throttling
= 0;
9620 ssh
->queuelen
= ssh
->queuesize
= 0;
9621 ssh
->queueing
= FALSE
;
9622 ssh
->qhead
= ssh
->qtail
= NULL
;
9623 ssh
->deferred_rekey_reason
= NULL
;
9624 bufchain_init(&ssh
->queued_incoming_data
);
9625 ssh
->frozen
= FALSE
;
9626 ssh
->username
= NULL
;
9627 ssh
->sent_console_eof
= FALSE
;
9628 ssh
->got_pty
= FALSE
;
9630 *backend_handle
= ssh
;
9633 if (crypto_startup() == 0)
9634 return "Microsoft high encryption pack not installed!";
9637 ssh
->frontend
= frontend_handle
;
9638 ssh
->term_width
= conf_get_int(ssh
->conf
, CONF_width
);
9639 ssh
->term_height
= conf_get_int(ssh
->conf
, CONF_height
);
9641 ssh
->channels
= NULL
;
9642 ssh
->rportfwds
= NULL
;
9643 ssh
->portfwds
= NULL
;
9648 ssh
->conn_throttle_count
= 0;
9649 ssh
->overall_bufsize
= 0;
9650 ssh
->fallback_cmd
= 0;
9652 ssh
->protocol
= NULL
;
9654 ssh
->protocol_initial_phase_done
= FALSE
;
9658 ssh
->incoming_data_size
= ssh
->outgoing_data_size
=
9659 ssh
->deferred_data_size
= 0L;
9660 ssh
->max_data_size
= parse_blocksize(conf_get_str(ssh
->conf
,
9661 CONF_ssh_rekey_data
));
9662 ssh
->kex_in_progress
= FALSE
;
9665 ssh
->gsslibs
= NULL
;
9668 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
, keepalive
);
9677 static void ssh_free(void *handle
)
9679 Ssh ssh
= (Ssh
) handle
;
9680 struct ssh_channel
*c
;
9681 struct ssh_rportfwd
*pf
;
9683 if (ssh
->v1_cipher_ctx
)
9684 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
9685 if (ssh
->cs_cipher_ctx
)
9686 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
9687 if (ssh
->sc_cipher_ctx
)
9688 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
9689 if (ssh
->cs_mac_ctx
)
9690 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
9691 if (ssh
->sc_mac_ctx
)
9692 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
9693 if (ssh
->cs_comp_ctx
) {
9695 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
9697 zlib_compress_cleanup(ssh
->cs_comp_ctx
);
9699 if (ssh
->sc_comp_ctx
) {
9701 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
9703 zlib_decompress_cleanup(ssh
->sc_comp_ctx
);
9706 dh_cleanup(ssh
->kex_ctx
);
9707 sfree(ssh
->savedhost
);
9709 while (ssh
->queuelen
-- > 0)
9710 ssh_free_packet(ssh
->queue
[ssh
->queuelen
]);
9713 while (ssh
->qhead
) {
9714 struct queued_handler
*qh
= ssh
->qhead
;
9715 ssh
->qhead
= qh
->next
;
9718 ssh
->qhead
= ssh
->qtail
= NULL
;
9720 if (ssh
->channels
) {
9721 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
9724 if (c
->u
.x11
.s
!= NULL
)
9725 x11_close(c
->u
.x11
.s
);
9728 case CHAN_SOCKDATA_DORMANT
:
9729 if (c
->u
.pfd
.s
!= NULL
)
9730 pfd_close(c
->u
.pfd
.s
);
9733 if (ssh
->version
== 2) {
9734 struct outstanding_channel_request
*ocr
, *nocr
;
9735 ocr
= c
->v
.v2
.chanreq_head
;
9737 ocr
->handler(c
, NULL
, ocr
->ctx
);
9742 bufchain_clear(&c
->v
.v2
.outbuffer
);
9746 freetree234(ssh
->channels
);
9747 ssh
->channels
= NULL
;
9750 if (ssh
->rportfwds
) {
9751 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
9753 freetree234(ssh
->rportfwds
);
9754 ssh
->rportfwds
= NULL
;
9756 sfree(ssh
->deferred_send_data
);
9758 x11_free_display(ssh
->x11disp
);
9759 sfree(ssh
->do_ssh_init_state
);
9760 sfree(ssh
->do_ssh1_login_state
);
9761 sfree(ssh
->do_ssh2_transport_state
);
9762 sfree(ssh
->do_ssh2_authconn_state
);
9765 sfree(ssh
->fullhostname
);
9766 if (ssh
->crcda_ctx
) {
9767 crcda_free_context(ssh
->crcda_ctx
);
9768 ssh
->crcda_ctx
= NULL
;
9771 ssh_do_close(ssh
, TRUE
);
9772 expire_timer_context(ssh
);
9774 pinger_free(ssh
->pinger
);
9775 bufchain_clear(&ssh
->queued_incoming_data
);
9776 sfree(ssh
->username
);
9777 conf_free(ssh
->conf
);
9780 ssh_gss_cleanup(ssh
->gsslibs
);
9788 * Reconfigure the SSH backend.
9790 static void ssh_reconfig(void *handle
, Conf
*conf
)
9792 Ssh ssh
= (Ssh
) handle
;
9793 char *rekeying
= NULL
, rekey_mandatory
= FALSE
;
9794 unsigned long old_max_data_size
;
9797 pinger_reconfig(ssh
->pinger
, ssh
->conf
, conf
);
9799 ssh_setup_portfwd(ssh
, conf
);
9801 rekey_time
= conf_get_int(conf
, CONF_ssh_rekey_time
);
9802 if (conf_get_int(ssh
->conf
, CONF_ssh_rekey_time
) != rekey_time
&&
9804 long new_next
= ssh
->last_rekey
+ rekey_time
*60*TICKSPERSEC
;
9805 long now
= GETTICKCOUNT();
9807 if (new_next
- now
< 0) {
9808 rekeying
= "timeout shortened";
9810 ssh
->next_rekey
= schedule_timer(new_next
- now
, ssh2_timer
, ssh
);
9814 old_max_data_size
= ssh
->max_data_size
;
9815 ssh
->max_data_size
= parse_blocksize(conf_get_str(ssh
->conf
,
9816 CONF_ssh_rekey_data
));
9817 if (old_max_data_size
!= ssh
->max_data_size
&&
9818 ssh
->max_data_size
!= 0) {
9819 if (ssh
->outgoing_data_size
> ssh
->max_data_size
||
9820 ssh
->incoming_data_size
> ssh
->max_data_size
)
9821 rekeying
= "data limit lowered";
9824 if (conf_get_int(ssh
->conf
, CONF_compression
) !=
9825 conf_get_int(conf
, CONF_compression
)) {
9826 rekeying
= "compression setting changed";
9827 rekey_mandatory
= TRUE
;
9830 for (i
= 0; i
< CIPHER_MAX
; i
++)
9831 if (conf_get_int_int(ssh
->conf
, CONF_ssh_cipherlist
, i
) !=
9832 conf_get_int_int(conf
, CONF_ssh_cipherlist
, i
)) {
9833 rekeying
= "cipher settings changed";
9834 rekey_mandatory
= TRUE
;
9836 if (conf_get_int(ssh
->conf
, CONF_ssh2_des_cbc
) !=
9837 conf_get_int(conf
, CONF_ssh2_des_cbc
)) {
9838 rekeying
= "cipher settings changed";
9839 rekey_mandatory
= TRUE
;
9842 conf_free(ssh
->conf
);
9843 ssh
->conf
= conf_copy(conf
);
9844 ssh_cache_conf_values(ssh
);
9847 if (!ssh
->kex_in_progress
) {
9848 do_ssh2_transport(ssh
, rekeying
, -1, NULL
);
9849 } else if (rekey_mandatory
) {
9850 ssh
->deferred_rekey_reason
= rekeying
;
9856 * Called to send data down the SSH connection.
9858 static int ssh_send(void *handle
, char *buf
, int len
)
9860 Ssh ssh
= (Ssh
) handle
;
9862 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
9865 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
9867 return ssh_sendbuffer(ssh
);
9871 * Called to query the current amount of buffered stdin data.
9873 static int ssh_sendbuffer(void *handle
)
9875 Ssh ssh
= (Ssh
) handle
;
9878 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
9882 * If the SSH socket itself has backed up, add the total backup
9883 * size on that to any individual buffer on the stdin channel.
9886 if (ssh
->throttled_all
)
9887 override_value
= ssh
->overall_bufsize
;
9889 if (ssh
->version
== 1) {
9890 return override_value
;
9891 } else if (ssh
->version
== 2) {
9893 return override_value
;
9895 return (override_value
+
9896 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
9903 * Called to set the size of the window from SSH's POV.
9905 static void ssh_size(void *handle
, int width
, int height
)
9907 Ssh ssh
= (Ssh
) handle
;
9908 struct Packet
*pktout
;
9910 ssh
->term_width
= width
;
9911 ssh
->term_height
= height
;
9913 switch (ssh
->state
) {
9914 case SSH_STATE_BEFORE_SIZE
:
9915 case SSH_STATE_PREPACKET
:
9916 case SSH_STATE_CLOSED
:
9917 break; /* do nothing */
9918 case SSH_STATE_INTERMED
:
9919 ssh
->size_needed
= TRUE
; /* buffer for later */
9921 case SSH_STATE_SESSION
:
9922 if (!conf_get_int(ssh
->conf
, CONF_nopty
)) {
9923 if (ssh
->version
== 1) {
9924 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
9925 PKT_INT
, ssh
->term_height
,
9926 PKT_INT
, ssh
->term_width
,
9927 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
9928 } else if (ssh
->mainchan
) {
9929 pktout
= ssh2_chanreq_init(ssh
->mainchan
, "window-change",
9931 ssh2_pkt_adduint32(pktout
, ssh
->term_width
);
9932 ssh2_pkt_adduint32(pktout
, ssh
->term_height
);
9933 ssh2_pkt_adduint32(pktout
, 0);
9934 ssh2_pkt_adduint32(pktout
, 0);
9935 ssh2_pkt_send(ssh
, pktout
);
9943 * Return a list of the special codes that make sense in this
9946 static const struct telnet_special
*ssh_get_specials(void *handle
)
9948 static const struct telnet_special ssh1_ignore_special
[] = {
9949 {"IGNORE message", TS_NOP
}
9951 static const struct telnet_special ssh2_ignore_special
[] = {
9952 {"IGNORE message", TS_NOP
},
9954 static const struct telnet_special ssh2_rekey_special
[] = {
9955 {"Repeat key exchange", TS_REKEY
},
9957 static const struct telnet_special ssh2_session_specials
[] = {
9960 /* These are the signal names defined by RFC 4254.
9961 * They include all the ISO C signals, but are a subset of the POSIX
9962 * required signals. */
9963 {"SIGINT (Interrupt)", TS_SIGINT
},
9964 {"SIGTERM (Terminate)", TS_SIGTERM
},
9965 {"SIGKILL (Kill)", TS_SIGKILL
},
9966 {"SIGQUIT (Quit)", TS_SIGQUIT
},
9967 {"SIGHUP (Hangup)", TS_SIGHUP
},
9968 {"More signals", TS_SUBMENU
},
9969 {"SIGABRT", TS_SIGABRT
}, {"SIGALRM", TS_SIGALRM
},
9970 {"SIGFPE", TS_SIGFPE
}, {"SIGILL", TS_SIGILL
},
9971 {"SIGPIPE", TS_SIGPIPE
}, {"SIGSEGV", TS_SIGSEGV
},
9972 {"SIGUSR1", TS_SIGUSR1
}, {"SIGUSR2", TS_SIGUSR2
},
9975 static const struct telnet_special specials_end
[] = {
9978 /* XXX review this length for any changes: */
9979 static struct telnet_special ssh_specials
[lenof(ssh2_ignore_special
) +
9980 lenof(ssh2_rekey_special
) +
9981 lenof(ssh2_session_specials
) +
9982 lenof(specials_end
)];
9983 Ssh ssh
= (Ssh
) handle
;
9985 #define ADD_SPECIALS(name) \
9987 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9988 memcpy(&ssh_specials[i], name, sizeof name); \
9992 if (ssh
->version
== 1) {
9993 /* Don't bother offering IGNORE if we've decided the remote
9994 * won't cope with it, since we wouldn't bother sending it if
9996 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
9997 ADD_SPECIALS(ssh1_ignore_special
);
9998 } else if (ssh
->version
== 2) {
9999 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
))
10000 ADD_SPECIALS(ssh2_ignore_special
);
10001 if (!(ssh
->remote_bugs
& BUG_SSH2_REKEY
))
10002 ADD_SPECIALS(ssh2_rekey_special
);
10004 ADD_SPECIALS(ssh2_session_specials
);
10005 } /* else we're not ready yet */
10008 ADD_SPECIALS(specials_end
);
10009 return ssh_specials
;
10013 #undef ADD_SPECIALS
10017 * Send special codes. TS_EOF is useful for `plink', so you
10018 * can send an EOF and collect resulting output (e.g. `plink
10021 static void ssh_special(void *handle
, Telnet_Special code
)
10023 Ssh ssh
= (Ssh
) handle
;
10024 struct Packet
*pktout
;
10026 if (code
== TS_EOF
) {
10027 if (ssh
->state
!= SSH_STATE_SESSION
) {
10029 * Buffer the EOF in case we are pre-SESSION, so we can
10030 * send it as soon as we reach SESSION.
10032 if (code
== TS_EOF
)
10033 ssh
->eof_needed
= TRUE
;
10036 if (ssh
->version
== 1) {
10037 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
10038 } else if (ssh
->mainchan
) {
10039 sshfwd_write_eof(ssh
->mainchan
);
10040 ssh
->send_ok
= 0; /* now stop trying to read from stdin */
10042 logevent("Sent EOF message");
10043 } else if (code
== TS_PING
|| code
== TS_NOP
) {
10044 if (ssh
->state
== SSH_STATE_CLOSED
10045 || ssh
->state
== SSH_STATE_PREPACKET
) return;
10046 if (ssh
->version
== 1) {
10047 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
10048 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
10050 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH2_IGNORE
)) {
10051 pktout
= ssh2_pkt_init(SSH2_MSG_IGNORE
);
10052 ssh2_pkt_addstring_start(pktout
);
10053 ssh2_pkt_send_noqueue(ssh
, pktout
);
10056 } else if (code
== TS_REKEY
) {
10057 if (!ssh
->kex_in_progress
&& ssh
->version
== 2) {
10058 do_ssh2_transport(ssh
, "at user request", -1, NULL
);
10060 } else if (code
== TS_BRK
) {
10061 if (ssh
->state
== SSH_STATE_CLOSED
10062 || ssh
->state
== SSH_STATE_PREPACKET
) return;
10063 if (ssh
->version
== 1) {
10064 logevent("Unable to send BREAK signal in SSH-1");
10065 } else if (ssh
->mainchan
) {
10066 pktout
= ssh2_chanreq_init(ssh
->mainchan
, "break", NULL
, NULL
);
10067 ssh2_pkt_adduint32(pktout
, 0); /* default break length */
10068 ssh2_pkt_send(ssh
, pktout
);
10071 /* Is is a POSIX signal? */
10072 char *signame
= NULL
;
10073 if (code
== TS_SIGABRT
) signame
= "ABRT";
10074 if (code
== TS_SIGALRM
) signame
= "ALRM";
10075 if (code
== TS_SIGFPE
) signame
= "FPE";
10076 if (code
== TS_SIGHUP
) signame
= "HUP";
10077 if (code
== TS_SIGILL
) signame
= "ILL";
10078 if (code
== TS_SIGINT
) signame
= "INT";
10079 if (code
== TS_SIGKILL
) signame
= "KILL";
10080 if (code
== TS_SIGPIPE
) signame
= "PIPE";
10081 if (code
== TS_SIGQUIT
) signame
= "QUIT";
10082 if (code
== TS_SIGSEGV
) signame
= "SEGV";
10083 if (code
== TS_SIGTERM
) signame
= "TERM";
10084 if (code
== TS_SIGUSR1
) signame
= "USR1";
10085 if (code
== TS_SIGUSR2
) signame
= "USR2";
10086 /* The SSH-2 protocol does in principle support arbitrary named
10087 * signals, including signame@domain, but we don't support those. */
10089 /* It's a signal. */
10090 if (ssh
->version
== 2 && ssh
->mainchan
) {
10091 pktout
= ssh2_chanreq_init(ssh
->mainchan
, "signal", NULL
, NULL
);
10092 ssh2_pkt_addstring(pktout
, signame
);
10093 ssh2_pkt_send(ssh
, pktout
);
10094 logeventf(ssh
, "Sent signal SIG%s", signame
);
10097 /* Never heard of it. Do nothing */
10102 void *new_sock_channel(void *handle
, Socket s
)
10104 Ssh ssh
= (Ssh
) handle
;
10105 struct ssh_channel
*c
;
10106 c
= snew(struct ssh_channel
);
10109 ssh2_channel_init(c
);
10110 c
->halfopen
= TRUE
;
10111 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
10113 add234(ssh
->channels
, c
);
10118 * This is called when stdout/stderr (the entity to which
10119 * from_backend sends data) manages to clear some backlog.
10121 static void ssh_unthrottle(void *handle
, int bufsize
)
10123 Ssh ssh
= (Ssh
) handle
;
10126 if (ssh
->version
== 1) {
10127 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
10128 ssh
->v1_stdout_throttling
= 0;
10129 ssh_throttle_conn(ssh
, -1);
10132 if (ssh
->mainchan
) {
10133 ssh2_set_window(ssh
->mainchan
,
10134 bufsize
< ssh
->mainchan
->v
.v2
.locmaxwin ?
10135 ssh
->mainchan
->v
.v2
.locmaxwin
- bufsize
: 0);
10136 if (conf_get_int(ssh
->conf
, CONF_ssh_simple
))
10139 buflimit
= ssh
->mainchan
->v
.v2
.locmaxwin
;
10140 if (ssh
->mainchan
->throttling_conn
&& bufsize
<= buflimit
) {
10141 ssh
->mainchan
->throttling_conn
= 0;
10142 ssh_throttle_conn(ssh
, -1);
10148 * Now process any SSH connection data that was stashed in our
10149 * queue while we were frozen.
10151 ssh_process_queued_incoming_data(ssh
);
10154 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
10156 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
10158 struct Packet
*pktout
;
10160 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
10162 if (ssh
->version
== 1) {
10163 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
10164 PKT_INT
, c
->localid
,
10167 /* PKT_STR, <org:orgport>, */
10170 pktout
= ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
10171 ssh2_pkt_addstring(pktout
, "direct-tcpip");
10172 ssh2_pkt_adduint32(pktout
, c
->localid
);
10173 ssh2_pkt_adduint32(pktout
, c
->v
.v2
.locwindow
);/* our window size */
10174 ssh2_pkt_adduint32(pktout
, OUR_V2_MAXPKT
); /* our max pkt size */
10175 ssh2_pkt_addstring(pktout
, hostname
);
10176 ssh2_pkt_adduint32(pktout
, port
);
10178 * We make up values for the originator data; partly it's
10179 * too much hassle to keep track, and partly I'm not
10180 * convinced the server should be told details like that
10181 * about my local network configuration.
10182 * The "originator IP address" is syntactically a numeric
10183 * IP address, and some servers (e.g., Tectia) get upset
10184 * if it doesn't match this syntax.
10186 ssh2_pkt_addstring(pktout
, "0.0.0.0");
10187 ssh2_pkt_adduint32(pktout
, 0);
10188 ssh2_pkt_send(ssh
, pktout
);
10192 static int ssh_connected(void *handle
)
10194 Ssh ssh
= (Ssh
) handle
;
10195 return ssh
->s
!= NULL
;
10198 static int ssh_sendok(void *handle
)
10200 Ssh ssh
= (Ssh
) handle
;
10201 return ssh
->send_ok
;
10204 static int ssh_ldisc(void *handle
, int option
)
10206 Ssh ssh
= (Ssh
) handle
;
10207 if (option
== LD_ECHO
)
10208 return ssh
->echoing
;
10209 if (option
== LD_EDIT
)
10210 return ssh
->editing
;
10214 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
10216 Ssh ssh
= (Ssh
) handle
;
10217 ssh
->ldisc
= ldisc
;
10220 static void ssh_provide_logctx(void *handle
, void *logctx
)
10222 Ssh ssh
= (Ssh
) handle
;
10223 ssh
->logctx
= logctx
;
10226 static int ssh_return_exitcode(void *handle
)
10228 Ssh ssh
= (Ssh
) handle
;
10229 if (ssh
->s
!= NULL
)
10232 return (ssh
->exitcode
>= 0 ? ssh
->exitcode
: INT_MAX
);
10236 * cfg_info for SSH is the currently running version of the
10237 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10239 static int ssh_cfg_info(void *handle
)
10241 Ssh ssh
= (Ssh
) handle
;
10242 return ssh
->version
;
10246 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10247 * that fails. This variable is the means by which scp.c can reach
10248 * into the SSH code and find out which one it got.
10250 extern int ssh_fallback_cmd(void *handle
)
10252 Ssh ssh
= (Ssh
) handle
;
10253 return ssh
->fallback_cmd
;
10256 Backend ssh_backend
= {
10266 ssh_return_exitcode
,
10270 ssh_provide_logctx
,