18 #define logevent(s) { logevent(s); \
19 if (!(flags & FLAG_CONNECTION) && (flags & FLAG_VERBOSE)) \
20 fprintf(stderr, "%s\n", s); }
22 #define SSH1_MSG_DISCONNECT 1
23 #define SSH1_SMSG_PUBLIC_KEY 2
24 #define SSH1_CMSG_SESSION_KEY 3
25 #define SSH1_CMSG_USER 4
26 #define SSH1_CMSG_AUTH_RSA 6
27 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7
28 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8
29 #define SSH1_CMSG_AUTH_PASSWORD 9
30 #define SSH1_CMSG_REQUEST_PTY 10
31 #define SSH1_CMSG_WINDOW_SIZE 11
32 #define SSH1_CMSG_EXEC_SHELL 12
33 #define SSH1_CMSG_EXEC_CMD 13
34 #define SSH1_SMSG_SUCCESS 14
35 #define SSH1_SMSG_FAILURE 15
36 #define SSH1_CMSG_STDIN_DATA 16
37 #define SSH1_SMSG_STDOUT_DATA 17
38 #define SSH1_SMSG_STDERR_DATA 18
39 #define SSH1_CMSG_EOF 19
40 #define SSH1_SMSG_EXIT_STATUS 20
41 #define SSH1_CMSG_EXIT_CONFIRMATION 33
42 #define SSH1_MSG_IGNORE 32
43 #define SSH1_MSG_DEBUG 36
44 #define SSH1_CMSG_AUTH_TIS 39
45 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40
46 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41
47 #define SSH1_CMSG_AUTH_CCARD 70
48 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71
49 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72
51 #define SSH1_AUTH_TIS 5
52 #define SSH1_AUTH_CCARD 16
54 #define SSH2_MSG_DISCONNECT 1
55 #define SSH2_MSG_IGNORE 2
56 #define SSH2_MSG_UNIMPLEMENTED 3
57 #define SSH2_MSG_DEBUG 4
58 #define SSH2_MSG_SERVICE_REQUEST 5
59 #define SSH2_MSG_SERVICE_ACCEPT 6
60 #define SSH2_MSG_KEXINIT 20
61 #define SSH2_MSG_NEWKEYS 21
62 #define SSH2_MSG_KEXDH_INIT 30
63 #define SSH2_MSG_KEXDH_REPLY 31
64 #define SSH2_MSG_USERAUTH_REQUEST 50
65 #define SSH2_MSG_USERAUTH_FAILURE 51
66 #define SSH2_MSG_USERAUTH_SUCCESS 52
67 #define SSH2_MSG_USERAUTH_BANNER 53
68 #define SSH2_MSG_USERAUTH_PK_OK 60
69 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60
70 #define SSH2_MSG_GLOBAL_REQUEST 80
71 #define SSH2_MSG_REQUEST_SUCCESS 81
72 #define SSH2_MSG_REQUEST_FAILURE 82
73 #define SSH2_MSG_CHANNEL_OPEN 90
74 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91
75 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92
76 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93
77 #define SSH2_MSG_CHANNEL_DATA 94
78 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95
79 #define SSH2_MSG_CHANNEL_EOF 96
80 #define SSH2_MSG_CHANNEL_CLOSE 97
81 #define SSH2_MSG_CHANNEL_REQUEST 98
82 #define SSH2_MSG_CHANNEL_SUCCESS 99
83 #define SSH2_MSG_CHANNEL_FAILURE 100
85 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1
86 #define SSH2_OPEN_CONNECT_FAILED 2
87 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3
88 #define SSH2_OPEN_RESOURCE_SHORTAGE 4
89 #define SSH2_EXTENDED_DATA_STDERR 1
91 #define GET_32BIT(cp) \
92 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
93 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
94 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
95 ((unsigned long)(unsigned char)(cp)[3]))
97 #define PUT_32BIT(cp, value) { \
98 (cp)[0] = (unsigned char)((value) >> 24); \
99 (cp)[1] = (unsigned char)((value) >> 16); \
100 (cp)[2] = (unsigned char)((value) >> 8); \
101 (cp)[3] = (unsigned char)(value); }
103 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
105 /* Coroutine mechanics for the sillier bits of the code */
106 #define crBegin1 static int crLine = 0;
107 #define crBegin2 switch(crLine) { case 0:;
108 #define crBegin crBegin1; crBegin2;
109 #define crFinish(z) } crLine = 0; return (z)
110 #define crFinishV } crLine = 0; return
111 #define crReturn(z) \
113 crLine=__LINE__; return (z); case __LINE__:;\
117 crLine=__LINE__; return; case __LINE__:;\
119 #define crStop(z) do{ crLine = 0; return (z); }while(0)
120 #define crStopV do{ crLine = 0; return; }while(0)
121 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
122 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
124 extern struct ssh_cipher ssh_3des
;
125 extern struct ssh_cipher ssh_3des_ssh2
;
126 extern struct ssh_cipher ssh_des
;
127 extern struct ssh_cipher ssh_blowfish
;
129 /* for ssh 2; we miss out single-DES because it isn't supported */
130 struct ssh_cipher
*ciphers
[] = { &ssh_3des_ssh2
, &ssh_blowfish
};
132 extern struct ssh_kex ssh_diffiehellman
;
133 struct ssh_kex
*kex_algs
[] = { &ssh_diffiehellman
};
135 extern struct ssh_hostkey ssh_dss
;
136 struct ssh_hostkey
*hostkey_algs
[] = { &ssh_dss
};
138 extern struct ssh_mac ssh_sha1
;
142 static void nullmac_key(unsigned char *key
) { }
143 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
144 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
145 struct ssh_mac ssh_mac_none
= {
146 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
148 struct ssh_mac
*macs
[] = { &ssh_sha1
, &ssh_mac_none
};
150 struct ssh_compress ssh_comp_none
= {
153 struct ssh_compress
*compressions
[] = { &ssh_comp_none
};
155 static SOCKET s
= INVALID_SOCKET
;
157 static unsigned char session_key
[32];
158 static struct ssh_cipher
*cipher
= NULL
;
159 static struct ssh_cipher
*cscipher
= NULL
;
160 static struct ssh_cipher
*sccipher
= NULL
;
161 static struct ssh_mac
*csmac
= NULL
;
162 static struct ssh_mac
*scmac
= NULL
;
163 static struct ssh_compress
*cscomp
= NULL
;
164 static struct ssh_compress
*sccomp
= NULL
;
165 static struct ssh_kex
*kex
= NULL
;
166 static struct ssh_hostkey
*hostkey
= NULL
;
167 int (*ssh_get_password
)(const char *prompt
, char *str
, int maxlen
) = NULL
;
169 static char *savedhost
;
170 static int ssh_send_ok
;
173 SSH_STATE_BEFORE_SIZE
,
177 } ssh_state
= SSH_STATE_BEFORE_SIZE
;
179 static int size_needed
= FALSE
;
181 static void s_write (char *buf
, int len
) {
183 int i
= send (s
, buf
, len
, 0);
186 fatalbox("Lost connection while sending");
192 static int s_read (char *buf
, int len
) {
195 int i
= recv (s
, buf
, len
, 0);
198 len
-= i
, buf
+= i
, ret
+= i
;
205 static void c_write (char *buf
, int len
) {
206 if (!(flags
& FLAG_CONNECTION
)) {
208 for (i
= 0; i
< len
; i
++)
210 fputc(buf
[i
], stderr
);
226 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
227 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
229 static int ssh_version
;
230 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
231 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
232 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
233 static void ssh_size(void);
235 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
238 * Collect incoming data in the incoming packet buffer.
239 * Decipher and verify the packet when it is completely read.
240 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
241 * Update the *data and *datalen variables.
242 * Return the additional nr of bytes needed, or 0 when
243 * a complete packet is available.
245 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
247 static long len
, pad
, biglen
, to_read
;
248 static unsigned long realcrc
, gotcrc
;
249 static unsigned char *p
;
259 for (i
= len
= 0; i
< 4; i
++) {
260 while ((*datalen
) == 0)
262 len
= (len
<< 8) + **data
;
263 (*data
)++, (*datalen
)--;
267 if (len
== 0x52656d6f) { /* "Remo"te server has closed ... */
268 len
= 0x300; /* big enough to carry to end */
274 pktin
.length
= len
- 5;
276 if (pktin
.maxlen
< biglen
) {
277 pktin
.maxlen
= biglen
;
278 pktin
.data
= (pktin
.data
== NULL ?
malloc(biglen
+APIEXTRA
) :
279 realloc(pktin
.data
, biglen
+APIEXTRA
));
281 fatalbox("Out of memory");
286 while (to_read
> 0) {
289 while ((*datalen
) == 0)
291 if (chunk
> (*datalen
))
293 memcpy(p
, *data
, chunk
);
301 cipher
->decrypt(pktin
.data
, biglen
);
303 pktin
.type
= pktin
.data
[pad
];
304 pktin
.body
= pktin
.data
+ pad
+ 1;
306 realcrc
= crc32(pktin
.data
, biglen
-4);
307 gotcrc
= GET_32BIT(pktin
.data
+biglen
-4);
308 if (gotcrc
!= realcrc
) {
309 fatalbox("Incorrect CRC received on packet");
312 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
313 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
314 pktin
.type
== SSH1_MSG_DEBUG
||
315 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
316 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
317 long strlen
= GET_32BIT(pktin
.body
);
318 if (strlen
+ 4 != pktin
.length
)
319 fatalbox("Received data packet with bogus string length");
322 if (pktin
.type
== SSH1_MSG_DEBUG
) {
323 /* log debug message */
325 int strlen
= GET_32BIT(pktin
.body
);
326 strcpy(buf
, "Remote: ");
327 if (strlen
> 70) strlen
= 70;
328 memcpy(buf
+8, pktin
.body
+4, strlen
);
329 buf
[8+strlen
] = '\0';
332 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
340 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
342 static long len
, pad
, payload
, packetlen
, maclen
;
344 static int cipherblk
;
345 static unsigned long incoming_sequence
= 0;
355 cipherblk
= cipher
->blksize
;
361 if (pktin
.maxlen
< cipherblk
) {
362 pktin
.maxlen
= cipherblk
;
363 pktin
.data
= (pktin
.data
== NULL ?
malloc(cipherblk
+APIEXTRA
) :
364 realloc(pktin
.data
, cipherblk
+APIEXTRA
));
366 fatalbox("Out of memory");
370 * Acquire and decrypt the first block of the packet. This will
371 * contain the length and padding details.
373 for (i
= len
= 0; i
< cipherblk
; i
++) {
374 while ((*datalen
) == 0)
375 crReturn(cipherblk
-i
);
376 pktin
.data
[i
] = *(*data
)++;
380 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
385 sccipher
->decrypt(pktin
.data
, cipherblk
);
388 * Now get the length and padding figures.
390 len
= GET_32BIT(pktin
.data
);
394 * This enables us to deduce the payload length.
396 payload
= len
- pad
- 1;
398 pktin
.length
= payload
+ 5;
401 * So now we can work out the total packet length.
404 maclen
= scmac ? scmac
->len
: 0;
407 * Adjust memory allocation if packet is too big.
409 if (pktin
.maxlen
< packetlen
) {
410 pktin
.maxlen
= packetlen
;
411 pktin
.data
= (pktin
.data
== NULL ?
malloc(packetlen
+APIEXTRA
) :
412 realloc(pktin
.data
, packetlen
+APIEXTRA
));
414 fatalbox("Out of memory");
418 * Read and decrypt the remainder of the packet.
420 for (i
= cipherblk
; i
< packetlen
+ maclen
; i
++) {
421 while ((*datalen
) == 0)
422 crReturn(packetlen
+ maclen
- i
);
423 pktin
.data
[i
] = *(*data
)++;
426 /* Decrypt everything _except_ the MAC. */
428 sccipher
->decrypt(pktin
.data
+ cipherblk
, packetlen
- cipherblk
);
431 debug(("Got packet len=%d pad=%d\r\n", len
, pad
));
432 for (i
= 0; i
< packetlen
; i
++)
433 debug((" %02x", (unsigned char)pktin
.data
[i
]));
440 if (scmac
&& !scmac
->verify(pktin
.data
, len
+4, incoming_sequence
))
441 fatalbox("Incorrect MAC received on packet");
442 incoming_sequence
++; /* whether or not we MACed */
445 pktin
.type
= pktin
.data
[5];
447 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
448 goto next_packet
; /* FIXME: print DEBUG message */
453 static void ssh_gotdata(unsigned char *data
, int datalen
)
455 while (datalen
> 0) {
456 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
457 ssh_protocol(NULL
, 0, 1);
458 if (ssh_state
== SSH_STATE_CLOSED
) {
466 static void s_wrpkt_start(int type
, int len
) {
469 len
+= 5; /* type and CRC */
473 pktout
.length
= len
-5;
474 if (pktout
.maxlen
< biglen
) {
475 pktout
.maxlen
= biglen
;
477 /* Allocate enough buffer space for extra block
478 * for MS CryptEncrypt() */
479 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+12) :
480 realloc(pktout
.data
, biglen
+12));
482 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+4) :
483 realloc(pktout
.data
, biglen
+4));
486 fatalbox("Out of memory");
490 pktout
.body
= pktout
.data
+4+pad
+1;
493 static void s_wrpkt(void) {
494 int pad
, len
, biglen
, i
;
497 len
= pktout
.length
+ 5; /* type and CRC */
501 pktout
.body
[-1] = pktout
.type
;
502 for (i
=0; i
<pad
; i
++)
503 pktout
.data
[i
+4] = random_byte();
504 crc
= crc32(pktout
.data
+4, biglen
-4);
505 PUT_32BIT(pktout
.data
+biglen
, crc
);
506 PUT_32BIT(pktout
.data
, len
);
509 cipher
->encrypt(pktout
.data
+4, biglen
);
511 s_write(pktout
.data
, biglen
+4);
515 * Construct a packet with the specified contents and
516 * send it to the server.
518 static void send_packet(int pkttype
, ...)
521 unsigned char *p
, *argp
, argchar
;
522 unsigned long argint
;
523 int pktlen
, argtype
, arglen
;
528 va_start(args
, pkttype
);
529 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
532 (void) va_arg(args
, int);
536 (void) va_arg(args
, char);
540 (void) va_arg(args
, unsigned char *);
541 arglen
= va_arg(args
, int);
545 argp
= va_arg(args
, unsigned char *);
546 arglen
= strlen(argp
);
547 pktlen
+= 4 + arglen
;
550 bn
= va_arg(args
, Bignum
);
552 while ( i
> 0 && (bn
[i
/16+1] >> (i
%16)) == 0 )
554 pktlen
+= 2 + (i
+7)/8;
562 s_wrpkt_start(pkttype
, pktlen
);
565 va_start(args
, pkttype
);
566 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
569 argint
= va_arg(args
, int);
570 PUT_32BIT(p
, argint
);
574 argchar
= va_arg(args
, unsigned char);
579 argp
= va_arg(args
, unsigned char *);
580 arglen
= va_arg(args
, int);
581 memcpy(p
, argp
, arglen
);
585 argp
= va_arg(args
, unsigned char *);
586 arglen
= strlen(argp
);
587 PUT_32BIT(p
, arglen
);
588 memcpy(p
+ 4, argp
, arglen
);
592 bn
= va_arg(args
, Bignum
);
594 while ( i
> 0 && (bn
[i
/16+1] >> (i
%16)) == 0 )
596 *p
++ = (i
>> 8) & 0xFF;
601 *p
++ = bn
[i
/2+1] >> 8;
603 *p
++ = bn
[i
/2+1] & 0xFF;
615 * Connect to specified host and port.
616 * Returns an error message, or NULL on success.
617 * Also places the canonical host name into `realhost'.
619 static char *connect_to_host(char *host
, int port
, char **realhost
)
629 savedhost
= malloc(1+strlen(host
));
631 fatalbox("Out of memory");
632 strcpy(savedhost
, host
);
635 port
= 22; /* default ssh port */
647 if ( (a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
648 if ( (h
= gethostbyname(host
)) == NULL
)
649 switch (WSAGetLastError()) {
650 case WSAENETDOWN
: return "Network is down";
651 case WSAHOST_NOT_FOUND
: case WSANO_DATA
:
652 return "Host does not exist";
653 case WSATRY_AGAIN
: return "Host not found";
654 default: return "gethostbyname: unknown error";
656 memcpy (&a
, h
->h_addr
, sizeof(a
));
657 *realhost
= h
->h_name
;
668 s
= socket(AF_INET
, SOCK_STREAM
, 0);
669 if (s
== INVALID_SOCKET
)
670 switch (WSAGetLastError()) {
671 case WSAENETDOWN
: return "Network is down";
672 case WSAEAFNOSUPPORT
: return "TCP/IP support not present";
673 default: return "socket(): unknown error";
677 * Bind to local address.
679 addr
.sin_family
= AF_INET
;
680 addr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
681 addr
.sin_port
= htons(0);
682 if (bind (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
683 switch (WSAGetLastError()) {
684 case WSAENETDOWN
: return "Network is down";
685 default: return "bind(): unknown error";
689 * Connect to remote address.
691 addr
.sin_addr
.s_addr
= htonl(a
);
692 addr
.sin_port
= htons((short)port
);
693 if (connect (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
694 switch (WSAGetLastError()) {
695 case WSAENETDOWN
: return "Network is down";
696 case WSAECONNREFUSED
: return "Connection refused";
697 case WSAENETUNREACH
: return "Network is unreachable";
698 case WSAEHOSTUNREACH
: return "No route to host";
699 default: return "connect(): unknown error";
703 send(s
, "connect ", 8, 0);
704 send(s
, FWhost
, strlen(FWhost
), 0);
707 sprintf(buf
, " %d\n", FWport
);
708 send (s
, buf
, strlen(buf
), 0);
715 static int ssh_versioncmp(char *a
, char *b
) {
717 unsigned long av
, bv
;
719 av
= strtoul(a
, &ae
, 10);
720 bv
= strtoul(b
, &be
, 10);
721 if (av
!= bv
) return (av
< bv ?
-1 : +1);
722 if (*ae
== '.') ae
++;
723 if (*be
== '.') be
++;
724 av
= strtoul(ae
, &ae
, 10);
725 bv
= strtoul(be
, &be
, 10);
726 if (av
!= bv
) return (av
< bv ?
-1 : +1);
732 * Utility routine for putting an SSH-protocol `string' into a SHA
736 void sha_string(SHA_State
*s
, void *str
, int len
) {
737 unsigned char lenblk
[4];
738 PUT_32BIT(lenblk
, len
);
739 SHA_Bytes(s
, lenblk
, 4);
740 SHA_Bytes(s
, str
, len
);
744 * SSH2 packet construction functions.
746 void ssh2_pkt_adddata(void *data
, int len
) {
747 pktout
.length
+= len
;
748 if (pktout
.maxlen
< pktout
.length
) {
749 pktout
.maxlen
= pktout
.length
+ 256;
750 pktout
.data
= (pktout
.data
== NULL ?
malloc(pktout
.maxlen
+APIEXTRA
) :
751 realloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
753 fatalbox("Out of memory");
755 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
757 void ssh2_pkt_addbyte(unsigned char byte
) {
758 ssh2_pkt_adddata(&byte
, 1);
760 void ssh2_pkt_init(int pkt_type
) {
762 ssh2_pkt_addbyte((unsigned char)pkt_type
);
764 void ssh2_pkt_addbool(unsigned char value
) {
765 ssh2_pkt_adddata(&value
, 1);
767 void ssh2_pkt_adduint32(unsigned long value
) {
770 ssh2_pkt_adddata(x
, 4);
772 void ssh2_pkt_addstring_start(void) {
773 ssh2_pkt_adduint32(0);
774 pktout
.savedpos
= pktout
.length
;
776 void ssh2_pkt_addstring_str(char *data
) {
777 ssh2_pkt_adddata(data
, strlen(data
));
778 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
779 pktout
.length
- pktout
.savedpos
);
781 void ssh2_pkt_addstring_data(char *data
, int len
) {
782 ssh2_pkt_adddata(data
, len
);
783 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
784 pktout
.length
- pktout
.savedpos
);
786 void ssh2_pkt_addstring(char *data
) {
787 ssh2_pkt_addstring_start();
788 ssh2_pkt_addstring_str(data
);
790 char *ssh2_mpint_fmt(Bignum b
, int *len
) {
793 p
= malloc(n
* 2 + 1);
795 fatalbox("out of memory");
797 for (i
= 0; i
< n
; i
++) {
798 p
[i
*2+1] = (b
[n
-i
] >> 8) & 0xFF;
799 p
[i
*2+2] = (b
[n
-i
] ) & 0xFF;
802 while (p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
804 memmove(p
, p
+i
, n
*2+1-i
);
808 void ssh2_pkt_addmp(Bignum b
) {
811 p
= ssh2_mpint_fmt(b
, &len
);
812 ssh2_pkt_addstring_start();
813 ssh2_pkt_addstring_data(p
, len
);
816 void ssh2_pkt_send(void) {
817 int cipherblk
, maclen
, padding
, i
;
818 static unsigned long outgoing_sequence
= 0;
821 * Add padding. At least four bytes, and must also bring total
822 * length (minus MAC) up to a multiple of the block size.
824 cipherblk
= cipher ? cipher
->blksize
: 8; /* block size */
825 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
827 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
828 pktout
.data
[4] = padding
;
829 for (i
= 0; i
< padding
; i
++)
830 pktout
.data
[pktout
.length
+ i
] = random_byte();
831 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
833 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
835 outgoing_sequence
++; /* whether or not we MACed */
838 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
839 for (i
= 0; i
< pktout
.length
+padding
; i
++)
840 debug((" %02x", (unsigned char)pktout
.data
[i
]));
845 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
846 maclen
= csmac ? csmac
->len
: 0;
848 s_write(pktout
.data
, pktout
.length
+ padding
+ maclen
);
852 void bndebug(char *string
, Bignum b
) {
855 p
= ssh2_mpint_fmt(b
, &len
);
856 debug(("%s", string
));
857 for (i
= 0; i
< len
; i
++)
858 debug((" %02x", p
[i
]));
864 void sha_mpint(SHA_State
*s
, Bignum b
) {
867 p
= ssh2_mpint_fmt(b
, &len
);
868 sha_string(s
, p
, len
);
873 * SSH2 packet decode functions.
875 unsigned long ssh2_pkt_getuint32(void) {
877 if (pktin
.length
- pktin
.savedpos
< 4)
878 return 0; /* arrgh, no way to decline (FIXME?) */
879 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
883 void ssh2_pkt_getstring(char **p
, int *length
) {
885 if (pktin
.length
- pktin
.savedpos
< 4)
887 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
889 if (pktin
.length
- pktin
.savedpos
< *length
)
891 *p
= pktin
.data
+pktin
.savedpos
;
892 pktin
.savedpos
+= *length
;
894 Bignum
ssh2_pkt_getmp(void) {
899 ssh2_pkt_getstring(&p
, &length
);
903 fatalbox("internal error: Can't handle negative mpints");
904 b
= newbn((length
+1)/2);
905 for (i
= 0; i
< length
; i
++) {
908 b
[j
/2+1] |= ((unsigned char)p
[i
]) << 8;
910 b
[j
/2+1] |= ((unsigned char)p
[i
]);
915 static int do_ssh_init(void) {
919 char vlog
[sizeof(vstring
)+20];
924 while (s_read(&c
, 1) == 1) {
925 if (c
== 'S' && i
< 2) i
++;
926 else if (c
== 'S' && i
== 2) i
= 2;
927 else if (c
== 'H' && i
== 2) break;
931 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
932 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
933 if (s_read(&c
,1) != 1 || c
!= 'H') return 0;
935 strcpy(vstring
, "SSH-");
937 if (s_read(&c
,1) != 1 || c
!= '-') return 0;
940 if (s_read(&c
,1) != 1)
942 if (vsp
< vstring
+sizeof(vstring
)-1)
948 } else if (i
< sizeof(version
)-1)
956 sprintf(vlog
, "Server version: %s", vstring
);
957 vlog
[strcspn(vlog
, "\r\n")] = '\0';
961 * Server version "1.99" means we can choose whether we use v1
962 * or v2 protocol. Choice is based on cfg.sshprot.
964 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
966 * This is a v2 server. Begin v2 protocol.
968 char *verstring
= "SSH-2.0-PuTTY";
971 * Hash our version string and their version string.
973 sha_string(&exhash
, verstring
, strlen(verstring
));
974 sha_string(&exhash
, vstring
, strcspn(vstring
, "\r\n"));
975 sprintf(vstring
, "%s\n", verstring
);
976 sprintf(vlog
, "We claim version: %s", verstring
);
978 logevent("Using SSH protocol version 2");
979 s_write(vstring
, strlen(vstring
));
980 ssh_protocol
= ssh2_protocol
;
982 s_rdpkt
= ssh2_rdpkt
;
985 * This is a v1 server. Begin v1 protocol.
987 sprintf(vstring
, "SSH-%s-PuTTY\n",
988 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
989 sprintf(vlog
, "We claim version: %s", vstring
);
990 vlog
[strcspn(vlog
, "\r\n")] = '\0';
992 logevent("Using SSH protocol version 1");
993 s_write(vstring
, strlen(vstring
));
994 ssh_protocol
= ssh1_protocol
;
996 s_rdpkt
= ssh1_rdpkt
;
1003 * Handle the key exchange and user authentication phases.
1005 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1008 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1009 unsigned char cookie
[8];
1010 struct RSAKey servkey
, hostkey
;
1011 struct MD5Context md5c
;
1012 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1013 static int tried_publickey
;
1014 static unsigned char session_id
[16];
1019 if (!ispkt
) crWaitUntil(ispkt
);
1021 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
)
1022 fatalbox("Public key packet not received");
1024 logevent("Received public keys");
1026 memcpy(cookie
, pktin
.body
, 8);
1028 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1029 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1032 * Hash the host key and print the hash in the log box. Just as
1033 * a last resort in case the registry's host key checking is
1034 * compromised, we'll allow the user some ability to verify
1038 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1039 MD5Final(session_id
, &md5c
);
1043 logevent("Host key MD5 is:");
1044 strcpy(logmsg
, " ");
1045 for (i
= 0; i
< 16; i
++)
1046 sprintf(logmsg
+strlen(logmsg
), "%02x", session_id
[i
]);
1050 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1051 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1054 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1055 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1056 MD5Update(&md5c
, pktin
.body
, 8);
1057 MD5Final(session_id
, &md5c
);
1059 for (i
=0; i
<32; i
++)
1060 session_key
[i
] = random_byte();
1062 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1064 rsabuf
= malloc(len
);
1066 fatalbox("Out of memory");
1069 * Verify the host key.
1073 * First format the key into a string.
1075 int len
= rsastr_len(&hostkey
);
1076 char *keystr
= malloc(len
);
1078 fatalbox("Out of memory");
1079 rsastr_fmt(keystr
, &hostkey
);
1080 verify_ssh_host_key(savedhost
, keystr
);
1084 for (i
=0; i
<32; i
++) {
1085 rsabuf
[i
] = session_key
[i
];
1087 rsabuf
[i
] ^= session_id
[i
];
1090 if (hostkey
.bytes
> servkey
.bytes
) {
1091 rsaencrypt(rsabuf
, 32, &servkey
);
1092 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1094 rsaencrypt(rsabuf
, 32, &hostkey
);
1095 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1098 logevent("Encrypted session key");
1100 cipher_type
= cfg
.cipher
== CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH
:
1101 cfg
.cipher
== CIPHER_DES ? SSH_CIPHER_DES
:
1103 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1104 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1105 cipher_type
= SSH_CIPHER_3DES
;
1107 switch (cipher_type
) {
1108 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1109 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1110 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1113 send_packet(SSH1_CMSG_SESSION_KEY
,
1114 PKT_CHAR
, cipher_type
,
1115 PKT_DATA
, cookie
, 8,
1116 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1117 PKT_DATA
, rsabuf
, len
,
1121 logevent("Trying to enable encryption...");
1125 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish
:
1126 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1128 cipher
->sesskey(session_key
);
1132 if (pktin
.type
!= SSH1_SMSG_SUCCESS
)
1133 fatalbox("Encryption not successfully enabled");
1135 logevent("Successfully started encryption");
1139 static char username
[100];
1142 if (!(flags
& FLAG_CONNECTION
) && !*cfg
.username
) {
1143 c_write("login as: ", 10);
1145 crWaitUntil(!ispkt
);
1146 while (inlen
--) switch (c
= *in
++) {
1153 c_write("\b \b", 3);
1159 c_write("\b \b", 3);
1168 if (((c
>= ' ' && c
<= '~') ||
1169 ((unsigned char)c
>= 160)) && pos
< 40) {
1170 username
[pos
++] = c
;
1177 username
[strcspn(username
, "\n\r")] = '\0';
1180 strncpy(username
, cfg
.username
, 99);
1181 username
[99] = '\0';
1182 if (flags
& FLAG_VERBOSE
) {
1183 sprintf(stuff
, "Sent username \"%s\".\r\n", username
);
1184 c_write(stuff
, strlen(stuff
));
1188 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1190 char userlog
[20+sizeof(username
)];
1191 sprintf(userlog
, "Sent username \"%s\"", username
);
1198 tried_publickey
= 0;
1200 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1201 static char password
[100];
1204 static int pwpkt_type
;
1206 * Show password prompt, having first obtained it via a TIS
1207 * or CryptoCard exchange if we're doing TIS or CryptoCard
1210 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1211 if (*cfg
.keyfile
&& !tried_publickey
)
1212 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1214 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
&& !FLAG_WINDOWED
) {
1216 sprintf(prompt
, "%s@%s's password: ", cfg
.username
, savedhost
);
1217 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1219 * get_password failed to get a password (for
1220 * example because one was supplied on the command
1221 * line which has already failed to work).
1224 logevent("No more passwords to try");
1225 ssh_state
= SSH_STATE_CLOSED
;
1230 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1232 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1233 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1234 logevent("Requested TIS authentication");
1235 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1237 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1238 logevent("TIS authentication declined");
1239 c_write("TIS authentication refused.\r\n", 29);
1241 int challengelen
= ((pktin
.body
[0] << 24) |
1242 (pktin
.body
[1] << 16) |
1243 (pktin
.body
[2] << 8) |
1245 logevent("Received TIS challenge");
1246 c_write(pktin
.body
+4, challengelen
);
1249 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1251 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1252 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1253 logevent("Requested CryptoCard authentication");
1254 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1256 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1257 logevent("CryptoCard authentication declined");
1258 c_write("CryptoCard authentication refused.\r\n", 29);
1260 int challengelen
= ((pktin
.body
[0] << 24) |
1261 (pktin
.body
[1] << 16) |
1262 (pktin
.body
[2] << 8) |
1264 logevent("Received CryptoCard challenge");
1265 c_write(pktin
.body
+4, challengelen
);
1266 c_write("\r\nResponse : ", 13);
1269 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
)
1270 c_write("password: ", 10);
1271 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1272 if (flags
& FLAG_VERBOSE
)
1273 c_write("Trying public key authentication.\r\n", 35);
1274 if (!rsakey_encrypted(cfg
.keyfile
)) {
1275 if (flags
& FLAG_VERBOSE
)
1276 c_write("No passphrase required.\r\n", 25);
1279 c_write("passphrase: ", 12);
1284 crWaitUntil(!ispkt
);
1285 while (inlen
--) switch (c
= *in
++) {
1302 if (((c
>= ' ' && c
<= '~') ||
1303 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1304 password
[pos
++] = c
;
1313 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1315 * Try public key authentication with the specified
1318 static struct RSAKey pubkey
;
1319 static Bignum challenge
, response
;
1321 static unsigned char buffer
[32];
1323 tried_publickey
= 1;
1324 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1326 c_write("Couldn't load public key from ", 30);
1327 c_write(cfg
.keyfile
, strlen(cfg
.keyfile
));
1328 c_write(".\r\n", 3);
1329 continue; /* go and try password */
1332 c_write("Wrong passphrase.\r\n", 19);
1333 tried_publickey
= 0;
1334 continue; /* try again */
1338 * Send a public key attempt.
1340 send_packet(SSH1_CMSG_AUTH_RSA
,
1341 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1344 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1345 if (flags
& FLAG_VERBOSE
)
1346 c_write("Server refused our public key.\r\n", 32);
1347 continue; /* go and try password */
1349 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
)
1350 fatalbox("Bizarre response to offer of public key");
1351 ssh1_read_bignum(pktin
.body
, &challenge
);
1352 response
= rsadecrypt(challenge
, &pubkey
);
1353 freebn(pubkey
.private_exponent
); /* burn the evidence */
1355 for (i
= 0; i
< 32; i
+= 2) {
1356 buffer
[i
] = response
[16-i
/2] >> 8;
1357 buffer
[i
+1] = response
[16-i
/2] & 0xFF;
1361 MD5Update(&md5c
, buffer
, 32);
1362 MD5Update(&md5c
, session_id
, 16);
1363 MD5Final(buffer
, &md5c
);
1365 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1366 PKT_DATA
, buffer
, 16, PKT_END
);
1369 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1370 if (flags
& FLAG_VERBOSE
)
1371 c_write("Failed to authenticate with our public key.\r\n",
1373 continue; /* go and try password */
1374 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1375 fatalbox("Bizarre response to RSA authentication response");
1378 break; /* we're through! */
1380 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1382 logevent("Sent password");
1383 memset(password
, 0, strlen(password
));
1385 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1386 if (flags
& FLAG_VERBOSE
)
1387 c_write("Access denied\r\n", 15);
1388 logevent("Authentication refused");
1389 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1390 logevent("Received disconnect request");
1391 ssh_state
= SSH_STATE_CLOSED
;
1393 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1394 fatalbox("Strange packet received, type %d", pktin
.type
);
1398 logevent("Authentication successful");
1403 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1408 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1411 if (ssh_state
== SSH_STATE_CLOSED
)
1415 send_packet(SSH1_CMSG_REQUEST_PTY
,
1416 PKT_STR
, cfg
.termtype
,
1417 PKT_INT
, rows
, PKT_INT
, cols
,
1418 PKT_INT
, 0, PKT_INT
, 0,
1421 ssh_state
= SSH_STATE_INTERMED
;
1422 do { crReturnV
; } while (!ispkt
);
1423 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1424 fatalbox("Protocol confusion");
1425 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1426 c_write("Server refused to allocate pty\r\n", 32);
1428 logevent("Allocated pty");
1431 if (*cfg
.remote_cmd
)
1432 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1434 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1435 logevent("Started session");
1437 ssh_state
= SSH_STATE_SESSION
;
1445 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1446 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1447 long len
= GET_32BIT(pktin
.body
);
1448 c_write(pktin
.body
+4, len
);
1449 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1450 ssh_state
= SSH_STATE_CLOSED
;
1451 logevent("Received disconnect request");
1452 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1453 /* may be from EXEC_SHELL on some servers */
1454 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1455 /* may be from EXEC_SHELL on some servers
1456 * if no pty is available or in other odd cases. Ignore */
1457 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
1458 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
1460 fatalbox("Strange packet received: type %d", pktin
.type
);
1463 send_packet(SSH1_CMSG_STDIN_DATA
,
1464 PKT_INT
, inlen
, PKT_DATA
, in
, inlen
, PKT_END
);
1472 * Utility routine for decoding comma-separated strings in KEXINIT.
1474 int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
1475 int needlen
= strlen(needle
);
1478 * Is it at the start of the string?
1480 if (haylen
>= needlen
&& /* haystack is long enough */
1481 !memcmp(needle
, haystack
, needlen
) && /* initial match */
1482 (haylen
== needlen
|| haystack
[needlen
] == ',')
1483 /* either , or EOS follows */
1487 * If not, search for the next comma and resume after that.
1488 * If no comma found, terminate.
1490 while (haylen
> 0 && *haystack
!= ',')
1491 haylen
--, haystack
++;
1494 haylen
--, haystack
++; /* skip over comma itself */
1499 * SSH2 key creation method.
1501 void ssh2_mkkey(Bignum K
, char *H
, char chr
, char *keyspace
) {
1503 /* First 20 bytes. */
1506 SHA_Bytes(&s
, H
, 20);
1507 SHA_Bytes(&s
, &chr
, 1);
1508 SHA_Bytes(&s
, H
, 20);
1509 SHA_Final(&s
, keyspace
);
1510 /* Next 20 bytes. */
1513 SHA_Bytes(&s
, H
, 20);
1514 SHA_Bytes(&s
, keyspace
, 20);
1515 SHA_Final(&s
, keyspace
+20);
1519 * Handle the SSH2 transport layer.
1521 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
1525 static Bignum e
, f
, K
;
1526 static struct ssh_cipher
*cscipher_tobe
= NULL
;
1527 static struct ssh_cipher
*sccipher_tobe
= NULL
;
1528 static struct ssh_mac
*csmac_tobe
= NULL
;
1529 static struct ssh_mac
*scmac_tobe
= NULL
;
1530 static struct ssh_compress
*cscomp_tobe
= NULL
;
1531 static struct ssh_compress
*sccomp_tobe
= NULL
;
1532 static char *hostkeydata
, *sigdata
, *keystr
;
1533 static int hostkeylen
, siglen
;
1534 static unsigned char exchange_hash
[20];
1535 static unsigned char keyspace
[40];
1542 * Construct and send our key exchange packet.
1544 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
1545 for (i
= 0; i
< 16; i
++)
1546 ssh2_pkt_addbyte((unsigned char)random_byte());
1547 /* List key exchange algorithms. */
1548 ssh2_pkt_addstring_start();
1549 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1550 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
1551 if (i
< lenof(kex_algs
)-1)
1552 ssh2_pkt_addstring_str(",");
1554 /* List server host key algorithms. */
1555 ssh2_pkt_addstring_start();
1556 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1557 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
1558 if (i
< lenof(hostkey_algs
)-1)
1559 ssh2_pkt_addstring_str(",");
1561 /* List client->server encryption algorithms. */
1562 ssh2_pkt_addstring_start();
1563 for (i
= 0; i
< lenof(ciphers
); i
++) {
1564 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1565 if (i
< lenof(ciphers
)-1)
1566 ssh2_pkt_addstring_str(",");
1568 /* List server->client encryption algorithms. */
1569 ssh2_pkt_addstring_start();
1570 for (i
= 0; i
< lenof(ciphers
); i
++) {
1571 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1572 if (i
< lenof(ciphers
)-1)
1573 ssh2_pkt_addstring_str(",");
1575 /* List client->server MAC algorithms. */
1576 ssh2_pkt_addstring_start();
1577 for (i
= 0; i
< lenof(macs
); i
++) {
1578 ssh2_pkt_addstring_str(macs
[i
]->name
);
1579 if (i
< lenof(macs
)-1)
1580 ssh2_pkt_addstring_str(",");
1582 /* List server->client MAC algorithms. */
1583 ssh2_pkt_addstring_start();
1584 for (i
= 0; i
< lenof(macs
); i
++) {
1585 ssh2_pkt_addstring_str(macs
[i
]->name
);
1586 if (i
< lenof(macs
)-1)
1587 ssh2_pkt_addstring_str(",");
1589 /* List client->server compression algorithms. */
1590 ssh2_pkt_addstring_start();
1591 for (i
= 0; i
< lenof(compressions
); i
++) {
1592 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1593 if (i
< lenof(compressions
)-1)
1594 ssh2_pkt_addstring_str(",");
1596 /* List server->client compression algorithms. */
1597 ssh2_pkt_addstring_start();
1598 for (i
= 0; i
< lenof(compressions
); i
++) {
1599 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1600 if (i
< lenof(compressions
)-1)
1601 ssh2_pkt_addstring_str(",");
1603 /* List client->server languages. Empty list. */
1604 ssh2_pkt_addstring_start();
1605 /* List server->client languages. Empty list. */
1606 ssh2_pkt_addstring_start();
1607 /* First KEX packet does _not_ follow, because we're not that brave. */
1608 ssh2_pkt_addbool(FALSE
);
1610 ssh2_pkt_adduint32(0);
1611 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
1614 if (!ispkt
) crWaitUntil(ispkt
);
1615 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
1618 * Now examine the other side's KEXINIT to see what we're up
1621 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
1622 fatalbox("expected key exchange packet from server");
1624 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
1625 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
1626 pktin
.savedpos
+= 16; /* skip garbage cookie */
1627 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
1628 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1629 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
1634 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
1635 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1636 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
1637 hostkey
= hostkey_algs
[i
];
1641 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
1642 for (i
= 0; i
< lenof(ciphers
); i
++) {
1643 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1644 cscipher_tobe
= ciphers
[i
];
1648 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
1649 for (i
= 0; i
< lenof(ciphers
); i
++) {
1650 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1651 sccipher_tobe
= ciphers
[i
];
1655 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
1656 for (i
= 0; i
< lenof(macs
); i
++) {
1657 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1658 csmac_tobe
= macs
[i
];
1662 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
1663 for (i
= 0; i
< lenof(macs
); i
++) {
1664 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1665 scmac_tobe
= macs
[i
];
1669 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
1670 for (i
= 0; i
< lenof(compressions
); i
++) {
1671 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1672 cscomp_tobe
= compressions
[i
];
1676 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
1677 for (i
= 0; i
< lenof(compressions
); i
++) {
1678 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1679 sccomp_tobe
= compressions
[i
];
1685 * Currently we only support Diffie-Hellman and DSS, so let's
1686 * bomb out if those aren't selected.
1688 if (kex
!= &ssh_diffiehellman
|| hostkey
!= &ssh_dss
)
1689 fatalbox("internal fault: chaos in SSH 2 transport layer");
1692 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1695 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT
);
1700 if (pktin
.type
!= SSH2_MSG_KEXDH_REPLY
) {
1701 fatalbox("expected key exchange packet from server");
1703 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
1704 f
= ssh2_pkt_getmp();
1705 ssh2_pkt_getstring(&sigdata
, &siglen
);
1709 sha_string(&exhash
, hostkeydata
, hostkeylen
);
1710 sha_mpint(&exhash
, e
);
1711 sha_mpint(&exhash
, f
);
1712 sha_mpint(&exhash
, K
);
1713 SHA_Final(&exhash
, exchange_hash
);
1716 debug(("Exchange hash is:\r\n"));
1717 for (i
= 0; i
< 20; i
++)
1718 debug((" %02x", exchange_hash
[i
]));
1722 hostkey
->setkey(hostkeydata
, hostkeylen
);
1723 if (!hostkey
->verifysig(sigdata
, siglen
, exchange_hash
, 20))
1724 fatalbox("Server failed host key check");
1727 * Expect SSH2_MSG_NEWKEYS from server.
1730 if (pktin
.type
!= SSH2_MSG_NEWKEYS
)
1731 fatalbox("expected new-keys packet from server");
1734 * Authenticate remote host: verify host key. (We've already
1735 * checked the signature of the exchange hash.)
1737 keystr
= hostkey
->fmtkey();
1738 verify_ssh_host_key(savedhost
, keystr
);
1742 * Send SSH2_MSG_NEWKEYS.
1744 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
1748 * Create and initialise session keys.
1750 cscipher
= cscipher_tobe
;
1751 sccipher
= sccipher_tobe
;
1754 cscomp
= cscomp_tobe
;
1755 sccomp
= sccomp_tobe
;
1757 * Set IVs after keys.
1759 ssh2_mkkey(K
, exchange_hash
, 'C', keyspace
); cscipher
->setcskey(keyspace
);
1760 ssh2_mkkey(K
, exchange_hash
, 'D', keyspace
); cscipher
->setsckey(keyspace
);
1761 ssh2_mkkey(K
, exchange_hash
, 'A', keyspace
); cscipher
->setcsiv(keyspace
);
1762 ssh2_mkkey(K
, exchange_hash
, 'B', keyspace
); sccipher
->setsciv(keyspace
);
1763 ssh2_mkkey(K
, exchange_hash
, 'E', keyspace
); csmac
->setcskey(keyspace
);
1764 ssh2_mkkey(K
, exchange_hash
, 'F', keyspace
); scmac
->setsckey(keyspace
);
1767 * Now we're encrypting. Begin returning 1 to the protocol main
1768 * function so that other things can run on top of the
1769 * transport. If we ever see a KEXINIT, we must go back to the
1774 } while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
));
1775 goto begin_key_exchange
;
1781 * SSH2: remote identifier for the main session channel.
1783 static unsigned long ssh_remote_channel
;
1786 * Handle the SSH2 userauth and connection layers.
1788 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
1790 static unsigned long remote_winsize
;
1791 static unsigned long remote_maxpkt
;
1796 * Request userauth protocol, and await a response to it.
1798 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
1799 ssh2_pkt_addstring("ssh-userauth");
1801 crWaitUntilV(ispkt
);
1802 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
)
1803 fatalbox("Server refused user authentication protocol");
1806 * FIXME: currently we support only password authentication.
1807 * (This places us technically in violation of the SSH2 spec.
1808 * We must fix this.)
1812 * Get a username and a password.
1814 static char username
[100];
1815 static char password
[100];
1819 if ((flags
& FLAG_CONNECTION
) && !*cfg
.username
) {
1820 c_write("login as: ", 10);
1822 crWaitUntilV(!ispkt
);
1823 while (inlen
--) switch (c
= *in
++) {
1830 c_write("\b \b", 3);
1836 c_write("\b \b", 3);
1845 if (((c
>= ' ' && c
<= '~') ||
1846 ((unsigned char)c
>= 160)) && pos
< 40) {
1847 username
[pos
++] = c
;
1854 username
[strcspn(username
, "\n\r")] = '\0';
1857 strncpy(username
, cfg
.username
, 99);
1858 username
[99] = '\0';
1859 if (flags
& FLAG_VERBOSE
) {
1860 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
1861 c_write(stuff
, strlen(stuff
));
1865 if (!(flags
& FLAG_WINDOWED
)) {
1867 sprintf(prompt
, "%s@%s's password: ", cfg
.username
, savedhost
);
1868 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1870 * get_password failed to get a password (for
1871 * example because one was supplied on the command
1872 * line which has already failed to work).
1875 logevent("No more passwords to try");
1876 ssh_state
= SSH_STATE_CLOSED
;
1880 c_write("password: ", 10);
1884 crWaitUntilV(!ispkt
);
1885 while (inlen
--) switch (c
= *in
++) {
1902 if (((c
>= ' ' && c
<= '~') ||
1903 ((unsigned char)c
>= 160)) && pos
< 40)
1904 password
[pos
++] = c
;
1911 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
1912 ssh2_pkt_addstring(username
);
1913 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1914 ssh2_pkt_addstring("password");
1915 ssh2_pkt_addbool(FALSE
);
1916 ssh2_pkt_addstring(password
);
1919 crWaitUntilV(ispkt
);
1920 if (pktin
.type
!= SSH2_MSG_USERAUTH_SUCCESS
) {
1921 c_write("Access denied\r\n", 15);
1922 logevent("Authentication refused");
1928 * Now we're authenticated for the connection protocol. The
1929 * connection protocol will automatically have started at this
1930 * point; there's no need to send SERVICE_REQUEST.
1934 * So now create a channel with a session in it.
1936 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
1937 ssh2_pkt_addstring("session");
1938 ssh2_pkt_adduint32(100); /* as good as any */
1939 ssh2_pkt_adduint32(0xFFFFFFFFUL
); /* very big window which we ignore */
1940 ssh2_pkt_adduint32(0xFFFFFFFFUL
); /* very big max pkt size */
1942 crWaitUntilV(ispkt
);
1943 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
1944 fatalbox("Server refused to open a session");
1945 /* FIXME: error data comes back in FAILURE packet */
1947 if (ssh2_pkt_getuint32() != 100) {
1948 fatalbox("Server's channel confirmation cited wrong channel");
1950 ssh_remote_channel
= ssh2_pkt_getuint32();
1951 remote_winsize
= ssh2_pkt_getuint32();
1952 remote_maxpkt
= ssh2_pkt_getuint32();
1953 logevent("Opened channel for session");
1956 * Now allocate a pty for the session.
1958 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
1959 ssh2_pkt_adduint32(ssh_remote_channel
); /* recipient channel */
1960 ssh2_pkt_addstring("pty-req");
1961 ssh2_pkt_addbool(1); /* want reply */
1962 ssh2_pkt_addstring(cfg
.termtype
);
1963 ssh2_pkt_adduint32(cols
);
1964 ssh2_pkt_adduint32(rows
);
1965 ssh2_pkt_adduint32(0); /* pixel width */
1966 ssh2_pkt_adduint32(0); /* pixel height */
1967 ssh2_pkt_addstring_start();
1968 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
1971 do { /* FIXME: pay attention to these */
1972 crWaitUntilV(ispkt
);
1973 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
1975 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
1976 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
1977 fatalbox("Server got confused by pty request");
1979 c_write("Server refused to allocate pty\r\n", 32);
1981 logevent("Allocated pty");
1987 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
1988 ssh2_pkt_adduint32(ssh_remote_channel
); /* recipient channel */
1989 ssh2_pkt_addstring("shell");
1990 ssh2_pkt_addbool(1); /* want reply */
1992 do { /* FIXME: pay attention to these */
1993 crWaitUntilV(ispkt
);
1994 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
1995 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
1996 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
1997 fatalbox("Server got confused by shell request");
1999 fatalbox("Server refused to start a shell");
2001 logevent("Started a shell");
2011 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
2012 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
2015 if (ssh2_pkt_getuint32() != 100)
2016 continue; /* wrong channel */
2017 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
2018 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
2019 continue; /* extended but not stderr */
2020 ssh2_pkt_getstring(&data
, &length
);
2022 c_write(data
, length
);
2023 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
2024 ssh_state
= SSH_STATE_CLOSED
;
2025 logevent("Received disconnect request");
2026 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
2027 continue; /* exit status et al; ignore (FIXME?) */
2028 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2029 continue; /* ignore for now (FIXME!) */
2031 fatalbox("Strange packet received: type %d", pktin
.type
);
2034 /* FIXME: for now, ignore window size */
2035 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2036 ssh2_pkt_adduint32(ssh_remote_channel
);
2037 ssh2_pkt_addstring_start();
2038 ssh2_pkt_addstring_data(in
, inlen
);
2047 * Handle the top-level SSH2 protocol.
2049 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
2051 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
2053 do_ssh2_authconn(in
, inlen
, ispkt
);
2057 * Called to set up the connection. Will arrange for WM_NETEVENT
2058 * messages to be passed to the specified window, whose window
2059 * procedure should then call telnet_msg().
2061 * Returns an error message, or NULL on success.
2063 static char *ssh_init (HWND hwnd
, char *host
, int port
, char **realhost
) {
2067 if(crypto_startup() == 0)
2068 return "Microsoft high encryption pack not installed!";
2071 p
= connect_to_host(host
, port
, realhost
);
2076 return "Protocol initialisation error";
2078 if (hwnd
&& WSAAsyncSelect (s
, hwnd
, WM_NETEVENT
, FD_READ
| FD_CLOSE
) == SOCKET_ERROR
)
2079 switch (WSAGetLastError()) {
2080 case WSAENETDOWN
: return "Network is down";
2081 default: return "WSAAsyncSelect(): unknown error";
2088 * Process a WM_NETEVENT message. Will return 0 if the connection
2089 * has closed, or <0 for a socket error.
2091 static int ssh_msg (WPARAM wParam
, LPARAM lParam
) {
2096 * Because reading less than the whole of the available pending
2097 * data can generate an FD_READ event, we need to allow for the
2098 * possibility that FD_READ may arrive with FD_CLOSE already in
2099 * the queue; so it's possible that we can get here even with s
2100 * invalid. If so, we return 1 and don't worry about it.
2102 if (s
== INVALID_SOCKET
)
2105 if (WSAGETSELECTERROR(lParam
) != 0)
2106 return -WSAGETSELECTERROR(lParam
);
2108 switch (WSAGETSELECTEVENT(lParam
)) {
2111 ret
= recv(s
, buf
, sizeof(buf
), 0);
2112 if (ret
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
)
2114 if (ret
< 0) /* any _other_ error */
2115 return -10000-WSAGetLastError();
2120 ssh_gotdata (buf
, ret
);
2121 if (ssh_state
== SSH_STATE_CLOSED
) {
2128 return 1; /* shouldn't happen, but WTF */
2132 * Called to send data down the Telnet connection.
2134 static void ssh_send (char *buf
, int len
) {
2135 if (s
== INVALID_SOCKET
)
2138 ssh_protocol(buf
, len
, 0);
2142 * Called to set the size of the window from Telnet's POV.
2144 static void ssh_size(void) {
2145 switch (ssh_state
) {
2146 case SSH_STATE_BEFORE_SIZE
:
2147 case SSH_STATE_CLOSED
:
2148 break; /* do nothing */
2149 case SSH_STATE_INTERMED
:
2150 size_needed
= TRUE
; /* buffer for later */
2152 case SSH_STATE_SESSION
:
2154 send_packet(SSH1_CMSG_WINDOW_SIZE
,
2155 PKT_INT
, rows
, PKT_INT
, cols
,
2156 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
2162 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2163 * can send an EOF and collect resulting output (e.g. `plink
2166 static void ssh_special (Telnet_Special code
) {
2167 if (code
== TS_EOF
) {
2168 if (ssh_version
= 1) {
2169 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2171 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
2172 ssh2_pkt_adduint32(ssh_remote_channel
);
2182 * Read and decrypt one incoming SSH packet.
2183 * (only used by pSCP)
2185 static void get_packet(void)
2187 unsigned char buf
[4096], *p
;
2194 while ((to_read
= s_rdpkt(&p
, &len
)) > 0) {
2195 if (to_read
> sizeof(buf
)) to_read
= sizeof(buf
);
2196 len
= s_read(buf
, to_read
);
2197 if (len
!= to_read
) {
2209 * Receive a block of data over the SSH link. Block until
2210 * all data is available. Return nr of bytes read (0 if lost connection).
2211 * (only used by pSCP)
2213 int ssh_scp_recv(unsigned char *buf
, int len
)
2215 static int pending_input_len
= 0;
2216 static unsigned char *pending_input_ptr
;
2219 if (pending_input_len
>= to_read
) {
2220 memcpy(buf
, pending_input_ptr
, to_read
);
2221 pending_input_ptr
+= to_read
;
2222 pending_input_len
-= to_read
;
2226 if (pending_input_len
> 0) {
2227 memcpy(buf
, pending_input_ptr
, pending_input_len
);
2228 buf
+= pending_input_len
;
2229 to_read
-= pending_input_len
;
2230 pending_input_len
= 0;
2233 if (s
== INVALID_SOCKET
)
2235 while (to_read
> 0) {
2237 if (s
== INVALID_SOCKET
)
2239 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
) {
2240 int plen
= GET_32BIT(pktin
.body
);
2241 if (plen
<= to_read
) {
2242 memcpy(buf
, pktin
.body
+ 4, plen
);
2246 memcpy(buf
, pktin
.body
+ 4, to_read
);
2247 pending_input_len
= plen
- to_read
;
2248 pending_input_ptr
= pktin
.body
+ 4 + to_read
;
2251 } else if (pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2252 int plen
= GET_32BIT(pktin
.body
);
2253 fwrite(pktin
.body
+ 4, plen
, 1, stderr
);
2254 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2255 logevent("Received disconnect request");
2256 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
||
2257 pktin
.type
== SSH1_SMSG_FAILURE
) {
2259 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2261 sprintf(logbuf
, "Remote exit status: %d", GET_32BIT(pktin
.body
));
2263 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2264 logevent("Closing connection");
2268 fatalbox("Strange packet received: type %d", pktin
.type
);
2276 * Send a block of data over the SSH link.
2277 * Block until all data is sent.
2278 * (only used by pSCP)
2280 void ssh_scp_send(unsigned char *buf
, int len
)
2282 if (s
== INVALID_SOCKET
)
2284 send_packet(SSH1_CMSG_STDIN_DATA
,
2285 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2289 * Send an EOF notification to the server.
2290 * (only used by pSCP)
2292 void ssh_scp_send_eof(void)
2294 if (s
== INVALID_SOCKET
)
2296 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2300 * Set up the connection, login on the remote host and
2301 * start execution of a command.
2302 * Returns an error message, or NULL on success.
2303 * (only used by pSCP)
2305 char *ssh_scp_init(char *host
, int port
, char *cmd
, char **realhost
)
2310 if (crypto_startup() == 0)
2311 return "Microsoft high encryption pack not installed!";
2314 p
= connect_to_host(host
, port
, realhost
);
2321 return "Protocol initialisation error";
2323 /* Exchange keys and login */
2326 if (s
== INVALID_SOCKET
)
2327 return "Connection closed by remote host";
2328 } while (!do_ssh1_login(NULL
, 0, 1));
2330 if (ssh_state
== SSH_STATE_CLOSED
) {
2333 return "Session initialisation error";
2336 /* Execute command */
2337 sprintf(buf
, "Sending command: %.100s", cmd
);
2339 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2344 static SOCKET
ssh_socket(void) { return s
; }
2346 static int ssh_sendok(void) { return ssh_send_ok
; }
2348 Backend ssh_backend
= {