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. */
19 SSL3FinishedLen = MD5dlen+SHA1dlen,
20 MaxKeyData = 104, /* amount of secret we may need */
24 MasterSecretSize = 48,
29 typedef struct TlsSec TlsSec;
33 uchar data[1]; /* [len] */
38 int data[1]; /* [len] */
49 typedef struct Finished{
50 uchar verify[SSL3FinishedLen];
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 */
67 int state; /* must be set using setstate */
69 /* input buffer for handshake messages */
70 uchar buf[MaxChunk+2048];
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 */
80 /* for finished messages */
81 MD5state hsmd5; /* handshake hash */
82 SHAstate hssha1; /* handshake hash */
91 uchar random[RandomSize];
98 uchar random[RandomSize];
111 } certificateRequest;
120 char *server; /* name of remote; nil for server */
121 int ok; /* <0 killed; ==0 in progress; >0 reusable */
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);
138 SSL3Version = 0x0300,
139 ProtocolVersion = 0x0301, /* maximum version we speak */
140 MinProtoVersion = 0x0300, /* limits on version we accept */
141 MaxProtoVersion = 0x03ff
149 HSSL2ClientHello = 9, /* local convention; see devtls.c */
163 EUnexpectedMessage = 10,
165 EDecryptionFailed = 21,
166 ERecordOverflow = 22,
167 EDecompressionFailure = 30,
168 EHandshakeFailure = 40,
170 EBadCertificate = 42,
171 EUnsupportedCertificate = 43,
172 ECertificateRevoked = 44,
173 ECertificateExpired = 45,
174 ECertificateUnknown = 46,
175 EIllegalParameter = 47,
180 EExportRestriction = 60,
181 EProtocolVersion = 70,
182 EInsufficientSecurity = 71,
185 ENoRenegotiation = 100,
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,
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,
235 /* compression methods */
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},
247 static uchar compressors[] = {
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, ...));
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);
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);
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);
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);
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);
309 /*================= client/server ======================== */
311 /* push TLS onto fd, returning new (application) file descriptor */
312 /* or -1 if error. */
314 tlsServer(int fd, TLSconn *conn)
318 int n, data, ctl, hand;
323 ctl = open("#a/tls/clone", ORDWR);
326 n = read(ctl, buf, sizeof(buf)-1);
332 sprint(conn->dir, "#a/tls/%s", buf);
333 sprint(dname, "#a/tls/%s/hand", buf);
334 hand = open(dname, ORDWR);
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);
355 conn->cert = 0; /* client certificates are not yet implemented */
357 conn->sessionIDlen = tls->sid->len;
358 conn->sessionID = emalloc(conn->sessionIDlen);
359 memcpy(conn->sessionID, tls->sid->data, conn->sessionIDlen);
360 tlsConnectionFree(tls);
364 /* push TLS onto fd, returning new (application) file descriptor */
365 /* or -1 if error. */
367 tlsClient(int fd, TLSconn *conn)
371 int n, data, ctl, hand;
376 ctl = open("#a/tls/clone", ORDWR);
379 n = read(ctl, buf, sizeof(buf)-1);
385 sprint(conn->dir, "#a/tls/%s", buf);
386 sprint(dname, "#a/tls/%s/hand", buf);
387 hand = open(dname, ORDWR);
392 sprint(dname, "#a/tls/%s/data", buf);
393 data = open(dname, ORDWR);
396 fprint(ctl, "fd %d 0x%x", fd, ProtocolVersion);
397 tls = tlsClient2(ctl, hand, conn->sessionID, conn->sessionIDlen, conn->trace);
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);
416 countchain(PEMChain *p)
427 static TlsConnection *
428 tlsServer2(int ctl, int hand, uchar *cert, int ncert, int (*trace)(char*fmt, ...), PEMChain *chp)
433 uchar sid[SidSize], kd[MaxKeyData];
435 int cipher, compressor, nsid, rv, numcerts, i;
438 trace("tlsServer2\n");
441 c = emalloc(sizeof(TlsConnection));
445 c->version = ProtocolVersion;
447 memset(&m, 0, sizeof(m));
450 trace("initial msgRecv failed\n");
453 if(m.tag != HClientHello) {
454 tlsError(c, EUnexpectedMessage, "expected a client hello");
457 c->clientVersion = m.u.clientHello.version;
459 trace("ClientHello version %x\n", c->clientVersion);
460 if(setVersion(c, m.u.clientHello.version) < 0) {
461 tlsError(c, EIllegalParameter, "incompatible version");
465 memmove(c->crandom, m.u.clientHello.random, RandomSize);
466 cipher = okCipher(m.u.clientHello.ciphers);
468 /* reply with EInsufficientSecurity if we know that's the case */
470 tlsError(c, EInsufficientSecurity, "cipher suites too weak");
472 tlsError(c, EHandshakeFailure, "no matching cipher suite");
475 if(!setAlgs(c, cipher)){
476 tlsError(c, EHandshakeFailure, "no matching cipher suite");
479 compressor = okCompression(m.u.clientHello.compressors);
481 tlsError(c, EHandshakeFailure, "no matching compressor");
485 csid = m.u.clientHello.sid;
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);
490 tlsError(c, EHandshakeFailure, "can't initialize security: %r");
493 c->sec->rpc = factotum_rsa_open(cert, ncert);
494 if(c->sec->rpc == nil){
495 tlsError(c, EHandshakeFailure, "factotum_rsa_open: %r");
498 c->sec->rsapub = X509toRSApub(cert, ncert, nil, 0);
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))
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))
523 m.tag = HServerHelloDone;
524 if(!msgSend(c, &m, AFlush))
530 if(m.tag != HClientKeyExchange) {
531 tlsError(c, EUnexpectedMessage, "expected a client key exchange");
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");
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);
545 memset(kd, 0, c->nsecret);
547 tlsError(c, EHandshakeFailure, "can't set keys: %r");
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");
559 if(m.tag != HFinished) {
560 tlsError(c, EUnexpectedMessage, "expected a finished");
563 if(!finishedMatch(c, &m.u.finished)) {
564 tlsError(c, EHandshakeFailure, "finished verification failed");
569 /* change cipher spec */
570 if(fprint(c->ctl, "changecipher") < 0){
571 tlsError(c, EInternalError, "can't enable cipher: %r");
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");
580 m.u.finished = c->finished;
581 if(!msgSend(c, &m, AFlush))
585 trace("tls finished\n");
587 if(fprint(c->ctl, "opened") < 0)
594 tlsConnectionFree(c);
598 static TlsConnection *
599 tlsClient2(int ctl, int hand, uchar *csid, int ncsid, int (*trace)(char*fmt, ...))
603 uchar kd[MaxKeyData], *epm;
610 c = emalloc(sizeof(TlsConnection));
611 c->version = ProtocolVersion;
616 c->clientVersion = c->version;
618 c->sec = tlsSecInitc(c->clientVersion, c->crandom);
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))
637 if(m.tag != HServerHello) {
638 tlsError(c, EUnexpectedMessage, "expected a server hello");
641 if(setVersion(c, m.u.serverHello.version) < 0) {
642 tlsError(c, EIllegalParameter, "incompatible version %r");
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");
651 if(!setAlgs(c, m.u.serverHello.cipher)) {
652 tlsError(c, EIllegalParameter, "invalid cipher suite");
655 if(m.u.serverHello.compressor != CompressionNull) {
656 tlsError(c, EIllegalParameter, "invalid compression");
662 if(!msgRecv(c, &m) || m.tag != HCertificate) {
663 tlsError(c, EUnexpectedMessage, "expected a certificate");
666 if(m.u.certificate.ncert < 1) {
667 tlsError(c, EIllegalParameter, "runt certificate");
670 c->cert = makebytes(m.u.certificate.certs[0]->data, m.u.certificate.certs[0]->len);
673 /* server key exchange (optional) */
676 if(m.tag == HServerKeyExchange) {
677 tlsError(c, EUnexpectedMessage, "got an server key exchange");
679 /* If implementing this later, watch out for rollback attack */
680 /* described in Wagner Schneier 1996, section 4.4. */
683 /* certificate request (optional) */
685 if(m.tag == HCertificateRequest) {
692 if(m.tag != HServerHelloDone) {
693 tlsError(c, EUnexpectedMessage, "expected a server hello done");
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");
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);
709 memset(kd, 0, c->nsecret);
711 tlsError(c, EHandshakeFailure, "can't set keys: %r");
716 /* send a zero length certificate */
717 m.tag = HCertificate;
718 if(!msgSend(c, &m, AFlush))
723 /* client key exchange */
724 m.tag = HClientKeyExchange;
725 m.u.clientKeyExchange.key = makebytes(epm, nepm);
728 if(m.u.clientKeyExchange.key == nil) {
729 tlsError(c, EHandshakeFailure, "can't set secret: %r");
732 if(!msgSend(c, &m, AFlush))
736 /* change cipher spec */
737 if(fprint(c->ctl, "changecipher") < 0){
738 tlsError(c, EInternalError, "can't enable cipher: %r");
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");
749 m.u.finished = c->finished;
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");
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");
763 if(!msgRecv(c, &m)) {
764 fprint(2, "tlsClient nepm=%d\n", nepm);
765 tlsError(c, EInternalError, "can't read server Finished: %r");
768 if(m.tag != HFinished) {
769 fprint(2, "tlsClient nepm=%d\n", nepm);
770 tlsError(c, EUnexpectedMessage, "expected a Finished msg from server");
774 if(!finishedMatch(c, &m.u.finished)) {
775 tlsError(c, EHandshakeFailure, "finished verification failed");
780 if(fprint(c->ctl, "opened") < 0){
782 trace("unable to do final open: %r\n");
791 tlsConnectionFree(c);
796 /*================= message functions ======================== */
798 static uchar sendbuf[9000], *sendp;
801 msgSend(TlsConnection *c, Msg *m, int act)
803 uchar *p; /* sendp = start of new message; p = write pointer */
810 c->trace("send %s", msgPrint((char*)p, (sizeof sendbuf) - (p-sendbuf), m));
812 p[0] = m->tag; /* header - fill in size later */
817 tlsError(c, EInternalError, "can't encode a %d", m->tag);
821 put16(p, m->u.clientHello.version);
825 memmove(p, m->u.clientHello.random, RandomSize);
829 n = m->u.clientHello.sid->len;
832 memmove(p+1, m->u.clientHello.sid->data, n);
835 n = m->u.clientHello.ciphers->len;
836 assert(n > 0 && n < 200);
840 put16(p, m->u.clientHello.ciphers->data[i]);
844 n = m->u.clientHello.compressors->len;
847 memmove(p+1, m->u.clientHello.compressors->data, n);
851 put16(p, m->u.serverHello.version);
855 memmove(p, m->u.serverHello.random, RandomSize);
859 n = m->u.serverHello.sid->len;
862 memmove(p+1, m->u.serverHello.sid->data, n);
865 put16(p, m->u.serverHello.cipher);
867 p[0] = m->u.serverHello.compressor;
870 case HServerHelloDone:
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");
882 for(i = 0; i < m->u.certificate.ncert; i++){
883 put24(p, m->u.certificate.certs[i]->len);
885 memmove(p, m->u.certificate.certs[i]->data, m->u.certificate.certs[i]->len);
886 p += m->u.certificate.certs[i]->len;
889 case HClientKeyExchange:
890 n = m->u.clientKeyExchange.key->len;
891 if(c->version != SSL3Version){
895 memmove(p, m->u.clientKeyExchange.key->data, n);
899 memmove(p, m->u.finished.verify, m->u.finished.n);
900 p += m->u.finished.n;
904 /* go back and fill in size */
906 assert(p <= sendbuf+sizeof(sendbuf));
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);
918 if(write(c->hand, sendbuf, p-sendbuf) < 0){
919 fprint(2, "write error: %r\n");
931 tlsReadN(TlsConnection *c, int n)
939 memmove(c->buf, c->rp, nn);
943 for(; nn < n; nn += nr) {
944 nr = read(c->hand, &c->rp[nn], n - nn);
956 msgRecv(TlsConnection *c, Msg *m)
959 int type, n, nn, i, nsid, nrandom, nciph;
968 if(type != HHelloRequest)
971 tlsError(c, EDecodeError, "invalid hello request during handshake");
976 if(n > sizeof(c->buf)) {
977 tlsError(c, EDecodeError, "handshake message too long %d %d", n, sizeof(c->buf));
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. */
988 md5(p, n, 0, &c->hsmd5);
989 sha1(p, n, 0, &c->hssha1);
990 m->tag = HClientHello;
993 m->u.clientHello.version = get16(p+1);
996 nn = get16(p); /* cipher_spec_len */
998 nrandom = get16(p + 4);
1001 if(nsid != 0 /* no sid's, since shouldn't restart using ssl2 header */
1002 || nrandom < 16 || nn % 3)
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} */
1008 for(i = 0; i < nn; i += 3)
1011 m->u.clientHello.ciphers = newints(nciph);
1013 for(i = 0; i < nn; i += 3)
1015 m->u.clientHello.ciphers->data[nciph++] = get16(&p[i + 1]);
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;
1027 md5(p, 4, 0, &c->hsmd5);
1028 sha1(p, 4, 0, &c->hssha1);
1034 md5(p, n, 0, &c->hsmd5);
1035 sha1(p, n, 0, &c->hssha1);
1041 tlsError(c, EUnexpectedMessage, "can't decode a %d", type);
1046 m->u.clientHello.version = get16(p);
1052 memmove(m->u.clientHello.random, p, RandomSize);
1055 if(n < 1 || n < p[0]+1)
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;
1067 if((nn & 1) || n < nn || nn < 2)
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]);
1075 if(n < 1 || n < p[0]+1 || p[0] == 0)
1078 m->u.clientHello.compressors = newbytes(nn);
1079 memmove(m->u.clientHello.compressors->data, p+1, nn);
1085 m->u.serverHello.version = get16(p);
1091 memmove(m->u.serverHello.random, p, RandomSize);
1095 if(n < 1 || n < p[0]+1)
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;
1103 m->u.serverHello.cipher = get16(p);
1104 m->u.serverHello.compressor = p[2];
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);
1133 case HCertificateRequest:
1139 if(nn < 1 || nn > n)
1141 m->u.certificateRequest.types = makebytes(p, nn);
1145 if(nn == 0 || n != nn)
1155 if(nn < 1 || nn > n)
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);
1165 case HServerHelloDone:
1167 case HClientKeyExchange:
1169 * this message depends upon the encryption selected
1172 if(c->version == SSL3Version)
1183 m->u.clientKeyExchange.key = makebytes(p, nn);
1187 m->u.finished.n = c->finished.n;
1188 if(n < m->u.finished.n)
1190 memmove(m->u.finished.verify, p, m->u.finished.n);
1191 n -= m->u.finished.n;
1195 if(type != HClientHello && n != 0)
1200 c->trace("recv %s", msgPrint(buf, sizeof buf, m));
1204 tlsError(c, EDecodeError, "handshake message has invalid length");
1217 sysfatal("msgClear: unknown message type: %d\n", m->tag);
1221 freebytes(m->u.clientHello.sid);
1222 freeints(m->u.clientHello.ciphers);
1223 freebytes(m->u.clientHello.compressors);
1226 freebytes(m->u.clientHello.sid);
1229 for(i=0; i<m->u.certificate.ncert; i++)
1230 freebytes(m->u.certificate.certs[i]);
1231 free(m->u.certificate.certs);
1233 case HCertificateRequest:
1234 freebytes(m->u.certificateRequest.types);
1235 for(i=0; i<m->u.certificateRequest.nca; i++)
1236 freebytes(m->u.certificateRequest.cas[i]);
1237 free(m->u.certificateRequest.cas);
1239 case HServerHelloDone:
1241 case HClientKeyExchange:
1242 freebytes(m->u.clientKeyExchange.key);
1247 memset(m, 0, sizeof(Msg));
1251 bytesPrint(char *bs, char *be, char *s0, Bytes *b, char *s1)
1256 bs = seprint(bs, be, "%s", s0);
1257 bs = seprint(bs, be, "[");
1259 bs = seprint(bs, be, "nil");
1261 for(i=0; i<b->len; i++)
1262 bs = seprint(bs, be, "%.2x ", b->data[i]);
1263 bs = seprint(bs, be, "]");
1265 bs = seprint(bs, be, "%s", s1);
1270 intsPrint(char *bs, char *be, char *s0, Ints *b, char *s1)
1275 bs = seprint(bs, be, "%s", s0);
1276 bs = seprint(bs, be, "[");
1278 bs = seprint(bs, be, "nil");
1280 for(i=0; i<b->len; i++)
1281 bs = seprint(bs, be, "%x ", b->data[i]);
1282 bs = seprint(bs, be, "]");
1284 bs = seprint(bs, be, "%s", s1);
1289 msgPrint(char *buf, int n, Msg *m)
1292 char *bs = buf, *be = buf+n;
1296 bs = seprint(bs, be, "unknown %d\n", m->tag);
1299 bs = seprint(bs, be, "ClientHello\n");
1300 bs = seprint(bs, be, "\tversion: %.4x\n", m->u.clientHello.version);
1301 bs = seprint(bs, be, "\trandom: ");
1302 for(i=0; i<RandomSize; i++)
1303 bs = seprint(bs, be, "%.2x", m->u.clientHello.random[i]);
1304 bs = seprint(bs, be, "\n");
1305 bs = bytesPrint(bs, be, "\tsid: ", m->u.clientHello.sid, "\n");
1306 bs = intsPrint(bs, be, "\tciphers: ", m->u.clientHello.ciphers, "\n");
1307 bs = bytesPrint(bs, be, "\tcompressors: ", m->u.clientHello.compressors, "\n");
1310 bs = seprint(bs, be, "ServerHello\n");
1311 bs = seprint(bs, be, "\tversion: %.4x\n", m->u.serverHello.version);
1312 bs = seprint(bs, be, "\trandom: ");
1313 for(i=0; i<RandomSize; i++)
1314 bs = seprint(bs, be, "%.2x", m->u.serverHello.random[i]);
1315 bs = seprint(bs, be, "\n");
1316 bs = bytesPrint(bs, be, "\tsid: ", m->u.serverHello.sid, "\n");
1317 bs = seprint(bs, be, "\tcipher: %.4x\n", m->u.serverHello.cipher);
1318 bs = seprint(bs, be, "\tcompressor: %.2x\n", m->u.serverHello.compressor);
1321 bs = seprint(bs, be, "Certificate\n");
1322 for(i=0; i<m->u.certificate.ncert; i++)
1323 bs = bytesPrint(bs, be, "\t", m->u.certificate.certs[i], "\n");
1325 case HCertificateRequest:
1326 bs = seprint(bs, be, "CertificateRequest\n");
1327 bs = bytesPrint(bs, be, "\ttypes: ", m->u.certificateRequest.types, "\n");
1328 bs = seprint(bs, be, "\tcertificateauthorities\n");
1329 for(i=0; i<m->u.certificateRequest.nca; i++)
1330 bs = bytesPrint(bs, be, "\t\t", m->u.certificateRequest.cas[i], "\n");
1332 case HServerHelloDone:
1333 bs = seprint(bs, be, "ServerHelloDone\n");
1335 case HClientKeyExchange:
1336 bs = seprint(bs, be, "HClientKeyExchange\n");
1337 bs = bytesPrint(bs, be, "\tkey: ", m->u.clientKeyExchange.key, "\n");
1340 bs = seprint(bs, be, "HFinished\n");
1341 for(i=0; i<m->u.finished.n; i++)
1342 bs = seprint(bs, be, "%.2x", m->u.finished.verify[i]);
1343 bs = seprint(bs, be, "\n");
1351 tlsError(TlsConnection *c, int err, char *fmt, ...)
1357 vseprint(msg, msg+sizeof(msg), fmt, arg);
1360 c->trace("tlsError: %s\n", msg);
1362 fprint(2, "double error: %r, %s", msg);
1364 werrstr("tls: local %s", msg);
1366 fprint(c->ctl, "alert %d", err);
1369 /* commit to specific version number */
1371 setVersion(TlsConnection *c, int version)
1373 if(c->verset || version > MaxProtoVersion || version < MinProtoVersion)
1375 if(version > c->version)
1376 version = c->version;
1377 if(version == SSL3Version) {
1378 c->version = version;
1379 c->finished.n = SSL3FinishedLen;
1380 }else if(version == TLSVersion){
1381 c->version = version;
1382 c->finished.n = TLSFinishedLen;
1386 return fprint(c->ctl, "version 0x%x", version);
1389 /* confirm that received Finished message matches the expected value */
1391 finishedMatch(TlsConnection *c, Finished *f)
1393 return memcmp(f->verify, c->finished.verify, f->n) == 0;
1396 /* free memory associated with TlsConnection struct */
1397 /* (but don't close the TLS channel itself) */
1399 tlsConnectionFree(TlsConnection *c)
1401 tlsSecClose(c->sec);
1404 memset(c, 0, sizeof(*c));
1409 /*================= cipher choices ======================== */
1411 static int weakCipher[CipherMax] =
1413 1, /* TLS_NULL_WITH_NULL_NULL */
1414 1, /* TLS_RSA_WITH_NULL_MD5 */
1415 1, /* TLS_RSA_WITH_NULL_SHA */
1416 1, /* TLS_RSA_EXPORT_WITH_RC4_40_MD5 */
1417 0, /* TLS_RSA_WITH_RC4_128_MD5 */
1418 0, /* TLS_RSA_WITH_RC4_128_SHA */
1419 1, /* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 */
1420 0, /* TLS_RSA_WITH_IDEA_CBC_SHA */
1421 1, /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA */
1422 0, /* TLS_RSA_WITH_DES_CBC_SHA */
1423 0, /* TLS_RSA_WITH_3DES_EDE_CBC_SHA */
1424 1, /* TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA */
1425 0, /* TLS_DH_DSS_WITH_DES_CBC_SHA */
1426 0, /* TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA */
1427 1, /* TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA */
1428 0, /* TLS_DH_RSA_WITH_DES_CBC_SHA */
1429 0, /* TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA */
1430 1, /* TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA */
1431 0, /* TLS_DHE_DSS_WITH_DES_CBC_SHA */
1432 0, /* TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA */
1433 1, /* TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA */
1434 0, /* TLS_DHE_RSA_WITH_DES_CBC_SHA */
1435 0, /* TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA */
1436 1, /* TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 */
1437 1, /* TLS_DH_anon_WITH_RC4_128_MD5 */
1438 1, /* TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA */
1439 1, /* TLS_DH_anon_WITH_DES_CBC_SHA */
1440 1, /* TLS_DH_anon_WITH_3DES_EDE_CBC_SHA */
1444 setAlgs(TlsConnection *c, int a)
1448 for(i = 0; i < nelem(cipherAlgs); i++){
1449 if(cipherAlgs[i].tlsid == a){
1450 c->enc = cipherAlgs[i].enc;
1451 c->digest = cipherAlgs[i].digest;
1452 c->nsecret = cipherAlgs[i].nsecret;
1453 if(c->nsecret > MaxKeyData)
1467 for(i = 0; i < cv->len; i++) {
1472 weak &= weakCipher[c];
1473 for(j = 0; j < nelem(cipherAlgs); j++)
1474 if(cipherAlgs[j].ok && cipherAlgs[j].tlsid == c)
1483 okCompression(Bytes *cv)
1487 for(i = 0; i < cv->len; i++) {
1489 for(j = 0; j < nelem(compressors); j++) {
1490 if(compressors[j] == c)
1497 static Lock ciphLock;
1498 static int nciphers;
1503 enum {MaxAlgF = 1024, MaxAlgs = 10};
1504 char s[MaxAlgF], *flds[MaxAlgs];
1512 j = open("#a/tls/encalgs", OREAD);
1514 werrstr("can't open #a/tls/encalgs: %r");
1517 n = read(j, s, MaxAlgF-1);
1520 werrstr("nothing in #a/tls/encalgs: %r");
1524 n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
1525 for(i = 0; i < nelem(cipherAlgs); i++){
1527 for(j = 0; j < n; j++){
1528 if(strcmp(cipherAlgs[i].enc, flds[j]) == 0){
1533 cipherAlgs[i].ok = ok;
1536 j = open("#a/tls/hashalgs", OREAD);
1538 werrstr("can't open #a/tls/hashalgs: %r");
1541 n = read(j, s, MaxAlgF-1);
1544 werrstr("nothing in #a/tls/hashalgs: %r");
1548 n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
1549 for(i = 0; i < nelem(cipherAlgs); i++){
1551 for(j = 0; j < n; j++){
1552 if(strcmp(cipherAlgs[i].digest, flds[j]) == 0){
1557 cipherAlgs[i].ok &= ok;
1558 if(cipherAlgs[i].ok)
1571 is = newints(nciphers);
1573 for(i = 0; i < nelem(cipherAlgs); i++){
1574 if(cipherAlgs[i].ok)
1575 is->data[j++] = cipherAlgs[i].tlsid;
1582 /*================= security functions ======================== */
1584 /* given X.509 certificate, set up connection to factotum */
1585 /* for using corresponding private key */
1587 factotum_rsa_open(uchar *cert, int certlen)
1594 if((rpc = auth_allocrpc()) == nil){
1597 s = "proto=rsa service=tls role=client";
1598 if(auth_rpc(rpc, "start", s, strlen(s)) != ARok){
1599 factotum_rsa_close(rpc);
1603 /* roll factotum keyring around to match certificate */
1604 rsapub = X509toRSApub(cert, certlen, nil, 0);
1606 if(auth_rpc(rpc, "read", nil, 0) != ARok){
1607 factotum_rsa_close(rpc);
1611 pub = strtomp(rpc->arg, nil, 16, nil);
1613 if(mpcmp(pub,rsapub->n) == 0)
1623 factotum_rsa_decrypt(AuthRpc *rpc, mpint *cipher)
1628 if((p = mptoa(cipher, 16, nil, 0)) == nil)
1630 rv = auth_rpc(rpc, "write", p, strlen(p));
1632 if(rv != ARok || auth_rpc(rpc, "read", nil, 0) != ARok)
1635 return strtomp(rpc->arg, nil, 16, nil);
1639 factotum_rsa_close(AuthRpc*rpc)
1648 tlsPmd5(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1650 uchar ai[MD5dlen], tmp[MD5dlen];
1655 s = hmac_md5(label, nlabel, key, nkey, nil, nil);
1656 s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
1657 hmac_md5(seed1, nseed1, key, nkey, ai, s);
1660 s = hmac_md5(ai, MD5dlen, key, nkey, nil, nil);
1661 s = hmac_md5(label, nlabel, key, nkey, nil, s);
1662 s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
1663 hmac_md5(seed1, nseed1, key, nkey, tmp, s);
1667 for(i = 0; i < n; i++)
1671 hmac_md5(ai, MD5dlen, key, nkey, tmp, nil);
1672 memmove(ai, tmp, MD5dlen);
1677 tlsPsha1(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1679 uchar ai[SHA1dlen], tmp[SHA1dlen];
1684 s = hmac_sha1(label, nlabel, key, nkey, nil, nil);
1685 s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
1686 hmac_sha1(seed1, nseed1, key, nkey, ai, s);
1689 s = hmac_sha1(ai, SHA1dlen, key, nkey, nil, nil);
1690 s = hmac_sha1(label, nlabel, key, nkey, nil, s);
1691 s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
1692 hmac_sha1(seed1, nseed1, key, nkey, tmp, s);
1696 for(i = 0; i < n; i++)
1700 hmac_sha1(ai, SHA1dlen, key, nkey, tmp, nil);
1701 memmove(ai, tmp, SHA1dlen);
1705 /* fill buf with md5(args)^sha1(args) */
1707 tlsPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1710 int nlabel = strlen(label);
1711 int n = (nkey + 1) >> 1;
1713 for(i = 0; i < nbuf; i++)
1715 tlsPmd5(buf, nbuf, key, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
1716 tlsPsha1(buf, nbuf, key+nkey-n, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
1720 * for setting server session id's
1722 static Lock sidLock;
1723 static long maxSid = 1;
1725 /* the keys are verified to have the same public components
1726 * and to function correctly with pkcs 1 encryption and decryption. */
1728 tlsSecInits(int cvers, uchar *csid, int ncsid, uchar *crandom, uchar *ssid, int *nssid, uchar *srandom)
1730 TlsSec *sec = emalloc(sizeof(*sec));
1732 USED(csid); USED(ncsid); /* ignore csid for now */
1734 memmove(sec->crandom, crandom, RandomSize);
1735 sec->clientVers = cvers;
1737 put32(sec->srandom, time(0));
1738 genrandom(sec->srandom+4, RandomSize-4);
1739 memmove(srandom, sec->srandom, RandomSize);
1742 * make up a unique sid: use our pid, and and incrementing id
1743 * can signal no sid by setting nssid to 0.
1745 memset(ssid, 0, SidSize);
1746 put32(ssid, getpid());
1748 put32(ssid+4, maxSid++);
1755 tlsSecSecrets(TlsSec *sec, int vers, uchar *epm, int nepm, uchar *kd, int nkd)
1758 if(setVers(sec, vers) < 0)
1760 serverMasterSecret(sec, epm, nepm);
1761 }else if(sec->vers != vers){
1762 werrstr("mismatched session versions");
1765 setSecrets(sec, kd, nkd);
1773 tlsSecInitc(int cvers, uchar *crandom)
1775 TlsSec *sec = emalloc(sizeof(*sec));
1776 sec->clientVers = cvers;
1777 put32(sec->crandom, time(0));
1778 genrandom(sec->crandom+4, RandomSize-4);
1779 memmove(crandom, sec->crandom, RandomSize);
1784 tlsSecSecretc(TlsSec *sec, uchar *sid, int nsid, uchar *srandom, uchar *cert, int ncert, int vers, uchar **epm, int *nepm, uchar *kd, int nkd)
1793 memmove(sec->srandom, srandom, RandomSize);
1795 if(setVers(sec, vers) < 0)
1798 pub = X509toRSApub(cert, ncert, nil, 0);
1800 werrstr("invalid x509/rsa certificate");
1803 if(clientMasterSecret(sec, pub, epm, nepm) < 0)
1806 setSecrets(sec, kd, nkd);
1817 tlsSecFinished(TlsSec *sec, MD5state md5, SHAstate sha1, uchar *fin, int nfin, int isclient)
1819 if(sec->nfin != nfin){
1821 werrstr("invalid finished exchange");
1826 (*sec->setFinished)(sec, md5, sha1, fin, isclient);
1831 tlsSecOk(TlsSec *sec)
1839 tlsSecKill(TlsSec *sec)
1843 factotum_rsa_close(sec->rpc);
1849 tlsSecClose(TlsSec *sec)
1853 factotum_rsa_close(sec->rpc);
1859 setVers(TlsSec *sec, int v)
1861 if(v == SSL3Version){
1862 sec->setFinished = sslSetFinished;
1863 sec->nfin = SSL3FinishedLen;
1865 }else if(v == TLSVersion){
1866 sec->setFinished = tlsSetFinished;
1867 sec->nfin = TLSFinishedLen;
1870 werrstr("invalid version");
1878 * generate secret keys from the master secret.
1880 * different crypto selections will require different amounts
1881 * of key expansion and use of key expansion data,
1882 * but it's all generated using the same function.
1885 setSecrets(TlsSec *sec, uchar *kd, int nkd)
1887 (*sec->prf)(kd, nkd, sec->sec, MasterSecretSize, "key expansion",
1888 sec->srandom, RandomSize, sec->crandom, RandomSize);
1892 * set the master secret from the pre-master secret.
1895 setMasterSecret(TlsSec *sec, Bytes *pm)
1897 (*sec->prf)(sec->sec, MasterSecretSize, pm->data, MasterSecretSize, "master secret",
1898 sec->crandom, RandomSize, sec->srandom, RandomSize);
1902 serverMasterSecret(TlsSec *sec, uchar *epm, int nepm)
1906 pm = pkcs1_decrypt(sec, epm, nepm);
1908 /* if the client messed up, just continue as if everything is ok, */
1909 /* to prevent attacks to check for correctly formatted messages. */
1910 /* Hence the fprint(2,) can't be replaced by tlsError(), which sends an Alert msg to the client. */
1911 if(sec->ok < 0 || pm == nil || get16(pm->data) != sec->clientVers){
1912 fprint(2, "serverMasterSecret failed ok=%d pm=%p pmvers=%x cvers=%x nepm=%d\n",
1913 sec->ok, pm, pm ? get16(pm->data) : -1, sec->clientVers, nepm);
1917 pm = newbytes(MasterSecretSize);
1918 genrandom(pm->data, MasterSecretSize);
1920 setMasterSecret(sec, pm);
1921 memset(pm->data, 0, pm->len);
1926 clientMasterSecret(TlsSec *sec, RSApub *pub, uchar **epm, int *nepm)
1930 pm = newbytes(MasterSecretSize);
1931 put16(pm->data, sec->clientVers);
1932 genrandom(pm->data+2, MasterSecretSize - 2);
1934 setMasterSecret(sec, pm);
1936 key = pkcs1_encrypt(pm, pub, 2);
1937 memset(pm->data, 0, pm->len);
1940 werrstr("tls pkcs1_encrypt failed");
1945 *epm = malloc(*nepm);
1948 werrstr("out of memory");
1951 memmove(*epm, key->data, *nepm);
1959 sslSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
1962 uchar h0[MD5dlen], h1[SHA1dlen], pad[48];
1970 md5((uchar*)label, 4, nil, &hsmd5);
1971 md5(sec->sec, MasterSecretSize, nil, &hsmd5);
1972 memset(pad, 0x36, 48);
1973 md5(pad, 48, nil, &hsmd5);
1974 md5(nil, 0, h0, &hsmd5);
1975 memset(pad, 0x5C, 48);
1976 s = md5(sec->sec, MasterSecretSize, nil, nil);
1977 s = md5(pad, 48, nil, s);
1978 md5(h0, MD5dlen, finished, s);
1980 sha1((uchar*)label, 4, nil, &hssha1);
1981 sha1(sec->sec, MasterSecretSize, nil, &hssha1);
1982 memset(pad, 0x36, 40);
1983 sha1(pad, 40, nil, &hssha1);
1984 sha1(nil, 0, h1, &hssha1);
1985 memset(pad, 0x5C, 40);
1986 s = sha1(sec->sec, MasterSecretSize, nil, nil);
1987 s = sha1(pad, 40, nil, s);
1988 sha1(h1, SHA1dlen, finished + MD5dlen, s);
1991 /* fill "finished" arg with md5(args)^sha1(args) */
1993 tlsSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
1995 uchar h0[MD5dlen], h1[SHA1dlen];
1998 /* get current hash value, but allow further messages to be hashed in */
1999 md5(nil, 0, h0, &hsmd5);
2000 sha1(nil, 0, h1, &hssha1);
2003 label = "client finished";
2005 label = "server finished";
2006 tlsPRF(finished, TLSFinishedLen, sec->sec, MasterSecretSize, label, h0, MD5dlen, h1, SHA1dlen);
2010 sslPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
2013 uchar sha1dig[SHA1dlen], md5dig[MD5dlen], tmp[26];
2021 for(i = 0; i < len; i++)
2022 tmp[i] = 'A' - 1 + len;
2023 s = sha1(tmp, len, nil, nil);
2024 s = sha1(key, nkey, nil, s);
2025 s = sha1(seed0, nseed0, nil, s);
2026 sha1(seed1, nseed1, sha1dig, s);
2027 s = md5(key, nkey, nil, nil);
2028 md5(sha1dig, SHA1dlen, md5dig, s);
2032 memmove(buf, md5dig, n);
2040 bytestomp(Bytes* bytes)
2044 ans = betomp(bytes->data, bytes->len, nil);
2049 * Convert mpint* to Bytes, putting high order byte first.
2052 mptobytes(mpint* big)
2058 n = (mpsignif(big)+7)/8;
2059 m = mptobe(big, nil, n, &a);
2060 ans = makebytes(a, m);
2064 /* Do RSA computation on block according to key, and pad */
2065 /* result on left with zeros to make it modlen long. */
2067 rsacomp(Bytes* block, RSApub* key, int modlen)
2073 x = bytestomp(block);
2074 y = rsaencrypt(key, x, nil);
2076 ybytes = mptobytes(y);
2080 a = newbytes(modlen);
2081 memset(a->data, 0, modlen-ylen);
2082 memmove(a->data+modlen-ylen, ybytes->data, ylen);
2086 else if(ylen > modlen) {
2087 /* assume it has leading zeros (mod should make it so) */
2088 a = newbytes(modlen);
2089 memmove(a->data, ybytes->data, modlen);
2097 /* encrypt data according to PKCS#1, /lib/rfc/rfc2437 9.1.2.1 */
2099 pkcs1_encrypt(Bytes* data, RSApub* key, int blocktype)
2101 Bytes *pad, *eb, *ans;
2102 int i, dlen, padlen, modlen;
2104 modlen = (mpsignif(key->n)+7)/8;
2106 if(modlen < 12 || dlen > modlen - 11)
2108 padlen = modlen - 3 - dlen;
2109 pad = newbytes(padlen);
2110 genrandom(pad->data, padlen);
2111 for(i = 0; i < padlen; i++) {
2114 else if(blocktype == 1)
2116 else if(pad->data[i] == 0)
2119 eb = newbytes(modlen);
2121 eb->data[1] = blocktype;
2122 memmove(eb->data+2, pad->data, padlen);
2123 eb->data[padlen+2] = 0;
2124 memmove(eb->data+padlen+3, data->data, dlen);
2125 ans = rsacomp(eb, key, modlen);
2131 /* decrypt data according to PKCS#1, with given key. */
2132 /* expect a block type of 2. */
2134 pkcs1_decrypt(TlsSec *sec, uchar *epm, int nepm)
2136 Bytes *eb, *ans = nil;
2140 modlen = (mpsignif(sec->rsapub->n)+7)/8;
2143 x = betomp(epm, nepm, nil);
2144 y = factotum_rsa_decrypt(sec->rpc, x);
2148 if(eb->len < modlen){ /* pad on left with zeros */
2149 ans = newbytes(modlen);
2150 memset(ans->data, 0, modlen-eb->len);
2151 memmove(ans->data+modlen-eb->len, eb->data, eb->len);
2155 if(eb->data[0] == 0 && eb->data[1] == 2) {
2156 for(i = 2; i < modlen; i++)
2157 if(eb->data[i] == 0)
2160 ans = makebytes(eb->data+i+1, modlen-(i+1));
2167 /*================= general utility functions ======================== */
2177 exits("out of memory");
2184 erealloc(void *ReallocP, int ReallocN)
2189 ReallocP = emalloc(ReallocN);
2190 else if(!(ReallocP = realloc(ReallocP, ReallocN))){
2191 exits("out of memory");
2197 put32(uchar *p, u32int x)
2206 put24(uchar *p, int x)
2214 put16(uchar *p, int x)
2224 return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
2231 return (p[0]<<16)|(p[1]<<8)|p[2];
2237 return (p[0]<<8)|p[1];
2240 /* ANSI offsetof() */
2241 #define OFFSET(x, s) ((intptr)(&(((s*)0)->x)))
2244 * malloc and return a new Bytes structure capable of
2245 * holding len bytes. (len >= 0)
2246 * Used to use crypt_malloc, which aborts if malloc fails.
2253 ans = (Bytes*)malloc(OFFSET(data[0], Bytes) + len);
2259 * newbytes(len), with data initialized from buf
2262 makebytes(uchar* buf, int len)
2266 ans = newbytes(len);
2267 memmove(ans->data, buf, len);
2278 /* len is number of ints */
2284 ans = (Ints*)malloc(OFFSET(data[0], Ints) + len*sizeof(int));
2291 makeints(int* buf, int len)
2297 memmove(ans->data, buf, len*sizeof(int));