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]
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, ...));
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
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);
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
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);
415 static TlsConnection *
416 tlsServer2(int ctl, int hand, uchar *cert, int ncert, int (*trace)(char*fmt, ...))
421 uchar sid[SidSize], kd[MaxKeyData];
423 int cipher, compressor, nsid, rv;
426 trace("tlsServer2\n");
429 c = emalloc(sizeof(TlsConnection));
433 c->version = ProtocolVersion;
435 memset(&m, 0, sizeof(m));
438 trace("initial msgRecv failed\n");
441 if(m.tag != HClientHello) {
442 tlsError(c, EUnexpectedMessage, "expected a client hello");
445 c->clientVersion = m.u.clientHello.version;
447 trace("ClientHello version %x\n", c->clientVersion);
448 if(setVersion(c, m.u.clientHello.version) < 0) {
449 tlsError(c, EIllegalParameter, "incompatible version");
453 memmove(c->crandom, m.u.clientHello.random, RandomSize);
454 cipher = okCipher(m.u.clientHello.ciphers);
456 // reply with EInsufficientSecurity if we know that's the case
458 tlsError(c, EInsufficientSecurity, "cipher suites too weak");
460 tlsError(c, EHandshakeFailure, "no matching cipher suite");
463 if(!setAlgs(c, cipher)){
464 tlsError(c, EHandshakeFailure, "no matching cipher suite");
467 compressor = okCompression(m.u.clientHello.compressors);
469 tlsError(c, EHandshakeFailure, "no matching compressor");
473 csid = m.u.clientHello.sid;
475 trace(" cipher %d, compressor %d, csidlen %d\n", cipher, compressor, csid->len);
476 c->sec = tlsSecInits(c->clientVersion, csid->data, csid->len, c->crandom, sid, &nsid, c->srandom);
478 tlsError(c, EHandshakeFailure, "can't initialize security: %r");
481 c->sec->rpc = factotum_rsa_open(cert, ncert);
482 if(c->sec->rpc == nil){
483 tlsError(c, EHandshakeFailure, "factotum_rsa_open: %r");
486 c->sec->rsapub = X509toRSApub(cert, ncert, nil, 0);
489 m.tag = HServerHello;
490 m.u.serverHello.version = c->version;
491 memmove(m.u.serverHello.random, c->srandom, RandomSize);
492 m.u.serverHello.cipher = cipher;
493 m.u.serverHello.compressor = compressor;
494 c->sid = makebytes(sid, nsid);
495 m.u.serverHello.sid = makebytes(c->sid->data, c->sid->len);
496 if(!msgSend(c, &m, AQueue))
500 m.tag = HCertificate;
501 m.u.certificate.ncert = 1;
502 m.u.certificate.certs = emalloc(m.u.certificate.ncert * sizeof(Bytes));
503 m.u.certificate.certs[0] = makebytes(cert, ncert);
504 if(!msgSend(c, &m, AQueue))
508 m.tag = HServerHelloDone;
509 if(!msgSend(c, &m, AFlush))
515 if(m.tag != HClientKeyExchange) {
516 tlsError(c, EUnexpectedMessage, "expected a client key exchange");
519 if(tlsSecSecrets(c->sec, c->version, m.u.clientKeyExchange.key->data, m.u.clientKeyExchange.key->len, kd, c->nsecret) < 0){
520 tlsError(c, EHandshakeFailure, "couldn't set secrets: %r");
524 trace("tls secrets\n");
525 secrets = (char*)emalloc(2*c->nsecret);
526 enc64(secrets, 2*c->nsecret, kd, c->nsecret);
527 rv = fprint(c->ctl, "secret %s %s 0 %s", c->digest, c->enc, secrets);
528 memset(secrets, 0, 2*c->nsecret);
530 memset(kd, 0, c->nsecret);
532 tlsError(c, EHandshakeFailure, "can't set keys: %r");
537 /* no CertificateVerify; skip to Finished */
538 if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 1) < 0){
539 tlsError(c, EInternalError, "can't set finished: %r");
544 if(m.tag != HFinished) {
545 tlsError(c, EUnexpectedMessage, "expected a finished");
548 if(!finishedMatch(c, &m.u.finished)) {
549 tlsError(c, EHandshakeFailure, "finished verification failed");
554 /* change cipher spec */
555 if(fprint(c->ctl, "changecipher") < 0){
556 tlsError(c, EInternalError, "can't enable cipher: %r");
560 if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 0) < 0){
561 tlsError(c, EInternalError, "can't set finished: %r");
565 m.u.finished = c->finished;
566 if(!msgSend(c, &m, AFlush))
570 trace("tls finished\n");
572 if(fprint(c->ctl, "opened") < 0)
579 tlsConnectionFree(c);
583 static TlsConnection *
584 tlsClient2(int ctl, int hand, uchar *csid, int ncsid, int (*trace)(char*fmt, ...))
588 uchar kd[MaxKeyData], *epm;
595 c = emalloc(sizeof(TlsConnection));
596 c->version = ProtocolVersion;
601 c->clientVersion = c->version;
603 c->sec = tlsSecInitc(c->clientVersion, c->crandom);
608 memset(&m, 0, sizeof(m));
609 m.tag = HClientHello;
610 m.u.clientHello.version = c->clientVersion;
611 memmove(m.u.clientHello.random, c->crandom, RandomSize);
612 m.u.clientHello.sid = makebytes(csid, ncsid);
613 m.u.clientHello.ciphers = makeciphers();
614 m.u.clientHello.compressors = makebytes(compressors,sizeof(compressors));
615 if(!msgSend(c, &m, AFlush))
622 if(m.tag != HServerHello) {
623 tlsError(c, EUnexpectedMessage, "expected a server hello");
626 if(setVersion(c, m.u.serverHello.version) < 0) {
627 tlsError(c, EIllegalParameter, "incompatible version %r");
630 memmove(c->srandom, m.u.serverHello.random, RandomSize);
631 c->sid = makebytes(m.u.serverHello.sid->data, m.u.serverHello.sid->len);
632 if(c->sid->len != 0 && c->sid->len != SidSize) {
633 tlsError(c, EIllegalParameter, "invalid server session identifier");
636 if(!setAlgs(c, m.u.serverHello.cipher)) {
637 tlsError(c, EIllegalParameter, "invalid cipher suite");
640 if(m.u.serverHello.compressor != CompressionNull) {
641 tlsError(c, EIllegalParameter, "invalid compression");
647 if(!msgRecv(c, &m) || m.tag != HCertificate) {
648 tlsError(c, EUnexpectedMessage, "expected a certificate");
651 if(m.u.certificate.ncert < 1) {
652 tlsError(c, EIllegalParameter, "runt certificate");
655 c->cert = makebytes(m.u.certificate.certs[0]->data, m.u.certificate.certs[0]->len);
658 /* server key exchange (optional) */
661 if(m.tag == HServerKeyExchange) {
662 tlsError(c, EUnexpectedMessage, "got an server key exchange");
664 // If implementing this later, watch out for rollback attack
665 // described in Wagner Schneier 1996, section 4.4.
668 /* certificate request (optional) */
670 if(m.tag == HCertificateRequest) {
677 if(m.tag != HServerHelloDone) {
678 tlsError(c, EUnexpectedMessage, "expected a server hello done");
683 if(tlsSecSecretc(c->sec, c->sid->data, c->sid->len, c->srandom,
684 c->cert->data, c->cert->len, c->version, &epm, &nepm,
685 kd, c->nsecret) < 0){
686 tlsError(c, EBadCertificate, "invalid x509/rsa certificate");
689 secrets = (char*)emalloc(2*c->nsecret);
690 enc64(secrets, 2*c->nsecret, kd, c->nsecret);
691 rv = fprint(c->ctl, "secret %s %s 1 %s", c->digest, c->enc, secrets);
692 memset(secrets, 0, 2*c->nsecret);
694 memset(kd, 0, c->nsecret);
696 tlsError(c, EHandshakeFailure, "can't set keys: %r");
701 /* send a zero length certificate */
702 m.tag = HCertificate;
703 if(!msgSend(c, &m, AFlush))
708 /* client key exchange */
709 m.tag = HClientKeyExchange;
710 m.u.clientKeyExchange.key = makebytes(epm, nepm);
713 if(m.u.clientKeyExchange.key == nil) {
714 tlsError(c, EHandshakeFailure, "can't set secret: %r");
717 if(!msgSend(c, &m, AFlush))
721 /* change cipher spec */
722 if(fprint(c->ctl, "changecipher") < 0){
723 tlsError(c, EInternalError, "can't enable cipher: %r");
727 // Cipherchange must occur immediately before Finished to avoid
728 // potential hole; see section 4.3 of Wagner Schneier 1996.
729 if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 1) < 0){
730 tlsError(c, EInternalError, "can't set finished 1: %r");
734 m.u.finished = c->finished;
736 if(!msgSend(c, &m, AFlush)) {
737 fprint(2, "tlsClient nepm=%d\n", nepm);
738 tlsError(c, EInternalError, "can't flush after client Finished: %r");
743 if(tlsSecFinished(c->sec, c->hsmd5, c->hssha1, c->finished.verify, c->finished.n, 0) < 0){
744 fprint(2, "tlsClient nepm=%d\n", nepm);
745 tlsError(c, EInternalError, "can't set finished 0: %r");
748 if(!msgRecv(c, &m)) {
749 fprint(2, "tlsClient nepm=%d\n", nepm);
750 tlsError(c, EInternalError, "can't read server Finished: %r");
753 if(m.tag != HFinished) {
754 fprint(2, "tlsClient nepm=%d\n", nepm);
755 tlsError(c, EUnexpectedMessage, "expected a Finished msg from server");
759 if(!finishedMatch(c, &m.u.finished)) {
760 tlsError(c, EHandshakeFailure, "finished verification failed");
765 if(fprint(c->ctl, "opened") < 0){
767 trace("unable to do final open: %r\n");
776 tlsConnectionFree(c);
781 //================= message functions ========================
783 static uchar sendbuf[9000], *sendp;
786 msgSend(TlsConnection *c, Msg *m, int act)
788 uchar *p; // sendp = start of new message; p = write pointer
795 c->trace("send %s", msgPrint((char*)p, (sizeof sendbuf) - (p-sendbuf), m));
797 p[0] = m->tag; // header - fill in size later
802 tlsError(c, EInternalError, "can't encode a %d", m->tag);
806 put16(p, m->u.clientHello.version);
810 memmove(p, m->u.clientHello.random, RandomSize);
814 n = m->u.clientHello.sid->len;
817 memmove(p+1, m->u.clientHello.sid->data, n);
820 n = m->u.clientHello.ciphers->len;
821 assert(n > 0 && n < 200);
825 put16(p, m->u.clientHello.ciphers->data[i]);
829 n = m->u.clientHello.compressors->len;
832 memmove(p+1, m->u.clientHello.compressors->data, n);
836 put16(p, m->u.serverHello.version);
840 memmove(p, m->u.serverHello.random, RandomSize);
844 n = m->u.serverHello.sid->len;
847 memmove(p+1, m->u.serverHello.sid->data, n);
850 put16(p, m->u.serverHello.cipher);
852 p[0] = m->u.serverHello.compressor;
855 case HServerHelloDone:
859 for(i = 0; i < m->u.certificate.ncert; i++)
860 nn += 3 + m->u.certificate.certs[i]->len;
861 if(p + 3 + nn - sendbuf > sizeof(sendbuf)) {
862 tlsError(c, EInternalError, "output buffer too small for certificate");
867 for(i = 0; i < m->u.certificate.ncert; i++){
868 put24(p, m->u.certificate.certs[i]->len);
870 memmove(p, m->u.certificate.certs[i]->data, m->u.certificate.certs[i]->len);
871 p += m->u.certificate.certs[i]->len;
874 case HClientKeyExchange:
875 n = m->u.clientKeyExchange.key->len;
876 if(c->version != SSL3Version){
880 memmove(p, m->u.clientKeyExchange.key->data, n);
884 memmove(p, m->u.finished.verify, m->u.finished.n);
885 p += m->u.finished.n;
889 // go back and fill in size
891 assert(p <= sendbuf+sizeof(sendbuf));
894 // remember hash of Handshake messages
895 if(m->tag != HHelloRequest) {
896 md5(sendp, n, 0, &c->hsmd5);
897 sha1(sendp, n, 0, &c->hssha1);
903 if(write(c->hand, sendbuf, p-sendbuf) < 0){
904 fprint(2, "write error: %r\n");
916 tlsReadN(TlsConnection *c, int n)
924 memmove(c->buf, c->rp, nn);
928 for(; nn < n; nn += nr) {
929 nr = read(c->hand, &c->rp[nn], n - nn);
941 msgRecv(TlsConnection *c, Msg *m)
944 int type, n, nn, i, nsid, nrandom, nciph;
953 if(type != HHelloRequest)
956 tlsError(c, EDecodeError, "invalid hello request during handshake");
961 if(n > sizeof(c->buf)) {
962 tlsError(c, EDecodeError, "handshake message too long %d %d", n, sizeof(c->buf));
966 if(type == HSSL2ClientHello){
967 /* Cope with an SSL3 ClientHello expressed in SSL2 record format.
968 This is sent by some clients that we must interoperate
969 with, such as Java's JSSE and Microsoft's Internet Explorer. */
973 md5(p, n, 0, &c->hsmd5);
974 sha1(p, n, 0, &c->hssha1);
975 m->tag = HClientHello;
978 m->u.clientHello.version = get16(p+1);
981 nn = get16(p); /* cipher_spec_len */
983 nrandom = get16(p + 4);
986 if(nsid != 0 /* no sid's, since shouldn't restart using ssl2 header */
987 || nrandom < 16 || nn % 3)
989 if(c->trace && (n - nrandom != nn))
990 c->trace("n-nrandom!=nn: n=%d nrandom=%d nn=%d\n", n, nrandom, nn);
991 /* ignore ssl2 ciphers and look for {0x00, ssl3 cipher} */
993 for(i = 0; i < nn; i += 3)
996 m->u.clientHello.ciphers = newints(nciph);
998 for(i = 0; i < nn; i += 3)
1000 m->u.clientHello.ciphers->data[nciph++] = get16(&p[i + 1]);
1002 m->u.clientHello.sid = makebytes(nil, 0);
1003 if(nrandom > RandomSize)
1004 nrandom = RandomSize;
1005 memset(m->u.clientHello.random, 0, RandomSize - nrandom);
1006 memmove(&m->u.clientHello.random[RandomSize - nrandom], p, nrandom);
1007 m->u.clientHello.compressors = newbytes(1);
1008 m->u.clientHello.compressors->data[0] = CompressionNull;
1012 md5(p, 4, 0, &c->hsmd5);
1013 sha1(p, 4, 0, &c->hssha1);
1019 md5(p, n, 0, &c->hsmd5);
1020 sha1(p, n, 0, &c->hssha1);
1026 tlsError(c, EUnexpectedMessage, "can't decode a %d", type);
1031 m->u.clientHello.version = get16(p);
1037 memmove(m->u.clientHello.random, p, RandomSize);
1040 if(n < 1 || n < p[0]+1)
1042 m->u.clientHello.sid = makebytes(p+1, p[0]);
1043 p += m->u.clientHello.sid->len+1;
1044 n -= m->u.clientHello.sid->len+1;
1052 if((nn & 1) || n < nn || nn < 2)
1054 m->u.clientHello.ciphers = newints(nn >> 1);
1055 for(i = 0; i < nn; i += 2)
1056 m->u.clientHello.ciphers->data[i >> 1] = get16(&p[i]);
1060 if(n < 1 || n < p[0]+1 || p[0] == 0)
1063 m->u.clientHello.compressors = newbytes(nn);
1064 memmove(m->u.clientHello.compressors->data, p+1, nn);
1070 m->u.serverHello.version = get16(p);
1076 memmove(m->u.serverHello.random, p, RandomSize);
1080 if(n < 1 || n < p[0]+1)
1082 m->u.serverHello.sid = makebytes(p+1, p[0]);
1083 p += m->u.serverHello.sid->len+1;
1084 n -= m->u.serverHello.sid->len+1;
1088 m->u.serverHello.cipher = get16(p);
1089 m->u.serverHello.compressor = p[2];
1110 m->u.certificate.ncert = i+1;
1111 m->u.certificate.certs = erealloc(m->u.certificate.certs, (i+1)*sizeof(Bytes));
1112 m->u.certificate.certs[i] = makebytes(p, nn);
1118 case HCertificateRequest:
1124 if(nn < 1 || nn > n)
1126 m->u.certificateRequest.types = makebytes(p, nn);
1130 if(nn == 0 || n != nn)
1140 if(nn < 1 || nn > n)
1142 m->u.certificateRequest.nca = i+1;
1143 m->u.certificateRequest.cas = erealloc(m->u.certificateRequest.cas, (i+1)*sizeof(Bytes));
1144 m->u.certificateRequest.cas[i] = makebytes(p, nn);
1150 case HServerHelloDone:
1152 case HClientKeyExchange:
1154 * this message depends upon the encryption selected
1157 if(c->version == SSL3Version)
1168 m->u.clientKeyExchange.key = makebytes(p, nn);
1172 m->u.finished.n = c->finished.n;
1173 if(n < m->u.finished.n)
1175 memmove(m->u.finished.verify, p, m->u.finished.n);
1176 n -= m->u.finished.n;
1180 if(type != HClientHello && n != 0)
1185 c->trace("recv %s", msgPrint(buf, sizeof buf, m));
1189 tlsError(c, EDecodeError, "handshake message has invalid length");
1202 sysfatal("msgClear: unknown message type: %d\n", m->tag);
1206 freebytes(m->u.clientHello.sid);
1207 freeints(m->u.clientHello.ciphers);
1208 freebytes(m->u.clientHello.compressors);
1211 freebytes(m->u.clientHello.sid);
1214 for(i=0; i<m->u.certificate.ncert; i++)
1215 freebytes(m->u.certificate.certs[i]);
1216 free(m->u.certificate.certs);
1218 case HCertificateRequest:
1219 freebytes(m->u.certificateRequest.types);
1220 for(i=0; i<m->u.certificateRequest.nca; i++)
1221 freebytes(m->u.certificateRequest.cas[i]);
1222 free(m->u.certificateRequest.cas);
1224 case HServerHelloDone:
1226 case HClientKeyExchange:
1227 freebytes(m->u.clientKeyExchange.key);
1232 memset(m, 0, sizeof(Msg));
1236 bytesPrint(char *bs, char *be, char *s0, Bytes *b, char *s1)
1241 bs = seprint(bs, be, "%s", s0);
1242 bs = seprint(bs, be, "[");
1244 bs = seprint(bs, be, "nil");
1246 for(i=0; i<b->len; i++)
1247 bs = seprint(bs, be, "%.2x ", b->data[i]);
1248 bs = seprint(bs, be, "]");
1250 bs = seprint(bs, be, "%s", s1);
1255 intsPrint(char *bs, char *be, char *s0, Ints *b, char *s1)
1260 bs = seprint(bs, be, "%s", s0);
1261 bs = seprint(bs, be, "[");
1263 bs = seprint(bs, be, "nil");
1265 for(i=0; i<b->len; i++)
1266 bs = seprint(bs, be, "%x ", b->data[i]);
1267 bs = seprint(bs, be, "]");
1269 bs = seprint(bs, be, "%s", s1);
1274 msgPrint(char *buf, int n, Msg *m)
1277 char *bs = buf, *be = buf+n;
1281 bs = seprint(bs, be, "unknown %d\n", m->tag);
1284 bs = seprint(bs, be, "ClientHello\n");
1285 bs = seprint(bs, be, "\tversion: %.4x\n", m->u.clientHello.version);
1286 bs = seprint(bs, be, "\trandom: ");
1287 for(i=0; i<RandomSize; i++)
1288 bs = seprint(bs, be, "%.2x", m->u.clientHello.random[i]);
1289 bs = seprint(bs, be, "\n");
1290 bs = bytesPrint(bs, be, "\tsid: ", m->u.clientHello.sid, "\n");
1291 bs = intsPrint(bs, be, "\tciphers: ", m->u.clientHello.ciphers, "\n");
1292 bs = bytesPrint(bs, be, "\tcompressors: ", m->u.clientHello.compressors, "\n");
1295 bs = seprint(bs, be, "ServerHello\n");
1296 bs = seprint(bs, be, "\tversion: %.4x\n", m->u.serverHello.version);
1297 bs = seprint(bs, be, "\trandom: ");
1298 for(i=0; i<RandomSize; i++)
1299 bs = seprint(bs, be, "%.2x", m->u.serverHello.random[i]);
1300 bs = seprint(bs, be, "\n");
1301 bs = bytesPrint(bs, be, "\tsid: ", m->u.serverHello.sid, "\n");
1302 bs = seprint(bs, be, "\tcipher: %.4x\n", m->u.serverHello.cipher);
1303 bs = seprint(bs, be, "\tcompressor: %.2x\n", m->u.serverHello.compressor);
1306 bs = seprint(bs, be, "Certificate\n");
1307 for(i=0; i<m->u.certificate.ncert; i++)
1308 bs = bytesPrint(bs, be, "\t", m->u.certificate.certs[i], "\n");
1310 case HCertificateRequest:
1311 bs = seprint(bs, be, "CertificateRequest\n");
1312 bs = bytesPrint(bs, be, "\ttypes: ", m->u.certificateRequest.types, "\n");
1313 bs = seprint(bs, be, "\tcertificateauthorities\n");
1314 for(i=0; i<m->u.certificateRequest.nca; i++)
1315 bs = bytesPrint(bs, be, "\t\t", m->u.certificateRequest.cas[i], "\n");
1317 case HServerHelloDone:
1318 bs = seprint(bs, be, "ServerHelloDone\n");
1320 case HClientKeyExchange:
1321 bs = seprint(bs, be, "HClientKeyExchange\n");
1322 bs = bytesPrint(bs, be, "\tkey: ", m->u.clientKeyExchange.key, "\n");
1325 bs = seprint(bs, be, "HFinished\n");
1326 for(i=0; i<m->u.finished.n; i++)
1327 bs = seprint(bs, be, "%.2x", m->u.finished.verify[i]);
1328 bs = seprint(bs, be, "\n");
1336 tlsError(TlsConnection *c, int err, char *fmt, ...)
1342 vseprint(msg, msg+sizeof(msg), fmt, arg);
1345 c->trace("tlsError: %s\n", msg);
1347 fprint(2, "double error: %r, %s", msg);
1349 werrstr("tls: local %s", msg);
1351 fprint(c->ctl, "alert %d", err);
1354 // commit to specific version number
1356 setVersion(TlsConnection *c, int version)
1358 if(c->verset || version > MaxProtoVersion || version < MinProtoVersion)
1360 if(version > c->version)
1361 version = c->version;
1362 if(version == SSL3Version) {
1363 c->version = version;
1364 c->finished.n = SSL3FinishedLen;
1365 }else if(version == TLSVersion){
1366 c->version = version;
1367 c->finished.n = TLSFinishedLen;
1371 return fprint(c->ctl, "version 0x%x", version);
1374 // confirm that received Finished message matches the expected value
1376 finishedMatch(TlsConnection *c, Finished *f)
1378 return memcmp(f->verify, c->finished.verify, f->n) == 0;
1381 // free memory associated with TlsConnection struct
1382 // (but don't close the TLS channel itself)
1384 tlsConnectionFree(TlsConnection *c)
1386 tlsSecClose(c->sec);
1389 memset(c, 0, sizeof(c));
1394 //================= cipher choices ========================
1396 static int weakCipher[CipherMax] =
1398 1, /* TLS_NULL_WITH_NULL_NULL */
1399 1, /* TLS_RSA_WITH_NULL_MD5 */
1400 1, /* TLS_RSA_WITH_NULL_SHA */
1401 1, /* TLS_RSA_EXPORT_WITH_RC4_40_MD5 */
1402 0, /* TLS_RSA_WITH_RC4_128_MD5 */
1403 0, /* TLS_RSA_WITH_RC4_128_SHA */
1404 1, /* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 */
1405 0, /* TLS_RSA_WITH_IDEA_CBC_SHA */
1406 1, /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA */
1407 0, /* TLS_RSA_WITH_DES_CBC_SHA */
1408 0, /* TLS_RSA_WITH_3DES_EDE_CBC_SHA */
1409 1, /* TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA */
1410 0, /* TLS_DH_DSS_WITH_DES_CBC_SHA */
1411 0, /* TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA */
1412 1, /* TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA */
1413 0, /* TLS_DH_RSA_WITH_DES_CBC_SHA */
1414 0, /* TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA */
1415 1, /* TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA */
1416 0, /* TLS_DHE_DSS_WITH_DES_CBC_SHA */
1417 0, /* TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA */
1418 1, /* TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA */
1419 0, /* TLS_DHE_RSA_WITH_DES_CBC_SHA */
1420 0, /* TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA */
1421 1, /* TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 */
1422 1, /* TLS_DH_anon_WITH_RC4_128_MD5 */
1423 1, /* TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA */
1424 1, /* TLS_DH_anon_WITH_DES_CBC_SHA */
1425 1, /* TLS_DH_anon_WITH_3DES_EDE_CBC_SHA */
1429 setAlgs(TlsConnection *c, int a)
1433 for(i = 0; i < nelem(cipherAlgs); i++){
1434 if(cipherAlgs[i].tlsid == a){
1435 c->enc = cipherAlgs[i].enc;
1436 c->digest = cipherAlgs[i].digest;
1437 c->nsecret = cipherAlgs[i].nsecret;
1438 if(c->nsecret > MaxKeyData)
1452 for(i = 0; i < cv->len; i++) {
1457 weak &= weakCipher[c];
1458 for(j = 0; j < nelem(cipherAlgs); j++)
1459 if(cipherAlgs[j].ok && cipherAlgs[j].tlsid == c)
1468 okCompression(Bytes *cv)
1472 for(i = 0; i < cv->len; i++) {
1474 for(j = 0; j < nelem(compressors); j++) {
1475 if(compressors[j] == c)
1482 static Lock ciphLock;
1483 static int nciphers;
1488 enum {MaxAlgF = 1024, MaxAlgs = 10};
1489 char s[MaxAlgF], *flds[MaxAlgs];
1497 j = open("#a/tls/encalgs", OREAD);
1499 werrstr("can't open #a/tls/encalgs: %r");
1502 n = read(j, s, MaxAlgF-1);
1505 werrstr("nothing in #a/tls/encalgs: %r");
1509 n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
1510 for(i = 0; i < nelem(cipherAlgs); i++){
1512 for(j = 0; j < n; j++){
1513 if(strcmp(cipherAlgs[i].enc, flds[j]) == 0){
1518 cipherAlgs[i].ok = ok;
1521 j = open("#a/tls/hashalgs", OREAD);
1523 werrstr("can't open #a/tls/hashalgs: %r");
1526 n = read(j, s, MaxAlgF-1);
1529 werrstr("nothing in #a/tls/hashalgs: %r");
1533 n = getfields(s, flds, MaxAlgs, 1, " \t\r\n");
1534 for(i = 0; i < nelem(cipherAlgs); i++){
1536 for(j = 0; j < n; j++){
1537 if(strcmp(cipherAlgs[i].digest, flds[j]) == 0){
1542 cipherAlgs[i].ok &= ok;
1543 if(cipherAlgs[i].ok)
1556 is = newints(nciphers);
1558 for(i = 0; i < nelem(cipherAlgs); i++){
1559 if(cipherAlgs[i].ok)
1560 is->data[j++] = cipherAlgs[i].tlsid;
1567 //================= security functions ========================
1569 // given X.509 certificate, set up connection to factotum
1570 // for using corresponding private key
1572 factotum_rsa_open(uchar *cert, int certlen)
1580 // start talking to factotum
1581 if((afd = open("/mnt/factotum/rpc", ORDWR)) < 0)
1583 if((rpc = auth_allocrpc(afd)) == nil){
1587 s = "proto=rsa service=tls role=client";
1588 if(auth_rpc(rpc, "start", s, strlen(s)) != ARok){
1589 factotum_rsa_close(rpc);
1593 // roll factotum keyring around to match certificate
1594 rsapub = X509toRSApub(cert, certlen, nil, 0);
1596 if(auth_rpc(rpc, "read", nil, 0) != ARok){
1597 factotum_rsa_close(rpc);
1601 pub = strtomp(rpc->arg, nil, 16, nil);
1603 if(mpcmp(pub,rsapub->n) == 0)
1613 factotum_rsa_decrypt(AuthRpc *rpc, mpint *cipher)
1618 if((p = mptoa(cipher, 16, nil, 0)) == nil)
1620 rv = auth_rpc(rpc, "write", p, strlen(p));
1622 if(rv != ARok || auth_rpc(rpc, "read", nil, 0) != ARok)
1625 return strtomp(rpc->arg, nil, 16, nil);
1629 factotum_rsa_close(AuthRpc*rpc)
1638 tlsPmd5(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1640 uchar ai[MD5dlen], tmp[MD5dlen];
1645 s = hmac_md5(label, nlabel, key, nkey, nil, nil);
1646 s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
1647 hmac_md5(seed1, nseed1, key, nkey, ai, s);
1650 s = hmac_md5(ai, MD5dlen, key, nkey, nil, nil);
1651 s = hmac_md5(label, nlabel, key, nkey, nil, s);
1652 s = hmac_md5(seed0, nseed0, key, nkey, nil, s);
1653 hmac_md5(seed1, nseed1, key, nkey, tmp, s);
1657 for(i = 0; i < n; i++)
1661 hmac_md5(ai, MD5dlen, key, nkey, tmp, nil);
1662 memmove(ai, tmp, MD5dlen);
1667 tlsPsha1(uchar *buf, int nbuf, uchar *key, int nkey, uchar *label, int nlabel, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1669 uchar ai[SHA1dlen], tmp[SHA1dlen];
1674 s = hmac_sha1(label, nlabel, key, nkey, nil, nil);
1675 s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
1676 hmac_sha1(seed1, nseed1, key, nkey, ai, s);
1679 s = hmac_sha1(ai, SHA1dlen, key, nkey, nil, nil);
1680 s = hmac_sha1(label, nlabel, key, nkey, nil, s);
1681 s = hmac_sha1(seed0, nseed0, key, nkey, nil, s);
1682 hmac_sha1(seed1, nseed1, key, nkey, tmp, s);
1686 for(i = 0; i < n; i++)
1690 hmac_sha1(ai, SHA1dlen, key, nkey, tmp, nil);
1691 memmove(ai, tmp, SHA1dlen);
1695 // fill buf with md5(args)^sha1(args)
1697 tlsPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
1700 int nlabel = strlen(label);
1701 int n = (nkey + 1) >> 1;
1703 for(i = 0; i < nbuf; i++)
1705 tlsPmd5(buf, nbuf, key, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
1706 tlsPsha1(buf, nbuf, key+nkey-n, n, (uchar*)label, nlabel, seed0, nseed0, seed1, nseed1);
1710 * for setting server session id's
1712 static Lock sidLock;
1713 static long maxSid = 1;
1715 /* the keys are verified to have the same public components
1716 * and to function correctly with pkcs 1 encryption and decryption. */
1718 tlsSecInits(int cvers, uchar *csid, int ncsid, uchar *crandom, uchar *ssid, int *nssid, uchar *srandom)
1720 TlsSec *sec = emalloc(sizeof(*sec));
1722 USED(csid); USED(ncsid); // ignore csid for now
1724 memmove(sec->crandom, crandom, RandomSize);
1725 sec->clientVers = cvers;
1727 put32(sec->srandom, time(0));
1728 genrandom(sec->srandom+4, RandomSize-4);
1729 memmove(srandom, sec->srandom, RandomSize);
1732 * make up a unique sid: use our pid, and and incrementing id
1733 * can signal no sid by setting nssid to 0.
1735 memset(ssid, 0, SidSize);
1736 put32(ssid, getpid());
1738 put32(ssid+4, maxSid++);
1745 tlsSecSecrets(TlsSec *sec, int vers, uchar *epm, int nepm, uchar *kd, int nkd)
1748 if(setVers(sec, vers) < 0)
1750 serverMasterSecret(sec, epm, nepm);
1751 }else if(sec->vers != vers){
1752 werrstr("mismatched session versions");
1755 setSecrets(sec, kd, nkd);
1763 tlsSecInitc(int cvers, uchar *crandom)
1765 TlsSec *sec = emalloc(sizeof(*sec));
1766 sec->clientVers = cvers;
1767 put32(sec->crandom, time(0));
1768 genrandom(sec->crandom+4, RandomSize-4);
1769 memmove(crandom, sec->crandom, RandomSize);
1774 tlsSecSecretc(TlsSec *sec, uchar *sid, int nsid, uchar *srandom, uchar *cert, int ncert, int vers, uchar **epm, int *nepm, uchar *kd, int nkd)
1783 memmove(sec->srandom, srandom, RandomSize);
1785 if(setVers(sec, vers) < 0)
1788 pub = X509toRSApub(cert, ncert, nil, 0);
1790 werrstr("invalid x509/rsa certificate");
1793 if(clientMasterSecret(sec, pub, epm, nepm) < 0)
1796 setSecrets(sec, kd, nkd);
1807 tlsSecFinished(TlsSec *sec, MD5state md5, SHAstate sha1, uchar *fin, int nfin, int isclient)
1809 if(sec->nfin != nfin){
1811 werrstr("invalid finished exchange");
1816 (*sec->setFinished)(sec, md5, sha1, fin, isclient);
1821 tlsSecOk(TlsSec *sec)
1828 tlsSecKill(TlsSec *sec)
1832 factotum_rsa_close(sec->rpc);
1837 tlsSecClose(TlsSec *sec)
1841 factotum_rsa_close(sec->rpc);
1847 setVers(TlsSec *sec, int v)
1849 if(v == SSL3Version){
1850 sec->setFinished = sslSetFinished;
1851 sec->nfin = SSL3FinishedLen;
1853 }else if(v == TLSVersion){
1854 sec->setFinished = tlsSetFinished;
1855 sec->nfin = TLSFinishedLen;
1858 werrstr("invalid version");
1866 * generate secret keys from the master secret.
1868 * different crypto selections will require different amounts
1869 * of key expansion and use of key expansion data,
1870 * but it's all generated using the same function.
1873 setSecrets(TlsSec *sec, uchar *kd, int nkd)
1875 (*sec->prf)(kd, nkd, sec->sec, MasterSecretSize, "key expansion",
1876 sec->srandom, RandomSize, sec->crandom, RandomSize);
1880 * set the master secret from the pre-master secret.
1883 setMasterSecret(TlsSec *sec, Bytes *pm)
1885 (*sec->prf)(sec->sec, MasterSecretSize, pm->data, MasterSecretSize, "master secret",
1886 sec->crandom, RandomSize, sec->srandom, RandomSize);
1890 serverMasterSecret(TlsSec *sec, uchar *epm, int nepm)
1894 pm = pkcs1_decrypt(sec, epm, nepm);
1896 // if the client messed up, just continue as if everything is ok,
1897 // to prevent attacks to check for correctly formatted messages.
1898 // Hence the fprint(2,) can't be replaced by tlsError(), which sends an Alert msg to the client.
1899 if(sec->ok < 0 || pm == nil || get16(pm->data) != sec->clientVers){
1900 fprint(2, "serverMasterSecret failed ok=%d pm=%p pmvers=%x cvers=%x nepm=%d\n",
1901 sec->ok, pm, pm ? get16(pm->data) : -1, sec->clientVers, nepm);
1905 pm = newbytes(MasterSecretSize);
1906 genrandom(pm->data, MasterSecretSize);
1908 setMasterSecret(sec, pm);
1909 memset(pm->data, 0, pm->len);
1914 clientMasterSecret(TlsSec *sec, RSApub *pub, uchar **epm, int *nepm)
1918 pm = newbytes(MasterSecretSize);
1919 put16(pm->data, sec->clientVers);
1920 genrandom(pm->data+2, MasterSecretSize - 2);
1922 setMasterSecret(sec, pm);
1924 key = pkcs1_encrypt(pm, pub, 2);
1925 memset(pm->data, 0, pm->len);
1928 werrstr("tls pkcs1_encrypt failed");
1933 *epm = malloc(*nepm);
1936 werrstr("out of memory");
1939 memmove(*epm, key->data, *nepm);
1947 sslSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
1950 uchar h0[MD5dlen], h1[SHA1dlen], pad[48];
1958 md5((uchar*)label, 4, nil, &hsmd5);
1959 md5(sec->sec, MasterSecretSize, nil, &hsmd5);
1960 memset(pad, 0x36, 48);
1961 md5(pad, 48, nil, &hsmd5);
1962 md5(nil, 0, h0, &hsmd5);
1963 memset(pad, 0x5C, 48);
1964 s = md5(sec->sec, MasterSecretSize, nil, nil);
1965 s = md5(pad, 48, nil, s);
1966 md5(h0, MD5dlen, finished, s);
1968 sha1((uchar*)label, 4, nil, &hssha1);
1969 sha1(sec->sec, MasterSecretSize, nil, &hssha1);
1970 memset(pad, 0x36, 40);
1971 sha1(pad, 40, nil, &hssha1);
1972 sha1(nil, 0, h1, &hssha1);
1973 memset(pad, 0x5C, 40);
1974 s = sha1(sec->sec, MasterSecretSize, nil, nil);
1975 s = sha1(pad, 40, nil, s);
1976 sha1(h1, SHA1dlen, finished + MD5dlen, s);
1979 // fill "finished" arg with md5(args)^sha1(args)
1981 tlsSetFinished(TlsSec *sec, MD5state hsmd5, SHAstate hssha1, uchar *finished, int isClient)
1983 uchar h0[MD5dlen], h1[SHA1dlen];
1986 // get current hash value, but allow further messages to be hashed in
1987 md5(nil, 0, h0, &hsmd5);
1988 sha1(nil, 0, h1, &hssha1);
1991 label = "client finished";
1993 label = "server finished";
1994 tlsPRF(finished, TLSFinishedLen, sec->sec, MasterSecretSize, label, h0, MD5dlen, h1, SHA1dlen);
1998 sslPRF(uchar *buf, int nbuf, uchar *key, int nkey, char *label, uchar *seed0, int nseed0, uchar *seed1, int nseed1)
2001 uchar sha1dig[SHA1dlen], md5dig[MD5dlen], tmp[26];
2009 for(i = 0; i < len; i++)
2010 tmp[i] = 'A' - 1 + len;
2011 s = sha1(tmp, len, nil, nil);
2012 s = sha1(key, nkey, nil, s);
2013 s = sha1(seed0, nseed0, nil, s);
2014 sha1(seed1, nseed1, sha1dig, s);
2015 s = md5(key, nkey, nil, nil);
2016 md5(sha1dig, SHA1dlen, md5dig, s);
2020 memmove(buf, md5dig, n);
2028 bytestomp(Bytes* bytes)
2032 ans = betomp(bytes->data, bytes->len, nil);
2037 * Convert mpint* to Bytes, putting high order byte first.
2040 mptobytes(mpint* big)
2046 n = (mpsignif(big)+7)/8;
2047 m = mptobe(big, nil, n, &a);
2048 ans = makebytes(a, m);
2052 // Do RSA computation on block according to key, and pad
2053 // result on left with zeros to make it modlen long.
2055 rsacomp(Bytes* block, RSApub* key, int modlen)
2061 x = bytestomp(block);
2062 y = rsaencrypt(key, x, nil);
2064 ybytes = mptobytes(y);
2068 a = newbytes(modlen);
2069 memset(a->data, 0, modlen-ylen);
2070 memmove(a->data+modlen-ylen, ybytes->data, ylen);
2074 else if(ylen > modlen) {
2075 // assume it has leading zeros (mod should make it so)
2076 a = newbytes(modlen);
2077 memmove(a->data, ybytes->data, modlen);
2085 // encrypt data according to PKCS#1, /lib/rfc/rfc2437 9.1.2.1
2087 pkcs1_encrypt(Bytes* data, RSApub* key, int blocktype)
2089 Bytes *pad, *eb, *ans;
2090 int i, dlen, padlen, modlen;
2092 modlen = (mpsignif(key->n)+7)/8;
2094 if(modlen < 12 || dlen > modlen - 11)
2096 padlen = modlen - 3 - dlen;
2097 pad = newbytes(padlen);
2098 genrandom(pad->data, padlen);
2099 for(i = 0; i < padlen; i++) {
2102 else if(blocktype == 1)
2104 else if(pad->data[i] == 0)
2107 eb = newbytes(modlen);
2109 eb->data[1] = blocktype;
2110 memmove(eb->data+2, pad->data, padlen);
2111 eb->data[padlen+2] = 0;
2112 memmove(eb->data+padlen+3, data->data, dlen);
2113 ans = rsacomp(eb, key, modlen);
2119 // decrypt data according to PKCS#1, with given key.
2120 // expect a block type of 2.
2122 pkcs1_decrypt(TlsSec *sec, uchar *epm, int nepm)
2124 Bytes *eb, *ans = nil;
2128 modlen = (mpsignif(sec->rsapub->n)+7)/8;
2131 x = betomp(epm, nepm, nil);
2132 y = factotum_rsa_decrypt(sec->rpc, x);
2136 if(eb->len < modlen){ // pad on left with zeros
2137 ans = newbytes(modlen);
2138 memset(ans->data, 0, modlen-eb->len);
2139 memmove(ans->data+modlen-eb->len, eb->data, eb->len);
2143 if(eb->data[0] == 0 && eb->data[1] == 2) {
2144 for(i = 2; i < modlen; i++)
2145 if(eb->data[i] == 0)
2148 ans = makebytes(eb->data+i+1, modlen-(i+1));
2155 //================= general utility functions ========================
2165 exits("out of memory");
2172 erealloc(void *ReallocP, int ReallocN)
2177 ReallocP = emalloc(ReallocN);
2178 else if(!(ReallocP = realloc(ReallocP, ReallocN))){
2179 exits("out of memory");
2185 put32(uchar *p, u32int x)
2194 put24(uchar *p, int x)
2202 put16(uchar *p, int x)
2211 return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
2217 return (p[0]<<16)|(p[1]<<8)|p[2];
2223 return (p[0]<<8)|p[1];
2226 /* ANSI offsetof() */
2227 #define OFFSET(x, s) ((int)(&(((s*)0)->x)))
2230 * malloc and return a new Bytes structure capable of
2231 * holding len bytes. (len >= 0)
2232 * Used to use crypt_malloc, which aborts if malloc fails.
2239 ans = (Bytes*)malloc(OFFSET(data[0], Bytes) + len);
2245 * newbytes(len), with data initialized from buf
2248 makebytes(uchar* buf, int len)
2252 ans = newbytes(len);
2253 memmove(ans->data, buf, len);
2264 /* len is number of ints */
2270 ans = (Ints*)malloc(OFFSET(data[0], Ints) + len*sizeof(int));
2276 makeints(int* buf, int len)
2282 memmove(ans->data, buf, len*sizeof(int));