xref: /plan9/sys/src/libsec/port/tlshand.c (revision 4d44ba9b9ee4246ddbd96c7fcaf0918ab92ab35a)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <auth.h>
5 #include <mp.h>
6 #include <libsec.h>
7 
8 // The main groups of functions are:
9 //		client/server - main handshake protocol definition
10 //		message functions - formating handshake messages
11 //		cipher choices - catalog of digest and encrypt algorithms
12 //		security functions - PKCS#1, sslHMAC, session keygen
13 //		general utility functions - malloc, serialization
14 // The handshake protocol builds on the TLS/SSL3 record layer protocol,
15 // which is implemented in kernel device #a.  See also /lib/rfc/rfc2246.
16 
17 enum {
18 	TLSFinishedLen = 12,
19 	SSL3FinishedLen = MD5dlen+SHA1dlen,
20 	MaxKeyData = 104,	// amount of secret we may need
21 	MaxChunk = 1<<14,
22 	RandomSize = 32,
23 	SidSize = 32,
24 	MasterSecretSize = 48,
25 	AQueue = 0,
26 	AFlush = 1,
27 };
28 
29 typedef struct TlsSec TlsSec;
30 
31 typedef struct Bytes{
32 	int len;
33 	uchar data[1];  // [len]
34 } Bytes;
35 
36 typedef struct Ints{
37 	int len;
38 	int data[1];  // [len]
39 } Ints;
40 
41 typedef struct Algs{
42 	char *enc;
43 	char *digest;
44 	int nsecret;
45 	int tlsid;
46 	int ok;
47 } Algs;
48 
49 typedef struct Finished{
50 	uchar verify[SSL3FinishedLen];
51 	int n;
52 } Finished;
53 
54 typedef struct TlsConnection{
55 	TlsSec *sec;	// security management goo
56 	int hand, ctl;	// record layer file descriptors
57 	int erred;		// set when tlsError called
58 	int (*trace)(char*fmt, ...); // for debugging
59 	int version;	// protocol we are speaking
60 	int verset;		// version has been set
61 	int ver2hi;		// server got a version 2 hello
62 	int isClient;	// is this the client or server?
63 	Bytes *sid;		// SessionID
64 	Bytes *cert;	// only last - no chain
65 
66 	Lock statelk;
67 	int state;		// must be set using setstate
68 
69 	// input buffer for handshake messages
70 	uchar buf[MaxChunk+2048];
71 	uchar *rp, *ep;
72 
73 	uchar crandom[RandomSize];	// client random
74 	uchar srandom[RandomSize];	// server random
75 	int clientVersion;	// version in ClientHello
76 	char *digest;	// name of digest algorithm to use
77 	char *enc;		// name of encryption algorithm to use
78 	int nsecret;	// amount of secret data to init keys
79 
80 	// for finished messages
81 	MD5state	hsmd5;	// handshake hash
82 	SHAstate	hssha1;	// handshake hash
83 	Finished	finished;
84 } TlsConnection;
85 
86 typedef struct Msg{
87 	int tag;
88 	union {
89 		struct {
90 			int version;
91 			uchar 	random[RandomSize];
92 			Bytes*	sid;
93 			Ints*	ciphers;
94 			Bytes*	compressors;
95 		} clientHello;
96 		struct {
97 			int version;
98 			uchar 	random[RandomSize];
99 			Bytes*	sid;
100 			int cipher;
101 			int compressor;
102 		} serverHello;
103 		struct {
104 			int ncert;
105 			Bytes **certs;
106 		} certificate;
107 		struct {
108 			Bytes *types;
109 			int nca;
110 			Bytes **cas;
111 		} certificateRequest;
112 		struct {
113 			Bytes *key;
114 		} clientKeyExchange;
115 		Finished finished;
116 	} u;
117 } Msg;
118 
119 typedef struct TlsSec{
120 	char *server;	// name of remote; nil for server
121 	int ok;	// <0 killed; ==0 in progress; >0 reusable
122 	RSApub *rsapub;
123 	AuthRpc *rpc;	// factotum for rsa private key
124 	uchar sec[MasterSecretSize];	// master secret
125 	uchar crandom[RandomSize];	// client random
126 	uchar srandom[RandomSize];	// server random
127 	int clientVers;		// version in ClientHello
128 	int vers;			// final version
129 	// byte generation and handshake checksum
130 	void (*prf)(uchar*, int, uchar*, int, char*, uchar*, int, uchar*, int);
131 	void (*setFinished)(TlsSec*, MD5state, SHAstate, uchar*, int);
132 	int nfin;
133 } TlsSec;
134 
135 
136 enum {
137 	TLSVersion = 0x0301,
138 	SSL3Version = 0x0300,
139 	ProtocolVersion = 0x0301,	// maximum version we speak
140 	MinProtoVersion = 0x0300,	// limits on version we accept
141 	MaxProtoVersion	= 0x03ff,
142 };
143 
144 // handshake type
145 enum {
146 	HHelloRequest,
147 	HClientHello,
148 	HServerHello,
149 	HSSL2ClientHello = 9,  /* local convention;  see devtls.c */
150 	HCertificate = 11,
151 	HServerKeyExchange,
152 	HCertificateRequest,
153 	HServerHelloDone,
154 	HCertificateVerify,
155 	HClientKeyExchange,
156 	HFinished = 20,
157 	HMax
158 };
159 
160 // alerts
161 enum {
162 	ECloseNotify = 0,
163 	EUnexpectedMessage = 10,
164 	EBadRecordMac = 20,
165 	EDecryptionFailed = 21,
166 	ERecordOverflow = 22,
167 	EDecompressionFailure = 30,
168 	EHandshakeFailure = 40,
169 	ENoCertificate = 41,
170 	EBadCertificate = 42,
171 	EUnsupportedCertificate = 43,
172 	ECertificateRevoked = 44,
173 	ECertificateExpired = 45,
174 	ECertificateUnknown = 46,
175 	EIllegalParameter = 47,
176 	EUnknownCa = 48,
177 	EAccessDenied = 49,
178 	EDecodeError = 50,
179 	EDecryptError = 51,
180 	EExportRestriction = 60,
181 	EProtocolVersion = 70,
182 	EInsufficientSecurity = 71,
183 	EInternalError = 80,
184 	EUserCanceled = 90,
185 	ENoRenegotiation = 100,
186 	EMax = 256
187 };
188 
189 // cipher suites
190 enum {
191 	TLS_NULL_WITH_NULL_NULL	 		= 0x0000,
192 	TLS_RSA_WITH_NULL_MD5 			= 0x0001,
193 	TLS_RSA_WITH_NULL_SHA 			= 0x0002,
194 	TLS_RSA_EXPORT_WITH_RC4_40_MD5 		= 0x0003,
195 	TLS_RSA_WITH_RC4_128_MD5 		= 0x0004,
196 	TLS_RSA_WITH_RC4_128_SHA 		= 0x0005,
197 	TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5	= 0X0006,
198 	TLS_RSA_WITH_IDEA_CBC_SHA 		= 0X0007,
199 	TLS_RSA_EXPORT_WITH_DES40_CBC_SHA	= 0X0008,
200 	TLS_RSA_WITH_DES_CBC_SHA		= 0X0009,
201 	TLS_RSA_WITH_3DES_EDE_CBC_SHA		= 0X000A,
202 	TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA	= 0X000B,
203 	TLS_DH_DSS_WITH_DES_CBC_SHA		= 0X000C,
204 	TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA	= 0X000D,
205 	TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA	= 0X000E,
206 	TLS_DH_RSA_WITH_DES_CBC_SHA		= 0X000F,
207 	TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA	= 0X0010,
208 	TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA	= 0X0011,
209 	TLS_DHE_DSS_WITH_DES_CBC_SHA		= 0X0012,
210 	TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA	= 0X0013,	// ZZZ must be implemented for tls1.0 compliance
211 	TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA	= 0X0014,
212 	TLS_DHE_RSA_WITH_DES_CBC_SHA		= 0X0015,
213 	TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA	= 0X0016,
214 	TLS_DH_anon_EXPORT_WITH_RC4_40_MD5	= 0x0017,
215 	TLS_DH_anon_WITH_RC4_128_MD5 		= 0x0018,
216 	TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA	= 0X0019,
217 	TLS_DH_anon_WITH_DES_CBC_SHA		= 0X001A,
218 	TLS_DH_anon_WITH_3DES_EDE_CBC_SHA	= 0X001B,
219 
220 	TLS_RSA_WITH_AES_128_CBC_SHA		= 0X002f,	// aes, aka rijndael with 128 bit blocks
221 	TLS_DH_DSS_WITH_AES_128_CBC_SHA		= 0X0030,
222 	TLS_DH_RSA_WITH_AES_128_CBC_SHA		= 0X0031,
223 	TLS_DHE_DSS_WITH_AES_128_CBC_SHA	= 0X0032,
224 	TLS_DHE_RSA_WITH_AES_128_CBC_SHA	= 0X0033,
225 	TLS_DH_anon_WITH_AES_128_CBC_SHA	= 0X0034,
226 	TLS_RSA_WITH_AES_256_CBC_SHA		= 0X0035,
227 	TLS_DH_DSS_WITH_AES_256_CBC_SHA		= 0X0036,
228 	TLS_DH_RSA_WITH_AES_256_CBC_SHA		= 0X0037,
229 	TLS_DHE_DSS_WITH_AES_256_CBC_SHA	= 0X0038,
230 	TLS_DHE_RSA_WITH_AES_256_CBC_SHA	= 0X0039,
231 	TLS_DH_anon_WITH_AES_256_CBC_SHA	= 0X003A,
232 	CipherMax
233 };
234 
235 // compression methods
236 enum {
237 	CompressionNull = 0,
238 	CompressionMax
239 };
240 
241 static Algs cipherAlgs[] = {
242 	{"rc4_128", "md5",	2 * (16 + MD5dlen), TLS_RSA_WITH_RC4_128_MD5},
243 	{"rc4_128", "sha1",	2 * (16 + SHA1dlen), TLS_RSA_WITH_RC4_128_SHA},
244 	{"3des_ede_cbc","sha1",2*(4*8+SHA1dlen), TLS_RSA_WITH_3DES_EDE_CBC_SHA},
245 };
246 
247 static uchar compressors[] = {
248 	CompressionNull,
249 };
250 
251 static TlsConnection *tlsServer2(int ctl, int hand, uchar *cert, int ncert, int (*trace)(char*fmt, ...), PEMChain *chain);
252 static TlsConnection *tlsClient2(int ctl, int hand, uchar *csid, int ncsid, int (*trace)(char*fmt, ...));
253 
254 static void	msgClear(Msg *m);
255 static char* msgPrint(char *buf, int n, Msg *m);
256 static int	msgRecv(TlsConnection *c, Msg *m);
257 static int	msgSend(TlsConnection *c, Msg *m, int act);
258 static void	tlsError(TlsConnection *c, int err, char *msg, ...);
259 #pragma	varargck argpos	tlsError 3
260 static int setVersion(TlsConnection *c, int version);
261 static int finishedMatch(TlsConnection *c, Finished *f);
262 static void tlsConnectionFree(TlsConnection *c);
263 
264 static int setAlgs(TlsConnection *c, int a);
265 static int okCipher(Ints *cv);
266 static int okCompression(Bytes *cv);
267 static int initCiphers(void);
268 static Ints* makeciphers(void);
269 
270 static TlsSec* tlsSecInits(int cvers, uchar *csid, int ncsid, uchar *crandom, uchar *ssid, int *nssid, uchar *srandom);
271 static int	tlsSecSecrets(TlsSec *sec, int vers, uchar *epm, int nepm, uchar *kd, int nkd);
272 static TlsSec*	tlsSecInitc(int cvers, uchar *crandom);
273 static int	tlsSecSecretc(TlsSec *sec, uchar *sid, int nsid, uchar *srandom, uchar *cert, int ncert, int vers, uchar **epm, int *nepm, uchar *kd, int nkd);
274 static int	tlsSecFinished(TlsSec *sec, MD5state md5, SHAstate sha1, uchar *fin, int nfin, int isclient);
275 static void	tlsSecOk(TlsSec *sec);
276 static void	tlsSecKill(TlsSec *sec);
277 static void	tlsSecClose(TlsSec *sec);
278 static void	setMasterSecret(TlsSec *sec, Bytes *pm);
279 static void	serverMasterSecret(TlsSec *sec, uchar *epm, int nepm);
280 static void	setSecrets(TlsSec *sec, uchar *kd, int nkd);
281 static int	clientMasterSecret(TlsSec *sec, RSApub *pub, uchar **epm, int *nepm);
282 static Bytes *pkcs1_encrypt(Bytes* data, RSApub* key, int blocktype);
283 static Bytes *pkcs1_decrypt(TlsSec *sec, uchar *epm, int nepm);
284 static void	tlsSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient);
285 static void	sslSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient);
286 static void	sslPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label,
287 			uchar *seed0, int nseed0, uchar *seed1, int nseed1);
288 static int setVers(TlsSec *sec, int version);
289 
290 static AuthRpc* factotum_rsa_open(uchar *cert, int certlen);
291 static mpint* factotum_rsa_decrypt(AuthRpc *rpc, mpint *cipher);
292 static void factotum_rsa_close(AuthRpc*rpc);
293 
294 static void* emalloc(int);
295 static void* erealloc(void*, int);
296 static void put32(uchar *p, u32int);
297 static void put24(uchar *p, int);
298 static void put16(uchar *p, int);
299 static u32int get32(uchar *p);
300 static int get24(uchar *p);
301 static int get16(uchar *p);
302 static Bytes* newbytes(int len);
303 static Bytes* makebytes(uchar* buf, int len);
304 static void freebytes(Bytes* b);
305 static Ints* newints(int len);
306 static Ints* makeints(int* buf, int len);
307 static void freeints(Ints* b);
308 
309 //================= client/server ========================
310 
311 //	push TLS onto fd, returning new (application) file descriptor
312 //		or -1 if error.
313 int
314 tlsServer(int fd, TLSconn *conn)
315 {
316 	char buf[8];
317 	char dname[64];
318 	int n, data, ctl, hand;
319 	TlsConnection *tls;
320 
321 	if(conn == nil)
322 		return -1;
323 	ctl = open("#a/tls/clone", ORDWR);
324 	if(ctl < 0)
325 		return -1;
326 	n = read(ctl, buf, sizeof(buf)-1);
327 	if(n < 0){
328 		close(ctl);
329 		return -1;
330 	}
331 	buf[n] = 0;
332 	sprint(conn->dir, "#a/tls/%s", buf);
333 	sprint(dname, "#a/tls/%s/hand", buf);
334 	hand = open(dname, ORDWR);
335 	if(hand < 0){
336 		close(ctl);
337 		return -1;
338 	}
339 	fprint(ctl, "fd %d 0x%x", fd, ProtocolVersion);
340 	tls = tlsServer2(ctl, hand, conn->cert, conn->certlen, conn->trace, conn->chain);
341 	sprint(dname, "#a/tls/%s/data", buf);
342 	data = open(dname, ORDWR);
343 	close(fd);
344 	close(hand);
345 	close(ctl);
346 	if(data < 0){
347 		return -1;
348 	}
349 	if(tls == nil){
350 		close(data);
351 		return -1;
352 	}
353 	if(conn->cert)
354 		free(conn->cert);
355 	conn->cert = 0;  // client certificates are not yet implemented
356 	conn->certlen = 0;
357 	conn->sessionIDlen = tls->sid->len;
358 	conn->sessionID = emalloc(conn->sessionIDlen);
359 	memcpy(conn->sessionID, tls->sid->data, conn->sessionIDlen);
360 	tlsConnectionFree(tls);
361 	return data;
362 }
363 
364 //	push TLS onto fd, returning new (application) file descriptor
365 //		or -1 if error.
366 int
367 tlsClient(int fd, TLSconn *conn)
368 {
369 	char buf[8];
370 	char dname[64];
371 	int n, data, ctl, hand;
372 	TlsConnection *tls;
373 
374 	if(!conn)
375 		return -1;
376 	ctl = open("#a/tls/clone", ORDWR);
377 	if(ctl < 0)
378 		return -1;
379 	n = read(ctl, buf, sizeof(buf)-1);
380 	if(n < 0){
381 		close(ctl);
382 		return -1;
383 	}
384 	buf[n] = 0;
385 	sprint(conn->dir, "#a/tls/%s", buf);
386 	sprint(dname, "#a/tls/%s/hand", buf);
387 	hand = open(dname, ORDWR);
388 	if(hand < 0){
389 		close(ctl);
390 		return -1;
391 	}
392 	sprint(dname, "#a/tls/%s/data", buf);
393 	data = open(dname, ORDWR);
394 	if(data < 0)
395 		return -1;
396 	fprint(ctl, "fd %d 0x%x", fd, ProtocolVersion);
397 	tls = tlsClient2(ctl, hand, conn->sessionID, conn->sessionIDlen, conn->trace);
398 	close(fd);
399 	close(hand);
400 	close(ctl);
401 	if(tls == nil){
402 		close(data);
403 		return -1;
404 	}
405 	conn->certlen = tls->cert->len;
406 	conn->cert = emalloc(conn->certlen);
407 	memcpy(conn->cert, tls->cert->data, conn->certlen);
408 	conn->sessionIDlen = tls->sid->len;
409 	conn->sessionID = emalloc(conn->sessionIDlen);
410 	memcpy(conn->sessionID, tls->sid->data, conn->sessionIDlen);
411 	tlsConnectionFree(tls);
412 	return data;
413 }
414 
415 static int
416 countchain(PEMChain *p)
417 {
418 	int i = 0;
419 
420 	while (p) {
421 		i++;
422 		p = p->next;
423 	}
424 	return i;
425 }
426 
427 static TlsConnection *
428 tlsServer2(int ctl, int hand, uchar *cert, int ncert, int (*trace)(char*fmt, ...), PEMChain *chp)
429 {
430 	TlsConnection *c;
431 	Msg m;
432 	Bytes *csid;
433 	uchar sid[SidSize], kd[MaxKeyData];
434 	char *secrets;
435 	int cipher, compressor, nsid, rv, numcerts, i;
436 
437 	if(trace)
438 		trace("tlsServer2\n");
439 	if(!initCiphers())
440 		return nil;
441 	c = emalloc(sizeof(TlsConnection));
442 	c->ctl = ctl;
443 	c->hand = hand;
444 	c->trace = trace;
445 	c->version = ProtocolVersion;
446 
447 	memset(&m, 0, sizeof(m));
448 	if(!msgRecv(c, &m)){
449 		if(trace)
450 			trace("initial msgRecv failed\n");
451 		goto Err;
452 	}
453 	if(m.tag != HClientHello) {
454 		tlsError(c, EUnexpectedMessage, "expected a client hello");
455 		goto Err;
456 	}
457 	c->clientVersion = m.u.clientHello.version;
458 	if(trace)
459 		trace("ClientHello version %x\n", c->clientVersion);
460 	if(setVersion(c, m.u.clientHello.version) < 0) {
461 		tlsError(c, EIllegalParameter, "incompatible version");
462 		goto Err;
463 	}
464 
465 	memmove(c->crandom, m.u.clientHello.random, RandomSize);
466 	cipher = okCipher(m.u.clientHello.ciphers);
467 	if(cipher < 0) {
468 		// reply with EInsufficientSecurity if we know that's the case
469 		if(cipher == -2)
470 			tlsError(c, EInsufficientSecurity, "cipher suites too weak");
471 		else
472 			tlsError(c, EHandshakeFailure, "no matching cipher suite");
473 		goto Err;
474 	}
475 	if(!setAlgs(c, cipher)){
476 		tlsError(c, EHandshakeFailure, "no matching cipher suite");
477 		goto Err;
478 	}
479 	compressor = okCompression(m.u.clientHello.compressors);
480 	if(compressor < 0) {
481 		tlsError(c, EHandshakeFailure, "no matching compressor");
482 		goto Err;
483 	}
484 
485 	csid = m.u.clientHello.sid;
486 	if(trace)
487 		trace("  cipher %d, compressor %d, csidlen %d\n", cipher, compressor, csid->len);
488 	c->sec = tlsSecInits(c->clientVersion, csid->data, csid->len, c->crandom, sid, &nsid, c->srandom);
489 	if(c->sec == nil){
490 		tlsError(c, EHandshakeFailure, "can't initialize security: %r");
491 		goto Err;
492 	}
493 	c->sec->rpc = factotum_rsa_open(cert, ncert);
494 	if(c->sec->rpc == nil){
495 		tlsError(c, EHandshakeFailure, "factotum_rsa_open: %r");
496 		goto Err;
497 	}
498 	c->sec->rsapub = X509toRSApub(cert, ncert, nil, 0);
499 	msgClear(&m);
500 
501 	m.tag = HServerHello;
502 	m.u.serverHello.version = c->version;
503 	memmove(m.u.serverHello.random, c->srandom, RandomSize);
504 	m.u.serverHello.cipher = cipher;
505 	m.u.serverHello.compressor = compressor;
506 	c->sid = makebytes(sid, nsid);
507 	m.u.serverHello.sid = makebytes(c->sid->data, c->sid->len);
508 	if(!msgSend(c, &m, AQueue))
509 		goto Err;
510 	msgClear(&m);
511 
512 	m.tag = HCertificate;
513 	numcerts = countchain(chp);
514 	m.u.certificate.ncert = 1 + numcerts;
515 	m.u.certificate.certs = emalloc(m.u.certificate.ncert * sizeof(Bytes));
516 	m.u.certificate.certs[0] = makebytes(cert, ncert);
517 	for (i = 0; i < numcerts && chp; i++, chp = chp->next)
518 		m.u.certificate.certs[i+1] = makebytes(chp->pem, chp->pemlen);
519 	if(!msgSend(c, &m, AQueue))
520 		goto Err;
521 	msgClear(&m);
522 
523 	m.tag = HServerHelloDone;
524 	if(!msgSend(c, &m, AFlush))
525 		goto Err;
526 	msgClear(&m);
527 
528 	if(!msgRecv(c, &m))
529 		goto Err;
530 	if(m.tag != HClientKeyExchange) {
531 		tlsError(c, EUnexpectedMessage, "expected a client key exchange");
532 		goto Err;
533 	}
534 	if(tlsSecSecrets(c->sec, c->version, m.u.clientKeyExchange.key->data, m.u.clientKeyExchange.key->len, kd, c->nsecret) < 0){
535 		tlsError(c, EHandshakeFailure, "couldn't set secrets: %r");
536 		goto Err;
537 	}
538 	if(trace)
539 		trace("tls secrets\n");
540 	secrets = (char*)emalloc(2*c->nsecret);
541 	enc64(secrets, 2*c->nsecret, kd, c->nsecret);
542 	rv = fprint(c->ctl, "secret %s %s 0 %s", c->digest, c->enc, secrets);
543 	memset(secrets, 0, 2*c->nsecret);
544 	free(secrets);
545 	memset(kd, 0, c->nsecret);
546 	if(rv < 0){
547 		tlsError(c, EHandshakeFailure, "can't set keys: %r");
548 		goto Err;
549 	}
550 	msgClear(&m);
551 
552 	/* no CertificateVerify; skip to Finished */
553 	if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 1) < 0){
554 		tlsError(c, EInternalError, "can't set finished: %r");
555 		goto Err;
556 	}
557 	if(!msgRecv(c, &m))
558 		goto Err;
559 	if(m.tag != HFinished) {
560 		tlsError(c, EUnexpectedMessage, "expected a finished");
561 		goto Err;
562 	}
563 	if(!finishedMatch(c, &m.u.finished)) {
564 		tlsError(c, EHandshakeFailure, "finished verification failed");
565 		goto Err;
566 	}
567 	msgClear(&m);
568 
569 	/* change cipher spec */
570 	if(fprint(c->ctl, "changecipher") < 0){
571 		tlsError(c, EInternalError, "can't enable cipher: %r");
572 		goto Err;
573 	}
574 
575 	if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 0) < 0){
576 		tlsError(c, EInternalError, "can't set finished: %r");
577 		goto Err;
578 	}
579 	m.tag = HFinished;
580 	m.u.finished = c->finished;
581 	if(!msgSend(c, &m, AFlush))
582 		goto Err;
583 	msgClear(&m);
584 	if(trace)
585 		trace("tls finished\n");
586 
587 	if(fprint(c->ctl, "opened") < 0)
588 		goto Err;
589 	tlsSecOk(c->sec);
590 	return c;
591 
592 Err:
593 	msgClear(&m);
594 	tlsConnectionFree(c);
595 	return 0;
596 }
597 
598 static TlsConnection *
599 tlsClient2(int ctl, int hand, uchar *csid, int ncsid, int (*trace)(char*fmt, ...))
600 {
601 	TlsConnection *c;
602 	Msg m;
603 	uchar kd[MaxKeyData], *epm;
604 	char *secrets;
605 	int creq, nepm, rv;
606 
607 	if(!initCiphers())
608 		return nil;
609 	epm = nil;
610 	c = emalloc(sizeof(TlsConnection));
611 	c->version = ProtocolVersion;
612 	c->ctl = ctl;
613 	c->hand = hand;
614 	c->trace = trace;
615 	c->isClient = 1;
616 	c->clientVersion = c->version;
617 
618 	c->sec = tlsSecInitc(c->clientVersion, c->crandom);
619 	if(c->sec == nil)
620 		goto Err;
621 
622 	/* client hello */
623 	memset(&m, 0, sizeof(m));
624 	m.tag = HClientHello;
625 	m.u.clientHello.version = c->clientVersion;
626 	memmove(m.u.clientHello.random, c->crandom, RandomSize);
627 	m.u.clientHello.sid = makebytes(csid, ncsid);
628 	m.u.clientHello.ciphers = makeciphers();
629 	m.u.clientHello.compressors = makebytes(compressors,sizeof(compressors));
630 	if(!msgSend(c, &m, AFlush))
631 		goto Err;
632 	msgClear(&m);
633 
634 	/* server hello */
635 	if(!msgRecv(c, &m))
636 		goto Err;
637 	if(m.tag != HServerHello) {
638 		tlsError(c, EUnexpectedMessage, "expected a server hello");
639 		goto Err;
640 	}
641 	if(setVersion(c, m.u.serverHello.version) < 0) {
642 		tlsError(c, EIllegalParameter, "incompatible version %r");
643 		goto Err;
644 	}
645 	memmove(c->srandom, m.u.serverHello.random, RandomSize);
646 	c->sid = makebytes(m.u.serverHello.sid->data, m.u.serverHello.sid->len);
647 	if(c->sid->len != 0 && c->sid->len != SidSize) {
648 		tlsError(c, EIllegalParameter, "invalid server session identifier");
649 		goto Err;
650 	}
651 	if(!setAlgs(c, m.u.serverHello.cipher)) {
652 		tlsError(c, EIllegalParameter, "invalid cipher suite");
653 		goto Err;
654 	}
655 	if(m.u.serverHello.compressor != CompressionNull) {
656 		tlsError(c, EIllegalParameter, "invalid compression");
657 		goto Err;
658 	}
659 	msgClear(&m);
660 
661 	/* certificate */
662 	if(!msgRecv(c, &m) || m.tag != HCertificate) {
663 		tlsError(c, EUnexpectedMessage, "expected a certificate");
664 		goto Err;
665 	}
666 	if(m.u.certificate.ncert < 1) {
667 		tlsError(c, EIllegalParameter, "runt certificate");
668 		goto Err;
669 	}
670 	c->cert = makebytes(m.u.certificate.certs[0]->data, m.u.certificate.certs[0]->len);
671 	msgClear(&m);
672 
673 	/* server key exchange (optional) */
674 	if(!msgRecv(c, &m))
675 		goto Err;
676 	if(m.tag == HServerKeyExchange) {
677 		tlsError(c, EUnexpectedMessage, "got an server key exchange");
678 		goto Err;
679 		// If implementing this later, watch out for rollback attack
680 		// described in Wagner Schneier 1996, section 4.4.
681 	}
682 
683 	/* certificate request (optional) */
684 	creq = 0;
685 	if(m.tag == HCertificateRequest) {
686 		creq = 1;
687 		msgClear(&m);
688 		if(!msgRecv(c, &m))
689 			goto Err;
690 	}
691 
692 	if(m.tag != HServerHelloDone) {
693 		tlsError(c, EUnexpectedMessage, "expected a server hello done");
694 		goto Err;
695 	}
696 	msgClear(&m);
697 
698 	if(tlsSecSecretc(c->sec, c->sid->data, c->sid->len, c->srandom,
699 			c->cert->data, c->cert->len, c->version, &epm, &nepm,
700 			kd, c->nsecret) < 0){
701 		tlsError(c, EBadCertificate, "invalid x509/rsa certificate");
702 		goto Err;
703 	}
704 	secrets = (char*)emalloc(2*c->nsecret);
705 	enc64(secrets, 2*c->nsecret, kd, c->nsecret);
706 	rv = fprint(c->ctl, "secret %s %s 1 %s", c->digest, c->enc, secrets);
707 	memset(secrets, 0, 2*c->nsecret);
708 	free(secrets);
709 	memset(kd, 0, c->nsecret);
710 	if(rv < 0){
711 		tlsError(c, EHandshakeFailure, "can't set keys: %r");
712 		goto Err;
713 	}
714 
715 	if(creq) {
716 		/* send a zero length certificate */
717 		m.tag = HCertificate;
718 		if(!msgSend(c, &m, AFlush))
719 			goto Err;
720 		msgClear(&m);
721 	}
722 
723 	/* client key exchange */
724 	m.tag = HClientKeyExchange;
725 	m.u.clientKeyExchange.key = makebytes(epm, nepm);
726 	free(epm);
727 	epm = nil;
728 	if(m.u.clientKeyExchange.key == nil) {
729 		tlsError(c, EHandshakeFailure, "can't set secret: %r");
730 		goto Err;
731 	}
732 	if(!msgSend(c, &m, AFlush))
733 		goto Err;
734 	msgClear(&m);
735 
736 	/* change cipher spec */
737 	if(fprint(c->ctl, "changecipher") < 0){
738 		tlsError(c, EInternalError, "can't enable cipher: %r");
739 		goto Err;
740 	}
741 
742 	// Cipherchange must occur immediately before Finished to avoid
743 	// potential hole;  see section 4.3 of Wagner Schneier 1996.
744 	if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 1) < 0){
745 		tlsError(c, EInternalError, "can't set finished 1: %r");
746 		goto Err;
747 	}
748 	m.tag = HFinished;
749 	m.u.finished = c->finished;
750 
751 	if(!msgSend(c, &m, AFlush)) {
752 		fprint(2, "tlsClient nepm=%d\n", nepm);
753 		tlsError(c, EInternalError, "can't flush after client Finished: %r");
754 		goto Err;
755 	}
756 	msgClear(&m);
757 
758 	if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 0) < 0){
759 		fprint(2, "tlsClient nepm=%d\n", nepm);
760 		tlsError(c, EInternalError, "can't set finished 0: %r");
761 		goto Err;
762 	}
763 	if(!msgRecv(c, &m)) {
764 		fprint(2, "tlsClient nepm=%d\n", nepm);
765 		tlsError(c, EInternalError, "can't read server Finished: %r");
766 		goto Err;
767 	}
768 	if(m.tag != HFinished) {
769 		fprint(2, "tlsClient nepm=%d\n", nepm);
770 		tlsError(c, EUnexpectedMessage, "expected a Finished msg from server");
771 		goto Err;
772 	}
773 
774 	if(!finishedMatch(c, &m.u.finished)) {
775 		tlsError(c, EHandshakeFailure, "finished verification failed");
776 		goto Err;
777 	}
778 	msgClear(&m);
779 
780 	if(fprint(c->ctl, "opened") < 0){
781 		if(trace)
782 			trace("unable to do final open: %r\n");
783 		goto Err;
784 	}
785 	tlsSecOk(c->sec);
786 	return c;
787 
788 Err:
789 	free(epm);
790 	msgClear(&m);
791 	tlsConnectionFree(c);
792 	return 0;
793 }
794 
795 
796 //================= message functions ========================
797 
798 static uchar sendbuf[9000], *sendp;
799 
800 static int
801 msgSend(TlsConnection *c, Msg *m, int act)
802 {
803 	uchar *p; // sendp = start of new message;  p = write pointer
804 	int nn, n, i;
805 
806 	if(sendp == nil)
807 		sendp = sendbuf;
808 	p = sendp;
809 	if(c->trace)
810 		c->trace("send %s", msgPrint((char*)p, (sizeof sendbuf) - (p-sendbuf), m));
811 
812 	p[0] = m->tag;	// header - fill in size later
813 	p += 4;
814 
815 	switch(m->tag) {
816 	default:
817 		tlsError(c, EInternalError, "can't encode a %d", m->tag);
818 		goto Err;
819 	case HClientHello:
820 		// version
821 		put16(p, m->u.clientHello.version);
822 		p += 2;
823 
824 		// random
825 		memmove(p, m->u.clientHello.random, RandomSize);
826 		p += RandomSize;
827 
828 		// sid
829 		n = m->u.clientHello.sid->len;
830 		assert(n < 256);
831 		p[0] = n;
832 		memmove(p+1, m->u.clientHello.sid->data, n);
833 		p += n+1;
834 
835 		n = m->u.clientHello.ciphers->len;
836 		assert(n > 0 && n < 200);
837 		put16(p, n*2);
838 		p += 2;
839 		for(i=0; i<n; i++) {
840 			put16(p, m->u.clientHello.ciphers->data[i]);
841 			p += 2;
842 		}
843 
844 		n = m->u.clientHello.compressors->len;
845 		assert(n > 0);
846 		p[0] = n;
847 		memmove(p+1, m->u.clientHello.compressors->data, n);
848 		p += n+1;
849 		break;
850 	case HServerHello:
851 		put16(p, m->u.serverHello.version);
852 		p += 2;
853 
854 		// random
855 		memmove(p, m->u.serverHello.random, RandomSize);
856 		p += RandomSize;
857 
858 		// sid
859 		n = m->u.serverHello.sid->len;
860 		assert(n < 256);
861 		p[0] = n;
862 		memmove(p+1, m->u.serverHello.sid->data, n);
863 		p += n+1;
864 
865 		put16(p, m->u.serverHello.cipher);
866 		p += 2;
867 		p[0] = m->u.serverHello.compressor;
868 		p += 1;
869 		break;
870 	case HServerHelloDone:
871 		break;
872 	case HCertificate:
873 		nn = 0;
874 		for(i = 0; i < m->u.certificate.ncert; i++)
875 			nn += 3 + m->u.certificate.certs[i]->len;
876 		if(p + 3 + nn - sendbuf > sizeof(sendbuf)) {
877 			tlsError(c, EInternalError, "output buffer too small for certificate");
878 			goto Err;
879 		}
880 		put24(p, nn);
881 		p += 3;
882 		for(i = 0; i < m->u.certificate.ncert; i++){
883 			put24(p, m->u.certificate.certs[i]->len);
884 			p += 3;
885 			memmove(p, m->u.certificate.certs[i]->data, m->u.certificate.certs[i]->len);
886 			p += m->u.certificate.certs[i]->len;
887 		}
888 		break;
889 	case HClientKeyExchange:
890 		n = m->u.clientKeyExchange.key->len;
891 		if(c->version != SSL3Version){
892 			put16(p, n);
893 			p += 2;
894 		}
895 		memmove(p, m->u.clientKeyExchange.key->data, n);
896 		p += n;
897 		break;
898 	case HFinished:
899 		memmove(p, m->u.finished.verify, m->u.finished.n);
900 		p += m->u.finished.n;
901 		break;
902 	}
903 
904 	// go back and fill in size
905 	n = p-sendp;
906 	assert(p <= sendbuf+sizeof(sendbuf));
907 	put24(sendp+1, n-4);
908 
909 	// remember hash of Handshake messages
910 	if(m->tag != HHelloRequest) {
911 		md5(sendp, n, 0, &c->hsmd5);
912 		sha1(sendp, n, 0, &c->hssha1);
913 	}
914 
915 	sendp = p;
916 	if(act == AFlush){
917 		sendp = sendbuf;
918 		if(write(c->hand, sendbuf, p-sendbuf) < 0){
919 			fprint(2, "write error: %r\n");
920 			goto Err;
921 		}
922 	}
923 	msgClear(m);
924 	return 1;
925 Err:
926 	msgClear(m);
927 	return 0;
928 }
929 
930 static uchar*
931 tlsReadN(TlsConnection *c, int n)
932 {
933 	uchar *p;
934 	int nn, nr;
935 
936 	nn = c->ep - c->rp;
937 	if(nn < n){
938 		if(c->rp != c->buf){
939 			memmove(c->buf, c->rp, nn);
940 			c->rp = c->buf;
941 			c->ep = &c->buf[nn];
942 		}
943 		for(; nn < n; nn += nr) {
944 			nr = read(c->hand, &c->rp[nn], n - nn);
945 			if(nr <= 0)
946 				return nil;
947 			c->ep += nr;
948 		}
949 	}
950 	p = c->rp;
951 	c->rp += n;
952 	return p;
953 }
954 
955 static int
956 msgRecv(TlsConnection *c, Msg *m)
957 {
958 	uchar *p;
959 	int type, n, nn, i, nsid, nrandom, nciph;
960 
961 	for(;;) {
962 		p = tlsReadN(c, 4);
963 		if(p == nil)
964 			return 0;
965 		type = p[0];
966 		n = get24(p+1);
967 
968 		if(type != HHelloRequest)
969 			break;
970 		if(n != 0) {
971 			tlsError(c, EDecodeError, "invalid hello request during handshake");
972 			return 0;
973 		}
974 	}
975 
976 	if(n > sizeof(c->buf)) {
977 		tlsError(c, EDecodeError, "handshake message too long %d %d", n, sizeof(c->buf));
978 		return 0;
979 	}
980 
981 	if(type == HSSL2ClientHello){
982 		/* Cope with an SSL3 ClientHello expressed in SSL2 record format.
983 			This is sent by some clients that we must interoperate
984 			with, such as Java's JSSE and Microsoft's Internet Explorer. */
985 		p = tlsReadN(c, n);
986 		if(p == nil)
987 			return 0;
988 		md5(p, n, 0, &c->hsmd5);
989 		sha1(p, n, 0, &c->hssha1);
990 		m->tag = HClientHello;
991 		if(n < 22)
992 			goto Short;
993 		m->u.clientHello.version = get16(p+1);
994 		p += 3;
995 		n -= 3;
996 		nn = get16(p); /* cipher_spec_len */
997 		nsid = get16(p + 2);
998 		nrandom = get16(p + 4);
999 		p += 6;
1000 		n -= 6;
1001 		if(nsid != 0 	/* no sid's, since shouldn't restart using ssl2 header */
1002 				|| nrandom < 16 || nn % 3)
1003 			goto Err;
1004 		if(c->trace && (n - nrandom != nn))
1005 			c->trace("n-nrandom!=nn: n=%d nrandom=%d nn=%d\n", n, nrandom, nn);
1006 		/* ignore ssl2 ciphers and look for {0x00, ssl3 cipher} */
1007 		nciph = 0;
1008 		for(i = 0; i < nn; i += 3)
1009 			if(p[i] == 0)
1010 				nciph++;
1011 		m->u.clientHello.ciphers = newints(nciph);
1012 		nciph = 0;
1013 		for(i = 0; i < nn; i += 3)
1014 			if(p[i] == 0)
1015 				m->u.clientHello.ciphers->data[nciph++] = get16(&p[i + 1]);
1016 		p += nn;
1017 		m->u.clientHello.sid = makebytes(nil, 0);
1018 		if(nrandom > RandomSize)
1019 			nrandom = RandomSize;
1020 		memset(m->u.clientHello.random, 0, RandomSize - nrandom);
1021 		memmove(&m->u.clientHello.random[RandomSize - nrandom], p, nrandom);
1022 		m->u.clientHello.compressors = newbytes(1);
1023 		m->u.clientHello.compressors->data[0] = CompressionNull;
1024 		goto Ok;
1025 	}
1026 
1027 	md5(p, 4, 0, &c->hsmd5);
1028 	sha1(p, 4, 0, &c->hssha1);
1029 
1030 	p = tlsReadN(c, n);
1031 	if(p == nil)
1032 		return 0;
1033 
1034 	md5(p, n, 0, &c->hsmd5);
1035 	sha1(p, n, 0, &c->hssha1);
1036 
1037 	m->tag = type;
1038 
1039 	switch(type) {
1040 	default:
1041 		tlsError(c, EUnexpectedMessage, "can't decode a %d", type);
1042 		goto Err;
1043 	case HClientHello:
1044 		if(n < 2)
1045 			goto Short;
1046 		m->u.clientHello.version = get16(p);
1047 		p += 2;
1048 		n -= 2;
1049 
1050 		if(n < RandomSize)
1051 			goto Short;
1052 		memmove(m->u.clientHello.random, p, RandomSize);
1053 		p += RandomSize;
1054 		n -= RandomSize;
1055 		if(n < 1 || n < p[0]+1)
1056 			goto Short;
1057 		m->u.clientHello.sid = makebytes(p+1, p[0]);
1058 		p += m->u.clientHello.sid->len+1;
1059 		n -= m->u.clientHello.sid->len+1;
1060 
1061 		if(n < 2)
1062 			goto Short;
1063 		nn = get16(p);
1064 		p += 2;
1065 		n -= 2;
1066 
1067 		if((nn & 1) || n < nn || nn < 2)
1068 			goto Short;
1069 		m->u.clientHello.ciphers = newints(nn >> 1);
1070 		for(i = 0; i < nn; i += 2)
1071 			m->u.clientHello.ciphers->data[i >> 1] = get16(&p[i]);
1072 		p += nn;
1073 		n -= nn;
1074 
1075 		if(n < 1 || n < p[0]+1 || p[0] == 0)
1076 			goto Short;
1077 		nn = p[0];
1078 		m->u.clientHello.compressors = newbytes(nn);
1079 		memmove(m->u.clientHello.compressors->data, p+1, nn);
1080 		n -= nn + 1;
1081 		break;
1082 	case HServerHello:
1083 		if(n < 2)
1084 			goto Short;
1085 		m->u.serverHello.version = get16(p);
1086 		p += 2;
1087 		n -= 2;
1088 
1089 		if(n < RandomSize)
1090 			goto Short;
1091 		memmove(m->u.serverHello.random, p, RandomSize);
1092 		p += RandomSize;
1093 		n -= RandomSize;
1094 
1095 		if(n < 1 || n < p[0]+1)
1096 			goto Short;
1097 		m->u.serverHello.sid = makebytes(p+1, p[0]);
1098 		p += m->u.serverHello.sid->len+1;
1099 		n -= m->u.serverHello.sid->len+1;
1100 
1101 		if(n < 3)
1102 			goto Short;
1103 		m->u.serverHello.cipher = get16(p);
1104 		m->u.serverHello.compressor = p[2];
1105 		n -= 3;
1106 		break;
1107 	case HCertificate:
1108 		if(n < 3)
1109 			goto Short;
1110 		nn = get24(p);
1111 		p += 3;
1112 		n -= 3;
1113 		if(n != nn)
1114 			goto Short;
1115 		/* certs */
1116 		i = 0;
1117 		while(n > 0) {
1118 			if(n < 3)
1119 				goto Short;
1120 			nn = get24(p);
1121 			p += 3;
1122 			n -= 3;
1123 			if(nn > n)
1124 				goto Short;
1125 			m->u.certificate.ncert = i+1;
1126 			m->u.certificate.certs = erealloc(m->u.certificate.certs, (i+1)*sizeof(Bytes));
1127 			m->u.certificate.certs[i] = makebytes(p, nn);
1128 			p += nn;
1129 			n -= nn;
1130 			i++;
1131 		}
1132 		break;
1133 	case HCertificateRequest:
1134 		if(n < 2)
1135 			goto Short;
1136 		nn = get16(p);
1137 		p += 2;
1138 		n -= 2;
1139 		if(nn < 1 || nn > n)
1140 			goto Short;
1141 		m->u.certificateRequest.types = makebytes(p, nn);
1142 		nn = get24(p);
1143 		p += 3;
1144 		n -= 3;
1145 		if(nn == 0 || n != nn)
1146 			goto Short;
1147 		/* cas */
1148 		i = 0;
1149 		while(n > 0) {
1150 			if(n < 2)
1151 				goto Short;
1152 			nn = get16(p);
1153 			p += 2;
1154 			n -= 2;
1155 			if(nn < 1 || nn > n)
1156 				goto Short;
1157 			m->u.certificateRequest.nca = i+1;
1158 			m->u.certificateRequest.cas = erealloc(m->u.certificateRequest.cas, (i+1)*sizeof(Bytes));
1159 			m->u.certificateRequest.cas[i] = makebytes(p, nn);
1160 			p += nn;
1161 			n -= nn;
1162 			i++;
1163 		}
1164 		break;
1165 	case HServerHelloDone:
1166 		break;
1167 	case HClientKeyExchange:
1168 		/*
1169 		 * this message depends upon the encryption selected
1170 		 * assume rsa.
1171 		 */
1172 		if(c->version == SSL3Version)
1173 			nn = n;
1174 		else{
1175 			if(n < 2)
1176 				goto Short;
1177 			nn = get16(p);
1178 			p += 2;
1179 			n -= 2;
1180 		}
1181 		if(n < nn)
1182 			goto Short;
1183 		m->u.clientKeyExchange.key = makebytes(p, nn);
1184 		n -= nn;
1185 		break;
1186 	case HFinished:
1187 		m->u.finished.n = c->finished.n;
1188 		if(n < m->u.finished.n)
1189 			goto Short;
1190 		memmove(m->u.finished.verify, p, m->u.finished.n);
1191 		n -= m->u.finished.n;
1192 		break;
1193 	}
1194 
1195 	if(type != HClientHello && n != 0)
1196 		goto Short;
1197 Ok:
1198 	if(c->trace){
1199 		char *buf;
1200 		buf = emalloc(8000);
1201 		c->trace("recv %s", msgPrint(buf, 8000, m));
1202 		free(buf);
1203 	}
1204 	return 1;
1205 Short:
1206 	tlsError(c, EDecodeError, "handshake message has invalid length");
1207 Err:
1208 	msgClear(m);
1209 	return 0;
1210 }
1211 
1212 static void
1213 msgClear(Msg *m)
1214 {
1215 	int i;
1216 
1217 	switch(m->tag) {
1218 	default:
1219 		sysfatal("msgClear: unknown message type: %d\n", m->tag);
1220 	case HHelloRequest:
1221 		break;
1222 	case HClientHello:
1223 		freebytes(m->u.clientHello.sid);
1224 		freeints(m->u.clientHello.ciphers);
1225 		freebytes(m->u.clientHello.compressors);
1226 		break;
1227 	case HServerHello:
1228 		freebytes(m->u.clientHello.sid);
1229 		break;
1230 	case HCertificate:
1231 		for(i=0; i<m->u.certificate.ncert; i++)
1232 			freebytes(m->u.certificate.certs[i]);
1233 		free(m->u.certificate.certs);
1234 		break;
1235 	case HCertificateRequest:
1236 		freebytes(m->u.certificateRequest.types);
1237 		for(i=0; i<m->u.certificateRequest.nca; i++)
1238 			freebytes(m->u.certificateRequest.cas[i]);
1239 		free(m->u.certificateRequest.cas);
1240 		break;
1241 	case HServerHelloDone:
1242 		break;
1243 	case HClientKeyExchange:
1244 		freebytes(m->u.clientKeyExchange.key);
1245 		break;
1246 	case HFinished:
1247 		break;
1248 	}
1249 	memset(m, 0, sizeof(Msg));
1250 }
1251 
1252 static char *
1253 bytesPrint(char *bs, char *be, char *s0, Bytes *b, char *s1)
1254 {
1255 	int i;
1256 
1257 	if(s0)
1258 		bs = seprint(bs, be, "%s", s0);
1259 	bs = seprint(bs, be, "[");
1260 	if(b == nil)
1261 		bs = seprint(bs, be, "nil");
1262 	else
1263 		for(i=0; i<b->len; i++)
1264 			bs = seprint(bs, be, "%.2x ", b->data[i]);
1265 	bs = seprint(bs, be, "]");
1266 	if(s1)
1267 		bs = seprint(bs, be, "%s", s1);
1268 	return bs;
1269 }
1270 
1271 static char *
1272 intsPrint(char *bs, char *be, char *s0, Ints *b, char *s1)
1273 {
1274 	int i;
1275 
1276 	if(s0)
1277 		bs = seprint(bs, be, "%s", s0);
1278 	bs = seprint(bs, be, "[");
1279 	if(b == nil)
1280 		bs = seprint(bs, be, "nil");
1281 	else
1282 		for(i=0; i<b->len; i++)
1283 			bs = seprint(bs, be, "%x ", b->data[i]);
1284 	bs = seprint(bs, be, "]");
1285 	if(s1)
1286 		bs = seprint(bs, be, "%s", s1);
1287 	return bs;
1288 }
1289 
1290 static char*
1291 msgPrint(char *buf, int n, Msg *m)
1292 {
1293 	int i;
1294 	char *bs = buf, *be = buf+n;
1295 
1296 	switch(m->tag) {
1297 	default:
1298 		bs = seprint(bs, be, "unknown %d\n", m->tag);
1299 		break;
1300 	case HClientHello:
1301 		bs = seprint(bs, be, "ClientHello\n");
1302 		bs = seprint(bs, be, "\tversion: %.4x\n", m->u.clientHello.version);
1303 		bs = seprint(bs, be, "\trandom: ");
1304 		for(i=0; i<RandomSize; i++)
1305 			bs = seprint(bs, be, "%.2x", m->u.clientHello.random[i]);
1306 		bs = seprint(bs, be, "\n");
1307 		bs = bytesPrint(bs, be, "\tsid: ", m->u.clientHello.sid, "\n");
1308 		bs = intsPrint(bs, be, "\tciphers: ", m->u.clientHello.ciphers, "\n");
1309 		bs = bytesPrint(bs, be, "\tcompressors: ", m->u.clientHello.compressors, "\n");
1310 		break;
1311 	case HServerHello:
1312 		bs = seprint(bs, be, "ServerHello\n");
1313 		bs = seprint(bs, be, "\tversion: %.4x\n", m->u.serverHello.version);
1314 		bs = seprint(bs, be, "\trandom: ");
1315 		for(i=0; i<RandomSize; i++)
1316 			bs = seprint(bs, be, "%.2x", m->u.serverHello.random[i]);
1317 		bs = seprint(bs, be, "\n");
1318 		bs = bytesPrint(bs, be, "\tsid: ", m->u.serverHello.sid, "\n");
1319 		bs = seprint(bs, be, "\tcipher: %.4x\n", m->u.serverHello.cipher);
1320 		bs = seprint(bs, be, "\tcompressor: %.2x\n", m->u.serverHello.compressor);
1321 		break;
1322 	case HCertificate:
1323 		bs = seprint(bs, be, "Certificate\n");
1324 		for(i=0; i<m->u.certificate.ncert; i++)
1325 			bs = bytesPrint(bs, be, "\t", m->u.certificate.certs[i], "\n");
1326 		break;
1327 	case HCertificateRequest:
1328 		bs = seprint(bs, be, "CertificateRequest\n");
1329 		bs = bytesPrint(bs, be, "\ttypes: ", m->u.certificateRequest.types, "\n");
1330 		bs = seprint(bs, be, "\tcertificateauthorities\n");
1331 		for(i=0; i<m->u.certificateRequest.nca; i++)
1332 			bs = bytesPrint(bs, be, "\t\t", m->u.certificateRequest.cas[i], "\n");
1333 		break;
1334 	case HServerHelloDone:
1335 		bs = seprint(bs, be, "ServerHelloDone\n");
1336 		break;
1337 	case HClientKeyExchange:
1338 		bs = seprint(bs, be, "HClientKeyExchange\n");
1339 		bs = bytesPrint(bs, be, "\tkey: ", m->u.clientKeyExchange.key, "\n");
1340 		break;
1341 	case HFinished:
1342 		bs = seprint(bs, be, "HFinished\n");
1343 		for(i=0; i<m->u.finished.n; i++)
1344 			bs = seprint(bs, be, "%.2x", m->u.finished.verify[i]);
1345 		bs = seprint(bs, be, "\n");
1346 		break;
1347 	}
1348 	USED(bs);
1349 	return buf;
1350 }
1351 
1352 static void
1353 tlsError(TlsConnection *c, int err, char *fmt, ...)
1354 {
1355 	char msg[512];
1356 	va_list arg;
1357 
1358 	va_start(arg, fmt);
1359 	vseprint(msg, msg+sizeof(msg), fmt, arg);
1360 	va_end(arg);
1361 	if(c->trace)
1362 		c->trace("tlsError: %s\n", msg);
1363 	else if(c->erred)
1364 		fprint(2, "double error: %r, %s", msg);
1365 	else
1366 		werrstr("tls: local %s", msg);
1367 	c->erred = 1;
1368 	fprint(c->ctl, "alert %d", err);
1369 }
1370 
1371 // commit to specific version number
1372 static int
1373 setVersion(TlsConnection *c, int version)
1374 {
1375 	if(c->verset || version > MaxProtoVersion || version < MinProtoVersion)
1376 		return -1;
1377 	if(version > c->version)
1378 		version = c->version;
1379 	if(version == SSL3Version) {
1380 		c->version = version;
1381 		c->finished.n = SSL3FinishedLen;
1382 	}else if(version == TLSVersion){
1383 		c->version = version;
1384 		c->finished.n = TLSFinishedLen;
1385 	}else
1386 		return -1;
1387 	c->verset = 1;
1388 	return fprint(c->ctl, "version 0x%x", version);
1389 }
1390 
1391 // confirm that received Finished message matches the expected value
1392 static int
1393 finishedMatch(TlsConnection *c, Finished *f)
1394 {
1395 	return memcmp(f->verify, c->finished.verify, f->n) == 0;
1396 }
1397 
1398 // free memory associated with TlsConnection struct
1399 //		(but don't close the TLS channel itself)
1400 static void
1401 tlsConnectionFree(TlsConnection *c)
1402 {
1403 	tlsSecClose(c->sec);
1404 	freebytes(c->sid);
1405 	freebytes(c->cert);
1406 	memset(c, 0, sizeof(c));
1407 	free(c);
1408 }
1409 
1410 
1411 //================= cipher choices ========================
1412 
1413 static int weakCipher[CipherMax] =
1414 {
1415 	1,	/* TLS_NULL_WITH_NULL_NULL */
1416 	1,	/* TLS_RSA_WITH_NULL_MD5 */
1417 	1,	/* TLS_RSA_WITH_NULL_SHA */
1418 	1,	/* TLS_RSA_EXPORT_WITH_RC4_40_MD5 */
1419 	0,	/* TLS_RSA_WITH_RC4_128_MD5 */
1420 	0,	/* TLS_RSA_WITH_RC4_128_SHA */
1421 	1,	/* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 */
1422 	0,	/* TLS_RSA_WITH_IDEA_CBC_SHA */
1423 	1,	/* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA */
1424 	0,	/* TLS_RSA_WITH_DES_CBC_SHA */
1425 	0,	/* TLS_RSA_WITH_3DES_EDE_CBC_SHA */
1426 	1,	/* TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA */
1427 	0,	/* TLS_DH_DSS_WITH_DES_CBC_SHA */
1428 	0,	/* TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA */
1429 	1,	/* TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA */
1430 	0,	/* TLS_DH_RSA_WITH_DES_CBC_SHA */
1431 	0,	/* TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA */
1432 	1,	/* TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA */
1433 	0,	/* TLS_DHE_DSS_WITH_DES_CBC_SHA */
1434 	0,	/* TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA */
1435 	1,	/* TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA */
1436 	0,	/* TLS_DHE_RSA_WITH_DES_CBC_SHA */
1437 	0,	/* TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA */
1438 	1,	/* TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 */
1439 	1,	/* TLS_DH_anon_WITH_RC4_128_MD5 */
1440 	1,	/* TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA */
1441 	1,	/* TLS_DH_anon_WITH_DES_CBC_SHA */
1442 	1,	/* TLS_DH_anon_WITH_3DES_EDE_CBC_SHA */
1443 };
1444 
1445 static int
1446 setAlgs(TlsConnection *c, int a)
1447 {
1448 	int i;
1449 
1450 	for(i = 0; i < nelem(cipherAlgs); i++){
1451 		if(cipherAlgs[i].tlsid == a){
1452 			c->enc = cipherAlgs[i].enc;
1453 			c->digest = cipherAlgs[i].digest;
1454 			c->nsecret = cipherAlgs[i].nsecret;
1455 			if(c->nsecret > MaxKeyData)
1456 				return 0;
1457 			return 1;
1458 		}
1459 	}
1460 	return 0;
1461 }
1462 
1463 static int
1464 okCipher(Ints *cv)
1465 {
1466 	int weak, i, j, c;
1467 
1468 	weak = 1;
1469 	for(i = 0; i < cv->len; i++) {
1470 		c = cv->data[i];
1471 		if(c >= CipherMax)
1472 			weak = 0;
1473 		else
1474 			weak &= weakCipher[c];
1475 		for(j = 0; j < nelem(cipherAlgs); j++)
1476 			if(cipherAlgs[j].ok && cipherAlgs[j].tlsid == c)
1477 				return c;
1478 	}
1479 	if(weak)
1480 		return -2;
1481 	return -1;
1482 }
1483 
1484 static int
1485 okCompression(Bytes *cv)
1486 {
1487 	int i, j, c;
1488 
1489 	for(i = 0; i < cv->len; i++) {
1490 		c = cv->data[i];
1491 		for(j = 0; j < nelem(compressors); j++) {
1492 			if(compressors[j] == c)
1493 				return c;
1494 		}
1495 	}
1496 	return -1;
1497 }
1498 
1499 static Lock	ciphLock;
1500 static int	nciphers;
1501 
1502 static int
1503 initCiphers(void)
1504 {
1505 	enum {MaxAlgF = 1024, MaxAlgs = 10};
1506 	char s[MaxAlgF], *flds[MaxAlgs];
1507 	int i, j, n, ok;
1508 
1509 	lock(&ciphLock);
1510 	if(nciphers){
1511 		unlock(&ciphLock);
1512 		return nciphers;
1513 	}
1514 	j = open("#a/tls/encalgs", OREAD);
1515 	if(j < 0){
1516 		werrstr("can't open #a/tls/encalgs: %r");
1517 		return 0;
1518 	}
1519 	n = read(j, s, MaxAlgF-1);
1520 	close(j);
1521 	if(n <= 0){
1522 		werrstr("nothing in #a/tls/encalgs: %r");
1523 		return 0;
1524 	}
1525 	s[n] = 0;
1526 	n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
1527 	for(i = 0; i < nelem(cipherAlgs); i++){
1528 		ok = 0;
1529 		for(j = 0; j < n; j++){
1530 			if(strcmp(cipherAlgs[i].enc, flds[j]) == 0){
1531 				ok = 1;
1532 				break;
1533 			}
1534 		}
1535 		cipherAlgs[i].ok = ok;
1536 	}
1537 
1538 	j = open("#a/tls/hashalgs", OREAD);
1539 	if(j < 0){
1540 		werrstr("can't open #a/tls/hashalgs: %r");
1541 		return 0;
1542 	}
1543 	n = read(j, s, MaxAlgF-1);
1544 	close(j);
1545 	if(n <= 0){
1546 		werrstr("nothing in #a/tls/hashalgs: %r");
1547 		return 0;
1548 	}
1549 	s[n] = 0;
1550 	n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
1551 	for(i = 0; i < nelem(cipherAlgs); i++){
1552 		ok = 0;
1553 		for(j = 0; j < n; j++){
1554 			if(strcmp(cipherAlgs[i].digest, flds[j]) == 0){
1555 				ok = 1;
1556 				break;
1557 			}
1558 		}
1559 		cipherAlgs[i].ok &= ok;
1560 		if(cipherAlgs[i].ok)
1561 			nciphers++;
1562 	}
1563 	unlock(&ciphLock);
1564 	return nciphers;
1565 }
1566 
1567 static Ints*
1568 makeciphers(void)
1569 {
1570 	Ints *is;
1571 	int i, j;
1572 
1573 	is = newints(nciphers);
1574 	j = 0;
1575 	for(i = 0; i < nelem(cipherAlgs); i++){
1576 		if(cipherAlgs[i].ok)
1577 			is->data[j++] = cipherAlgs[i].tlsid;
1578 	}
1579 	return is;
1580 }
1581 
1582 
1583 
1584 //================= security functions ========================
1585 
1586 // given X.509 certificate, set up connection to factotum
1587 //	for using corresponding private key
1588 static AuthRpc*
1589 factotum_rsa_open(uchar *cert, int certlen)
1590 {
1591 	int afd;
1592 	char *s;
1593 	mpint *pub = nil;
1594 	RSApub *rsapub;
1595 	AuthRpc *rpc;
1596 
1597 	// start talking to factotum
1598 	if((afd = open("/mnt/factotum/rpc", ORDWR)) < 0)
1599 		return nil;
1600 	if((rpc = auth_allocrpc(afd)) == nil){
1601 		close(afd);
1602 		return nil;
1603 	}
1604 	s = "proto=rsa service=tls role=client";
1605 	if(auth_rpc(rpc, "start", s, strlen(s)) != ARok){
1606 		factotum_rsa_close(rpc);
1607 		return nil;
1608 	}
1609 
1610 	// roll factotum keyring around to match certificate
1611 	rsapub = X509toRSApub(cert, certlen, nil, 0);
1612 	while(1){
1613 		if(auth_rpc(rpc, "read", nil, 0) != ARok){
1614 			factotum_rsa_close(rpc);
1615 			rpc = nil;
1616 			goto done;
1617 		}
1618 		pub = strtomp(rpc->arg, nil, 16, nil);
1619 		assert(pub != nil);
1620 		if(mpcmp(pub,rsapub->n) == 0)
1621 			break;
1622 	}
1623 done:
1624 	mpfree(pub);
1625 	rsapubfree(rsapub);
1626 	return rpc;
1627 }
1628 
1629 static mpint*
1630 factotum_rsa_decrypt(AuthRpc *rpc, mpint *cipher)
1631 {
1632 	char *p;
1633 	int rv;
1634 
1635 	if((p = mptoa(cipher, 16, nil, 0)) == nil)
1636 		return nil;
1637 	rv = auth_rpc(rpc, "write", p, strlen(p));
1638 	free(p);
1639 	if(rv != ARok || auth_rpc(rpc, "read", nil, 0) != ARok)
1640 		return nil;
1641 	mpfree(cipher);
1642 	return strtomp(rpc->arg, nil, 16, nil);
1643 }
1644 
1645 static void
1646 factotum_rsa_close(AuthRpc*rpc)
1647 {
1648 	if(!rpc)
1649 		return;
1650 	close(rpc->afd);
1651 	auth_freerpc(rpc);
1652 }
1653 
1654 static void
1655 tlsPmd5(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1656 {
1657 	uchar ai[MD5dlen], tmp[MD5dlen];
1658 	int i, n;
1659 	MD5state *s;
1660 
1661 	// generate a1
1662 	s = hmac_md5(label, nlabel, key, nkey, nil, nil);
1663 	s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
1664 	hmac_md5(seed1, nseed1, key, nkey, ai, s);
1665 
1666 	while(nbuf > 0) {
1667 		s = hmac_md5(ai, MD5dlen, key, nkey, nil, nil);
1668 		s = hmac_md5(label, nlabel, key, nkey, nil, s);
1669 		s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
1670 		hmac_md5(seed1, nseed1, key, nkey, tmp, s);
1671 		n = MD5dlen;
1672 		if(n > nbuf)
1673 			n = nbuf;
1674 		for(i = 0; i < n; i++)
1675 			buf[i] ^= tmp[i];
1676 		buf += n;
1677 		nbuf -= n;
1678 		hmac_md5(ai, MD5dlen, key, nkey, tmp, nil);
1679 		memmove(ai, tmp, MD5dlen);
1680 	}
1681 }
1682 
1683 static void
1684 tlsPsha1(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1685 {
1686 	uchar ai[SHA1dlen], tmp[SHA1dlen];
1687 	int i, n;
1688 	SHAstate *s;
1689 
1690 	// generate a1
1691 	s = hmac_sha1(label, nlabel, key, nkey, nil, nil);
1692 	s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
1693 	hmac_sha1(seed1, nseed1, key, nkey, ai, s);
1694 
1695 	while(nbuf > 0) {
1696 		s = hmac_sha1(ai, SHA1dlen, key, nkey, nil, nil);
1697 		s = hmac_sha1(label, nlabel, key, nkey, nil, s);
1698 		s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
1699 		hmac_sha1(seed1, nseed1, key, nkey, tmp, s);
1700 		n = SHA1dlen;
1701 		if(n > nbuf)
1702 			n = nbuf;
1703 		for(i = 0; i < n; i++)
1704 			buf[i] ^= tmp[i];
1705 		buf += n;
1706 		nbuf -= n;
1707 		hmac_sha1(ai, SHA1dlen, key, nkey, tmp, nil);
1708 		memmove(ai, tmp, SHA1dlen);
1709 	}
1710 }
1711 
1712 // fill buf with md5(args)^sha1(args)
1713 static void
1714 tlsPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1715 {
1716 	int i;
1717 	int nlabel = strlen(label);
1718 	int n = (nkey + 1) >> 1;
1719 
1720 	for(i = 0; i < nbuf; i++)
1721 		buf[i] = 0;
1722 	tlsPmd5(buf, nbuf, key, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
1723 	tlsPsha1(buf, nbuf, key+nkey-n, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
1724 }
1725 
1726 /*
1727  * for setting server session id's
1728  */
1729 static Lock	sidLock;
1730 static long	maxSid = 1;
1731 
1732 /* the keys are verified to have the same public components
1733  * and to function correctly with pkcs 1 encryption and decryption. */
1734 static TlsSec*
1735 tlsSecInits(int cvers, uchar *csid, int ncsid, uchar *crandom, uchar *ssid, int *nssid, uchar *srandom)
1736 {
1737 	TlsSec *sec = emalloc(sizeof(*sec));
1738 
1739 	USED(csid); USED(ncsid);  // ignore csid for now
1740 
1741 	memmove(sec->crandom, crandom, RandomSize);
1742 	sec->clientVers = cvers;
1743 
1744 	put32(sec->srandom, time(0));
1745 	genrandom(sec->srandom+4, RandomSize-4);
1746 	memmove(srandom, sec->srandom, RandomSize);
1747 
1748 	/*
1749 	 * make up a unique sid: use our pid, and and incrementing id
1750 	 * can signal no sid by setting nssid to 0.
1751 	 */
1752 	memset(ssid, 0, SidSize);
1753 	put32(ssid, getpid());
1754 	lock(&sidLock);
1755 	put32(ssid+4, maxSid++);
1756 	unlock(&sidLock);
1757 	*nssid = SidSize;
1758 	return sec;
1759 }
1760 
1761 static int
1762 tlsSecSecrets(TlsSec *sec, int vers, uchar *epm, int nepm, uchar *kd, int nkd)
1763 {
1764 	if(epm != nil){
1765 		if(setVers(sec, vers) < 0)
1766 			goto Err;
1767 		serverMasterSecret(sec, epm, nepm);
1768 	}else if(sec->vers != vers){
1769 		werrstr("mismatched session versions");
1770 		goto Err;
1771 	}
1772 	setSecrets(sec, kd, nkd);
1773 	return 0;
1774 Err:
1775 	sec->ok = -1;
1776 	return -1;
1777 }
1778 
1779 static TlsSec*
1780 tlsSecInitc(int cvers, uchar *crandom)
1781 {
1782 	TlsSec *sec = emalloc(sizeof(*sec));
1783 	sec->clientVers = cvers;
1784 	put32(sec->crandom, time(0));
1785 	genrandom(sec->crandom+4, RandomSize-4);
1786 	memmove(crandom, sec->crandom, RandomSize);
1787 	return sec;
1788 }
1789 
1790 static int
1791 tlsSecSecretc(TlsSec *sec, uchar *sid, int nsid, uchar *srandom, uchar *cert, int ncert, int vers, uchar **epm, int *nepm, uchar *kd, int nkd)
1792 {
1793 	RSApub *pub;
1794 
1795 	pub = nil;
1796 
1797 	USED(sid);
1798 	USED(nsid);
1799 
1800 	memmove(sec->srandom, srandom, RandomSize);
1801 
1802 	if(setVers(sec, vers) < 0)
1803 		goto Err;
1804 
1805 	pub = X509toRSApub(cert, ncert, nil, 0);
1806 	if(pub == nil){
1807 		werrstr("invalid x509/rsa certificate");
1808 		goto Err;
1809 	}
1810 	if(clientMasterSecret(sec, pub, epm, nepm) < 0)
1811 		goto Err;
1812 	rsapubfree(pub);
1813 	setSecrets(sec, kd, nkd);
1814 	return 0;
1815 
1816 Err:
1817 	if(pub != nil)
1818 		rsapubfree(pub);
1819 	sec->ok = -1;
1820 	return -1;
1821 }
1822 
1823 static int
1824 tlsSecFinished(TlsSec *sec, MD5state md5, SHAstate sha1, uchar *fin, int nfin, int isclient)
1825 {
1826 	if(sec->nfin != nfin){
1827 		sec->ok = -1;
1828 		werrstr("invalid finished exchange");
1829 		return -1;
1830 	}
1831 	md5.malloced = 0;
1832 	sha1.malloced = 0;
1833 	(*sec->setFinished)(sec, md5, sha1, fin, isclient);
1834 	return 1;
1835 }
1836 
1837 static void
1838 tlsSecOk(TlsSec *sec)
1839 {
1840 	if(sec->ok == 0)
1841 		sec->ok = 1;
1842 }
1843 
1844 static void
1845 tlsSecKill(TlsSec *sec)
1846 {
1847 	if(!sec)
1848 		return;
1849 	factotum_rsa_close(sec->rpc);
1850 	sec->ok = -1;
1851 }
1852 
1853 static void
1854 tlsSecClose(TlsSec *sec)
1855 {
1856 	if(!sec)
1857 		return;
1858 	factotum_rsa_close(sec->rpc);
1859 	free(sec->server);
1860 	free(sec);
1861 }
1862 
1863 static int
1864 setVers(TlsSec *sec, int v)
1865 {
1866 	if(v == SSL3Version){
1867 		sec->setFinished = sslSetFinished;
1868 		sec->nfin = SSL3FinishedLen;
1869 		sec->prf = sslPRF;
1870 	}else if(v == TLSVersion){
1871 		sec->setFinished = tlsSetFinished;
1872 		sec->nfin = TLSFinishedLen;
1873 		sec->prf = tlsPRF;
1874 	}else{
1875 		werrstr("invalid version");
1876 		return -1;
1877 	}
1878 	sec->vers = v;
1879 	return 0;
1880 }
1881 
1882 /*
1883  * generate secret keys from the master secret.
1884  *
1885  * different crypto selections will require different amounts
1886  * of key expansion and use of key expansion data,
1887  * but it's all generated using the same function.
1888  */
1889 static void
1890 setSecrets(TlsSec *sec, uchar *kd, int nkd)
1891 {
1892 	(*sec->prf)(kd, nkd, sec->sec, MasterSecretSize, "key expansion",
1893 			sec->srandom, RandomSize, sec->crandom, RandomSize);
1894 }
1895 
1896 /*
1897  * set the master secret from the pre-master secret.
1898  */
1899 static void
1900 setMasterSecret(TlsSec *sec, Bytes *pm)
1901 {
1902 	(*sec->prf)(sec->sec, MasterSecretSize, pm->data, MasterSecretSize, "master secret",
1903 			sec->crandom, RandomSize, sec->srandom, RandomSize);
1904 }
1905 
1906 static void
1907 serverMasterSecret(TlsSec *sec, uchar *epm, int nepm)
1908 {
1909 	Bytes *pm;
1910 
1911 	pm = pkcs1_decrypt(sec, epm, nepm);
1912 
1913 	// if the client messed up, just continue as if everything is ok,
1914 	// to prevent attacks to check for correctly formatted messages.
1915 	// Hence the fprint(2,) can't be replaced by tlsError(), which sends an Alert msg to the client.
1916 	if(sec->ok < 0 || pm == nil || get16(pm->data) != sec->clientVers){
1917 		fprint(2, "serverMasterSecret failed ok=%d pm=%p pmvers=%x cvers=%x nepm=%d\n",
1918 			sec->ok, pm, pm ? get16(pm->data) : -1, sec->clientVers, nepm);
1919 		sec->ok = -1;
1920 		if(pm != nil)
1921 			freebytes(pm);
1922 		pm = newbytes(MasterSecretSize);
1923 		genrandom(pm->data, MasterSecretSize);
1924 	}
1925 	setMasterSecret(sec, pm);
1926 	memset(pm->data, 0, pm->len);
1927 	freebytes(pm);
1928 }
1929 
1930 static int
1931 clientMasterSecret(TlsSec *sec, RSApub *pub, uchar **epm, int *nepm)
1932 {
1933 	Bytes *pm, *key;
1934 
1935 	pm = newbytes(MasterSecretSize);
1936 	put16(pm->data, sec->clientVers);
1937 	genrandom(pm->data+2, MasterSecretSize - 2);
1938 
1939 	setMasterSecret(sec, pm);
1940 
1941 	key = pkcs1_encrypt(pm, pub, 2);
1942 	memset(pm->data, 0, pm->len);
1943 	freebytes(pm);
1944 	if(key == nil){
1945 		werrstr("tls pkcs1_encrypt failed");
1946 		return -1;
1947 	}
1948 
1949 	*nepm = key->len;
1950 	*epm = malloc(*nepm);
1951 	if(*epm == nil){
1952 		freebytes(key);
1953 		werrstr("out of memory");
1954 		return -1;
1955 	}
1956 	memmove(*epm, key->data, *nepm);
1957 
1958 	freebytes(key);
1959 
1960 	return 1;
1961 }
1962 
1963 static void
1964 sslSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
1965 {
1966 	DigestState *s;
1967 	uchar h0[MD5dlen], h1[SHA1dlen], pad[48];
1968 	char *label;
1969 
1970 	if(isClient)
1971 		label = "CLNT";
1972 	else
1973 		label = "SRVR";
1974 
1975 	md5((uchar*)label, 4, nil, &hsmd5);
1976 	md5(sec->sec, MasterSecretSize, nil, &hsmd5);
1977 	memset(pad, 0x36, 48);
1978 	md5(pad, 48, nil, &hsmd5);
1979 	md5(nil, 0, h0, &hsmd5);
1980 	memset(pad, 0x5C, 48);
1981 	s = md5(sec->sec, MasterSecretSize, nil, nil);
1982 	s = md5(pad, 48, nil, s);
1983 	md5(h0, MD5dlen, finished, s);
1984 
1985 	sha1((uchar*)label, 4, nil, &hssha1);
1986 	sha1(sec->sec, MasterSecretSize, nil, &hssha1);
1987 	memset(pad, 0x36, 40);
1988 	sha1(pad, 40, nil, &hssha1);
1989 	sha1(nil, 0, h1, &hssha1);
1990 	memset(pad, 0x5C, 40);
1991 	s = sha1(sec->sec, MasterSecretSize, nil, nil);
1992 	s = sha1(pad, 40, nil, s);
1993 	sha1(h1, SHA1dlen, finished + MD5dlen, s);
1994 }
1995 
1996 // fill "finished" arg with md5(args)^sha1(args)
1997 static void
1998 tlsSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
1999 {
2000 	uchar h0[MD5dlen], h1[SHA1dlen];
2001 	char *label;
2002 
2003 	// get current hash value, but allow further messages to be hashed in
2004 	md5(nil, 0, h0, &hsmd5);
2005 	sha1(nil, 0, h1, &hssha1);
2006 
2007 	if(isClient)
2008 		label = "client finished";
2009 	else
2010 		label = "server finished";
2011 	tlsPRF(finished, TLSFinishedLen, sec->sec, MasterSecretSize, label, h0, MD5dlen, h1, SHA1dlen);
2012 }
2013 
2014 static void
2015 sslPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
2016 {
2017 	DigestState *s;
2018 	uchar sha1dig[SHA1dlen], md5dig[MD5dlen], tmp[26];
2019 	int i, n, len;
2020 
2021 	USED(label);
2022 	len = 1;
2023 	while(nbuf > 0){
2024 		if(len > 26)
2025 			return;
2026 		for(i = 0; i < len; i++)
2027 			tmp[i] = 'A' - 1 + len;
2028 		s = sha1(tmp, len, nil, nil);
2029 		s = sha1(key, nkey, nil, s);
2030 		s = sha1(seed0, nseed0, nil, s);
2031 		sha1(seed1, nseed1, sha1dig, s);
2032 		s = md5(key, nkey, nil, nil);
2033 		md5(sha1dig, SHA1dlen, md5dig, s);
2034 		n = MD5dlen;
2035 		if(n > nbuf)
2036 			n = nbuf;
2037 		memmove(buf, md5dig, n);
2038 		buf += n;
2039 		nbuf -= n;
2040 		len++;
2041 	}
2042 }
2043 
2044 static mpint*
2045 bytestomp(Bytes* bytes)
2046 {
2047 	mpint* ans;
2048 
2049 	ans = betomp(bytes->data, bytes->len, nil);
2050 	return ans;
2051 }
2052 
2053 /*
2054  * Convert mpint* to Bytes, putting high order byte first.
2055  */
2056 static Bytes*
2057 mptobytes(mpint* big)
2058 {
2059 	int n, m;
2060 	uchar *a;
2061 	Bytes* ans;
2062 
2063 	n = (mpsignif(big)+7)/8;
2064 	m = mptobe(big, nil, n, &a);
2065 	ans = makebytes(a, m);
2066 	return ans;
2067 }
2068 
2069 // Do RSA computation on block according to key, and pad
2070 // result on left with zeros to make it modlen long.
2071 static Bytes*
2072 rsacomp(Bytes* block, RSApub* key, int modlen)
2073 {
2074 	mpint *x, *y;
2075 	Bytes *a, *ybytes;
2076 	int ylen;
2077 
2078 	x = bytestomp(block);
2079 	y = rsaencrypt(key, x, nil);
2080 	mpfree(x);
2081 	ybytes = mptobytes(y);
2082 	ylen = ybytes->len;
2083 
2084 	if(ylen < modlen) {
2085 		a = newbytes(modlen);
2086 		memset(a->data, 0, modlen-ylen);
2087 		memmove(a->data+modlen-ylen, ybytes->data, ylen);
2088 		freebytes(ybytes);
2089 		ybytes = a;
2090 	}
2091 	else if(ylen > modlen) {
2092 		// assume it has leading zeros (mod should make it so)
2093 		a = newbytes(modlen);
2094 		memmove(a->data, ybytes->data, modlen);
2095 		freebytes(ybytes);
2096 		ybytes = a;
2097 	}
2098 	mpfree(y);
2099 	return ybytes;
2100 }
2101 
2102 // encrypt data according to PKCS#1, /lib/rfc/rfc2437 9.1.2.1
2103 static Bytes*
2104 pkcs1_encrypt(Bytes* data, RSApub* key, int blocktype)
2105 {
2106 	Bytes *pad, *eb, *ans;
2107 	int i, dlen, padlen, modlen;
2108 
2109 	modlen = (mpsignif(key->n)+7)/8;
2110 	dlen = data->len;
2111 	if(modlen < 12 || dlen > modlen - 11)
2112 		return nil;
2113 	padlen = modlen - 3 - dlen;
2114 	pad = newbytes(padlen);
2115 	genrandom(pad->data, padlen);
2116 	for(i = 0; i < padlen; i++) {
2117 		if(blocktype == 0)
2118 			pad->data[i] = 0;
2119 		else if(blocktype == 1)
2120 			pad->data[i] = 255;
2121 		else if(pad->data[i] == 0)
2122 			pad->data[i] = 1;
2123 	}
2124 	eb = newbytes(modlen);
2125 	eb->data[0] = 0;
2126 	eb->data[1] = blocktype;
2127 	memmove(eb->data+2, pad->data, padlen);
2128 	eb->data[padlen+2] = 0;
2129 	memmove(eb->data+padlen+3, data->data, dlen);
2130 	ans = rsacomp(eb, key, modlen);
2131 	freebytes(eb);
2132 	freebytes(pad);
2133 	return ans;
2134 }
2135 
2136 // decrypt data according to PKCS#1, with given key.
2137 // expect a block type of 2.
2138 static Bytes*
2139 pkcs1_decrypt(TlsSec *sec, uchar *epm, int nepm)
2140 {
2141 	Bytes *eb, *ans = nil;
2142 	int i, modlen;
2143 	mpint *x, *y;
2144 
2145 	modlen = (mpsignif(sec->rsapub->n)+7)/8;
2146 	if(nepm != modlen)
2147 		return nil;
2148 	x = betomp(epm, nepm, nil);
2149 	y = factotum_rsa_decrypt(sec->rpc, x);
2150 	if(y == nil)
2151 		return nil;
2152 	eb = mptobytes(y);
2153 	if(eb->len < modlen){ // pad on left with zeros
2154 		ans = newbytes(modlen);
2155 		memset(ans->data, 0, modlen-eb->len);
2156 		memmove(ans->data+modlen-eb->len, eb->data, eb->len);
2157 		freebytes(eb);
2158 		eb = ans;
2159 	}
2160 	if(eb->data[0] == 0 && eb->data[1] == 2) {
2161 		for(i = 2; i < modlen; i++)
2162 			if(eb->data[i] == 0)
2163 				break;
2164 		if(i < modlen - 1)
2165 			ans = makebytes(eb->data+i+1, modlen-(i+1));
2166 	}
2167 	freebytes(eb);
2168 	return ans;
2169 }
2170 
2171 
2172 //================= general utility functions ========================
2173 
2174 static void *
2175 emalloc(int n)
2176 {
2177 	void *p;
2178 	if(n==0)
2179 		n=1;
2180 	p = malloc(n);
2181 	if(p == nil){
2182 		exits("out of memory");
2183 	}
2184 	memset(p, 0, n);
2185 	return p;
2186 }
2187 
2188 static void *
2189 erealloc(void *ReallocP, int ReallocN)
2190 {
2191 	if(ReallocN == 0)
2192 		ReallocN = 1;
2193 	if(!ReallocP)
2194 		ReallocP = emalloc(ReallocN);
2195 	else if(!(ReallocP = realloc(ReallocP, ReallocN))){
2196 		exits("out of memory");
2197 	}
2198 	return(ReallocP);
2199 }
2200 
2201 static void
2202 put32(uchar *p, u32int x)
2203 {
2204 	p[0] = x>>24;
2205 	p[1] = x>>16;
2206 	p[2] = x>>8;
2207 	p[3] = x;
2208 }
2209 
2210 static void
2211 put24(uchar *p, int x)
2212 {
2213 	p[0] = x>>16;
2214 	p[1] = x>>8;
2215 	p[2] = x;
2216 }
2217 
2218 static void
2219 put16(uchar *p, int x)
2220 {
2221 	p[0] = x>>8;
2222 	p[1] = x;
2223 }
2224 
2225 static u32int
2226 get32(uchar *p)
2227 {
2228 	return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
2229 }
2230 
2231 static int
2232 get24(uchar *p)
2233 {
2234 	return (p[0]<<16)|(p[1]<<8)|p[2];
2235 }
2236 
2237 static int
2238 get16(uchar *p)
2239 {
2240 	return (p[0]<<8)|p[1];
2241 }
2242 
2243 /* ANSI offsetof() */
2244 #define OFFSET(x, s) ((int)(&(((s*)0)->x)))
2245 
2246 /*
2247  * malloc and return a new Bytes structure capable of
2248  * holding len bytes. (len >= 0)
2249  * Used to use crypt_malloc, which aborts if malloc fails.
2250  */
2251 static Bytes*
2252 newbytes(int len)
2253 {
2254 	Bytes* ans;
2255 
2256 	ans = (Bytes*)malloc(OFFSET(data[0], Bytes) + len);
2257 	ans->len = len;
2258 	return ans;
2259 }
2260 
2261 /*
2262  * newbytes(len), with data initialized from buf
2263  */
2264 static Bytes*
2265 makebytes(uchar* buf, int len)
2266 {
2267 	Bytes* ans;
2268 
2269 	ans = newbytes(len);
2270 	memmove(ans->data, buf, len);
2271 	return ans;
2272 }
2273 
2274 static void
2275 freebytes(Bytes* b)
2276 {
2277 	if(b != nil)
2278 		free(b);
2279 }
2280 
2281 /* len is number of ints */
2282 static Ints*
2283 newints(int len)
2284 {
2285 	Ints* ans;
2286 
2287 	ans = (Ints*)malloc(OFFSET(data[0], Ints) + len*sizeof(int));
2288 	ans->len = len;
2289 	return ans;
2290 }
2291 
2292 static Ints*
2293 makeints(int* buf, int len)
2294 {
2295 	Ints* ans;
2296 
2297 	ans = newints(len);
2298 	if(len > 0)
2299 		memmove(ans->data, buf, len*sizeof(int));
2300 	return ans;
2301 }
2302 
2303 static void
2304 freeints(Ints* b)
2305 {
2306 	if(b != nil)
2307 		free(b);
2308 }
2309