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 */
119 /* record layer mac functions for different protocol versions */
120 void (*packMac)(Secret*, uchar*, uchar*, uchar*, uchar*, int, uchar*);
122 /* input side -- protected by in.io */
124 Block *processed; /* next bunch of application data */
125 Block *unprocessed; /* data read from c but not parsed into records */
127 /* handshake queue */
128 Lock hqlock; /* protects hqref, alloc & free of handq, hprocessed */
130 Queue *handq; /* queue of handshake messages */
131 Block *hprocessed; /* remainder of last block read from handq */
132 QLock hqread; /* protects reads for hprocessed, handq */
150 static TlsErrs tlserrs[] = {
151 {ECloseNotify, ECloseNotify, ECloseNotify, 0, "close notify"},
152 {EUnexpectedMessage, EUnexpectedMessage, EUnexpectedMessage, 1, "unexpected message"},
153 {EBadRecordMac, EBadRecordMac, EBadRecordMac, 1, "bad record mac"},
154 {EDecryptionFailed, EIllegalParameter, EDecryptionFailed, 1, "decryption failed"},
155 {ERecordOverflow, EIllegalParameter, ERecordOverflow, 1, "record too long"},
156 {EDecompressionFailure, EDecompressionFailure, EDecompressionFailure, 1, "decompression failed"},
157 {EHandshakeFailure, EHandshakeFailure, EHandshakeFailure, 1, "could not negotiate acceptable security paramters"},
158 {ENoCertificate, ENoCertificate, ECertificateUnknown, 1, "no appropriate certificate available"},
159 {EBadCertificate, EBadCertificate, EBadCertificate, 1, "corrupted or invalid certificate"},
160 {EUnsupportedCertificate, EUnsupportedCertificate, EUnsupportedCertificate, 1, "unsupported certificate type"},
161 {ECertificateRevoked, ECertificateRevoked, ECertificateRevoked, 1, "revoked certificate"},
162 {ECertificateExpired, ECertificateExpired, ECertificateExpired, 1, "expired certificate"},
163 {ECertificateUnknown, ECertificateUnknown, ECertificateUnknown, 1, "unacceptable certificate"},
164 {EIllegalParameter, EIllegalParameter, EIllegalParameter, 1, "illegal parameter"},
165 {EUnknownCa, EHandshakeFailure, EUnknownCa, 1, "unknown certificate authority"},
166 {EAccessDenied, EHandshakeFailure, EAccessDenied, 1, "access denied"},
167 {EDecodeError, EIllegalParameter, EDecodeError, 1, "error decoding message"},
168 {EDecryptError, EIllegalParameter, EDecryptError, 1, "error decrypting message"},
169 {EExportRestriction, EHandshakeFailure, EExportRestriction, 1, "export restriction violated"},
170 {EProtocolVersion, EIllegalParameter, EProtocolVersion, 1, "protocol version not supported"},
171 {EInsufficientSecurity, EHandshakeFailure, EInsufficientSecurity, 1, "stronger security routines required"},
172 {EInternalError, EHandshakeFailure, EInternalError, 1, "internal error"},
173 {EUserCanceled, ECloseNotify, EUserCanceled, 0, "handshake canceled by user"},
174 {ENoRenegotiation, EUnexpectedMessage, ENoRenegotiation, 0, "no renegotiation"},
179 /* max. open tls connections */
185 static int maxtlsdevs = 128;
186 static TlsRec **tlsdevs;
187 static char **trnames;
188 static char *encalgs;
189 static char *hashalgs;
192 Qtopdir = 1, /* top level directory */
197 Qconvdir, /* directory for a conversation */
205 #define TYPE(x) ((x).path & 0xf)
206 #define CONV(x) (((x).path >> 5)&(MaxTlsDevs-1))
207 #define QID(c, y) (((c)<<5) | (y))
209 static void checkstate(TlsRec *, int, int);
210 static void ensure(TlsRec*, Block**, int);
211 static void consume(Block**, uchar*, int);
212 static Chan* buftochan(char*);
213 static void tlshangup(TlsRec*);
214 static void tlsError(TlsRec*, char *);
215 static void alertHand(TlsRec*, char *);
216 static TlsRec *newtls(Chan *c);
217 static TlsRec *mktlsrec(void);
218 static DigestState*sslmac_md5(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
219 static DigestState*sslmac_sha1(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
220 static DigestState*nomac(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s);
221 static void sslPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac);
222 static void tlsPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac);
223 static void put64(uchar *p, vlong x);
224 static void put32(uchar *p, u32int);
225 static void put24(uchar *p, int);
226 static void put16(uchar *p, int);
227 static u32int get32(uchar *p);
228 static int get16(uchar *p);
229 static void tlsSetState(TlsRec *tr, int new, int old);
230 static void rcvAlert(TlsRec *tr, int err);
231 static void sendAlert(TlsRec *tr, int err);
232 static void rcvError(TlsRec *tr, int err, char *msg, ...);
233 static int rc4enc(Secret *sec, uchar *buf, int n);
234 static int des3enc(Secret *sec, uchar *buf, int n);
235 static int des3dec(Secret *sec, uchar *buf, int n);
236 static int noenc(Secret *sec, uchar *buf, int n);
237 static int sslunpad(uchar *buf, int n, int block);
238 static int tlsunpad(uchar *buf, int n, int block);
239 static void freeSec(Secret *sec);
240 static char *tlsstate(int s);
242 #pragma varargck argpos rcvError 3
244 static char *tlsnames[] = {
246 [Qencalgs] "encalgs",
247 [Qhashalgs] "hashalgs",
255 static int convdir[] = { Qctl, Qdata, Qhand, Qstatus, Qstats };
258 tlsgen(Chan *c, char*, Dirtab *, int, int s, Dir *dp)
272 q.path = QID(0, Qtopdir);
274 devdir(c, q, "#a", 0, eve, 0555, dp);
279 q.path = QID(0, Qprotodir);
281 devdir(c, q, "tls", 0, eve, 0555, dp);
285 q.path = QID(0, Qtopdir);
287 devdir(c, q, ".", 0, eve, 0555, dp);
295 q.path = QID(0, Qclonus);
298 q.path = QID(0, Qencalgs);
301 q.path = QID(0, Qhashalgs);
305 if(TYPE(q) == Qclonus)
307 devdir(c, q, tlsnames[TYPE(q)], 0, eve, perm, dp);
313 q.path = QID(s, Qconvdir);
321 if((name = trnames[s]) == nil) {
322 name = trnames[s] = smalloc(16);
323 sprint(name, "%d", s);
325 devdir(c, q, name, 0, nm, 0555, dp);
330 q.path = QID(0, Qprotodir);
332 devdir(c, q, "tls", 0, eve, 0555, dp);
335 if(s < 0 || s >= nelem(convdir))
338 tr = tlsdevs[CONV(c->qid)];
347 if(t == Qstatus || t == Qstats)
349 q.path = QID(CONV(c->qid), t);
350 devdir(c, q, tlsnames[t], 0, nm, perm, dp);
359 devdir(c, c->qid, tlsnames[t], 0, eve, perm, dp);
363 tr = tlsdevs[CONV(c->qid)];
371 if(t == Qstatus || t == Qstats)
373 devdir(c, c->qid, tlsnames[t], 0, nm, perm, dp);
381 tlsattach(char *spec)
385 c = devattach('a', spec);
386 c->qid.path = QID(0, Qtopdir);
393 tlswalk(Chan *c, Chan *nc, char **name, int nname)
395 return devwalk(c, nc, name, nname, nil, 0, tlsgen);
399 tlsstat(Chan *c, uchar *db, int n)
401 return devstat(c, db, n, nil, 0, tlsgen);
405 tlsopen(Chan *c, int omode)
444 if((t == Qstatus || t == Qstats) && omode != OREAD)
451 pp = &tlsdevs[CONV(c->qid)];
454 error("must open connection using clone");
455 if((perm & (tr->perm>>6)) != perm
456 && (strcmp(up->user, tr->user) != 0
457 || (perm & tr->perm) != perm))
467 tr->handq = qopen(2 * MaxCipherRecLen, 0, nil, nil);
469 error("can't allocate handshake queue");
484 c->mode = openmode(omode);
487 c->iounit = qiomaxatomic;
492 tlswstat(Chan *c, uchar *dp, int n)
506 tr = tlsdevs[CONV(c->qid)];
509 if(strcmp(tr->user, up->user) != 0)
512 d = smalloc(n + sizeof *d);
513 rv = convM2D(dp, n, &d[0], (char*) &d[1]);
516 if(!emptystr(d->uid))
517 kstrdup(&tr->user, d->uid);
532 if(--tr->hqref == 0){
533 if(tr->handq != nil){
537 if(tr->hprocessed != nil){
538 freeb(tr->hprocessed);
539 tr->hprocessed = nil;
558 if((c->flag & COPEN) == 0)
561 tr = tlsdevs[CONV(c->qid)];
573 tlsdevs[CONV(c->qid)] = nil;
576 if(tr->c != nil && !waserror()){
577 checkstate(tr, 0, SOpen|SHandshake|SRClose);
578 sendAlert(tr, ECloseNotify);
586 freeSec(tr->out.sec);
587 freeSec(tr->out.new);
595 * make sure we have at least 'n' bytes in list 'l'
598 ensure(TlsRec *s, Block **l, int n)
604 for(b = *l; b; b = b->next){
612 bl = devtab[s->c->type]->bread(s->c, MaxCipherRecLen + RecHdrLen, 0);
617 for(b = bl; b; b = b->next){
628 * copy 'n' bytes from 'l' into 'p' and free
632 consume(Block **l, uchar *p, int n)
637 for(; *l && n > 0; n -= i){
642 memmove(p, b->rp, i);
658 regurgitate(TlsRec *s, uchar *p, int n)
665 if(s->unprocessed == nil || b->rp - b->base < n) {
667 memmove(b->wp, p, n);
669 b->next = s->unprocessed;
673 memmove(b->rp, p, n);
678 * remove at most n bytes from the queue
681 qgrab(Block **l, int n)
694 for(bb = b; bb != nil && i < n; bb = bb->next)
700 consume(l, bb->wp, i);
706 tlsclosed(TlsRec *tr, int new)
709 if(tr->state == SOpen || tr->state == SHandshake)
711 else if((new | tr->state) == (SRClose|SLClose))
713 unlock(&tr->statelk);
714 alertHand(tr, "close notify");
718 * read and process one tls record layer message
719 * must be called with tr->in.io held
720 * We can't let Eintrs lose data, since doing so will get
721 * us out of sync with the sender and break the reliablity
722 * of the channel. Eintr only happens during the reads in
723 * consume. Therefore we put back any bytes consumed before
724 * the last call to ensure.
727 tlsrecread(TlsRec *tr)
731 uchar *p, seq[8], header[RecHdrLen], hmac[MD5dlen];
732 int volatile nconsumed;
733 int len, type, ver, unpad_len;
737 if(strcmp(up->errstr, Eintr) == 0 && !waserror()){
738 regurgitate(tr, header, nconsumed);
741 tlsError(tr, "channel error");
744 ensure(tr, &tr->unprocessed, RecHdrLen);
745 consume(&tr->unprocessed, header, RecHdrLen);
746 nconsumed = RecHdrLen;
748 if((tr->handin == 0) && (header[0] & 0x80)){
749 /* Cope with an SSL3 ClientHello expressed in SSL2 record format.
750 This is sent by some clients that we must interoperate
751 with, such as Java's JSSE and Microsoft's Internet Explorer. */
752 len = (get16(header) & ~0x8000) - 3;
754 ver = get16(header + 3);
755 if(type != SSL2ClientHello || len < 22)
756 rcvError(tr, EProtocolVersion, "invalid initial SSL2-like message");
757 }else{ /* normal SSL3 record format */
759 ver = get16(header+1);
760 len = get16(header+3);
762 if(ver != tr->version && (tr->verset || ver < MinProtoVersion || ver > MaxProtoVersion))
763 rcvError(tr, EProtocolVersion, "devtls expected ver=%x%s, saw (len=%d) type=%x ver=%x '%.12s'",
764 tr->version, tr->verset?"/set":"", len, type, ver, (char*)header);
765 if(len > MaxCipherRecLen || len < 0)
766 rcvError(tr, ERecordOverflow, "record message too long %d", len);
767 ensure(tr, &tr->unprocessed, len);
772 * If an Eintr happens after this, we'll get out of sync.
773 * Make sure nothing we call can sleep.
774 * Errors are ok, as they kill the connection.
775 * Luckily, allocb won't sleep, it'll just error out.
781 tlsError(tr, "channel error");
784 b = qgrab(&tr->unprocessed, len);
788 qunlock(&in->seclock);
794 /* to avoid Canvel-Hiltgen-Vaudenay-Vuagnoux attack, all errors here
795 should look alike, including timing of the response. */
796 unpad_len = (*in->sec->dec)(in->sec, p, len);
797 if(unpad_len > in->sec->maclen)
798 len = unpad_len - in->sec->maclen;
801 put16(header+3, len);
804 (*tr->packMac)(in->sec, in->sec->mackey, seq, header, p, len, hmac);
805 if(unpad_len <= in->sec->maclen || memcmp(hmac, p+len, in->sec->maclen) != 0)
806 rcvError(tr, EBadRecordMac, "record mac mismatch");
809 qunlock(&in->seclock);
812 rcvError(tr, EDecodeError, "runt record message");
816 rcvError(tr, EIllegalParameter, "invalid record message 0x%x", type);
818 case RChangeCipherSpec:
819 if(len != 1 || p[0] != 1)
820 rcvError(tr, EDecodeError, "invalid change cipher spec");
823 qunlock(&in->seclock);
824 rcvError(tr, EUnexpectedMessage, "unexpected change cipher spec");
830 qunlock(&in->seclock);
834 rcvError(tr, EDecodeError, "invalid alert");
838 rcvError(tr, EIllegalParameter, "invalid alert fatal code");
841 * propate non-fatal alerts to handshaker
843 if(p[1] == ECloseNotify) {
844 tlsclosed(tr, SRClose);
847 error("close notify");
849 if(p[1] == ENoRenegotiation)
850 alertHand(tr, "no renegotiation");
851 else if(p[1] == EUserCanceled)
852 alertHand(tr, "handshake canceled by user");
854 rcvError(tr, EIllegalParameter, "invalid alert code");
858 * don't worry about dropping the block
859 * qbwrite always queues even if flow controlled and interrupted.
861 * if there isn't any handshaker, ignore the request,
862 * but notify the other side we are doing so.
865 if(tr->handq != nil){
874 qbwrite(tr->handq, b);
880 if(tr->verset && tr->version != SSL3Version && !waserror()){
881 sendAlert(tr, ENoRenegotiation);
886 case SSL2ClientHello:
888 if(tr->handq != nil){
895 /* Pass the SSL2 format data, so that the handshake code can compute
896 the correct checksums. HSSL2ClientHello = HandshakeType 9 is
897 unused in RFC2246. */
899 b->rp[0] = RHandshake;
900 b->rp[1] = HSSL2ClientHello;
901 put24(&b->rp[2], len+3);
902 b->rp[5] = SSL2ClientHello;
903 put16(&b->rp[6], ver);
904 qbwrite(tr->handq, b);
910 if(tr->verset && tr->version != SSL3Version && !waserror()){
911 sendAlert(tr, ENoRenegotiation);
918 rcvError(tr, EUnexpectedMessage, "application message received before handshake completed");
929 * got a fatal alert message
932 rcvAlert(TlsRec *tr, int err)
938 for(i=0; i < nelem(tlserrs); i++){
939 if(tlserrs[i].err == err){
952 * found an error while decoding the input stream
955 rcvError(TlsRec *tr, int err, char *fmt, ...)
961 vseprint(msg, msg+sizeof(msg), fmt, arg);
972 * make sure the next hand operation returns with a 'msg' error
975 alertHand(TlsRec *tr, char *msg)
981 if(tr->handq == nil){
995 memmove(b->wp, msg, n + 1);
998 qbwrite(tr->handq, b);
1005 checkstate(TlsRec *tr, int ishand, int ok)
1011 unlock(&tr->statelk);
1026 error("tls hungup");
1028 error("tls improperly configured");
1032 tlsbread(Chan *c, long n, ulong offset)
1036 TlsRec *volatile tr;
1041 return devbread(c, n, offset);
1047 tr = tlsdevs[CONV(c->qid)];
1052 qunlock(&tr->in.io);
1057 checkstate(tr, 0, SOpen);
1058 while(tr->processed == nil)
1061 /* return at most what was asked for */
1062 b = qgrab(&tr->processed, n);
1063 qunlock(&tr->in.io);
1065 tr->datain += BLEN(b);
1067 checkstate(tr, 1, SOpen|SHandshake|SLClose);
1070 * it's ok to look at state without the lock
1071 * since it only protects reading records,
1072 * and we have that tr->in.io held.
1074 while(!tr->opened && tr->hprocessed == nil && !qcanread(tr->handq))
1077 qunlock(&tr->in.io);
1081 qunlock(&tr->hqread);
1085 if(tr->hprocessed == nil){
1086 b = qbread(tr->handq, MaxRecLen + 1);
1087 if(*b->rp++ == RAlert){
1088 strecpy(up->errstr, up->errstr+ERRMAX, (char*)b->rp);
1094 b = qgrab(&tr->hprocessed, n);
1096 qunlock(&tr->hqread);
1097 tr->handin += BLEN(b);
1104 tlsread(Chan *c, void *a, long n, vlong off)
1114 if(c->qid.type & QTDIR)
1115 return devdirread(c, a, n, 0, 0, tlsgen);
1117 tr = tlsdevs[CONV(c->qid)];
1123 buf = smalloc(Statlen);
1124 qlock(&tr->in.seclock);
1125 qlock(&tr->out.seclock);
1128 s = seprint(s, e, "State: %s\n", tlsstate(tr->state));
1129 s = seprint(s, e, "Version: 0x%x\n", tr->version);
1130 if(tr->in.sec != nil)
1131 s = seprint(s, e, "EncIn: %s\nHashIn: %s\n", tr->in.sec->encalg, tr->in.sec->hashalg);
1132 if(tr->in.new != nil)
1133 s = seprint(s, e, "NewEncIn: %s\nNewHashIn: %s\n", tr->in.new->encalg, tr->in.new->hashalg);
1134 if(tr->out.sec != nil)
1135 s = seprint(s, e, "EncOut: %s\nHashOut: %s\n", tr->out.sec->encalg, tr->out.sec->hashalg);
1136 if(tr->out.new != nil)
1137 seprint(s, e, "NewEncOut: %s\nNewHashOut: %s\n", tr->out.new->encalg, tr->out.new->hashalg);
1138 qunlock(&tr->in.seclock);
1139 qunlock(&tr->out.seclock);
1140 n = readstr(offset, a, n, buf);
1144 buf = smalloc(Statlen);
1147 s = seprint(s, e, "DataIn: %lld\n", tr->datain);
1148 s = seprint(s, e, "DataOut: %lld\n", tr->dataout);
1149 s = seprint(s, e, "HandIn: %lld\n", tr->handin);
1150 seprint(s, e, "HandOut: %lld\n", tr->handout);
1151 n = readstr(offset, a, n, buf);
1155 buf = smalloc(Statlen);
1156 snprint(buf, Statlen, "%llud", CONV(c->qid));
1157 n = readstr(offset, a, n, buf);
1162 b = tlsbread(c, n, offset);
1165 return readstr(offset, a, n, encalgs);
1167 return readstr(offset, a, n, hashalgs);
1177 for(nb = b; nb; nb = nb->next){
1179 memmove(va+n, nb->rp, i);
1190 * write a block in tls records
1193 tlsrecwrite(TlsRec *tr, int type, Block *b)
1198 OneWay *volatile out;
1199 int n, maclen, pad, ok;
1211 ok = SHandshake|SOpen|SRClose;
1215 checkstate(tr, type != RApplication, ok);
1218 * get at most one maximal record's input,
1219 * with padding on the front for header and
1220 * back for mac and maximal block padding.
1223 qunlock(&out->seclock);
1226 qlock(&out->seclock);
1229 if(out->sec != nil){
1230 maclen = out->sec->maclen;
1231 pad = maclen + out->sec->block;
1236 nb = allocb(n + pad + RecHdrLen);
1237 memmove(nb->wp + RecHdrLen, bb->rp, n);
1241 * carefully reuse bb so it will get freed if we're out of memory
1243 bb = padblock(bb, RecHdrLen);
1245 nb = padblock(bb, -pad);
1253 put16(p+1, tr->version);
1256 if(out->sec != nil){
1257 put64(seq, out->seq);
1259 (*tr->packMac)(out->sec, out->sec->mackey, seq, p, p + RecHdrLen, n, p + RecHdrLen + n);
1263 n = (*out->sec->enc)(out->sec, p + RecHdrLen, n);
1264 nb->wp = p + RecHdrLen + n;
1269 if(type == RChangeCipherSpec){
1271 error("change cipher without a new cipher");
1273 out->sec = out->new;
1277 qunlock(&out->seclock);
1281 * if bwrite error's, we assume the block is queued.
1282 * if not, we're out of sync with the receiver and will not recover.
1285 if(strcmp(up->errstr, "interrupted") != 0)
1286 tlsError(tr, "channel error");
1289 devtab[tr->c->type]->bwrite(tr->c, nb, 0);
1297 tlsbwrite(Chan *c, Block *b, ulong offset)
1305 tr = tlsdevs[CONV(c->qid)];
1312 return devbwrite(c, b, offset);
1314 tlsrecwrite(tr, RHandshake, b);
1318 checkstate(tr, 0, SOpen);
1319 tlsrecwrite(tr, RApplication, b);
1327 typedef struct Hashalg Hashalg;
1332 void (*initkey)(Hashalg *, int, Secret *, uchar*);
1336 initmd5key(Hashalg *ha, int version, Secret *s, uchar *p)
1338 s->maclen = ha->maclen;
1339 if(version == SSL3Version)
1340 s->mac = sslmac_md5;
1343 memmove(s->mackey, p, ha->maclen);
1347 initclearmac(Hashalg *, int, Secret *s, uchar *)
1354 initsha1key(Hashalg *ha, int version, Secret *s, uchar *p)
1356 s->maclen = ha->maclen;
1357 if(version == SSL3Version)
1358 s->mac = sslmac_sha1;
1361 memmove(s->mackey, p, ha->maclen);
1364 static Hashalg hashtab[] =
1366 { "clear", 0, initclearmac, },
1367 { "md5", MD5dlen, initmd5key, },
1368 { "sha1", SHA1dlen, initsha1key, },
1373 parsehashalg(char *p)
1377 for(ha = hashtab; ha->name; ha++)
1378 if(strcmp(p, ha->name) == 0)
1380 error("unsupported hash algorithm");
1384 typedef struct Encalg Encalg;
1390 void (*initkey)(Encalg *ea, Secret *, uchar*, uchar*);
1394 initRC4key(Encalg *ea, Secret *s, uchar *p, uchar *)
1396 s->enckey = smalloc(sizeof(RC4state));
1400 setupRC4state(s->enckey, p, ea->keylen);
1404 initDES3key(Encalg *, Secret *s, uchar *p, uchar *iv)
1406 s->enckey = smalloc(sizeof(DES3state));
1410 setupDES3state(s->enckey, (uchar(*)[8])p, iv);
1414 initclearenc(Encalg *, Secret *s, uchar *, uchar *)
1421 static Encalg encrypttab[] =
1423 { "clear", 0, 0, initclearenc },
1424 { "rc4_128", 128/8, 0, initRC4key },
1425 { "3des_ede_cbc", 3 * 8, 8, initDES3key },
1430 parseencalg(char *p)
1434 for(ea = encrypttab; ea->name; ea++)
1435 if(strcmp(p, ea->name) == 0)
1437 error("unsupported encryption algorithm");
1442 tlswrite(Chan *c, void *a, long n, vlong off)
1446 TlsRec *volatile tr;
1447 Secret *volatile tos, *volatile toc;
1449 Cmdbuf *volatile cb;
1455 tr = tlsdevs[CONV(c->qid)];
1475 memmove(b->wp, p, m);
1479 tlsbwrite(c, b, offset);
1491 cb = parsecmd(a, n);
1497 error("short control request");
1499 /* mutex with operations using what we're about to change */
1501 qunlock(&tr->in.seclock);
1502 qunlock(&tr->out.seclock);
1505 qlock(&tr->in.seclock);
1506 qlock(&tr->out.seclock);
1508 if(strcmp(cb->f[0], "fd") == 0){
1510 error("usage: fd open-fd version");
1513 m = strtol(cb->f[2], nil, 0);
1514 if(m < MinProtoVersion || m > MaxProtoVersion)
1515 error("unsupported version");
1516 tr->c = buftochan(cb->f[1]);
1518 tlsSetState(tr, SHandshake, SClosed);
1519 }else if(strcmp(cb->f[0], "version") == 0){
1521 error("usage: version vers");
1523 error("must set fd before version");
1525 error("version already set");
1526 m = strtol(cb->f[1], nil, 0);
1527 if(m == SSL3Version)
1528 tr->packMac = sslPackMac;
1529 else if(m == TLSVersion)
1530 tr->packMac = tlsPackMac;
1532 error("unsupported version");
1535 }else if(strcmp(cb->f[0], "secret") == 0){
1537 error("usage: secret hashalg encalg isclient secretdata");
1538 if(tr->c == nil || !tr->verset)
1539 error("must set fd and version before secrets");
1541 if(tr->in.new != nil){
1542 freeSec(tr->in.new);
1545 if(tr->out.new != nil){
1546 freeSec(tr->out.new);
1550 ha = parsehashalg(cb->f[1]);
1551 ea = parseencalg(cb->f[2]);
1554 m = (strlen(p)*3)/2;
1564 m = dec64(x, m, p, strlen(p));
1565 if(m < 2 * ha->maclen + 2 * ea->keylen + 2 * ea->ivlen)
1566 error("not enough secret data provided");
1568 tos = smalloc(sizeof(Secret));
1569 toc = smalloc(sizeof(Secret));
1570 if(!ha->initkey || !ea->initkey)
1571 error("misimplemented secret algorithm");
1572 (*ha->initkey)(ha, tr->version, tos, &x[0]);
1573 (*ha->initkey)(ha, tr->version, toc, &x[ha->maclen]);
1574 (*ea->initkey)(ea, tos, &x[2 * ha->maclen], &x[2 * ha->maclen + 2 * ea->keylen]);
1575 (*ea->initkey)(ea, toc, &x[2 * ha->maclen + ea->keylen], &x[2 * ha->maclen + 2 * ea->keylen + ea->ivlen]);
1577 if(!tos->mac || !tos->enc || !tos->dec
1578 || !toc->mac || !toc->enc || !toc->dec)
1579 error("missing algorithm implementations");
1580 if(strtol(cb->f[3], nil, 0) == 0){
1587 if(tr->version == SSL3Version){
1588 toc->unpad = sslunpad;
1589 tos->unpad = sslunpad;
1591 toc->unpad = tlsunpad;
1592 tos->unpad = tlsunpad;
1594 toc->encalg = ea->name;
1595 toc->hashalg = ha->name;
1596 tos->encalg = ea->name;
1597 tos->hashalg = ha->name;
1601 }else if(strcmp(cb->f[0], "changecipher") == 0){
1603 error("usage: changecipher");
1604 if(tr->out.new == nil)
1605 error("can't change cipher spec without setting secret");
1607 qunlock(&tr->in.seclock);
1608 qunlock(&tr->out.seclock);
1614 * the real work is done as the message is written
1615 * so the stream is encrypted in sync.
1619 tlsrecwrite(tr, RChangeCipherSpec, b);
1621 }else if(strcmp(cb->f[0], "opened") == 0){
1623 error("usage: opened");
1624 if(tr->in.sec == nil || tr->out.sec == nil)
1625 error("cipher must be configured before enabling data messages");
1627 if(tr->state != SHandshake && tr->state != SOpen){
1628 unlock(&tr->statelk);
1629 error("can't enable data messages");
1632 unlock(&tr->statelk);
1634 }else if(strcmp(cb->f[0], "alert") == 0){
1636 error("usage: alert n");
1638 error("must set fd before sending alerts");
1639 m = strtol(cb->f[1], nil, 0);
1641 qunlock(&tr->in.seclock);
1642 qunlock(&tr->out.seclock);
1649 if(m == ECloseNotify)
1650 tlsclosed(tr, SLClose);
1656 qunlock(&tr->in.seclock);
1657 qunlock(&tr->out.seclock);
1673 tlsdevs = smalloc(sizeof(TlsRec*) * maxtlsdevs);
1674 trnames = smalloc((sizeof *trnames) * maxtlsdevs);
1677 for(e = encrypttab; e->name != nil; e++)
1678 n += strlen(e->name) + 1;
1679 cp = encalgs = smalloc(n);
1680 for(e = encrypttab;;){
1681 strcpy(cp, e->name);
1682 cp += strlen(e->name);
1691 for(h = hashtab; h->name != nil; h++)
1692 n += strlen(h->name) + 1;
1693 cp = hashalgs = smalloc(n);
1695 strcpy(cp, h->name);
1696 cp += strlen(h->name);
1726 /* get channel associated with an fd */
1735 fd = strtoul(p, 0, 0);
1738 c = fdtochan(fd, -1, 0, 1); /* error check and inc ref */
1743 sendAlert(TlsRec *tr, int err)
1750 msg = "tls unknown alert";
1751 for(i=0; i < nelem(tlserrs); i++) {
1752 if(tlserrs[i].err == err) {
1753 msg = tlserrs[i].msg;
1754 if(tr->version == SSL3Version)
1755 err = tlserrs[i].sslerr;
1757 err = tlserrs[i].tlserr;
1758 fatal = tlserrs[i].fatal;
1765 *b->wp++ = fatal + 1;
1768 tlsSetState(tr, SAlert, SOpen|SHandshake|SRClose);
1769 tlsrecwrite(tr, RAlert, b);
1777 tlsError(TlsRec *tr, char *msg)
1785 strncpy(tr->err, msg, ERRMAX - 1);
1786 tr->err[ERRMAX - 1] = '\0';
1788 unlock(&tr->statelk);
1794 tlsSetState(TlsRec *tr, int new, int old)
1799 unlock(&tr->statelk);
1802 /* hand up a digest connection */
1804 tlshangup(TlsRec *tr)
1809 for(b = tr->processed; b; b = tr->processed){
1810 tr->processed = b->next;
1813 if(tr->unprocessed != nil){
1814 freeb(tr->unprocessed);
1815 tr->unprocessed = nil;
1817 qunlock(&tr->in.io);
1819 tlsSetState(tr, SClosed, ~0);
1825 TlsRec **pp, **ep, **np;
1834 ep = &tlsdevs[maxtlsdevs];
1835 for(pp = tlsdevs; pp < ep; pp++)
1839 if(maxtlsdevs >= MaxTlsDevs) {
1844 newmax = 2 * maxtlsdevs;
1845 if(newmax > MaxTlsDevs)
1846 newmax = MaxTlsDevs;
1847 np = smalloc(sizeof(TlsRec*) * newmax);
1848 memmove(np, tlsdevs, sizeof(TlsRec*) * maxtlsdevs);
1850 pp = &tlsdevs[maxtlsdevs];
1851 memset(pp, 0, sizeof(TlsRec*)*(newmax - maxtlsdevs));
1853 nmp = smalloc(sizeof *nmp * newmax);
1854 memmove(nmp, trnames, sizeof *nmp * maxtlsdevs);
1857 maxtlsdevs = newmax;
1860 if(pp - tlsdevs >= tdhiwat)
1865 ch->qid.path = QID(pp - tlsdevs, t);
1877 tr = mallocz(sizeof(*tr), 1);
1880 tr->state = SClosed;
1882 kstrdup(&tr->user, up->user);
1892 return "Handshaking";
1894 return "Established";
1896 return "RemoteClosed";
1898 return "LocalClosed";
1919 noenc(Secret *, uchar *, int n)
1925 rc4enc(Secret *sec, uchar *buf, int n)
1927 rc4(sec->enckey, buf, n);
1932 tlsunpad(uchar *buf, int n, int block)
1938 if(nn <= 0 || n % block)
1941 if(pad != buf[n - 1])
1947 sslunpad(uchar *buf, int n, int block)
1953 if(nn <= 0 || n % block)
1959 blockpad(uchar *buf, int n, int block)
1972 des3enc(Secret *sec, uchar *buf, int n)
1974 n = blockpad(buf, n, 8);
1975 des3CBCencrypt(buf, n, sec->enckey);
1980 des3dec(Secret *sec, uchar *buf, int n)
1982 des3CBCdecrypt(buf, n, sec->enckey);
1983 return (*sec->unpad)(buf, n, 8);
1986 nomac(uchar *, ulong, uchar *, ulong, uchar *, DigestState *)
1992 * sslmac: mac calculations for ssl 3.0 only; tls 1.0 uses the standard hmac.
1995 sslmac_x(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s,
1996 DigestState*(*x)(uchar*, ulong, uchar*, DigestState*), int xlen, int padlen)
1999 uchar pad[48], innerdigest[20];
2001 if(xlen > sizeof(innerdigest)
2002 || padlen > sizeof(pad))
2008 /* first time through */
2010 for(i=0; i<padlen; i++)
2012 s = (*x)(key, klen, nil, nil);
2013 s = (*x)(pad, padlen, nil, s);
2018 s = (*x)(p, len, nil, s);
2022 /* last time through */
2023 for(i=0; i<padlen; i++)
2025 (*x)(nil, 0, innerdigest, s);
2026 s = (*x)(key, klen, nil, nil);
2027 s = (*x)(pad, padlen, nil, s);
2028 (*x)(innerdigest, xlen, digest, s);
2033 sslmac_sha1(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2035 return sslmac_x(p, len, key, klen, digest, s, sha1, SHA1dlen, 40);
2039 sslmac_md5(uchar *p, ulong len, uchar *key, ulong klen, uchar *digest, DigestState *s)
2041 return sslmac_x(p, len, key, klen, digest, s, md5, MD5dlen, 48);
2045 sslPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac)
2050 memmove(buf, seq, 8);
2053 buf[10] = header[4];
2055 s = (*sec->mac)(buf, 11, mackey, sec->maclen, 0, 0);
2056 (*sec->mac)(body, len, mackey, sec->maclen, mac, s);
2060 tlsPackMac(Secret *sec, uchar *mackey, uchar *seq, uchar *header, uchar *body, int len, uchar *mac)
2065 memmove(buf, seq, 8);
2066 memmove(&buf[8], header, 5);
2068 s = (*sec->mac)(buf, 13, mackey, sec->maclen, 0, 0);
2069 (*sec->mac)(body, len, mackey, sec->maclen, mac, s);
2073 put32(uchar *p, u32int x)
2082 put64(uchar *p, vlong x)
2084 put32(p, (u32int)(x >> 32));
2085 put32(p+4, (u32int)x);
2089 put24(uchar *p, int x)
2097 put16(uchar *p, int x)
2106 return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
2112 return (p[0]<<8)|p[1];