2 * devtls - record layer for transport layer security 1.0 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,
26 /* protocol versions we can accept */
29 ProtocolVersion = 0x0301, /* maximum version we speak */
30 MinProtoVersion = 0x0300, /* limits on version we accept */
31 MaxProtoVersion = 0x03ff,
33 /* connection states */
34 SHandshake = 1 << 0, /* doing handshake */
35 SOpen = 1 << 1, /* application data can be sent */
36 SRClose = 1 << 2, /* remote side has closed down */
37 SLClose = 1 << 3, /* sent a close notify alert */
38 SAlert = 1 << 5, /* sending or sent a fatal alert */
39 SError = 1 << 6, /* some sort of error has occured */
40 SClosed = 1 << 7, /* it is all over */
43 RChangeCipherSpec = 20,
49 HSSL2ClientHello = 9, /* local convention; see tlshand.c */
53 EUnexpectedMessage = 10,
55 EDecryptionFailed = 21,
57 EDecompressionFailure = 30,
58 EHandshakeFailure = 40,
61 EUnsupportedCertificate = 43,
62 ECertificateRevoked = 44,
63 ECertificateExpired = 45,
64 ECertificateUnknown = 46,
65 EIllegalParameter = 47,
70 EExportRestriction = 60,
71 EProtocolVersion = 70,
72 EInsufficientSecurity = 71,
75 ENoRenegotiation = 100,
82 char *encalg; /* name of encryption alg */
83 char *hashalg; /* name of hash alg */
84 int (*enc)(Secret*, uchar*, int);
85 int (*dec)(Secret*, uchar*, int);
86 int (*unpad)(uchar*, int, int);
87 DigestState *(*mac)(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
88 int block; /* encryption block len, 0 if none */
91 uchar mackey[MaxMacLen];
96 QLock io; /* locks io access */
97 QLock seclock; /* locks secret paramaters */
99 Secret *sec; /* cipher in use */
100 Secret *new; /* cipher waiting for enable */
105 Chan *c; /* io channel */
106 int ref; /* serialized by tdlock for atomic destroy */
107 int version; /* version of the protocol we are speaking */
108 char verset; /* version has been set */
109 char opened; /* opened command every issued? */
110 char err[ERRMAX]; /* error message to return to handshake requests */
111 vlong handin; /* bytes communicated by the record layer */
120 /* record layer mac functions for different protocol versions */
121 void (*packMac)(Secret*, uchar*, uchar*, uchar*, uchar*, int, uchar*);
123 /* input side -- protected by in.io */
125 Block *processed; /* next bunch of application data */
126 Block *unprocessed; /* data read from c but not parsed into records */
128 /* handshake queue */
129 Lock hqlock; /* protects hqref, alloc & free of handq, hprocessed */
131 Queue *handq; /* queue of handshake messages */
132 Block *hprocessed; /* remainder of last block read from handq */
133 QLock hqread; /* protects reads for hprocessed, handq */
151 static TlsErrs tlserrs[] = {
152 {ECloseNotify, ECloseNotify, ECloseNotify, 0, "close notify"},
153 {EUnexpectedMessage, EUnexpectedMessage, EUnexpectedMessage, 1, "unexpected message"},
154 {EBadRecordMac, EBadRecordMac, EBadRecordMac, 1, "bad record mac"},
155 {EDecryptionFailed, EIllegalParameter, EDecryptionFailed, 1, "decryption failed"},
156 {ERecordOverflow, EIllegalParameter, ERecordOverflow, 1, "record too long"},
157 {EDecompressionFailure, EDecompressionFailure, EDecompressionFailure, 1, "decompression failed"},
158 {EHandshakeFailure, EHandshakeFailure, EHandshakeFailure, 1, "could not negotiate acceptable security parameters"},
159 {ENoCertificate, ENoCertificate, ECertificateUnknown, 1, "no appropriate certificate available"},
160 {EBadCertificate, EBadCertificate, EBadCertificate, 1, "corrupted or invalid certificate"},
161 {EUnsupportedCertificate, EUnsupportedCertificate, EUnsupportedCertificate, 1, "unsupported certificate type"},
162 {ECertificateRevoked, ECertificateRevoked, ECertificateRevoked, 1, "revoked certificate"},
163 {ECertificateExpired, ECertificateExpired, ECertificateExpired, 1, "expired certificate"},
164 {ECertificateUnknown, ECertificateUnknown, ECertificateUnknown, 1, "unacceptable certificate"},
165 {EIllegalParameter, EIllegalParameter, EIllegalParameter, 1, "illegal parameter"},
166 {EUnknownCa, EHandshakeFailure, EUnknownCa, 1, "unknown certificate authority"},
167 {EAccessDenied, EHandshakeFailure, EAccessDenied, 1, "access denied"},
168 {EDecodeError, EIllegalParameter, EDecodeError, 1, "error decoding message"},
169 {EDecryptError, EIllegalParameter, EDecryptError, 1, "error decrypting message"},
170 {EExportRestriction, EHandshakeFailure, EExportRestriction, 1, "export restriction violated"},
171 {EProtocolVersion, EIllegalParameter, EProtocolVersion, 1, "protocol version not supported"},
172 {EInsufficientSecurity, EHandshakeFailure, EInsufficientSecurity, 1, "stronger security routines required"},
173 {EInternalError, EHandshakeFailure, EInternalError, 1, "internal error"},
174 {EUserCanceled, ECloseNotify, EUserCanceled, 0, "handshake canceled by user"},
175 {ENoRenegotiation, EUnexpectedMessage, ENoRenegotiation, 0, "no renegotiation"},
180 /* max. open tls connections */
186 static int maxtlsdevs = 128;
187 static TlsRec **tlsdevs;
188 static char **trnames;
189 static char *encalgs;
190 static char *hashalgs;
193 Qtopdir = 1, /* top level directory */
198 Qconvdir, /* directory for a conversation */
206 #define TYPE(x) ((x).path & 0xf)
207 #define CONV(x) (((x).path >> 5)&(MaxTlsDevs-1))
208 #define QID(c, y) (((c)<<5) | (y))
210 static void checkstate(TlsRec *, int, int);
211 static void ensure(TlsRec*, Block**, int);
212 static void consume(Block**, uchar*, int);
213 static Chan* buftochan(char*);
214 static void tlshangup(TlsRec*);
215 static void tlsError(TlsRec*, char *);
216 static void alertHand(TlsRec*, char *);
217 static TlsRec *newtls(Chan *c);
218 static TlsRec *mktlsrec(void);
219 static DigestState*sslmac_md5(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
220 static DigestState*sslmac_sha1(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
221 static DigestState*nomac(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
222 static void sslPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac);
223 static void tlsPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac);
224 static void put64(uchar *p, vlong x);
225 static void put32(uchar *p, u32int);
226 static void put24(uchar *p, int);
227 static void put16(uchar *p, int);
228 static u32int get32(uchar *p);
229 static int get16(uchar *p);
230 static void tlsSetState(TlsRec *tr, int new, int old);
231 static void rcvAlert(TlsRec *tr, int err);
232 static void sendAlert(TlsRec *tr, int err);
233 static void rcvError(TlsRec *tr, int err, char *msg, ...);
234 static int rc4enc(Secret *sec, uchar *buf, int n);
235 static int des3enc(Secret *sec, uchar *buf, int n);
236 static int des3dec(Secret *sec, uchar *buf, int n);
237 static int aesenc(Secret *sec, uchar *buf, int n);
238 static int aesdec(Secret *sec, uchar *buf, int n);
239 static int noenc(Secret *sec, uchar *buf, int n);
240 static int sslunpad(uchar *buf, int n, int block);
241 static int tlsunpad(uchar *buf, int n, int block);
242 static void freeSec(Secret *sec);
243 static char *tlsstate(int s);
244 static void pdump(int, void*, char*);
246 #pragma varargck argpos rcvError 3
248 static char *tlsnames[] = {
250 [Qencalgs] "encalgs",
251 [Qhashalgs] "hashalgs",
259 static int convdir[] = { Qctl, Qdata, Qhand, Qstatus, Qstats };
262 tlsgen(Chan *c, char*, Dirtab *, int, int s, Dir *dp)
276 q.path = QID(0, Qtopdir);
278 devdir(c, q, "#a", 0, eve, 0555, dp);
283 q.path = QID(0, Qprotodir);
285 devdir(c, q, "tls", 0, eve, 0555, dp);
289 q.path = QID(0, Qtopdir);
291 devdir(c, q, ".", 0, eve, 0555, dp);
299 q.path = QID(0, Qclonus);
302 q.path = QID(0, Qencalgs);
305 q.path = QID(0, Qhashalgs);
309 if(TYPE(q) == Qclonus)
311 devdir(c, q, tlsnames[TYPE(q)], 0, eve, perm, dp);
317 q.path = QID(s, Qconvdir);
325 if((name = trnames[s]) == nil){
326 name = trnames[s] = smalloc(16);
327 sprint(name, "%d", s);
329 devdir(c, q, name, 0, nm, 0555, dp);
334 q.path = QID(0, Qprotodir);
336 devdir(c, q, "tls", 0, eve, 0555, dp);
339 if(s < 0 || s >= nelem(convdir))
342 tr = tlsdevs[CONV(c->qid)];
351 if(t == Qstatus || t == Qstats)
353 q.path = QID(CONV(c->qid), t);
354 devdir(c, q, tlsnames[t], 0, nm, perm, dp);
363 devdir(c, c->qid, tlsnames[t], 0, eve, perm, dp);
367 tr = tlsdevs[CONV(c->qid)];
375 if(t == Qstatus || t == Qstats)
377 devdir(c, c->qid, tlsnames[t], 0, nm, perm, dp);
384 tlsattach(char *spec)
388 c = devattach('a', spec);
389 c->qid.path = QID(0, Qtopdir);
396 tlswalk(Chan *c, Chan *nc, char **name, int nname)
398 return devwalk(c, nc, name, nname, nil, 0, tlsgen);
402 tlsstat(Chan *c, uchar *db, int n)
404 return devstat(c, db, n, nil, 0, tlsgen);
408 tlsopen(Chan *c, int omode)
447 if((t == Qstatus || t == Qstats) && omode != OREAD)
454 pp = &tlsdevs[CONV(c->qid)];
457 error("must open connection using clone");
458 if((perm & (tr->perm>>6)) != perm
459 && (strcmp(up->user, tr->user) != 0
460 || (perm & tr->perm) != perm))
470 tr->handq = qopen(2 * MaxCipherRecLen, 0, nil, nil);
472 error("cannot allocate handshake queue");
487 c->mode = openmode(omode);
490 c->iounit = qiomaxatomic;
495 tlswstat(Chan *c, uchar *dp, int n)
509 tr = tlsdevs[CONV(c->qid)];
512 if(strcmp(tr->user, up->user) != 0)
515 d = smalloc(n + sizeof *d);
516 rv = convM2D(dp, n, &d[0], (char*) &d[1]);
519 if(!emptystr(d->uid))
520 kstrdup(&tr->user, d->uid);
535 if(--tr->hqref == 0){
536 if(tr->handq != nil){
540 if(tr->hprocessed != nil){
541 freeb(tr->hprocessed);
542 tr->hprocessed = nil;
561 if((c->flag & COPEN) == 0)
564 tr = tlsdevs[CONV(c->qid)];
576 tlsdevs[CONV(c->qid)] = nil;
579 if(tr->c != nil && !waserror()){
580 checkstate(tr, 0, SOpen|SHandshake|SRClose);
581 sendAlert(tr, ECloseNotify);
589 freeSec(tr->out.sec);
590 freeSec(tr->out.new);
598 * make sure we have at least 'n' bytes in list 'l'
601 ensure(TlsRec *s, Block **l, int n)
607 for(b = *l; b; b = b->next){
615 bl = devtab[s->c->type]->bread(s->c, MaxCipherRecLen + RecHdrLen, 0);
620 for(b = bl; b; b = b->next){
628 if(s->debug) pprint("ensure read %d\n", sofar);
632 * copy 'n' bytes from 'l' into 'p' and free
636 consume(Block **l, uchar *p, int n)
641 for(; *l && n > 0; n -= i){
646 memmove(p, b->rp, i);
662 regurgitate(TlsRec *s, uchar *p, int n)
669 if(s->unprocessed == nil || b->rp - b->base < n) {
671 memmove(b->wp, p, n);
673 b->next = s->unprocessed;
677 memmove(b->rp, p, n);
682 * remove at most n bytes from the queue
685 qgrab(Block **l, int n)
698 for(bb = b; bb != nil && i < n; bb = bb->next)
704 consume(l, bb->wp, i);
710 tlsclosed(TlsRec *tr, int new)
713 if(tr->state == SOpen || tr->state == SHandshake)
715 else if((new | tr->state) == (SRClose|SLClose))
717 unlock(&tr->statelk);
718 alertHand(tr, "close notify");
722 * read and process one tls record layer message
723 * must be called with tr->in.io held
724 * We can't let Eintrs lose data, since doing so will get
725 * us out of sync with the sender and break the reliablity
726 * of the channel. Eintr only happens during the reads in
727 * consume. Therefore we put back any bytes consumed before
728 * the last call to ensure.
731 tlsrecread(TlsRec *tr)
735 uchar *p, seq[8], header[RecHdrLen], hmac[MaxMacLen];
736 int volatile nconsumed;
737 int len, type, ver, unpad_len;
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);
800 /* to avoid Canvel-Hiltgen-Vaudenay-Vuagnoux attack, all errors here
801 should look alike, including timing of the response. */
802 unpad_len = (*in->sec->dec)(in->sec, p, len);
803 if(unpad_len >= in->sec->maclen)
804 len = unpad_len - in->sec->maclen;
805 if(tr->debug) pprint("decrypted %d\n", unpad_len);
806 if(tr->debug) pdump(unpad_len, p, "decrypted:");
809 put16(header+3, len);
812 (*tr->packMac)(in->sec, in->sec->mackey, seq, header, p, len, hmac);
813 if(unpad_len < in->sec->maclen)
814 rcvError(tr, EBadRecordMac, "short record mac");
815 if(memcmp(hmac, p+len, in->sec->maclen) != 0)
816 rcvError(tr, EBadRecordMac, "record mac mismatch");
819 qunlock(&in->seclock);
822 rcvError(tr, EDecodeError, "runt record message");
826 rcvError(tr, EIllegalParameter, "invalid record message %#x", type);
828 case RChangeCipherSpec:
829 if(len != 1 || p[0] != 1)
830 rcvError(tr, EDecodeError, "invalid change cipher spec");
833 qunlock(&in->seclock);
834 rcvError(tr, EUnexpectedMessage, "unexpected change cipher spec");
840 qunlock(&in->seclock);
844 rcvError(tr, EDecodeError, "invalid alert");
848 rcvError(tr, EIllegalParameter, "invalid alert fatal code");
851 * propagate non-fatal alerts to handshaker
853 if(p[1] == ECloseNotify) {
854 tlsclosed(tr, SRClose);
857 error("close notify");
859 if(p[1] == ENoRenegotiation)
860 alertHand(tr, "no renegotiation");
861 else if(p[1] == EUserCanceled)
862 alertHand(tr, "handshake canceled by user");
864 rcvError(tr, EIllegalParameter, "invalid alert code");
868 * don't worry about dropping the block
869 * qbwrite always queues even if flow controlled and interrupted.
871 * if there isn't any handshaker, ignore the request,
872 * but notify the other side we are doing so.
875 if(tr->handq != nil){
884 qbwrite(tr->handq, b);
890 if(tr->verset && tr->version != SSL3Version && !waserror()){
891 sendAlert(tr, ENoRenegotiation);
896 case SSL2ClientHello:
898 if(tr->handq != nil){
905 /* Pass the SSL2 format data, so that the handshake code can compute
906 the correct checksums. HSSL2ClientHello = HandshakeType 9 is
907 unused in RFC2246. */
909 b->rp[0] = RHandshake;
910 b->rp[1] = HSSL2ClientHello;
911 put24(&b->rp[2], len+3);
912 b->rp[5] = SSL2ClientHello;
913 put16(&b->rp[6], ver);
914 qbwrite(tr->handq, b);
920 if(tr->verset && tr->version != SSL3Version && !waserror()){
921 sendAlert(tr, ENoRenegotiation);
928 rcvError(tr, EUnexpectedMessage, "application message received before handshake completed");
941 * got a fatal alert message
944 rcvAlert(TlsRec *tr, int err)
950 for(i=0; i < nelem(tlserrs); i++){
951 if(tlserrs[i].err == err){
956 if(tr->debug) pprint("rcvAlert: %s\n", s);
965 * found an error while decoding the input stream
968 rcvError(TlsRec *tr, int err, char *fmt, ...)
974 vseprint(msg, msg+sizeof(msg), fmt, arg);
976 if(tr->debug) pprint("rcvError: %s\n", msg);
986 * make sure the next hand operation returns with a 'msg' error
989 alertHand(TlsRec *tr, char *msg)
995 if(tr->handq == nil){
1000 unlock(&tr->hqlock);
1009 memmove(b->wp, msg, n + 1);
1012 qbwrite(tr->handq, b);
1019 checkstate(TlsRec *tr, int ishand, int ok)
1025 unlock(&tr->statelk);
1040 error("tls hungup");
1042 error("tls improperly configured");
1046 tlsbread(Chan *c, long n, ulong offset)
1050 TlsRec *volatile tr;
1055 return devbread(c, n, offset);
1061 tr = tlsdevs[CONV(c->qid)];
1066 qunlock(&tr->in.io);
1071 checkstate(tr, 0, SOpen);
1072 while(tr->processed == nil)
1075 /* return at most what was asked for */
1076 b = qgrab(&tr->processed, n);
1077 if(tr->debug) pprint("consumed processed %ld\n", BLEN(b));
1078 if(tr->debug) pdump(BLEN(b), b->rp, "consumed:");
1079 qunlock(&tr->in.io);
1081 tr->datain += BLEN(b);
1083 checkstate(tr, 1, SOpen|SHandshake|SLClose);
1086 * it's ok to look at state without the lock
1087 * since it only protects reading records,
1088 * and we have that tr->in.io held.
1090 while(!tr->opened && tr->hprocessed == nil && !qcanread(tr->handq))
1093 qunlock(&tr->in.io);
1097 qunlock(&tr->hqread);
1101 if(tr->hprocessed == nil){
1102 b = qbread(tr->handq, MaxRecLen + 1);
1103 if(*b->rp++ == RAlert){
1104 kstrcpy(up->errstr, (char*)b->rp, ERRMAX);
1110 b = qgrab(&tr->hprocessed, n);
1112 qunlock(&tr->hqread);
1113 tr->handin += BLEN(b);
1120 tlsread(Chan *c, void *a, long n, vlong off)
1130 if(c->qid.type & QTDIR)
1131 return devdirread(c, a, n, 0, 0, tlsgen);
1133 tr = tlsdevs[CONV(c->qid)];
1139 buf = smalloc(Statlen);
1140 qlock(&tr->in.seclock);
1141 qlock(&tr->out.seclock);
1144 s = seprint(s, e, "State: %s\n", tlsstate(tr->state));
1145 s = seprint(s, e, "Version: %#x\n", tr->version);
1146 if(tr->in.sec != nil)
1147 s = seprint(s, e, "EncIn: %s\nHashIn: %s\n", tr->in.sec->encalg, tr->in.sec->hashalg);
1148 if(tr->in.new != nil)
1149 s = seprint(s, e, "NewEncIn: %s\nNewHashIn: %s\n", tr->in.new->encalg, tr->in.new->hashalg);
1150 if(tr->out.sec != nil)
1151 s = seprint(s, e, "EncOut: %s\nHashOut: %s\n", tr->out.sec->encalg, tr->out.sec->hashalg);
1152 if(tr->out.new != nil)
1153 seprint(s, e, "NewEncOut: %s\nNewHashOut: %s\n", tr->out.new->encalg, tr->out.new->hashalg);
1154 qunlock(&tr->in.seclock);
1155 qunlock(&tr->out.seclock);
1156 n = readstr(offset, a, n, buf);
1160 buf = smalloc(Statlen);
1163 s = seprint(s, e, "DataIn: %lld\n", tr->datain);
1164 s = seprint(s, e, "DataOut: %lld\n", tr->dataout);
1165 s = seprint(s, e, "HandIn: %lld\n", tr->handin);
1166 seprint(s, e, "HandOut: %lld\n", tr->handout);
1167 n = readstr(offset, a, n, buf);
1171 buf = smalloc(Statlen);
1172 snprint(buf, Statlen, "%llud", CONV(c->qid));
1173 n = readstr(offset, a, n, buf);
1178 b = tlsbread(c, n, offset);
1181 return readstr(offset, a, n, encalgs);
1183 return readstr(offset, a, n, hashalgs);
1193 for(nb = b; nb; nb = nb->next){
1195 memmove(va+n, nb->rp, i);
1206 * write a block in tls records
1209 tlsrecwrite(TlsRec *tr, int type, Block *b)
1214 OneWay *volatile out;
1215 int n, maclen, pad, ok;
1226 if(tr->debug)pprint("send %ld\n", BLEN(b));
1227 if(tr->debug)pdump(BLEN(b), b->rp, "sent:");
1230 ok = SHandshake|SOpen|SRClose;
1234 checkstate(tr, type != RApplication, ok);
1237 * get at most one maximal record's input,
1238 * with padding on the front for header and
1239 * back for mac and maximal block padding.
1242 qunlock(&out->seclock);
1245 qlock(&out->seclock);
1248 if(out->sec != nil){
1249 maclen = out->sec->maclen;
1250 pad = maclen + out->sec->block;
1255 nb = allocb(n + pad + RecHdrLen);
1256 memmove(nb->wp + RecHdrLen, bb->rp, n);
1260 * carefully reuse bb so it will get freed if we're out of memory
1262 bb = padblock(bb, RecHdrLen);
1264 nb = padblock(bb, -pad);
1272 put16(p+1, tr->version);
1275 if(out->sec != nil){
1276 put64(seq, out->seq);
1278 (*tr->packMac)(out->sec, out->sec->mackey, seq, p, p + RecHdrLen, n, p + RecHdrLen + n);
1282 n = (*out->sec->enc)(out->sec, p + RecHdrLen, n);
1283 nb->wp = p + RecHdrLen + n;
1288 if(type == RChangeCipherSpec){
1290 error("change cipher without a new cipher");
1292 out->sec = out->new;
1296 qunlock(&out->seclock);
1300 * if bwrite error's, we assume the block is queued.
1301 * if not, we're out of sync with the receiver and will not recover.
1304 if(strcmp(up->errstr, "interrupted") != 0)
1305 tlsError(tr, "channel error");
1308 devtab[tr->c->type]->bwrite(tr->c, nb, 0);
1316 tlsbwrite(Chan *c, Block *b, ulong offset)
1324 tr = tlsdevs[CONV(c->qid)];
1331 return devbwrite(c, b, offset);
1333 tlsrecwrite(tr, RHandshake, b);
1337 checkstate(tr, 0, SOpen);
1338 tlsrecwrite(tr, RApplication, b);
1346 typedef struct Hashalg Hashalg;
1351 void (*initkey)(Hashalg *, int, Secret *, uchar*);
1355 initmd5key(Hashalg *ha, int version, Secret *s, uchar *p)
1357 s->maclen = ha->maclen;
1358 if(version == SSL3Version)
1359 s->mac = sslmac_md5;
1362 memmove(s->mackey, p, ha->maclen);
1366 initclearmac(Hashalg *, int, Secret *s, uchar *)
1373 initsha1key(Hashalg *ha, int version, Secret *s, uchar *p)
1375 s->maclen = ha->maclen;
1376 if(version == SSL3Version)
1377 s->mac = sslmac_sha1;
1380 memmove(s->mackey, p, ha->maclen);
1383 static Hashalg hashtab[] =
1385 { "clear", 0, initclearmac, },
1386 { "md5", MD5dlen, initmd5key, },
1387 { "sha1", SHA1dlen, initsha1key, },
1392 parsehashalg(char *p)
1396 for(ha = hashtab; ha->name; ha++)
1397 if(strcmp(p, ha->name) == 0)
1399 error("unsupported hash algorithm");
1403 typedef struct Encalg Encalg;
1409 void (*initkey)(Encalg *ea, Secret *, uchar*, uchar*);
1413 initRC4key(Encalg *ea, Secret *s, uchar *p, uchar *)
1415 s->enckey = smalloc(sizeof(RC4state));
1419 setupRC4state(s->enckey, p, ea->keylen);
1423 initDES3key(Encalg *, Secret *s, uchar *p, uchar *iv)
1425 s->enckey = smalloc(sizeof(DES3state));
1429 setupDES3state(s->enckey, (uchar(*)[8])p, iv);
1433 initAESkey(Encalg *ea, Secret *s, uchar *p, uchar *iv)
1435 s->enckey = smalloc(sizeof(AESstate));
1439 setupAESstate(s->enckey, p, ea->keylen, iv);
1443 initclearenc(Encalg *, Secret *s, uchar *, uchar *)
1450 static Encalg encrypttab[] =
1452 { "clear", 0, 0, initclearenc },
1453 { "rc4_128", 128/8, 0, initRC4key },
1454 { "3des_ede_cbc", 3 * 8, 8, initDES3key },
1455 { "aes_128_cbc", 128/8, 16, initAESkey },
1456 { "aes_256_cbc", 256/8, 16, initAESkey },
1461 parseencalg(char *p)
1465 for(ea = encrypttab; ea->name; ea++)
1466 if(strcmp(p, ea->name) == 0)
1468 error("unsupported encryption algorithm");
1473 tlswrite(Chan *c, void *a, long n, vlong off)
1477 TlsRec *volatile tr;
1478 Secret *volatile tos, *volatile toc;
1480 Cmdbuf *volatile cb;
1486 tr = tlsdevs[CONV(c->qid)];
1506 memmove(b->wp, p, m);
1510 tlsbwrite(c, b, offset);
1522 cb = parsecmd(a, n);
1528 error("short control request");
1530 /* mutex with operations using what we're about to change */
1532 qunlock(&tr->in.seclock);
1533 qunlock(&tr->out.seclock);
1536 qlock(&tr->in.seclock);
1537 qlock(&tr->out.seclock);
1539 if(strcmp(cb->f[0], "fd") == 0){
1541 error("usage: fd open-fd version");
1544 m = strtol(cb->f[2], nil, 0);
1545 if(m < MinProtoVersion || m > MaxProtoVersion)
1546 error("unsupported version");
1547 tr->c = buftochan(cb->f[1]);
1549 tlsSetState(tr, SHandshake, SClosed);
1550 }else if(strcmp(cb->f[0], "version") == 0){
1552 error("usage: version vers");
1554 error("must set fd before version");
1556 error("version already set");
1557 m = strtol(cb->f[1], nil, 0);
1558 if(m == SSL3Version)
1559 tr->packMac = sslPackMac;
1560 else if(m == TLSVersion)
1561 tr->packMac = tlsPackMac;
1563 error("unsupported version");
1566 }else if(strcmp(cb->f[0], "secret") == 0){
1568 error("usage: secret hashalg encalg isclient secretdata");
1569 if(tr->c == nil || !tr->verset)
1570 error("must set fd and version before secrets");
1572 if(tr->in.new != nil){
1573 freeSec(tr->in.new);
1576 if(tr->out.new != nil){
1577 freeSec(tr->out.new);
1581 ha = parsehashalg(cb->f[1]);
1582 ea = parseencalg(cb->f[2]);
1585 m = (strlen(p)*3)/2;
1595 m = dec64(x, m, p, strlen(p));
1596 if(m < 2 * ha->maclen + 2 * ea->keylen + 2 * ea->ivlen)
1597 error("not enough secret data provided");
1599 tos = smalloc(sizeof(Secret));
1600 toc = smalloc(sizeof(Secret));
1601 if(!ha->initkey || !ea->initkey)
1602 error("misimplemented secret algorithm");
1603 (*ha->initkey)(ha, tr->version, tos, &x[0]);
1604 (*ha->initkey)(ha, tr->version, toc, &x[ha->maclen]);
1605 (*ea->initkey)(ea, tos, &x[2 * ha->maclen], &x[2 * ha->maclen + 2 * ea->keylen]);
1606 (*ea->initkey)(ea, toc, &x[2 * ha->maclen + ea->keylen], &x[2 * ha->maclen + 2 * ea->keylen + ea->ivlen]);
1608 if(!tos->mac || !tos->enc || !tos->dec
1609 || !toc->mac || !toc->enc || !toc->dec)
1610 error("missing algorithm implementations");
1611 if(strtol(cb->f[3], nil, 0) == 0){
1618 if(tr->version == SSL3Version){
1619 toc->unpad = sslunpad;
1620 tos->unpad = sslunpad;
1622 toc->unpad = tlsunpad;
1623 tos->unpad = tlsunpad;
1625 toc->encalg = ea->name;
1626 toc->hashalg = ha->name;
1627 tos->encalg = ea->name;
1628 tos->hashalg = ha->name;
1632 }else if(strcmp(cb->f[0], "changecipher") == 0){
1634 error("usage: changecipher");
1635 if(tr->out.new == nil)
1636 error("cannot change cipher spec without setting secret");
1638 qunlock(&tr->in.seclock);
1639 qunlock(&tr->out.seclock);
1645 * the real work is done as the message is written
1646 * so the stream is encrypted in sync.
1650 tlsrecwrite(tr, RChangeCipherSpec, b);
1652 }else if(strcmp(cb->f[0], "opened") == 0){
1654 error("usage: opened");
1655 if(tr->in.sec == nil || tr->out.sec == nil)
1656 error("cipher must be configured before enabling data messages");
1658 if(tr->state != SHandshake && tr->state != SOpen){
1659 unlock(&tr->statelk);
1660 error("cannot enable data messages");
1663 unlock(&tr->statelk);
1665 }else if(strcmp(cb->f[0], "alert") == 0){
1667 error("usage: alert n");
1669 error("must set fd before sending alerts");
1670 m = strtol(cb->f[1], nil, 0);
1672 qunlock(&tr->in.seclock);
1673 qunlock(&tr->out.seclock);
1680 if(m == ECloseNotify)
1681 tlsclosed(tr, SLClose);
1684 } else if(strcmp(cb->f[0], "debug") == 0){
1686 if(strcmp(cb->f[1], "on") == 0)
1695 qunlock(&tr->in.seclock);
1696 qunlock(&tr->out.seclock);
1714 fmtinstall('H', encodefmt);
1718 tlsdevs = smalloc(sizeof(TlsRec*) * maxtlsdevs);
1719 trnames = smalloc((sizeof *trnames) * maxtlsdevs);
1722 for(e = encrypttab; e->name != nil; e++)
1723 n += strlen(e->name) + 1;
1724 cp = encalgs = smalloc(n);
1725 for(e = encrypttab;;){
1726 strcpy(cp, e->name);
1727 cp += strlen(e->name);
1736 for(h = hashtab; h->name != nil; h++)
1737 n += strlen(h->name) + 1;
1738 cp = hashalgs = smalloc(n);
1740 strcpy(cp, h->name);
1741 cp += strlen(h->name);
1771 /* get channel associated with an fd */
1780 fd = strtoul(p, 0, 0);
1783 c = fdtochan(fd, -1, 0, 1); /* error check and inc ref */
1788 sendAlert(TlsRec *tr, int err)
1794 if(tr->debug)pprint("sendAlert %d\n", err);
1796 msg = "tls unknown alert";
1797 for(i=0; i < nelem(tlserrs); i++) {
1798 if(tlserrs[i].err == err) {
1799 msg = tlserrs[i].msg;
1800 if(tr->version == SSL3Version)
1801 err = tlserrs[i].sslerr;
1803 err = tlserrs[i].tlserr;
1804 fatal = tlserrs[i].fatal;
1811 *b->wp++ = fatal + 1;
1814 tlsSetState(tr, SAlert, SOpen|SHandshake|SRClose);
1815 tlsrecwrite(tr, RAlert, b);
1823 tlsError(TlsRec *tr, char *msg)
1827 if(tr->debug)pprint("tleError %s\n", msg);
1832 strncpy(tr->err, msg, ERRMAX - 1);
1833 tr->err[ERRMAX - 1] = '\0';
1835 unlock(&tr->statelk);
1841 tlsSetState(TlsRec *tr, int new, int old)
1846 unlock(&tr->statelk);
1849 /* hand up a digest connection */
1851 tlshangup(TlsRec *tr)
1856 for(b = tr->processed; b; b = tr->processed){
1857 tr->processed = b->next;
1860 if(tr->unprocessed != nil){
1861 freeb(tr->unprocessed);
1862 tr->unprocessed = nil;
1864 qunlock(&tr->in.io);
1866 tlsSetState(tr, SClosed, ~0);
1872 TlsRec **pp, **ep, **np;
1881 ep = &tlsdevs[maxtlsdevs];
1882 for(pp = tlsdevs; pp < ep; pp++)
1886 if(maxtlsdevs >= MaxTlsDevs) {
1891 newmax = 2 * maxtlsdevs;
1892 if(newmax > MaxTlsDevs)
1893 newmax = MaxTlsDevs;
1894 np = smalloc(sizeof(TlsRec*) * newmax);
1895 memmove(np, tlsdevs, sizeof(TlsRec*) * maxtlsdevs);
1897 pp = &tlsdevs[maxtlsdevs];
1898 memset(pp, 0, sizeof(TlsRec*)*(newmax - maxtlsdevs));
1900 nmp = smalloc(sizeof *nmp * newmax);
1901 memmove(nmp, trnames, sizeof *nmp * maxtlsdevs);
1904 maxtlsdevs = newmax;
1907 if(pp - tlsdevs >= tdhiwat)
1912 ch->qid.path = QID(pp - tlsdevs, t);
1924 tr = mallocz(sizeof(*tr), 1);
1927 tr->state = SClosed;
1929 kstrdup(&tr->user, up->user);
1939 return "Handshaking";
1941 return "Established";
1943 return "RemoteClosed";
1945 return "LocalClosed";
1966 noenc(Secret *, uchar *, int n)
1972 rc4enc(Secret *sec, uchar *buf, int n)
1974 rc4(sec->enckey, buf, n);
1979 tlsunpad(uchar *buf, int n, int block)
1985 if(nn <= 0 || n % block)
1988 if(pad != buf[n - 1])
1994 sslunpad(uchar *buf, int n, int block)
2000 if(nn <= 0 || n % block)
2006 blockpad(uchar *buf, int n, int block)
2019 des3enc(Secret *sec, uchar *buf, int n)
2021 n = blockpad(buf, n, 8);
2022 des3CBCencrypt(buf, n, sec->enckey);
2027 des3dec(Secret *sec, uchar *buf, int n)
2029 des3CBCdecrypt(buf, n, sec->enckey);
2030 return (*sec->unpad)(buf, n, 8);
2034 aesenc(Secret *sec, uchar *buf, int n)
2036 n = blockpad(buf, n, 16);
2037 aesCBCencrypt(buf, n, sec->enckey);
2042 aesdec(Secret *sec, uchar *buf, int n)
2044 aesCBCdecrypt(buf, n, sec->enckey);
2045 return (*sec->unpad)(buf, n, 16);
2049 nomac(uchar *, ulong, uchar *, ulong, uchar *, DigestState *)
2055 * sslmac: mac calculations for ssl 3.0 only; tls 1.0 uses the standard hmac.
2058 sslmac_x(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s,
2059 DigestState*(*x)(uchar*, ulong, uchar*, DigestState*), int xlen, int padlen)
2062 uchar pad[48], innerdigest[20];
2064 if(xlen > sizeof(innerdigest)
2065 || padlen > sizeof(pad))
2071 /* first time through */
2073 for(i=0; i<padlen; i++)
2075 s = (*x)(key, klen, nil, nil);
2076 s = (*x)(pad, padlen, nil, s);
2081 s = (*x)(p, len, nil, s);
2085 /* last time through */
2086 for(i=0; i<padlen; i++)
2088 (*x)(nil, 0, innerdigest, s);
2089 s = (*x)(key, klen, nil, nil);
2090 s = (*x)(pad, padlen, nil, s);
2091 (*x)(innerdigest, xlen, digest, s);
2096 sslmac_sha1(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2098 return sslmac_x(p, len, key, klen, digest, s, sha1, SHA1dlen, 40);
2102 sslmac_md5(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2104 return sslmac_x(p, len, key, klen, digest, s, md5, MD5dlen, 48);
2108 sslPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac)
2113 memmove(buf, seq, 8);
2116 buf[10] = header[4];
2118 s = (*sec->mac)(buf, 11, mackey, sec->maclen, 0, 0);
2119 (*sec->mac)(body, len, mackey, sec->maclen, mac, s);
2123 tlsPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac)
2128 memmove(buf, seq, 8);
2129 memmove(&buf[8], header, 5);
2131 s = (*sec->mac)(buf, 13, mackey, sec->maclen, 0, 0);
2132 (*sec->mac)(body, len, mackey, sec->maclen, mac, s);
2136 put32(uchar *p, u32int x)
2145 put64(uchar *p, vlong x)
2147 put32(p, (u32int)(x >> 32));
2148 put32(p+4, (u32int)x);
2152 put24(uchar *p, int x)
2160 put16(uchar *p, int x)
2169 return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
2175 return (p[0]<<8)|p[1];
2178 static char *charmap = "0123456789abcdef";
2181 pdump(int len, void *a, char *tag)
2191 q = buf + strlen(tag);
2192 for(i = 0; len > 0 && i < 32; i++){
2193 if(*p >= ' ' && *p < 0x7f){
2197 *q++ = charmap[*p>>4];
2198 *q++ = charmap[*p & 0xf];
2206 pprint("%s...\n", buf);
2208 pprint("%s\n", buf);