2 * devtls - record layer for transport layer security 1.2 and secure sockets layer 3.0
5 #include "../port/lib.h"
9 #include "../port/error.h"
13 typedef struct OneWay OneWay;
14 typedef struct Secret Secret;
15 typedef struct TlsRec TlsRec;
16 typedef struct TlsErrs TlsErrs;
19 Statlen= 1024, /* max. length of status or stats message */
21 MaxRecLen = 1<<14, /* max payload length of a record layer message */
22 MaxCipherRecLen = MaxRecLen + 2048,
24 MaxMacLen = SHA2_256dlen,
26 /* protocol versions we can accept */
28 TLS10Version = 0x0301,
29 TLS11Version = 0x0302,
30 TLS12Version = 0x0303,
31 MinProtoVersion = 0x0300, /* limits on version we accept */
32 MaxProtoVersion = 0x03ff,
34 /* connection states */
35 SHandshake = 1 << 0, /* doing handshake */
36 SOpen = 1 << 1, /* application data can be sent */
37 SRClose = 1 << 2, /* remote side has closed down */
38 SLClose = 1 << 3, /* sent a close notify alert */
39 SAlert = 1 << 5, /* sending or sent a fatal alert */
40 SError = 1 << 6, /* some sort of error has occured */
41 SClosed = 1 << 7, /* it is all over */
44 RChangeCipherSpec = 20,
50 HSSL2ClientHello = 9, /* local convention; see tlshand.c */
54 EUnexpectedMessage = 10,
56 EDecryptionFailed = 21,
58 EDecompressionFailure = 30,
59 EHandshakeFailure = 40,
62 EUnsupportedCertificate = 43,
63 ECertificateRevoked = 44,
64 ECertificateExpired = 45,
65 ECertificateUnknown = 46,
66 EIllegalParameter = 47,
71 EExportRestriction = 60,
72 EProtocolVersion = 70,
73 EInsufficientSecurity = 71,
76 ENoRenegotiation = 100,
77 EUnrecognizedName = 112,
84 char *encalg; /* name of encryption alg */
85 char *hashalg; /* name of hash alg */
87 int (*aead_enc)(Secret*, uchar*, int, uchar*, uchar*, int);
88 int (*aead_dec)(Secret*, uchar*, int, uchar*, uchar*, int);
90 int (*enc)(Secret*, uchar*, int);
91 int (*dec)(Secret*, uchar*, int);
92 int (*unpad)(uchar*, int, int);
93 DigestState* (*mac)(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
95 int block; /* encryption block len, 0 if none */
96 int maclen; /* # bytes of record mac / authentication tag */
97 int recivlen; /* # bytes of record iv for AEAD ciphers */
99 uchar mackey[MaxMacLen];
104 QLock io; /* locks io access */
105 QLock seclock; /* locks secret paramaters */
107 Secret *sec; /* cipher in use */
108 Secret *new; /* cipher waiting for enable */
113 Chan *c; /* io channel */
114 int ref; /* serialized by tdlock for atomic destroy */
115 int version; /* version of the protocol we are speaking */
116 char verset; /* version has been set */
117 char opened; /* opened command every issued? */
118 char err[ERRMAX]; /* error message to return to handshake requests */
119 vlong handin; /* bytes communicated by the record layer */
129 * function to genrate authenticated data blob for different
132 int (*packAAD)(u64int, uchar*, uchar*);
134 /* input side -- protected by in.io */
136 Block *processed; /* next bunch of application data */
137 Block *unprocessed; /* data read from c but not parsed into records */
139 /* handshake queue */
140 Lock hqlock; /* protects hqref, alloc & free of handq, hprocessed */
142 Queue *handq; /* queue of handshake messages */
143 Block *hprocessed; /* remainder of last block read from handq */
144 QLock hqread; /* protects reads for hprocessed, handq */
162 static TlsErrs tlserrs[] = {
163 {ECloseNotify, ECloseNotify, ECloseNotify, 0, "close notify"},
164 {EUnexpectedMessage, EUnexpectedMessage, EUnexpectedMessage, 1, "unexpected message"},
165 {EBadRecordMac, EBadRecordMac, EBadRecordMac, 1, "bad record mac"},
166 {EDecryptionFailed, EIllegalParameter, EDecryptionFailed, 1, "decryption failed"},
167 {ERecordOverflow, EIllegalParameter, ERecordOverflow, 1, "record too long"},
168 {EDecompressionFailure, EDecompressionFailure, EDecompressionFailure, 1, "decompression failed"},
169 {EHandshakeFailure, EHandshakeFailure, EHandshakeFailure, 1, "could not negotiate acceptable security parameters"},
170 {ENoCertificate, ENoCertificate, ECertificateUnknown, 1, "no appropriate certificate available"},
171 {EBadCertificate, EBadCertificate, EBadCertificate, 1, "corrupted or invalid certificate"},
172 {EUnsupportedCertificate, EUnsupportedCertificate, EUnsupportedCertificate, 1, "unsupported certificate type"},
173 {ECertificateRevoked, ECertificateRevoked, ECertificateRevoked, 1, "revoked certificate"},
174 {ECertificateExpired, ECertificateExpired, ECertificateExpired, 1, "expired certificate"},
175 {ECertificateUnknown, ECertificateUnknown, ECertificateUnknown, 1, "unacceptable certificate"},
176 {EIllegalParameter, EIllegalParameter, EIllegalParameter, 1, "illegal parameter"},
177 {EUnknownCa, EHandshakeFailure, EUnknownCa, 1, "unknown certificate authority"},
178 {EAccessDenied, EHandshakeFailure, EAccessDenied, 1, "access denied"},
179 {EDecodeError, EIllegalParameter, EDecodeError, 1, "error decoding message"},
180 {EDecryptError, EIllegalParameter, EDecryptError, 1, "error decrypting message"},
181 {EExportRestriction, EHandshakeFailure, EExportRestriction, 1, "export restriction violated"},
182 {EProtocolVersion, EIllegalParameter, EProtocolVersion, 1, "protocol version not supported"},
183 {EInsufficientSecurity, EHandshakeFailure, EInsufficientSecurity, 1, "stronger security routines required"},
184 {EInternalError, EHandshakeFailure, EInternalError, 1, "internal error"},
185 {EUserCanceled, ECloseNotify, EUserCanceled, 0, "handshake canceled by user"},
186 {ENoRenegotiation, EUnexpectedMessage, ENoRenegotiation, 0, "no renegotiation"},
191 /* max. open tls connections */
197 static int maxtlsdevs = 128;
198 static TlsRec **tlsdevs;
199 static char **trnames;
200 static char *encalgs;
201 static char *hashalgs;
204 Qtopdir = 1, /* top level directory */
209 Qconvdir, /* directory for a conversation */
217 #define TYPE(x) ((x).path & 0xf)
218 #define CONV(x) (((x).path >> 5)&(MaxTlsDevs-1))
219 #define QID(c, y) (((c)<<5) | (y))
221 static void checkstate(TlsRec *, int, int);
222 static void ensure(TlsRec*, Block**, int);
223 static void consume(Block**, uchar*, int);
224 static Chan* buftochan(char*);
225 static void tlshangup(TlsRec*);
226 static void tlsError(TlsRec*, char *);
227 static void alertHand(TlsRec*, char *);
228 static TlsRec *newtls(Chan *c);
229 static TlsRec *mktlsrec(void);
230 static DigestState*sslmac_md5(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
231 static DigestState*sslmac_sha1(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
232 static DigestState*nomac(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
233 static int sslPackAAD(u64int, uchar*, uchar*);
234 static int tlsPackAAD(u64int, uchar*, uchar*);
235 static void packMac(Secret*, uchar*, int, uchar*, int, uchar*);
236 static void put64(uchar *p, u64int);
237 static void put32(uchar *p, u32int);
238 static void put24(uchar *p, int);
239 static void put16(uchar *p, int);
240 static u32int get32(uchar *p);
241 static int get16(uchar *p);
242 static void tlsSetState(TlsRec *tr, int new, int old);
243 static void rcvAlert(TlsRec *tr, int err);
244 static void sendAlert(TlsRec *tr, int err);
245 static void rcvError(TlsRec *tr, int err, char *msg, ...);
246 static int rc4enc(Secret *sec, uchar *buf, int n);
247 static int des3enc(Secret *sec, uchar *buf, int n);
248 static int des3dec(Secret *sec, uchar *buf, int n);
249 static int aesenc(Secret *sec, uchar *buf, int n);
250 static int aesdec(Secret *sec, uchar *buf, int n);
251 static int ccpoly_aead_enc(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len);
252 static int ccpoly_aead_dec(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len);
253 static int aesgcm_aead_enc(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len);
254 static int aesgcm_aead_dec(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len);
255 static int noenc(Secret *sec, uchar *buf, int n);
256 static int sslunpad(uchar *buf, int n, int block);
257 static int tlsunpad(uchar *buf, int n, int block);
258 static void freeSec(Secret *sec);
259 static char *tlsstate(int s);
260 static void pdump(int, void*, char*);
262 #pragma varargck argpos rcvError 3
264 static char *tlsnames[] = {
266 [Qencalgs] "encalgs",
267 [Qhashalgs] "hashalgs",
275 static int convdir[] = { Qctl, Qdata, Qhand, Qstatus, Qstats };
278 tlsgen(Chan *c, char*, Dirtab *, int, int s, Dir *dp)
292 q.path = QID(0, Qtopdir);
294 devdir(c, q, "#a", 0, eve, 0555, dp);
299 q.path = QID(0, Qprotodir);
301 devdir(c, q, "tls", 0, eve, 0555, dp);
305 q.path = QID(0, Qtopdir);
307 devdir(c, q, ".", 0, eve, 0555, dp);
315 q.path = QID(0, Qclonus);
318 q.path = QID(0, Qencalgs);
321 q.path = QID(0, Qhashalgs);
325 if(TYPE(q) == Qclonus)
327 devdir(c, q, tlsnames[TYPE(q)], 0, eve, perm, dp);
333 q.path = QID(s, Qconvdir);
341 if((name = trnames[s]) == nil){
342 name = trnames[s] = smalloc(16);
343 sprint(name, "%d", s);
345 devdir(c, q, name, 0, nm, 0555, dp);
350 q.path = QID(0, Qprotodir);
352 devdir(c, q, "tls", 0, eve, 0555, dp);
355 if(s < 0 || s >= nelem(convdir))
358 tr = tlsdevs[CONV(c->qid)];
367 if(t == Qstatus || t == Qstats)
369 q.path = QID(CONV(c->qid), t);
370 devdir(c, q, tlsnames[t], 0, nm, perm, dp);
379 devdir(c, c->qid, tlsnames[t], 0, eve, perm, dp);
383 tr = tlsdevs[CONV(c->qid)];
391 if(t == Qstatus || t == Qstats)
393 devdir(c, c->qid, tlsnames[t], 0, nm, perm, dp);
400 tlsattach(char *spec)
404 c = devattach('a', spec);
405 c->qid.path = QID(0, Qtopdir);
412 tlswalk(Chan *c, Chan *nc, char **name, int nname)
414 return devwalk(c, nc, name, nname, nil, 0, tlsgen);
418 tlsstat(Chan *c, uchar *db, int n)
420 return devstat(c, db, n, nil, 0, tlsgen);
424 tlsopen(Chan *c, int omode)
449 if((t == Qstatus || t == Qstats) && omode != OREAD)
456 pp = &tlsdevs[CONV(c->qid)];
459 error("must open connection using clone");
460 devpermcheck(tr->user, tr->perm, omode);
469 tr->handq = qopen(2 * MaxCipherRecLen, 0, nil, nil);
471 error("cannot allocate handshake queue");
486 c->mode = openmode(omode);
489 c->iounit = MaxRecLen;
494 tlswstat(Chan *c, uchar *dp, int n)
508 tr = tlsdevs[CONV(c->qid)];
511 if(strcmp(tr->user, up->user) != 0)
514 d = smalloc(n + sizeof *d);
515 rv = convM2D(dp, n, &d[0], (char*) &d[1]);
518 if(!emptystr(d->uid))
519 kstrdup(&tr->user, d->uid);
534 if(--tr->hqref == 0){
535 if(tr->handq != nil){
539 if(tr->hprocessed != nil){
540 freeb(tr->hprocessed);
541 tr->hprocessed = nil;
560 if((c->flag & COPEN) == 0)
563 tr = tlsdevs[CONV(c->qid)];
575 tlsdevs[CONV(c->qid)] = nil;
578 if(tr->c != nil && !waserror()){
579 checkstate(tr, 0, SOpen|SHandshake|SRClose);
580 sendAlert(tr, ECloseNotify);
588 freeSec(tr->out.sec);
589 freeSec(tr->out.new);
597 * make sure we have at least 'n' bytes in list 'l'
600 ensure(TlsRec *s, Block **l, int n)
606 for(b = *l; b; b = b->next){
614 bl = devtab[s->c->type]->bread(s->c, MaxCipherRecLen + RecHdrLen, 0);
619 for(b = bl; b; b = b->next){
627 if(s->debug) pprint("ensure read %d\n", sofar);
631 * copy 'n' bytes from 'l' into 'p' and free
635 consume(Block **l, uchar *p, int n)
640 for(; *l && n > 0; n -= i){
645 memmove(p, b->rp, i);
661 regurgitate(TlsRec *s, uchar *p, int n)
668 if(s->unprocessed == nil || b->rp - b->base < n) {
670 memmove(b->wp, p, n);
672 b->next = s->unprocessed;
676 memmove(b->rp, p, n);
681 * remove at most n bytes from the queue
684 qgrab(Block **l, int n)
697 for(bb = b; bb != nil && i < n; bb = bb->next)
703 consume(l, bb->wp, i);
709 tlsclosed(TlsRec *tr, int new)
712 if(tr->state == SOpen || tr->state == SHandshake)
714 else if((new | tr->state) == (SRClose|SLClose))
716 unlock(&tr->statelk);
717 alertHand(tr, "close notify");
721 * read and process one tls record layer message
722 * must be called with tr->in.io held
723 * We can't let Eintrs lose data, since doing so will get
724 * us out of sync with the sender and break the reliablity
725 * of the channel. Eintr only happens during the reads in
726 * consume. Therefore we put back any bytes consumed before
727 * the last call to ensure.
730 tlsrecread(TlsRec *tr)
734 uchar *p, aad[8+RecHdrLen], header[RecHdrLen], hmac[MaxMacLen];
735 int volatile nconsumed;
736 int len, type, ver, unpad_len, aadlen, ivlen;
741 if(strcmp(up->errstr, Eintr) == 0 && !waserror()){
742 regurgitate(tr, header, nconsumed);
745 tlsError(tr, "channel error");
748 ensure(tr, &tr->unprocessed, RecHdrLen);
749 consume(&tr->unprocessed, header, RecHdrLen);
750 if(tr->debug)pprint("consumed %d header\n", RecHdrLen);
751 nconsumed = RecHdrLen;
753 if((tr->handin == 0) && (header[0] & 0x80)){
754 /* Cope with an SSL3 ClientHello expressed in SSL2 record format.
755 This is sent by some clients that we must interoperate
756 with, such as Java's JSSE and Microsoft's Internet Explorer. */
757 len = (get16(header) & ~0x8000) - 3;
759 ver = get16(header + 3);
760 if(type != SSL2ClientHello || len < 22)
761 rcvError(tr, EProtocolVersion, "invalid initial SSL2-like message");
762 }else{ /* normal SSL3 record format */
764 ver = get16(header+1);
765 len = get16(header+3);
767 if(ver != tr->version && (tr->verset || ver < MinProtoVersion || ver > MaxProtoVersion))
768 rcvError(tr, EProtocolVersion, "devtls expected ver=%x%s, saw (len=%d) type=%x ver=%x '%.12s'",
769 tr->version, tr->verset?"/set":"", len, type, ver, (char*)header);
770 if(len > MaxCipherRecLen || len < 0)
771 rcvError(tr, ERecordOverflow, "record message too long %d", len);
772 ensure(tr, &tr->unprocessed, len);
777 * If an Eintr happens after this, we'll get out of sync.
778 * Make sure nothing we call can sleep.
779 * Errors are ok, as they kill the connection.
780 * Luckily, allocb won't sleep, it'll just error out.
786 tlsError(tr, "channel error");
789 b = qgrab(&tr->unprocessed, len);
790 if(tr->debug) pprint("consumed unprocessed %d\n", len);
794 qunlock(&in->seclock);
801 /* to avoid Canvel-Hiltgen-Vaudenay-Vuagnoux attack, all errors here
802 should look alike, including timing of the response. */
803 if(sec->aead_dec != nil)
806 unpad_len = (*sec->dec)(sec, p, len);
807 if(tr->debug) pprint("decrypted %d\n", unpad_len);
808 if(tr->debug) pdump(unpad_len, p, "decrypted:");
811 ivlen = sec->recivlen;
812 if(tr->version >= TLS11Version){
818 rcvError(tr, EDecodeError, "runt record message");
822 if(unpad_len >= sec->maclen)
823 len = unpad_len - sec->maclen;
826 put16(header+3, len);
827 aadlen = (*tr->packAAD)(in->seq++, header, aad);
828 if(sec->aead_dec != nil) {
829 len = (*sec->aead_dec)(sec, aad, aadlen, p - ivlen, p, unpad_len);
831 rcvError(tr, EBadRecordMac, "record mac mismatch");
833 packMac(sec, aad, aadlen, p, len, hmac);
834 if(unpad_len < sec->maclen)
835 rcvError(tr, EBadRecordMac, "short record mac");
836 if(tsmemcmp(hmac, p + len, sec->maclen) != 0)
837 rcvError(tr, EBadRecordMac, "record mac mismatch");
842 qunlock(&in->seclock);
845 rcvError(tr, EDecodeError, "runt record message");
849 rcvError(tr, EIllegalParameter, "invalid record message %#x", type);
851 case RChangeCipherSpec:
852 if(len != 1 || p[0] != 1)
853 rcvError(tr, EDecodeError, "invalid change cipher spec");
856 qunlock(&in->seclock);
857 rcvError(tr, EUnexpectedMessage, "unexpected change cipher spec");
863 qunlock(&in->seclock);
867 rcvError(tr, EDecodeError, "invalid alert");
871 rcvError(tr, EIllegalParameter, "invalid alert fatal code");
874 * propagate non-fatal alerts to handshaker
878 tlsclosed(tr, SRClose);
881 error("close notify");
883 case ENoRenegotiation:
884 alertHand(tr, "no renegotiation");
887 alertHand(tr, "handshake canceled by user");
889 case EUnrecognizedName:
890 /* happens in response to SNI, can be ignored. */
893 rcvError(tr, EIllegalParameter, "invalid alert code");
898 * don't worry about dropping the block
899 * qbwrite always queues even if flow controlled and interrupted.
901 * if there isn't any handshaker, ignore the request,
902 * but notify the other side we are doing so.
905 if(tr->handq != nil){
914 qbwrite(tr->handq, b);
920 if(tr->verset && tr->version != SSL3Version && !waserror()){
921 sendAlert(tr, ENoRenegotiation);
926 case SSL2ClientHello:
928 if(tr->handq != nil){
935 /* Pass the SSL2 format data, so that the handshake code can compute
936 the correct checksums. HSSL2ClientHello = HandshakeType 9 is
937 unused in RFC2246. */
939 b->rp[0] = RHandshake;
940 b->rp[1] = HSSL2ClientHello;
941 put24(&b->rp[2], len+3);
942 b->rp[5] = SSL2ClientHello;
943 put16(&b->rp[6], ver);
944 qbwrite(tr->handq, b);
950 if(tr->verset && tr->version != SSL3Version && !waserror()){
951 sendAlert(tr, ENoRenegotiation);
958 rcvError(tr, EUnexpectedMessage, "application message received before handshake completed");
971 * got a fatal alert message
974 rcvAlert(TlsRec *tr, int err)
980 for(i=0; i < nelem(tlserrs); i++){
981 if(tlserrs[i].err == err){
986 if(tr->debug) pprint("rcvAlert: %s\n", s);
995 * found an error while decoding the input stream
998 rcvError(TlsRec *tr, int err, char *fmt, ...)
1004 vseprint(msg, msg+sizeof(msg), fmt, arg);
1006 if(tr->debug) pprint("rcvError: %s\n", msg);
1016 * make sure the next hand operation returns with a 'msg' error
1019 alertHand(TlsRec *tr, char *msg)
1025 if(tr->handq == nil){
1026 unlock(&tr->hqlock);
1030 unlock(&tr->hqlock);
1039 memmove(b->wp, msg, n + 1);
1042 qbwrite(tr->handq, b);
1049 checkstate(TlsRec *tr, int ishand, int ok)
1055 unlock(&tr->statelk);
1070 error("tls hungup");
1072 error("tls improperly configured");
1076 tlsbread(Chan *c, long n, ulong offset)
1080 TlsRec *volatile tr;
1085 return devbread(c, n, offset);
1091 tr = tlsdevs[CONV(c->qid)];
1096 qunlock(&tr->in.io);
1101 checkstate(tr, 0, SOpen);
1102 while(tr->processed == nil)
1105 /* return at most what was asked for */
1106 b = qgrab(&tr->processed, n);
1107 if(tr->debug) pprint("consumed processed %zd\n", BLEN(b));
1108 if(tr->debug) pdump(BLEN(b), b->rp, "consumed:");
1109 qunlock(&tr->in.io);
1111 tr->datain += BLEN(b);
1113 checkstate(tr, 1, SOpen|SHandshake|SLClose);
1116 * it's ok to look at state without the lock
1117 * since it only protects reading records,
1118 * and we have that tr->in.io held.
1120 while(!tr->opened && tr->hprocessed == nil && !qcanread(tr->handq))
1123 qunlock(&tr->in.io);
1127 qunlock(&tr->hqread);
1131 if(tr->hprocessed == nil){
1132 b = qbread(tr->handq, MaxRecLen + 1);
1133 if(*b->rp++ == RAlert){
1134 kstrcpy(up->errstr, (char*)b->rp, ERRMAX);
1140 b = qgrab(&tr->hprocessed, n);
1142 qunlock(&tr->hqread);
1143 tr->handin += BLEN(b);
1150 tlsread(Chan *c, void *a, long n, vlong off)
1160 if(c->qid.type & QTDIR)
1161 return devdirread(c, a, n, 0, 0, tlsgen);
1163 tr = tlsdevs[CONV(c->qid)];
1169 buf = smalloc(Statlen);
1170 qlock(&tr->in.seclock);
1171 qlock(&tr->out.seclock);
1174 s = seprint(s, e, "State: %s\n", tlsstate(tr->state));
1175 s = seprint(s, e, "Version: %#x\n", tr->version);
1176 if(tr->in.sec != nil)
1177 s = seprint(s, e, "EncIn: %s\nHashIn: %s\n", tr->in.sec->encalg, tr->in.sec->hashalg);
1178 if(tr->in.new != nil)
1179 s = seprint(s, e, "NewEncIn: %s\nNewHashIn: %s\n", tr->in.new->encalg, tr->in.new->hashalg);
1180 if(tr->out.sec != nil)
1181 s = seprint(s, e, "EncOut: %s\nHashOut: %s\n", tr->out.sec->encalg, tr->out.sec->hashalg);
1182 if(tr->out.new != nil)
1183 s = seprint(s, e, "NewEncOut: %s\nNewHashOut: %s\n", tr->out.new->encalg, tr->out.new->hashalg);
1185 seprint(s, e, "Chan: %s\n", chanpath(tr->c));
1186 qunlock(&tr->in.seclock);
1187 qunlock(&tr->out.seclock);
1188 n = readstr(offset, a, n, buf);
1192 buf = smalloc(Statlen);
1195 s = seprint(s, e, "DataIn: %lld\n", tr->datain);
1196 s = seprint(s, e, "DataOut: %lld\n", tr->dataout);
1197 s = seprint(s, e, "HandIn: %lld\n", tr->handin);
1198 seprint(s, e, "HandOut: %lld\n", tr->handout);
1199 n = readstr(offset, a, n, buf);
1203 buf = smalloc(Statlen);
1204 snprint(buf, Statlen, "%llud", CONV(c->qid));
1205 n = readstr(offset, a, n, buf);
1210 b = tlsbread(c, n, offset);
1213 return readstr(offset, a, n, encalgs);
1215 return readstr(offset, a, n, hashalgs);
1225 for(nb = b; nb; nb = nb->next){
1227 memmove(va+n, nb->rp, i);
1238 randfill(uchar *buf, int len)
1241 *buf++ = nrand(256);
1245 * write a block in tls records
1248 tlsrecwrite(TlsRec *tr, int type, Block *b)
1252 uchar *p, aad[8+RecHdrLen];
1253 OneWay *volatile out;
1254 int n, ivlen, maclen, aadlen, pad, ok;
1266 if(tr->debug)pprint("send %zd\n", BLEN(b));
1267 if(tr->debug)pdump(BLEN(b), b->rp, "sent:");
1270 ok = SHandshake|SOpen|SRClose;
1274 checkstate(tr, type != RApplication, ok);
1277 * get at most one maximal record's input,
1278 * with padding on the front for header and
1279 * back for mac and maximal block padding.
1282 qunlock(&out->seclock);
1285 qlock(&out->seclock);
1291 maclen = sec->maclen;
1292 pad = maclen + sec->block;
1293 ivlen = sec->recivlen;
1294 if(tr->version >= TLS11Version){
1302 nb = allocb(RecHdrLen + ivlen + n + pad);
1303 memmove(nb->wp + RecHdrLen + ivlen, bb->rp, n);
1307 * carefully reuse bb so it will get freed if we're out of memory
1309 bb = padblock(bb, RecHdrLen + ivlen);
1311 nb = padblock(bb, -pad);
1319 put16(p+1, tr->version);
1323 aadlen = (*tr->packAAD)(out->seq++, p, aad);
1324 if(sec->aead_enc != nil)
1325 n = (*sec->aead_enc)(sec, aad, aadlen, p + RecHdrLen, p + RecHdrLen + ivlen, n) + ivlen;
1328 randfill(p + RecHdrLen, ivlen);
1329 packMac(sec, aad, aadlen, p + RecHdrLen + ivlen, n, p + RecHdrLen + ivlen + n);
1330 n = (*sec->enc)(sec, p + RecHdrLen, ivlen + n + maclen);
1332 nb->wp = p + RecHdrLen + n;
1337 if(type == RChangeCipherSpec){
1339 error("change cipher without a new cipher");
1341 out->sec = out->new;
1345 qunlock(&out->seclock);
1349 * if bwrite error's, we assume the block is queued.
1350 * if not, we're out of sync with the receiver and will not recover.
1353 if(strcmp(up->errstr, "interrupted") != 0)
1354 tlsError(tr, "channel error");
1357 devtab[tr->c->type]->bwrite(tr->c, nb, 0);
1365 tlsbwrite(Chan *c, Block *b, ulong offset)
1373 tr = tlsdevs[CONV(c->qid)];
1380 return devbwrite(c, b, offset);
1382 tlsrecwrite(tr, RHandshake, b);
1386 checkstate(tr, 0, SOpen);
1387 tlsrecwrite(tr, RApplication, b);
1395 typedef struct Hashalg Hashalg;
1400 void (*initkey)(Hashalg *, int, Secret *, uchar*);
1404 initmd5key(Hashalg *ha, int version, Secret *s, uchar *p)
1406 s->maclen = ha->maclen;
1407 if(version == SSL3Version)
1408 s->mac = sslmac_md5;
1411 memmove(s->mackey, p, ha->maclen);
1415 initclearmac(Hashalg *, int, Secret *s, uchar *)
1421 initsha1key(Hashalg *ha, int version, Secret *s, uchar *p)
1423 s->maclen = ha->maclen;
1424 if(version == SSL3Version)
1425 s->mac = sslmac_sha1;
1428 memmove(s->mackey, p, ha->maclen);
1432 initsha2_256key(Hashalg *ha, int version, Secret *s, uchar *p)
1434 if(version == SSL3Version)
1435 error("sha256 cannot be used with SSL");
1436 s->maclen = ha->maclen;
1437 s->mac = hmac_sha2_256;
1438 memmove(s->mackey, p, ha->maclen);
1441 static Hashalg hashtab[] =
1443 { "clear", 0, initclearmac, },
1444 { "md5", MD5dlen, initmd5key, },
1445 { "sha1", SHA1dlen, initsha1key, },
1446 { "sha256", SHA2_256dlen, initsha2_256key, },
1451 parsehashalg(char *p)
1455 for(ha = hashtab; ha->name; ha++)
1456 if(strcmp(p, ha->name) == 0)
1458 error("unsupported hash algorithm");
1462 typedef struct Encalg Encalg;
1468 void (*initkey)(Encalg *ea, Secret *, uchar*, uchar*);
1472 initRC4key(Encalg *ea, Secret *s, uchar *p, uchar *)
1474 s->enckey = secalloc(sizeof(RC4state));
1477 setupRC4state(s->enckey, p, ea->keylen);
1481 initDES3key(Encalg *, Secret *s, uchar *p, uchar *iv)
1483 s->enckey = secalloc(sizeof(DES3state));
1487 setupDES3state(s->enckey, (uchar(*)[8])p, iv);
1491 initAESkey(Encalg *ea, Secret *s, uchar *p, uchar *iv)
1493 s->enckey = secalloc(sizeof(AESstate));
1497 setupAESstate(s->enckey, p, ea->keylen, iv);
1501 initccpolykey(Encalg *ea, Secret *s, uchar *p, uchar *iv)
1503 s->enckey = secalloc(sizeof(Chachastate));
1504 s->aead_enc = ccpoly_aead_enc;
1505 s->aead_dec = ccpoly_aead_dec;
1506 s->maclen = Poly1305dlen;
1507 if(ea->ivlen == 0) {
1508 /* older draft version, iv is 64-bit sequence number */
1509 setupChachastate(s->enckey, p, ea->keylen, nil, 64/8, 20);
1511 /* IETF standard, 96-bit iv xored with sequence number */
1512 memmove(s->mackey, iv, ea->ivlen);
1513 setupChachastate(s->enckey, p, ea->keylen, iv, ea->ivlen, 20);
1518 initaesgcmkey(Encalg *ea, Secret *s, uchar *p, uchar *iv)
1520 s->enckey = secalloc(sizeof(AESGCMstate));
1521 s->aead_enc = aesgcm_aead_enc;
1522 s->aead_dec = aesgcm_aead_dec;
1525 memmove(s->mackey, iv, ea->ivlen);
1526 randfill(s->mackey + ea->ivlen, s->recivlen);
1527 setupAESGCMstate(s->enckey, p, ea->keylen, nil, 0);
1531 initclearenc(Encalg *, Secret *s, uchar *, uchar *)
1537 static Encalg encrypttab[] =
1539 { "clear", 0, 0, initclearenc },
1540 { "rc4_128", 128/8, 0, initRC4key },
1541 { "3des_ede_cbc", 3 * 8, 8, initDES3key },
1542 { "aes_128_cbc", 128/8, 16, initAESkey },
1543 { "aes_256_cbc", 256/8, 16, initAESkey },
1544 { "ccpoly64_aead", 256/8, 0, initccpolykey },
1545 { "ccpoly96_aead", 256/8, 96/8, initccpolykey },
1546 { "aes_128_gcm_aead", 128/8, 4, initaesgcmkey },
1547 { "aes_256_gcm_aead", 256/8, 4, initaesgcmkey },
1552 parseencalg(char *p)
1556 for(ea = encrypttab; ea->name; ea++)
1557 if(strcmp(p, ea->name) == 0)
1559 error("unsupported encryption algorithm");
1564 tlswrite(Chan *c, void *a, long n, vlong off)
1568 TlsRec *volatile tr;
1569 Secret *volatile tos, *volatile toc;
1571 Cmdbuf *volatile cb;
1577 tr = tlsdevs[CONV(c->qid)];
1597 memmove(b->wp, p, m);
1601 tlsbwrite(c, b, offset);
1613 cb = parsecmd(a, n);
1619 error("short control request");
1621 /* mutex with operations using what we're about to change */
1623 qunlock(&tr->in.seclock);
1624 qunlock(&tr->out.seclock);
1627 qlock(&tr->in.seclock);
1628 qlock(&tr->out.seclock);
1630 if(strcmp(cb->f[0], "fd") == 0){
1632 error("usage: fd open-fd version");
1635 m = strtol(cb->f[2], nil, 0);
1636 if(m < MinProtoVersion || m > MaxProtoVersion)
1637 error("unsupported version");
1638 tr->c = buftochan(cb->f[1]);
1640 tlsSetState(tr, SHandshake, SClosed);
1641 }else if(strcmp(cb->f[0], "version") == 0){
1643 error("usage: version vers");
1645 error("must set fd before version");
1647 error("version already set");
1648 m = strtol(cb->f[1], nil, 0);
1649 if(m < MinProtoVersion || m > MaxProtoVersion)
1650 error("unsupported version");
1651 if(m == SSL3Version)
1652 tr->packAAD = sslPackAAD;
1654 tr->packAAD = tlsPackAAD;
1657 }else if(strcmp(cb->f[0], "secret") == 0){
1659 error("usage: secret hashalg encalg isclient secretdata");
1660 if(tr->c == nil || !tr->verset)
1661 error("must set fd and version before secrets");
1663 if(tr->in.new != nil){
1664 freeSec(tr->in.new);
1667 if(tr->out.new != nil){
1668 freeSec(tr->out.new);
1672 ha = parsehashalg(cb->f[1]);
1673 ea = parseencalg(cb->f[2]);
1676 m = (strlen(p)*3)/2 + 1;
1678 tos = secalloc(sizeof(Secret));
1679 toc = secalloc(sizeof(Secret));
1687 m = dec64(x, m, p, strlen(p));
1688 memset(p, 0, strlen(p));
1689 if(m < 2 * ha->maclen + 2 * ea->keylen + 2 * ea->ivlen)
1690 error("not enough secret data provided");
1692 if(!ha->initkey || !ea->initkey)
1693 error("misimplemented secret algorithm");
1695 (*ha->initkey)(ha, tr->version, tos, &x[0]);
1696 (*ha->initkey)(ha, tr->version, toc, &x[ha->maclen]);
1697 (*ea->initkey)(ea, tos, &x[2 * ha->maclen], &x[2 * ha->maclen + 2 * ea->keylen]);
1698 (*ea->initkey)(ea, toc, &x[2 * ha->maclen + ea->keylen], &x[2 * ha->maclen + 2 * ea->keylen + ea->ivlen]);
1700 if(!tos->aead_enc || !tos->aead_dec || !toc->aead_enc || !toc->aead_dec)
1701 if(!tos->mac || !tos->enc || !tos->dec || !toc->mac || !toc->enc || !toc->dec)
1702 error("missing algorithm implementations");
1704 if(strtol(cb->f[3], nil, 0) == 0){
1711 if(tr->version == SSL3Version){
1712 toc->unpad = sslunpad;
1713 tos->unpad = sslunpad;
1715 toc->unpad = tlsunpad;
1716 tos->unpad = tlsunpad;
1718 toc->encalg = ea->name;
1719 toc->hashalg = ha->name;
1720 tos->encalg = ea->name;
1721 tos->hashalg = ha->name;
1725 }else if(strcmp(cb->f[0], "changecipher") == 0){
1727 error("usage: changecipher");
1728 if(tr->out.new == nil)
1729 error("cannot change cipher spec without setting secret");
1731 qunlock(&tr->in.seclock);
1732 qunlock(&tr->out.seclock);
1738 * the real work is done as the message is written
1739 * so the stream is encrypted in sync.
1743 tlsrecwrite(tr, RChangeCipherSpec, b);
1745 }else if(strcmp(cb->f[0], "opened") == 0){
1747 error("usage: opened");
1748 if(tr->in.sec == nil || tr->out.sec == nil)
1749 error("cipher must be configured before enabling data messages");
1751 if(tr->state != SHandshake && tr->state != SOpen){
1752 unlock(&tr->statelk);
1753 error("cannot enable data messages");
1756 unlock(&tr->statelk);
1758 }else if(strcmp(cb->f[0], "alert") == 0){
1760 error("usage: alert n");
1762 error("must set fd before sending alerts");
1763 m = strtol(cb->f[1], nil, 0);
1765 qunlock(&tr->in.seclock);
1766 qunlock(&tr->out.seclock);
1773 if(m == ECloseNotify)
1774 tlsclosed(tr, SLClose);
1777 } else if(strcmp(cb->f[0], "debug") == 0){
1779 if(strcmp(cb->f[1], "on") == 0)
1788 qunlock(&tr->in.seclock);
1789 qunlock(&tr->out.seclock);
1807 fmtinstall('H', encodefmt);
1811 tlsdevs = smalloc(sizeof(TlsRec*) * maxtlsdevs);
1812 trnames = smalloc((sizeof *trnames) * maxtlsdevs);
1815 for(e = encrypttab; e->name != nil; e++)
1816 n += strlen(e->name) + 1;
1817 cp = encalgs = smalloc(n);
1818 for(e = encrypttab;;){
1819 strcpy(cp, e->name);
1820 cp += strlen(e->name);
1829 for(h = hashtab; h->name != nil; h++)
1830 n += strlen(h->name) + 1;
1831 cp = hashalgs = smalloc(n);
1833 strcpy(cp, h->name);
1834 cp += strlen(h->name);
1864 /* get channel associated with an fd */
1873 fd = strtoul(p, 0, 0);
1876 c = fdtochan(fd, ORDWR, 1, 1); /* error check and inc ref */
1881 sendAlert(TlsRec *tr, int err)
1887 if(tr->debug)pprint("sendAlert %d\n", err);
1889 msg = "tls unknown alert";
1890 for(i=0; i < nelem(tlserrs); i++) {
1891 if(tlserrs[i].err == err) {
1892 msg = tlserrs[i].msg;
1893 if(tr->version == SSL3Version)
1894 err = tlserrs[i].sslerr;
1896 err = tlserrs[i].tlserr;
1897 fatal = tlserrs[i].fatal;
1904 *b->wp++ = fatal + 1;
1907 tlsSetState(tr, SAlert, SOpen|SHandshake|SRClose);
1908 tlsrecwrite(tr, RAlert, b);
1916 tlsError(TlsRec *tr, char *msg)
1920 if(tr->debug)pprint("tlsError %s\n", msg);
1925 strncpy(tr->err, msg, ERRMAX - 1);
1926 tr->err[ERRMAX - 1] = '\0';
1928 unlock(&tr->statelk);
1934 tlsSetState(TlsRec *tr, int new, int old)
1939 unlock(&tr->statelk);
1942 /* hand up a digest connection */
1944 tlshangup(TlsRec *tr)
1949 for(b = tr->processed; b; b = tr->processed){
1950 tr->processed = b->next;
1953 if(tr->unprocessed != nil){
1954 freeb(tr->unprocessed);
1955 tr->unprocessed = nil;
1957 qunlock(&tr->in.io);
1959 tlsSetState(tr, SClosed, ~0);
1965 TlsRec **pp, **ep, **np;
1974 ep = &tlsdevs[maxtlsdevs];
1975 for(pp = tlsdevs; pp < ep; pp++)
1979 if(maxtlsdevs >= MaxTlsDevs) {
1984 newmax = 2 * maxtlsdevs;
1985 if(newmax > MaxTlsDevs)
1986 newmax = MaxTlsDevs;
1987 np = smalloc(sizeof(TlsRec*) * newmax);
1988 memmove(np, tlsdevs, sizeof(TlsRec*) * maxtlsdevs);
1990 pp = &tlsdevs[maxtlsdevs];
1991 memset(pp, 0, sizeof(TlsRec*)*(newmax - maxtlsdevs));
1993 nmp = smalloc(sizeof *nmp * newmax);
1994 memmove(nmp, trnames, sizeof *nmp * maxtlsdevs);
1997 maxtlsdevs = newmax;
2000 if(pp - tlsdevs >= tdhiwat)
2005 ch->qid.path = QID(pp - tlsdevs, t);
2017 tr = mallocz(sizeof(*tr), 1);
2020 tr->state = SClosed;
2022 kstrdup(&tr->user, up->user);
2032 return "Handshaking";
2034 return "Established";
2036 return "RemoteClosed";
2038 return "LocalClosed";
2059 noenc(Secret *, uchar *, int n)
2065 rc4enc(Secret *sec, uchar *buf, int n)
2067 rc4(sec->enckey, buf, n);
2072 tlsunpad(uchar *buf, int n, int block)
2078 if(nn <= 0 || n % block)
2081 if(pad != buf[n - 1])
2087 sslunpad(uchar *buf, int n, int block)
2093 if(nn <= 0 || n % block)
2099 blockpad(uchar *buf, int n, int block)
2112 des3enc(Secret *sec, uchar *buf, int n)
2114 n = blockpad(buf, n, 8);
2115 des3CBCencrypt(buf, n, sec->enckey);
2120 des3dec(Secret *sec, uchar *buf, int n)
2122 des3CBCdecrypt(buf, n, sec->enckey);
2123 return (*sec->unpad)(buf, n, 8);
2127 aesenc(Secret *sec, uchar *buf, int n)
2129 n = blockpad(buf, n, 16);
2130 aesCBCencrypt(buf, n, sec->enckey);
2135 aesdec(Secret *sec, uchar *buf, int n)
2137 aesCBCdecrypt(buf, n, sec->enckey);
2138 return (*sec->unpad)(buf, n, 16);
2142 ccpoly_aead_setiv(Secret *sec, uchar seq[8])
2144 uchar iv[ChachaIVlen];
2148 cs = (Chachastate*)sec->enckey;
2149 if(cs->ivwords == 2){
2150 chacha_setiv(cs, seq);
2154 memmove(iv, sec->mackey, ChachaIVlen);
2156 iv[i+(ChachaIVlen-8)] ^= seq[i];
2158 chacha_setiv(cs, iv);
2160 memset(iv, 0, sizeof(iv));
2164 ccpoly_aead_enc(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len)
2167 ccpoly_aead_setiv(sec, aad);
2168 ccpoly_encrypt(data, len, aad, aadlen, data+len, sec->enckey);
2169 return len + sec->maclen;
2173 ccpoly_aead_dec(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len)
2179 ccpoly_aead_setiv(sec, aad);
2180 if(ccpoly_decrypt(data, len, aad, aadlen, data+len, sec->enckey) != 0)
2186 aesgcm_aead_enc(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len)
2191 memmove(iv, sec->mackey, 4+8);
2192 for(i=0; i<8; i++) iv[4+i] ^= aad[i];
2193 memmove(reciv, iv+4, 8);
2194 aesgcm_setiv(sec->enckey, iv, 12);
2195 memset(iv, 0, sizeof(iv));
2196 aesgcm_encrypt(data, len, aad, aadlen, data+len, sec->enckey);
2197 return len + sec->maclen;
2201 aesgcm_aead_dec(Secret *sec, uchar *aad, int aadlen, uchar *reciv, uchar *data, int len)
2208 memmove(iv, sec->mackey, 4);
2209 memmove(iv+4, reciv, 8);
2210 aesgcm_setiv(sec->enckey, iv, 12);
2211 memset(iv, 0, sizeof(iv));
2212 if(aesgcm_decrypt(data, len, aad, aadlen, data+len, sec->enckey) != 0)
2219 nomac(uchar *, ulong, uchar *, ulong, uchar *, DigestState *)
2225 * sslmac: mac calculations for ssl 3.0 only; tls 1.0 uses the standard hmac.
2228 sslmac_x(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s,
2229 DigestState*(*x)(uchar*, ulong, uchar*, DigestState*), int xlen, int padlen)
2232 uchar pad[48], innerdigest[20];
2234 if(xlen > sizeof(innerdigest)
2235 || padlen > sizeof(pad))
2241 /* first time through */
2243 for(i=0; i<padlen; i++)
2245 s = (*x)(key, klen, nil, nil);
2246 s = (*x)(pad, padlen, nil, s);
2251 s = (*x)(p, len, nil, s);
2255 /* last time through */
2256 for(i=0; i<padlen; i++)
2258 (*x)(nil, 0, innerdigest, s);
2259 s = (*x)(key, klen, nil, nil);
2260 s = (*x)(pad, padlen, nil, s);
2261 (*x)(innerdigest, xlen, digest, s);
2266 sslmac_sha1(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2268 return sslmac_x(p, len, key, klen, digest, s, sha1, SHA1dlen, 40);
2272 sslmac_md5(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2274 return sslmac_x(p, len, key, klen, digest, s, md5, MD5dlen, 48);
2278 sslPackAAD(u64int seq, uchar *hdr, uchar *aad)
2288 tlsPackAAD(u64int seq, uchar *hdr, uchar *aad)
2300 packMac(Secret *sec, uchar *aad, int aadlen, uchar *body, int bodylen, uchar *mac)
2304 s = (*sec->mac)(aad, aadlen, sec->mackey, sec->maclen, nil, nil);
2305 (*sec->mac)(body, bodylen, sec->mackey, sec->maclen, mac, s);
2309 put32(uchar *p, u32int x)
2318 put64(uchar *p, u64int x)
2325 put24(uchar *p, int x)
2333 put16(uchar *p, int x)
2342 return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
2348 return (p[0]<<8)|p[1];
2351 static char *charmap = "0123456789abcdef";
2354 pdump(int len, void *a, char *tag)
2364 q = buf + strlen(tag);
2365 for(i = 0; len > 0 && i < 32; i++){
2366 if(*p >= ' ' && *p < 0x7f){
2370 *q++ = charmap[*p>>4];
2371 *q++ = charmap[*p & 0xf];
2379 pprint("%s...\n", buf);
2381 pprint("%s\n", buf);