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 noenc(Secret *sec, uchar *buf, int n);
238 static int sslunpad(uchar *buf, int n, int block);
239 static int tlsunpad(uchar *buf, int n, int block);
240 static void freeSec(Secret *sec);
241 static char *tlsstate(int s);
242 static void pdump(int, void*, char*);
244 #pragma varargck argpos rcvError 3
246 static char *tlsnames[] = {
248 [Qencalgs] "encalgs",
249 [Qhashalgs] "hashalgs",
257 static int convdir[] = { Qctl, Qdata, Qhand, Qstatus, Qstats };
260 tlsgen(Chan *c, char*, Dirtab *, int, int s, Dir *dp)
274 q.path = QID(0, Qtopdir);
276 devdir(c, q, "#a", 0, eve, 0555, dp);
281 q.path = QID(0, Qprotodir);
283 devdir(c, q, "tls", 0, eve, 0555, dp);
287 q.path = QID(0, Qtopdir);
289 devdir(c, q, ".", 0, eve, 0555, dp);
297 q.path = QID(0, Qclonus);
300 q.path = QID(0, Qencalgs);
303 q.path = QID(0, Qhashalgs);
307 if(TYPE(q) == Qclonus)
309 devdir(c, q, tlsnames[TYPE(q)], 0, eve, perm, dp);
315 q.path = QID(s, Qconvdir);
323 if((name = trnames[s]) == nil){
324 name = trnames[s] = smalloc(16);
325 sprint(name, "%d", s);
327 devdir(c, q, name, 0, nm, 0555, dp);
332 q.path = QID(0, Qprotodir);
334 devdir(c, q, "tls", 0, eve, 0555, dp);
337 if(s < 0 || s >= nelem(convdir))
340 tr = tlsdevs[CONV(c->qid)];
349 if(t == Qstatus || t == Qstats)
351 q.path = QID(CONV(c->qid), t);
352 devdir(c, q, tlsnames[t], 0, nm, perm, dp);
361 devdir(c, c->qid, tlsnames[t], 0, eve, perm, dp);
365 tr = tlsdevs[CONV(c->qid)];
373 if(t == Qstatus || t == Qstats)
375 devdir(c, c->qid, tlsnames[t], 0, nm, perm, dp);
382 tlsattach(char *spec)
386 c = devattach('a', spec);
387 c->qid.path = QID(0, Qtopdir);
394 tlswalk(Chan *c, Chan *nc, char **name, int nname)
396 return devwalk(c, nc, name, nname, nil, 0, tlsgen);
400 tlsstat(Chan *c, uchar *db, int n)
402 return devstat(c, db, n, nil, 0, tlsgen);
406 tlsopen(Chan *c, int omode)
445 if((t == Qstatus || t == Qstats) && omode != OREAD)
452 pp = &tlsdevs[CONV(c->qid)];
455 error("must open connection using clone");
456 if((perm & (tr->perm>>6)) != perm
457 && (strcmp(up->user, tr->user) != 0
458 || (perm & tr->perm) != perm))
468 tr->handq = qopen(2 * MaxCipherRecLen, 0, nil, nil);
470 error("cannot allocate handshake queue");
485 c->mode = openmode(omode);
488 c->iounit = qiomaxatomic;
493 tlswstat(Chan *c, uchar *dp, int n)
507 tr = tlsdevs[CONV(c->qid)];
510 if(strcmp(tr->user, up->user) != 0)
513 d = smalloc(n + sizeof *d);
514 rv = convM2D(dp, n, &d[0], (char*) &d[1]);
517 if(!emptystr(d->uid))
518 kstrdup(&tr->user, d->uid);
533 if(--tr->hqref == 0){
534 if(tr->handq != nil){
538 if(tr->hprocessed != nil){
539 freeb(tr->hprocessed);
540 tr->hprocessed = nil;
559 if((c->flag & COPEN) == 0)
562 tr = tlsdevs[CONV(c->qid)];
574 tlsdevs[CONV(c->qid)] = nil;
577 if(tr->c != nil && !waserror()){
578 checkstate(tr, 0, SOpen|SHandshake|SRClose);
579 sendAlert(tr, ECloseNotify);
587 freeSec(tr->out.sec);
588 freeSec(tr->out.new);
596 * make sure we have at least 'n' bytes in list 'l'
599 ensure(TlsRec *s, Block **l, int n)
605 for(b = *l; b; b = b->next){
613 bl = devtab[s->c->type]->bread(s->c, MaxCipherRecLen + RecHdrLen, 0);
618 for(b = bl; b; b = b->next){
626 if(s->debug) pprint("ensure read %d\n", sofar);
630 * copy 'n' bytes from 'l' into 'p' and free
634 consume(Block **l, uchar *p, int n)
639 for(; *l && n > 0; n -= i){
644 memmove(p, b->rp, i);
660 regurgitate(TlsRec *s, uchar *p, int n)
667 if(s->unprocessed == nil || b->rp - b->base < n) {
669 memmove(b->wp, p, n);
671 b->next = s->unprocessed;
675 memmove(b->rp, p, n);
680 * remove at most n bytes from the queue
683 qgrab(Block **l, int n)
696 for(bb = b; bb != nil && i < n; bb = bb->next)
702 consume(l, bb->wp, i);
708 tlsclosed(TlsRec *tr, int new)
711 if(tr->state == SOpen || tr->state == SHandshake)
713 else if((new | tr->state) == (SRClose|SLClose))
715 unlock(&tr->statelk);
716 alertHand(tr, "close notify");
720 * read and process one tls record layer message
721 * must be called with tr->in.io held
722 * We can't let Eintrs lose data, since doing so will get
723 * us out of sync with the sender and break the reliablity
724 * of the channel. Eintr only happens during the reads in
725 * consume. Therefore we put back any bytes consumed before
726 * the last call to ensure.
729 tlsrecread(TlsRec *tr)
733 uchar *p, seq[8], header[RecHdrLen], hmac[MD5dlen];
734 int volatile nconsumed;
735 int len, type, ver, unpad_len;
739 if(strcmp(up->errstr, Eintr) == 0 && !waserror()){
740 regurgitate(tr, header, nconsumed);
743 tlsError(tr, "channel error");
746 ensure(tr, &tr->unprocessed, RecHdrLen);
747 consume(&tr->unprocessed, header, RecHdrLen);
748 if(tr->debug)pprint("consumed %d header\n", RecHdrLen);
749 nconsumed = RecHdrLen;
751 if((tr->handin == 0) && (header[0] & 0x80)){
752 /* Cope with an SSL3 ClientHello expressed in SSL2 record format.
753 This is sent by some clients that we must interoperate
754 with, such as Java's JSSE and Microsoft's Internet Explorer. */
755 len = (get16(header) & ~0x8000) - 3;
757 ver = get16(header + 3);
758 if(type != SSL2ClientHello || len < 22)
759 rcvError(tr, EProtocolVersion, "invalid initial SSL2-like message");
760 }else{ /* normal SSL3 record format */
762 ver = get16(header+1);
763 len = get16(header+3);
765 if(ver != tr->version && (tr->verset || ver < MinProtoVersion || ver > MaxProtoVersion))
766 rcvError(tr, EProtocolVersion, "devtls expected ver=%x%s, saw (len=%d) type=%x ver=%x '%.12s'",
767 tr->version, tr->verset?"/set":"", len, type, ver, (char*)header);
768 if(len > MaxCipherRecLen || len < 0)
769 rcvError(tr, ERecordOverflow, "record message too long %d", len);
770 ensure(tr, &tr->unprocessed, len);
775 * If an Eintr happens after this, we'll get out of sync.
776 * Make sure nothing we call can sleep.
777 * Errors are ok, as they kill the connection.
778 * Luckily, allocb won't sleep, it'll just error out.
784 tlsError(tr, "channel error");
787 b = qgrab(&tr->unprocessed, len);
788 if(tr->debug) pprint("consumed unprocessed %d\n", len);
792 qunlock(&in->seclock);
798 /* to avoid Canvel-Hiltgen-Vaudenay-Vuagnoux attack, all errors here
799 should look alike, including timing of the response. */
800 unpad_len = (*in->sec->dec)(in->sec, p, len);
801 if(unpad_len >= in->sec->maclen)
802 len = unpad_len - in->sec->maclen;
803 if(tr->debug) pprint("decrypted %d\n", unpad_len);
804 if(tr->debug) pdump(unpad_len, p, "decrypted:");
807 put16(header+3, len);
810 (*tr->packMac)(in->sec, in->sec->mackey, seq, header, p, len, hmac);
811 if(unpad_len < in->sec->maclen)
812 rcvError(tr, EBadRecordMac, "short record mac");
813 if(memcmp(hmac, p+len, in->sec->maclen) != 0)
814 rcvError(tr, EBadRecordMac, "record mac mismatch");
817 qunlock(&in->seclock);
820 rcvError(tr, EDecodeError, "runt record message");
824 rcvError(tr, EIllegalParameter, "invalid record message %#x", type);
826 case RChangeCipherSpec:
827 if(len != 1 || p[0] != 1)
828 rcvError(tr, EDecodeError, "invalid change cipher spec");
831 qunlock(&in->seclock);
832 rcvError(tr, EUnexpectedMessage, "unexpected change cipher spec");
838 qunlock(&in->seclock);
842 rcvError(tr, EDecodeError, "invalid alert");
846 rcvError(tr, EIllegalParameter, "invalid alert fatal code");
849 * propate non-fatal alerts to handshaker
851 if(p[1] == ECloseNotify) {
852 tlsclosed(tr, SRClose);
855 error("close notify");
857 if(p[1] == ENoRenegotiation)
858 alertHand(tr, "no renegotiation");
859 else if(p[1] == EUserCanceled)
860 alertHand(tr, "handshake canceled by user");
862 rcvError(tr, EIllegalParameter, "invalid alert code");
866 * don't worry about dropping the block
867 * qbwrite always queues even if flow controlled and interrupted.
869 * if there isn't any handshaker, ignore the request,
870 * but notify the other side we are doing so.
873 if(tr->handq != nil){
882 qbwrite(tr->handq, b);
888 if(tr->verset && tr->version != SSL3Version && !waserror()){
889 sendAlert(tr, ENoRenegotiation);
894 case SSL2ClientHello:
896 if(tr->handq != nil){
903 /* Pass the SSL2 format data, so that the handshake code can compute
904 the correct checksums. HSSL2ClientHello = HandshakeType 9 is
905 unused in RFC2246. */
907 b->rp[0] = RHandshake;
908 b->rp[1] = HSSL2ClientHello;
909 put24(&b->rp[2], len+3);
910 b->rp[5] = SSL2ClientHello;
911 put16(&b->rp[6], ver);
912 qbwrite(tr->handq, b);
918 if(tr->verset && tr->version != SSL3Version && !waserror()){
919 sendAlert(tr, ENoRenegotiation);
926 rcvError(tr, EUnexpectedMessage, "application message received before handshake completed");
939 * got a fatal alert message
942 rcvAlert(TlsRec *tr, int err)
948 for(i=0; i < nelem(tlserrs); i++){
949 if(tlserrs[i].err == err){
954 if(tr->debug) pprint("rcvAlert: %s\n", s);
963 * found an error while decoding the input stream
966 rcvError(TlsRec *tr, int err, char *fmt, ...)
972 vseprint(msg, msg+sizeof(msg), fmt, arg);
974 if(tr->debug) pprint("rcvError: %s\n", msg);
984 * make sure the next hand operation returns with a 'msg' error
987 alertHand(TlsRec *tr, char *msg)
993 if(tr->handq == nil){
1007 memmove(b->wp, msg, n + 1);
1010 qbwrite(tr->handq, b);
1017 checkstate(TlsRec *tr, int ishand, int ok)
1023 unlock(&tr->statelk);
1038 error("tls hungup");
1040 error("tls improperly configured");
1044 tlsbread(Chan *c, long n, ulong offset)
1048 TlsRec *volatile tr;
1053 return devbread(c, n, offset);
1059 tr = tlsdevs[CONV(c->qid)];
1064 qunlock(&tr->in.io);
1069 checkstate(tr, 0, SOpen);
1070 while(tr->processed == nil)
1073 /* return at most what was asked for */
1074 b = qgrab(&tr->processed, n);
1075 if(tr->debug) pprint("consumed processed %ld\n", BLEN(b));
1076 if(tr->debug) pdump(BLEN(b), b->rp, "consumed:");
1077 qunlock(&tr->in.io);
1079 tr->datain += BLEN(b);
1081 checkstate(tr, 1, SOpen|SHandshake|SLClose);
1084 * it's ok to look at state without the lock
1085 * since it only protects reading records,
1086 * and we have that tr->in.io held.
1088 while(!tr->opened && tr->hprocessed == nil && !qcanread(tr->handq))
1091 qunlock(&tr->in.io);
1095 qunlock(&tr->hqread);
1099 if(tr->hprocessed == nil){
1100 b = qbread(tr->handq, MaxRecLen + 1);
1101 if(*b->rp++ == RAlert){
1102 kstrcpy(up->errstr, (char*)b->rp, ERRMAX);
1108 b = qgrab(&tr->hprocessed, n);
1110 qunlock(&tr->hqread);
1111 tr->handin += BLEN(b);
1118 tlsread(Chan *c, void *a, long n, vlong off)
1128 if(c->qid.type & QTDIR)
1129 return devdirread(c, a, n, 0, 0, tlsgen);
1131 tr = tlsdevs[CONV(c->qid)];
1137 buf = smalloc(Statlen);
1138 qlock(&tr->in.seclock);
1139 qlock(&tr->out.seclock);
1142 s = seprint(s, e, "State: %s\n", tlsstate(tr->state));
1143 s = seprint(s, e, "Version: %#x\n", tr->version);
1144 if(tr->in.sec != nil)
1145 s = seprint(s, e, "EncIn: %s\nHashIn: %s\n", tr->in.sec->encalg, tr->in.sec->hashalg);
1146 if(tr->in.new != nil)
1147 s = seprint(s, e, "NewEncIn: %s\nNewHashIn: %s\n", tr->in.new->encalg, tr->in.new->hashalg);
1148 if(tr->out.sec != nil)
1149 s = seprint(s, e, "EncOut: %s\nHashOut: %s\n", tr->out.sec->encalg, tr->out.sec->hashalg);
1150 if(tr->out.new != nil)
1151 seprint(s, e, "NewEncOut: %s\nNewHashOut: %s\n", tr->out.new->encalg, tr->out.new->hashalg);
1152 qunlock(&tr->in.seclock);
1153 qunlock(&tr->out.seclock);
1154 n = readstr(offset, a, n, buf);
1158 buf = smalloc(Statlen);
1161 s = seprint(s, e, "DataIn: %lld\n", tr->datain);
1162 s = seprint(s, e, "DataOut: %lld\n", tr->dataout);
1163 s = seprint(s, e, "HandIn: %lld\n", tr->handin);
1164 seprint(s, e, "HandOut: %lld\n", tr->handout);
1165 n = readstr(offset, a, n, buf);
1169 buf = smalloc(Statlen);
1170 snprint(buf, Statlen, "%llud", CONV(c->qid));
1171 n = readstr(offset, a, n, buf);
1176 b = tlsbread(c, n, offset);
1179 return readstr(offset, a, n, encalgs);
1181 return readstr(offset, a, n, hashalgs);
1191 for(nb = b; nb; nb = nb->next){
1193 memmove(va+n, nb->rp, i);
1204 * write a block in tls records
1207 tlsrecwrite(TlsRec *tr, int type, Block *b)
1212 OneWay *volatile out;
1213 int n, maclen, pad, ok;
1224 if(tr->debug)pprint("send %ld\n", BLEN(b));
1225 if(tr->debug)pdump(BLEN(b), b->rp, "sent:");
1228 ok = SHandshake|SOpen|SRClose;
1232 checkstate(tr, type != RApplication, ok);
1235 * get at most one maximal record's input,
1236 * with padding on the front for header and
1237 * back for mac and maximal block padding.
1240 qunlock(&out->seclock);
1243 qlock(&out->seclock);
1246 if(out->sec != nil){
1247 maclen = out->sec->maclen;
1248 pad = maclen + out->sec->block;
1253 nb = allocb(n + pad + RecHdrLen);
1254 memmove(nb->wp + RecHdrLen, bb->rp, n);
1258 * carefully reuse bb so it will get freed if we're out of memory
1260 bb = padblock(bb, RecHdrLen);
1262 nb = padblock(bb, -pad);
1270 put16(p+1, tr->version);
1273 if(out->sec != nil){
1274 put64(seq, out->seq);
1276 (*tr->packMac)(out->sec, out->sec->mackey, seq, p, p + RecHdrLen, n, p + RecHdrLen + n);
1280 n = (*out->sec->enc)(out->sec, p + RecHdrLen, n);
1281 nb->wp = p + RecHdrLen + n;
1286 if(type == RChangeCipherSpec){
1288 error("change cipher without a new cipher");
1290 out->sec = out->new;
1294 qunlock(&out->seclock);
1298 * if bwrite error's, we assume the block is queued.
1299 * if not, we're out of sync with the receiver and will not recover.
1302 if(strcmp(up->errstr, "interrupted") != 0)
1303 tlsError(tr, "channel error");
1306 devtab[tr->c->type]->bwrite(tr->c, nb, 0);
1314 tlsbwrite(Chan *c, Block *b, ulong offset)
1322 tr = tlsdevs[CONV(c->qid)];
1329 return devbwrite(c, b, offset);
1331 tlsrecwrite(tr, RHandshake, b);
1335 checkstate(tr, 0, SOpen);
1336 tlsrecwrite(tr, RApplication, b);
1344 typedef struct Hashalg Hashalg;
1349 void (*initkey)(Hashalg *, int, Secret *, uchar*);
1353 initmd5key(Hashalg *ha, int version, Secret *s, uchar *p)
1355 s->maclen = ha->maclen;
1356 if(version == SSL3Version)
1357 s->mac = sslmac_md5;
1360 memmove(s->mackey, p, ha->maclen);
1364 initclearmac(Hashalg *, int, Secret *s, uchar *)
1371 initsha1key(Hashalg *ha, int version, Secret *s, uchar *p)
1373 s->maclen = ha->maclen;
1374 if(version == SSL3Version)
1375 s->mac = sslmac_sha1;
1378 memmove(s->mackey, p, ha->maclen);
1381 static Hashalg hashtab[] =
1383 { "clear", 0, initclearmac, },
1384 { "md5", MD5dlen, initmd5key, },
1385 { "sha1", SHA1dlen, initsha1key, },
1390 parsehashalg(char *p)
1394 for(ha = hashtab; ha->name; ha++)
1395 if(strcmp(p, ha->name) == 0)
1397 error("unsupported hash algorithm");
1401 typedef struct Encalg Encalg;
1407 void (*initkey)(Encalg *ea, Secret *, uchar*, uchar*);
1411 initRC4key(Encalg *ea, Secret *s, uchar *p, uchar *)
1413 s->enckey = smalloc(sizeof(RC4state));
1417 setupRC4state(s->enckey, p, ea->keylen);
1421 initDES3key(Encalg *, Secret *s, uchar *p, uchar *iv)
1423 s->enckey = smalloc(sizeof(DES3state));
1427 setupDES3state(s->enckey, (uchar(*)[8])p, iv);
1431 initclearenc(Encalg *, Secret *s, uchar *, uchar *)
1438 static Encalg encrypttab[] =
1440 { "clear", 0, 0, initclearenc },
1441 { "rc4_128", 128/8, 0, initRC4key },
1442 { "3des_ede_cbc", 3 * 8, 8, initDES3key },
1447 parseencalg(char *p)
1451 for(ea = encrypttab; ea->name; ea++)
1452 if(strcmp(p, ea->name) == 0)
1454 error("unsupported encryption algorithm");
1459 tlswrite(Chan *c, void *a, long n, vlong off)
1463 TlsRec *volatile tr;
1464 Secret *volatile tos, *volatile toc;
1466 Cmdbuf *volatile cb;
1472 tr = tlsdevs[CONV(c->qid)];
1492 memmove(b->wp, p, m);
1496 tlsbwrite(c, b, offset);
1508 cb = parsecmd(a, n);
1514 error("short control request");
1516 /* mutex with operations using what we're about to change */
1518 qunlock(&tr->in.seclock);
1519 qunlock(&tr->out.seclock);
1522 qlock(&tr->in.seclock);
1523 qlock(&tr->out.seclock);
1525 if(strcmp(cb->f[0], "fd") == 0){
1527 error("usage: fd open-fd version");
1530 m = strtol(cb->f[2], nil, 0);
1531 if(m < MinProtoVersion || m > MaxProtoVersion)
1532 error("unsupported version");
1533 tr->c = buftochan(cb->f[1]);
1535 tlsSetState(tr, SHandshake, SClosed);
1536 }else if(strcmp(cb->f[0], "version") == 0){
1538 error("usage: version vers");
1540 error("must set fd before version");
1542 error("version already set");
1543 m = strtol(cb->f[1], nil, 0);
1544 if(m == SSL3Version)
1545 tr->packMac = sslPackMac;
1546 else if(m == TLSVersion)
1547 tr->packMac = tlsPackMac;
1549 error("unsupported version");
1552 }else if(strcmp(cb->f[0], "secret") == 0){
1554 error("usage: secret hashalg encalg isclient secretdata");
1555 if(tr->c == nil || !tr->verset)
1556 error("must set fd and version before secrets");
1558 if(tr->in.new != nil){
1559 freeSec(tr->in.new);
1562 if(tr->out.new != nil){
1563 freeSec(tr->out.new);
1567 ha = parsehashalg(cb->f[1]);
1568 ea = parseencalg(cb->f[2]);
1571 m = (strlen(p)*3)/2;
1581 m = dec64(x, m, p, strlen(p));
1582 if(m < 2 * ha->maclen + 2 * ea->keylen + 2 * ea->ivlen)
1583 error("not enough secret data provided");
1585 tos = smalloc(sizeof(Secret));
1586 toc = smalloc(sizeof(Secret));
1587 if(!ha->initkey || !ea->initkey)
1588 error("misimplemented secret algorithm");
1589 (*ha->initkey)(ha, tr->version, tos, &x[0]);
1590 (*ha->initkey)(ha, tr->version, toc, &x[ha->maclen]);
1591 (*ea->initkey)(ea, tos, &x[2 * ha->maclen], &x[2 * ha->maclen + 2 * ea->keylen]);
1592 (*ea->initkey)(ea, toc, &x[2 * ha->maclen + ea->keylen], &x[2 * ha->maclen + 2 * ea->keylen + ea->ivlen]);
1594 if(!tos->mac || !tos->enc || !tos->dec
1595 || !toc->mac || !toc->enc || !toc->dec)
1596 error("missing algorithm implementations");
1597 if(strtol(cb->f[3], nil, 0) == 0){
1604 if(tr->version == SSL3Version){
1605 toc->unpad = sslunpad;
1606 tos->unpad = sslunpad;
1608 toc->unpad = tlsunpad;
1609 tos->unpad = tlsunpad;
1611 toc->encalg = ea->name;
1612 toc->hashalg = ha->name;
1613 tos->encalg = ea->name;
1614 tos->hashalg = ha->name;
1618 }else if(strcmp(cb->f[0], "changecipher") == 0){
1620 error("usage: changecipher");
1621 if(tr->out.new == nil)
1622 error("cannot change cipher spec without setting secret");
1624 qunlock(&tr->in.seclock);
1625 qunlock(&tr->out.seclock);
1631 * the real work is done as the message is written
1632 * so the stream is encrypted in sync.
1636 tlsrecwrite(tr, RChangeCipherSpec, b);
1638 }else if(strcmp(cb->f[0], "opened") == 0){
1640 error("usage: opened");
1641 if(tr->in.sec == nil || tr->out.sec == nil)
1642 error("cipher must be configured before enabling data messages");
1644 if(tr->state != SHandshake && tr->state != SOpen){
1645 unlock(&tr->statelk);
1646 error("cannot enable data messages");
1649 unlock(&tr->statelk);
1651 }else if(strcmp(cb->f[0], "alert") == 0){
1653 error("usage: alert n");
1655 error("must set fd before sending alerts");
1656 m = strtol(cb->f[1], nil, 0);
1658 qunlock(&tr->in.seclock);
1659 qunlock(&tr->out.seclock);
1666 if(m == ECloseNotify)
1667 tlsclosed(tr, SLClose);
1670 } else if(strcmp(cb->f[0], "debug") == 0){
1672 if(strcmp(cb->f[1], "on") == 0)
1681 qunlock(&tr->in.seclock);
1682 qunlock(&tr->out.seclock);
1700 fmtinstall('H', encodefmt);
1704 tlsdevs = smalloc(sizeof(TlsRec*) * maxtlsdevs);
1705 trnames = smalloc((sizeof *trnames) * maxtlsdevs);
1708 for(e = encrypttab; e->name != nil; e++)
1709 n += strlen(e->name) + 1;
1710 cp = encalgs = smalloc(n);
1711 for(e = encrypttab;;){
1712 strcpy(cp, e->name);
1713 cp += strlen(e->name);
1722 for(h = hashtab; h->name != nil; h++)
1723 n += strlen(h->name) + 1;
1724 cp = hashalgs = smalloc(n);
1726 strcpy(cp, h->name);
1727 cp += strlen(h->name);
1757 /* get channel associated with an fd */
1766 fd = strtoul(p, 0, 0);
1769 c = fdtochan(fd, -1, 0, 1); /* error check and inc ref */
1774 sendAlert(TlsRec *tr, int err)
1780 if(tr->debug)pprint("sendAlert %d\n", err);
1782 msg = "tls unknown alert";
1783 for(i=0; i < nelem(tlserrs); i++) {
1784 if(tlserrs[i].err == err) {
1785 msg = tlserrs[i].msg;
1786 if(tr->version == SSL3Version)
1787 err = tlserrs[i].sslerr;
1789 err = tlserrs[i].tlserr;
1790 fatal = tlserrs[i].fatal;
1797 *b->wp++ = fatal + 1;
1800 tlsSetState(tr, SAlert, SOpen|SHandshake|SRClose);
1801 tlsrecwrite(tr, RAlert, b);
1809 tlsError(TlsRec *tr, char *msg)
1813 if(tr->debug)pprint("tleError %s\n", msg);
1818 strncpy(tr->err, msg, ERRMAX - 1);
1819 tr->err[ERRMAX - 1] = '\0';
1821 unlock(&tr->statelk);
1827 tlsSetState(TlsRec *tr, int new, int old)
1832 unlock(&tr->statelk);
1835 /* hand up a digest connection */
1837 tlshangup(TlsRec *tr)
1842 for(b = tr->processed; b; b = tr->processed){
1843 tr->processed = b->next;
1846 if(tr->unprocessed != nil){
1847 freeb(tr->unprocessed);
1848 tr->unprocessed = nil;
1850 qunlock(&tr->in.io);
1852 tlsSetState(tr, SClosed, ~0);
1858 TlsRec **pp, **ep, **np;
1867 ep = &tlsdevs[maxtlsdevs];
1868 for(pp = tlsdevs; pp < ep; pp++)
1872 if(maxtlsdevs >= MaxTlsDevs) {
1877 newmax = 2 * maxtlsdevs;
1878 if(newmax > MaxTlsDevs)
1879 newmax = MaxTlsDevs;
1880 np = smalloc(sizeof(TlsRec*) * newmax);
1881 memmove(np, tlsdevs, sizeof(TlsRec*) * maxtlsdevs);
1883 pp = &tlsdevs[maxtlsdevs];
1884 memset(pp, 0, sizeof(TlsRec*)*(newmax - maxtlsdevs));
1886 nmp = smalloc(sizeof *nmp * newmax);
1887 memmove(nmp, trnames, sizeof *nmp * maxtlsdevs);
1890 maxtlsdevs = newmax;
1893 if(pp - tlsdevs >= tdhiwat)
1898 ch->qid.path = QID(pp - tlsdevs, t);
1910 tr = mallocz(sizeof(*tr), 1);
1913 tr->state = SClosed;
1915 kstrdup(&tr->user, up->user);
1925 return "Handshaking";
1927 return "Established";
1929 return "RemoteClosed";
1931 return "LocalClosed";
1952 noenc(Secret *, uchar *, int n)
1958 rc4enc(Secret *sec, uchar *buf, int n)
1960 rc4(sec->enckey, buf, n);
1965 tlsunpad(uchar *buf, int n, int block)
1971 if(nn <= 0 || n % block)
1974 if(pad != buf[n - 1])
1980 sslunpad(uchar *buf, int n, int block)
1986 if(nn <= 0 || n % block)
1992 blockpad(uchar *buf, int n, int block)
2005 des3enc(Secret *sec, uchar *buf, int n)
2007 n = blockpad(buf, n, 8);
2008 des3CBCencrypt(buf, n, sec->enckey);
2013 des3dec(Secret *sec, uchar *buf, int n)
2015 des3CBCdecrypt(buf, n, sec->enckey);
2016 return (*sec->unpad)(buf, n, 8);
2019 nomac(uchar *, ulong, uchar *, ulong, uchar *, DigestState *)
2025 * sslmac: mac calculations for ssl 3.0 only; tls 1.0 uses the standard hmac.
2028 sslmac_x(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s,
2029 DigestState*(*x)(uchar*, ulong, uchar*, DigestState*), int xlen, int padlen)
2032 uchar pad[48], innerdigest[20];
2034 if(xlen > sizeof(innerdigest)
2035 || padlen > sizeof(pad))
2041 /* first time through */
2043 for(i=0; i<padlen; i++)
2045 s = (*x)(key, klen, nil, nil);
2046 s = (*x)(pad, padlen, nil, s);
2051 s = (*x)(p, len, nil, s);
2055 /* last time through */
2056 for(i=0; i<padlen; i++)
2058 (*x)(nil, 0, innerdigest, s);
2059 s = (*x)(key, klen, nil, nil);
2060 s = (*x)(pad, padlen, nil, s);
2061 (*x)(innerdigest, xlen, digest, s);
2066 sslmac_sha1(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2068 return sslmac_x(p, len, key, klen, digest, s, sha1, SHA1dlen, 40);
2072 sslmac_md5(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2074 return sslmac_x(p, len, key, klen, digest, s, md5, MD5dlen, 48);
2078 sslPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac)
2083 memmove(buf, seq, 8);
2086 buf[10] = header[4];
2088 s = (*sec->mac)(buf, 11, mackey, sec->maclen, 0, 0);
2089 (*sec->mac)(body, len, mackey, sec->maclen, mac, s);
2093 tlsPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac)
2098 memmove(buf, seq, 8);
2099 memmove(&buf[8], header, 5);
2101 s = (*sec->mac)(buf, 13, mackey, sec->maclen, 0, 0);
2102 (*sec->mac)(body, len, mackey, sec->maclen, mac, s);
2106 put32(uchar *p, u32int x)
2115 put64(uchar *p, vlong x)
2117 put32(p, (u32int)(x >> 32));
2118 put32(p+4, (u32int)x);
2122 put24(uchar *p, int x)
2130 put16(uchar *p, int x)
2139 return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
2145 return (p[0]<<8)|p[1];
2148 static char *charmap = "0123456789abcdef";
2151 pdump(int len, void *a, char *tag)
2161 q = buf + strlen(tag);
2162 for(i = 0; len > 0 && i < 32; i++){
2163 if(*p >= ' ' && *p < 0x7f){
2167 *q++ = charmap[*p>>4];
2168 *q++ = charmap[*p & 0xf];
2176 pprint("%s...\n", buf);
2178 pprint("%s\n", buf);